Skip to main content

feynkit_kinematics/
transform.rs

1use serde::{Deserialize, Deserializer, Serialize, de};
2use thiserror::Error;
3
4use crate::{FourMomentum, KinematicScalar, ThreeMomentum};
5
6/// Cartesian axis for an exact quarter-turn rotation.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
8#[serde(rename_all = "snake_case")]
9pub enum Axis {
10    /// X axis.
11    X,
12    /// Y axis.
13    Y,
14    /// Z axis.
15    Z,
16}
17
18/// An active spatial rotation with Euler matrix `Rz(gamma) * Ry(beta) * Rx(alpha)`.
19#[derive(Debug, Default, Clone, Copy, PartialEq, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case", tag = "kind")]
21pub enum Rotation<T> {
22    /// No rotation.
23    #[default]
24    Identity,
25    /// Euler angles `(alpha, beta, gamma)` without an intermediate precision conversion.
26    Euler {
27        /// First Euler angle.
28        alpha: T,
29        /// Second Euler angle.
30        beta: T,
31        /// Third Euler angle.
32        gamma: T,
33    },
34    /// An exact positive `pi/2` rotation around a Cartesian axis.
35    QuarterTurn {
36        /// Rotation axis.
37        axis: Axis,
38    },
39}
40
41impl<T> Rotation<T> {
42    /// Construct an Euler-angle rotation.
43    pub const fn euler(alpha: T, beta: T, gamma: T) -> Self {
44        Self::Euler { alpha, beta, gamma }
45    }
46
47    /// Construct an exact positive quarter turn.
48    pub const fn quarter_turn(axis: Axis) -> Self {
49        Self::QuarterTurn { axis }
50    }
51
52    /// Return whether this is the identity transformation.
53    pub const fn is_identity(&self) -> bool {
54        matches!(self, Self::Identity)
55    }
56
57    /// Transform the angle scalar type.
58    pub fn map<U>(self, mut map: impl FnMut(T) -> U) -> Rotation<U> {
59        match self {
60            Self::Identity => Rotation::Identity,
61            Self::Euler { alpha, beta, gamma } => {
62                Rotation::euler(map(alpha), map(beta), map(gamma))
63            }
64            Self::QuarterTurn { axis } => Rotation::quarter_turn(axis),
65        }
66    }
67}
68
69impl<T: KinematicScalar> Rotation<T> {
70    /// Rotate a spatial momentum.
71    pub fn rotate_three(&self, momentum: &ThreeMomentum<T>) -> ThreeMomentum<T> {
72        match self {
73            Self::Identity => momentum.clone(),
74            Self::QuarterTurn { axis: Axis::X } => ThreeMomentum::new(
75                momentum.px.clone(),
76                -momentum.pz.clone(),
77                momentum.py.clone(),
78            ),
79            Self::QuarterTurn { axis: Axis::Y } => ThreeMomentum::new(
80                momentum.pz.clone(),
81                momentum.py.clone(),
82                -momentum.px.clone(),
83            ),
84            Self::QuarterTurn { axis: Axis::Z } => ThreeMomentum::new(
85                -momentum.py.clone(),
86                momentum.px.clone(),
87                momentum.pz.clone(),
88            ),
89            Self::Euler { alpha, beta, gamma } => {
90                let sin_alpha = alpha.sin();
91                let cos_alpha = alpha.cos();
92                let sin_beta = beta.sin();
93                let cos_beta = beta.cos();
94                let sin_gamma = gamma.sin();
95                let cos_gamma = gamma.cos();
96
97                let px = momentum.px.clone();
98                let py = momentum.py.clone();
99                let pz = momentum.pz.clone();
100
101                ThreeMomentum::new(
102                    cos_gamma.clone() * cos_beta.clone() * px.clone()
103                        + (-cos_alpha.clone() * sin_gamma.clone()
104                            + sin_alpha.clone() * sin_beta.clone() * cos_gamma.clone())
105                            * py.clone()
106                        + (sin_alpha.clone() * sin_gamma.clone()
107                            + cos_alpha.clone() * sin_beta.clone() * cos_gamma)
108                            * pz.clone(),
109                    sin_gamma.clone() * cos_beta.clone() * px.clone()
110                        + (cos_alpha.clone() * gamma.cos()
111                            + sin_alpha.clone() * sin_beta.clone() * sin_gamma.clone())
112                            * py.clone()
113                        + (-sin_alpha.clone() * gamma.cos()
114                            + cos_alpha.clone() * sin_beta * sin_gamma)
115                            * pz.clone(),
116                    -beta.sin() * px
117                        + cos_beta.clone() * sin_alpha * py
118                        + cos_alpha * cos_beta * pz,
119                )
120            }
121        }
122    }
123
124    /// Apply the inverse rotation to a spatial momentum.
125    pub fn inverse_rotate_three(&self, momentum: &ThreeMomentum<T>) -> ThreeMomentum<T> {
126        match self {
127            Self::Identity => momentum.clone(),
128            Self::QuarterTurn { axis: Axis::X } => ThreeMomentum::new(
129                momentum.px.clone(),
130                momentum.pz.clone(),
131                -momentum.py.clone(),
132            ),
133            Self::QuarterTurn { axis: Axis::Y } => ThreeMomentum::new(
134                -momentum.pz.clone(),
135                momentum.py.clone(),
136                momentum.px.clone(),
137            ),
138            Self::QuarterTurn { axis: Axis::Z } => ThreeMomentum::new(
139                momentum.py.clone(),
140                -momentum.px.clone(),
141                momentum.pz.clone(),
142            ),
143            Self::Euler { alpha, beta, gamma } => {
144                let sin_alpha = alpha.sin();
145                let cos_alpha = alpha.cos();
146                let sin_beta = beta.sin();
147                let cos_beta = beta.cos();
148                let sin_gamma = gamma.sin();
149                let cos_gamma = gamma.cos();
150
151                let px = momentum.px.clone();
152                let py = momentum.py.clone();
153                let pz = momentum.pz.clone();
154
155                ThreeMomentum::new(
156                    cos_gamma.clone() * cos_beta.clone() * px.clone()
157                        + sin_gamma.clone() * cos_beta.clone() * py.clone()
158                        - sin_beta.clone() * pz.clone(),
159                    (-cos_alpha.clone() * sin_gamma.clone()
160                        + sin_alpha.clone() * sin_beta.clone() * cos_gamma.clone())
161                        * px.clone()
162                        + (cos_alpha.clone() * cos_gamma.clone()
163                            + sin_alpha.clone() * sin_beta.clone() * sin_gamma.clone())
164                            * py.clone()
165                        + cos_beta.clone() * sin_alpha * pz.clone(),
166                    (alpha.sin() * sin_gamma
167                        + cos_alpha.clone() * sin_beta.clone() * cos_gamma.clone())
168                        * px
169                        + (-alpha.sin() * cos_gamma + cos_alpha.clone() * sin_beta * gamma.sin())
170                            * py
171                        + cos_alpha * cos_beta * pz,
172                )
173            }
174        }
175    }
176
177    /// Rotate only the spatial component of a four-momentum.
178    pub fn rotate_four(&self, momentum: &FourMomentum<T>) -> FourMomentum<T> {
179        FourMomentum::new(
180            momentum.temporal.clone(),
181            self.rotate_three(&momentum.spatial),
182        )
183    }
184
185    /// Apply the inverse rotation to only the spatial component of a four-momentum.
186    pub fn inverse_rotate_four(&self, momentum: &FourMomentum<T>) -> FourMomentum<T> {
187        FourMomentum::new(
188            momentum.temporal.clone(),
189            self.inverse_rotate_three(&momentum.spatial),
190        )
191    }
192}
193
194/// A physical Lorentz boost parameterized by the three-velocity `beta`.
195#[derive(Debug, Clone, PartialEq, Serialize)]
196pub struct Boost<T> {
197    beta: ThreeMomentum<T>,
198}
199
200#[derive(Deserialize)]
201struct BoostData<T> {
202    beta: ThreeMomentum<T>,
203}
204
205/// Invalid Lorentz-boost parameters.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
207pub enum BoostError {
208    /// A beta component is non-finite.
209    #[error("boost velocity contains a non-finite component")]
210    NonFinite,
211    /// Physical boosts require `|beta| < 1`.
212    #[error("boost velocity must satisfy |beta| < 1")]
213    Superluminal,
214}
215
216impl<'de, T> Deserialize<'de> for Boost<T>
217where
218    T: KinematicScalar + Deserialize<'de>,
219{
220    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
221    where
222        D: Deserializer<'de>,
223    {
224        let BoostData { beta } = BoostData::deserialize(deserializer)?;
225        Self::new(beta).map_err(de::Error::custom)
226    }
227}
228
229impl<T: KinematicScalar> Boost<T> {
230    /// Validate and construct a boost.
231    pub fn new(beta: ThreeMomentum<T>) -> Result<Self, BoostError> {
232        if beta
233            .components()
234            .into_iter()
235            .any(|component| !component.is_finite())
236        {
237            return Err(BoostError::NonFinite);
238        }
239
240        let beta_squared = beta.norm_squared();
241        if beta_squared >= beta_squared.one() {
242            return Err(BoostError::Superluminal);
243        }
244        Ok(Self { beta })
245    }
246
247    /// Borrow the boost velocity.
248    pub fn beta(&self) -> &ThreeMomentum<T> {
249        &self.beta
250    }
251
252    /// Apply the boost using the mostly-minus metric convention.
253    pub fn apply(&self, momentum: &FourMomentum<T>) -> FourMomentum<T> {
254        let beta_squared = self.beta.norm_squared();
255        let one = beta_squared.one();
256        let zero = beta_squared.zero();
257        let gamma = (one.clone() - beta_squared.clone()).sqrt().inv();
258        let beta_dot_momentum = momentum.spatial.dot(&self.beta);
259        let gamma_two = if beta_squared > zero {
260            (gamma.clone() - one) / beta_squared
261        } else {
262            zero
263        };
264        let spatial_factor =
265            gamma_two * beta_dot_momentum.clone() + gamma.clone() * momentum.temporal.value.clone();
266
267        FourMomentum::from_args(
268            gamma * (momentum.temporal.value.clone() + beta_dot_momentum),
269            self.beta.px.clone() * spatial_factor.clone() + momentum.spatial.px.clone(),
270            self.beta.py.clone() * spatial_factor.clone() + momentum.spatial.py.clone(),
271            self.beta.pz.clone() * spatial_factor + momentum.spatial.pz.clone(),
272        )
273    }
274
275    /// Apply the inverse boost without reconstructing configuration constants.
276    pub fn apply_inverse(&self, momentum: &FourMomentum<T>) -> FourMomentum<T> {
277        let inverse = Self { beta: -&self.beta };
278        inverse.apply(momentum)
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use numerica::domains::float::{FloatLike, Real};
285
286    use super::*;
287
288    fn assert_close(lhs: f64, rhs: f64) {
289        assert!((lhs - rhs).abs() < 1.0e-12, "{lhs} != {rhs}");
290    }
291
292    fn assert_momentum_close(lhs: &FourMomentum<f64>, rhs: &FourMomentum<f64>) {
293        for (left, right) in lhs.into_iter().zip(rhs) {
294            assert_close(*left, *right);
295        }
296    }
297
298    #[test]
299    fn exact_quarter_turn_matches_euler_rotation() {
300        let zero = 0.0;
301        let half_pi = zero.pi() / zero.from_usize(2);
302        let momentum = FourMomentum::from_args(2.0, 3.0, 1.0, 2.0);
303
304        for (axis, euler) in [
305            (Axis::X, Rotation::euler(half_pi, zero, zero)),
306            (Axis::Y, Rotation::euler(zero, half_pi, zero)),
307            (Axis::Z, Rotation::euler(zero, zero, half_pi)),
308        ] {
309            let exact = Rotation::quarter_turn(axis).rotate_four(&momentum);
310            let rotated = euler.rotate_four(&momentum);
311            assert_momentum_close(&exact, &rotated);
312            assert_momentum_close(&euler.inverse_rotate_four(&rotated), &momentum);
313        }
314    }
315
316    #[test]
317    fn inverse_restores_a_general_euler_rotation() {
318        let momentum = FourMomentum::from_args(7.0, 3.0, -2.0, 5.0);
319        let rotation = Rotation::euler(0.37, -0.28, 0.91);
320        let rotated = rotation.rotate_four(&momentum);
321
322        assert_close(rotated.mass_squared(), momentum.mass_squared());
323        assert_momentum_close(&rotation.inverse_rotate_four(&rotated), &momentum);
324    }
325
326    #[test]
327    fn boost_and_inverse_preserve_invariant_mass() {
328        let momentum = FourMomentum::from_args(5.0, 0.0, 0.0, 0.0);
329        let boost = Boost::new(ThreeMomentum::new(0.6, 0.0, 0.0)).unwrap();
330        let boosted = boost.apply(&momentum);
331
332        assert_close(boosted.temporal.value, 6.25);
333        assert_close(boosted.spatial.px, 3.75);
334        assert_close(boosted.mass_squared(), momentum.mass_squared());
335        assert_momentum_close(&boost.apply_inverse(&boosted), &momentum);
336    }
337
338    #[test]
339    fn rejects_lightlike_or_non_finite_boost_velocity() {
340        assert_eq!(
341            Boost::new(ThreeMomentum::new(1.0, 0.0, 0.0)).unwrap_err(),
342            BoostError::Superluminal
343        );
344        assert_eq!(
345            Boost::new(ThreeMomentum::new(f64::NAN, 0.0, 0.0)).unwrap_err(),
346            BoostError::NonFinite
347        );
348    }
349
350    #[test]
351    fn deserialization_rejects_superluminal_boost_velocity() {
352        let error = serde_json::from_str::<Boost<f64>>(r#"{"beta":{"px":1.0,"py":0.0,"pz":0.0}}"#)
353            .unwrap_err();
354
355        assert!(error.to_string().contains("|beta| < 1"));
356    }
357}