Algorithm Search⌘K

Algorithmcore

Yee FDTD scheme

Also called finite-difference time-domain method, FDTD.

Solves Maxwell's equations with E and H on staggered grids and leapfrog time steps. Second order, and the discrete divergence of the fields stays constant.

Time
Θ(N M) worst
Space
Θ(M) extra
Where
M = the number of grid cells; N = the number of time steps
Properties
deterministicdivergence preservingexplicit
Origin
K. S. Yee, A. Taflove, 1966

The Yee scheme, the basis of the finite-difference time-domain (FDTD) method, solves Maxwell's equations εEt=∇×H\varepsilon E_t = \nabla\times H, μHt=−∇×E\mu H_t = -\nabla\times E on a staggered grid. Each component of EE sits at the centre of a cell edge and each component of HH at the centre of a cell face, so every curl is a centred difference over one cell. EE is computed at whole time steps and HH at half steps, and the two updates leapfrog over each other. The scheme is explicit, second order in space and time, and has no numerical dissipation. It keeps the discrete divergences of εE\varepsilon E (with no charges) and of μH\mu H constant exactly. It is stable for c Δt≤1/1/Δx2+1/Δy2+1/Δz2c\,\Delta t \le 1/\sqrt{1/\Delta x^2 + 1/\Delta y^2 + 1/\Delta z^2}. Kane Yee published it in 1966. With absorbing boundaries such as the perfectly matched layer, it is the standard method for antennas, scattering, photonics and microwave circuits.

In plain words

Electric and magnetic fields drive each other: a change in one makes a curl in the other. The Yee scheme puts the two fields on two grids, moved half a cell apart, so that each electric value sits in the middle of a loop of magnetic values, and the other way around. It also moves the two fields half a time step apart. Then each new electric value comes from the magnetic loop around it, and each new magnetic value comes from the electric loop around it. The steps go back and forth. Nothing needs to be solved, and the method uses only simple differences.

The problem

Solve Maxwell's equations in a region with given ε(x)\varepsilon(x) and μ(x)\mu(x), initial fields and boundary conditions, for a time TT. The reference code solves the two-dimensional transverse magnetic (TMz\text{TM}_z) case, where only EzE_z, HxH_x and HyH_y are nonzero:

ε ∂tEz=∂xHy−∂yHx,μ ∂tHx=−∂yEz,μ ∂tHy=∂xEz,\varepsilon\,\partial_tE_z = \partial_xH_y - \partial_yH_x,\qquad \mu\,\partial_tH_x = -\partial_yE_z,\qquad \mu\,\partial_tH_y = \partial_xE_z,

in a rectangle with perfectly conducting walls (Ez=0E_z = 0 on the boundary).

The algorithm

EzE_z sits at the nodes (iΔx,jΔy)(i\Delta x, j\Delta y), HxH_x at (iΔx,(j+12)Δy)(i\Delta x, (j + \tfrac12)\Delta y), and HyH_y at ((i+12)Δx,jΔy)((i + \tfrac12)\Delta x, j\Delta y). EzE_z is known at tn=nΔtt_n = n\Delta t and HH at tn−1/2t_{n-1/2}. One step:

  1. YEE-STEP(E_z, H_x, H_y, Δx, Δy, Δt)
  2. 1for each (i, j+1/2) do H_x ← H_x - (Δt/μΔy)(E_z[i, j+1] - E_z[i, j])
  3. 2for each (i+1/2, j) do H_y ← H_y + (Δt/μΔx)(E_z[i+1, j] - E_z[i, j])
  4. 3for each interior node (i, j) do E_z ← E_z + (Δt/ε)((H_y[i+1/2, j] - H_y[i-1/2, j])/Δx - (H_x[i, j+1/2] - H_x[i, j-1/2])/Δy)
  5. 4on the conducting walls set E_z ← 0

In three dimensions there are six such updates, one for each component, and each uses the four values of the other field on the loop around it. The staggered positions make each difference centred in space, and the half-step offset makes each update centred in time.

Example

