Skip to main content

feynkit_kinematics/
helicity.rs

1use std::{fmt::Display, str::FromStr};
2
3use linnet::num_traits::{Sign, SignOrZero};
4use serde::{Deserialize, Serialize};
5use thiserror::Error;
6
7/// A fixed external-state helicity in GammaLoop's integer normalization.
8///
9/// Fermion helicities use `-1` and `+1` rather than half-integers. Summation
10/// policies belong to event or runtime configuration and are deliberately not
11/// represented by this fixed-helicity primitive.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
13#[serde(transparent)]
14pub struct Helicity(SignOrZero);
15
16/// An integer or textual value is not a fixed helicity.
17#[derive(Debug, Clone, PartialEq, Eq, Error)]
18pub enum HelicityError {
19    #[error("invalid helicity {value}; expected -1, 0, or 1")]
20    InvalidInteger { value: i8 },
21    #[error("invalid helicity '{value}'; expected minus, zero, or plus")]
22    InvalidText { value: String },
23}
24
25impl Helicity {
26    pub const MINUS: Self = Self(SignOrZero::Minus);
27    pub const ZERO: Self = Self(SignOrZero::Zero);
28    pub const PLUS: Self = Self(SignOrZero::Plus);
29
30    /// Construct a fixed helicity from a validated sign or zero.
31    pub const fn new(value: SignOrZero) -> Self {
32        Self(value)
33    }
34
35    /// Return the underlying sign representation.
36    pub const fn sign(self) -> SignOrZero {
37        self.0
38    }
39
40    /// Return the integer convention used by serialized kinematics.
41    pub const fn integer(self) -> i8 {
42        match self.0 {
43            SignOrZero::Minus => -1,
44            SignOrZero::Zero => 0,
45            SignOrZero::Plus => 1,
46        }
47    }
48
49    pub const fn is_minus(self) -> bool {
50        matches!(self.0, SignOrZero::Minus)
51    }
52
53    pub const fn is_zero(self) -> bool {
54        matches!(self.0, SignOrZero::Zero)
55    }
56
57    pub const fn is_plus(self) -> bool {
58        matches!(self.0, SignOrZero::Plus)
59    }
60}
61
62impl TryFrom<i8> for Helicity {
63    type Error = HelicityError;
64
65    fn try_from(value: i8) -> Result<Self, Self::Error> {
66        SignOrZero::try_from(value)
67            .map(Self)
68            .map_err(|_| HelicityError::InvalidInteger { value })
69    }
70}
71
72impl From<SignOrZero> for Helicity {
73    fn from(value: SignOrZero) -> Self {
74        Self(value)
75    }
76}
77
78impl From<Sign> for Helicity {
79    fn from(value: Sign) -> Self {
80        Self(value.into())
81    }
82}
83
84impl From<Helicity> for SignOrZero {
85    fn from(value: Helicity) -> Self {
86        value.0
87    }
88}
89
90impl Display for Helicity {
91    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        formatter.write_str(match self.0 {
93            SignOrZero::Minus => "-",
94            SignOrZero::Zero => "0",
95            SignOrZero::Plus => "+",
96        })
97    }
98}
99
100impl FromStr for Helicity {
101    type Err = HelicityError;
102
103    fn from_str(value: &str) -> Result<Self, Self::Err> {
104        match value.trim().to_ascii_lowercase().as_str() {
105            "-1" | "-" | "minus" => Ok(Self::MINUS),
106            "0" | "zero" => Ok(Self::ZERO),
107            "1" | "+1" | "+" | "plus" => Ok(Self::PLUS),
108            _ => Err(HelicityError::InvalidText {
109                value: value.to_owned(),
110            }),
111        }
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn validates_integer_helicities() {
121        assert_eq!(Helicity::try_from(-1).unwrap(), Helicity::MINUS);
122        assert_eq!(Helicity::try_from(0).unwrap(), Helicity::ZERO);
123        assert_eq!(Helicity::try_from(1).unwrap(), Helicity::PLUS);
124        assert_eq!(
125            Helicity::try_from(2).unwrap_err(),
126            HelicityError::InvalidInteger { value: 2 }
127        );
128    }
129
130    #[test]
131    fn serde_uses_the_integer_convention() {
132        assert_eq!(serde_json::to_string(&Helicity::MINUS).unwrap(), "-1");
133        assert_eq!(
134            serde_json::from_str::<Helicity>("0").unwrap(),
135            Helicity::ZERO
136        );
137        assert!(serde_json::from_str::<Helicity>("2").is_err());
138    }
139
140    #[test]
141    fn parses_and_displays_named_helicities() {
142        assert_eq!("minus".parse(), Ok(Helicity::MINUS));
143        assert_eq!("+1".parse(), Ok(Helicity::PLUS));
144        assert_eq!(Helicity::ZERO.to_string(), "0");
145    }
146}