Skip to main content

lib_jsl_electromagnetics/algorithms/
near_field_far_field.rs

1//! Near-field to far-field transformation from measured or simulated tangential fields.
2//!
3//! * [`planar_near_to_far`]: tangential `E_x, E_y` sampled on a plane `z = z₀` in front of the
4//!   antenna give its plane-wave spectrum `A(k_x, k_y) = e^{jk_z z₀} ∬ E_t e^{j(k_x x + k_y y)} dx dy`,
5//!   and the far field follows by stationary phase,
6//!   `F_θ = (jk/2π)(A_x cos φ + A_y sin φ)`, `F_φ = (jk cos θ/2π)(A_y cos φ − A_x sin φ)`
7//!   (forward half-space only; the scan must be sampled at `≤ λ/2`). Truncating the scan
8//!   abruptly rings like a rectangular window; tapering the outer part with [`scan_taper`]
9//!   suppresses it.
10//! * [`spherical_near_to_far`]: tangential `E_θ, E_φ` on a sphere of radius `r₀` enclosing the
11//!   antenna are projected onto the vector spherical harmonics, and dividing by the radial wave
12//!   functions gives the spherical wave amplitudes, hence the far field in every direction.
13//!
14//! The engineering convention `e^{+jωt}` is used internally; inputs and outputs are converted.
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, TimeConvention};
19use crate::fields::spherical_waves::{SphericalWaveExpansion, gauss_legendre, hankel, vector_spherical_harmonics};
20use lib_jsl_core::ErrorsJSL;
21use lib_jsl_core::constants::em::C0;
22use ndarray::Array2;
23use std::f64::consts::{FRAC_PI_2, TAU};
24
25/// Raised-cosine edge weights for scan coordinates: 1 in the inner `1 − fraction` of the
26/// half-extent, rolling smoothly to 0 at the edges. Multiply the sampled fields by
27/// `w(x_i) w(y_j)` to suppress truncation ripple in [`planar_near_to_far`].
28pub fn scan_taper(coordinates: &[f64], fraction: f64) -> Vec<f64> {
29    let half = coordinates.iter().fold(0.0f64, |m, c| m.max(c.abs())).max(f64::MIN_POSITIVE);
30    let start = 1.0 - fraction.clamp(0.0, 1.0);
31    coordinates
32        .iter()
33        .map(|c| {
34            let r = c.abs() / half;
35            if r <= start || fraction <= 0.0 { 1.0 } else { 0.5 * (1.0 + (std::f64::consts::PI * (r - start) / (1.0 - start)).cos()) }
36        })
37        .collect()
38}
39
40/// The far field `[F_θ, F_φ]` (V, `e^{−jkr}/r` removed) in each direction `(θ, φ)` with
41/// `θ < π/2`, from `E_x[[i, j]]`, `E_y[[i, j]]` sampled at `(xs[i], ys[j], z0)` on a uniform grid.
42#[allow(clippy::too_many_arguments)]
43pub fn planar_near_to_far(xs: &[f64], ys: &[f64], ex: &Array2<C64>, ey: &Array2<C64>, z0: f64, frequency: f64, directions: &[(f64, f64)], convention: TimeConvention) -> Result<Vec<[C64; 2]>, ErrorsJSL> {
44    if xs.len() < 2 || ys.len() < 2 || ex.dim() != (xs.len(), ys.len()) || ey.dim() != ex.dim() {
45        return Err(ErrorsJSL::InvalidInputRange("The field arrays must match the grid of at least 2 × 2 points."));
46    }
47    if directions.iter().any(|&(t, _)| !(0.0..FRAC_PI_2).contains(&t)) {
48        return Err(ErrorsJSL::InvalidInputRange("Planar transformation covers only the forward half-space (θ < π/2)."));
49    }
50    let k = TAU * frequency / C0;
51    let (dx, dy) = (xs[1] - xs[0], ys[1] - ys[0]);
52    let to_plus = |v: C64| convention.convert(v, TimeConvention::PlusJ);
53    let j = C64::new(0.0, 1.0);
54    Ok(directions
55        .iter()
56        .map(|&(theta, phi)| {
57            // ANCHOR: planar_spectrum
58            let (kx, ky, kz) = (k * theta.sin() * phi.cos(), k * theta.sin() * phi.sin(), k * theta.cos());
59            // Separable phase factors.
60            let px: Vec<C64> = xs.iter().map(|&x| C64::from_polar(1.0, kx * x)).collect();
61            let py: Vec<C64> = ys.iter().map(|&y| C64::from_polar(1.0, ky * y)).collect();
62            let (mut ax, mut ay) = (C64::new(0.0, 0.0), C64::new(0.0, 0.0));
63            for (i, fx) in px.iter().enumerate() {
64                for (jj, fy) in py.iter().enumerate() {
65                    let w = fx * fy;
66                    ax += to_plus(ex[[i, jj]]) * w;
67                    ay += to_plus(ey[[i, jj]]) * w;
68                }
69            }
70            let shift = C64::from_polar(dx * dy, kz * z0);
71            let (ax, ay) = (ax * shift, ay * shift);
72            let (s, c) = phi.sin_cos();
73            let f_theta = j * k / TAU * (ax * c + ay * s);
74            let f_phi = j * k * theta.cos() / TAU * (ay * c - ax * s);
75            // ANCHOR_END: planar_spectrum
76            [f_theta, f_phi].map(|v| TimeConvention::PlusJ.convert(v, convention))
77        })
78        .collect())
79}
80
81/// The spherical wave expansion (and hence the far field) of an antenna from the tangential
82/// field `[E_θ, E_φ]` on a sphere of radius `r0` enclosing it, truncated at `max_degree`
83/// (about `k r_min + 10` for a minimum sphere of radius `r_min`). `field(θ, φ)` is sampled at the
84/// Gauss-Legendre × uniform quadrature points of that degree.
85pub fn spherical_near_to_far<F>(field: F, r0: f64, frequency: f64, max_degree: u32, convention: TimeConvention) -> Result<SphericalWaveExpansion, ErrorsJSL>
86where
87    F: Fn(f64, f64) -> [C64; 2],
88{
89    if max_degree == 0 || r0.is_nan() || r0 <= 0.0 || frequency.is_nan() || frequency <= 0.0 {
90        return Err(ErrorsJSL::InvalidInputRange("Need a positive radius, frequency and maximum degree."));
91    }
92    let size = SphericalWaveExpansion::index(max_degree, max_degree as i32) + 1;
93    let (mut a, mut b) = (vec![C64::new(0.0, 0.0); size], vec![C64::new(0.0, 0.0); size]);
94    let thetas = gauss_legendre(max_degree as usize + 2);
95    let phis = 2 * max_degree as usize + 2;
96    for &(x, w) in &thetas {
97        let theta = x.acos();
98        for p in 0..phis {
99            let phi = TAU * p as f64 / phis as f64;
100            let e = field(theta, phi).map(|v| convention.convert(v, TimeConvention::PlusJ));
101            let weight = w * TAU / phis as f64;
102            for n in 1..=max_degree {
103                for m in -(n as i32)..=n as i32 {
104                    let (psi, phv) = vector_spherical_harmonics(n, m, theta, phi);
105                    let i = SphericalWaveExpansion::index(n, m);
106                    a[i] += weight * (e[0] * psi[0].conj() + e[1] * psi[1].conj());
107                    b[i] += weight * (e[0] * phv[0].conj() + e[1] * phv[1].conj());
108                }
109            }
110        }
111    }
112    let kr = TAU * frequency / C0 * r0;
113    let (mut te, mut tm) = (vec![C64::new(0.0, 0.0); size], vec![C64::new(0.0, 0.0); size]);
114    for n in 1..=max_degree {
115        let (h, dh) = hankel(n, kr);
116        for m in -(n as i32)..=n as i32 {
117            let i = SphericalWaveExpansion::index(n, m);
118            // ⟨E, Φ⟩ = α h_n(kr₀) and ⟨E, Ψ⟩ = −β (kr₀ h_n)' / (kr₀).
119            te[i] = b[i] / h;
120            tm[i] = -a[i] * kr / dh;
121        }
122    }
123    Ok(SphericalWaveExpansion { frequency, max_degree, te, tm })
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use std::f64::consts::PI;
130    use crate::antenna_models::HertzianDipole;
131    use crate::coordinates::systems::Position;
132    use crate::conventions::Medium;
133
134    const F: f64 = 1e9;
135
136    fn lambda() -> f64 {
137        C0 / F
138    }
139
140    /// The exact Cartesian E of a unit-current dipole of length `l` along `axis` (unit) at the
141    /// Cartesian point `p`, built from the z-dipole by a rotation taking ẑ to `axis`.
142    fn dipole_cartesian(l: f64, axis: [f64; 3], p: [f64; 3]) -> [C64; 3] {
143        // An orthonormal frame (u, v, axis).
144        let a = axis;
145        let helper = if a[2].abs() < 0.9 { [0.0, 0.0, 1.0] } else { [1.0, 0.0, 0.0] };
146        let cross = |x: [f64; 3], y: [f64; 3]| [x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]];
147        let u = { let c = cross(helper, a); let n = (c[0] * c[0] + c[1] * c[1] + c[2] * c[2]).sqrt(); [c[0] / n, c[1] / n, c[2] / n] };
148        let v = cross(a, u);
149        let dot = |x: [f64; 3], y: [f64; 3]| x[0] * y[0] + x[1] * y[1] + x[2] * y[2];
150        let local = [dot(p, u), dot(p, v), dot(p, a)];
151        let (r, theta, phi) = { let r = dot(local, local).sqrt(); (r, (local[2] / r).acos(), local[1].atan2(local[0])) };
152        let (e, _) = HertzianDipole::new(l).near_field(&Position::spherical(r, theta, phi), F, TimeConvention::PlusJ);
153        let (st, ct, sp, cp) = (theta.sin(), theta.cos(), phi.sin(), phi.cos());
154        let lx = e[0] * st * cp + e[1] * ct * cp - e[2] * sp;
155        let ly = e[0] * st * sp + e[1] * ct * sp + e[2] * cp;
156        let lz = e[0] * ct - e[1] * st;
157        [0, 1, 2].map(|c| lx * u[c] + ly * v[c] + lz * a[c])
158    }
159
160    /// The analytic far field of that dipole: `−(jηkl/4π) (â − (â·r̂) r̂)` in θ, φ components.
161    fn dipole_far(l: f64, axis: [f64; 3], theta: f64, phi: f64) -> [C64; 2] {
162        let k = TAU / lambda();
163        let eta = Medium::VACUUM.impedance(TimeConvention::PlusJ).re;
164        let c = C64::new(0.0, -eta * k * l / (4.0 * PI));
165        let t_hat = [theta.cos() * phi.cos(), theta.cos() * phi.sin(), -theta.sin()];
166        let p_hat = [-phi.sin(), phi.cos(), 0.0];
167        let dot = |x: [f64; 3], y: [f64; 3]| x[0] * y[0] + x[1] * y[1] + x[2] * y[2];
168        [c * dot(axis, t_hat), c * dot(axis, p_hat)]
169    }
170
171    #[test]
172    fn spherical_scan_recovers_an_offset_dipole_exactly() {
173        // A dipole tilted and displaced 0.3λ from the origin excites many spherical modes.
174        let l = 0.01;
175        let axis = { let a = [0.3f64, -0.5, 0.8]; let n = (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt(); [a[0] / n, a[1] / n, a[2] / n] };
176        let offset = [0.3 * lambda(), 0.0, 0.1 * lambda()];
177        let r0 = 0.8 * lambda();
178        let field = |theta: f64, phi: f64| {
179            let p = Position::spherical(r0, theta, phi).to_cartesian();
180            let e = dipole_cartesian(l, axis, [p[0] - offset[0], p[1] - offset[1], p[2] - offset[2]]);
181            let t_hat = [theta.cos() * phi.cos(), theta.cos() * phi.sin(), -theta.sin()];
182            let p_hat = [-phi.sin(), phi.cos(), 0.0];
183            [e[0] * t_hat[0] + e[1] * t_hat[1] + e[2] * t_hat[2], e[0] * p_hat[0] + e[1] * p_hat[1]]
184        };
185        let swe = spherical_near_to_far(field, r0, F, 14, TimeConvention::PlusJ).unwrap();
186        let k = TAU / lambda();
187        for &(t, p) in &[(0.3f64, 0.2f64), (1.1, 2.5), (2.2, -1.0), (1.6, 4.0)] {
188            let r_hat = [t.sin() * p.cos(), t.sin() * p.sin(), t.cos()];
189            let phase = C64::from_polar(1.0, k * (r_hat[0] * offset[0] + r_hat[1] * offset[1] + r_hat[2] * offset[2]));
190            let want = dipole_far(l, axis, t, p).map(|v| v * phase);
191            let got = swe.far_field(t, p, TimeConvention::PlusJ);
192            let scale = (want[0].norm_sqr() + want[1].norm_sqr()).sqrt().max(1e-3);
193            assert!((got[0] - want[0]).norm() < 1e-6 * scale && (got[1] - want[1]).norm() < 1e-6 * scale, "({t}, {p}): {got:?} vs {want:?}");
194        }
195        assert!(spherical_near_to_far(field, 0.0, F, 5, TimeConvention::PlusJ).is_err());
196    }
197
198    #[test]
199    fn planar_scan_recovers_the_forward_pattern() {
200        // An x-directed dipole 2λ below a 24λ × 24λ scan plane sampled at λ/4, tapered over
201        // the outer 30% (without the taper the truncation ripple is about 10%).
202        let (l, axis) = (0.01, [1.0, 0.0, 0.0]);
203        let z0 = 2.0 * lambda();
204        let n = 97;
205        let coords: Vec<f64> = (0..n).map(|i| (i as f64 - 48.0) * lambda() / 4.0).collect();
206        let w = scan_taper(&coords, 0.3);
207        let mut ex = Array2::zeros((n, n));
208        let mut ey = Array2::zeros((n, n));
209        for (i, &x) in coords.iter().enumerate() {
210            for (j, &y) in coords.iter().enumerate() {
211                let e = dipole_cartesian(l, axis, [x, y, z0]);
212                ex[[i, j]] = e[0] * w[i] * w[j];
213                ey[[i, j]] = e[1] * w[i] * w[j];
214            }
215        }
216        let directions = [(0.0, 0.0), (0.3, 0.0), (0.4, FRAC_PI_2), (0.5, 0.8)];
217        let far = planar_near_to_far(&coords, &coords, &ex, &ey, z0, F, &directions, TimeConvention::PlusJ).unwrap();
218        let peak = dipole_far(l, axis, 0.0, 0.0)[0].norm();
219        for (&(t, p), got) in directions.iter().zip(&far) {
220            let want = dipole_far(l, axis, t, p);
221            assert!((got[0] - want[0]).norm() < 0.01 * peak && (got[1] - want[1]).norm() < 0.01 * peak, "({t}, {p}): {got:?} vs {want:?}");
222        }
223        // Conventions conjugate consistently.
224        let minus = planar_near_to_far(&coords, &coords, &ex.mapv(|v: C64| v.conj()), &ey.mapv(|v: C64| v.conj()), z0, F, &directions[..1], TimeConvention::MinusI).unwrap();
225        assert!((minus[0][0] - far[0][0].conj()).norm() < 1e-9 * peak);
226        assert!(planar_near_to_far(&coords, &coords, &ex, &ey, z0, F, &[(2.0, 0.0)], TimeConvention::PlusJ).is_err());
227        assert!(w[48] == 1.0 && w[0] < 1e-12 && scan_taper(&coords, 0.0).iter().all(|&v| v == 1.0));
228    }
229}