The magic time step by hand. In one dimension with c=1c = 1, EE at ii and HH at i+12i + \tfrac12, the scheme is Hi+1/2←Hi+1/2+λ(Ei+1−Ei)H_{i+1/2} \leftarrow H_{i+1/2} + \lambda(E_{i+1} - E_i), then Ei←Ei+λ(Hi+1/2−Hi−1/2)E_i \leftarrow E_i + \lambda(H_{i+1/2} - H_{i-1/2}), with λ=cΔt/Δx\lambda = c\Delta t/\Delta x. Take λ=1\lambda = 1 and a wave moving right: Ei0=fiE^0_i = f_i and Hi+1/2−1/2=−fi+1H^{-1/2}_{i+1/2} = -f_{i+1}. Then Hi+1/21/2=−fi+1+fi+1−fi=−fiH^{1/2}_{i+1/2} = -f_{i+1} + f_{i+1} - f_i = -f_i and Ei1=fi+(−fi+fi−1)=fi−1E^1_i = f_i + (-f_i + f_{i-1}) = f_{i-1}. The pulse moves exactly one cell per step, with no error. For λ<1\lambda < 1 the scheme has numerical dispersion: a mode ei(κx−ωt)e^{i(\kappa x - \omega t)} has sin⁡(ωΔt/2)=λsin⁡(κΔx/2)\sin(\omega\Delta t/2) = \lambda\sin(\kappa\Delta x/2), so short waves are slower than cc.

Cavity mode (measurement). The TM11\text{TM}_{11} mode of the unit square, Ez=sin⁡πxsin⁡πycos⁡ωtE_z = \sin\pi x\sin\pi y\cos\omega t with ω=π2=4.442883\omega = \pi\sqrt2 = 4.442883, Δt=14Δx\Delta t = \tfrac14\Delta x (0.354 of the CFL limit), T=0.5T = 0.5. The scheme has the discrete mode with sin⁡(ωhΔt/2)=Δtsin⁡2(πΔx/2)/Δx2+sin⁡2(πΔy/2)/Δy2\sin(\omega_h\Delta t/2) = \Delta t\sqrt{\sin^2(\pi\Delta x/2)/\Delta x^2 + \sin^2(\pi\Delta y/2)/\Delta y^2}, which it reproduces to rounding.

cells per side largest error of EzE_z ratio discrete ωh\omega_h
8 9.987e-3 4.417898
16 2.488e-3 4.01 4.436638
32 6.213e-4 4.00 4.441322
64 1.553e-4 4.00 4.442493

The error falls by 4 per halving of the grid, which is second order. The frequency error ω−ωh\omega - \omega_h also falls by 4. With random initial fields on a 20×2020\times20 grid, the scheme stays bounded for 400 steps at the CFL limit and blows up at 1.02 times the limit.

Correctness

The proof is in proofs/correctness.md. It shows that every difference in L1 to L3 is centred in space and time, so the local truncation error is O(Δt2+Δx2+Δy2)O(\Delta t^2 + \Delta x^2 + \Delta y^2). It shows that the discrete divergence of HH at the cell centres does not change, because the discrete divergence of a discrete curl is zero. It gives a conserved discrete energy, which is positive definite and so bounds the fields when cΔt≤1/1/Δx2+1/Δy2c\Delta t \le 1/\sqrt{1/\Delta x^2 + 1/\Delta y^2}. Above that limit, the mode with the shortest wavelength grows geometrically, and the same eigenvalue analysis gives the discrete dispersion relation.

Proof: The Yee scheme is consistent of second order, keeps the discrete divergence and a discrete energy, and is stable up to the CFL limitfull

Setting. The TMz\text{TM}_z scheme of the main page with constant ε\varepsilon and μ\mu, c=1/εμc = 1/\sqrt{\varepsilon\mu}, on a rectangle with Ez=0E_z = 0 on the walls. Write δx\delta_x for the centred difference over one cell, (δxq)i=(qi+1/2−qi−1/2)/Δx(\delta_xq)_{i} = (q_{i+1/2} - q_{i-1/2})/\Delta x, and similarly δy\delta_y and δt\delta_t. The scheme is

μ δtHx=−δyEz,μ δtHy=δxEz,ε δtEz=δxHy−δyHx,\mu\,\delta_tH_x = -\delta_yE_z,\qquad \mu\,\delta_tH_y = \delta_xE_z,\qquad \varepsilon\,\delta_tE_z = \delta_xH_y - \delta_yH_x,

where each equation is taken at the point where the updated value lives: L1 and L2 at tnt_n and L3 at tn+1/2t_{n+1/2}.

Lemma 1 (consistency). For smooth solutions the local truncation error is O(Δt2+Δx2+Δy2)O(\Delta t^2 + \Delta x^2 + \Delta y^2).

