Skip to main content

lib_jsl_electromagnetics/coordinates/
systems.rs

1//! Cartesian, spherical and cylindrical coordinates: point conversion, scale factors and local
2//! unit-vector frames.
3//!
4//! Spherical coordinates are `(r, θ, φ)` with θ the polar angle from +z in `[0, π]` and φ the
5//! azimuth from +x; cylindrical coordinates are `(ρ, φ, z)`. A [`Position`] keeps the coordinates
6//! it was given, so angles survive conversions between the angular systems and the local frame stays
7//! well defined at the origin and on the polar axis (where Cartesian input could not determine it).
8
9/// A three-dimensional coordinate system.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum CoordinateSystem {
12    /// `(x, y, z)`
13    Cartesian,
14    /// `(r, θ, φ)`
15    Spherical,
16    /// `(ρ, φ, z)`
17    Cylindrical,
18}
19
20/// A point expressed in a particular coordinate system.
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct Position {
23    pub system: CoordinateSystem,
24    pub coords: [f64; 3],
25}
26
27impl Position {
28    pub fn cartesian(x: f64, y: f64, z: f64) -> Self {
29        Position { system: CoordinateSystem::Cartesian, coords: [x, y, z] }
30    }
31
32    pub fn spherical(r: f64, theta: f64, phi: f64) -> Self {
33        Position { system: CoordinateSystem::Spherical, coords: [r, theta, phi] }
34    }
35
36    pub fn cylindrical(rho: f64, phi: f64, z: f64) -> Self {
37        Position { system: CoordinateSystem::Cylindrical, coords: [rho, phi, z] }
38    }
39
40    /// The Cartesian coordinates `[x, y, z]`.
41    pub fn to_cartesian(&self) -> [f64; 3] {
42        let [a, b, c] = self.coords;
43        match self.system {
44            CoordinateSystem::Cartesian => [a, b, c],
45            CoordinateSystem::Spherical => {
46                let (st, ct) = b.sin_cos();
47                let (sp, cp) = c.sin_cos();
48                [a * st * cp, a * st * sp, a * ct]
49            }
50            CoordinateSystem::Cylindrical => {
51                let (sp, cp) = b.sin_cos();
52                [a * cp, a * sp, c]
53            }
54        }
55    }
56
57    /// The same point expressed in `system`. Angles are carried over directly between the
58    /// spherical and cylindrical systems (they share φ), so no information is lost on the axis.
59    pub fn in_system(&self, system: CoordinateSystem) -> Position {
60        use CoordinateSystem::*;
61        if system == self.system {
62            return *self;
63        }
64        let coords = match (self.system, system) {
65            (Spherical, Cylindrical) => {
66                let [r, t, p] = self.coords;
67                [r * t.sin(), p, r * t.cos()]
68            }
69            (Cylindrical, Spherical) => {
70                let [rho, p, z] = self.coords;
71                [rho.hypot(z), rho.atan2(z), p]
72            }
73            (_, Cartesian) => self.to_cartesian(),
74            (Cartesian, Spherical) => {
75                let [x, y, z] = self.coords;
76                let rho = x.hypot(y);
77                [rho.hypot(z), rho.atan2(z), y.atan2(x)]
78            }
79            (Cartesian, Cylindrical) => {
80                let [x, y, z] = self.coords;
81                [x.hypot(y), y.atan2(x), z]
82            }
83            _ => unreachable!("identical systems handled above"),
84        };
85        Position { system, coords }
86    }
87
88    /// The scale factors `(h₁, h₂, h₃)` of `system` at this point, so that
89    /// `ds² = Σ hᵢ² duᵢ²`: `(1, 1, 1)`, `(1, r, r sin θ)` or `(1, ρ, 1)`.
90    pub fn scale_factors(&self, system: CoordinateSystem) -> [f64; 3] {
91        let p = self.in_system(system);
92        match system {
93            CoordinateSystem::Cartesian => [1.0, 1.0, 1.0],
94            CoordinateSystem::Spherical => [1.0, p.coords[0], p.coords[0] * p.coords[1].sin()],
95            CoordinateSystem::Cylindrical => [1.0, p.coords[0], 1.0],
96        }
97    }
98
99    /// The orthonormal, right-handed unit vectors `(û₁, û₂, û₃)` of `system` at this point, each
100    /// as Cartesian components (`frame[i]` is `ûᵢ`). Built from the angles, so it is defined even
101    /// where the position alone is degenerate (r = 0, ρ = 0, the poles).
102    pub fn frame(&self, system: CoordinateSystem) -> [[f64; 3]; 3] {
103        let p = self.in_system(system);
104        match system {
105            CoordinateSystem::Cartesian => [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
106            CoordinateSystem::Spherical => {
107                let (st, ct) = p.coords[1].sin_cos();
108                let (sp, cp) = p.coords[2].sin_cos();
109                [[st * cp, st * sp, ct], [ct * cp, ct * sp, -st], [-sp, cp, 0.0]]
110            }
111            CoordinateSystem::Cylindrical => {
112                let (sp, cp) = p.coords[1].sin_cos();
113                [[cp, sp, 0.0], [-sp, cp, 0.0], [0.0, 0.0, 1.0]]
114            }
115        }
116    }
117
118    /// The Euclidean distance to another point.
119    pub fn distance(&self, other: &Position) -> f64 {
120        let (a, b) = (self.to_cartesian(), other.to_cartesian());
121        ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt()
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128    use std::f64::consts::{FRAC_PI_2, PI};
129
130    const SYSTEMS: [CoordinateSystem; 3] = [CoordinateSystem::Cartesian, CoordinateSystem::Spherical, CoordinateSystem::Cylindrical];
131
132    fn close(a: [f64; 3], b: [f64; 3], tol: f64) -> bool {
133        (0..3).all(|i| (a[i] - b[i]).abs() < tol)
134    }
135
136    #[test]
137    fn conversions_round_trip_between_every_pair() {
138        let pts = [Position::cartesian(1.0, -2.0, 0.5), Position::spherical(3.0, 2.2, -1.1), Position::cylindrical(0.7, 2.9, -4.0)];
139        for p in pts {
140            for s in SYSTEMS {
141                for t in SYSTEMS {
142                    let back = p.in_system(s).in_system(t).to_cartesian();
143                    assert!(close(back, p.to_cartesian(), 1e-12), "{p:?} via {s:?} to {t:?}");
144                }
145            }
146        }
147        let s = Position::cartesian(0.0, 1.0, 1.0).in_system(CoordinateSystem::Spherical);
148        assert!(close(s.coords, [2f64.sqrt(), PI / 4.0, FRAC_PI_2], 1e-12));
149        assert!((Position::cartesian(0.0, 0.0, 0.0).distance(&Position::spherical(2.0, 1.0, 3.0)) - 2.0).abs() < 1e-12);
150    }
151
152    #[test]
153    fn frames_are_orthonormal_right_handed_and_match_coordinate_derivatives() {
154        let pts = [Position::spherical(2.0, 0.6, 1.3), Position::cylindrical(1.5, -2.0, 0.4), Position::cartesian(0.3, 0.4, -0.2)];
155        for p in pts {
156            for s in SYSTEMS {
157                let f = p.frame(s);
158                let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
159                for i in 0..3 {
160                    for j in 0..3 {
161                        assert!((dot(f[i], f[j]) - f64::from(i == j)).abs() < 1e-12);
162                    }
163                }
164                let cross = [f[0][1] * f[1][2] - f[0][2] * f[1][1], f[0][2] * f[1][0] - f[0][0] * f[1][2], f[0][0] * f[1][1] - f[0][1] * f[1][0]];
165                assert!(close(cross, f[2], 1e-12), "right-handed {s:?}");
166                // ∂r/∂uᵢ = hᵢ ûᵢ (central differences in the native coordinates).
167                let native = p.in_system(s);
168                let h = p.scale_factors(s);
169                for i in 0..3 {
170                    let step = 1e-6;
171                    let mut a = native;
172                    let mut b = native;
173                    a.coords[i] += step;
174                    b.coords[i] -= step;
175                    let (ca, cb) = (a.to_cartesian(), b.to_cartesian());
176                    let d: [f64; 3] = std::array::from_fn(|k| (ca[k] - cb[k]) / (2.0 * step));
177                    assert!(close(d, f[i].map(|v| v * h[i]), 1e-6), "{s:?} axis {i}");
178                }
179            }
180        }
181    }
182
183    #[test]
184    fn angles_survive_the_axis_and_the_origin() {
185        // On the z axis Cartesian input cannot fix φ, but a spherical position keeps it.
186        let pole = Position::spherical(1.0, 0.0, 1.2);
187        let f = pole.frame(CoordinateSystem::Spherical);
188        assert!(close(f[2], [-(1.2f64).sin(), 1.2f64.cos(), 0.0], 1e-12)); // φ̂ follows the stored φ
189        assert!(close(pole.in_system(CoordinateSystem::Cylindrical).coords, [0.0, 1.2, 1.0], 1e-12));
190        let origin = Position::spherical(0.0, 0.5, 0.25);
191        assert_eq!(origin.to_cartesian(), [0.0, 0.0, 0.0]);
192        assert!(close(origin.frame(CoordinateSystem::Spherical)[0], Position::spherical(1.0, 0.5, 0.25).frame(CoordinateSystem::Spherical)[0], 1e-15));
193        assert_eq!(pole.scale_factors(CoordinateSystem::Spherical)[2], 0.0);
194    }
195}