Skip to main content

lib_jsl_electromagnetics/algorithms/
method_of_moments.rs

1//! The method of moments for straight thin-wire antennas (Hallén's integral equation).
2//!
3//! A centre-fed straight wire of length `L` and radius `a ≪ λ` along z carries a current `I(z)`
4//! with `I(±L/2) = 0`. Hallén's equation (engineering convention `e^{+jωt}`) for a delta-gap
5//! voltage `V` is
6//!
7//! `∫ I(z') G(z − z') dz' = C cos kz − (jV / 2η) sin k|z|`,  `G = e^{−jkR} / (4πR)`,
8//! `R = √((z − z')² + a²)` (the reduced kernel),
9//!
10//! with an unknown constant `C`. The current is expanded in triangle functions on `N` interior
11//! nodes and the equation matched at those nodes and at the wire end, giving a square system for
12//! the node currents and `C`. The near-singular `1/R` part of the kernel is integrated
13//! analytically and the smooth remainder by Gauss-Legendre quadrature.
14//!
15//! See the book entry [The method of moments for wire antennas](https://jwkunz.github.io/lib_jsl/book/em-waves/method-of-moments.html).
16
17use crate::conventions::{C64, Medium, TimeConvention};
18use lib_jsl_core::ErrorsJSL;
19use lib_jsl_core::constants::em::C0;
20use std::f64::consts::{PI, TAU};
21
22/// A centre-fed straight wire dipole along z.
23#[derive(Debug, Clone, Copy, PartialEq)]
24pub struct WireDipole {
25    pub length: f64,
26    pub radius: f64,
27}
28
29/// The moment-method solution at one frequency for a 1 V delta-gap excitation.
30#[derive(Debug, Clone)]
31pub struct WireSolution {
32    pub frequency: f64,
33    /// Node positions along the wire (m), ends excluded (where the current is zero).
34    pub nodes: Vec<f64>,
35    /// Node currents (A) for 1 V across the gap, in the `e^{+jωt}` convention.
36    pub currents: Vec<C64>,
37    /// The input impedance `V / I(0)` (Ω).
38    pub input_impedance: C64,
39    length: f64,
40}
41
42const GAUSS_8: [(f64, f64); 8] = [
43    (-0.960_289_856_497_536_2, 0.101_228_536_290_376_26),
44    (-0.796_666_477_413_626_7, 0.222_381_034_453_374_47),
45    (-0.525_532_409_916_329, 0.313_706_645_877_887_3),
46    (-0.183_434_642_495_649_8, 0.362_683_783_378_362),
47    (0.183_434_642_495_649_8, 0.362_683_783_378_362),
48    (0.525_532_409_916_329, 0.313_706_645_877_887_3),
49    (0.796_666_477_413_626_7, 0.222_381_034_453_374_47),
50    (0.960_289_856_497_536_2, 0.101_228_536_290_376_26),
51];
52
53/// `∫_{u0}^{u1} (α + βu) / √(u² + a²) du`.
54fn linear_over_r(alpha: f64, beta: f64, u0: f64, u1: f64, a: f64) -> f64 {
55    let f = |u: f64| alpha * (u / a).asinh() + beta * (u * u + a * a).sqrt();
56    f(u1) - f(u0)
57}
58
59/// Solves `A x = b` for a dense complex system by Gaussian elimination with partial pivoting.
60fn solve_complex(mut a: Vec<Vec<C64>>, mut b: Vec<C64>) -> Result<Vec<C64>, ErrorsJSL> {
61    let n = b.len();
62    for k in 0..n {
63        let p = (k..n).max_by(|&i, &j| a[i][k].norm().total_cmp(&a[j][k].norm())).expect("non-empty");
64        if a[p][k].norm() < 1e-300 {
65            return Err(ErrorsJSL::RuntimeError("The moment matrix is singular."));
66        }
67        a.swap(k, p);
68        b.swap(k, p);
69        for i in k + 1..n {
70            let m = a[i][k] / a[k][k];
71            let (top, rest) = a.split_at_mut(i);
72            rest[0][k..].iter_mut().zip(&top[k][k..]).for_each(|(x, y)| *x -= m * y);
73            b[i] = b[i] - m * b[k];
74        }
75    }
76    for i in (0..n).rev() {
77        let s: C64 = (i + 1..n).map(|j| a[i][j] * b[j]).sum();
78        b[i] = (b[i] - s) / a[i][i];
79    }
80    Ok(b)
81}
82
83impl WireDipole {
84    pub fn new(length: f64, radius: f64) -> Result<Self, ErrorsJSL> {
85        if length.is_nan() || radius.is_nan() || length <= 0.0 || radius <= 0.0 || radius * 20.0 > length {
86            return Err(ErrorsJSL::InvalidInputRange("Need a thin wire: 0 < 20 a < L."));
87        }
88        Ok(WireDipole { length, radius })
89    }
90
91    /// Solves for the current with `interior_nodes` (odd, so a node sits at the feed) at
92    /// `frequency`. Segments should stay longer than a few radii for the thin-wire kernel.
93    pub fn solve(&self, frequency: f64, interior_nodes: usize) -> Result<WireSolution, ErrorsJSL> {
94        if interior_nodes < 3 || interior_nodes.is_multiple_of(2) || frequency.is_nan() || frequency <= 0.0 {
95            return Err(ErrorsJSL::InvalidInputRange("Need an odd number (>= 3) of interior nodes and a positive frequency."));
96        }
97        let n = interior_nodes;
98        let (h, a) = (self.length / 2.0, self.radius);
99        let k = TAU * frequency / C0;
100        let eta = Medium::VACUUM.impedance(TimeConvention::PlusJ).re;
101        let delta = self.length / (n + 1) as f64;
102        let node = |i: usize| -h + i as f64 * delta; // i = 0 ..= n + 1, ends at 0 and n + 1
103        // Match at the interior nodes and at one end: midpoint matching against triangle bases
104        // decouples alternate nodes and makes the current oscillate.
105        let matches: Vec<f64> = (1..=n).map(node).chain(std::iter::once(h)).collect();
106        let j = C64::new(0.0, 1.0);
107        let mut matrix = vec![vec![C64::new(0.0, 0.0); n + 1]; n + 1];
108        let mut rhs = vec![C64::new(0.0, 0.0); n + 1];
109        // ANCHOR: hallen_fill
110        for (m, &z) in matches.iter().enumerate() {
111            for (col, entry) in matrix[m].iter_mut().take(n).enumerate() {
112                let (left, centre, right) = (node(col), node(col + 1), node(col + 2));
113                // Analytic part: ∫ Λ(z') / (4πR) dz' on both halves of the triangle.
114                let mut value = C64::new(
115                    (linear_over_r((z - left) / delta, 1.0 / delta, left - z, centre - z, a) + linear_over_r((right - z) / delta, -1.0 / delta, centre - z, right - z, a)) / (4.0 * PI),
116                    0.0,
117                );
118                // Smooth part: (e^{−jkR} − 1) / (4πR), finite as R → a.
119                for (lo, hi, rising) in [(left, centre, true), (centre, right, false)] {
120                    let (mid, half) = (0.5 * (lo + hi), 0.5 * (hi - lo));
121                    for &(x, w) in &GAUSS_8 {
122                        let zp = mid + half * x;
123                        let shape = if rising { (zp - lo) / delta } else { (hi - zp) / delta };
124                        let r = ((z - zp).powi(2) + a * a).sqrt();
125                        value += w * half * shape * ((-j * k * r).exp() - 1.0) / (4.0 * PI * r);
126                    }
127                }
128                *entry = value;
129            }
130            matrix[m][n] = C64::new(-(k * z).cos(), 0.0);
131            rhs[m] = -j / (2.0 * eta) * (k * z.abs()).sin();
132        }
133        // ANCHOR_END: hallen_fill
134        let x = solve_complex(matrix, rhs)?;
135        let currents = x[..n].to_vec();
136        let feed = currents[n / 2];
137        Ok(WireSolution { frequency, nodes: (1..=n).map(node).collect(), currents, input_impedance: C64::new(1.0, 0.0) / feed, length: self.length })
138    }
139}
140
141impl WireSolution {
142    /// The far field `E_θ` (V, with `e^{−jkr}/r` removed) at polar angle `θ` for the 1 V feed:
143    /// `jηk sinθ / (4π) ∫ I(z') e^{jkz' cosθ} dz'`, integrating the piecewise-linear current
144    /// exactly segment by segment with Gauss quadrature.
145    pub fn far_field_theta(&self, theta: f64, convention: TimeConvention) -> C64 {
146        let k = TAU * self.frequency / C0;
147        let eta = Medium::VACUUM.impedance(TimeConvention::PlusJ).re;
148        let h = self.length / 2.0;
149        let mut z: Vec<f64> = vec![-h];
150        z.extend(&self.nodes);
151        z.push(h);
152        let mut i: Vec<C64> = vec![C64::new(0.0, 0.0)];
153        i.extend(&self.currents);
154        i.push(C64::new(0.0, 0.0));
155        let mut integral = C64::new(0.0, 0.0);
156        for s in 0..z.len() - 1 {
157            let (mid, half) = (0.5 * (z[s] + z[s + 1]), 0.5 * (z[s + 1] - z[s]));
158            for &(x, w) in &GAUSS_8 {
159                let current = i[s] + (i[s + 1] - i[s]) * (0.5 * (x + 1.0));
160                integral += w * half * current * C64::from_polar(1.0, k * (mid + half * x) * theta.cos());
161            }
162        }
163        let value = C64::new(0.0, eta * k * theta.sin() / (4.0 * PI)) * integral;
164        TimeConvention::PlusJ.convert(value, convention)
165    }
166
167    /// The radiated power (W) for the 1 V feed by integrating `|E_θ|² / (2η)` over the sphere.
168    pub fn radiated_power(&self) -> f64 {
169        let eta = Medium::VACUUM.impedance(TimeConvention::PlusJ).re;
170        let steps = 720;
171        let d = PI / steps as f64;
172        (0..steps)
173            .map(|s| {
174                let theta = (s as f64 + 0.5) * d;
175                self.far_field_theta(theta, TimeConvention::PlusJ).norm_sqr() / (2.0 * eta) * TAU * theta.sin() * d
176            })
177            .sum()
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    const F: f64 = 300e6;
186
187    fn lambda() -> f64 {
188        C0 / F
189    }
190
191    #[test]
192    fn half_wave_dipole_impedance_and_power_balance() {
193        let dipole = WireDipole::new(0.5 * lambda(), 1e-4 * lambda()).unwrap();
194        let solution = dipole.solve(F, 61).unwrap();
195        let z = solution.input_impedance;
196        // Thin-wire limit 73 + j42.5 Ω; a finite radius raises both a little.
197        assert!(z.re > 70.0 && z.re < 90.0 && z.im > 30.0 && z.im < 55.0, "{z}");
198        // Power conservation: the radiated power equals the power delivered, ½ Re(Z) |I|².
199        let delivered = 0.5 * (C64::new(1.0, 0.0) / z.conj()).re;
200        assert!((solution.radiated_power() / delivered - 1.0).abs() < 0.02, "{} vs {delivered}", solution.radiated_power());
201        // The current is close to the sinusoid cos(kz) of a half-wave dipole.
202        let k = TAU / lambda();
203        let feed = solution.currents[30];
204        for (z, i) in solution.nodes.iter().zip(&solution.currents).step_by(6) {
205            assert!(((i / feed).norm() - (k * z).cos()).abs() < 0.1, "z={z}");
206        }
207    }
208
209    #[test]
210    fn resonance_falls_just_short_of_half_a_wavelength_and_converges() {
211        let reactance = |fraction: f64| WireDipole::new(fraction * lambda(), 1e-3 * lambda()).unwrap().solve(F, 41).unwrap().input_impedance.im;
212        assert!(reactance(0.45) < 0.0 && reactance(0.5) > 0.0);
213        // Bisect the resonant length.
214        let (mut lo, mut hi) = (0.45, 0.5);
215        for _ in 0..30 {
216            let mid = 0.5 * (lo + hi);
217            if reactance(mid) < 0.0 { lo = mid } else { hi = mid }
218        }
219        assert!(lo > 0.46 && lo < 0.49, "{lo}");
220        let resonant = WireDipole::new(lo * lambda(), 1e-3 * lambda()).unwrap().solve(F, 41).unwrap().input_impedance;
221        assert!(resonant.re > 55.0 && resonant.re < 75.0, "{resonant}");
222        // Refining the mesh changes the impedance little.
223        let d = WireDipole::new(0.5 * lambda(), 1e-3 * lambda()).unwrap();
224        let (coarse, fine) = (d.solve(F, 41).unwrap().input_impedance, d.solve(F, 81).unwrap().input_impedance);
225        assert!((coarse - fine).norm() < 0.03 * fine.norm(), "{coarse} {fine}");
226        assert!(d.solve(F, 40).is_err() && WireDipole::new(1.0, 0.1).is_err());
227    }
228
229    #[test]
230    fn short_dipole_matches_the_hertzian_radiation_resistance() {
231        // A short dipole's triangular current gives R = 20π² (L/λ)² (a quarter of the uniform case).
232        // The delta-gap feed adds a gap capacitance that grows slowly as the mesh is refined, which
233        // lowers R a little below the ideal value, so allow 15% on a coarse mesh.
234        let l = 0.05 * lambda();
235        let solution = WireDipole::new(l, 1e-4 * lambda()).unwrap().solve(F, 11).unwrap();
236        let expected = 20.0 * PI * PI * 0.05f64.powi(2);
237        assert!((solution.input_impedance.re / expected - 1.0).abs() < 0.15, "{} vs {expected}", solution.input_impedance.re);
238        // R scales as (L/λ)².
239        let half = WireDipole::new(l / 2.0, 0.5e-4 * lambda()).unwrap().solve(F, 11).unwrap();
240        assert!((solution.input_impedance.re / half.input_impedance.re / 4.0 - 1.0).abs() < 0.05);
241        assert!(solution.input_impedance.im < -100.0); // strongly capacitive
242        let peak = solution.far_field_theta(std::f64::consts::FRAC_PI_2, TimeConvention::PlusJ);
243        assert!((solution.far_field_theta(0.3, TimeConvention::MinusI) - solution.far_field_theta(0.3, TimeConvention::PlusJ).conj()).norm() < 1e-12 * peak.norm());
244    }
245}