Proof. Each operator is a centred difference at the point where the equation is taken. For a smooth function, (q(s+h/2)−q(s−h/2))/h=q′(s)+h224q′′′(s)+O(h4)(q(s + h/2) - q(s - h/2))/h = q'(s) + \frac{h^2}{24}q'''(s) + O(h^4) by Taylor expansion about ss. Inserting the exact solution into each of the three equations therefore leaves residuals of order Δt2\Delta t^2, Δx2\Delta x^2 and Δy2\Delta y^2. □\square

Lemma 2 (divergence). Let Di+1/2,j+1/2=δxHx+δyHyD_{i+1/2,j+1/2} = \delta_xH_x + \delta_yH_y at the cell centres. L1 and L2 do not change DD.

Proof. By L1 and L2, μ δtD=−δxδyEz+δyδxEz\mu\,\delta_tD = -\delta_x\delta_yE_z + \delta_y\delta_xE_z. The operators δx\delta_x and δy\delta_y act on different indices, so they commute, and the difference is zero. Written out at one cell centre, each of the four values of EzE_z at the corners appears twice, with opposite signs. □\square

In three dimensions the same argument applies to each of the two curl updates, so the discrete divergences of μH\mu H at the cell centres and of εE\varepsilon E at the nodes stay constant when there are no currents.

Notation for the energy. Let ⟨⋅,⋅⟩\langle\cdot,\cdot\rangle be the sum over the grid points of each field, times ΔxΔy\Delta x\Delta y, and ∥⋅∥\|\cdot\| its norm. Define KE=(δyEz,−δxEz)KE = (\delta_yE_z, -\delta_xE_z), a field at the positions of (Hx,Hy)(H_x, H_y), and K∗H=δxHy−δyHxK^*H = \delta_xH_y - \delta_yH_x at the interior nodes. Then L1 and L2 read Hn+1/2=Hn−1/2−ΔtμKEnH^{n+1/2} = H^{n-1/2} - \frac{\Delta t}{\mu}KE^n, and L3 with L4 reads En+1=En+ΔtεK∗Hn+1/2E^{n+1} = E^n + \frac{\Delta t}{\varepsilon}K^*H^{n+1/2}, with Ez=0E_z = 0 on the walls.

Lemma 3 (adjoint). If Ez=0E_z = 0 on the walls, ⟨KE,H⟩=⟨E,K∗H⟩\langle KE, H\rangle = \langle E, K^*H\rangle.

Proof. In one column, ∑j(δyEz)j+1/2Hx,j+1/2=−∑jEz,j(δyHx)j\sum_j(\delta_yE_z)_{j+1/2}H_{x,j+1/2} = -\sum_jE_{z,j}(\delta_yH_x)_j plus terms with EzE_z at the two walls, which are zero. This is summation by parts. The same holds in each row for δx\delta_x. So ⟨KE,H⟩=−⟨E,δyHx⟩+⟨E,δxHy⟩=⟨E,K∗H⟩\langle KE, H\rangle = -\langle E, \delta_yH_x\rangle + \langle E, \delta_xH_y\rangle = \langle E, K^*H\rangle. □\square

Lemma 4 (energy). Wn=ε∥En∥2+μ⟨Hn−1/2,Hn+1/2⟩W^n = \varepsilon\|E^n\|^2 + \mu\langle H^{n-1/2}, H^{n+1/2}\rangle is the same for all nn.

Proof. By the EE update,

ε∥En+1∥2−ε∥En∥2=ε⟨En+1−En,En+1+En⟩=Δt ⟨K∗Hn+1/2,En+1+En⟩.\varepsilon\|E^{n+1}\|^2 - \varepsilon\|E^n\|^2 = \varepsilon\langle E^{n+1} - E^n, E^{n+1} + E^n\rangle = \Delta t\,\langle K^*H^{n+1/2}, E^{n+1} + E^n\rangle.

By the HH update at the steps nn and n+1n + 1, Hn+3/2−Hn−1/2=−ΔtμK(En+1+En)H^{n+3/2} - H^{n-1/2} = -\frac{\Delta t}{\mu}K(E^{n+1} + E^n), so by Lemma 3

μ⟨Hn+1/2,Hn+3/2⟩−μ⟨Hn−1/2,Hn+1/2⟩=−Δt ⟨Hn+1/2,K(En+1+En)⟩=−Δt ⟨K∗Hn+1/2,En+1+En⟩.\mu\langle H^{n+1/2}, H^{n+3/2}\rangle - \mu\langle H^{n-1/2}, H^{n+1/2}\rangle = -\Delta t\,\langle H^{n+1/2}, K(E^{n+1} + E^n)\rangle = -\Delta t\,\langle K^*H^{n+1/2}, E^{n+1} + E^n\rangle.

