Skip to main content

lib_jsl_electromagnetics/coordinates/
polarization.rs

1//! Polarization bases: how the three components of a field vector are defined at a point.
2//!
3//! - [`PolarizationBasis::Linear`]`(system)`: the unit vectors of `system` (x̂ŷẑ, r̂θ̂φ̂ or ρ̂φ̂ẑ),
4//!   components in that order.
5//! - [`PolarizationBasis::Circular`]`(system)`: right- and left-hand circular components formed
6//!   from the two unit vectors transverse to the system's *longitudinal* direction (ẑ, r̂ or ρ̂),
7//!   followed by the longitudinal component. Components are ordered `[R, L, longitudinal]`.
8//!
9//! Handedness follows the IEEE definition (right-hand: the field rotates counter-clockwise when
10//! viewed along the longitudinal direction, i.e. the right-hand rule about it) in either time
11//! convention, which is why circular conversions take a [`TimeConvention`]. Every conversion goes
12//! through Cartesian components at the sample's [`Position`].
13
14use super::systems::{CoordinateSystem, Position};
15use crate::conventions::{C64, TimeConvention};
16use lib_jsl_core::ErrorsJSL;
17use std::f64::consts::FRAC_1_SQRT_2;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum PolarizationBasis {
21    Linear(CoordinateSystem),
22    Circular(CoordinateSystem),
23}
24
25impl PolarizationBasis {
26    pub const CARTESIAN: PolarizationBasis = PolarizationBasis::Linear(CoordinateSystem::Cartesian);
27    pub const SPHERICAL: PolarizationBasis = PolarizationBasis::Linear(CoordinateSystem::Spherical);
28    pub const CYLINDRICAL: PolarizationBasis = PolarizationBasis::Linear(CoordinateSystem::Cylindrical);
29
30    pub fn system(self) -> CoordinateSystem {
31        match self {
32            PolarizationBasis::Linear(s) | PolarizationBasis::Circular(s) => s,
33        }
34    }
35
36    pub fn is_circular(self) -> bool {
37        matches!(self, PolarizationBasis::Circular(_))
38    }
39
40    /// Indices into the system's frame of the transverse pair `(a, b)` (with `â × b̂` along the
41    /// longitudinal direction) and of the longitudinal vector.
42    fn transverse_axes(system: CoordinateSystem) -> ([usize; 2], usize) {
43        match system {
44            CoordinateSystem::Cartesian => ([0, 1], 2),   // x̂ × ŷ = ẑ
45            CoordinateSystem::Spherical => ([1, 2], 0),   // θ̂ × φ̂ = r̂
46            CoordinateSystem::Cylindrical => ([1, 2], 0), // φ̂ × ẑ = ρ̂
47        }
48    }
49
50    /// The basis vectors at `position`, as complex Cartesian components (`vectors[i]` is the i-th
51    /// basis vector). Component `i` of a field in this basis is `vectors[i]ᴴ · E`.
52    pub fn vectors(self, position: &Position, convention: TimeConvention) -> [[C64; 3]; 3] {
53        let frame = position.frame(self.system());
54        let real = |v: [f64; 3]| v.map(|x| C64::new(x, 0.0));
55        match self {
56            PolarizationBasis::Linear(_) => frame.map(real),
57            PolarizationBasis::Circular(s) => {
58                let ([a, b], l) = Self::transverse_axes(s);
59                // RHCP for e^{+jωt}: (â - j b̂)/√2; the other convention conjugates.
60                let j = convention.unit();
61                let r: [C64; 3] = std::array::from_fn(|k| (C64::new(frame[a][k], 0.0) - j * frame[b][k]) * FRAC_1_SQRT_2);
62                let left: [C64; 3] = std::array::from_fn(|k| (C64::new(frame[a][k], 0.0) + j * frame[b][k]) * FRAC_1_SQRT_2);
63                [r, left, real(frame[l])]
64            }
65        }
66    }
67
68    /// Converts components in this basis to Cartesian components.
69    pub fn to_cartesian(self, components: [C64; 3], position: &Position, convention: TimeConvention) -> [C64; 3] {
70        let v = self.vectors(position, convention);
71        std::array::from_fn(|k| (0..3).map(|i| components[i] * v[i][k]).sum())
72    }
73
74    /// Converts Cartesian components to components in this basis.
75    pub fn from_cartesian(self, cartesian: [C64; 3], position: &Position, convention: TimeConvention) -> [C64; 3] {
76        let v = self.vectors(position, convention);
77        std::array::from_fn(|i| (0..3).map(|k| v[i][k].conj() * cartesian[k]).sum())
78    }
79
80    /// Converts components from this basis to `target` at `position`.
81    pub fn convert(self, components: [C64; 3], target: PolarizationBasis, position: &Position, convention: TimeConvention) -> [C64; 3] {
82        if self == target {
83            return components;
84        }
85        target.from_cartesian(self.to_cartesian(components, position, convention), position, convention)
86    }
87
88    /// Real (time-domain) vectors can only be expressed in linear bases.
89    pub fn convert_real(self, components: [f64; 3], target: PolarizationBasis, position: &Position) -> Result<[f64; 3], ErrorsJSL> {
90        if self.is_circular() || target.is_circular() {
91            return Err(ErrorsJSL::InvalidInputRange("Circular bases need complex (harmonic) field values."));
92        }
93        let (from, to) = (position.frame(self.system()), position.frame(target.system()));
94        let cart: [f64; 3] = std::array::from_fn(|k| (0..3).map(|i| components[i] * from[i][k]).sum());
95        Ok(std::array::from_fn(|i| (0..3).map(|k| to[i][k] * cart[k]).sum()))
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    use std::f64::consts::FRAC_PI_2;
103
104    const ALL: [PolarizationBasis; 6] = [
105        PolarizationBasis::Linear(CoordinateSystem::Cartesian),
106        PolarizationBasis::Linear(CoordinateSystem::Spherical),
107        PolarizationBasis::Linear(CoordinateSystem::Cylindrical),
108        PolarizationBasis::Circular(CoordinateSystem::Cartesian),
109        PolarizationBasis::Circular(CoordinateSystem::Spherical),
110        PolarizationBasis::Circular(CoordinateSystem::Cylindrical),
111    ];
112
113    fn close(a: [C64; 3], b: [C64; 3]) -> bool {
114        (0..3).all(|i| (a[i] - b[i]).norm() < 1e-12)
115    }
116
117    fn c(re: f64, im: f64) -> C64 {
118        C64::new(re, im)
119    }
120
121    #[test]
122    fn every_basis_is_unitary_and_round_trips() {
123        let e = [c(1.0, 0.5), c(-0.3, 2.0), c(0.7, -1.1)];
124        let power: f64 = e.iter().map(|v| v.norm_sqr()).sum();
125        for pos in [Position::spherical(2.0, 0.8, -2.1), Position::cylindrical(1.0, 0.4, 3.0), Position::cartesian(1.0, 2.0, 3.0)] {
126            for conv in [TimeConvention::PlusJ, TimeConvention::MinusI] {
127                for a in ALL {
128                    let in_a = a.from_cartesian(e, &pos, conv);
129                    assert!((in_a.iter().map(|v| v.norm_sqr()).sum::<f64>() - power).abs() < 1e-12, "{a:?} preserves power");
130                    assert!(close(a.to_cartesian(in_a, &pos, conv), e), "{a:?} round trip");
131                    for b in ALL {
132                        let there = a.convert(in_a, b, &pos, conv);
133                        assert!(close(b.convert(there, a, &pos, conv), in_a), "{a:?} <-> {b:?}");
134                    }
135                }
136            }
137        }
138    }
139
140    #[test]
141    fn linear_components_match_textbook_values() {
142        // On the equator at φ = 0: ẑ = -θ̂ and x̂ = r̂.
143        let p = Position::spherical(1.0, FRAC_PI_2, 0.0);
144        let z_hat = [c(0.0, 0.0), c(0.0, 0.0), c(1.0, 0.0)];
145        assert!(close(PolarizationBasis::SPHERICAL.from_cartesian(z_hat, &p, TimeConvention::PlusJ), [c(0.0, 0.0), c(-1.0, 0.0), c(0.0, 0.0)]));
146        let x_hat = [c(1.0, 0.0), c(0.0, 0.0), c(0.0, 0.0)];
147        assert!(close(PolarizationBasis::SPHERICAL.from_cartesian(x_hat, &p, TimeConvention::PlusJ), [c(1.0, 0.0), c(0.0, 0.0), c(0.0, 0.0)]));
148        // A purely radial field in cylindrical coordinates at φ = 90° points along +y.
149        let q = Position::cylindrical(2.0, FRAC_PI_2, 0.0);
150        let cart = PolarizationBasis::CYLINDRICAL.to_cartesian([c(3.0, 0.0), c(0.0, 0.0), c(0.0, 0.0)], &q, TimeConvention::PlusJ);
151        assert!(close(cart, [c(0.0, 0.0), c(3.0, 0.0), c(0.0, 0.0)]));
152        // Real vectors convert the same way; circular bases are rejected for real data.
153        let r = PolarizationBasis::CARTESIAN.convert_real([0.0, 0.0, 1.0], PolarizationBasis::SPHERICAL, &p).unwrap();
154        assert!((r[1] + 1.0).abs() < 1e-12);
155        assert!(PolarizationBasis::CARTESIAN.convert_real([1.0, 0.0, 0.0], PolarizationBasis::Circular(CoordinateSystem::Cartesian), &p).is_err());
156    }
157
158    #[test]
159    fn rhcp_rotates_by_the_right_hand_rule_in_both_conventions() {
160        // A pure R component along +z must rotate x̂ → ŷ (counter-clockwise about +z).
161        let pos = Position::cartesian(0.0, 0.0, 0.0);
162        let omega = 1.0;
163        for conv in [TimeConvention::PlusJ, TimeConvention::MinusI] {
164            let e = PolarizationBasis::Circular(CoordinateSystem::Cartesian).to_cartesian([c(1.0, 0.0), c(0.0, 0.0), c(0.0, 0.0)], &pos, conv);
165            let at = |t: f64| [conv.instantaneous(e[0], omega, t), conv.instantaneous(e[1], omega, t)];
166            let (a, b) = (at(0.0), at(0.1));
167            let cross = a[0] * b[1] - a[1] * b[0];
168            assert!(cross > 0.0, "{conv:?}: RHCP must turn counter-clockwise about +z");
169            // The left-hand vector turns the other way.
170            let l = PolarizationBasis::Circular(CoordinateSystem::Cartesian).to_cartesian([c(0.0, 0.0), c(1.0, 0.0), c(0.0, 0.0)], &pos, conv);
171            let lt = |t: f64| [conv.instantaneous(l[0], omega, t), conv.instantaneous(l[1], omega, t)];
172            let (la, lb) = (lt(0.0), lt(0.1));
173            assert!(la[0] * lb[1] - la[1] * lb[0] < 0.0);
174        }
175        // In the spherical circular basis an outgoing wave along +x (θ = 90°, φ = 0) has its
176        // transverse pair (θ̂, φ̂) = (-ẑ, ŷ): R must rotate counter-clockwise about +x as well.
177        let p = Position::spherical(1.0, FRAC_PI_2, 0.0);
178        let e = PolarizationBasis::Circular(CoordinateSystem::Spherical).to_cartesian([c(1.0, 0.0), c(0.0, 0.0), c(0.0, 0.0)], &p, TimeConvention::PlusJ);
179        let at = |t: f64| [TimeConvention::PlusJ.instantaneous(e[1], 1.0, t), TimeConvention::PlusJ.instantaneous(e[2], 1.0, t)];
180        let (a, b) = (at(0.0), at(0.1));
181        assert!(a[0] * b[1] - a[1] * b[0] > 0.0); // y → z rotation is counter-clockwise about +x
182    }
183}