Skip to main content

lib_jsl_geometry/dim_4/
space_time_vector.rs

1//! Events and four-vectors in Minkowski space.
2//!
3//! A [`SpaceTimeVector4D`] holds `(t, x, y, z)` with the time component `t` expressed in the same
4//! length unit as the spatial ones (that is, `t` is really `c·time`, with `c = 1` in natural
5//! units; use [`SpaceTimeVector4D::from_time`] to convert from seconds and a speed of light).
6//! The metric signature is `(-, +, +, +)`: the invariant interval `-t² + x² + y² + z²` is negative
7//! for timelike separations, positive for spacelike, and zero on the light cone.
8//!
9//! See the book entry [Space-time](https://jwkunz.github.io/lib_jsl/book/geometry/spacetime.html#minkowski-space-and-lorentz-boosts).
10
11use std::ops::{Add, Mul, Neg, Sub};
12
13#[derive(Debug, Clone, Copy, PartialEq, Default)]
14
15pub struct SpaceTimeVector4D {
16    pub t: f64,
17    pub x: f64,
18    pub y: f64,
19    pub z: f64,
20}
21
22/// How a four-vector sits relative to the light cone.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24
25pub enum Causality {
26    Timelike,
27    Lightlike,
28    Spacelike,
29}
30
31impl SpaceTimeVector4D {
32    pub const fn new(t: f64, x: f64, y: f64, z: f64) -> Self {
33        SpaceTimeVector4D { t, x, y, z }
34    }
35
36    /// From a time in seconds (or any unit) and speed of light `c` in length-per-time units.
37    pub fn from_time(time: f64, c: f64, x: f64, y: f64, z: f64) -> Self {
38        SpaceTimeVector4D::new(c * time, x, y, z)
39    }
40
41    /// The components as `[t, x, y, z]`.
42    pub const fn components(&self) -> [f64; 4] {
43        [self.t, self.x, self.y, self.z]
44    }
45
46    /// The spatial part `[x, y, z]`.
47    pub const fn spatial(&self) -> [f64; 3] {
48        [self.x, self.y, self.z]
49    }
50
51    /// The Minkowski inner product `-t t' + x x' + y y' + z z'`.
52    pub fn dot(&self, other: &Self) -> f64 {
53        -self.t * other.t + self.x * other.x + self.y * other.y + self.z * other.z
54    }
55
56    /// The squared interval `self · self`: negative timelike, zero lightlike, positive spacelike.
57    pub fn interval_squared(&self) -> f64 {
58        self.dot(self)
59    }
60
61    /// Classifies the vector, treating `|interval²| <= tol` as lightlike.
62    pub fn causality(&self, tol: f64) -> Causality {
63        let s = self.interval_squared();
64        if s.abs() <= tol {
65            Causality::Lightlike
66        } else if s < 0.0 {
67            Causality::Timelike
68        } else {
69            Causality::Spacelike
70        }
71    }
72
73    /// The proper time (as `c·τ` length) between two events separated by this timelike vector;
74    /// `None` if the separation is not timelike.
75    pub fn proper_time(&self) -> Option<f64> {
76        let s = self.interval_squared();
77        (s < 0.0).then(|| (-s).sqrt())
78    }
79
80    /// The proper distance between events separated by this spacelike vector; `None` otherwise.
81    pub fn proper_distance(&self) -> Option<f64> {
82        let s = self.interval_squared();
83        (s > 0.0).then(|| s.sqrt())
84    }
85
86    /// The Euclidean magnitude of the spatial part.
87    pub fn spatial_norm(&self) -> f64 {
88        (self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
89    }
90
91    /// The Lorentz factor `1 / sqrt(1 - β²)` for a velocity `beta` (units of `c`); `None` if
92    /// `|beta| >= 1`.
93    pub fn gamma(beta: [f64; 3]) -> Option<f64> {
94        let b2 = beta[0] * beta[0] + beta[1] * beta[1] + beta[2] * beta[2];
95        (b2 < 1.0).then(|| 1.0 / (1.0 - b2).sqrt())
96    }
97
98    /// The 4×4 matrix (rows/columns ordered `t, x, y, z`) of the boost to a frame moving with
99    /// velocity `beta` (units of `c`) relative to the current one: components of a vector in the
100    /// current frame map to its components in the moving frame. `None` if `|beta| >= 1`.
101    pub fn boost_matrix(beta: [f64; 3]) -> Option<[[f64; 4]; 4]> {
102        let g = Self::gamma(beta)?;
103        let b2 = beta[0] * beta[0] + beta[1] * beta[1] + beta[2] * beta[2];
104        let mut m = [[0.0; 4]; 4];
105        m[0][0] = g;
106        for i in 0..3 {
107            m[0][i + 1] = -g * beta[i];
108            m[i + 1][0] = -g * beta[i];
109            for j in 0..3 {
110                let delta = if i == j { 1.0 } else { 0.0 };
111                m[i + 1][j + 1] = delta + if b2 > 0.0 { (g - 1.0) * beta[i] * beta[j] / b2 } else { 0.0 };
112            }
113        }
114        Some(m)
115    }
116
117    /// Applies a 4×4 matrix to the components.
118    pub fn transformed(&self, m: &[[f64; 4]; 4]) -> Self {
119        let v = self.components();
120        let r: [f64; 4] = std::array::from_fn(|i| (0..4).map(|j| m[i][j] * v[j]).sum());
121        SpaceTimeVector4D::new(r[0], r[1], r[2], r[3])
122    }
123
124    /// This vector as seen from a frame moving with velocity `beta` (units of `c`).
125    pub fn boosted(&self, beta: [f64; 3]) -> Option<Self> {
126        Self::boost_matrix(beta).map(|m| self.transformed(&m))
127    }
128
129    /// The four-velocity `γ (1, v)` of a particle with 3-velocity `beta` (units of `c`); its
130    /// interval is always `-1`. `None` if `|beta| >= 1`.
131    pub fn four_velocity(beta: [f64; 3]) -> Option<Self> {
132        let g = Self::gamma(beta)?;
133        Some(SpaceTimeVector4D::new(g, g * beta[0], g * beta[1], g * beta[2]))
134    }
135
136    /// The rapidity `atanh(β)` for motion along one axis; `None` if `|beta| >= 1`.
137    pub fn rapidity(beta: f64) -> Option<f64> {
138        (beta.abs() < 1.0).then(|| beta.atanh())
139    }
140
141    /// The relativistic composition of two collinear velocities (units of `c`).
142    pub fn add_collinear_velocities(u: f64, v: f64) -> f64 {
143        (u + v) / (1.0 + u * v)
144    }
145}
146
147impl Add for SpaceTimeVector4D {
148    type Output = Self;
149    fn add(self, o: Self) -> Self {
150        SpaceTimeVector4D::new(self.t + o.t, self.x + o.x, self.y + o.y, self.z + o.z)
151    }
152}
153impl Sub for SpaceTimeVector4D {
154    type Output = Self;
155    fn sub(self, o: Self) -> Self {
156        SpaceTimeVector4D::new(self.t - o.t, self.x - o.x, self.y - o.y, self.z - o.z)
157    }
158}
159impl Neg for SpaceTimeVector4D {
160    type Output = Self;
161    fn neg(self) -> Self {
162        SpaceTimeVector4D::new(-self.t, -self.x, -self.y, -self.z)
163    }
164}
165impl Mul<f64> for SpaceTimeVector4D {
166    type Output = Self;
167    fn mul(self, s: f64) -> Self {
168        SpaceTimeVector4D::new(self.t * s, self.x * s, self.y * s, self.z * s)
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    #[test]
177    fn interval_and_causality() {
178        let timelike = SpaceTimeVector4D::new(5.0, 3.0, 0.0, 0.0);
179        assert_eq!(timelike.interval_squared(), -16.0);
180        assert_eq!(timelike.proper_time(), Some(4.0));
181        assert_eq!(timelike.causality(1e-12), Causality::Timelike);
182        let spacelike = SpaceTimeVector4D::new(1.0, 2.0, 2.0, 0.0);
183        assert_eq!(spacelike.proper_distance(), Some(7.0f64.sqrt()));
184        assert_eq!(spacelike.causality(1e-12), Causality::Spacelike);
185        let light = SpaceTimeVector4D::new(5.0, 3.0, 4.0, 0.0);
186        assert_eq!(light.causality(1e-12), Causality::Lightlike);
187        assert!(light.proper_time().is_none() && light.proper_distance().is_none());
188        assert_eq!(SpaceTimeVector4D::from_time(2.0, 3.0, 1.0, 0.0, 0.0).t, 6.0);
189    }
190
191    #[test]
192    fn boosts_preserve_the_interval_and_dilate_time() {
193        let v = SpaceTimeVector4D::new(3.0, 1.0, -2.0, 0.5);
194        for beta in [[0.6, 0.0, 0.0], [0.0, -0.3, 0.4], [0.2, 0.3, -0.5]] {
195            let b = v.boosted(beta).unwrap();
196            assert!((b.interval_squared() - v.interval_squared()).abs() < 1e-12, "{beta:?}");
197        }
198        // Time dilation: a clock at rest in frame S' at x' = 0 ticks 1 unit of proper time while
199        // S sees γ units. Boosting the event (1,0,0,0) into a frame moving at β gives (γ, -γβ, ...).
200        let tick = SpaceTimeVector4D::new(1.0, 0.0, 0.0, 0.0);
201        let seen = tick.boosted([0.6, 0.0, 0.0]).unwrap();
202        assert!((seen.t - 1.25).abs() < 1e-12 && (seen.x + 0.75).abs() < 1e-12);
203        // Boost followed by the opposite boost is the identity.
204        let back = v.boosted([0.2, 0.3, -0.5]).unwrap().boosted([-0.2, -0.3, 0.5]).unwrap();
205        assert!((back - v).components().iter().all(|c| c.abs() < 1e-12));
206        assert!(v.boosted([0.8, 0.8, 0.0]).is_none() && SpaceTimeVector4D::boost_matrix([1.0, 0.0, 0.0]).is_none());
207        assert_eq!(v.boosted([0.0; 3]).unwrap(), v);
208    }
209
210    #[test]
211    fn four_velocity_rapidity_and_velocity_addition() {
212        let u = SpaceTimeVector4D::four_velocity([0.6, 0.0, 0.0]).unwrap();
213        assert!((u.interval_squared() + 1.0).abs() < 1e-12 && (u.t - 1.25).abs() < 1e-12);
214        // Seen from its own rest frame the four-velocity is (1, 0, 0, 0).
215        let rest = u.boosted([0.6, 0.0, 0.0]).unwrap();
216        assert!((rest.t - 1.0).abs() < 1e-12 && rest.spatial_norm() < 1e-12);
217        // Rapidities add; so do velocities relativistically, and never exceed c.
218        let (r1, r2) = (SpaceTimeVector4D::rapidity(0.5).unwrap(), SpaceTimeVector4D::rapidity(0.7).unwrap());
219        assert!(((r1 + r2).tanh() - SpaceTimeVector4D::add_collinear_velocities(0.5, 0.7)).abs() < 1e-12);
220        assert!(SpaceTimeVector4D::add_collinear_velocities(0.99, 0.99) < 1.0);
221        assert!(SpaceTimeVector4D::rapidity(1.0).is_none());
222        let sum = SpaceTimeVector4D::new(1.0, 2.0, 3.0, 4.0) + SpaceTimeVector4D::new(1.0, 1.0, 1.0, 1.0) * 2.0 - SpaceTimeVector4D::new(0.0, 1.0, 0.0, 0.0);
223        assert_eq!(sum, SpaceTimeVector4D::new(3.0, 3.0, 5.0, 6.0));
224        assert_eq!(-SpaceTimeVector4D::new(1.0, 0.0, 0.0, 0.0), SpaceTimeVector4D::new(-1.0, 0.0, 0.0, 0.0));
225    }
226}