The two changes cancel, so Wn+1=WnW^{n+1} = W^n. □\square

Theorem 1 (stability). Let σ=cΔt1/Δx2+1/Δy2\sigma = c\Delta t\sqrt{1/\Delta x^2 + 1/\Delta y^2}. If σ≤1\sigma \le 1, the fields stay bounded for all nn, by a constant that depends on the grid but not on nn. If σ>1\sigma > 1, then on fine enough grids there are initial fields that grow geometrically.

Proof. K∗K=−(δx2+δy2)K^*K = -(\delta_x^2 + \delta_y^2) is the five-point Laplacian with Dirichlet walls, with the eigenvectors sin⁡(kxx)sin⁡(kyy)\sin(k_xx)\sin(k_yy), kx=mπ/ak_x = m\pi/a, ky=nπ/bk_y = n\pi/b, 1≤m<Nx1 \le m < N_x, 1≤n<Ny1 \le n < N_y, and the eigenvalues

Λmn=4Δx2sin⁡2kxΔx2+4Δy2sin⁡2kyΔy2<4(1Δx2+1Δy2).\Lambda_{mn} = \frac{4}{\Delta x^2}\sin^2\frac{k_x\Delta x}{2} + \frac{4}{\Delta y^2}\sin^2\frac{k_y\Delta y}{2} < 4\Big(\frac1{\Delta x^2} + \frac1{\Delta y^2}\Big).

So ∥K∥2=max⁡Λmn<4σ2/(cΔt)2\|K\|^2 = \max\Lambda_{mn} < 4\sigma^2/(c\Delta t)^2.

Bounded case. Write Wn=ε∥En∥2+μ∥Hn−1/2∥2−Δt⟨Hn−1/2,KEn⟩W^n = \varepsilon\|E^n\|^2 + \mu\|H^{n-1/2}\|^2 - \Delta t\langle H^{n-1/2}, KE^n\rangle. By the Cauchy-Schwarz inequality the last term is at most Δt∥K∥ ∥Hn−1/2∥ ∥En∥\Delta t\|K\|\,\|H^{n-1/2}\|\,\|E^n\|. The quadratic form εe2+μh2−Δt∥K∥eh\varepsilon e^2 + \mu h^2 - \Delta t\|K\|eh is positive definite when Δt2∥K∥2<4εμ\Delta t^2\|K\|^2 < 4\varepsilon\mu, that is c2Δt2∥K∥2<4c^2\Delta t^2\|K\|^2 < 4, which holds because c2Δt2∥K∥2<4σ2≤4c^2\Delta t^2\|K\|^2 < 4\sigma^2 \le 4. Then Wn≥γ(∥En∥2+∥Hn−1/2∥2)W^n \ge \gamma(\|E^n\|^2 + \|H^{n-1/2}\|^2) with some γ>0\gamma > 0, and since Wn=W0W^n = W^0 by Lemma 4, the fields are bounded.

Unbounded case. Eliminating HH gives En+1−2En+En−1=−c2Δt2K∗KEnE^{n+1} - 2E^n + E^{n-1} = -c^2\Delta t^2K^*KE^n. For one eigenvector the factor gg per step satisfies g+1/g=2−c2Δt2Λmng + 1/g = 2 - c^2\Delta t^2\Lambda_{mn}. If c2Δt2Λmn>4c^2\Delta t^2\Lambda_{mn} > 4, the right side is below −2-2, so one root is real with ∣g∣>1|g| > 1 and the mode grows geometrically. For m=Nx−1m = N_x - 1 and n=Ny−1n = N_y - 1, c2Δt2Λmn→4σ2>4c^2\Delta t^2\Lambda_{mn} \to 4\sigma^2 > 4 as the grid is refined at fixed ratios cΔt/Δxc\Delta t/\Delta x and cΔt/Δyc\Delta t/\Delta y. □\square

Dispersion. For c2Δt2Λmn<4c^2\Delta t^2\Lambda_{mn} < 4 the two roots are g=e±iωhΔtg = e^{\pm i\omega_h\Delta t} with sin⁡(ωhΔt/2)=12cΔtΛmn\sin(\omega_h\Delta t/2) = \tfrac12c\Delta t\sqrt{\Lambda_{mn}}, which is the dispersion relation on the main page.

