Skip to main content

lib_jsl_geometry/dim_4/
christoffel_symbols.rs

1//! Christoffel symbols of the Levi-Civita connection in four dimensions.
2//!
3//! For a metric `g_{μν}(x)` the symbols are
4//! `Γ^λ_{μν} = ½ g^{λσ} (∂_μ g_{σν} + ∂_ν g_{σμ} - ∂_σ g_{μν})`.
5//! They are stored as `gamma[λ][μ][ν]` (symmetric in the lower pair) and give the geodesic
6//! equation `d²x^λ/dτ² = -Γ^λ_{μν} dx^μ/dτ dx^ν/dτ`.
7//!
8//! See the book entry [Space-time](https://jwkunz.github.io/lib_jsl/book/geometry/spacetime.html#christoffel-symbols-and-geodesics).
9
10/// A 4×4 metric tensor `g[μ][ν]`.
11pub type Metric4 = [[f64; 4]; 4];
12
13/// The Christoffel symbols `Γ^λ_{μν}` at one point.
14#[derive(Debug, Clone, Copy, PartialEq)]
15
16pub struct ChristoffelSymbols4D {
17    pub gamma: [[[f64; 4]; 4]; 4],
18}
19
20/// Inverse of a 4×4 matrix by Gauss-Jordan elimination with partial pivoting; `None` if singular.
21pub fn invert_4x4(m: &Metric4) -> Option<Metric4> {
22    let mut a = *m;
23    let mut inv = [[0.0; 4]; 4];
24    for (i, row) in inv.iter_mut().enumerate() {
25        row[i] = 1.0;
26    }
27    for col in 0..4 {
28        let pivot = (col..4).max_by(|&i, &j| a[i][col].abs().total_cmp(&a[j][col].abs()))?;
29        if a[pivot][col].abs() < 1e-300 {
30            return None;
31        }
32        a.swap(col, pivot);
33        inv.swap(col, pivot);
34        let d = a[col][col];
35        for j in 0..4 {
36            a[col][j] /= d;
37            inv[col][j] /= d;
38        }
39        for i in 0..4 {
40            if i != col {
41                let f = a[i][col];
42                for j in 0..4 {
43                    a[i][j] -= f * a[col][j];
44                    inv[i][j] -= f * inv[col][j];
45                }
46            }
47        }
48    }
49    Some(inv)
50}
51
52impl ChristoffelSymbols4D {
53    /// The symbols from the metric `g` and its partial derivatives `dg[σ][μ][ν] = ∂_σ g_{μν}`
54    /// at a point. `None` if the metric is singular there.
55    // ANCHOR: christoffel
56    pub fn from_metric_derivatives(g: &Metric4, dg: &[Metric4; 4]) -> Option<Self> {
57        let inv = invert_4x4(g)?;
58        let mut gamma = [[[0.0; 4]; 4]; 4];
59        for (l, plane) in gamma.iter_mut().enumerate() {
60            for (m, row) in plane.iter_mut().enumerate() {
61                for (n, entry) in row.iter_mut().enumerate() {
62                    *entry = 0.5 * (0..4).map(|s| inv[l][s] * (dg[m][s][n] + dg[n][s][m] - dg[s][m][n])).sum::<f64>();
63                }
64            }
65        }
66        Some(ChristoffelSymbols4D { gamma })
67    }
68    // ANCHOR_END: christoffel
69
70    /// The symbols of the metric field `metric(x)` at `point`, with the derivatives taken by
71    /// fourth-order central differences of step `h` (a relative step near `1e-3` works well for
72    /// smooth metrics). `None` if the metric is singular at `point`.
73    pub fn from_metric_function(metric: impl Fn(&[f64; 4]) -> Metric4, point: [f64; 4], h: f64) -> Option<Self> {
74        let g = metric(&point);
75        let mut dg = [[[0.0; 4]; 4]; 4];
76        for (s, d) in dg.iter_mut().enumerate() {
77            let shifted = |k: f64| {
78                let mut p = point;
79                p[s] += k * h;
80                metric(&p)
81            };
82            let (m2, m1, p1, p2) = (shifted(-2.0), shifted(-1.0), shifted(1.0), shifted(2.0));
83            for i in 0..4 {
84                for j in 0..4 {
85                    d[i][j] = (m2[i][j] - 8.0 * m1[i][j] + 8.0 * p1[i][j] - p2[i][j]) / (12.0 * h);
86                }
87            }
88        }
89        Self::from_metric_derivatives(&g, &dg)
90    }
91
92    /// Flat Minkowski space in Cartesian coordinates: all symbols vanish.
93    pub fn minkowski() -> Self {
94        ChristoffelSymbols4D { gamma: [[[0.0; 4]; 4]; 4] }
95    }
96
97    /// Exact symbols of the Schwarzschild metric of mass `mass` (units `G = c = 1`) in coordinates
98    /// `(t, r, θ, φ)` at radius `r > 2·mass` and polar angle `theta` (not a pole). `None` outside
99    /// that domain.
100    pub fn schwarzschild(mass: f64, r: f64, theta: f64) -> Option<Self> {
101        let s = theta.sin();
102        if r <= 2.0 * mass || s.abs() < 1e-12 {
103            return None;
104        }
105        let f = 1.0 - 2.0 * mass / r;
106        let mut g = [[[0.0; 4]; 4]; 4];
107        let set = |g: &mut [[[f64; 4]; 4]; 4], l: usize, a: usize, b: usize, v: f64| {
108            g[l][a][b] = v;
109            g[l][b][a] = v;
110        };
111        set(&mut g, 0, 0, 1, mass / (r * r * f));
112        set(&mut g, 1, 0, 0, mass * f / (r * r));
113        set(&mut g, 1, 1, 1, -mass / (r * r * f));
114        set(&mut g, 1, 2, 2, -r * f);
115        set(&mut g, 1, 3, 3, -r * f * s * s);
116        set(&mut g, 2, 1, 2, 1.0 / r);
117        set(&mut g, 2, 3, 3, -s * theta.cos());
118        set(&mut g, 3, 1, 3, 1.0 / r);
119        set(&mut g, 3, 2, 3, theta.cos() / s);
120        Some(ChristoffelSymbols4D { gamma: g })
121    }
122
123    /// The coordinate acceleration `d²x/dτ² = -Γ^λ_{μν} u^μ u^ν` of a free particle with
124    /// coordinate velocity `u = dx/dτ`.
125    pub fn geodesic_acceleration(&self, u: [f64; 4]) -> [f64; 4] {
126        std::array::from_fn(|l| -(0..4).flat_map(|m| (0..4).map(move |n| (m, n))).map(|(m, n)| self.gamma[l][m][n] * u[m] * u[n]).sum::<f64>())
127    }
128
129    /// Whether the symbols are symmetric in their lower indices (always true for Levi-Civita).
130    pub fn is_torsion_free(&self, tol: f64) -> bool {
131        (0..4).all(|l| (0..4).all(|m| (0..4).all(|n| (self.gamma[l][m][n] - self.gamma[l][n][m]).abs() <= tol)))
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    fn flat_spherical(x: &[f64; 4]) -> Metric4 {
140        // ds² = -dt² + dr² + r² dθ² + r² sin²θ dφ²
141        let (r, th) = (x[1], x[2]);
142        let mut g = [[0.0; 4]; 4];
143        g[0][0] = -1.0;
144        g[1][1] = 1.0;
145        g[2][2] = r * r;
146        g[3][3] = r * r * th.sin().powi(2);
147        g
148    }
149
150    fn schwarzschild_metric(mass: f64) -> impl Fn(&[f64; 4]) -> Metric4 {
151        move |x| {
152            let (r, th) = (x[1], x[2]);
153            let f = 1.0 - 2.0 * mass / r;
154            let mut g = [[0.0; 4]; 4];
155            g[0][0] = -f;
156            g[1][1] = 1.0 / f;
157            g[2][2] = r * r;
158            g[3][3] = r * r * th.sin().powi(2);
159            g
160        }
161    }
162
163    #[test]
164    fn flat_space_in_spherical_coordinates() {
165        let c = ChristoffelSymbols4D::from_metric_function(flat_spherical, [0.0, 2.0, 1.0, 0.3], 1e-3).unwrap();
166        let th: f64 = 1.0;
167        assert!((c.gamma[1][2][2] + 2.0).abs() < 1e-8); // Γ^r_θθ = -r
168        assert!((c.gamma[1][3][3] + 2.0 * th.sin().powi(2)).abs() < 1e-8); // Γ^r_φφ = -r sin²θ
169        assert!((c.gamma[2][1][2] - 0.5).abs() < 1e-8); // Γ^θ_rθ = 1/r
170        assert!((c.gamma[3][2][3] - th.cos() / th.sin()).abs() < 1e-8); // Γ^φ_θφ = cot θ
171        assert!(c.gamma[0].iter().flatten().all(|v| v.abs() < 1e-9));
172        assert!(c.is_torsion_free(1e-12));
173        assert_eq!(ChristoffelSymbols4D::minkowski().geodesic_acceleration([1.0, 0.3, 0.2, 0.1]), [0.0; 4]);
174    }
175
176    #[test]
177    fn numerical_symbols_match_the_exact_schwarzschild_ones() {
178        let (m, r, th) = (1.0, 6.0, 1.2);
179        let exact = ChristoffelSymbols4D::schwarzschild(m, r, th).unwrap();
180        let num = ChristoffelSymbols4D::from_metric_function(schwarzschild_metric(m), [0.0, r, th, 0.0], 1e-3).unwrap();
181        for l in 0..4 {
182            for a in 0..4 {
183                for b in 0..4 {
184                    assert!((exact.gamma[l][a][b] - num.gamma[l][a][b]).abs() < 1e-8, "Γ^{l}_{a}{b}: {} vs {}", exact.gamma[l][a][b], num.gamma[l][a][b]);
185                }
186            }
187        }
188        assert!(exact.is_torsion_free(0.0));
189        // Γ^t_tr = M / (r (r - 2M)).
190        assert!((exact.gamma[0][0][1] - m / (r * (r - 2.0 * m))).abs() < 1e-15);
191    }
192
193    #[test]
194    fn geodesic_motion_in_schwarzschild() {
195        let (m, r) = (1.0, 10.0);
196        let c = ChristoffelSymbols4D::schwarzschild(m, r, std::f64::consts::FRAC_PI_2).unwrap();
197        // A particle momentarily at rest (u = (u^t, 0, 0, 0)) falls inward at M (r - 2M) / r³ (u^t)².
198        let f = 1.0 - 2.0 * m / r;
199        let ut = 1.0 / f.sqrt();
200        let a = c.geodesic_acceleration([ut, 0.0, 0.0, 0.0]);
201        assert!(a[1] < 0.0);
202        assert!((a[1] + m * f / (r * r) * ut * ut).abs() < 1e-15);
203        // Newtonian limit: acceleration ≈ -M/r² at large r.
204        let far = ChristoffelSymbols4D::schwarzschild(m, 1.0e4, std::f64::consts::FRAC_PI_2).unwrap();
205        let af = far.geodesic_acceleration([1.0, 0.0, 0.0, 0.0]);
206        assert!((af[1] * 1.0e8 + 1.0).abs() < 1e-3);
207        // Domain checks.
208        assert!(ChristoffelSymbols4D::schwarzschild(1.0, 1.5, 1.0).is_none() && ChristoffelSymbols4D::schwarzschild(1.0, 5.0, 0.0).is_none());
209        let singular = |_: &[f64; 4]| [[0.0; 4]; 4];
210        assert!(ChristoffelSymbols4D::from_metric_function(singular, [0.0; 4], 1e-3).is_none());
211    }
212
213    #[test]
214    #[allow(clippy::needless_range_loop)]
215    fn matrix_inverse() {
216        let g = schwarzschild_metric(1.0)(&[0.0, 5.0, 1.0, 0.0]);
217        let inv = invert_4x4(&g).unwrap();
218        for i in 0..4 {
219            for j in 0..4 {
220                let p: f64 = (0..4).map(|k| g[i][k] * inv[k][j]).sum();
221                assert!((p - if i == j { 1.0 } else { 0.0 }).abs() < 1e-12);
222            }
223        }
224    }
225}