Skip to main content

lib_jsl_electromagnetics/fields/
spherical_waves.rs

1//! Spherical wave expansions of radiated fields.
2//!
3//! Outside a sphere enclosing all sources, the field is a sum of outgoing vector spherical wave
4//! functions (engineering convention `e^{+jωt}`, spherical Hankel functions `h_n = h_n^{(2)}`):
5//!
6//! `E = Σ_{n,m} α_nm M_nm + β_nm N_nm`, `M_nm = h_n(kr) Φ_nm`,
7//! `N_nm = (1/k)∇×M_nm = −√(n(n+1)) h_n(kr)/(kr) Y_nm r̂ − (1/kr) (kr h_n)' Ψ_nm`,
8//!
9//! where `Y_nm` are the orthonormal spherical harmonics, `Ψ_nm = r∇Y_nm / √(n(n+1))` and
10//! `Φ_nm = r̂ × Ψ_nm` the orthonormal tangential vector spherical harmonics. The far-field
11//! pattern (with `e^{−jkr}/r` removed) is `F = Σ (j^{n+1}/k) α_nm Φ_nm + (j^{n+2}/k) β_nm Ψ_nm`,
12//! so projecting a pattern onto `Φ_nm` and `Ψ_nm` gives the wave amplitudes, from which the
13//! field follows at any radius outside the minimum sphere. A source of electrical radius
14//! `k r₀` needs degrees up to about `k r₀ + 10`.
15//!
16//! See the book entry [Spherical waves and near-field to far-field transformation](https://jwkunz.github.io/lib_jsl/book/em-waves/near-to-far.html).
17
18use crate::conventions::{C64, Medium, TimeConvention};
19use lib_jsl_core::ErrorsJSL;
20use lib_jsl_core::constants::em::C0;
21use lib_jsl_special_functions::{bessel_spherical, bessel_spherical_y, legendre_with_derivative, spherical_harmonic};
22use std::f64::consts::{PI, TAU};
23
24/// The tangential vector spherical harmonics `(Ψ_nm, Φ_nm)` as `[θ, φ]` components (`n ≥ 1`,
25/// `|m| ≤ n`). Poles are approached rather than evaluated (θ is nudged by 1e-9).
26pub fn vector_spherical_harmonics(n: u32, m: i32, theta: f64, phi: f64) -> ([C64; 2], [C64; 2]) {
27    let theta = theta.clamp(1e-9, PI - 1e-9);
28    let (nf, mf) = (n as f64, m as f64);
29    // ∂Y/∂θ = ½ [√((n−m)(n+m+1)) e^{−jφ} Y_n^{m+1} − √((n+m)(n−m+1)) e^{jφ} Y_n^{m−1}].
30    let up = if m < n as i32 { ((nf - mf) * (nf + mf + 1.0)).sqrt() * C64::from_polar(1.0, -phi) * spherical_harmonic(n, m + 1, theta, phi) } else { C64::new(0.0, 0.0) };
31    let down = if m > -(n as i32) { ((nf + mf) * (nf - mf + 1.0)).sqrt() * C64::from_polar(1.0, phi) * spherical_harmonic(n, m - 1, theta, phi) } else { C64::new(0.0, 0.0) };
32    let d_theta = 0.5 * (up - down);
33    let d_phi_over_sin = C64::new(0.0, mf) * spherical_harmonic(n, m, theta, phi) / theta.sin();
34    let norm = 1.0 / (nf * (nf + 1.0)).sqrt();
35    let psi = [d_theta * norm, d_phi_over_sin * norm];
36    // r̂ × (a θ̂ + b φ̂) = a φ̂ − b θ̂.
37    let phi_vec = [-psi[1], psi[0]];
38    (psi, phi_vec)
39}
40
41/// The outgoing spherical Hankel function `h_n^{(2)}(x) = j_n(x) − j y_n(x)` and
42/// `(x h_n(x))'`.
43pub(crate) fn hankel(n: u32, x: f64) -> (C64, C64) {
44    let h = |k: i32| C64::new(bessel_spherical(k, x), -bessel_spherical_y(k, x));
45    let hn = h(n as i32);
46    (hn, x * h(n as i32 - 1) - n as f64 * hn)
47}
48
49/// Gauss-Legendre nodes and weights on [−1, 1] by Newton's method.
50pub(crate) fn gauss_legendre(count: usize) -> Vec<(f64, f64)> {
51    (0..count)
52        .map(|i| {
53            let mut x = (PI * (i as f64 + 0.75) / (count as f64 + 0.5)).cos();
54            for _ in 0..100 {
55                let (p, dp) = legendre_with_derivative(count as u32, x);
56                let dx = p / dp;
57                x -= dx;
58                if dx.abs() < 1e-16 {
59                    break;
60                }
61            }
62            let dp = legendre_with_derivative(count as u32, x).1;
63            (x, 2.0 / ((1.0 - x * x) * dp * dp))
64        })
65        .collect()
66}
67
68/// A spherical wave expansion truncated at degree `N`.
69#[derive(Debug, Clone)]
70pub struct SphericalWaveExpansion {
71    pub frequency: f64,
72    pub max_degree: u32,
73    /// TE amplitudes `α_nm`, indexed by [`SphericalWaveExpansion::index`].
74    pub te: Vec<C64>,
75    /// TM amplitudes `β_nm`.
76    pub tm: Vec<C64>,
77}
78
79impl SphericalWaveExpansion {
80    /// The storage index of `(n, m)`: `n² − 1 + n + m` (degrees from 1).
81    pub fn index(n: u32, m: i32) -> usize {
82        ((n * n) as i64 - 1 + n as i64 + m as i64) as usize
83    }
84
85    fn wavenumber(&self) -> f64 {
86        TAU * self.frequency / C0
87    }
88
89    /// Expands a far-field pattern `[F_θ, F_φ]` (V, `e^{−jkr}/r` removed, in `convention`) up to
90    /// degree `max_degree`, projecting by Gauss-Legendre quadrature in θ and the trapezoid rule
91    /// in φ (exact for patterns band-limited to that degree).
92    pub fn from_far_field<F>(pattern: F, frequency: f64, max_degree: u32, convention: TimeConvention) -> Result<Self, ErrorsJSL>
93    where
94        F: Fn(f64, f64) -> [C64; 2],
95    {
96        if max_degree == 0 || frequency.is_nan() || frequency <= 0.0 {
97            return Err(ErrorsJSL::InvalidInputRange("Need a positive frequency and maximum degree."));
98        }
99        let size = Self::index(max_degree, max_degree as i32) + 1;
100        let (mut a, mut b) = (vec![C64::new(0.0, 0.0); size], vec![C64::new(0.0, 0.0); size]);
101        let thetas = gauss_legendre(max_degree as usize + 2);
102        let phis = 2 * max_degree as usize + 2;
103        // ANCHOR: swe_projection
104        for &(x, w) in &thetas {
105            let theta = x.acos();
106            for p in 0..phis {
107                let phi = TAU * p as f64 / phis as f64;
108                let f = pattern(theta, phi).map(|v| convention.convert(v, TimeConvention::PlusJ));
109                let weight = w * TAU / phis as f64;
110                for n in 1..=max_degree {
111                    for m in -(n as i32)..=n as i32 {
112                        let (psi, phv) = vector_spherical_harmonics(n, m, theta, phi);
113                        let k = Self::index(n, m);
114                        a[k] += weight * (f[0] * psi[0].conj() + f[1] * psi[1].conj());
115                        b[k] += weight * (f[0] * phv[0].conj() + f[1] * phv[1].conj());
116                    }
117                }
118            }
119        }
120        // ANCHOR_END: swe_projection
121        let k = TAU * frequency / C0;
122        let j = C64::new(0.0, 1.0);
123        let mut te = vec![C64::new(0.0, 0.0); size];
124        let mut tm = vec![C64::new(0.0, 0.0); size];
125        for n in 1..=max_degree {
126            for m in -(n as i32)..=n as i32 {
127                let i = Self::index(n, m);
128                te[i] = k * b[i] / j.powu(n + 1);
129                tm[i] = k * a[i] / j.powu(n + 2);
130            }
131        }
132        Ok(SphericalWaveExpansion { frequency, max_degree, te, tm })
133    }
134
135    /// The far-field pattern `[F_θ, F_φ]` in `convention`.
136    pub fn far_field(&self, theta: f64, phi: f64, convention: TimeConvention) -> [C64; 2] {
137        let k = self.wavenumber();
138        let j = C64::new(0.0, 1.0);
139        let mut f = [C64::new(0.0, 0.0); 2];
140        for n in 1..=self.max_degree {
141            for m in -(n as i32)..=n as i32 {
142                let i = Self::index(n, m);
143                let (psi, phv) = vector_spherical_harmonics(n, m, theta, phi);
144                let (ca, cb) = (self.te[i] * j.powu(n + 1) / k, self.tm[i] * j.powu(n + 2) / k);
145                for c in 0..2 {
146                    f[c] += ca * phv[c] + cb * psi[c];
147                }
148            }
149        }
150        f.map(|v| TimeConvention::PlusJ.convert(v, convention))
151    }
152
153    /// The electric field `[E_r, E_θ, E_φ]` at a point outside the minimum sphere.
154    pub fn field_at(&self, r: f64, theta: f64, phi: f64, convention: TimeConvention) -> [C64; 3] {
155        let kr = self.wavenumber() * r;
156        let mut e = [C64::new(0.0, 0.0); 3];
157        for n in 1..=self.max_degree {
158            let (h, dh) = hankel(n, kr);
159            let nn = (n as f64 * (n as f64 + 1.0)).sqrt();
160            for m in -(n as i32)..=n as i32 {
161                let i = Self::index(n, m);
162                let (psi, phv) = vector_spherical_harmonics(n, m, theta, phi);
163                e[0] -= self.tm[i] * nn * h / kr * spherical_harmonic(n, m, theta.clamp(1e-9, PI - 1e-9), phi);
164                for c in 0..2 {
165                    e[c + 1] += self.te[i] * h * phv[c] - self.tm[i] * dh / kr * psi[c];
166                }
167            }
168        }
169        e.map(|v| TimeConvention::PlusJ.convert(v, convention))
170    }
171
172    /// The radiated power `(1/2η) ∫ |F|² dΩ` from the coefficients (Parseval).
173    pub fn radiated_power(&self) -> f64 {
174        let k = self.wavenumber();
175        let eta = Medium::VACUUM.impedance(TimeConvention::PlusJ).re;
176        self.te.iter().chain(&self.tm).map(|c| c.norm_sqr()).sum::<f64>() / (k * k * 2.0 * eta)
177    }
178
179    /// The fraction of power carried by each degree `n = 1..=N`.
180    pub fn power_by_degree(&self) -> Vec<f64> {
181        let total: f64 = self.te.iter().chain(&self.tm).map(|c| c.norm_sqr()).sum();
182        (1..=self.max_degree)
183            .map(|n| (-(n as i32)..=n as i32).map(|m| { let i = Self::index(n, m); self.te[i].norm_sqr() + self.tm[i].norm_sqr() }).sum::<f64>() / total)
184            .collect()
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191    use crate::antenna_models::{Antenna, HalfWaveDipole, HertzianDipole};
192    use crate::coordinates::systems::Position;
193
194    const F: f64 = 1e9;
195
196    #[test]
197    fn vector_harmonics_are_orthonormal_and_match_finite_differences() {
198        let nodes = gauss_legendre(12);
199        let modes = [(1u32, 0i32), (1, 1), (2, -1), (3, 2)];
200        for &(n1, m1) in &modes {
201            for &(n2, m2) in &modes {
202                let (mut pp, mut ff, mut pf) = (C64::new(0.0, 0.0), C64::new(0.0, 0.0), C64::new(0.0, 0.0));
203                for &(x, w) in &nodes {
204                    for p in 0..16 {
205                        let (t, ph) = (x.acos(), TAU * p as f64 / 16.0);
206                        let (a1, b1) = vector_spherical_harmonics(n1, m1, t, ph);
207                        let (a2, b2) = vector_spherical_harmonics(n2, m2, t, ph);
208                        let dw = w * TAU / 16.0;
209                        pp += dw * (a1[0] * a2[0].conj() + a1[1] * a2[1].conj());
210                        ff += dw * (b1[0] * b2[0].conj() + b1[1] * b2[1].conj());
211                        pf += dw * (a1[0] * b2[0].conj() + a1[1] * b2[1].conj());
212                    }
213                }
214                let want = if (n1, m1) == (n2, m2) { 1.0 } else { 0.0 };
215                assert!((pp - want).norm() < 1e-12 && (ff - want).norm() < 1e-12 && pf.norm() < 1e-12, "({n1},{m1}) ({n2},{m2})");
216            }
217        }
218        // The θ derivative identity against a finite difference.
219        let (t, ph, h) = (0.7, 0.4, 1e-6);
220        let numeric = (spherical_harmonic(3, 2, t + h, ph) - spherical_harmonic(3, 2, t - h, ph)) / (2.0 * h);
221        let (psi, _) = vector_spherical_harmonics(3, 2, t, ph);
222        assert!((psi[0] * 12f64.sqrt() - numeric).norm() < 1e-8);
223    }
224
225    #[test]
226    fn a_hertzian_dipole_is_a_single_tm_mode_and_its_near_field_is_reconstructed() {
227        let dipole = HertzianDipole::new(0.01);
228        let swe = SphericalWaveExpansion::from_far_field(|t, p| dipole.far_field(t, p, F, TimeConvention::PlusJ), F, 4, TimeConvention::PlusJ).unwrap();
229        let power = swe.power_by_degree();
230        assert!(power[0] > 1.0 - 1e-12 && swe.te.iter().all(|c| c.norm() < 1e-12 * swe.tm[SphericalWaveExpansion::index(1, 0)].norm()));
231        // The exact near field, reactive terms included, from the far-field coefficients alone.
232        let lambda = C0 / F;
233        for &(r, t, p) in &[(0.2 * lambda, 0.6, 0.3), (0.5 * lambda, 1.4, 2.0), (3.0 * lambda, 2.5, -1.0)] {
234            let e = swe.field_at(r, t, p, TimeConvention::PlusJ);
235            let (exact, _) = dipole.near_field(&Position::spherical(r, t, p), F, TimeConvention::PlusJ);
236            let scale = exact.iter().map(|v| v.norm()).fold(0.0, f64::max);
237            for c in 0..3 {
238                assert!((e[c] - exact[c]).norm() < 1e-9 * scale, "r={r} component {c}: {} vs {}", e[c], exact[c]);
239            }
240        }
241        assert!((swe.radiated_power() / dipole.radiated_power(F) - 1.0).abs() < 1e-9);
242    }
243
244    #[test]
245    fn half_wave_dipole_pattern_converges_and_conventions_conjugate() {
246        let antenna = HalfWaveDipole::new(F);
247        let pattern = |t: f64, p: f64| antenna.far_field(t, p, F, TimeConvention::PlusJ);
248        let swe = SphericalWaveExpansion::from_far_field(pattern, F, 15, TimeConvention::PlusJ).unwrap();
249        for &(t, p) in &[(0.4, 0.0), (1.2, 1.0), (2.0, 4.0)] {
250            let (a, b) = (swe.far_field(t, p, TimeConvention::PlusJ), pattern(t, p));
251            assert!((a[0] - b[0]).norm() < 1e-6 * b[0].norm().max(1.0), "θ={t}");
252        }
253        assert!((swe.radiated_power() / antenna.radiated_power(F) - 1.0).abs() < 1e-6);
254        // Only odd TM degrees with m = 0 (a z-directed, symmetric current).
255        assert!(swe.tm[SphericalWaveExpansion::index(2, 0)].norm() < 1e-9 * swe.tm[SphericalWaveExpansion::index(1, 0)].norm());
256        let minus = swe.far_field(1.0, 0.5, TimeConvention::MinusI);
257        assert!((minus[0] - swe.far_field(1.0, 0.5, TimeConvention::PlusJ)[0].conj()).norm() < 1e-15);
258        assert!(SphericalWaveExpansion::from_far_field(pattern, F, 0, TimeConvention::PlusJ).is_err());
259    }
260}