Corollary (exact discrete mode). With ωh\omega_h from the dispersion relation, Ez=cos⁡(ωhtn)sin⁡(kxxi)sin⁡(kyyj)E_z = \cos(\omega_ht_n)\sin(k_xx_i)\sin(k_yy_j), Hx=Axsin⁡(ωhtn+1/2)sin⁡(kxxi)cos⁡(kyyj+1/2)H_x = A_x\sin(\omega_ht_{n+1/2})\sin(k_xx_i)\cos(k_yy_{j+1/2}) and Hy=Aysin⁡(ωhtn+1/2)cos⁡(kxxi+1/2)sin⁡(kyyj)H_y = A_y\sin(\omega_ht_{n+1/2})\cos(k_xx_{i+1/2})\sin(k_yy_j), with Ax=−Δtsin⁡(kyΔy/2)μΔysin⁡(ωhΔt/2)A_x = -\frac{\Delta t\sin(k_y\Delta y/2)}{\mu\Delta y\sin(\omega_h\Delta t/2)} and Ay=Δtsin⁡(kxΔx/2)μΔxsin⁡(ωhΔt/2)A_y = \frac{\Delta t\sin(k_x\Delta x/2)}{\mu\Delta x\sin(\omega_h\Delta t/2)}, solve the scheme exactly. Inserting them into L1 and L2 uses sin⁡(s+h)−sin⁡(s−h)=2cos⁡ssin⁡h\sin(s + h) - \sin(s - h) = 2\cos s\sin h and fixes AxA_x and AyA_y. Inserting them into L3 uses cos⁡(s+h)−cos⁡(s−h)=−2sin⁡ssin⁡h\cos(s + h) - \cos(s - h) = -2\sin s\sin h and gives the dispersion relation.

Termination. One step is three loops over at most (Nx+1)(Ny+1)(N_x + 1)(N_y + 1) points each, so NN steps end after Θ(NNxNy)\Theta(NN_xN_y) operations.

■\blacksquare

Complexity

Each step updates every field component once with a few additions and multiplications, so it costs Θ(M)\Theta(M) for MM cells, and NN steps cost Θ(NM)\Theta(NM). Memory is the six field arrays (three in TMz\text{TM}_z) and the material coefficients. Because Δt\Delta t is tied to the smallest cell by the CFL condition, a fine feature in one place forces small steps everywhere. The method parallelizes well: each update needs only nearest neighbours.

Properties

  • Second order in space and time on uniform grids; first order at staircased curved boundaries.
  • No dissipation: the discrete energy ∑εEn⋅En+μHn−1/2⋅Hn+1/2\sum \varepsilon E^n\cdot E^n + \mu H^{n-1/2}\cdot H^{n+1/2} is conserved exactly.
  • The discrete divergence of μH\mu H, and of εE\varepsilon E without sources, stays constant, so no spurious charges appear.
  • Numerical dispersion depends on the direction and the wavelength. It is the main source of error, and about 10 to 20 cells per wavelength are needed in practice.
  • Stable exactly for cΔt≤1/∑d1/Δxd2c\Delta t \le 1/\sqrt{\sum_d 1/\Delta x_d^2}. In one dimension cΔt=Δxc\Delta t = \Delta x gives the exact shift.
  • The leapfrog in time is the Verlet method for the linear system, and it is symplectic.

Variants and improvements

  • Absorbing boundaries. The perfectly matched layer of Berenger (1994) and its convolutional form (CPML) are the standard ways to model open space.
  • Dispersive materials. Auxiliary differential equations or recursive convolutions add Debye, Drude and Lorentz media.
  • Subcell models. Conformal methods change the coefficients in the cells cut by a curved conductor, which avoids the first-order staircase error.
  • Total-field and scattered-field formulation. A plane wave is injected through a closed surface, so only the scattered field enters the absorbing layer.
  • Unconditionally stable versions. ADI-FDTD and locally one-dimensional schemes remove the CFL limit at the cost of an implicit solve and larger dispersion errors.
  • Higher order. Wider stencils such as the (2,4) scheme cut the dispersion error. Discontinuous Galerkin and finite element methods handle complex geometry with high order.
  • The same staggering elsewhere. The MAC grid of incompressible flow puts velocities on faces and pressure at centres for the same reason.

When to use it

Use it for broadband time-domain problems in electromagnetics and acoustics on simple, mostly structured geometry: antennas, waveguides, photonic crystals, radar cross sections, biological tissue, ground-penetrating radar. One run with a short pulse gives the response at all frequencies through a Fourier transform. For problems at a single frequency with large scale differences, frequency-domain finite element or integral equation methods are often more efficient. For curved geometry with high accuracy, use conformal FDTD or discontinuous Galerkin methods.

