1#![allow(dead_code)]
2
3pub mod sample;
4pub mod signature;
5
6use std::{
7 borrow::Borrow,
8 fmt::{Display, LowerExp},
9 ops::{Add, AddAssign, Index, Mul, MulAssign, Neg, Sub, SubAssign},
10 str::FromStr,
11};
12
13use bincode_trait_derive::{Decode, Encode};
14use eyre::Context;
15use feynkit_kinematics::{Axis as KinematicAxis, Rotation as KinematicRotation, WavefunctionError};
16use linnet::half_edge::involution::EdgeIndex;
17pub use linnet::num_traits::{Pow, Sign, SignError, SignOrZero};
18use momtrop::vector::Vector;
19use schemars::JsonSchema;
20use serde::{Deserialize, Serialize};
21use spenso::{
22 algebra::{algebraic_traits::RefZero, complex::Complex, upgrading_arithmetic::FallibleAdd},
23 contraction::Contract,
24 iterators::IteratableTensor,
25 shadowing::Shadowable,
26 structure::{
27 Canonicalized, CastStructure, IndexLess, NamedStructure, OrderedStructure,
28 TensorDataLayout, TensorStructure, ToSymbolic,
29 abstract_index::AbstractIndex,
30 representation::{BaseRepName, Euclidean, LibraryRep, Minkowski, RepName},
31 slot::{DualSlotTo, Slot},
32 },
33 tensors::{
34 complex::RealOrComplexTensor,
35 data::{
36 DataIterator, DataTensor, DenseTensor, HasTensorData, SetTensorData, SparseTensor,
37 StorageTensor,
38 },
39 parametric::{
40 EvalTensor, FlatCoefficent, MixedTensor, ParamOrConcrete, atomcore::TensorAtomOps,
41 },
42 },
43};
44use symbolica::{
45 domains::{
46 dual::HyperDual,
47 float::{Complex as SymComplex, FloatLike as SymFloatLike},
48 rational::RationalField,
49 },
50 prelude::*,
51};
52use symbolica_utils::NoArgs;
53use thiserror::Error;
54
55use crate::{
56 GammaLoopContext,
57 settings::runtime::RotationSetting,
58 utils::{
59 ApproxEq, F, FloatLike, RefDefault, hyperdual_utils::new_constant, representations::GR,
60 },
61};
62
63#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Encode, Decode)]
64pub struct Energy<T> {
65 pub value: T,
66}
67
68impl<T> Energy<T> {
69 pub(crate) fn map_ref<U>(&self, f: &impl Fn(&T) -> U) -> Energy<U> {
70 Energy {
71 value: f(&self.value),
72 }
73 }
74
75 pub(crate) fn map<U>(self, f: &impl Fn(T) -> U) -> Energy<U> {
76 Energy {
77 value: f(self.value),
78 }
79 }
80}
81
82impl<T: FloatLike> ApproxEq<Energy<F<T>>, F<T>> for Energy<F<T>> {
83 fn approx_eq(&self, other: &Energy<F<T>>, threshold: &F<T>) -> bool {
84 self.value.approx_eq(&other.value, threshold)
85 }
86}
87
88impl<T: FloatLike> Energy<F<T>> {
89 pub(crate) fn higher(&self) -> Energy<F<T::Higher>>
90 where
91 T::Higher: FloatLike,
92 {
93 Energy {
94 value: self.value.higher(),
95 }
96 }
97
98 pub(crate) fn lower(&self) -> Energy<F<T::Lower>>
99 where
100 T::Lower: FloatLike,
101 {
102 Energy {
103 value: self.value.lower(),
104 }
105 }
106
107 pub(crate) fn from_ff64(energy: Energy<F<f64>>) -> Self {
108 Energy {
109 value: F::from_ff64(energy.value),
110 }
111 }
112}
113
114impl<T: FloatLike> From<Energy<T>> for Energy<F<T>> {
115 fn from(value: Energy<T>) -> Self {
116 Energy {
117 value: F(value.value),
118 }
119 }
120}
121
122impl<T: Real> Energy<T> {
123 pub(crate) fn zero(&self) -> Self {
124 Energy {
125 value: self.value.zero(),
126 }
127 }
128}
129
130impl<T> Add<Energy<T>> for Energy<T>
131where
132 T: Add<T, Output = T>,
133{
134 type Output = Energy<T>;
135 fn add(self, rhs: Energy<T>) -> Self::Output {
136 Energy {
137 value: self.value + rhs.value,
138 }
139 }
140}
141
142impl<T> Add<&Energy<T>> for Energy<T>
143where
144 T: for<'a> Add<&'a T, Output = T>,
145{
146 type Output = Energy<T>;
147 fn add(self, rhs: &Energy<T>) -> Self::Output {
148 Energy {
149 value: self.value + &rhs.value,
150 }
151 }
152}
153
154impl<'b, T> Add<&Energy<T>> for &'b Energy<T>
155where
156 &'b T: for<'a> Add<&'a T, Output = T>,
157{
158 type Output = Energy<T>;
159 fn add(self, rhs: &Energy<T>) -> Self::Output {
160 Energy {
161 value: &self.value + &rhs.value,
162 }
163 }
164}
165
166impl<T> Add<Energy<T>> for &Energy<T>
167where
168 T: for<'a> Add<&'a T, Output = T>,
169{
170 type Output = Energy<T>;
171 fn add(self, rhs: Energy<T>) -> Self::Output {
172 rhs + self
173 }
174}
175
176impl<T> AddAssign<Energy<T>> for Energy<T>
177where
178 T: AddAssign<T>,
179{
180 fn add_assign(&mut self, rhs: Energy<T>) {
181 self.value += rhs.value;
182 }
183}
184
185impl<'a, T> AddAssign<&'a Energy<T>> for Energy<T>
186where
187 T: AddAssign<&'a T>,
188{
189 fn add_assign(&mut self, rhs: &'a Energy<T>) {
190 self.value += &rhs.value;
191 }
192}
193
194impl<T> Sub<Energy<T>> for Energy<T>
195where
196 T: Sub<T, Output = T>,
197{
198 type Output = Energy<T>;
199 fn sub(self, rhs: Energy<T>) -> Self::Output {
200 Energy {
201 value: self.value - rhs.value,
202 }
203 }
204}
205
206impl<T> SubAssign<Energy<T>> for Energy<T>
207where
208 T: SubAssign<T>,
209{
210 fn sub_assign(&mut self, rhs: Energy<T>) {
211 self.value -= rhs.value;
212 }
213}
214
215impl<'a, T> SubAssign<&'a Energy<T>> for Energy<T>
216where
217 T: SubAssign<&'a T>,
218{
219 fn sub_assign(&mut self, rhs: &'a Energy<T>) {
220 self.value -= &rhs.value;
221 }
222}
223impl<T> Mul<Energy<T>> for Energy<T>
224where
225 T: Mul<T, Output = T>,
226{
227 type Output = T;
228 fn mul(self, rhs: Energy<T>) -> Self::Output {
229 self.value * rhs.value
230 }
231}
232
233impl<T> MulAssign<Energy<T>> for Energy<T>
234where
235 T: MulAssign<T>,
236{
237 fn mul_assign(&mut self, rhs: Energy<T>) {
238 self.value *= rhs.value;
239 }
240}
241
242impl<T> Neg for Energy<T>
243where
244 T: Neg<Output = T>,
245{
246 type Output = Energy<T>;
247 fn neg(self) -> Self::Output {
248 Energy { value: -self.value }
249 }
250}
251
252impl<T> Energy<T> {
253 pub(crate) fn new(value: T) -> Self {
254 Energy { value }
255 }
256
257 }
269
270impl<U, T: RefZero<U>> RefZero<Energy<U>> for Energy<T>
277where
278 Energy<T>: Borrow<Energy<U>>,
279{
280 fn ref_zero(&self) -> Energy<U> {
281 Energy {
282 value: self.value.ref_zero(),
283 }
284 }
285}
286
287impl Energy<Atom> {
288 pub(crate) fn new_parametric(id: usize) -> Self {
289 let value = parse!(&format!("E_{}", id));
290 Energy { value }
291 }
292}
293
294impl<T: Display> Display for Energy<T> {
295 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
296 write!(f, "E: {}", self.value)
297 }
298}
299
300impl<T: LowerExp> LowerExp for Energy<T> {
301 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
302 write!(f, "E: {:e}", self.value)
303 }
304}
305
306impl<T: Default> Default for Energy<T> {
307 fn default() -> Self {
308 Energy {
309 value: T::default(),
310 }
311 }
312}
313
314impl<T> From<T> for Energy<T> {
315 fn from(value: T) -> Self {
316 Energy { value }
317 }
318}
319
320#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Encode, Decode)]
321pub struct ThreeMomentum<T> {
322 pub px: T,
323 pub py: T,
324 pub pz: T,
325}
326
327impl<T> ThreeMomentum<T> {
328 pub(crate) fn map_ref<U>(&self, f: &impl Fn(&T) -> U) -> ThreeMomentum<U> {
329 ThreeMomentum {
330 px: f(&self.px),
331 py: f(&self.py),
332 pz: f(&self.pz),
333 }
334 }
335
336 pub(crate) fn map<U>(self, f: &impl Fn(T) -> U) -> ThreeMomentum<U> {
337 ThreeMomentum {
338 px: f(self.px),
339 py: f(self.py),
340 pz: f(self.pz),
341 }
342 }
343}
344
345impl<T: FloatLike> ApproxEq<ThreeMomentum<F<T>>, F<T>> for ThreeMomentum<F<T>> {
346 fn approx_eq(&self, other: &ThreeMomentum<F<T>>, threshold: &F<T>) -> bool {
347 F::approx_eq_iterator(
348 [&self.px, &self.py, &self.pz],
349 [&other.px, &other.py, &other.pz],
350 threshold,
351 )
352 }
353}
354
355pub struct ThreeRotation<T> {
356 pub map: fn(ThreeMomentum<T>) -> ThreeMomentum<T>,
357 pub inv_map: fn(ThreeMomentum<T>) -> ThreeMomentum<T>,
358}
359
360impl<T: Neg<Output = T>> ThreeRotation<T> {
361 pub(crate) fn half_pi_x() -> Self {
362 let map = |mut momentum: ThreeMomentum<T>| -> ThreeMomentum<T> {
363 std::mem::swap(&mut momentum.py, &mut momentum.pz);
364 momentum.pz = -momentum.pz;
365 momentum
366 };
367
368 let inv_map = |mut momentum: ThreeMomentum<T>| -> ThreeMomentum<T> {
369 momentum.pz = -momentum.pz;
370 std::mem::swap(&mut momentum.py, &mut momentum.pz);
371 momentum
372 };
373
374 ThreeRotation { map, inv_map }
375 }
376
377 pub(crate) fn half_pi_y() -> Self {
378 let map = |mut momentum: ThreeMomentum<T>| -> ThreeMomentum<T> {
379 std::mem::swap(&mut momentum.px, &mut momentum.pz);
380 momentum.px = -momentum.px;
381 momentum
382 };
383
384 let inv_map = |mut momentum: ThreeMomentum<T>| -> ThreeMomentum<T> {
385 momentum.px = -momentum.px;
386 std::mem::swap(&mut momentum.px, &mut momentum.pz);
387 momentum
388 };
389
390 ThreeRotation { map, inv_map }
391 }
392
393 pub(crate) fn half_pi_z() -> Self {
394 let map = |mut momentum: ThreeMomentum<T>| -> ThreeMomentum<T> {
395 std::mem::swap(&mut momentum.px, &mut momentum.py);
396 momentum.py = -momentum.py;
397 momentum
398 };
399
400 let inv_map = |mut momentum: ThreeMomentum<T>| -> ThreeMomentum<T> {
401 momentum.py = -momentum.py;
402 std::mem::swap(&mut momentum.px, &mut momentum.py);
403 momentum
404 };
405
406 ThreeRotation { map, inv_map }
407 }
408}
409
410impl<T: FloatLike> ThreeMomentum<F<T>> {
411 pub(crate) fn higher(&self) -> ThreeMomentum<F<T::Higher>>
412 where
413 T::Higher: FloatLike,
414 {
415 ThreeMomentum {
416 px: self.px.higher(),
417 py: self.py.higher(),
418 pz: self.pz.higher(),
419 }
420 }
421
422 pub(crate) fn lower(&self) -> ThreeMomentum<F<T::Lower>>
423 where
424 T::Lower: FloatLike,
425 {
426 ThreeMomentum {
427 px: self.px.lower(),
428 py: self.py.lower(),
429 pz: self.pz.lower(),
430 }
431 }
432
433 pub(crate) fn from_ff64(three_mom: ThreeMomentum<F<f64>>) -> Self {
434 ThreeMomentum {
435 px: F::from_ff64(three_mom.px),
436 py: F::from_ff64(three_mom.py),
437 pz: F::from_ff64(three_mom.pz),
438 }
439 }
440}
441
442impl<T: FloatLike> From<ThreeMomentum<T>> for ThreeMomentum<F<T>> {
443 fn from(value: ThreeMomentum<T>) -> Self {
444 ThreeMomentum {
445 px: F(value.px),
446 py: F(value.py),
447 pz: F(value.pz),
448 }
449 }
450}
451
452impl<T> IntoIterator for ThreeMomentum<T> {
453 type Item = T;
454 type IntoIter = std::array::IntoIter<T, 3>;
455
456 fn into_iter(self) -> Self::IntoIter {
457 let [px, py, pz] = [self.px, self.py, self.pz];
458 [px, py, pz].into_iter()
459 }
460}
461
462impl<'a, T> IntoIterator for &'a ThreeMomentum<T> {
463 type Item = &'a T;
464 type IntoIter = std::array::IntoIter<&'a T, 3>;
465
466 fn into_iter(self) -> Self::IntoIter {
467 let [px, py, pz] = [&self.px, &self.py, &self.pz];
468 [px, py, pz].into_iter()
469 }
470}
471
472impl<T: Real> RefDefault for ThreeMomentum<T> {
473 fn default(&self) -> Self {
474 let zero = self.px.zero();
475 ThreeMomentum {
476 px: zero.clone(),
477 py: zero.clone(),
478 pz: zero.clone(),
479 }
480 }
481}
482
483impl<T: Real> ThreeMomentum<T> {
484 pub(crate) fn zero(&self) -> Self {
485 let zero = self.px.zero();
486 ThreeMomentum {
487 px: zero.clone(),
488 py: zero.clone(),
489 pz: zero.clone(),
490 }
491 }
492}
493
494impl<T: RefZero> RefZero for ThreeMomentum<T> {
495 fn ref_zero(&self) -> Self {
496 ThreeMomentum {
497 px: self.px.ref_zero(),
498 py: self.py.ref_zero(),
499 pz: self.pz.ref_zero(),
500 }
501 }
502}
503
504impl<T> ThreeMomentum<T> {
505 pub(crate) fn new(px: T, py: T, pz: T) -> Self {
506 ThreeMomentum { px, py, pz }
507 }
508
509 pub(crate) fn into_dense(self, index: AbstractIndex) -> DenseTensor<T, OrderedStructure>
510 where
511 T: Clone,
512 {
513 let structure =
514 Canonicalized::from_iter(vec![Euclidean {}.new_slot(3, index)]).into_canonical();
515 DenseTensor::from_storage_data(vec![self.px, self.py, self.pz], structure).unwrap()
516 }
517
518 pub(crate) fn into_dense_param(self, index: AbstractIndex) -> DenseTensor<T, OrderedStructure>
519 where
520 T: Clone,
521 {
522 let structure =
523 Canonicalized::from_iter(vec![Euclidean {}.new_slot(3, index)]).into_canonical();
524 DenseTensor::from_storage_data(vec![self.px, self.py, self.pz], structure).unwrap()
525 }
526}
527
528impl<T: FloatLike> ThreeMomentum<F<T>> {
529 pub(crate) fn to_f64(&self) -> ThreeMomentum<F<f64>> {
530 ThreeMomentum {
531 px: F(self.px.to_f64()),
532 py: F(self.py.to_f64()),
533 pz: F(self.pz.to_f64()),
534 }
535 }
536 pub(crate) fn getdelphi(&self, p2: &ThreeMomentum<F<T>>) -> F<T> {
538 let pt1 = self.pt();
539 let pt2 = p2.pt();
540 if pt1.is_zero() {
541 return pt1.max_value();
542 }
543 if pt2.is_zero() {
544 return pt2.max_value();
545 }
546
547 let mut tmp = self.px.clone() * &p2.px + self.py.clone() * &p2.py;
548
549 tmp /= pt1 * pt2;
550 if tmp.norm() > tmp.one() + tmp.epsilon() {
551 panic!("Cosine larger than 1. in phase-space cuts.")
552 }
553 if tmp.norm() > tmp.one() {
554 (tmp.clone() / tmp.norm()).acos()
555 } else {
556 tmp.acos()
557 }
558 }
559
560 #[inline]
562 pub(crate) fn delta_r(&self, p2: &ThreeMomentum<F<T>>) -> F<T>
563 where
564 T: Real,
565 {
566 let delta_eta = self.pseudo_rap() - p2.pseudo_rap();
567 let delta_phi = self.getdelphi(p2);
568 (delta_eta.square() + delta_phi.square()).sqrt()
569 }
570
571 pub(crate) fn rotate_mut(&mut self, alpha: &F<T>, beta: &F<T>, gamma: &F<T>) {
572 let sin_alpha = alpha.sin();
573 let cos_alpha = alpha.cos();
574 let sin_beta = beta.sin();
575 let cos_beta = beta.cos();
576 let sin_gamma = gamma.sin();
577 let cos_gamma = gamma.cos();
578
579 let px = self.px.clone();
580 let py = self.py.clone();
581 let pz = self.pz.clone();
582
583 self.px = cos_gamma.clone() * &cos_beta * &px
584 + (-(cos_alpha.clone()) * &sin_gamma + sin_alpha.clone() * &sin_beta * &cos_gamma)
585 * &py
586 + (sin_alpha.clone() * &sin_gamma + cos_alpha.clone() * &sin_beta * &cos_gamma) * &pz;
587
588 self.py = sin_gamma.clone() * &cos_beta * &px
589 + (cos_alpha.clone() * &cos_gamma + sin_alpha.clone() * &sin_beta * &sin_gamma) * &py
590 + (-sin_alpha.clone() * &cos_gamma + cos_alpha.clone() * &sin_beta * &sin_gamma) * &pz;
591
592 self.pz =
593 -sin_beta * &px + cos_beta.clone() * &sin_alpha * &py + cos_alpha * &cos_beta * &pz;
594 }
595
596 #[inline]
598 pub(crate) fn pt(&self) -> F<T> {
599 (self.px.square() + self.py.square()).sqrt()
600 }
601
602 #[inline]
604 pub(crate) fn pseudo_rap(&self) -> F<T> {
605 let pt = self.pt();
606 if pt.less_than_epsilon() && self.pz.norm().less_than_epsilon() {
607 if self.pz.positive() {
608 return pt.max_value();
609 } else {
610 return pt.min_value();
611 }
612 }
613 let th = pt.atan2(&self.pz);
614 let two = pt.from_i64(2);
615 -(th / two).tan().ln()
616 }
617
618 pub(crate) fn cross_product(&self, rhs: &ThreeMomentum<F<T>>) -> ThreeMomentum<F<T>> {
619 ThreeMomentum {
620 px: &self.py * &rhs.pz - &self.pz * &rhs.py,
621 py: &self.pz * &rhs.px - &self.px * &rhs.pz,
622 pz: &self.px * &rhs.py - &self.py * &rhs.px,
623 }
624 }
625
626 pub(crate) fn axis_angle_rotation(
628 &self,
629 cos_theta: &F<T>,
630 axis: &ThreeMomentum<F<T>>,
631 ) -> ThreeMomentum<F<T>> {
632 let scale = axis.px.norm().max(axis.py.norm()).max(axis.pz.norm());
635 let axis = ThreeMomentum {
636 px: &axis.px / &scale,
637 py: &axis.py / &scale,
638 pz: &axis.pz / &scale,
639 };
640 let axis = &axis * &axis.norm().inv();
641 let sin_theta = if cos_theta >= &cos_theta.one() {
642 cos_theta.zero()
643 } else {
644 (cos_theta.one() - cos_theta.square()).sqrt()
645 };
646 let k_cross_v = axis.cross_product(self);
647 let k_dot_v = self * axis.clone();
648
649 self * cos_theta + k_cross_v * &sin_theta + &axis * &k_dot_v * &(self.px.one() - cos_theta)
650 }
651
652 pub(crate) fn get_cos_theta_with(&self, rhs: &ThreeMomentum<F<T>>) -> F<T> {
653 let self_norm = self.norm();
654 let rhs_norm = rhs.norm();
655 if self_norm < self_norm.epsilon() || rhs_norm < rhs_norm.epsilon() {
656 return self_norm.one();
657 }
658
659 let dot = self * rhs.clone();
660 dot / (self.norm() * rhs.norm())
661 }
662}
663
664impl<T: Neg<Output = T> + Clone> ThreeMomentum<T> {
665 pub(crate) fn perform_pi2_rotation_x_mut(&mut self) {
666 self.pz = -self.pz.clone();
667 std::mem::swap(&mut self.pz, &mut self.py);
668 }
669
670 pub(crate) fn perform_pi2_rotation_x(&self) -> Self {
671 Self {
673 px: self.px.clone(),
674 py: -self.pz.clone(),
675 pz: self.py.clone(),
676 }
677 }
678
679 pub(crate) fn perform_pi2_rotation_y_mut(&mut self) {
680 self.px = -self.px.clone();
681 std::mem::swap(&mut self.px, &mut self.pz);
682 }
683
684 pub(crate) fn perform_pi2_rotation_y(&self) -> Self {
685 Self {
687 px: self.pz.clone(),
688 py: self.py.clone(),
689 pz: -self.px.clone(),
690 }
691 }
692
693 pub(crate) fn perform_pi2_rotation_z_mut(&mut self) {
694 self.py = -self.py.clone();
695 std::mem::swap(&mut self.px, &mut self.py);
696 }
697
698 pub(crate) fn perform_pi2_rotation_z(&self) -> Self {
699 Self {
701 px: -self.py.clone(),
702 py: self.px.clone(),
703 pz: self.pz.clone(),
704 }
705 }
706}
707
708impl<T> Add<ThreeMomentum<T>> for ThreeMomentum<T>
709where
710 T: Add<T, Output = T>,
711{
712 type Output = ThreeMomentum<T>;
713 fn add(self, rhs: ThreeMomentum<T>) -> Self::Output {
714 ThreeMomentum {
715 px: self.px + rhs.px,
716 py: self.py + rhs.py,
717 pz: self.pz + rhs.pz,
718 }
719 }
720}
721
722impl<T> Add<&ThreeMomentum<T>> for ThreeMomentum<T>
723where
724 T: for<'a> Add<&'a T, Output = T>,
725{
726 type Output = ThreeMomentum<T>;
727 fn add(self, rhs: &ThreeMomentum<T>) -> Self::Output {
728 ThreeMomentum {
729 px: self.px + &rhs.px,
730 py: self.py + &rhs.py,
731 pz: self.pz + &rhs.pz,
732 }
733 }
734}
735
736impl<'b, T> Add<&ThreeMomentum<T>> for &'b ThreeMomentum<T>
737where
738 &'b T: for<'a> Add<&'a T, Output = T>,
739{
740 type Output = ThreeMomentum<T>;
741 fn add(self, rhs: &ThreeMomentum<T>) -> Self::Output {
742 ThreeMomentum {
743 px: &self.px + &rhs.px,
744 py: &self.py + &rhs.py,
745 pz: &self.pz + &rhs.pz,
746 }
747 }
748}
749
750impl<T> Add<ThreeMomentum<T>> for &ThreeMomentum<T>
751where
752 T: for<'a> Add<&'a T, Output = T>,
753{
754 type Output = ThreeMomentum<T>;
755 fn add(self, rhs: ThreeMomentum<T>) -> Self::Output {
756 rhs + self
757 }
758}
759
760impl<T> AddAssign<ThreeMomentum<T>> for ThreeMomentum<T>
761where
762 T: AddAssign<T>,
763{
764 fn add_assign(&mut self, rhs: ThreeMomentum<T>) {
765 self.px += rhs.px;
766 self.py += rhs.py;
767 self.pz += rhs.pz;
768 }
769}
770
771impl<'a, T> AddAssign<&'a ThreeMomentum<T>> for ThreeMomentum<T>
772where
773 T: AddAssign<&'a T>,
774{
775 fn add_assign(&mut self, rhs: &'a ThreeMomentum<T>) {
776 self.px += &rhs.px;
777 self.py += &rhs.py;
778 self.pz += &rhs.pz;
779 }
780}
781
782impl<T> Sub<ThreeMomentum<T>> for ThreeMomentum<T>
783where
784 T: Sub<T, Output = T>,
785{
786 type Output = ThreeMomentum<T>;
787 fn sub(self, rhs: ThreeMomentum<T>) -> Self::Output {
788 ThreeMomentum {
789 px: self.px - rhs.px,
790 py: self.py - rhs.py,
791 pz: self.pz - rhs.pz,
792 }
793 }
794}
795
796impl<T> Sub<&ThreeMomentum<T>> for &ThreeMomentum<T>
797where
798 for<'a> &'a T: Sub<&'a T, Output = T>,
799{
800 type Output = ThreeMomentum<T>;
801 fn sub(self, rhs: &ThreeMomentum<T>) -> Self::Output {
802 ThreeMomentum {
803 px: &self.px - &rhs.px,
804 py: &self.py - &rhs.py,
805 pz: &self.pz - &rhs.pz,
806 }
807 }
808}
809
810impl<T> SubAssign<ThreeMomentum<T>> for ThreeMomentum<T>
811where
812 T: SubAssign<T>,
813{
814 fn sub_assign(&mut self, rhs: ThreeMomentum<T>) {
815 self.px -= rhs.px;
816 self.py -= rhs.py;
817 self.pz -= rhs.pz;
818 }
819}
820
821impl<'a, T> SubAssign<&'a ThreeMomentum<T>> for ThreeMomentum<T>
822where
823 T: SubAssign<&'a T>,
824{
825 fn sub_assign(&mut self, rhs: &'a ThreeMomentum<T>) {
826 self.px -= &rhs.px;
827 self.py -= &rhs.py;
828 self.pz -= &rhs.pz;
829 }
830}
831
832impl<T> Mul<ThreeMomentum<T>> for ThreeMomentum<T>
833where
834 T: Mul<T, Output = T> + Add<T, Output = T>,
835{
836 type Output = T;
837 fn mul(self, rhs: ThreeMomentum<T>) -> Self::Output {
838 self.px * rhs.px + self.py * rhs.py + self.pz * rhs.pz
839 }
840}
841
842impl<T> Mul<&ThreeMomentum<T>> for ThreeMomentum<T>
843where
844 T: for<'a> Mul<&'a T, Output = T> + Add<T, Output = T>,
845{
846 type Output = T;
847 fn mul(self, rhs: &ThreeMomentum<T>) -> Self::Output {
848 self.px * &rhs.px + self.py * &rhs.py + self.pz * &rhs.pz
849 }
850}
851
852impl<T> Mul<ThreeMomentum<T>> for &ThreeMomentum<T>
853where
854 T: for<'b> Mul<&'b T, Output = T> + Add<T, Output = T>,
855{
856 type Output = T;
857 fn mul(self, rhs: ThreeMomentum<T>) -> Self::Output {
858 rhs * self
859 }
860}
861
862impl<T> Mul<T> for ThreeMomentum<T>
863where
864 T: Mul<T, Output = T> + Clone,
865{
866 type Output = ThreeMomentum<T>;
867 fn mul(self, rhs: T) -> Self::Output {
868 ThreeMomentum {
869 px: self.px * rhs.clone(),
870 py: self.py * rhs.clone(),
871 pz: self.pz * rhs,
872 }
873 }
874}
875
876impl<T> Mul<&T> for ThreeMomentum<T>
877where
878 T: for<'a> Mul<&'a T, Output = T> + Clone,
879{
880 type Output = ThreeMomentum<T>;
881 fn mul(self, rhs: &T) -> Self::Output {
882 ThreeMomentum {
883 px: self.px * rhs,
884 py: self.py * rhs,
885 pz: self.pz * rhs,
886 }
887 }
888}
889
890impl<T> Mul<T> for &ThreeMomentum<T>
891where
892 T: Mul<T, Output = T> + Clone,
893{
894 type Output = ThreeMomentum<T>;
895 fn mul(self, rhs: T) -> Self::Output {
896 ThreeMomentum {
897 px: self.px.clone() * rhs.clone(),
898 py: self.py.clone() * rhs.clone(),
899 pz: self.pz.clone() * rhs,
900 }
901 }
902}
903
904impl<T> Mul<&T> for &ThreeMomentum<T>
905where
906 T: for<'b> Mul<&'b T, Output = T> + Clone,
907{
908 type Output = ThreeMomentum<T>;
909 fn mul(self, rhs: &T) -> Self::Output {
910 ThreeMomentum {
911 px: self.px.clone() * rhs,
912 py: self.py.clone() * rhs,
913 pz: self.pz.clone() * rhs,
914 }
915 }
916}
917
918impl<T> Neg for ThreeMomentum<T>
919where
920 T: Neg<Output = T>,
921{
922 type Output = ThreeMomentum<T>;
923 fn neg(self) -> Self::Output {
924 ThreeMomentum {
925 px: -self.px,
926 py: -self.py,
927 pz: -self.pz,
928 }
929 }
930}
931
932impl<T> Neg for &ThreeMomentum<T>
933where
934 T: Neg<Output = T> + Clone,
935{
936 type Output = ThreeMomentum<T>;
937 fn neg(self) -> Self::Output {
938 ThreeMomentum {
939 px: -self.px.clone(),
940 py: -self.py.clone(),
941 pz: -self.pz.clone(),
942 }
943 }
944}
945
946impl<T: Display> Display for ThreeMomentum<T> {
947 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
948 write!(f, "px: {}, py: {}, pz: {}", self.px, self.py, self.pz)
949 }
950}
951
952impl<T: LowerExp> LowerExp for ThreeMomentum<T> {
953 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
954 write!(f, "px: {:e}, py: {:e}, pz: {:e}", self.px, self.py, self.pz)
955 }
956}
957
958impl<T: Default> Default for ThreeMomentum<T> {
959 fn default() -> Self {
960 ThreeMomentum {
961 px: T::default(),
962 py: T::default(),
963 pz: T::default(),
964 }
965 }
966}
967
968impl<T> ThreeMomentum<T> {
969 pub(crate) fn norm_squared(&self) -> T
970 where
971 T: for<'a> Mul<&'a T, Output = T> + Add<T, Output = T> + Clone,
972 {
973 self.px.clone() * &self.px + self.py.clone() * &self.py + self.pz.clone() * &self.pz
974 }
975
976 pub(crate) fn on_shell_energy(&self, mass: Option<T>) -> Energy<T>
977 where
978 T: Mul<T, Output = T> + Add<T, Output = T> + Clone + std::ops::Add<Output = T> + Real,
979 {
980 let energy_squared = self.on_shell_energy_squared(mass);
981 Energy {
982 value: energy_squared.value.sqrt(),
983 }
984 }
985
986 pub(crate) fn on_shell_energy_squared(&self, mass: Option<T>) -> Energy<T>
987 where
988 T: for<'a> Mul<&'a T, Output = T>
989 + Add<T, Output = T>
990 + Clone
991 + std::ops::Add<Output = T>
992 + Display,
993 {
994 let p2 = self.norm_squared();
995 if let Some(mass) = mass {
996 Energy {
998 value: p2 + mass.clone() * &mass,
999 }
1000 } else {
1001 Energy { value: p2 }
1002 }
1003 }
1004
1005 pub(crate) fn norm(&self) -> T
1006 where
1007 T: for<'a> Mul<&'a T, Output = T> + Add<T> + Real,
1008 {
1009 self.norm_squared().sqrt()
1010 }
1011
1012 pub(crate) fn into_four_momentum_parametric(self, id: usize) -> FourMomentum<T, Atom> {
1013 let energy = Energy::new_parametric(id);
1014 FourMomentum {
1015 temporal: energy,
1016 spatial: self,
1017 }
1018 }
1019
1020 pub(crate) fn into_on_shell_four_momentum(self, mass: Option<T>) -> FourMomentum<T, T>
1021 where
1022 T: Mul<T> + Add<T> + std::ops::Add<Output = T> + Real,
1023 {
1024 FourMomentum::new_on_shell(self, mass)
1025 }
1026
1027 pub(crate) fn cast<U>(&self) -> ThreeMomentum<U>
1028 where
1029 T: Clone + Into<U>,
1030 {
1031 ThreeMomentum {
1032 px: (self.px.clone()).into(),
1033 py: (self.py.clone()).into(),
1034 pz: (self.pz.clone()).into(),
1035 }
1036 }
1037
1038 #[allow(clippy::wrong_self_convention)]
1039 pub(crate) fn into_f64(&self) -> ThreeMomentum<f64>
1040 where
1041 T: FloatLike,
1042 {
1043 ThreeMomentum {
1044 px: self.px.to_f64(),
1045 py: self.py.to_f64(),
1046 pz: self.pz.to_f64(),
1047 }
1048 }
1049}
1050
1051impl<T> From<[T; 3]> for ThreeMomentum<T> {
1052 fn from(data: [T; 3]) -> Self {
1053 let [px, py, pz] = data;
1054 ThreeMomentum { px, py, pz }
1055 }
1056}
1057
1058impl<T> From<ThreeMomentum<T>> for [T; 3] {
1059 fn from(data: ThreeMomentum<T>) -> Self {
1060 [data.px, data.py, data.pz]
1061 }
1062}
1063
1064impl<T> From<(T, T, T)> for ThreeMomentum<T> {
1065 fn from(data: (T, T, T)) -> Self {
1066 let (px, py, pz) = data;
1067 ThreeMomentum { px, py, pz }
1068 }
1069}
1070
1071impl<T> From<ThreeMomentum<T>> for (T, T, T) {
1072 fn from(data: ThreeMomentum<T>) -> Self {
1073 (data.px, data.py, data.pz)
1074 }
1075}
1076
1077#[derive(Default, Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Encode, Decode)]
1078pub struct FourMomentum<T, U = T> {
1079 pub temporal: Energy<U>,
1080 pub spatial: ThreeMomentum<T>,
1081}
1082
1083impl<T: FloatLike> Sub<&FourMomentum<F<T>>> for &FourMomentum<F<T>> {
1084 type Output = FourMomentum<F<T>>;
1085 fn sub(self, rhs: &FourMomentum<F<T>>) -> Self::Output {
1086 FourMomentum {
1087 temporal: Energy {
1088 value: &self.temporal.value - &rhs.temporal.value,
1089 },
1090 spatial: &self.spatial - &rhs.spatial,
1091 }
1092 }
1093}
1094
1095impl<T> FourMomentum<T> {
1096 pub(crate) fn map_ref<U>(&self, f: &impl Fn(&T) -> U) -> FourMomentum<U> {
1097 FourMomentum {
1098 temporal: self.temporal.map_ref(f),
1099 spatial: self.spatial.map_ref(f),
1100 }
1101 }
1102
1103 pub(crate) fn map<U>(self, f: &impl Fn(T) -> U) -> FourMomentum<U> {
1104 FourMomentum {
1105 temporal: self.temporal.map(f),
1106 spatial: self.spatial.map(f),
1107 }
1108 }
1109}
1110
1111impl<T: FloatLike> ApproxEq<FourMomentum<F<T>>, F<T>> for FourMomentum<F<T>> {
1112 fn approx_eq(&self, other: &FourMomentum<F<T>>, threshold: &F<T>) -> bool {
1113 self.temporal.approx_eq(&other.temporal, threshold)
1114 && self.spatial.approx_eq(&other.spatial, threshold)
1115 }
1116}
1117
1118impl<T: FloatLike> ApproxEq<Polarization<Complex<F<T>>>, F<T>> for FourMomentum<F<T>> {
1119 fn approx_eq(&self, other: &Polarization<Complex<F<T>>>, tolerance: &F<T>) -> bool {
1120 if other.tensor.size().unwrap() != 4 {
1121 false
1122 } else {
1123 self.into_iter()
1124 .zip(other.tensor.iter_flat())
1125 .all(|(a, (_, b))| a.approx_eq(b, tolerance))
1126 }
1127 }
1128
1129 fn approx_eq_res(
1130 &self,
1131 other: &Polarization<Complex<F<T>>>,
1132 tolerance: &F<T>,
1133 ) -> color_eyre::Result<()> {
1134 if other.tensor.size().unwrap() != 4 {
1135 Err(eyre::eyre!("Polarization tensor has wrong size."))
1136 } else {
1137 self.into_iter()
1138 .zip(other.tensor.iter_flat())
1139 .try_for_each(|(a, (i, b))| {
1140 a.approx_eq_res(b, tolerance).wrap_err(format!(
1141 "Polarization tensor element {} does not match. ",
1142 i
1143 ))
1144 })
1145 }
1146 }
1147}
1148
1149impl<T: FloatLike> FourMomentum<F<T>> {
1150 pub(crate) fn from_ff64(four_momentum: &FourMomentum<F<f64>>) -> Self {
1151 let temporal = Energy::from_ff64(four_momentum.temporal);
1152 let spatial = ThreeMomentum::from_ff64(four_momentum.spatial);
1153 FourMomentum { temporal, spatial }
1154 }
1155
1156 pub(crate) fn rescale_spatial(&self, x: &F<T>) -> Self {
1157 FourMomentum {
1158 temporal: self.temporal.clone(),
1159 spatial: ThreeMomentum {
1160 px: &self.spatial.px * x,
1161 py: &self.spatial.py * x,
1162 pz: &self.spatial.pz * x,
1163 },
1164 }
1165 }
1166
1167 pub(crate) fn set_energy_on_shell(&self, mass: Option<F<T>>) -> Self {
1168 let energy = self.spatial.on_shell_energy(mass);
1169 FourMomentum {
1170 temporal: energy,
1171 spatial: self.spatial.clone(),
1172 }
1173 }
1174
1175 pub(crate) fn rapidity(&self) -> F<T> {
1176 let pt = self.spatial.pt();
1177 self.rapidity_with_pt2(&pt.square())
1178 }
1179
1180 pub(crate) fn rapidity_with_pt2(&self, pt2: &F<T>) -> F<T> {
1181 const MAX_RAPIDITY_SENTINEL: usize = 100_000;
1182
1183 let zero = self.temporal.value.zero();
1184 let pz = self.spatial.pz.clone();
1185 let abs_pz = pz.norm();
1186 let energy = self.temporal.value.clone();
1187
1188 if *pt2 == zero.clone() && energy == abs_pz {
1189 let max_rapidity_here = abs_pz.from_usize(MAX_RAPIDITY_SENTINEL) + abs_pz;
1190 if pz >= zero {
1191 max_rapidity_here
1192 } else {
1193 -max_rapidity_here
1194 }
1195 } else {
1196 let mass2 = energy.square()
1197 - (self.spatial.px.square() + self.spatial.py.square() + self.spatial.pz.square());
1198 let effective_mass2 = if mass2 < zero { zero.clone() } else { mass2 };
1199 let e_plus_abs_pz = energy + abs_pz;
1200 let half = e_plus_abs_pz.one() / e_plus_abs_pz.from_usize(2);
1201 let mut rapidity =
1202 ((pt2.clone() + effective_mass2) / (e_plus_abs_pz.clone() * e_plus_abs_pz)).ln()
1203 * half;
1204 if pz > zero {
1205 rapidity = -rapidity;
1206 }
1207 rapidity
1208 }
1209 }
1210}
1211
1212#[derive(
1213 Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Encode, Decode, Hash, JsonSchema,
1214)]
1215#[serde(untagged)]
1217pub enum ExternalMomenta<T> {
1218 Dependent(Dep),
1219 Independent([T; 4]),
1220}
1221
1222impl<T: FloatLike> Rotatable for ExternalMomenta<F<T>> {
1223 fn rotate(&self, rotation: &Rotation) -> Self {
1224 match self {
1225 ExternalMomenta::Dependent(_) => ExternalMomenta::Dependent(Dep::Dep),
1226 ExternalMomenta::Independent(data) => {
1227 let fm = FourMomentum::from(data.clone());
1228 fm.rotate(rotation).into()
1229 }
1230 }
1231 }
1232}
1233
1234#[derive(
1235 Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize, Encode, Decode, Hash, JsonSchema,
1236)]
1237pub enum Dep {
1238 #[serde(rename = "dependent")]
1239 Dep,
1240}
1241
1242#[derive(Error, Debug)]
1243pub enum ExternalMomentaError {
1244 #[error("Dependent momenta cannot be converted to FourMomentum")]
1245 Dependent,
1246}
1247
1248impl<T> TryFrom<ExternalMomenta<T>> for FourMomentum<T> {
1249 type Error = ExternalMomentaError;
1250 fn try_from(value: ExternalMomenta<T>) -> Result<Self, Self::Error> {
1251 match value {
1252 ExternalMomenta::Dependent(_) => Err(ExternalMomentaError::Dependent),
1253 ExternalMomenta::Independent(data) => Ok(FourMomentum::from(data)),
1254 }
1255 }
1256}
1257
1258impl<T> From<FourMomentum<T>> for ExternalMomenta<T> {
1259 fn from(value: FourMomentum<T>) -> Self {
1260 ExternalMomenta::Independent(value.into())
1261 }
1262}
1263
1264impl<T> From<[T; 4]> for ExternalMomenta<T> {
1265 fn from(data: [T; 4]) -> Self {
1266 ExternalMomenta::Independent(data)
1267 }
1268}
1269
1270impl<T: RefZero, U: RefZero> RefZero for FourMomentum<T, U> {
1271 fn ref_zero(&self) -> Self {
1272 FourMomentum {
1273 temporal: self.temporal.ref_zero(),
1274 spatial: self.spatial.ref_zero(),
1275 }
1276 }
1277}
1278
1279impl<T: RefZero, U: RefZero> RefZero<FourMomentum<T, U>> for &FourMomentum<T, U> {
1280 fn ref_zero(&self) -> FourMomentum<T, U> {
1281 FourMomentum {
1282 temporal: self.temporal.ref_zero(),
1283 spatial: self.spatial.ref_zero(),
1284 }
1285 }
1286}
1287
1288#[derive(
1289 Debug, PartialEq, Clone, Copy, Serialize, Deserialize, Encode, Decode, Eq, PartialOrd, Ord,
1290)]
1291pub struct PolDef {
1292 pub pol_type: PolType,
1293 pub eid: EdgeIndex,
1294}
1295
1296#[derive(
1297 Debug, PartialEq, Clone, Copy, Serialize, Deserialize, Encode, Decode, Eq, PartialOrd, Ord,
1298)]
1299pub enum PolType {
1300 U,
1301 V,
1302 UBar,
1303 VBar,
1304 Scalar,
1305 Epsilon,
1306 EpsilonBar,
1307}
1308
1309impl From<PolType> for feynkit_kinematics::WavefunctionKind {
1310 fn from(value: PolType) -> Self {
1311 match value {
1312 PolType::Scalar => Self::Scalar,
1313 PolType::Epsilon => Self::Epsilon,
1314 PolType::EpsilonBar => Self::EpsilonBar,
1315 PolType::U => Self::U,
1316 PolType::UBar => Self::UBar,
1317 PolType::V => Self::V,
1318 PolType::VBar => Self::VBar,
1319 }
1320 }
1321}
1322
1323impl From<feynkit_kinematics::WavefunctionKind> for PolType {
1324 fn from(value: feynkit_kinematics::WavefunctionKind) -> Self {
1325 use feynkit_kinematics::WavefunctionKind as Kind;
1326 match value {
1327 Kind::Scalar => Self::Scalar,
1328 Kind::Epsilon => Self::Epsilon,
1329 Kind::EpsilonBar => Self::EpsilonBar,
1330 Kind::U => Self::U,
1331 Kind::UBar => Self::UBar,
1332 Kind::V => Self::V,
1333 Kind::VBar => Self::VBar,
1334 }
1335 }
1336}
1337
1338impl PolType {
1339 pub(crate) fn bar(self) -> Self {
1340 feynkit_kinematics::WavefunctionKind::from(self)
1341 .bar()
1342 .into()
1343 }
1344}
1345
1346impl Display for PolType {
1347 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1348 match self {
1349 Self::U => write!(f, "u"),
1350 Self::V => write!(f, "v"),
1351 Self::VBar => write!(f, "vbar"),
1352 Self::UBar => write!(f, "ubar"),
1353 Self::Scalar => write!(f, ""),
1354 Self::Epsilon => write!(f, "ϵ"),
1355 Self::EpsilonBar => write!(f, "ϵbar"),
1356 }
1357 }
1358}
1359
1360#[derive(Debug, PartialEq, Clone, bincode_trait_derive::Encode, bincode_trait_derive::Decode)]
1361#[trait_decode(trait = symbolica::state::HasStateMap)]
1362pub struct Polarization<T> {
1363 pub tensor: DenseTensor<T, IndexLess<LibraryRep>>,
1364 pol_type: PolType,
1365}
1366
1367impl<T: FloatLike> ApproxEq<Polarization<Complex<F<T>>>, F<T>> for Polarization<Complex<F<T>>> {
1368 fn approx_eq(&self, other: &Polarization<Complex<F<T>>>, tolerance: &F<T>) -> bool {
1369 self.pol_type == other.pol_type
1370 && self
1371 .tensor
1372 .flat_iter()
1373 .zip(other.tensor.flat_iter())
1374 .all(|((_, a), (_, b))| a.approx_eq(b, tolerance))
1375 }
1376
1377 fn approx_eq_res(
1378 &self,
1379 other: &Polarization<Complex<F<T>>>,
1380 tolerance: &F<T>,
1381 ) -> color_eyre::Result<()> {
1382 if self.pol_type != other.pol_type {
1383 Err(eyre::eyre!(
1384 "Polarization types do not match. self: {}, other: {}",
1385 self,
1386 other
1387 ))
1388 } else {
1389 self.tensor
1390 .flat_iter()
1391 .zip(other.tensor.flat_iter())
1392 .try_for_each(|((i, a), (_, b))| {
1393 a.approx_eq_res(b, tolerance).wrap_err(format!(
1394 "Polarization tensor element {} does not match. self: {}, other: {}",
1395 i, self, other
1396 ))
1397 })
1398 }
1399 }
1400}
1401
1402impl<T: for<'a> std::ops::AddAssign<&'a T>> AddAssign<Polarization<T>> for Polarization<T> {
1403 fn add_assign(&mut self, rhs: Polarization<T>) {
1404 self.tensor += rhs.tensor;
1405 }
1406}
1407
1408impl<T: for<'a> SubAssign<&'a T>> SubAssign<Polarization<T>> for Polarization<T> {
1409 fn sub_assign(&mut self, rhs: Polarization<T>) {
1410 self.tensor -= rhs.tensor;
1411 }
1412}
1413
1414impl<T: FloatLike> Display for Polarization<F<T>> {
1415 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1416 write!(f, "Pol {}: {}", self.pol_type, self.tensor)
1417 }
1418}
1419
1420impl<T: FloatLike> Display for Polarization<Complex<F<T>>> {
1421 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1422 write!(f, "Pol {}: {}", self.pol_type, self.tensor)
1423 }
1424}
1425
1426impl<T: FloatLike> LowerExp for Polarization<Complex<F<T>>> {
1427 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1428 write!(f, "Pol {}: {:+e}", self.pol_type, self.tensor)
1429 }
1430}
1431
1432impl<T> Polarization<T> {
1433 pub(crate) fn map<U>(&self, f: impl Fn(&T) -> U) -> Polarization<U> {
1434 Polarization {
1435 tensor: self.tensor.map_data_ref(f),
1436 pol_type: self.pol_type,
1437 }
1438 }
1439}
1440
1441impl<T: Clone> Polarization<T> {
1442 pub(crate) fn is_scalar(&self) -> bool {
1443 self.pol_type == PolType::Scalar
1444 }
1445 pub(crate) fn scalar(value: T) -> Self {
1446 let structure = IndexLess::new(vec![]);
1447 Polarization {
1448 tensor: DenseTensor {
1449 data: vec![value],
1450 structure,
1451 },
1452 pol_type: PolType::Scalar,
1453 }
1454 }
1455
1456 pub(crate) fn lorentz(value: [T; 4]) -> Self {
1457 let structure = IndexLess::new(vec![Minkowski {}.new_rep(4).cast()]);
1458 Polarization {
1459 tensor: DenseTensor {
1460 data: value.to_vec(),
1461 structure,
1462 },
1463 pol_type: PolType::Epsilon,
1464 }
1465 }
1466
1467 pub(crate) fn bispinor_u(value: [T; 4]) -> Self {
1468 let structure = IndexLess::new(vec![GR.bis.new_rep(4)]);
1469
1470 Polarization {
1471 tensor: DenseTensor {
1472 data: value.to_vec(),
1473 structure,
1474 },
1475 pol_type: PolType::U,
1476 }
1477 }
1478
1479 pub(crate) fn bispinor_v(value: [T; 4]) -> Self {
1480 let structure = IndexLess::new(vec![GR.bis.new_rep(4)]);
1481
1482 Polarization {
1483 tensor: DenseTensor {
1484 data: value.to_vec(),
1485 structure,
1486 },
1487 pol_type: PolType::V,
1488 }
1489 }
1490
1491 pub(crate) fn shadow(&self) -> DenseTensor<Atom, IndexLess<LibraryRep>> {
1492 self.tensor
1493 .structure
1494 .clone()
1495 .to_dense_labeled(|_, i| FlatCoefficent::<NoArgs> {
1496 index: i,
1497 name: Some(symbol!(self.pol_type.to_string())),
1498 args: None,
1499 })
1500 .unwrap()
1501 }
1502}
1503
1504impl<T> Index<usize> for Polarization<T> {
1505 type Output = T;
1506 fn index(&self, index: usize) -> &Self::Output {
1507 &self.tensor[index.into()]
1508 }
1509}
1510
1511impl<T> RefZero for Polarization<T>
1512where
1513 T: RefZero + Clone,
1514{
1515 fn ref_zero(&self) -> Self {
1516 Polarization {
1517 tensor: <DenseTensor<_, _> as RefZero>::ref_zero(&self.tensor),
1518 pol_type: self.pol_type,
1519 }
1520 }
1521}
1522
1523impl<'a, T, U> Mul<&'a U> for Polarization<T>
1524where
1525 T: Clone + MulAssign<&'a U>,
1526{
1527 type Output = Polarization<T>;
1528 fn mul(mut self, rhs: &'a U) -> Self::Output {
1529 for i in self.tensor.data.iter_mut() {
1530 *i *= rhs;
1531 }
1532 self
1533 }
1534}
1535
1536impl<'a, T> MulAssign<&'a T> for Polarization<T>
1537where
1538 T: Clone + MulAssign<&'a T>,
1539{
1540 fn mul_assign(&mut self, rhs: &'a T) {
1541 for i in self.tensor.data.iter_mut() {
1542 *i *= rhs;
1543 }
1544 }
1545}
1546
1547impl<T, U, Out> FallibleAdd<Polarization<U>> for Polarization<T>
1548where
1549 T: FallibleAdd<U, Output = Out>,
1550{
1551 type Output = Polarization<Out>;
1552 fn add_fallible(&self, rhs: &Polarization<U>) -> Option<Self::Output> {
1553 Some(Polarization {
1554 tensor: self.tensor.add_fallible(&rhs.tensor)?,
1555 pol_type: self.pol_type,
1556 })
1557 }
1558}
1559
1560impl<T> Polarization<T> {
1561 pub(crate) fn cast<U>(&self) -> Polarization<U>
1562 where
1563 T: Clone,
1564 U: Clone + From<T>,
1565 {
1566 Polarization {
1567 tensor: self.tensor.cast(),
1568 pol_type: self.pol_type,
1569 }
1570 }
1571}
1572
1573impl<T> Polarization<Complex<T>> {
1574 pub(crate) fn complex_cast<U>(&self) -> Polarization<Complex<U>>
1575 where
1576 T: Clone,
1577 U: Clone + From<T>,
1578 {
1579 Polarization {
1580 tensor: self
1581 .tensor
1582 .map_data_ref(|d| d.map_ref(|r| r.clone().into())),
1583 pol_type: self.pol_type,
1584 }
1585 }
1586}
1587
1588impl<T: FloatLike> Polarization<Complex<F<T>>> {
1589 pub(crate) fn higher(&self) -> Polarization<Complex<F<T::Higher>>>
1590 where
1591 T::Higher: FloatLike,
1592 {
1593 Polarization {
1594 tensor: self.tensor.map_data_ref(|t| t.map_ref(|r| r.higher())),
1595 pol_type: self.pol_type,
1596 }
1597 }
1598
1599 pub(crate) fn lower(&self) -> Polarization<Complex<F<T::Lower>>>
1600 where
1601 T::Lower: FloatLike,
1602 {
1603 Polarization {
1604 tensor: self.tensor.map_data_ref(|t| t.map_ref(|r| r.lower())),
1605 pol_type: self.pol_type,
1606 }
1607 }
1608}
1609
1610impl<T: FloatLike, U: FloatLike> From<FourMomentum<T, U>> for FourMomentum<F<T>, F<U>> {
1611 fn from(value: FourMomentum<T, U>) -> Self {
1612 FourMomentum {
1613 temporal: value.temporal.into(),
1614 spatial: value.spatial.into(),
1615 }
1616 }
1617}
1618
1619impl<T: FloatLike, U: FloatLike> FourMomentum<F<T>, F<U>> {
1620 pub(crate) fn higher(&self) -> FourMomentum<F<T::Higher>, F<U::Higher>>
1621 where
1622 T::Higher: FloatLike,
1623 U::Higher: FloatLike,
1624 {
1625 FourMomentum {
1626 temporal: self.temporal.higher(),
1627 spatial: self.spatial.higher(),
1628 }
1629 }
1630
1631 pub(crate) fn lower(&self) -> FourMomentum<F<T::Lower>, F<U::Lower>>
1632 where
1633 T::Lower: FloatLike,
1634 U::Lower: FloatLike,
1635 {
1636 FourMomentum {
1637 temporal: self.temporal.lower(),
1638 spatial: self.spatial.lower(),
1639 }
1640 }
1641}
1642
1643impl<T, U> FourMomentum<T, U> {
1644 pub(crate) fn new(energy: Energy<U>, three_momentum: ThreeMomentum<T>) -> Self {
1645 FourMomentum {
1646 temporal: energy,
1647 spatial: three_momentum,
1648 }
1649 }
1650}
1651
1652impl<T: Real> RefDefault for FourMomentum<T, T> {
1653 fn default(&self) -> Self {
1654 let zero = self.temporal.value.zero();
1655 FourMomentum {
1656 temporal: Energy::new(zero.clone()),
1657 spatial: ThreeMomentum::new(zero.clone(), zero.clone(), zero.clone()),
1658 }
1659 }
1660}
1661
1662impl<T> Mul<T> for &FourMomentum<T, T>
1663where
1664 T: Mul<T, Output = T> + Clone,
1665{
1666 type Output = FourMomentum<T, T>;
1667 fn mul(self, rhs: T) -> Self::Output {
1668 FourMomentum {
1669 temporal: Energy {
1670 value: self.temporal.value.clone() * rhs.clone(),
1671 },
1672 spatial: self.spatial.clone() * rhs,
1673 }
1674 }
1675}
1676
1677impl<T> Mul<&T> for &FourMomentum<T, T>
1678where
1679 T: for<'b> Mul<&'b T, Output = T> + Clone,
1680{
1681 type Output = FourMomentum<T, T>;
1682 fn mul(self, rhs: &T) -> Self::Output {
1683 FourMomentum {
1684 temporal: Energy {
1685 value: self.temporal.value.clone() * rhs,
1686 },
1687 spatial: self.spatial.clone() * rhs,
1688 }
1689 }
1690}
1691
1692impl<T> FourMomentum<T, T> {
1693 pub(crate) fn zero(&self) -> Self
1694 where
1695 T: Real,
1696 {
1697 let zero = self.temporal.value.zero();
1698 FourMomentum {
1699 temporal: Energy::new(zero.clone()),
1700 spatial: ThreeMomentum::new(zero.clone(), zero.clone(), zero.clone()),
1701 }
1702 }
1703
1704 pub(crate) fn square(&self) -> T
1705 where
1706 T: for<'a> Mul<&'a T, Output = T> + Add<T, Output = T> + Clone + Sub<T, Output = T>,
1707 {
1708 let temporal = self.temporal.value.clone();
1709 let spatial = self.spatial.norm_squared();
1710 temporal * &self.temporal.value - spatial
1711 }
1712
1713 pub(crate) fn norm(&self) -> T
1714 where
1715 T: Real,
1716 {
1717 self.square().sqrt()
1718 }
1719
1720 pub(crate) fn from_args(energy: T, px: T, py: T, pz: T) -> Self {
1721 let energy = Energy::new(energy);
1722 let three_momentum = ThreeMomentum { px, py, pz };
1723 FourMomentum {
1724 temporal: energy,
1725 spatial: three_momentum,
1726 }
1727 }
1728 pub(crate) fn new_on_shell(three_momentum: ThreeMomentum<T>, mass: Option<T>) -> Self
1729 where
1730 T: Mul<T> + Add<T> + std::ops::Add<Output = T> + Real,
1731 {
1732 let energy = three_momentum.on_shell_energy(mass);
1733 FourMomentum {
1735 temporal: energy,
1736 spatial: three_momentum,
1737 }
1738 }
1739
1740 pub(crate) fn into_dense(self, index: AbstractIndex) -> DenseTensor<T, OrderedStructure>
1741 where
1742 T: Clone,
1743 {
1744 let structure =
1745 Canonicalized::from_iter([LibraryRep::new_slot(Minkowski {}.into(), 4, index)])
1746 .into_canonical();
1747 DenseTensor::from_storage_data(
1748 vec![
1749 self.temporal.value,
1750 self.spatial.px,
1751 self.spatial.py,
1752 self.spatial.pz,
1753 ],
1754 structure,
1755 )
1756 .unwrap()
1757 }
1758
1759 pub(crate) fn into_dense_named(
1760 self,
1761 index: AbstractIndex,
1762 name: Symbol,
1763 num: usize,
1764 ) -> DenseTensor<T, NamedStructure<Symbol, usize>>
1765 where
1766 T: Clone,
1767 {
1768 let structure = Canonicalized::<OrderedStructure>::from_iter([LibraryRep::new_slot(
1769 Minkowski {}.into(),
1770 4,
1771 index,
1772 )])
1773 .into_canonical()
1774 .to_named(name, Some(num));
1775 DenseTensor::from_storage_data(
1776 vec![
1777 self.temporal.value,
1778 self.spatial.px,
1779 self.spatial.py,
1780 self.spatial.pz,
1781 ],
1782 structure,
1783 )
1784 .unwrap()
1785 }
1786
1787 pub(crate) fn cast<U>(&self) -> FourMomentum<U, U>
1788 where
1789 T: Clone + Into<U>,
1790 {
1791 FourMomentum {
1792 temporal: Energy::new((self.temporal.value.clone()).into()),
1793 spatial: ThreeMomentum::cast(&self.spatial),
1794 }
1795 }
1796
1797 pub(crate) fn boost(&self, boost_vector: &ThreeMomentum<T>) -> FourMomentum<T>
1798 where
1799 T: Real + SingleFloat + PartialOrd,
1800 {
1801 let b2 = boost_vector.norm_squared();
1802 let one = b2.one();
1803 let zero = one.zero();
1804 let gamma = (one.clone() - &b2).sqrt().inv();
1805
1806 let bp = self.spatial.clone() * boost_vector;
1807 let gamma2 = if b2 > zero {
1808 (gamma.clone() - &one) / b2
1809 } else {
1810 zero
1811 };
1812 let factor = gamma2 * &bp + gamma.clone() * &self.temporal.value;
1813
1814 FourMomentum::from_args(
1815 (bp + &self.temporal.value) * &gamma,
1816 self.spatial.px.mul_add(&factor, &boost_vector.px),
1817 self.spatial.py.mul_add(&factor, &boost_vector.py),
1818 self.spatial.pz.mul_add(&factor, &boost_vector.pz),
1819 )
1820 }
1821}
1822
1823impl<T: FloatLike> FourMomentum<F<T>, F<T>> {
1824 pub(crate) fn dot(&self, p2: &FourMomentum<F<T>>) -> F<T> {
1825 &self.temporal.value * &p2.temporal.value
1826 - (&self.spatial.px * &p2.spatial.px
1827 + &self.spatial.py * &p2.spatial.py
1828 + &self.spatial.pz * &p2.spatial.pz)
1829 }
1830 pub(crate) fn getdelphi(&self, p2: &FourMomentum<F<T>>) -> F<T>
1832 where
1833 T: Real,
1834 {
1835 self.spatial.getdelphi(&p2.spatial)
1836 }
1837
1838 #[inline]
1840 pub(crate) fn delta_r(&self, p2: &FourMomentum<F<T>>) -> F<T>
1841 where
1842 T: Real,
1843 {
1844 self.spatial.delta_r(&p2.spatial)
1845 }
1846
1847 pub(crate) fn pt(&self) -> F<T>
1848 where
1849 T: Real,
1850 {
1851 self.spatial.pt()
1852 }
1853
1854 pub(crate) fn to_f64(&self) -> FourMomentum<F<f64>, F<f64>> {
1855 FourMomentum {
1856 temporal: Energy {
1857 value: F(self.temporal.value.to_f64()),
1858 },
1859 spatial: self.spatial.to_f64().cast(),
1860 }
1861 }
1862
1863 fn external_state_momentum(&self) -> feynkit_kinematics::FourMomentum<F<T>> {
1864 feynkit_kinematics::FourMomentum::from_args(
1865 self.temporal.value.clone(),
1866 self.spatial.px.clone(),
1867 self.spatial.py.clone(),
1868 self.spatial.pz.clone(),
1869 )
1870 }
1871
1872 pub(crate) fn pol_one(&self) -> [F<T>; 4] {
1873 self.external_state_momentum().transverse_basis()[0].clone()
1874 }
1875
1876 pub(crate) fn pol_two(&self) -> [F<T>; 4] {
1877 self.external_state_momentum().transverse_basis()[1].clone()
1878 }
1879
1880 pub(crate) fn eps_pol<Hel: Into<Helicity>>(
1881 &self,
1882 lambda: Hel,
1883 ) -> Result<Polarization<Complex<F<T>>>, WavefunctionError> {
1884 match lambda.into() {
1885 Helicity::Signed(lambda) => Ok(Polarization::from_external_state(
1886 self.external_state_momentum()
1887 .wavefunction(feynkit_kinematics::WavefunctionKind::Epsilon, lambda.into())?,
1888 )),
1889 _ => {
1891 let zero = self.temporal.value.zero();
1892 let cmpz = Complex::new_re(zero);
1893 Ok(Polarization::lorentz([
1894 cmpz.clone(),
1895 cmpz.clone(),
1896 cmpz.clone(),
1897 cmpz.clone(),
1898 ]))
1899 }
1900 }
1901 }
1902
1903 pub(crate) fn external_polarization(
1908 &self,
1909 pol_type: PolType,
1910 helicity: SignOrZero,
1911 rotations: &[RotationMethod],
1912 ) -> Result<Option<Polarization<Complex<F<T>>>>, WavefunctionError> {
1913 if pol_type == PolType::Scalar {
1914 return Ok(None);
1915 }
1916 let mut kinematic_rotations = Vec::with_capacity(rotations.len());
1917 for rotation in rotations {
1918 rotation.append_kinematic_rotations(&mut kinematic_rotations);
1919 }
1920 Ok(Some(Polarization::from_external_state(
1921 self.external_state_momentum()
1922 .wavefunction_after_rotations(
1923 pol_type.into(),
1924 helicity.into(),
1925 &kinematic_rotations,
1926 )?,
1927 )))
1928 }
1929
1930 pub(crate) fn omega(&self, lambda: Sign) -> Complex<F<T>> {
1931 let value = self.external_state_momentum().spinor_energy_factor(lambda);
1932 Complex::new(value.re, value.im)
1933 }
1934
1935 pub(crate) fn u(&self, lambda: Sign) -> Result<Polarization<Complex<F<T>>>, WavefunctionError> {
1936 Ok(Polarization::from_external_state(
1937 self.external_state_momentum()
1938 .wavefunction(feynkit_kinematics::WavefunctionKind::U, lambda.into())?,
1939 ))
1940 }
1941
1942 pub(crate) fn v(&self, lambda: Sign) -> Result<Polarization<Complex<F<T>>>, WavefunctionError> {
1943 Ok(Polarization::from_external_state(
1944 self.external_state_momentum()
1945 .wavefunction(feynkit_kinematics::WavefunctionKind::V, lambda.into())?,
1946 ))
1947 }
1948
1949 pub(crate) fn xi(&self, lambda: Sign) -> [Complex<F<T>>; 2] {
1950 self.external_state_momentum()
1951 .helicity_spinor(lambda)
1952 .map(|value| Complex::new(value.re, value.im))
1953 }
1954}
1955
1956impl<T: FloatLike> Polarization<Complex<F<T>>> {
1957 fn from_external_state(state: feynkit_kinematics::Wavefunction<F<T>>) -> Self {
1959 let kind = state.kind();
1960 let data = state
1961 .into_components()
1962 .into_iter()
1963 .map(|value| Complex::new(value.re, value.im))
1964 .collect();
1965 let structure = if kind == feynkit_kinematics::WavefunctionKind::Scalar {
1966 IndexLess::new(vec![])
1967 } else if kind.is_spinor() {
1968 IndexLess::new(vec![GR.bis.new_rep(4)])
1969 } else {
1970 IndexLess::new(vec![Minkowski {}.new_rep(4).cast()])
1971 };
1972 Self {
1973 tensor: DenseTensor { data, structure },
1974 pol_type: kind.into(),
1975 }
1976 }
1977
1978 pub(crate) fn bar(&self) -> Self {
1979 let state = feynkit_kinematics::Wavefunction::from_components(
1980 self.pol_type.into(),
1981 self.tensor
1982 .data
1983 .iter()
1984 .map(|value| SymComplex::new(value.re.clone(), value.im.clone()))
1985 .collect(),
1986 )
1987 .expect("invalid external wavefunction components")
1988 .bar();
1989 Self {
1991 tensor: DenseTensor {
1992 data: state
1993 .into_components()
1994 .into_iter()
1995 .map(|value| Complex::new(value.re, value.im))
1996 .collect(),
1997 structure: self.tensor.structure.clone(),
1998 },
1999 pol_type: self.pol_type.bar(),
2000 }
2001 }
2002}
2003
2004impl<T> IntoIterator for Polarization<T> {
2005 type IntoIter = std::vec::IntoIter<Self::Item>;
2006 type Item = T;
2007
2008 fn into_iter(self) -> Self::IntoIter {
2009 self.tensor.data.into_iter()
2010 }
2011}
2012
2013impl<'a, T> IntoIterator for &'a Polarization<T> {
2014 type IntoIter = std::slice::Iter<'a, T>;
2015 type Item = &'a T;
2016
2017 fn into_iter(self) -> Self::IntoIter {
2018 self.tensor.data.iter()
2019 }
2020}
2021
2022#[derive(
2023 Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Hash, bincode::Encode, bincode::Decode,
2024)]
2025pub enum Helicity {
2026 Signed(SignOrZero),
2027 Summed,
2028 SummedAveraged,
2029}
2030
2031impl Display for Helicity {
2032 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2033 match self {
2034 Helicity::Signed(s) => write!(f, "{}", s),
2035 Helicity::Summed => write!(f, "summed"),
2036 Helicity::SummedAveraged => write!(f, "summed_averaged"),
2037 }
2038 }
2039}
2040
2041impl Serialize for Helicity {
2042 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2043 where
2044 S: serde::Serializer,
2045 {
2046 match self {
2047 Helicity::Signed(SignOrZero::Plus) => serializer.serialize_i8(1),
2048 Helicity::Signed(SignOrZero::Minus) => serializer.serialize_i8(-1),
2049 Helicity::Signed(SignOrZero::Zero) => serializer.serialize_i8(0),
2050 Helicity::Summed => serializer.serialize_str("summed"),
2051 Helicity::SummedAveraged => serializer.serialize_str("summed_averaged"),
2052 }
2053 }
2054}
2055
2056#[derive(Deserialize)]
2057#[serde(untagged)]
2058enum HelicitySerde {
2059 Numeric(i8),
2060 Text(String),
2061}
2062
2063impl<'de> Deserialize<'de> for Helicity {
2064 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2065 where
2066 D: serde::Deserializer<'de>,
2067 {
2068 let value = HelicitySerde::deserialize(deserializer)?;
2069 match value {
2070 HelicitySerde::Numeric(value) => {
2071 Helicity::try_from(value).map_err(serde::de::Error::custom)
2072 }
2073 HelicitySerde::Text(value) => {
2074 Helicity::from_str(&value).map_err(serde::de::Error::custom)
2075 }
2076 }
2077 }
2078}
2079
2080impl JsonSchema for Helicity {
2081 fn schema_name() -> std::borrow::Cow<'static, str> {
2082 "Helicity".into()
2083 }
2084
2085 fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
2086 schemars::json_schema!({
2087 "description": "Helicity input. Use -1, 0, or 1 for fixed helicities; or use a string for summed modes.",
2088 "oneOf": [
2089 {
2090 "type": "integer",
2091 "enum": [-1, 0, 1]
2092 },
2093 {
2094 "type": "string",
2095 "enum": [
2096 "+",
2097 "-",
2098 "0",
2099 "plus",
2100 "minus",
2101 "zero",
2102 "summed",
2103 "summed_averaged",
2104 "summed-averaged"
2105 ]
2106 }
2107 ]
2108 })
2109 }
2110}
2111
2112impl TryFrom<i8> for Helicity {
2113 type Error = SignError;
2114 fn try_from(value: i8) -> Result<Self, Self::Error> {
2115 Ok(Helicity::Signed(SignOrZero::try_from(value)?))
2116 }
2117}
2118
2119impl From<Sign> for Helicity {
2120 fn from(sign: Sign) -> Self {
2121 Self::Signed(sign.into())
2122 }
2123}
2124
2125impl From<SignOrZero> for Helicity {
2126 fn from(sign: SignOrZero) -> Self {
2127 Self::Signed(sign)
2128 }
2129}
2130
2131impl TryFrom<Helicity> for SignOrZero {
2132 type Error = SignError;
2133
2134 fn try_from(value: Helicity) -> Result<Self, Self::Error> {
2135 match value {
2136 Helicity::Signed(sign) => Ok(sign),
2137 Helicity::Summed | Helicity::SummedAveraged => Err(SignError::InvalidValue),
2138 }
2139 }
2140}
2141
2142impl TryFrom<Helicity> for Sign {
2143 type Error = SignError;
2144
2145 fn try_from(value: Helicity) -> Result<Self, Self::Error> {
2146 match value {
2147 Helicity::Signed(sign) => sign.try_into(),
2148 Helicity::Summed | Helicity::SummedAveraged => Err(SignError::InvalidValue),
2149 }
2150 }
2151}
2152
2153#[allow(non_upper_case_globals)]
2154impl Helicity {
2155 pub const ZERO: Self = Self::Signed(SignOrZero::Zero);
2156 pub const PLUS: Self = Self::Signed(SignOrZero::Plus);
2157 pub const MINUS: Self = Self::Signed(SignOrZero::Minus);
2158 pub const Zero: Self = Self::ZERO;
2159 pub const Plus: Self = Self::PLUS;
2160 pub const Minus: Self = Self::MINUS;
2161}
2162
2163impl FromStr for Helicity {
2164 type Err = String;
2165
2166 fn from_str(value: &str) -> Result<Self, Self::Err> {
2167 match value.trim().to_ascii_lowercase().as_str() {
2168 "+" | "plus" => Ok(Self::PLUS),
2169 "-" | "minus" => Ok(Self::MINUS),
2170 "0" | "zero" => Ok(Self::ZERO),
2171 "summed" => Ok(Self::Summed),
2172 "summed_averaged" | "summed-averaged" => Ok(Self::SummedAveraged),
2173 _ => Err(format!(
2174 "Invalid helicity '{value}'. Expected one of -1, 0, 1, plus, minus, zero, summed, summed_averaged"
2175 )),
2176 }
2177 }
2178}
2179
2180#[derive(
2181 Debug, PartialEq, Eq, Clone, Serialize, Deserialize, Encode, Decode, PartialOrd, Ord, Hash,
2182)]
2183pub struct Signature(pub Vec<SignOrZero>);
2184
2185impl Display for Signature {
2186 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2187 for sign in &self.0 {
2188 write!(f, "{}", sign)?;
2189 }
2190 Ok(())
2191 }
2192}
2193
2194impl FromIterator<SignOrZero> for Signature {
2195 fn from_iter<I: IntoIterator<Item = SignOrZero>>(iter: I) -> Self {
2196 Signature(iter.into_iter().collect())
2197 }
2198}
2199
2200impl FromIterator<i8> for Signature {
2201 fn from_iter<I: IntoIterator<Item = i8>>(iter: I) -> Self {
2202 Signature(
2203 iter.into_iter()
2204 .map(|x| match x {
2205 0 => SignOrZero::Zero,
2206 1 => SignOrZero::Plus,
2207 -1 => SignOrZero::Minus,
2208 _ => panic!("Invalid value for Signature"),
2209 })
2210 .collect(),
2211 )
2212 }
2213}
2214
2215impl FromIterator<isize> for Signature {
2216 fn from_iter<I: IntoIterator<Item = isize>>(iter: I) -> Self {
2217 Signature(
2218 iter.into_iter()
2219 .map(|x| match x {
2220 0 => SignOrZero::Zero,
2221 1 => SignOrZero::Plus,
2222 -1 => SignOrZero::Minus,
2223 _ => panic!("Invalid value for Signature"),
2224 })
2225 .collect(),
2226 )
2227 }
2228}
2229
2230impl From<Vec<i8>> for Signature {
2231 fn from(value: Vec<i8>) -> Self {
2232 Signature::from_iter(value)
2233 }
2234}
2235
2236impl IntoIterator for Signature {
2237 type Item = SignOrZero;
2238 type IntoIter = std::vec::IntoIter<Self::Item>;
2239
2240 fn into_iter(self) -> Self::IntoIter {
2241 self.0.into_iter()
2242 }
2243}
2244
2245impl<'a> IntoIterator for &'a Signature {
2246 type Item = SignOrZero;
2247 type IntoIter = std::iter::Copied<std::slice::Iter<'a, Self::Item>>;
2248
2249 fn into_iter(self) -> Self::IntoIter {
2250 self.0.iter().copied()
2251 }
2252}
2253
2254impl Index<usize> for Signature {
2255 type Output = SignOrZero;
2256 fn index(&self, index: usize) -> &Self::Output {
2257 &self.0[index]
2258 }
2259}
2260
2261impl Signature {
2262 pub(crate) fn validate_basis<T>(&self, basis: &[T]) -> bool {
2263 self.len() == basis.len()
2264 }
2265
2266 pub(crate) fn sum(&mut self, other: &Self) {
2267 for (i, sign) in other.iter().enumerate() {
2268 match (self[i], sign) {
2269 (SignOrZero::Zero, SignOrZero::Zero) => self.0[i] = SignOrZero::Zero,
2270 (SignOrZero::Zero, SignOrZero::Plus) => self.0[i] = SignOrZero::Plus,
2271 (SignOrZero::Zero, SignOrZero::Minus) => self.0[i] = SignOrZero::Minus,
2272 (SignOrZero::Plus, SignOrZero::Zero) => self.0[i] = SignOrZero::Plus,
2273 (SignOrZero::Plus, SignOrZero::Plus) => panic!("cannot add two positive signs"),
2274 (SignOrZero::Plus, SignOrZero::Minus) => self.0[i] = SignOrZero::Zero,
2275 (SignOrZero::Minus, SignOrZero::Zero) => self.0[i] = SignOrZero::Minus,
2276 (SignOrZero::Minus, SignOrZero::Plus) => self.0[i] = SignOrZero::Zero,
2277 (SignOrZero::Minus, SignOrZero::Minus) => panic!("cannot add two negative signs"),
2278 }
2279 }
2280 }
2281
2282 pub(crate) fn panic_validate_basis<T>(&self, basis: &[T]) {
2283 if !self.validate_basis(basis) {
2284 panic!(
2285 "Invalid basis for Signature, expected length {}, got length {}",
2286 self.len(),
2287 basis.len()
2288 );
2289 }
2290 }
2291
2292 pub(crate) fn to_momtrop_format(&self) -> Vec<isize> {
2293 self.0
2294 .iter()
2295 .map(|x| match x {
2296 SignOrZero::Zero => 0,
2297 SignOrZero::Plus => 1,
2298 SignOrZero::Minus => -1,
2299 })
2300 .collect()
2301 }
2302 pub(crate) fn len(&self) -> usize {
2303 self.0.len()
2304 }
2305
2306 pub(crate) fn iter(&'_ self) -> std::slice::Iter<'_, SignOrZero> {
2307 self.0.iter()
2308 }
2309
2310 pub(crate) fn is_empty(&self) -> bool {
2311 self.0.is_empty()
2312 }
2313 pub(crate) fn apply<T>(&self, basis: &[T]) -> T
2314 where
2315 T: RefZero + Clone + Neg<Output = T> + AddAssign<T>,
2316 {
2317 let mut result = basis[0].ref_zero();
2319 for (&sign, t) in self.0.iter().zip(basis.iter().cloned()) {
2320 result += sign * t;
2321 }
2322 result
2323 }
2324
2325 pub(crate) fn apply_iter<I, T>(&self, basis: I) -> Option<T>
2326 where
2327 I: IntoIterator,
2328 I::Item: RefZero<T>,
2329 T: Clone + SubAssign<I::Item> + AddAssign<I::Item>,
2330 {
2331 let mut basis_iter = basis.into_iter();
2332 let mut signature_iter = self.into_iter();
2333
2334 while let (Some(sign), Some(item)) = (signature_iter.next(), basis_iter.next()) {
2335 if sign.is_sign() {
2336 let mut result = item.ref_zero();
2338 match sign {
2339 SignOrZero::Zero => {
2340 panic!("unreachable");
2341 }
2343 SignOrZero::Plus => {
2344 result += item;
2345 }
2346 SignOrZero::Minus => {
2347 result -= item;
2348 }
2349 }
2350
2351 while let (Some(sign), Some(item)) = (signature_iter.next(), basis_iter.next()) {
2353 match sign {
2354 SignOrZero::Zero => {}
2355 SignOrZero::Plus => {
2356 result += item;
2357 }
2358 SignOrZero::Minus => {
2359 result -= item;
2360 }
2361 }
2362 }
2363
2364 return Some(result);
2365 }
2366 }
2367
2368 None
2370 }
2371
2372 pub(crate) fn label_with(&self, label: &str) -> String {
2373 let mut result = String::new();
2374 let mut first = true;
2375 for (i, sign) in self.0.iter().enumerate() {
2376 if !first {
2377 result.push_str(&sign.to_string());
2378 } else {
2379 first = false;
2380 }
2381 if sign.is_sign() {
2382 result.push_str(&format!("{}_{}", label, i));
2383 }
2384 }
2385 result
2386 }
2387}
2388
2389#[test]
2390fn test_signature() {
2391 let sig = Signature(vec![SignOrZero::Plus, SignOrZero::Minus]);
2392 let basis: Vec<i32> = vec![1, 2];
2393 assert_eq!(sig.apply(&basis), 1 - 2);
2394 assert_eq!(sig.apply_iter(basis.iter()), Some(-1));
2395
2396 let basis: [FourMomentum<i32>; 4] = [
2397 FourMomentum::from_args(1, 1, 0, 0),
2398 FourMomentum::from_args(1, 0, 1, 0),
2399 FourMomentum::from_args(1, 0, 0, 1),
2400 FourMomentum::from_args(1, 1, 1, 1),
2401 ];
2402
2403 let sig = Signature(vec![
2404 SignOrZero::Plus,
2405 SignOrZero::Minus,
2406 SignOrZero::Zero,
2407 SignOrZero::Plus,
2408 ]);
2409
2410 assert_eq!(sig.apply(&basis), FourMomentum::from_args(1, 2, 0, 1));
2411 let sig = Signature(vec![
2412 SignOrZero::Zero,
2413 SignOrZero::Zero,
2414 SignOrZero::Zero,
2415 SignOrZero::Zero,
2416 ]);
2417 assert_eq!(sig.apply_iter(basis.iter()), None);
2418 let sig = Signature(vec![
2419 SignOrZero::Zero,
2420 SignOrZero::Zero,
2421 SignOrZero::Zero,
2422 SignOrZero::Minus,
2423 ]);
2424 assert_eq!(sig.apply_iter(basis.iter()), Some(-basis[3]));
2425}
2426
2427impl<T> IntoIterator for FourMomentum<T> {
2457 type Item = T;
2458 type IntoIter = std::array::IntoIter<T, 4>;
2459
2460 fn into_iter(self) -> Self::IntoIter {
2461 let [e, px, py, pz] = [
2462 self.temporal.value,
2463 self.spatial.px,
2464 self.spatial.py,
2465 self.spatial.pz,
2466 ];
2467 [e, px, py, pz].into_iter()
2468 }
2469}
2470
2471impl<'a, T> IntoIterator for &'a FourMomentum<T> {
2472 type Item = &'a T;
2473 type IntoIter = std::array::IntoIter<&'a T, 4>;
2474
2475 fn into_iter(self) -> Self::IntoIter {
2476 let [e, px, py, pz] = [
2477 &self.temporal.value,
2478 &self.spatial.px,
2479 &self.spatial.py,
2480 &self.spatial.pz,
2481 ];
2482 [e, px, py, pz].into_iter()
2483 }
2484}
2485
2486impl<T> From<[T; 4]> for FourMomentum<T, T> {
2487 fn from(data: [T; 4]) -> Self {
2488 let [t, px, py, pz] = data;
2489 FourMomentum {
2490 temporal: Energy::new(t),
2491 spatial: ThreeMomentum { px, py, pz },
2492 }
2493 }
2494}
2495
2496impl<T> From<FourMomentum<T, T>> for [T; 4] {
2497 fn from(data: FourMomentum<T, T>) -> Self {
2498 [
2499 data.temporal.value,
2500 data.spatial.px,
2501 data.spatial.py,
2502 data.spatial.pz,
2503 ]
2504 }
2505}
2506
2507impl<T> From<(T, T, T, T)> for FourMomentum<T, T> {
2508 fn from(data: (T, T, T, T)) -> Self {
2509 let (t, px, py, pz) = data;
2510 FourMomentum {
2511 temporal: Energy::new(t),
2512 spatial: ThreeMomentum { px, py, pz },
2513 }
2514 }
2515}
2516
2517impl<T> From<FourMomentum<T, T>> for (T, T, T, T) {
2518 fn from(data: FourMomentum<T, T>) -> Self {
2519 (
2520 data.temporal.value,
2521 data.spatial.px,
2522 data.spatial.py,
2523 data.spatial.pz,
2524 )
2525 }
2526}
2527
2528impl<T> FourMomentum<T, Atom> {
2529 pub(crate) fn into_dense_param(
2530 self,
2531 index: AbstractIndex,
2532 ) -> DenseTensor<MultivariatePolynomial<RationalField, T>, OrderedStructure>
2533 where
2534 T: Clone + Into<Coefficient> + Exponent,
2535 {
2536 let structure =
2537 Canonicalized::from_iter([LibraryRep::new_slot(Minkowski {}.into(), 4, index)])
2538 .into_canonical();
2539 let energy = self
2540 .temporal
2541 .value
2542 .to_polynomial(&RationalField::new(IntegerRing {}), None);
2543
2544 let px: MultivariatePolynomial<RationalField, _> =
2545 Atom::num(self.spatial.px).to_polynomial(&RationalField::new(IntegerRing {}), None);
2546 let py =
2547 Atom::num(self.spatial.py).to_polynomial(&RationalField::new(IntegerRing {}), None);
2548 let pz =
2549 Atom::num(self.spatial.pz).to_polynomial(&RationalField::new(IntegerRing {}), None);
2550
2551 DenseTensor::from_storage_data(vec![energy, px, py, pz], structure).unwrap()
2552 }
2553}
2554
2555impl<T, U> Add<FourMomentum<T, U>> for FourMomentum<T, U>
2556where
2557 T: Add<T, Output = T>,
2558 U: Add<U, Output = U>,
2559{
2560 type Output = FourMomentum<T, U>;
2561 fn add(self, rhs: FourMomentum<T, U>) -> Self::Output {
2562 FourMomentum {
2563 temporal: self.temporal + rhs.temporal,
2564 spatial: self.spatial + rhs.spatial,
2565 }
2566 }
2567}
2568
2569impl<T, U> AddAssign<FourMomentum<T, U>> for FourMomentum<T, U>
2570where
2571 T: AddAssign<T>,
2572 U: AddAssign<U>,
2573{
2574 fn add_assign(&mut self, rhs: FourMomentum<T, U>) {
2575 self.temporal += rhs.temporal;
2576 self.spatial += rhs.spatial;
2577 }
2578}
2579
2580impl<'a, T, U> AddAssign<&'a FourMomentum<T, U>> for FourMomentum<T, U>
2581where
2582 T: AddAssign<&'a T>,
2583 U: AddAssign<&'a U>,
2584{
2585 fn add_assign(&mut self, rhs: &'a FourMomentum<T, U>) {
2586 self.temporal += &rhs.temporal;
2587 self.spatial += &rhs.spatial;
2588 }
2589}
2590
2591impl<T, U> Sub<FourMomentum<T, U>> for FourMomentum<T, U>
2592where
2593 T: Sub<T, Output = T>,
2594 U: Sub<U, Output = U>,
2595{
2596 type Output = FourMomentum<T, U>;
2597 fn sub(self, rhs: FourMomentum<T, U>) -> Self::Output {
2598 FourMomentum {
2599 temporal: self.temporal - rhs.temporal,
2600 spatial: self.spatial - rhs.spatial,
2601 }
2602 }
2603}
2604
2605impl<T, U> Neg for FourMomentum<T, U>
2606where
2607 T: Neg<Output = T>,
2608 U: Neg<Output = U>,
2609{
2610 type Output = FourMomentum<T, U>;
2611 fn neg(self) -> Self::Output {
2612 FourMomentum {
2613 temporal: -self.temporal,
2614 spatial: -self.spatial,
2615 }
2616 }
2617}
2618
2619impl<T, U> Neg for &FourMomentum<T, U>
2620where
2621 T: Neg<Output = T> + Clone,
2622 U: Neg<Output = U> + Clone,
2623{
2624 type Output = FourMomentum<T, U>;
2625 fn neg(self) -> Self::Output {
2626 FourMomentum {
2627 temporal: -self.temporal.clone(),
2628 spatial: -self.spatial.clone(),
2629 }
2630 }
2631}
2632
2633impl<T, U> SubAssign<FourMomentum<T, U>> for FourMomentum<T, U>
2634where
2635 T: SubAssign<T>,
2636 U: SubAssign<U>,
2637{
2638 fn sub_assign(&mut self, rhs: FourMomentum<T, U>) {
2639 self.temporal -= rhs.temporal;
2640 self.spatial -= rhs.spatial;
2641 }
2642}
2643
2644impl<'a, T, U> SubAssign<&'a FourMomentum<T, U>> for FourMomentum<T, U>
2645where
2646 T: SubAssign<&'a T>,
2647 U: SubAssign<&'a U>,
2648{
2649 fn sub_assign(&mut self, rhs: &'a FourMomentum<T, U>) {
2650 self.temporal -= &rhs.temporal;
2651 self.spatial -= &rhs.spatial;
2652 }
2653}
2654
2655impl<T: Display, U: Display> Display for FourMomentum<T, U> {
2656 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
2657 write!(f, "{}, {}", self.temporal, self.spatial)
2658 }
2659}
2660
2661impl<T: LowerExp, U: LowerExp> LowerExp for FourMomentum<T, U> {
2662 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
2663 write!(f, "{:e}, {:e}", self.temporal, self.spatial)
2664 }
2665}
2666
2667impl<T: FloatLike> From<Vector<F<T>, 3>> for ThreeMomentum<F<T>> {
2668 fn from(value: Vector<F<T>, 3>) -> Self {
2669 ThreeMomentum::new(value[0].clone(), value[1].clone(), value[2].clone())
2670 }
2671}
2672
2673pub enum LorentzTransformation<T> {
2674 Boost(ThreeMomentum<T>),
2675 Rotation(Rotation),
2676 General {
2677 boost: ThreeMomentum<T>,
2678 rotation: Rotation,
2679 },
2680}
2681
2682pub trait LorentzTransformable<T>: Rotatable {
2683 fn lorentz_transform(&self, transformation: &LorentzTransformation<T>) -> Self;
2684}
2685
2686pub enum LorentzRep {
2714 Scalar,
2717 Vector,
2718 Bispinor,
2719}
2720
2721#[derive(Clone, Copy, Debug, Encode, Decode)]
2722pub enum RotationMethod {
2723 EulerAngles(f64, f64, f64),
2724 Pi2X,
2725 Pi2Y,
2726 Pi2Z,
2727 Identity,
2728 AxisAngle { axis: [f64; 3], cos_theta: f64 },
2729}
2730
2731impl RotationMethod {
2732 fn append_kinematic_rotations<T: FloatLike>(
2734 &self,
2735 rotations: &mut Vec<KinematicRotation<F<T>>>,
2736 ) {
2737 let rotation = match *self {
2738 RotationMethod::Identity => KinematicRotation::Identity,
2739 RotationMethod::Pi2X => KinematicRotation::quarter_turn(KinematicAxis::X),
2740 RotationMethod::Pi2Y => KinematicRotation::quarter_turn(KinematicAxis::Y),
2741 RotationMethod::Pi2Z => KinematicRotation::quarter_turn(KinematicAxis::Z),
2742 RotationMethod::EulerAngles(alpha, beta, gamma) => {
2744 KinematicRotation::euler(F::from_f64(alpha), F::from_f64(beta), F::from_f64(gamma))
2745 }
2746 RotationMethod::AxisAngle { cos_theta: 1.0, .. } => KinematicRotation::Identity,
2747 RotationMethod::AxisAngle { axis, cos_theta } => {
2748 let [x, y, z] = axis.map(|v| F(T::from_f64_exact_binary(v)));
2751 let scale = x.norm().max(y.norm()).max(z.norm());
2752 let (x, y, z) = (x / &scale, y / &scale, z / scale);
2753 let transverse = (x.square() + y.square()).sqrt();
2754 let phi = if x.is_zero() && y.is_zero() {
2755 z.zero()
2756 } else {
2757 y.atan2(&x)
2758 };
2759 let beta = transverse.atan2(&z);
2760 let theta = F(T::from_f64_exact_binary(cos_theta)).acos();
2761 rotations.push(KinematicRotation::euler(z.zero(), z.zero(), -&phi));
2762 rotations.push(KinematicRotation::euler(z.zero(), -&beta, theta));
2763 KinematicRotation::euler(z.zero(), beta, phi)
2764 }
2765 };
2766 rotations.push(rotation);
2767 }
2768}
2769
2770impl Display for RotationMethod {
2771 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2772 match self {
2773 RotationMethod::EulerAngles(alpha, beta, gamma) => {
2774 write!(f, "EulerAngles({}, {}, {})", alpha, beta, gamma)
2775 }
2776 RotationMethod::Pi2X => write!(f, "Pi/2 rotation around x-axis"),
2777 RotationMethod::Pi2Y => write!(f, "Pi/2 rotation around y-axis"),
2778 RotationMethod::Pi2Z => write!(f, "Pi/2 rotation around z-axis"),
2779 RotationMethod::Identity => write!(f, "Identity rotation"),
2780 RotationMethod::AxisAngle { axis, cos_theta } => {
2781 write!(f, "Axis-angle rotation around {axis:?}, cosine {cos_theta}")
2782 }
2783 }
2784 }
2785}
2786
2787impl From<RotationMethod> for Rotation {
2788 fn from(method: RotationMethod) -> Self {
2789 Rotation::new(method)
2790 }
2791}
2792
2793#[derive(Clone, Encode, Decode)]
2794#[trait_decode(trait = GammaLoopContext)]
2795pub struct Rotation {
2796 pub method: RotationMethod,
2797 pub lorentz_rotation: EvalTensor<ExpressionEvaluator<Complex<F<f64>>>, OrderedStructure>,
2798 pub bispinor_rotation: EvalTensor<ExpressionEvaluator<Complex<F<f64>>>, OrderedStructure>,
2799 }
2801
2802impl Rotation {
2803 pub(crate) fn is_identity(&self) -> bool {
2804 matches!(self.method, RotationMethod::Identity)
2805 || matches!(self.method, RotationMethod::AxisAngle { cos_theta, .. } if cos_theta == 1.0)
2806 }
2807
2808 pub(crate) fn inverse_rotate_three<T: FloatLike>(
2809 &self,
2810 momentum: &ThreeMomentum<F<T>>,
2811 ) -> ThreeMomentum<F<T>> {
2812 match self.method {
2813 RotationMethod::Identity => momentum.clone(),
2814 RotationMethod::Pi2X => ThreeMomentum {
2815 px: momentum.px.clone(),
2816 py: momentum.pz.clone(),
2817 pz: -momentum.py.clone(),
2818 },
2819 RotationMethod::Pi2Y => ThreeMomentum {
2820 px: -momentum.pz.clone(),
2821 py: momentum.py.clone(),
2822 pz: momentum.px.clone(),
2823 },
2824 RotationMethod::Pi2Z => ThreeMomentum {
2825 px: momentum.py.clone(),
2826 py: -momentum.px.clone(),
2827 pz: momentum.pz.clone(),
2828 },
2829 RotationMethod::AxisAngle { axis, cos_theta } => {
2830 let axis = ThreeMomentum::from(
2831 axis.map(|component| F(T::from_f64_exact_binary(-component))),
2832 );
2833 momentum.axis_angle_rotation(&F(T::from_f64_exact_binary(cos_theta)), &axis)
2834 }
2835 RotationMethod::EulerAngles(alpha, beta, gamma) => {
2836 let alpha = F::<T>::from_f64(alpha);
2839 let beta = F::<T>::from_f64(beta);
2840 let gamma = F::<T>::from_f64(gamma);
2841 let sin_alpha = alpha.sin();
2842 let cos_alpha = alpha.cos();
2843 let sin_beta = beta.sin();
2844 let cos_beta = beta.cos();
2845 let sin_gamma = gamma.sin();
2846 let cos_gamma = gamma.cos();
2847
2848 let px = momentum.px.clone();
2849 let py = momentum.py.clone();
2850 let pz = momentum.pz.clone();
2851
2852 ThreeMomentum {
2853 px: cos_gamma.clone() * &cos_beta * &px + sin_gamma.clone() * &cos_beta * &py
2854 - sin_beta.clone() * &pz,
2855 py: (-(cos_alpha.clone()) * &sin_gamma
2856 + sin_alpha.clone() * &sin_beta * &cos_gamma)
2857 * &px
2858 + (cos_alpha.clone() * &cos_gamma
2859 + sin_alpha.clone() * &sin_beta * &sin_gamma)
2860 * &py
2861 + cos_beta.clone() * &sin_alpha * &pz,
2862 pz: (sin_alpha.clone() * &sin_gamma
2863 + cos_alpha.clone() * &sin_beta * &cos_gamma)
2864 * &px
2865 + (-sin_alpha.clone() * &cos_gamma
2866 + cos_alpha.clone() * &sin_beta * &sin_gamma)
2867 * &py
2868 + cos_alpha * &cos_beta * &pz,
2869 }
2870 }
2871 }
2872 }
2873
2874 pub(crate) fn inverse_rotate_four<T: FloatLike>(
2875 &self,
2876 momentum: &FourMomentum<F<T>>,
2877 ) -> FourMomentum<F<T>> {
2878 FourMomentum {
2879 temporal: momentum.temporal.clone(),
2880 spatial: self.inverse_rotate_three(&momentum.spatial),
2881 }
2882 }
2883
2884 pub(crate) fn setting(&self) -> RotationSetting {
2885 match self.method {
2886 RotationMethod::EulerAngles(alpha, beta, gamma) => {
2887 RotationSetting::EulerAngles { alpha, beta, gamma }
2888 }
2889 RotationMethod::Pi2X => RotationSetting::Pi2X {},
2890 RotationMethod::Pi2Y => RotationSetting::Pi2Y {},
2891 RotationMethod::Pi2Z => RotationSetting::Pi2Z {},
2892 RotationMethod::Identity => RotationSetting::None {},
2893 RotationMethod::AxisAngle { axis, cos_theta } => {
2894 RotationSetting::AxisAngle { axis, cos_theta }
2895 }
2896 }
2897 }
2898 pub(crate) fn new(method: RotationMethod) -> Self {
2899 let mu = Minkowski::slot(4, 1);
2900
2901 let al = Minkowski::slot(4, 3);
2902 let mud = mu.dual();
2903
2904 let shadow: NamedStructure<String, ()> = Canonicalized::<OrderedStructure>::from_iter([mu])
2905 .into_canonical()
2906 .to_named("eps".to_string(), None);
2907 let shadow_t: MixedTensor<_, OrderedStructure> =
2908 ParamOrConcrete::param(shadow.to_shell().expanded_shadow().unwrap().into())
2909 .cast_structure();
2910
2911 let rotation: MixedTensor<f64, _> = method
2912 .lorentz_tensor(mud, al)
2913 .try_into_dense()
2914 .unwrap()
2915 .into();
2916
2917 let fn_map = FunctionMap::new();
2918
2919 let lorentz_eval: EvalTensor<ExpressionEvaluator<SymComplex<Rational>>, OrderedStructure> =
2920 shadow_t
2921 .contract(&rotation)
2922 .unwrap()
2923 .try_into_parametric()
2924 .unwrap()
2925 .to_evaluation_tree(
2926 &fn_map,
2927 &shadow_t.try_into_parametric().unwrap().tensor.data(),
2928 )
2929 .unwrap()
2930 .linearize(
2931 &OptimizationSettings::new()
2932 .cpe_iterations(Some(1))
2933 .verbose(false),
2934 );
2935
2936 let i = GR.bis.new_slot(4, 1);
2937
2938 let j = GR.bis.new_slot(4, 3);
2939
2940 let shadow: NamedStructure<String, ()> = Canonicalized::from_iter([i.cast::<LibraryRep>()])
2941 .into_canonical()
2942 .to_named("u".to_string(), None);
2943 let shadow_t: MixedTensor<_, OrderedStructure> =
2944 ParamOrConcrete::param(shadow.to_shell().expanded_shadow().unwrap().into())
2945 .cast_structure();
2946
2947 let rotation: MixedTensor<f64, _> =
2948 ParamOrConcrete::Concrete(RealOrComplexTensor::Complex(method.bispinor_tensor(i, j)));
2949
2950 let res = shadow_t
2951 .contract(&rotation)
2952 .unwrap()
2953 .try_into_parametric()
2954 .unwrap();
2955
2956 let fn_map = FunctionMap::new();
2957 let mut params = shadow_t.try_into_parametric().unwrap().tensor.data();
2958 params.push(Atom::i());
2959
2960 let spinor_eval: EvalTensor<ExpressionEvaluator<SymComplex<Rational>>, OrderedStructure> =
2961 res.to_evaluation_tree(&fn_map, ¶ms).unwrap().linearize(
2962 &OptimizationSettings::new()
2963 .cpe_iterations(Some(1))
2964 .verbose(false),
2965 );
2966
2967 Self {
2968 method,
2969 lorentz_rotation: lorentz_eval.map_coeff(&|f| {
2970 Complex::new(F::from_f64(f.re.to_f64()), F::from_f64(f.im.to_f64()))
2971 }),
2972 bispinor_rotation: spinor_eval.map_coeff(&|f| {
2973 Complex::new(F::from_f64(f.re.to_f64()), F::from_f64(f.im.to_f64()))
2974 }),
2975 }
2976 }
2977}
2978
2979impl RotationMethod {
2980 pub(crate) fn generator(
2981 &self,
2982 i: AbstractIndex,
2983 j: AbstractIndex,
2984 ) -> DataTensor<f64, OrderedStructure> {
2985 let structure = Canonicalized::from_iter([
2986 LibraryRep::new_slot(Minkowski {}.into(), 4, i),
2987 LibraryRep::new_slot(Minkowski {}.into(), 4, j),
2988 ]);
2989 let layout = TensorDataLayout::from_canonicalized(&structure)
2990 .expect("rotation generators have concrete dimensions");
2991 let zero = 0.;
2992 match self {
2993 RotationMethod::Identity => {
2994 let omega = SparseTensor::empty(structure.into_canonical(), zero);
2995 omega.into()
2996 }
2997 RotationMethod::Pi2X => {
2998 let mut omega = SparseTensor::empty(structure.into_canonical(), zero);
2999 omega
3000 .set(
3001 &layout
3002 .logical_expanded_to_storage_expanded(&[2, 3])
3003 .unwrap(),
3004 -zero.PIHALF(),
3005 )
3006 .unwrap();
3007 omega
3008 .set(
3009 &layout
3010 .logical_expanded_to_storage_expanded(&[3, 2])
3011 .unwrap(),
3012 zero.PIHALF(),
3013 )
3014 .unwrap();
3015 omega.into()
3016 }
3017 RotationMethod::Pi2Y => {
3018 let mut omega = SparseTensor::empty(structure.into_canonical(), zero);
3019 omega
3020 .set(
3021 &layout
3022 .logical_expanded_to_storage_expanded(&[1, 3])
3023 .unwrap(),
3024 zero.PIHALF(),
3025 )
3026 .unwrap();
3027 omega
3028 .set(
3029 &layout
3030 .logical_expanded_to_storage_expanded(&[3, 1])
3031 .unwrap(),
3032 -zero.PIHALF(),
3033 )
3034 .unwrap();
3035 omega.into()
3036 }
3037 RotationMethod::Pi2Z => {
3038 let mut omega = SparseTensor::empty(structure.into_canonical(), zero);
3039 omega
3040 .set(
3041 &layout
3042 .logical_expanded_to_storage_expanded(&[1, 2])
3043 .unwrap(),
3044 -zero.PIHALF(),
3045 )
3046 .unwrap();
3047 omega
3048 .set(
3049 &layout
3050 .logical_expanded_to_storage_expanded(&[2, 1])
3051 .unwrap(),
3052 zero.PIHALF(),
3053 )
3054 .unwrap();
3055 omega.into()
3056 }
3057 RotationMethod::AxisAngle { axis, cos_theta } => {
3058 let scale = axis.iter().map(|value| value.abs()).fold(0.0_f64, f64::max);
3059 let scaled = axis.map(|value| value / scale);
3060 let norm = scaled.iter().map(|value| value * value).sum::<f64>().sqrt();
3061 let [x, y, z] = scaled.map(|value| value / norm * cos_theta.acos());
3062 DenseTensor::from_storage_data(
3063 layout
3064 .reorder_to_storage(vec![
3065 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -z, y, 0.0, z, 0.0, -x, 0.0, -y, x, 0.0,
3066 ])
3067 .unwrap(),
3068 structure.into_canonical(),
3069 )
3070 .unwrap()
3071 .into()
3072 }
3073 RotationMethod::EulerAngles(alpha, beta, gamma) => DenseTensor::from_storage_data(
3074 layout
3075 .reorder_to_storage(vec![
3076 zero, zero, zero, zero, zero, zero, -gamma, *beta, zero, *gamma, zero, -alpha, zero, -beta, *alpha, zero,
3081 ])
3082 .unwrap(),
3083 structure.into_canonical(),
3084 )
3085 .unwrap()
3086 .into(),
3087 }
3088 }
3089
3090 pub(crate) fn lorentz_tensor(
3091 &self,
3092 i: Slot<Minkowski>,
3093 j: Slot<Minkowski>,
3094 ) -> DataTensor<f64, OrderedStructure> {
3095 let structure = Canonicalized::from_iter([i.cast::<LibraryRep>(), j.cast()]);
3096 let layout = TensorDataLayout::from_canonicalized(&structure)
3097 .expect("Lorentz rotations have concrete dimensions");
3098
3099 match self {
3100 RotationMethod::Identity => {
3101 let rot = DenseTensor::from_storage_data(
3102 layout
3103 .reorder_to_storage(vec![
3104 1., 0., 0., 0., 0., -1., 0., 0., 0., 0., -1., 0., 0., 0., 0., -1.,
3108 ])
3109 .unwrap(),
3110 structure.into_canonical(),
3111 )
3112 .unwrap();
3113 rot.into()
3114 }
3115 RotationMethod::Pi2X => {
3116 let rot = DenseTensor::from_storage_data(
3117 layout
3118 .reorder_to_storage(vec![
3119 1., 0., 0., 0., 0., -1., 0., 0., 0., 0., 0., -1., 0., 0., 1., 0.,
3123 ])
3124 .unwrap(),
3125 structure.into_canonical(),
3126 )
3127 .unwrap();
3128 rot.into()
3129 }
3130 RotationMethod::Pi2Y => {
3131 let rot = DenseTensor::from_storage_data(
3132 layout
3133 .reorder_to_storage(vec![
3134 1., 0., 0., 0., 0., 0., 0., 1., 0., 0., -1., 0., 0., -1., 0., 0.,
3138 ])
3139 .unwrap(),
3140 structure.into_canonical(),
3141 )
3142 .unwrap();
3143 rot.into()
3144 }
3145 RotationMethod::Pi2Z => {
3146 let rot = DenseTensor::from_storage_data(
3147 layout
3148 .reorder_to_storage(vec![
3149 1., 0., 0., 0., 0., 0., -1., 0., 0., 1., 0., 0., 0., 0., 0., -1.,
3153 ])
3154 .unwrap(),
3155 structure.into_canonical(),
3156 )
3157 .unwrap();
3158 rot.into()
3159 }
3160 RotationMethod::AxisAngle { axis, cos_theta } => {
3161 let axis = ThreeMomentum::from(axis.map(F));
3162 let mut data = vec![0.0; 16];
3163 data[0] = 1.0;
3164 for input in 0..3 {
3165 let basis = ThreeMomentum::from(std::array::from_fn(|index| {
3166 F(if index == input { 1.0 } else { 0.0 })
3167 }));
3168 let rotated = basis.axis_angle_rotation(&F(*cos_theta), &axis);
3169 for (output, value) in rotated.into_iter().enumerate() {
3170 data[(input + 1) * 4 + output + 1] = -value.0;
3173 }
3174 }
3175 DenseTensor::from_storage_data(
3176 layout.reorder_to_storage(data).unwrap(),
3177 structure.into_canonical(),
3178 )
3179 .unwrap()
3180 .into()
3181 }
3182 RotationMethod::EulerAngles(alpha, beta, gamma) => DenseTensor::from_storage_data(
3183 layout
3184 .reorder_to_storage(vec![
3185 1.,
3187 0.,
3188 0.,
3189 0.,
3190 0.,
3192 -gamma.cos() * beta.cos(),
3193 alpha.sin() * beta.sin() * gamma.cos() - alpha.cos() * gamma.sin(),
3194 alpha.sin() * gamma.sin() + alpha.cos() * beta.sin() * gamma.cos(),
3195 0.,
3197 gamma.sin() * beta.cos(),
3198 -alpha.cos() * gamma.cos() - alpha.sin() * beta.sin() * gamma.sin(),
3199 -alpha.sin() * gamma.cos() + alpha.cos() * beta.sin() * gamma.sin(),
3200 0.,
3202 -beta.sin(),
3203 alpha.sin() * beta.cos(),
3204 -alpha.cos() * beta.cos(),
3205 ])
3206 .unwrap(),
3207 structure.into_canonical(),
3208 )
3209 .unwrap()
3210 .into(),
3211 }
3239 }
3240
3241 pub(crate) fn bispinor_tensor(
3242 &self,
3243 i: Slot<LibraryRep>,
3244 j: Slot<LibraryRep>,
3245 ) -> DataTensor<Complex<f64>, OrderedStructure> {
3246 let structure = Canonicalized::from_iter([i.cast::<LibraryRep>(), j.cast()]);
3247 let layout = TensorDataLayout::from_canonicalized(&structure)
3248 .expect("bispinor rotations have concrete dimensions");
3249 let storage_indices = |logical: &[usize]| {
3250 layout
3251 .logical_expanded_to_storage_expanded(logical)
3252 .expect("hard-coded bispinor coordinates are in bounds")
3253 };
3254 let zero = 0.; let zeroc = Complex::new_re(zero);
3256
3257 match self {
3258 RotationMethod::Identity => {
3259 let mut rot = SparseTensor::empty(structure.into_canonical(), zeroc);
3260 rot.set(&storage_indices(&[0, 0]), zeroc.one()).unwrap();
3261 rot.set(&storage_indices(&[1, 1]), zeroc.one()).unwrap();
3262 rot.set(&storage_indices(&[2, 2]), zeroc.one()).unwrap();
3263 rot.set(&storage_indices(&[3, 3]), zeroc.one()).unwrap();
3264 rot.into()
3265 }
3266 RotationMethod::Pi2X => {
3267 let mut rot = SparseTensor::empty(structure.into_canonical(), zeroc);
3268 let sqrt2_half = zero.SQRT_2_HALF();
3269 let sqrt2_halfim = Complex::new_im(sqrt2_half);
3270 let sqrt2_halfre = Complex::new_re(sqrt2_half);
3271
3272 rot.set(&storage_indices(&[0, 0]), sqrt2_halfim).unwrap();
3273 rot.set(&storage_indices(&[0, 1]), sqrt2_halfim).unwrap();
3274 rot.set(&storage_indices(&[1, 0]), sqrt2_halfim).unwrap();
3275 rot.set(&storage_indices(&[1, 1]), sqrt2_halfre).unwrap();
3276 rot.set(&storage_indices(&[2, 2]), sqrt2_halfim).unwrap();
3277 rot.set(&storage_indices(&[2, 3]), sqrt2_halfim).unwrap();
3278 rot.set(&storage_indices(&[3, 2]), sqrt2_halfim).unwrap();
3279 rot.set(&storage_indices(&[3, 3]), sqrt2_halfre).unwrap();
3280 rot.into()
3281 }
3282 RotationMethod::Pi2Y => {
3283 let mut rot = SparseTensor::empty(structure.into_canonical(), zeroc);
3284 let sqrt2_half = zero.SQRT_2_HALF();
3285 let sqrt2_halfim = Complex::new_im(sqrt2_half);
3286 let sqrt2_halfre = Complex::new_re(sqrt2_half);
3287 let nsqrt2_half = -sqrt2_halfre;
3288
3289 rot.set(&storage_indices(&[0, 0]), sqrt2_halfim).unwrap();
3290 rot.set(&storage_indices(&[0, 1]), nsqrt2_half).unwrap();
3291 rot.set(&storage_indices(&[1, 0]), nsqrt2_half).unwrap();
3292 rot.set(&storage_indices(&[1, 1]), sqrt2_halfre).unwrap();
3293 rot.set(&storage_indices(&[2, 2]), sqrt2_halfim).unwrap();
3294 rot.set(&storage_indices(&[2, 3]), nsqrt2_half).unwrap();
3295 rot.set(&storage_indices(&[3, 2]), nsqrt2_half).unwrap();
3296 rot.set(&storage_indices(&[3, 3]), sqrt2_halfre).unwrap();
3297 rot.into()
3298 }
3299 RotationMethod::Pi2Z => {
3300 let mut rot = SparseTensor::empty(structure.into_canonical(), zeroc);
3301 let sqrt2_half = zero.SQRT_2_HALF();
3302 let sqrt2_halfc = Complex::new(sqrt2_half, sqrt2_half);
3303 let sqrt2_halfcc = sqrt2_halfc.conj();
3304
3305 rot.set(&storage_indices(&[0, 0]), sqrt2_halfc).unwrap();
3306 rot.set(&storage_indices(&[1, 1]), sqrt2_halfcc).unwrap();
3307 rot.set(&storage_indices(&[2, 2]), sqrt2_halfc).unwrap();
3308 rot.set(&storage_indices(&[3, 3]), sqrt2_halfcc).unwrap();
3309 rot.into()
3310 }
3311 RotationMethod::AxisAngle { axis, cos_theta } => {
3312 let scale = axis.iter().map(|value| value.abs()).fold(0.0_f64, f64::max);
3313 let scaled = axis.map(|value| value / scale);
3314 let norm = scaled.iter().map(|value| value * value).sum::<f64>().sqrt();
3315 let [x, y, z] = scaled.map(|value| value / norm);
3316 let cosine_half = ((1.0 + cos_theta) / 2.0).sqrt();
3317 let sine_half = ((1.0 - cos_theta) / 2.0).sqrt();
3318 let diagonal = Complex::new(cosine_half, -z * sine_half);
3321 let lower = Complex::new(y * sine_half, -x * sine_half);
3322 let upper = Complex::new(-y * sine_half, -x * sine_half);
3323 DenseTensor::from_storage_data(
3324 layout
3325 .reorder_to_storage(vec![
3326 diagonal,
3327 lower,
3328 zeroc,
3329 zeroc,
3330 upper,
3331 diagonal.conj(),
3332 zeroc,
3333 zeroc,
3334 zeroc,
3335 zeroc,
3336 diagonal,
3337 lower,
3338 zeroc,
3339 zeroc,
3340 upper,
3341 diagonal.conj(),
3342 ])
3343 .unwrap(),
3344 structure.into_canonical(),
3345 )
3346 .unwrap()
3347 .into()
3348 }
3349 RotationMethod::EulerAngles(alpha, beta, gamma) => {
3350 let norm = alpha.square() + beta.square() + gamma.square();
3351
3352 if alpha.is_zero() && beta.is_zero() {
3353 let normhalf = &norm / 2.; let cos_phihalf = normhalf.cos();
3355 let sin_phihalf = normhalf.sin();
3356
3357 let e = Complex::new(cos_phihalf, sin_phihalf);
3358 let econj = e.conj();
3359 return DenseTensor::from_storage_data(
3360 layout
3361 .reorder_to_storage(vec![
3362 e, zeroc, zeroc, zeroc, zeroc, econj, zeroc, zeroc, zeroc, zeroc, e, zeroc, zeroc, zeroc, zeroc, econj,
3367 ])
3368 .unwrap(),
3369 structure.into_canonical(),
3370 )
3371 .unwrap()
3372 .into();
3373 }
3374
3375 let complex_phi = Complex::new(*alpha, *beta);
3376
3377 let normhalf = &norm / 2.; let cos_phihalf = normhalf.cos();
3379 let sin_phihalf = normhalf.sin();
3380
3381 let a_00 = Complex::new(gamma / norm * cos_phihalf, sin_phihalf);
3382 let a_01 =
3383 Complex::new_im((norm - gamma.square() / norm) * sin_phihalf) / complex_phi;
3384 let a_10 = complex_phi * Complex::new_im(sin_phihalf / norm);
3385 let a_11 = Complex::new(cos_phihalf, -gamma / norm * sin_phihalf);
3386
3387 DenseTensor::from_storage_data(
3388 layout
3389 .reorder_to_storage(vec![
3390 a_00, a_01, zeroc, zeroc, a_10, a_11, zeroc, zeroc, zeroc, zeroc, a_00, a_01, zeroc, zeroc, a_10, a_11,
3395 ])
3396 .unwrap(),
3397 structure.into_canonical(),
3398 )
3399 .unwrap()
3400 .into()
3401 }
3402 }
3403 }
3404}
3405
3406pub trait Rotatable {
3407 fn rotate(&self, rotation: &Rotation) -> Self;
3408}
3409
3410impl<T: FloatLike> Rotatable for ThreeMomentum<F<T>> {
3411 fn rotate(&self, rotation: &Rotation) -> Self {
3412 match rotation.method {
3413 RotationMethod::Identity => self.clone(),
3414 RotationMethod::Pi2X => ThreeMomentum::perform_pi2_rotation_x(self),
3415 RotationMethod::Pi2Y => ThreeMomentum::perform_pi2_rotation_y(self),
3416 RotationMethod::Pi2Z => ThreeMomentum::perform_pi2_rotation_z(self),
3417 RotationMethod::AxisAngle { axis, cos_theta } => {
3418 let axis = ThreeMomentum::from(
3421 axis.map(|component| F(T::from_f64_exact_binary(component))),
3422 );
3423 self.axis_angle_rotation(&F(T::from_f64_exact_binary(cos_theta)), &axis)
3424 }
3425 RotationMethod::EulerAngles(alpha, beta, gamma) => {
3426 let mut result = self.clone();
3427 result.rotate_mut(&F::from_f64(alpha), &F::from_f64(beta), &F::from_f64(gamma));
3428 result
3429 }
3430 }
3431 }
3432}
3433
3434impl<T: FloatLike> Rotatable for ThreeMomentum<HyperDual<F<T>>> {
3435 fn rotate(&self, rotation: &Rotation) -> Self {
3436 match rotation.method {
3437 RotationMethod::Identity => self.clone(),
3438 RotationMethod::Pi2X => ThreeMomentum::perform_pi2_rotation_x(self),
3439 RotationMethod::Pi2Y => ThreeMomentum::perform_pi2_rotation_y(self),
3440 RotationMethod::Pi2Z => ThreeMomentum::perform_pi2_rotation_z(self),
3441 RotationMethod::AxisAngle { axis, cos_theta } => {
3442 let axis = ThreeMomentum::from(
3443 axis.map(|component| F(T::from_f64_exact_binary(component))),
3444 );
3445 let cosine = F(T::from_f64_exact_binary(cos_theta));
3446 let mut result = self.clone();
3447 for coefficient in 0..self.px.values.len() {
3450 let vector = ThreeMomentum {
3451 px: self.px.values[coefficient].clone(),
3452 py: self.py.values[coefficient].clone(),
3453 pz: self.pz.values[coefficient].clone(),
3454 }
3455 .axis_angle_rotation(&cosine, &axis);
3456 result.px.values[coefficient] = vector.px;
3457 result.py.values[coefficient] = vector.py;
3458 result.pz.values[coefficient] = vector.pz;
3459 }
3460 result
3461 }
3462 RotationMethod::EulerAngles(alpha, beta, gamma) => {
3463 let mut result = self.clone();
3464 result.rotate_mut(
3465 &new_constant(&self.px, &F::from_f64(alpha)),
3466 &new_constant(&self.py, &F::from_f64(beta)),
3467 &new_constant(&self.pz, &F::from_f64(gamma)),
3468 );
3469 result
3470 }
3471 }
3472 }
3473}
3474
3475impl<T: FloatLike> ThreeMomentum<HyperDual<F<T>>> {
3476 fn rotate_mut(
3477 &mut self,
3478 alpha: &HyperDual<F<T>>,
3479 beta: &HyperDual<F<T>>,
3480 gamma: &HyperDual<F<T>>,
3481 ) {
3482 let sin_alpha = alpha.sin();
3483 let cos_alpha = alpha.cos();
3484 let sin_beta = beta.sin();
3485 let cos_beta = beta.cos();
3486 let sin_gamma = gamma.sin();
3487 let cos_gamma = gamma.cos();
3488
3489 let px = self.px.clone();
3490 let py = self.py.clone();
3491 let pz = self.pz.clone();
3492
3493 self.px = cos_gamma.clone() * &cos_beta * &px
3494 + (-(cos_alpha.clone()) * &sin_gamma + sin_alpha.clone() * &sin_beta * &cos_gamma)
3495 * &py
3496 + (sin_alpha.clone() * &sin_gamma + cos_alpha.clone() * &sin_beta * &cos_gamma) * &pz;
3497
3498 self.py = sin_gamma.clone() * &cos_beta * &px
3499 + (cos_alpha.clone() * &cos_gamma + sin_alpha.clone() * &sin_beta * &sin_gamma) * &py
3500 + (-sin_alpha.clone() * &cos_gamma + cos_alpha.clone() * &sin_beta * &sin_gamma) * &pz;
3501
3502 self.pz =
3503 -sin_beta * &px + cos_beta.clone() * &sin_alpha * &py + cos_alpha * &cos_beta * &pz;
3504 }
3505}
3506
3507impl<T: FloatLike> Rotatable for FourMomentum<F<T>> {
3508 fn rotate(&self, rotation: &Rotation) -> Self {
3509 Self {
3510 temporal: self.temporal.clone(),
3511 spatial: self.spatial.rotate(rotation),
3512 }
3513 }
3514}
3515
3516impl<T: FloatLike + EvaluationDomain> Rotatable for Polarization<Complex<F<T>>> {
3517 fn rotate(&self, rotation: &Rotation) -> Self {
3518 let rotated = match self.pol_type {
3519 PolType::Epsilon | PolType::EpsilonBar => rotation
3520 .lorentz_rotation
3521 .clone()
3522 .map_coeff(&|t| t.map(|f| F::from_ff64(f)))
3523 .evaluate(&self.tensor.data)
3524 .try_into_dense()
3525 .unwrap()
3526 .cast_structure(),
3527 PolType::U | PolType::UBar | PolType::V | PolType::VBar | PolType::Scalar => {
3528 self.tensor.clone()
3529 }
3530 };
3531
3532 Polarization {
3533 tensor: rotated,
3534 pol_type: self.pol_type,
3535 }
3536 }
3537}
3538
3539#[cfg(test)]
3540mod tests {
3541
3542 use core::f64;
3543
3544 use eyre::Context;
3545 use schemars::schema_for;
3546
3547 use crate::utils::F;
3548
3549 use super::*;
3550 use crate::utils::ApproxEq;
3551
3552 #[test]
3553 fn shared_polarized_density_matches_runtime_spinors() {
3554 use feynkit_amplitude::SpinSum;
3555 use spenso::{
3556 network::{
3557 ExecutionResult, Sequential, SmallestDegree,
3558 library::symbolic::ExplicitKey,
3559 parsing::{ParseSettings, StrictTensorFilter},
3560 },
3561 tensors::data::GetTensorData,
3562 };
3563 use spenso_hep_lib::{FUN_LIB, HepNet, hep_lib_su3};
3564
3565 let model = feynkit_model::Model::from_json(include_str!(
3566 "../../../feynkit-model/tests/fixtures/sm.json"
3567 ))
3568 .unwrap();
3569 let p = spenso::tensor_symbol!("polarized_runtime::p");
3570 let spin = spenso::tensor_symbol!("polarized_runtime::s");
3571 let indices = [
3572 symbol!("polarized_runtime::a"),
3573 symbol!("polarized_runtime::b"),
3574 ];
3575 for (momentum, axis) in [
3576 ([5.0, 0.0, 0.0, 4.0], [4.0 / 3.0, 0.0, 0.0, 5.0 / 3.0]),
3577 (
3578 [5.0, 12.0 / 5.0, 16.0 / 5.0, 0.0],
3579 [4.0 / 3.0, 1.0, 4.0 / 3.0, 0.0],
3580 ),
3581 ] {
3582 let runtime_p = FourMomentum::from_args(
3583 F(momentum[0]),
3584 F(momentum[1]),
3585 F(momentum[2]),
3586 F(momentum[3]),
3587 );
3588 for helicity in [Sign::Positive, Sign::Negative] {
3589 let orientation = if helicity == Sign::Positive {
3590 1.0
3591 } else {
3592 -1.0
3593 };
3594 let mut library = hep_lib_su3::<AbstractIndex>();
3595 for (name, components) in [(p, momentum), (spin, axis.map(|x| orientation * x))] {
3596 let key = ExplicitKey::from_iter([Minkowski {}.new_rep(4)], name, None);
3597 library.insert_explicit(key.map_canonical(|key| {
3598 DenseTensor::from_storage_data(components.to_vec(), key)
3599 .unwrap()
3600 .into()
3601 }));
3602 }
3603 for pdg in [15, -15] {
3604 let particle = model
3605 .particle_by_id(model.particle_id_by_pdg(pdg).unwrap())
3606 .unwrap();
3607 let density = SpinSum::new(particle, &model)
3608 .unwrap()
3609 .expression(
3610 &p.to_atom(),
3611 indices.map(|index| index.to_atom()),
3612 None,
3613 Some(&spin.to_atom()),
3614 )
3615 .unwrap()
3616 .replace(particle.symbolic_mass(&model).to_pattern())
3617 .with(Atom::num(3))
3618 .expand();
3619 let mut network = HepNet::<AbstractIndex>::try_from_view(
3620 density.as_view(),
3621 &library,
3622 &ParseSettings::default()
3623 .with_strict_tensor_filter(StrictTensorFilter::ContainsReps),
3624 )
3625 .unwrap();
3626 network
3627 .execute::<Sequential, SmallestDegree, _, _, _>(&library, &*FUN_LIB)
3628 .unwrap();
3629 let ExecutionResult::Val(result) = network.result_tensor(&library).unwrap()
3630 else {
3631 panic!("a polarized density must retain its two spinor indices");
3632 };
3633 let mut density_tensor = result.into_owned();
3634 density_tensor.evaluate_complex::<Atom>(&Default::default());
3635 let concrete = density_tensor.try_into_concrete().unwrap();
3636 assert_eq!(
3637 concrete.external_indices(),
3638 indices.map(AbstractIndex::from),
3639 "density axes must follow the spinor row and adjoint column"
3640 );
3641 let spinor = if pdg > 0 {
3642 runtime_p.u(helicity).unwrap()
3643 } else {
3644 runtime_p.v(helicity).unwrap()
3645 };
3646 let adjoint = spinor.bar();
3647 for row in 0..4 {
3648 for column in 0..4 {
3649 let actual = concrete.get_ref([row, column]).unwrap();
3650 let actual = match actual {
3651 spenso::algebra::complex::RealOrComplexRef::Real(value) => {
3652 Complex::new(*value, 0.0)
3653 }
3654 spenso::algebra::complex::RealOrComplexRef::Complex(value) => {
3655 *value
3656 }
3657 };
3658 let expected = spinor.tensor.data[row] * adjoint.tensor.data[column];
3659 assert!(
3660 (actual.re - expected.re.0).abs() < 1e-12,
3661 "PDG {pdg}, helicity {helicity:?}, ({row},{column}): {actual:?} vs {expected:?}"
3662 );
3663 assert!(
3664 (actual.im - expected.im.0).abs() < 1e-12,
3665 "PDG {pdg}, helicity {helicity:?}, ({row},{column}): {actual:?} vs {expected:?}"
3666 );
3667 }
3668 }
3669 }
3670 }
3671 }
3672 }
3673
3674 #[test]
3675 fn polarization() {
3676 let mom = FourMomentum::from_args(F(1.), F(1.), F(0.), F(0.));
3677
3678 let pol: Polarization<F<f64>> = Polarization::lorentz(mom.pol_one());
3679 println!("{}", pol)
3680
3681 }
3695
3696 #[test]
3697 fn serialization() {
3698 #[derive(Debug, Serialize, Deserialize, PartialEq)]
3699 struct HelicityToml {
3700 helicities: Vec<Helicity>,
3701 }
3702
3703 let hels = vec![
3704 Helicity::PLUS,
3705 Helicity::MINUS,
3706 Helicity::ZERO,
3707 Helicity::Summed,
3708 Helicity::SummedAveraged,
3709 ];
3710 let serialized = serde_json::to_string(&hels).unwrap();
3711 assert_eq!(serialized, r#"[1,-1,0,"summed","summed_averaged"]"#);
3712
3713 let deserialized: Vec<Helicity> =
3714 serde_json::from_str(r#"[1,"minus","0","summed","summed-averaged"]"#).unwrap();
3715 assert_eq!(deserialized, hels);
3716
3717 let toml_value = toml::from_str::<HelicityToml>(
3718 r#"
3719helicities = [1, "minus", "zero", "summed", "summed_averaged"]
3720"#,
3721 )
3722 .unwrap();
3723 assert_eq!(toml_value.helicities, hels);
3724
3725 let schema = serde_json::to_value(schema_for!(Helicity)).unwrap();
3726 let allowed_strings = &schema["enum"];
3727 assert!(allowed_strings.is_null());
3728 assert!(
3729 schema["oneOf"][0]["enum"]
3730 .as_array()
3731 .unwrap()
3732 .contains(&(-1).into())
3733 );
3734 assert!(
3735 schema["oneOf"][1]["enum"]
3736 .as_array()
3737 .unwrap()
3738 .contains(&"summed_averaged".into())
3739 );
3740 }
3741
3742 #[test]
3743 fn eps() {
3744 let mom = FourMomentum::from_args(
3745 F(156.2565490076973),
3746 F(-108.59017233120495),
3747 F(-100.2097685717689),
3748 F(50.81619686346704),
3749 );
3750
3751 let pol = mom.eps_pol(SignOrZero::Plus).unwrap();
3752 println!("{}", pol);
3753
3754 let mom = FourMomentum::from_args(
3755 F(441.7831721921727),
3756 F(237.7632083614734),
3757 F(368.76330416225863),
3758 F(-51.523329523343534),
3759 );
3760
3761 let pol = mom.eps_pol(SignOrZero::Plus).unwrap();
3762 println!("{}", pol);
3763
3764 let mom = FourMomentum::from_args(F(485.0355), F(0.), F(0.), F(485.0355));
3765
3766 let pol = mom.eps_pol(SignOrZero::Plus).unwrap();
3767
3768 println!("{}", pol);
3769
3770 println!("pt{}", mom.pt());
3771
3772 let mom = FourMomentum::from_args(F(485.0355), F(-107.6044), F(-431.5174), F(193.5805));
3773
3774 let pol = mom.eps_pol(SignOrZero::Plus).unwrap().bar();
3775
3776 println!("{}", pol);
3783 println!("pt{}", mom.pt());
3784 }
3785
3786 #[test]
3787 fn spinors_degenerate() {
3788 let mom = FourMomentum::from_args(F(2.), F(0.), F(0.), F(-2.));
3789
3790 assert_eq!(
3791 [Complex::new_zero(), Complex::new_re(F(-1.))],
3792 mom.xi(Sign::Positive)
3793 );
3794
3795 assert_eq!(
3796 [Complex::new_re(F(1.)), Complex::new_re(F(0.))],
3797 mom.xi(Sign::Negative)
3798 );
3799
3800 let u_p = mom.u(Sign::Positive).unwrap();
3801 let u_p_target: Polarization<Complex<F<_>>> =
3802 Polarization::bispinor_u([F(0.), F(0.), F(0.), F(-2.)]).cast();
3803
3804 u_p.approx_eq_res(&u_p_target, &F(0.001))
3805 .wrap_err("u+((2,0,0,-2)) does not match target: (0,0,0,-2)")
3806 .unwrap();
3807
3808 let mut u_p_bar_target: Polarization<Complex<F<_>>> =
3809 Polarization::bispinor_u([F(0.), F(-2.), F(0.), F(0.)]).cast();
3810
3811 u_p_bar_target.pol_type = PolType::UBar;
3812
3813 u_p.bar()
3814 .approx_eq_res(&u_p_bar_target, &F(0.001))
3815 .wrap_err("u+bar((2,0,0,-2)) does not match target: (0,-2,0,0)")
3816 .unwrap();
3817
3818 let u_m = mom.u(Sign::Negative).unwrap();
3819 let u_m_target: Polarization<Complex<F<_>>> =
3820 Polarization::bispinor_u([F(2.), F(0.), F(0.), F(0.)]).cast();
3821
3822 u_m.approx_eq_res(&u_m_target, &F(0.001))
3823 .wrap_err("u-((2,0,0,-2)) does not match target: (2,0,0,0)")
3824 .unwrap();
3825
3826 let mut u_m_bar_target: Polarization<Complex<F<_>>> =
3827 Polarization::bispinor_u([F(0.), F(0.), F(2.), F(0.)]).cast();
3828
3829 u_m_bar_target.pol_type = PolType::UBar;
3830
3831 u_m.bar()
3832 .approx_eq_res(&u_m_bar_target, &F(0.001))
3833 .wrap_err("u-bar((2,0,0,-2)) does not match target: (0,0,2,0)")
3834 .unwrap();
3835
3836 let v_p = mom.v(Sign::Positive).unwrap();
3837 let v_p_target: Polarization<Complex<F<_>>> =
3838 Polarization::bispinor_v([F(-2.), F(0.), F(0.), F(0.)]).cast();
3839
3840 v_p.approx_eq_res(&v_p_target, &F(0.001))
3841 .wrap_err("v+((2,0,0,-2)) does not match target: (-2,0,0,0)")
3842 .unwrap();
3843
3844 let mut v_p_bar_target: Polarization<Complex<F<_>>> =
3845 Polarization::bispinor_v([F(0.), F(0.), F(-2.), F(0.)]).cast();
3846
3847 v_p_bar_target.pol_type = PolType::VBar;
3848
3849 v_p.bar()
3850 .approx_eq_res(&v_p_bar_target, &F(0.001))
3851 .wrap_err("v+bar((2,0,0,-2)) does not match target: (0,0,-2,0)")
3852 .unwrap();
3853
3854 let v_m = mom.v(Sign::Negative).unwrap();
3855 let v_m_target: Polarization<Complex<F<_>>> =
3856 Polarization::bispinor_v([F(0.), F(0.), F(0.), F(2.)]).cast();
3857
3858 v_m.approx_eq_res(&v_m_target, &F(0.001))
3859 .wrap_err("v-((2,0,0,-2)) does not match target: (0,0,0,2)")
3860 .unwrap();
3861
3862 let mut v_m_bar_target: Polarization<Complex<F<_>>> =
3863 Polarization::bispinor_v([F(0.), F(2.), F(0.), F(0.)]).cast();
3864
3865 v_m_bar_target.pol_type = PolType::VBar;
3866
3867 v_m.bar()
3868 .approx_eq_res(&v_m_bar_target, &F(0.001))
3869 .wrap_err("v-bar((2,0,0,-2)) does not match target: (0,2,0,0)")
3870 .unwrap();
3871 }
3872
3873 #[test]
3874 fn spinors() {
3875 let mom = FourMomentum::from_args(F(4.), F(0.), F(4.), F(0.));
3876
3877 assert!(
3878 Complex::approx_eq_slice(
3879 &[
3880 Complex::new_re(F(f64::consts::FRAC_1_SQRT_2)),
3881 Complex::new_im(F(f64::consts::FRAC_1_SQRT_2)),
3882 ],
3883 &mom.xi(Sign::Positive),
3884 &F(0.001),
3885 ),
3886 "xi+((4,0,4,0)) does not match target: (1/sqrt(2),i/sqrt(2))"
3887 );
3888
3889 assert!(
3890 Complex::approx_eq_slice(
3891 &[
3892 Complex::new_im(F(f64::consts::FRAC_1_SQRT_2)),
3893 Complex::new_re(F(f64::consts::FRAC_1_SQRT_2)),
3894 ],
3895 &mom.xi(Sign::Negative),
3896 &F(0.001),
3897 ),
3898 "xi-((4,0,4,0)) does not match target: (i/sqrt(2),1/sqrt(2))"
3899 );
3900
3901 let zero: Complex<_> = F(0.).into();
3902 let u_p = mom.u(Sign::Positive).unwrap();
3903 let u_p_target: Polarization<Complex<F<_>>> =
3904 Polarization::bispinor_u([zero, zero, Complex::new_re(F(2.)), Complex::new_im(F(2.))])
3905 .cast();
3906
3907 u_p.approx_eq_res(&u_p_target, &F(0.001))
3908 .wrap_err("u+((4,0,4,0)) does not match target: (0,0,2,i2)")
3909 .unwrap();
3910
3911 let mut u_p_bar_target: Polarization<Complex<F<_>>> =
3912 Polarization::bispinor_u([Complex::new_re(F(2.)), Complex::new_im(-F(2.)), zero, zero])
3913 .cast();
3914
3915 u_p_bar_target.pol_type = PolType::UBar;
3916
3917 u_p.bar()
3918 .approx_eq_res(&u_p_bar_target, &F(0.001))
3919 .wrap_err("u+bar((4,0,4,0)) does not match target: (2,-2i,0,0)")
3920 .unwrap();
3921
3922 let u_m = mom.u(Sign::Negative).unwrap();
3923 let u_m_target: Polarization<Complex<F<_>>> =
3924 Polarization::bispinor_u([Complex::new_im(F(2.)), Complex::new_re(F(2.)), zero, zero])
3925 .cast();
3926
3927 u_m.approx_eq_res(&u_m_target, &F(0.001))
3928 .wrap_err("u-((4,0,4,0)) does not match target: (2i,2,0,0)")
3929 .unwrap();
3930
3931 let mut u_m_bar_target: Polarization<Complex<F<_>>> =
3932 Polarization::bispinor_u([zero, zero, Complex::new_im(-F(2.)), Complex::new_re(F(2.))])
3933 .cast();
3934
3935 u_m_bar_target.pol_type = PolType::UBar;
3936
3937 u_m.bar()
3938 .approx_eq_res(&u_m_bar_target, &F(0.001))
3939 .wrap_err("u-bar((4,0,4,0)) does not match target: (0,0,-2i,2)")
3940 .unwrap();
3941
3942 let v_p = mom.v(Sign::Positive).unwrap();
3943 let v_p_target: Polarization<Complex<F<_>>> = Polarization::bispinor_v([
3944 Complex::new_im(-F(2.)),
3945 Complex::new_re(-F(2.)),
3946 zero,
3947 zero,
3948 ])
3949 .cast();
3950
3951 v_p.approx_eq_res(&v_p_target, &F(0.001))
3952 .wrap_err("v+((4,0,4,0)) does not match target: (-2i,-2,0,0)")
3953 .unwrap();
3954
3955 let mut v_p_bar_target: Polarization<Complex<F<_>>> =
3956 Polarization::bispinor_v([zero, zero, Complex::new_im(F(2.)), Complex::new_re(F(-2.))])
3957 .cast();
3958
3959 v_p_bar_target.pol_type = PolType::VBar;
3960
3961 v_p.bar()
3962 .approx_eq_res(&v_p_bar_target, &F(0.001))
3963 .wrap_err("v+bar((4,0,4,0)) does not match target: (0,0,2i,-2)")
3964 .unwrap();
3965
3966 let v_m = mom.v(Sign::Negative).unwrap();
3967 let v_m_target: Polarization<Complex<F<_>>> = Polarization::bispinor_v([
3968 zero,
3969 zero,
3970 Complex::new_re(-F(2.)),
3971 Complex::new_im(-F(2.)),
3972 ])
3973 .cast();
3974
3975 v_m.approx_eq_res(&v_m_target, &F(0.001))
3976 .wrap_err("v-((4,0,4,0)) does not match target: (0,0,-2,-2i)")
3977 .unwrap();
3978
3979 let mut v_m_bar_target: Polarization<Complex<F<_>>> =
3980 Polarization::bispinor_v([Complex::new_re(-F(2.)), Complex::new_im(F(2.)), zero, zero])
3981 .cast();
3982
3983 v_m_bar_target.pol_type = PolType::VBar;
3984
3985 v_m.bar()
3986 .approx_eq_res(&v_m_bar_target, &F(0.001))
3987 .wrap_err("v-bar((4,0,4,0)) does not match target: (-2,2i,0,0)")
3988 .unwrap();
3989 }
3990
3991 #[test]
3992 fn vectors_degenerate() {
3993 let mom = FourMomentum::from_args(F(2.), F(0.), F(0.), F(-2.));
3994
3995 assert!(
3996 F::approx_eq_slice(&mom.pol_one(), &[0., 1., 0., 0.].map(F), &F(0.001)),
3997 "pol_one((2,0,0,-2)) does not match target: (0,1,0,0)"
3998 );
3999
4000 assert!(
4001 F::approx_eq_slice(&mom.pol_two(), &[0., 0., -1., 0.].map(F), &F(0.001)),
4002 "pol_two((2,0,0,-2)) does not match target: (0,0,-1,0)"
4003 );
4004
4005 let e_p = mom.eps_pol(SignOrZero::Plus).unwrap();
4006
4007 let zero = F(0.).into();
4008 let e_p_target = Polarization::lorentz([
4009 zero,
4010 Complex::new_re(F(-f64::consts::FRAC_1_SQRT_2)),
4011 Complex::new_im(F(f64::consts::FRAC_1_SQRT_2)),
4012 zero,
4013 ]);
4014
4015 let mut e_p_bar_target = Polarization::lorentz([
4016 zero,
4017 Complex::new_re(F(-f64::consts::FRAC_1_SQRT_2)),
4018 Complex::new_im(F(-f64::consts::FRAC_1_SQRT_2)),
4019 zero,
4020 ]);
4021
4022 e_p_bar_target.pol_type = PolType::EpsilonBar;
4023
4024 e_p.approx_eq_res(&e_p_target, &F(0.0001))
4025 .wrap_err("e+((2,0,0,-2)) does not match target: (0,-1/sqrt(2),i/sqrt(2),0)")
4026 .unwrap();
4027
4028 e_p.bar()
4029 .approx_eq_res(&e_p_bar_target, &F(0.0001))
4030 .wrap_err("e+bar((2,0,0,-2)) does not match target: (0,-1/sqrt(2),-i/sqrt(2),0)")
4031 .unwrap();
4032
4033 let e_m = mom.eps_pol(SignOrZero::Minus).unwrap();
4034
4035 let e_m_target = Polarization::lorentz([
4036 zero,
4037 Complex::new_re(F(f64::consts::FRAC_1_SQRT_2)),
4038 Complex::new_im(F(f64::consts::FRAC_1_SQRT_2)),
4039 zero,
4040 ]);
4041
4042 let mut e_m_bar_target = Polarization::lorentz([
4043 zero,
4044 Complex::new_re(F(f64::consts::FRAC_1_SQRT_2)),
4045 Complex::new_im(F(-f64::consts::FRAC_1_SQRT_2)),
4046 zero,
4047 ]);
4048
4049 e_m_bar_target.pol_type = PolType::EpsilonBar;
4050
4051 e_m.approx_eq_res(&e_m_target, &F(0.0001))
4052 .wrap_err("e-((2,0,0,-2)) does not match target: (0,1/sqrt(2),i/sqrt(2),0)")
4053 .unwrap();
4054
4055 e_m.bar()
4056 .approx_eq_res(&e_m_bar_target, &F(0.0001))
4057 .wrap_err("e-bar((2,0,0,-2)) does not match target: (0,1/sqrt(2),-i/sqrt(2),0)")
4058 .unwrap();
4059 }
4060
4061 #[test]
4062 fn vectors() {
4063 let mom = FourMomentum::from_args(F(2.), F(0.), F(0.), F(-2.));
4064
4065 assert!(
4066 F::approx_eq_slice(&mom.pol_one(), &[0., 1., 0., 0.].map(F), &F(0.001)),
4067 "pol_one((2,0,0,-2)) does not match target: (0,1,0,0)"
4068 );
4069
4070 assert!(
4071 F::approx_eq_slice(&mom.pol_two(), &[0., 0., -1., 0.].map(F), &F(0.001)),
4072 "pol_two((2,0,0,-2)) does not match target: (0,0,-1,0)"
4073 );
4074
4075 let e_p = mom.eps_pol(SignOrZero::Plus).unwrap();
4076
4077 let zero = F(0.).into();
4078 let e_p_target = Polarization::lorentz([
4079 zero,
4080 Complex::new_re(F(-f64::consts::FRAC_1_SQRT_2)),
4081 Complex::new_im(F(f64::consts::FRAC_1_SQRT_2)),
4082 zero,
4083 ]);
4084
4085 let mut e_p_bar_target = Polarization::lorentz([
4086 zero,
4087 Complex::new_re(F(-f64::consts::FRAC_1_SQRT_2)),
4088 Complex::new_im(F(-f64::consts::FRAC_1_SQRT_2)),
4089 zero,
4090 ]);
4091
4092 e_p_bar_target.pol_type = PolType::EpsilonBar;
4093
4094 e_p.approx_eq_res(&e_p_target, &F(0.0001))
4095 .wrap_err("e+((2,0,0,-2)) does not match target: (0,-1/sqrt(2),i/sqrt(2),0)")
4096 .unwrap();
4097
4098 e_p.bar()
4099 .approx_eq_res(&e_p_bar_target, &F(0.0001))
4100 .wrap_err("e+bar((2,0,0,-2)) does not match target: (0,-1/sqrt(2),-i/sqrt(2),0)")
4101 .unwrap();
4102
4103 let e_m = mom.eps_pol(SignOrZero::Minus).unwrap();
4104
4105 let e_m_target = Polarization::lorentz([
4106 zero,
4107 Complex::new_re(F(f64::consts::FRAC_1_SQRT_2)),
4108 Complex::new_im(F(f64::consts::FRAC_1_SQRT_2)),
4109 zero,
4110 ]);
4111
4112 let mut e_m_bar_target = Polarization::lorentz([
4113 zero,
4114 Complex::new_re(F(f64::consts::FRAC_1_SQRT_2)),
4115 Complex::new_im(F(-f64::consts::FRAC_1_SQRT_2)),
4116 zero,
4117 ]);
4118
4119 e_m_bar_target.pol_type = PolType::EpsilonBar;
4120
4121 e_m.approx_eq_res(&e_m_target, &F(0.0001))
4122 .wrap_err("e-((2,0,0,-2)) does not match target: (0,1/sqrt(2),i/sqrt(2),0)")
4123 .unwrap();
4124
4125 e_m.bar()
4126 .approx_eq_res(&e_m_bar_target, &F(0.0001))
4127 .wrap_err("e-bar((2,0,0,-2)) does not match target: (0,1/sqrt(2),-i/sqrt(2),0)")
4128 .unwrap();
4129 }
4130
4131 #[test]
4132 fn axis_angle_quarter_turn_matches_matrix_inverse_and_lorentz_tensor() {
4133 let original = FourMomentum::from_args(F(11.0), F(3.0), F(-5.0), F(7.0));
4134 let expected =
4135 FourMomentum::from_args(F(11.0), F(79.0 / 9.0), F(11.0 / 9.0), F(-19.0 / 9.0));
4136 for scale in [1.0, 1.0e-300, 1.0e300] {
4137 let axis = [scale, 2.0 * scale, 2.0 * scale];
4138 let rotation = Rotation::new(RotationMethod::AxisAngle {
4139 axis,
4140 cos_theta: 0.0,
4141 });
4142 let actual = original.rotate(&rotation);
4143 actual.approx_eq_res(&expected, &F(1.0e-13)).unwrap();
4144 rotation
4145 .inverse_rotate_four(&actual)
4146 .approx_eq_res(&original, &F(1.0e-13))
4147 .unwrap();
4148 let polarization =
4149 Polarization::lorentz(<[F<f64>; 4]>::from(original).map(Complex::new_re));
4150 actual
4151 .approx_eq_res(&polarization.rotate(&rotation), &F(1.0e-13))
4152 .unwrap();
4153 assert_eq!(
4154 rotation.setting(),
4155 RotationSetting::AxisAngle {
4156 axis,
4157 cos_theta: 0.0
4158 }
4159 );
4160 }
4161 }
4162
4163 #[test]
4164 fn axis_angle_transports_external_vector_and_spinor_at_rest() {
4165 let rest = FourMomentum::from_args(F(2.0), F(0.0), F(0.0), F(0.0));
4166 for (axis, cos_theta) in [
4167 ([1.0e-300, 2.0e-300, 2.0e-300], 0.6),
4168 ([1.0e300, 2.0e300, 2.0e300], -1.0),
4169 ([0.0, 0.0, -1.0], 0.0),
4170 ([1.0, 0.0, 0.0], 1.0),
4171 ] {
4172 let method = RotationMethod::AxisAngle { axis, cos_theta };
4173 let mut rotation = Rotation::new(method);
4174 for kind in [PolType::Epsilon, PolType::U] {
4175 let original = rest
4176 .external_polarization(kind, SignOrZero::Plus, &[])
4177 .unwrap()
4178 .unwrap();
4179 let expected = if kind == PolType::U {
4180 let mut input = original.tensor.data.clone();
4181 input.push(Complex::new(F(0.0), F(1.0)));
4182 Polarization {
4183 tensor: rotation
4184 .bispinor_rotation
4185 .evaluate(&input)
4186 .try_into_dense()
4187 .unwrap()
4188 .cast_structure(),
4189 pol_type: kind,
4190 }
4191 } else {
4192 original.rotate(&rotation)
4193 };
4194 rest.external_polarization(kind, SignOrZero::Plus, &[method])
4195 .unwrap()
4196 .unwrap()
4197 .approx_eq_res(&expected, &F(1.0e-13))
4198 .unwrap();
4199 }
4200 }
4201 }
4202
4203 #[test]
4204 fn axis_angle_rotation_preserves_its_axis_at_native_precision_and_rotates_hyperdual_coefficients()
4205 {
4206 use crate::utils::{ArbPrec, hyperdual_utils::simple_n_deriv_shape};
4207 let one = <F<ArbPrec> as Default>::default().one();
4208 let tolerance = one.from_i64(2).powi(-900);
4209 let rotation = Rotation::new(RotationMethod::AxisAngle {
4210 axis: [1.0, 2.0, 2.0],
4211 cos_theta: 0.0,
4212 });
4213 let axis = ThreeMomentum::from([one.clone(), one.from_i64(2), one.from_i64(2)]);
4214 let rotated = axis.rotate(&rotation);
4215 for (actual, expected) in rotated.into_iter().zip(&axis) {
4216 assert!((actual - expected).norm() < tolerance);
4217 }
4218 let point = ThreeMomentum::from([
4219 &one / one.from_i64(7),
4220 -&one / one.from_i64(5),
4221 &one / one.from_i64(11),
4222 ]);
4223 let inverse = rotation.inverse_rotate_three(&point.rotate(&rotation));
4224 for (actual, expected) in inverse.into_iter().zip(&point) {
4225 assert!((actual - expected).norm() < tolerance);
4226 }
4227 let shape = simple_n_deriv_shape(2);
4228 let jet = ThreeMomentum {
4229 px: HyperDual::from_values(
4230 shape.clone(),
4231 [3, 1, 0].map(|value| one.from_i64(value)).to_vec(),
4232 ),
4233 py: HyperDual::from_values(
4234 shape.clone(),
4235 [-5, 0, 1].map(|value| one.from_i64(value)).to_vec(),
4236 ),
4237 pz: HyperDual::from_values(shape, [7, 0, 0].map(|value| one.from_i64(value)).to_vec()),
4238 };
4239 let rotated = jet.rotate(&rotation);
4240 for (component, expected) in [rotated.px, rotated.py, rotated.pz].into_iter().zip([
4241 [79, 1, -4],
4242 [11, 8, 4],
4243 [-19, -4, 7],
4244 ]) {
4245 for (actual, numerator) in component.values.into_iter().zip(expected) {
4246 assert!((actual - one.from_i64(numerator) / one.from_i64(9)).norm() < tolerance);
4247 }
4248 }
4249 }
4250
4251 #[test]
4252 fn axis_angle_spinor_tensor_intertwines_the_native_spatial_rotation() {
4253 let zero = Complex::new(0.0, 0.0);
4254 let one = Complex::new(1.0, 0.0);
4255 let imaginary = Complex::new(0.0, 1.0);
4256 let pauli = [
4257 [[zero, one], [one, zero]],
4258 [[zero, -imaginary], [imaginary, zero]],
4259 [[one, zero], [zero, -one]],
4260 ];
4261 for (axis, cos_theta) in [
4262 ([1.0, 2.0, 2.0], 0.0),
4263 ([1.0, 2.0, 2.0], 0.6),
4264 ([0.0, 0.0, 1.0], 0.0),
4265 ([1.0, 0.0, 0.0], -1.0),
4266 ] {
4267 let mut rotation = Rotation::new(RotationMethod::AxisAngle { axis, cos_theta });
4268 let columns: [[Complex<f64>; 4]; 4] = std::array::from_fn(|column| {
4269 let mut input = std::array::from_fn::<_, 4, _>(|index| {
4270 Complex::new_re(F(if index == column { 1.0 } else { 0.0 }))
4271 })
4272 .to_vec();
4273 input.push(Complex::new(F(0.0), F(1.0)));
4275 let output = rotation
4276 .bispinor_rotation
4277 .evaluate(&input)
4278 .try_into_dense()
4279 .unwrap();
4280 std::array::from_fn(|row| {
4281 Complex::new(output.data[row].re.0, output.data[row].im.0)
4282 })
4283 });
4284 let spinor: [[Complex<f64>; 4]; 4] =
4285 std::array::from_fn(|row| std::array::from_fn(|column| columns[column][row]));
4286 for row in 0..4 {
4287 for column in 0..4 {
4288 let unitary = (0..4)
4289 .map(|inner| spinor[inner][row].conj() * spinor[inner][column])
4290 .fold(zero, |sum, term| sum + term);
4291 let difference = unitary - if row == column { one } else { zero };
4292 assert!(difference.re.hypot(difference.im) < 1.0e-13);
4293 if row < 2 && column < 2 {
4294 assert_eq!(spinor[row][column], spinor[row + 2][column + 2]);
4295 assert_eq!(spinor[row][column + 2], zero);
4296 assert_eq!(spinor[row + 2][column], zero);
4297 }
4298 }
4299 }
4300 for (direction, sigma) in pauli.iter().enumerate() {
4301 let basis = ThreeMomentum::from(std::array::from_fn(|index| {
4302 F(if index == direction { 1.0 } else { 0.0 })
4303 }));
4304 let rotated: [F<f64>; 3] = basis.rotate(&rotation).into();
4305 for row in 0..2 {
4306 for column in 0..2 {
4307 let mut transformed = zero;
4308 for left in 0..2 {
4309 for right in 0..2 {
4310 transformed += spinor[row][left]
4311 * sigma[left][right]
4312 * spinor[column][right].conj();
4313 }
4314 }
4315 let expected = (0..3)
4316 .map(|component| pauli[component][row][column] * rotated[component].0)
4317 .fold(zero, |sum, term| sum + term);
4318 let difference = transformed - expected;
4319 assert!(
4320 difference.re.hypot(difference.im) < 1.0e-13,
4321 "axis={axis:?}, cosine={cos_theta}, Pauli direction={direction}, row={row}, column={column}"
4322 );
4323 }
4324 }
4325 }
4326 }
4327 }
4328
4329 #[test]
4330 fn rotations() {
4331 let mom = FourMomentum::from_args(F(2.), F(3.), F(1.), F(2.));
4332
4333 let momc: [F<f64>; 4] = mom.into();
4334 let e = Polarization::lorentz(momc.map(Complex::new_re));
4335 let u = mom.u(Sign::Negative).unwrap();
4336
4337 let rot: Rotation = RotationMethod::EulerAngles(std::f64::consts::PI / 2., 0., 0.).into();
4338 let rotx = RotationMethod::Pi2X.into();
4339
4340 let rotye: Rotation = RotationMethod::EulerAngles(0., std::f64::consts::PI / 2., 0.).into();
4341 let roty = RotationMethod::Pi2Y.into();
4342
4343 let rotze: Rotation = RotationMethod::EulerAngles(0., 0., std::f64::consts::PI / 2.).into();
4344 let rotz = RotationMethod::Pi2Z.into();
4345
4346 let rotid = RotationMethod::Identity.into();
4347 let mom_rot = mom.rotate(&rot);
4356 let mom_id = mom.rotate(&rotid);
4357 let other_mom_rot = mom.rotate(&rotx);
4358 let mom_rotye = mom.rotate(&rotye);
4359 let mom_roty = mom.rotate(&roty);
4360 let mom_rotze = mom.rotate(&rotze);
4361 let mom_rotz = mom.rotate(&rotz);
4362
4363 println!("id:\t{}", mom_id);
4364 mom_id
4365 .approx_eq_res(&mom, &F(0.001))
4366 .wrap_err("mom is not identical to mom transformed with identity")
4367 .unwrap();
4368 println!("orig:\t{}", mom);
4369
4370 println!("rotxe:\t{}", mom_rot);
4371 println!("pi2x:\t{}", other_mom_rot);
4372 mom_rot.approx_eq_res(&other_mom_rot, &F(0.001)).unwrap();
4373
4374 println!("rotye:\t{}", mom_rotye);
4375 println!("pi2y:\t{}", mom_roty);
4376
4377 mom_rotye.approx_eq_res(&mom_roty, &F(0.001)).unwrap();
4378 println!("rotze:\t{}", mom_rotze);
4379 println!("pi2z:\t{}", mom_rotz);
4380 mom_rotze.approx_eq_res(&mom_rotz, &F(0.001)).unwrap();
4381
4382 let e_rot = e.rotate(&rot);
4383 println!("rotxe:{}", e_rot);
4384 mom_rot.approx_eq_res(&e_rot, &F(0.001)).unwrap();
4385
4386 let e_id = e.rotate(&rotid);
4387 mom_id.approx_eq_res(&e_id, &F(0.001)).unwrap();
4388 let e_rotye = e.rotate(&rotye);
4389
4390 println!("rotye:{}", e_rotye);
4391 mom_rotye.approx_eq_res(&e_rotye, &F(0.001)).unwrap();
4392 let e_roty = e.rotate(&roty);
4393 mom_roty.approx_eq_res(&e_roty, &F(0.001)).unwrap();
4394 let e_rotze = e.rotate(&rotze);
4395 mom_rotze.approx_eq_res(&e_rotze, &F(0.001)).unwrap();
4396 let e_rotz = e.rotate(&rotz);
4397 mom_rotz.approx_eq_res(&e_rotz, &F(0.001)).unwrap();
4398 let u_rot = u.rotate(&rot);
4399 let u_id = u.rotate(&rotid);
4400
4401 let other_e_rot = e.rotate(&rotx);
4402
4403 let other_u_rot = u.rotate(&rotx);
4404
4405 println!("id:{}", e_id);
4406 println!("orig:{}", e);
4407 println!("euler:{}", e_rot);
4408 println!("Pi2X:{}", other_e_rot);
4409 println!("rotye:{}", e_rotye);
4410 println!("pi2y:{}", e_roty);
4411 println!("rotze:{}", e_rotze);
4412 println!("pi2z:{}", e_rotz);
4413
4414 println!("id:{}", u_id);
4415 println!("orig:{}", u);
4416 println!("euler:{}", u_rot);
4417 println!("Pi2X {}", other_u_rot);
4418 }
4419
4420 }