Skip to main content

lib_jsl_electromagnetics/algorithms/
fdtd.rs

1//! Finite-difference time-domain (FDTD) solvers on Yee grids.
2//!
3//! * [`Fdtd1D`]: `E_z`, `H_y` along x with per-cell permittivity, permeability and conductivity,
4//!   and first-order Mur absorbing ends (exact at the magic time step, Courant number 1).
5//! * [`FdtdTmz`]: the 2D transverse-magnetic mode (`E_z`, `H_x`, `H_y`) with a graded Berenger
6//!   split-field perfectly matched layer around the domain, per-cell permittivity and perfect
7//!   electric conductors.
8//!
9//! Fields use the normalised magnetic field `H̃ = η₀ H` so `E` and `H̃` share units, and the time
10//! step is `Δt = S Δ / c` for Courant number `S` (`S ≤ 1` in 1D, `S ≤ 1/√2` in 2D).
11//!
12//! See the book entry [The finite-difference time-domain method](https://jwkunz.github.io/lib_jsl/book/em-waves/fdtd.html).
13
14use lib_jsl_core::ErrorsJSL;
15use lib_jsl_core::constants::em::{C0, EPS_0};
16
17/// A one-dimensional FDTD grid.
18#[derive(Debug, Clone)]
19pub struct Fdtd1D {
20    pub ez: Vec<f64>,
21    /// `η₀ H_y`, located half a cell to the right of `ez[i]`.
22    pub hy: Vec<f64>,
23    eps_r: Vec<f64>,
24    mu_r: Vec<f64>,
25    sigma: Vec<f64>,
26    courant: f64,
27    dx: f64,
28    steps: usize,
29}
30
31impl Fdtd1D {
32    pub fn new(cells: usize, dx: f64, courant: f64) -> Result<Self, ErrorsJSL> {
33        if cells < 3 || dx.is_nan() || dx <= 0.0 || !(courant > 0.0 && courant <= 1.0) {
34            return Err(ErrorsJSL::InvalidInputRange("Need at least 3 cells, dx > 0 and 0 < S <= 1."));
35        }
36        Ok(Fdtd1D { ez: vec![0.0; cells], hy: vec![0.0; cells - 1], eps_r: vec![1.0; cells], mu_r: vec![1.0; cells - 1], sigma: vec![0.0; cells], courant, dx, steps: 0 })
37    }
38
39    pub fn time_step(&self) -> f64 {
40        self.courant * self.dx / C0
41    }
42
43    pub fn time(&self) -> f64 {
44        self.steps as f64 * self.time_step()
45    }
46
47    /// Sets the material of cells `start..end`: relative permittivity, conductivity (S/m) and
48    /// relative permeability.
49    pub fn set_material(&mut self, start: usize, end: usize, eps_r: f64, sigma: f64, mu_r: f64) {
50        let end = end.min(self.ez.len());
51        for i in start..end {
52            self.eps_r[i] = eps_r;
53            self.sigma[i] = sigma;
54            if i < self.mu_r.len() {
55                self.mu_r[i] = mu_r;
56            }
57        }
58    }
59
60    /// Advances one time step; `source` is added to `E_z` at its index (a soft source).
61    pub fn step(&mut self, source: Option<(usize, f64)>) {
62        // ANCHOR: fdtd1d
63        let s = self.courant;
64        let n = self.ez.len();
65        for i in 0..n - 1 {
66            self.hy[i] += s / self.mu_r[i] * (self.ez[i + 1] - self.ez[i]);
67        }
68        let (old_left, old_right) = (self.ez[1], self.ez[n - 2]);
69        let dt = self.time_step();
70        for i in 1..n - 1 {
71            let loss = self.sigma[i] * dt / (2.0 * EPS_0 * self.eps_r[i]);
72            self.ez[i] = (1.0 - loss) / (1.0 + loss) * self.ez[i] + s / (self.eps_r[i] * (1.0 + loss)) * (self.hy[i] - self.hy[i - 1]);
73        }
74        if let Some((i, value)) = source {
75            self.ez[i] += value;
76        }
77        // First-order Mur boundaries with the local Courant number.
78        let mur = |s_local: f64| (s_local - 1.0) / (s_local + 1.0);
79        let (sl, sr) = (s / self.eps_r[0].sqrt(), s / self.eps_r[n - 1].sqrt());
80        self.ez[0] = old_left + mur(sl) * (self.ez[1] - self.ez[0]);
81        self.ez[n - 1] = old_right + mur(sr) * (self.ez[n - 2] - self.ez[n - 1]);
82        // ANCHOR_END: fdtd1d
83        self.steps += 1;
84    }
85}
86
87/// A two-dimensional TMz FDTD grid with a perfectly matched layer.
88#[derive(Debug, Clone)]
89pub struct FdtdTmz {
90    nx: usize,
91    ny: usize,
92    courant: f64,
93    delta: f64,
94    ezx: Vec<f64>,
95    ezy: Vec<f64>,
96    /// `η₀ H_x` at `(i, j + ½)`.
97    pub hx: Vec<f64>,
98    /// `η₀ H_y` at `(i + ½, j)`.
99    pub hy: Vec<f64>,
100    eps_r: Vec<f64>,
101    pec: Vec<bool>,
102    sigma_x: Vec<f64>,
103    sigma_y: Vec<f64>,
104    steps: usize,
105}
106
107impl FdtdTmz {
108    /// An `nx × ny` grid of square cells of side `delta` with a PML of `pml_cells` on every side,
109    /// graded polynomially (order 3) for a normal-incidence reflection of about 1e-6.
110    pub fn new(nx: usize, ny: usize, delta: f64, courant: f64, pml_cells: usize) -> Result<Self, ErrorsJSL> {
111        if nx < 2 * pml_cells + 3 || ny < 2 * pml_cells + 3 || delta.is_nan() || delta <= 0.0 || !(courant > 0.0 && courant <= std::f64::consts::FRAC_1_SQRT_2) {
112            return Err(ErrorsJSL::InvalidInputRange("Need room inside the PML, delta > 0 and 0 < S <= 1/√2."));
113        }
114        // Normalised conductivity σΔt/(2ε₀) at depth d (cells) into the layer.
115        let order = 3.0;
116        let s_max = -(order + 1.0) * (1e-6f64).ln() * courant / (4.0 * pml_cells.max(1) as f64);
117        let profile = |index: f64, cells: usize| -> f64 {
118            if pml_cells == 0 {
119                return 0.0;
120            }
121            let depth = if index < pml_cells as f64 { pml_cells as f64 - index } else if index > (cells - 1 - pml_cells) as f64 { index - (cells - 1 - pml_cells) as f64 } else { 0.0 };
122            s_max * (depth / pml_cells as f64).powf(order)
123        };
124        let size = nx * ny;
125        let mut sigma_x = vec![0.0; size];
126        let mut sigma_y = vec![0.0; size];
127        for j in 0..ny {
128            for i in 0..nx {
129                sigma_x[j * nx + i] = profile(i as f64, nx);
130                sigma_y[j * nx + i] = profile(j as f64, ny);
131            }
132        }
133        Ok(FdtdTmz { nx, ny, courant, delta, ezx: vec![0.0; size], ezy: vec![0.0; size], hx: vec![0.0; size], hy: vec![0.0; size], eps_r: vec![1.0; size], pec: vec![false; size], sigma_x, sigma_y, steps: 0 })
134    }
135
136    fn id(&self, i: usize, j: usize) -> usize {
137        j * self.nx + i
138    }
139
140    pub fn dimensions(&self) -> (usize, usize) {
141        (self.nx, self.ny)
142    }
143
144    pub fn time_step(&self) -> f64 {
145        self.courant * self.delta / C0
146    }
147
148    pub fn time(&self) -> f64 {
149        self.steps as f64 * self.time_step()
150    }
151
152    /// `E_z` at node `(i, j)`.
153    pub fn ez(&self, i: usize, j: usize) -> f64 {
154        let k = self.id(i, j);
155        self.ezx[k] + self.ezy[k]
156    }
157
158    /// Sets the relative permittivity in the box `[i0, i1) × [j0, j1)`.
159    pub fn set_permittivity(&mut self, i0: usize, i1: usize, j0: usize, j1: usize, eps_r: f64) {
160        for j in j0..j1.min(self.ny) {
161            for i in i0..i1.min(self.nx) {
162                let k = self.id(i, j);
163                self.eps_r[k] = eps_r;
164            }
165        }
166    }
167
168    /// Makes the box `[i0, i1) × [j0, j1)` a perfect electric conductor (`E_z = 0`).
169    pub fn set_pec(&mut self, i0: usize, i1: usize, j0: usize, j1: usize) {
170        for j in j0..j1.min(self.ny) {
171            for i in i0..i1.min(self.nx) {
172                let k = self.id(i, j);
173                self.pec[k] = true;
174            }
175        }
176    }
177
178    /// Advances one time step with an optional soft source added to `E_z` at `(i, j)`.
179    pub fn step(&mut self, source: Option<(usize, usize, f64)>) {
180        let (nx, ny, s) = (self.nx, self.ny, self.courant);
181        // Magnetic fields with matched magnetic conductivity.
182        for j in 0..ny - 1 {
183            for i in 0..nx {
184                let k = j * nx + i;
185                let sy = 0.5 * (self.sigma_y[k] + self.sigma_y[k + nx]);
186                let curl = self.ezx[k + nx] + self.ezy[k + nx] - self.ezx[k] - self.ezy[k];
187                self.hx[k] = (1.0 - sy) / (1.0 + sy) * self.hx[k] - s / (1.0 + sy) * curl;
188            }
189        }
190        for j in 0..ny {
191            for i in 0..nx - 1 {
192                let k = j * nx + i;
193                let sx = 0.5 * (self.sigma_x[k] + self.sigma_x[k + 1]);
194                let curl = self.ezx[k + 1] + self.ezy[k + 1] - self.ezx[k] - self.ezy[k];
195                self.hy[k] = (1.0 - sx) / (1.0 + sx) * self.hy[k] + s / (1.0 + sx) * curl;
196            }
197        }
198        // Split electric field; the outermost nodes stay zero (PEC backing the PML).
199        for j in 1..ny - 1 {
200            for i in 1..nx - 1 {
201                let k = j * nx + i;
202                if self.pec[k] {
203                    self.ezx[k] = 0.0;
204                    self.ezy[k] = 0.0;
205                    continue;
206                }
207                let (sx, sy, e) = (self.sigma_x[k], self.sigma_y[k], self.eps_r[k]);
208                self.ezx[k] = (1.0 - sx) / (1.0 + sx) * self.ezx[k] + s / (e * (1.0 + sx)) * (self.hy[k] - self.hy[k - 1]);
209                self.ezy[k] = (1.0 - sy) / (1.0 + sy) * self.ezy[k] - s / (e * (1.0 + sy)) * (self.hx[k] - self.hx[k - nx]);
210            }
211        }
212        if let Some((i, j, value)) = source {
213            let k = self.id(i, j);
214            self.ezx[k] += 0.5 * value;
215            self.ezy[k] += 0.5 * value;
216        }
217        self.steps += 1;
218    }
219
220    /// The electromagnetic energy proxy `Σ (ε_r E_z² + H̃²)` over the interior (outside the PML).
221    pub fn interior_energy(&self, pml_cells: usize) -> f64 {
222        let mut total = 0.0;
223        for j in pml_cells..self.ny - pml_cells {
224            for i in pml_cells..self.nx - pml_cells {
225                let k = self.id(i, j);
226                total += self.eps_r[k] * (self.ezx[k] + self.ezy[k]).powi(2) + self.hx[k].powi(2) + self.hy[k].powi(2);
227            }
228        }
229        total
230    }
231}
232
233/// A Gaussian pulse `exp(−((n − delay)/width)²)` in time steps.
234pub fn gaussian_pulse(step: usize, delay: f64, width: f64) -> f64 {
235    (-((step as f64 - delay) / width).powi(2)).exp()
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn one_dimensional_pulses_travel_at_c_and_leave_through_mur_boundaries() {
244        let mut grid = Fdtd1D::new(400, 1e-3, 1.0).unwrap();
245        for n in 0..60 {
246            grid.step(Some((200, gaussian_pulse(n, 30.0, 8.0))));
247        }
248        // Two pulses moving one cell per step away from the source (peak injected at step 30).
249        for _ in 0..100 {
250            grid.step(None);
251        }
252        let right = (200..400).max_by(|&a, &b| grid.ez[a].abs().total_cmp(&grid.ez[b].abs())).unwrap();
253        assert!((right as i64 - (200 + 130)).abs() <= 1, "{right}");
254        assert!((grid.time() - 160.0 * 1e-3 / C0).abs() < 1e-18);
255        for _ in 0..400 {
256            grid.step(None);
257        }
258        let residual = grid.ez.iter().fold(0.0f64, |m, v| m.max(v.abs()));
259        // Mur boundaries are exact at S = 1; a soft source leaves only a tiny residue.
260        assert!(residual < 1e-5, "{residual}");
261    }
262
263    #[test]
264    fn dielectric_interface_reflects_with_the_fresnel_coefficient() {
265        // ε_r = 4: reflection (1 − 2)/(1 + 2) = −1/3, transmission 2/3.
266        let mut grid = Fdtd1D::new(1200, 1e-3, 0.5).unwrap();
267        grid.set_material(600, 1200, 4.0, 0.0, 1.0);
268        let (mut incident, mut reflected, mut transmitted) = (0.0f64, 0.0f64, 0.0f64);
269        for n in 0..2000 {
270            // A total-field source would be cleaner; record at a probe before and after reflection.
271            grid.step(Some((300, gaussian_pulse(n, 120.0, 40.0))));
272            if n < 700 {
273                incident = incident.max(grid.ez[450].abs());
274            } else {
275                reflected = if grid.ez[450].abs() > reflected.abs() { grid.ez[450] } else { reflected };
276            }
277            transmitted = transmitted.max(grid.ez[800].abs());
278        }
279        // Grid dispersion in the slower medium costs a little transmitted peak amplitude.
280        assert!((reflected / incident + 1.0 / 3.0).abs() < 0.03, "{}", reflected / incident);
281        assert!((transmitted / incident - 2.0 / 3.0).abs() < 0.03, "{}", transmitted / incident);
282        assert!(Fdtd1D::new(10, 1e-3, 1.5).is_err());
283    }
284
285    #[test]
286    fn two_dimensional_pml_absorbs_an_outgoing_cylindrical_wave() {
287        let (n, pml) = (120, 12);
288        let mut small = FdtdTmz::new(n, n, 1e-3, 0.5, pml).unwrap();
289        let big_n = 3 * n;
290        let mut big = FdtdTmz::new(big_n, big_n, 1e-3, 0.5, pml).unwrap();
291        let (c, bc) = (n / 2, big_n / 2);
292        let (mut worst, mut peak, mut energy) = (0.0f64, 0.0f64, 0.0f64);
293        for step in 0..260 {
294            let pulse = gaussian_pulse(step, 40.0, 12.0);
295            small.step(Some((c, c, pulse)));
296            big.step(Some((bc, bc, pulse)));
297            // A probe 40 cells from the source; the big grid is reflection-free for this window.
298            let (a, b) = (small.ez(c + 40, c), big.ez(bc + 40, bc));
299            worst = worst.max((a - b).abs());
300            peak = peak.max(b.abs());
301            energy = energy.max(small.interior_energy(pml));
302            // Cylindrical symmetry.
303            assert!((small.ez(c + 25, c) - small.ez(c, c + 25)).abs() < 1e-9 * (1.0 + peak));
304        }
305        assert!(worst < 0.01 * peak, "PML reflection {:.2e} of {:.2e}", worst, peak);
306        for _ in 0..600 {
307            small.step(None);
308        }
309        // What remains after the wave has left is a small fraction of the peak interior energy.
310        assert!(small.interior_energy(pml) < 1e-3 * energy, "{} of {energy}", small.interior_energy(pml));
311    }
312
313    #[test]
314    fn a_conducting_wall_reflects_with_a_phase_reversal() {
315        let mut grid = FdtdTmz::new(200, 60, 1e-3, 0.5, 10);
316        let g = grid.as_mut().unwrap();
317        g.set_pec(150, 152, 0, 60);
318        g.set_permittivity(0, 1, 0, 1, 1.0);
319        let mut most_negative = 0.0f64;
320        for step in 0..500 {
321            // A line source across the guide approximates a plane wave.
322            for j in 11..49 {
323                let k = g.id(60, j);
324                let pulse = gaussian_pulse(step, 40.0, 10.0);
325                g.ezx[k] += 0.5 * pulse;
326                g.ezy[k] += 0.5 * pulse;
327            }
328            g.step(None);
329            if step > 200 {
330                most_negative = most_negative.min(g.ez(100, 30));
331            }
332        }
333        assert!(most_negative < -0.1, "{most_negative}");
334        assert_eq!(g.ez(150, 30), 0.0);
335        assert_eq!(g.dimensions(), (200, 60));
336    }
337}