Pitfalls

  • Wrong positions of the components. Putting EE and HH at the same points gives a non-centred scheme with spurious modes. Each component has its own position.
  • Time step above the limit. A few percent above the CFL limit, the highest mode grows by a large factor per step and the run blows up.
  • Too few cells per wavelength. Phase errors build up with distance. A wave crossing 100 wavelengths needs more resolution than one that crosses 5.
  • Initial fields at the wrong time. HH must be given at t=−Δt/2t = -\Delta t/2, not at t=0t = 0. Otherwise the error is first order.
  • Staircased conductors. Curved metal surfaces on a Cartesian grid give first-order errors in resonance frequencies.
  • Simple absorbing conditions. First-order boundary conditions reflect waves at grazing angles. Use a PML.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

yee_fdtd_scheme.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/yee-fdtd-scheme/. The authors are listed in prov/Z3QKRQ.jsonl.
"""The Yee finite-difference time-domain scheme for Maxwell's equations.

Two-dimensional TM_z mode on the rectangle [0, Nx dx] x [0, Ny dy] with
perfectly conducting (PEC) walls:

    eps dEz/dt = dHy/dx - dHx/dy,   mu dHx/dt = -dEz/dy,   mu dHy/dt = dEz/dx.

Ez[i][j] lives at the node (i dx, j dy), 0 <= i <= Nx, 0 <= j <= Ny.
Hx[i][j] lives at (i dx, (j + 1/2) dy), Hy[i][j] at ((i + 1/2) dx, j dy).
Ez is at integer time steps, Hx and Hy at half steps. Values may be floats
or Fractions.
"""

import math


def cfl_limit(dx, dy, c=1.0):
    """Largest stable time step: c dt <= 1 / sqrt(1/dx^2 + 1/dy^2)."""
    return 1.0 / (c * math.sqrt(1.0 / dx ** 2 + 1.0 / dy ** 2))


def yee_step(Ez, Hx, Hy, dx, dy, dt, eps=1, mu=1):
    """Advance H from n - 1/2 to n + 1/2 and Ez from n to n + 1, in place."""
    nx, ny = len(Ez) - 1, len(Ez[0]) - 1
    for i in range(nx + 1):
        for j in range(ny):
            # @line L1: Hx from the y-difference of Ez
            Hx[i][j] -= dt / (mu * dy) * (Ez[i][j + 1] - Ez[i][j])
    for i in range(nx):
        for j in range(ny + 1):
            # @line L2: Hy from the x-difference of Ez
            Hy[i][j] += dt / (mu * dx) * (Ez[i + 1][j] - Ez[i][j])
    for i in range(1, nx):
        for j in range(1, ny):
            # @line L3: Ez from the curl of H at the node
            Ez[i][j] += dt / eps * ((Hy[i][j] - Hy[i - 1][j]) / dx
                                    - (Hx[i][j] - Hx[i][j - 1]) / dy)
    for i in range(nx + 1):
        # @line L4: tangential E is zero on the PEC walls
        Ez[i][0] = Ez[i][ny] = 0 * Ez[i][0]
    for j in range(ny + 1):
        Ez[0][j] = Ez[nx][j] = 0 * Ez[0][j]


def zeros(m, n):
    return [[0.0] * n for _ in range(m)]


def discrete_omega(kx, ky, dx, dy, dt, c=1.0):
    """Frequency of a Yee mode from the discrete dispersion relation."""
    s = c * dt * math.sqrt((math.sin(kx * dx / 2) / dx) ** 2 + (math.sin(ky * dy / 2) / dy) ** 2)
    if s > 1:
        raise ValueError("time step above the CFL limit")
    return 2 / dt * math.asin(s)


def cavity_mode(nx, ny, dx, dy, dt, m, n, omega, t0=0.0):
    """Fields of the TM_mn cavity mode with frequency omega: Ez at t0, H at t0 - dt/2.

    With the discrete omega this is an exact solution of the Yee scheme.
    """
    a, b = nx * dx, ny * dy
    kx, ky = m * math.pi / a, n * math.pi / b
    sh = math.sin(omega * dt / 2)
    ax = -dt * math.sin(ky * dy / 2) / (dy * sh)
    ay = dt * math.sin(kx * dx / 2) / (dx * sh)
    th = math.sin(omega * (t0 - dt / 2))
    Ez = [[math.cos(omega * t0) * math.sin(kx * i * dx) * math.sin(ky * j * dy)
           for j in range(ny + 1)] for i in range(nx + 1)]
    Hx = [[ax * th * math.sin(kx * i * dx) * math.cos(ky * (j + 0.5) * dy)
           for j in range(ny)] for i in range(nx + 1)]
    Hy = [[ay * th * math.cos(kx * (i + 0.5) * dx) * math.sin(ky * j * dy)
           for j in range(ny + 1)] for i in range(nx)]
    for i in (0, nx):
        Ez[i] = [0.0] * (ny + 1)
    for row in Ez:
        row[0] = row[ny] = 0.0
    return Ez, Hx, Hy


