1use std::array;
6use std::{fmt, str::FromStr};
7
8use numerica::domains::float::Complex;
9use thiserror::Error;
10
11use crate::{Axis, FourMomentum, Helicity, KinematicScalar, Rotation, Sign, ThreeMomentum};
12
13#[cfg(test)]
14mod tests;
15
16#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum WavefunctionKind {
19 Scalar,
20 Epsilon,
21 EpsilonBar,
22 U,
23 UBar,
24 V,
25 VBar,
26}
27
28impl WavefunctionKind {
29 pub const fn bar(self) -> Self {
30 match self {
31 Self::Scalar => Self::Scalar,
32 Self::Epsilon => Self::EpsilonBar,
33 Self::EpsilonBar => Self::Epsilon,
34 Self::U => Self::UBar,
35 Self::UBar => Self::U,
36 Self::V => Self::VBar,
37 Self::VBar => Self::V,
38 }
39 }
40
41 pub const fn is_spinor(self) -> bool {
42 matches!(self, Self::U | Self::UBar | Self::V | Self::VBar)
43 }
44
45 pub const fn component_count(self) -> usize {
46 if matches!(self, Self::Scalar) { 1 } else { 4 }
47 }
48}
49
50impl fmt::Display for WavefunctionKind {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 f.write_str(match self {
53 Self::Scalar => "scalar",
54 Self::Epsilon => "epsilon",
55 Self::EpsilonBar => "epsilon_bar",
56 Self::U => "u",
57 Self::UBar => "u_bar",
58 Self::V => "v",
59 Self::VBar => "v_bar",
60 })
61 }
62}
63
64impl FromStr for WavefunctionKind {
65 type Err = WavefunctionError;
66 fn from_str(value: &str) -> Result<Self, Self::Err> {
67 match value {
68 "scalar" => Ok(Self::Scalar),
69 "epsilon" => Ok(Self::Epsilon),
70 "epsilon_bar" => Ok(Self::EpsilonBar),
71 "u" => Ok(Self::U),
72 "u_bar" => Ok(Self::UBar),
73 "v" => Ok(Self::V),
74 "v_bar" => Ok(Self::VBar),
75 _ => Err(WavefunctionError::UnknownKind(value.into())),
76 }
77 }
78}
79
80#[derive(Clone, Debug, Error, Eq, PartialEq)]
81pub enum WavefunctionError {
82 #[error("unknown wavefunction kind '{0}'")]
83 UnknownKind(String),
84 #[error("{kind} requires {expected} components, received {actual}")]
85 ComponentCount {
86 kind: WavefunctionKind,
87 expected: usize,
88 actual: usize,
89 },
90 #[error("external momentum or wavefunction components are not finite")]
91 NonFinite,
92 #[error("{0} does not admit the requested helicity")]
93 Helicity(WavefunctionKind),
94 #[error("longitudinal polarization requires positive mass squared")]
95 UndefinedLongitudinal,
96}
97
98#[derive(Clone, Debug, PartialEq)]
100pub struct Wavefunction<T: KinematicScalar> {
101 kind: WavefunctionKind,
102 components: Vec<Complex<T>>,
103}
104
105impl<T: KinematicScalar> Wavefunction<T> {
106 pub fn from_components(
108 kind: WavefunctionKind,
109 components: Vec<Complex<T>>,
110 ) -> Result<Self, WavefunctionError> {
111 if components.len() != kind.component_count() {
112 return Err(WavefunctionError::ComponentCount {
113 kind,
114 expected: kind.component_count(),
115 actual: components.len(),
116 });
117 }
118 if components
119 .iter()
120 .any(|c| !c.re.is_finite() || !c.im.is_finite())
121 {
122 return Err(WavefunctionError::NonFinite);
123 }
124 Ok(Self { kind, components })
125 }
126
127 pub fn kind(&self) -> WavefunctionKind {
128 self.kind
129 }
130 pub fn components(&self) -> &[Complex<T>] {
131 &self.components
132 }
133 pub fn into_components(self) -> Vec<Complex<T>> {
134 self.components
135 }
136
137 pub fn bar(&self) -> Self {
139 let mut components = self
140 .components
141 .iter()
142 .map(Complex::conj)
143 .collect::<Vec<_>>();
144 if self.kind.is_spinor() {
145 components.swap(0, 2);
146 components.swap(1, 3);
147 }
148 Self {
149 kind: self.kind.bar(),
150 components,
151 }
152 }
153
154 pub fn rotate(&self, rotation: &Rotation<T>) -> Result<Self, WavefunctionError> {
162 let mut components = self.components.clone();
163 match self.kind {
164 WavefunctionKind::Scalar => {}
165 WavefunctionKind::Epsilon | WavefunctionKind::EpsilonBar => {
166 let part = |part: fn(&Complex<T>) -> T| {
167 rotation.rotate_three(&ThreeMomentum::new(
168 part(&components[1]),
169 part(&components[2]),
170 part(&components[3]),
171 ))
172 };
173 let (re, im) = (part(|c| c.re.clone()), part(|c| c.im.clone()));
174 components[1] = Complex::new(re.px, im.px);
175 components[2] = Complex::new(re.py, im.py);
176 components[3] = Complex::new(re.pz, im.pz);
177 }
178 kind => {
179 let mut matrix = spin_matrix(rotation, &components[0].re);
180 if !matches!(kind, WavefunctionKind::U | WavefunctionKind::V) {
181 matrix = matrix.map(|row| row.map(|entry| entry.conj()));
182 }
183 for block in components.as_chunks_mut::<2>().0 {
184 let [a, b] = [block[0].clone(), block[1].clone()];
185 block[0] = matrix[0][0].clone() * a.clone() + matrix[0][1].clone() * b.clone();
186 block[1] = matrix[1][0].clone() * a + matrix[1][1].clone() * b;
187 }
188 }
189 }
190 Self::from_components(self.kind, components)
191 }
192}
193
194type SpinMatrix<T> = [[Complex<T>; 2]; 2];
195
196fn axis_spin_matrix<T: KinematicScalar>(axis: Axis, cos: T, sin: T) -> SpinMatrix<T> {
198 let zero = cos.zero();
199 let c = |re: &T, im: &T| Complex::new(re.clone(), im.clone());
200 let minus_sin = -sin.clone();
201 match axis {
202 Axis::X => [
203 [c(&cos, &zero), c(&zero, &minus_sin)],
204 [c(&zero, &minus_sin), c(&cos, &zero)],
205 ],
206 Axis::Y => [
207 [c(&cos, &zero), c(&minus_sin, &zero)],
208 [c(&sin, &zero), c(&cos, &zero)],
209 ],
210 Axis::Z => [
211 [c(&cos, &minus_sin), c(&zero, &zero)],
212 [c(&zero, &zero), c(&cos, &sin)],
213 ],
214 }
215}
216
217fn spin_matrix_product<T: KinematicScalar>(a: &SpinMatrix<T>, b: &SpinMatrix<T>) -> SpinMatrix<T> {
218 array::from_fn(|i| {
219 array::from_fn(|j| a[i][0].clone() * b[0][j].clone() + a[i][1].clone() * b[1][j].clone())
220 })
221}
222
223fn spin_matrix<T: KinematicScalar>(rotation: &Rotation<T>, unit: &T) -> SpinMatrix<T> {
226 let about = |angle: &T, axis| {
227 let half = angle.clone() / angle.from_usize(2);
228 axis_spin_matrix(axis, half.cos(), half.sin())
229 };
230 match rotation {
231 Rotation::Identity => axis_spin_matrix(Axis::Z, unit.one(), unit.zero()),
232 Rotation::QuarterTurn { axis } => {
233 let half = unit.from_usize(2).sqrt().inv();
234 axis_spin_matrix(*axis, half.clone(), half)
235 }
236 Rotation::Euler { alpha, beta, gamma } => spin_matrix_product(
237 &spin_matrix_product(&about(gamma, Axis::Z), &about(beta, Axis::Y)),
238 &about(alpha, Axis::X),
239 ),
240 }
241}
242
243impl<T: KinematicScalar> FourMomentum<T> {
244 pub fn transverse_basis(&self) -> [[T; 4]; 2] {
249 let pt = self.pt();
250 let p = self.spatial.norm();
251 let zero = pt.zero();
252 let (a, b) = if pt == zero {
253 (
254 [zero.clone(), pt.one(), zero.clone(), zero.clone()],
255 [
256 zero.clone(),
257 zero.clone(),
258 if self.spatial.pz > zero {
259 pt.one()
260 } else {
261 -pt.one()
262 },
263 zero,
264 ],
265 )
266 } else {
267 (
268 [
269 zero.clone(),
270 self.spatial.px.clone() * self.spatial.pz.clone() / (pt.clone() * p.clone()),
271 self.spatial.py.clone() * self.spatial.pz.clone() / (pt.clone() * p.clone()),
272 -(pt.clone() / p),
273 ],
274 [
275 zero.clone(),
276 -(self.spatial.py.clone() / pt.clone()),
277 self.spatial.px.clone() / pt,
278 zero,
279 ],
280 )
281 };
282 [a, b]
283 }
284
285 pub fn helicity_spinor(&self, helicity: Sign) -> [Complex<T>; 2] {
287 let p = self.spatial.norm();
288 let zero = self.temporal.value.zero();
289 if (self.spatial.pz < zero && self.spatial.py == zero && self.spatial.px == zero)
290 || self.spatial.pz == -p.clone()
291 {
292 let z = Complex::new(zero.clone(), zero);
293 let one = z.one();
294 return match helicity {
295 Sign::Positive => [z, -one],
296 Sign::Negative => [one, z],
297 };
298 }
299 let factor = (p.from_usize(2) * p.clone() * (p.clone() + self.spatial.pz.clone()))
300 .sqrt()
301 .inv();
302 let mut xi = [
303 Complex::new(factor.clone() * (p + self.spatial.pz.clone()), zero),
304 Complex::new(
305 self.spatial.px.clone() * factor.clone(),
306 self.spatial.py.clone() * factor,
307 ),
308 ];
309 if helicity == Sign::Negative {
310 xi.swap(0, 1);
311 xi[0].re = -xi[0].re.clone();
312 }
313 xi
314 }
315
316 pub fn spinor_energy_factor(&self, sign: Sign) -> Complex<T> {
318 let p = self.spatial.norm();
319 let value = self.temporal.value.clone() + if sign == Sign::Positive { p } else { -p };
320 if value > value.zero() {
321 Complex::new(value.sqrt(), value.zero())
322 } else {
323 Complex::new(value.zero(), (-value).sqrt())
324 }
325 }
326
327 pub fn wavefunction(
336 &self,
337 kind: WavefunctionKind,
338 helicity: Helicity,
339 ) -> Result<Wavefunction<T>, WavefunctionError> {
340 if [
341 &self.temporal.value,
342 &self.spatial.px,
343 &self.spatial.py,
344 &self.spatial.pz,
345 ]
346 .iter()
347 .any(|x| !x.is_finite())
348 {
349 return Err(WavefunctionError::NonFinite);
350 }
351 if matches!(
352 kind,
353 WavefunctionKind::EpsilonBar | WavefunctionKind::UBar | WavefunctionKind::VBar
354 ) {
355 return Ok(self.wavefunction(kind.bar(), helicity)?.bar());
356 }
357 let zero = self.temporal.value.zero();
358 let components = match kind {
359 WavefunctionKind::Scalar => {
360 if !helicity.is_zero() {
361 return Err(WavefunctionError::Helicity(kind));
362 }
363 vec![Complex::new(self.temporal.value.one(), zero)]
364 }
365 WavefunctionKind::Epsilon if helicity.is_zero() => {
366 let mass2 = self.mass_squared();
367 if mass2 <= zero {
368 return Err(WavefunctionError::UndefinedLongitudinal);
369 }
370 let spatial_scale = self
373 .spatial
374 .components()
375 .into_iter()
376 .map(|component| component.norm())
377 .fold(zero.clone(), |largest, component| {
378 if component > largest {
379 component
380 } else {
381 largest
382 }
383 });
384 let components = if spatial_scale == zero {
385 [zero.clone(), zero.clone(), zero.clone(), zero.one()]
386 } else {
387 let scaled = self
388 .spatial
389 .map_ref(|component| component.clone() / spatial_scale.clone());
390 let scaled_norm = scaled.norm();
391 let mass = mass2.sqrt();
392 let energy_over_mass = self.temporal.value.clone() / mass.clone();
393 [
394 spatial_scale * scaled_norm.clone() / mass,
395 scaled.px / scaled_norm.clone() * energy_over_mass.clone(),
396 scaled.py / scaled_norm.clone() * energy_over_mass.clone(),
397 scaled.pz / scaled_norm * energy_over_mass,
398 ]
399 };
400 components
401 .into_iter()
402 .map(|x| Complex::new(x, zero.clone()))
403 .collect()
404 }
405 WavefunctionKind::Epsilon => {
406 let [a, b] = self.transverse_basis();
407 let scale = self.temporal.value.from_usize(2).sqrt().inv();
408 a.into_iter()
409 .zip(b)
410 .map(|(a, b)| {
411 Complex::new(
412 (if helicity.is_plus() { -a } else { a }) * scale.clone(),
413 -b * scale.clone(),
414 )
415 })
416 .collect()
417 }
418 WavefunctionKind::U | WavefunctionKind::V => {
419 let sign = if helicity.is_plus() {
420 Sign::Positive
421 } else if helicity.is_minus() {
422 Sign::Negative
423 } else {
424 return Err(WavefunctionError::Helicity(kind));
425 };
426 let xi = self.helicity_spinor(if kind == WavefunctionKind::U {
427 sign
428 } else {
429 -sign
430 });
431 let (lower, upper) = if kind == WavefunctionKind::U {
432 (
433 self.spinor_energy_factor(-sign),
434 self.spinor_energy_factor(sign),
435 )
436 } else {
437 let a = self.spinor_energy_factor(sign);
438 let b = self.spinor_energy_factor(-sign);
439 if sign == Sign::Positive {
440 (-a, b)
441 } else {
442 (a, -b)
443 }
444 };
445 vec![
446 lower.clone() * xi[0].clone(),
447 lower * xi[1].clone(),
448 upper.clone() * xi[0].clone(),
449 upper * xi[1].clone(),
450 ]
451 }
452 _ => unreachable!("adjoints returned above"),
453 };
454 Wavefunction::from_components(kind, components)
455 }
456
457 pub fn wavefunction_after_rotations(
465 &self,
466 kind: WavefunctionKind,
467 helicity: Helicity,
468 rotations: &[Rotation<T>],
469 ) -> Result<Wavefunction<T>, WavefunctionError> {
470 let reference = rotations
471 .iter()
472 .rev()
473 .fold(self.clone(), |p, rotation| rotation.inverse_rotate_four(&p));
474 rotations.iter().try_fold(
475 reference.wavefunction(kind, helicity)?,
476 |state, rotation| state.rotate(rotation),
477 )
478 }
479}