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.
- Solves
- Wave equation
- Time
- Θ(N M) worst
- Space
- Θ(M) extra
- Where
- M = the number of grid cells; N = the number of time steps
- Model
- Real RAM
- Properties
- deterministicdivergence preservingexplicit
- Evidence
- Proof sketchCode in 1 languages
- Origin
- K. S. Yee, A. Taflove, 1966
The Yee scheme, the basis of the finite-difference time-domain (FDTD) method, solves Maxwell's equations , on a staggered grid. Each component of sits at the centre of a cell edge and each component of at the centre of a cell face, so every curl is a centred difference over one cell. is computed at whole time steps and 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 (with no charges) and of constant exactly. It is stable for . 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 and , initial fields and boundary conditions, for a time . The reference code solves the two-dimensional transverse magnetic () case, where only , and are nonzero:
in a rectangle with perfectly conducting walls ( on the boundary).
The algorithm
sits at the nodes , at , and at . is known at and at . One step:
YEE-STEP(E_z, H_x, H_y, Δx, Δy, Δt)- 1
for each (i, j+1/2) do H_x ← H_x - (Δt/μΔy)(E_z[i, j+1] - E_z[i, j]) - 2
for each (i+1/2, j) do H_y ← H_y + (Δt/μΔx)(E_z[i+1, j] - E_z[i, j]) - 3
for 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) - 4
on 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 , at and at , the scheme is , then , with . Take and a wave moving right: and . Then and . The pulse moves exactly one cell per step, with no error. For the scheme has numerical dispersion: a mode has , so short waves are slower than .
Cavity mode (measurement). The mode of the unit square, with , (0.354 of the CFL limit), . The scheme has the discrete mode with , which it reproduces to rounding.
| cells per side | largest error of | ratio | discrete |
|---|---|---|---|
| 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 also falls by 4. With random initial fields on a 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 . It shows that the discrete divergence of 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 . 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 scheme of the main page with constant and , , on a rectangle with on the walls. Write for the centred difference over one cell, , and similarly and . The scheme is
where each equation is taken at the point where the updated value lives: L1 and L2 at and L3 at .
Lemma 1 (consistency). For smooth solutions the local truncation error is .
Proof. Each operator is a centred difference at the point where the equation is taken. For a smooth function, by Taylor expansion about . Inserting the exact solution into each of the three equations therefore leaves residuals of order , and .
Lemma 2 (divergence). Let at the cell centres. L1 and L2 do not change .
Proof. By L1 and L2, . The operators and act on different indices, so they commute, and the difference is zero. Written out at one cell centre, each of the four values of at the corners appears twice, with opposite signs.
In three dimensions the same argument applies to each of the two curl updates, so the discrete divergences of at the cell centres and of at the nodes stay constant when there are no currents.
Notation for the energy. Let be the sum over the grid points of each field, times , and its norm. Define , a field at the positions of , and at the interior nodes. Then L1 and L2 read , and L3 with L4 reads , with on the walls.
Lemma 3 (adjoint). If on the walls, .
Proof. In one column, plus terms with at the two walls, which are zero. This is summation by parts. The same holds in each row for . So .
Lemma 4 (energy). is the same for all .
Proof. By the update,
By the update at the steps and , , so by Lemma 3
The two changes cancel, so .
Theorem 1 (stability). Let . If , the fields stay bounded for all , by a constant that depends on the grid but not on . If , then on fine enough grids there are initial fields that grow geometrically.
Proof. is the five-point Laplacian with Dirichlet walls, with the eigenvectors , , , , , and the eigenvalues
So .
Bounded case. Write . By the Cauchy-Schwarz inequality the last term is at most . The quadratic form is positive definite when , that is , which holds because . Then with some , and since by Lemma 4, the fields are bounded.
Unbounded case. Eliminating gives . For one eigenvector the factor per step satisfies . If , the right side is below , so one root is real with and the mode grows geometrically. For and , as the grid is refined at fixed ratios and .
Dispersion. For the two roots are with , which is the dispersion relation on the main page.
Corollary (exact discrete mode). With from the dispersion relation, , and , with and , solve the scheme exactly. Inserting them into L1 and L2 uses and fixes and . Inserting them into L3 uses and gives the dispersion relation.
Termination. One step is three loops over at most points each, so steps end after operations.
Complexity
Each step updates every field component once with a few additions and multiplications, so it costs for cells, and steps cost . Memory is the six field arrays (three in ) and the material coefficients. Because 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 is conserved exactly.
- The discrete divergence of , and of 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 . In one dimension 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 and 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. must be given at , not at . 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.
# 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Z3QKRQ Edit this page History Report an error Markdown