def div_h(Hx, Hy, dx, dy):
    """Discrete divergence of H at the cell centres ((i + 1/2) dx, (j + 1/2) dy)."""
    nx, ny = len(Hy), len(Hx[0])
    return [[(Hx[i + 1][j] - Hx[i][j]) / dx + (Hy[i][j + 1] - Hy[i][j]) / dy
             for j in range(ny)] for i in range(nx)]


def yee_1d_step(E, H, lam):
    """Periodic 1D Yee step: H[i] at i + 1/2, E[i] at i; lam = c dt / dx."""
    m = len(E)
    for i in range(m):
        H[i] += lam * (E[(i + 1) % m] - E[i])
    for i in range(m):
        E[i] += lam * (H[i] - H[i - 1])
test_yee_fdtd_scheme.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/yee-fdtd-scheme/. The authors are listed in prov/Z3QKRQ.jsonl.

import math
import random
from fractions import Fraction

import pytest

from yee_fdtd_scheme import (cavity_mode, cfl_limit, discrete_omega, div_h, yee_1d_step,
                             yee_step, zeros)


def max_diff(A, B):
    return max(abs(a - b) for ra, rb in zip(A, B) for a, b in zip(ra, rb))


def test_cfl_limit_values():
    assert abs(cfl_limit(0.1, 0.1) - 0.1 / math.sqrt(2)) < 1e-15
    assert abs(cfl_limit(0.1, 0.2) - 1 / math.sqrt(125)) < 1e-15


def test_discrete_cavity_mode_is_an_exact_solution():
    nx, ny, a, b = 12, 8, 1.0, 0.7
    dx, dy = a / nx, b / ny
    dt = 0.9 * cfl_limit(dx, dy)
    m, n = 2, 1
    w = discrete_omega(m * math.pi / a, n * math.pi / b, dx, dy, dt)
    Ez, Hx, Hy = cavity_mode(nx, ny, dx, dy, dt, m, n, w)
    for _ in range(60):
        yee_step(Ez, Hx, Hy, dx, dy, dt)
    E2, X2, Y2 = cavity_mode(nx, ny, dx, dy, dt, m, n, w, t0=60 * dt)
    assert max_diff(Ez, E2) < 1e-12 and max_diff(Hx, X2) < 1e-12 and max_diff(Hy, Y2) < 1e-12


def test_second_order_convergence_to_the_continuous_mode():
    a = b = 1.0
    T = 0.5
    w = math.pi * math.sqrt(2)                       # continuous TM_11 frequency
    errs = []
    for nx in (8, 16, 32):
        dx = a / nx
        steps = 2 * nx                               # dt = T / steps = 0.5 dx / 2
        dt = T / steps
        Ez, Hx, Hy = cavity_mode(nx, nx, dx, dx, dt, 1, 1, w)
        for _ in range(steps):
            yee_step(Ez, Hx, Hy, dx, dx, dt)
        ex = cavity_mode(nx, nx, dx, dx, dt, 1, 1, w, t0=T)[0]
        errs.append(max_diff(Ez, ex))
    r1, r2 = math.log2(errs[0] / errs[1]), math.log2(errs[1] / errs[2])
    assert 1.8 < r1 < 2.2 and 1.8 < r2 < 2.2


def test_discrete_divergence_of_h_is_kept_exactly():
    rng = random.Random(3)
    nx, ny = 6, 5
    dx, dy, dt = Fraction(1, 6), Fraction(1, 5), Fraction(1, 10)
    rnd = (lambda: Fraction(rng.randint(-9, 9), 7))
    Ez = [[rnd() if 0 < i < nx and 0 < j < ny else Fraction(0) for j in range(ny + 1)]
          for i in range(nx + 1)]
    Hx = [[rnd() for _ in range(ny)] for _ in range(nx + 1)]
    Hy = [[rnd() for _ in range(ny + 1)] for _ in range(nx)]
    d0 = div_h(Hx, Hy, dx, dy)
    assert any(v != 0 for row in d0 for v in row)
    for _ in range(5):
        yee_step(Ez, Hx, Hy, dx, dy, dt)
        assert div_h(Hx, Hy, dx, dy) == d0


