lib_jsl_electromagnetics/algorithms/
method_of_moments.rs1use 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#[derive(Debug, Clone, Copy, PartialEq)]
24pub struct WireDipole {
25 pub length: f64,
26 pub radius: f64,
27}
28
29#[derive(Debug, Clone)]
31pub struct WireSolution {
32 pub frequency: f64,
33 pub nodes: Vec<f64>,
35 pub currents: Vec<C64>,
37 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
53fn 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
59fn 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 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; 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 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 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 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 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 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 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 assert!(z.re > 70.0 && z.re < 90.0 && z.im > 30.0 && z.im < 55.0, "{z}");
198 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 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 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 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 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 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); 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}