def test_discrete_energy_is_conserved_exactly():
    rng = random.Random(2)
    nx, ny = 5, 4
    dx, dy, dt = Fraction(1, 5), Fraction(1, 4), Fraction(1, 9)   # below the limit 0.156
    Ez = [[Fraction(rng.randint(-9, 9)) if 0 < i < nx and 0 < j < ny else Fraction(0)
           for j in range(ny + 1)] for i in range(nx + 1)]
    Hx = [[Fraction(rng.randint(-9, 9)) for _ in range(ny)] for _ in range(nx + 1)]
    Hy = [[Fraction(rng.randint(-9, 9)) for _ in range(ny + 1)] for _ in range(nx)]

    def dot(A, B):
        return sum(a * b for ra, rb in zip(A, B) for a, b in zip(ra, rb))

    energies = []
    for _ in range(6):
        E0, X0, Y0 = [r[:] for r in Ez], [r[:] for r in Hx], [r[:] for r in Hy]
        yee_step(Ez, Hx, Hy, dx, dy, dt)
        energies.append(dot(E0, E0) + dot(X0, Hx) + dot(Y0, Hy))
    assert len(set(energies)) == 1


@pytest.mark.parametrize("factor,stable", [(0.99, True), (1.0, True), (1.02, False)])
def test_stability_limit(factor, stable):
    rng = random.Random(1)
    nx = ny = 20
    dx = dy = 1.0 / nx
    dt = factor * cfl_limit(dx, dy)
    Ez = [[rng.uniform(-1, 1) if 0 < i < nx and 0 < j < ny else 0.0 for j in range(ny + 1)]
          for i in range(nx + 1)]
    Hx, Hy = zeros(nx + 1, ny), zeros(nx, ny + 1)
    for _ in range(400):
        yee_step(Ez, Hx, Hy, dx, dy, dt)
    big = max(abs(v) for row in Ez for v in row)
    assert (big < 100) == stable


def test_magic_time_step_in_one_dimension_shifts_exactly():
    m = 32
    f = [max(0, 8 - abs(i - 10)) for i in range(m)]  # integer triangle pulse
    E = list(f)
    H = [-f[(i + 1) % m] for i in range(m)]           # right-moving wave, H at n - 1/2
    for n in range(1, 41):
        yee_1d_step(E, H, 1)
        assert E == [f[(i - n) % m] for i in range(m)]


def test_one_dimensional_scheme_has_numerical_dispersion_below_the_magic_step():
    m, lam, k = 64, 0.5, 8
    w = 2 * math.asin(lam * math.sin(math.pi * k / m))          # omega dt
    E = [math.cos(2 * math.pi * k * i / m) for i in range(m)]
    H = [-math.cos(2 * math.pi * k * (i + 0.5) / m + w / 2) * math.sin(math.pi * k / m)
         * lam / math.sin(w / 2) for i in range(m)]
    for _ in range(100):
        yee_1d_step(E, H, lam)
    ex = [math.cos(2 * math.pi * k * i / m - 100 * w) for i in range(m)]
    assert max(abs(a - b) for a, b in zip(E, ex)) < 1e-9
    assert w < 2 * math.pi * k / m * lam                       # slower than c


def test_rejects_unstable_step_in_mode_frequency():
    with pytest.raises(ValueError):
        discrete_omega(math.pi * 20, math.pi * 20, 0.05, 0.05, 0.04)

History

Kane Yee (1966) proposed the staggered grid and the leapfrog scheme and stated its stability condition, with computations of a pulse scattered by a perfectly conducting obstacle. Taflove and coworkers developed the method from the 1970s on, with absorbing boundaries, the total-field and scattered-field formulation and applications to scattering, and the name finite-difference time-domain became standard. Berenger's perfectly matched layer (1994) removed the main remaining weakness, the reflection at the outer boundary.

References

  1. Kane S. Yee, Numerical solution of initial boundary value problems involving Maxwell's equations in isotropic media, IEEE Transactions on Antennas and Propagation 14(3) (1966) 302-307, the staggered positions of the E and H components, the difference equations, the stability condition
  2. Allen Taflove and Susan C. Hagness, Computational Electrodynamics, The Finite-Difference Time-Domain Method, 3rd edition, Artech House, 2005, Chapter 3 (the Yee algorithm), Chapter 4 (numerical dispersion and stability)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example