A common first reaction when an explicit time-stepping code blows up is: ‘Just cut by !’ Try that on explicit Forward-Time Central-Space (FTCS) pure advection , and find that FTCS is unstable for every , even at , because its complex Fourier amplification factor has magnitude . Yet add just enough physical viscosity (), and FTCS suddenly becomes conditionally stable. In this lecture, we cover von Neumann Fourier analysis (von_neumann_advection_diffusion_amp), contrast amplitude dissipation vs. dispersive phase-speed errors across "ftcs", "upwind", "lax_friedrichs", and "lax_wendroff", and verify modified-equation truncation physics on live wave packets.
Learning objectives¶
Derive and evaluate complex Fourier amplification factors across dimensionless wavenumber using
von_neumann_advection_diffusion_amp.Prove why explicit FTCS pure advection is unconditionally unstable (), yet stabilizes when physical diffusion satisfies .
Distinguish diffusive amplitude damping ( in
"upwind"and"lax_friedrichs") from dispersive phase-velocity lag (trailing oscillations in"lax_wendroff").Verify modified-equation numerical viscosity and show via
np.fft.fftthat equals the exact single-step spectral multiplier.
Time: about 60 min
try: # use the installed package, or the copy in this repository
import engcfd
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engcfd" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engcfd.git"], check=True)
import engcfd
import inspect
import numpy as np
import matplotlib.pyplot as plt
from engcfd import (burgers_riemann, constants, convection_diffusion, elliptic_multigrid, grids_fvm,
lattice_boltzmann, navier_stokes, tvd_advection)
from engcfd.plotting import label_panels, panel_label, use_style
use_style()
def show_source(obj):
"""Return the source code of a library function or class."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))1. Discrete Fourier Modes & Exact vs. Numerical Amplification Factors¶
1.1 Von Neumann Normal-Mode Ansatz¶
On a periodic uniform grid , any square-integrable error or wave profile decomposes into discrete Fourier modes , where is the dimensionless grid wavenumber ( for well-resolved long waves; for the shortest Nyquist sawtooth ).
For linear advection–diffusion with Courant number and mesh Fourier number , one exact PDE step multiplies mode by:
A linear explicit finite-difference/FVM scheme multiplies by (constants.von_neumann_advection_diffusion_amp), and is von Neumann stable if and only if for all .
heading("Demonstration 1: Amplification Factors at C = 0.6, r = 0 Across All 4 Schemes")
theta_grid = np.linspace(0.0, np.pi, 257)
cfl_demo = 0.6
print(f"{'Scheme':16s} | {'|G(pi/4)|':>10s} | {'|G(pi/2)|':>10s} | {'|G(pi)|':>10s} | {'max |G|':>10s} | {'Stable?':>8s}")
print("-" * 78)
for sc in ("ftcs", "upwind", "lax_friedrichs", "lax_wendroff"):
out = constants.von_neumann_advection_diffusion_amp(theta_grid, cfl=cfl_demo, r_diff=0.0, scheme=sc)
g_q = constants.von_neumann_advection_diffusion_amp(0.25 * np.pi, cfl=cfl_demo, r_diff=0.0, scheme=sc)["magnitude"]
g_h = constants.von_neumann_advection_diffusion_amp(0.50 * np.pi, cfl=cfl_demo, r_diff=0.0, scheme=sc)["magnitude"]
g_p = constants.von_neumann_advection_diffusion_amp(np.pi, cfl=cfl_demo, r_diff=0.0, scheme=sc)["magnitude"]
print(f"{sc:16s} | {g_q:10.5f} | {g_h:10.5f} | {g_p:10.5f} | {np.max(out['magnitude']):10.5f} | {str(out['stable']):>8s}")
if sc == "ftcs":
assert out["stable"] is False and np.isclose(g_h, np.sqrt(1.0 + cfl_demo ** 2), rtol=1e-14)
else:
assert out["stable"] is True
Demonstration 1: Amplification Factors at C = 0.6, r = 0 Across All 4 Schemes
=============================================================================
Scheme | |G(pi/4)| | |G(pi/2)| | |G(pi)| | max |G| | Stable?
------------------------------------------------------------------------------
ftcs | 1.08628 | 1.16619 | 1.00000 | 1.16619 | False
upwind | 0.92704 | 0.72111 | 0.20000 | 1.00000 | True
lax_friedrichs | 0.82462 | 0.60000 | 1.00000 | 1.00000 | True
lax_wendroff | 0.99007 | 0.87727 | 0.28000 | 1.00000 | True
What Demonstration 1 shows. At :
"ftcs"has : every wave grows by per time step (stable == False)."upwind","lax_friedrichs", and"lax_wendroff"all satisfy (stable == True), though"lax_friedrichs"heavily damps mid-wavenumbers () while"lax_wendroff"preserves long/mid waves much closer to 1 ().
2. Why Pure-Advection FTCS Always Explodes, and How Physical Diffusion Saves It¶
For explicit "ftcs", substituting and gives:
Setting yields an exact quadratic in :
When (pure advection), for every .
When (advection–diffusion), for all if and only if both slope at and endpoint at are bounded:
heading("Demonstration 2: Pure-Advection FTCS Instability & Peclet-Diffusion Stabilization")
th_dense = np.linspace(0.0, np.pi, 513)
# 1. Even tiny Courant numbers C = 1e-1, 1e-2, 1e-4 are UNSTABLE for pure-advection FTCS (r = 0):
for c_tiny in (1.0e-1, 1.0e-2, 1.0e-4):
res_tiny = constants.von_neumann_advection_diffusion_amp(th_dense, cfl=c_tiny, r_diff=0.0, scheme="ftcs")
g_max_exact = np.sqrt(1.0 + c_tiny ** 2)
print(f"Pure-advection FTCS at C = {c_tiny:.0e}, r = 0: max |G| = {np.max(res_tiny['magnitude']):.10f} (= sqrt(1+C^2) = {g_max_exact:.10f}) -> stable = {res_tiny['stable']}")
assert res_tiny["stable"] is False
assert np.isclose(np.max(res_tiny["magnitude"]), g_max_exact, rtol=1e-14)
# 2. Verify exact stabilization threshold C^2 <= 2*r_diff and r_diff <= 0.5 at C = 0.4 (threshold r* = C^2 / 2 = 0.08):
c_fixed = 0.4
for r_val, expected_stable in [(0.075, False), (0.080, True), (0.250, True), (0.500, True), (0.510, False)]:
res_ftcs = constants.von_neumann_advection_diffusion_amp(th_dense, cfl=c_fixed, r_diff=r_val, scheme="ftcs")
print(f"FTCS at C = {c_fixed:.2f}, r = {r_val:.3f} (2r - C^2 = {2*r_val - c_fixed**2:+.3f}): max |G| = {np.max(res_ftcs['magnitude']):.6f}, stable = {res_ftcs['stable']}")
assert res_ftcs["stable"] is expected_stable
Demonstration 2: Pure-Advection FTCS Instability & Peclet-Diffusion Stabilization
=================================================================================
Pure-advection FTCS at C = 1e-01, r = 0: max |G| = 1.0049875621 (= sqrt(1+C^2) = 1.0049875621) -> stable = False
Pure-advection FTCS at C = 1e-02, r = 0: max |G| = 1.0000499988 (= sqrt(1+C^2) = 1.0000499988) -> stable = False
Pure-advection FTCS at C = 1e-04, r = 0: max |G| = 1.0000000050 (= sqrt(1+C^2) = 1.0000000050) -> stable = False
FTCS at C = 0.40, r = 0.075 (2r - C^2 = -0.010): max |G| = 1.000363, stable = False
FTCS at C = 0.40, r = 0.080 (2r - C^2 = -0.000): max |G| = 1.000000, stable = True
FTCS at C = 0.40, r = 0.250 (2r - C^2 = +0.340): max |G| = 1.000000, stable = True
FTCS at C = 0.40, r = 0.500 (2r - C^2 = +0.840): max |G| = 1.000000, stable = True
FTCS at C = 0.40, r = 0.510 (2r - C^2 = +0.860): max |G| = 1.040000, stable = False
theta_map = np.linspace(0.0, np.pi, 181)
c_axis = np.linspace(0.0, 1.2, 121)
r_axis = np.linspace(0.0, 0.6, 121)
g_max = np.array([[np.max(constants.von_neumann_advection_diffusion_amp(theta_map, cc, rr, scheme="ftcs")["magnitude"])
for cc in c_axis] for rr in r_axis])
fig, ax = plt.subplots(figsize=(6.4, 4.2))
ax.contourf(c_axis, r_axis, g_max <= 1.0 + 1e-12, levels=[0.5, 1.5], colors=["#c6dbef"])
ax.plot(c_axis, 0.5 * c_axis ** 2, "k-", label=r"$r = C^2/2$")
ax.axhline(0.5, color="k", ls="--", label=r"$r = 1/2$")
ax.set_xlabel("Courant number $C$ [-]"); ax.set_ylabel("diffusion number $r$ [-]")
ax.set_xlim(0.0, 1.2); ax.set_ylim(0.0, 0.6)
ax.text(0.30, 0.27, "stable", fontsize=10)
ax.legend(loc="lower right")
plt.show()
Figure 5.1. Stability region of the forward-time, centered-space scheme for advection with diffusion (shaded), found by evaluating the amplification factor on a grid of Courant and diffusion numbers. It lies between the parabola and the line .
What Demonstration 2 shows. The output follows Equation (2.3): for , FTCS flips from unstable (r = 0.075) to strictly stable at the exact parabola , stays stable up to , and then goes unstable again at due to Nyquist diffusion overshoot at .
3. Amplitude Dissipation vs. Dispersive Phase-Speed Lag¶
Stability () only prevents blowup, accuracy requires both (low numerical dissipation) and numerical phase (low numerical dispersion, i.e., relative wave speed ). We plot and across at .
heading("Demonstration 3: Polar/Spectral Portrait of Dissipation |G(theta)| & Relative Phase Speed")
th_pos = np.linspace(1.0e-3, np.pi - 1.0e-3, 300)
c_plot = 0.5
scheme_meta = [
("ftcs", "--", "#d62728", "FTCS (Unstable $|G|>1$)"),
("lax_friedrichs", ":", "#9467bd", "Lax-Friedrichs (Heavy mid-$k$ damping)"),
("upwind", "-.", "#ff7f0e", "1st-Order Upwind ($O(\\Delta x)$ dissipative)"),
("lax_wendroff", "-", "#1f77b4", "2nd-Order Lax-Wendroff ($O(\\Delta x^2)$ dispersive)"),
]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.3))
ax1.axhline(1.0, color="#111111", lw=1.8, label="Exact Advection ($|G|=1$)")
ax2.axhline(1.0, color="#111111", lw=1.8, label="Exact Wave Speed ($c_{\\mathrm{num}}/u=1$)")
for sc, ls, col, lbl in scheme_meta:
d = constants.von_neumann_advection_diffusion_amp(th_pos, cfl=c_plot, r_diff=0.0, scheme=sc)
rel_speed = -np.unwrap(d["phase_rad"]) / (c_plot * th_pos)
ax1.plot(th_pos / np.pi, d["magnitude"], ls=ls, color=col, lw=2.0, label=lbl)
ax2.plot(th_pos / np.pi, rel_speed, ls=ls, color=col, lw=2.0, label=lbl)
ax1.set_ylim(0.0, 1.22)
ax1.set_xlabel(r"Normalized Wavenumber $\theta / \pi = k\Delta x / \pi$ [-]")
ax1.set_ylabel(r"Amplification Magnitude $|G(\theta)|$ [-]")
ax1.set_title(r"Amplitude Dissipation ($C = 0.5, r = 0$)")
ax1.legend(fontsize=8.0, frameon=False)
ax2.set_ylim(0.0, 1.35)
ax2.set_xlabel(r"Normalized Wavenumber $\theta / \pi = k\Delta x / \pi$ [-]")
ax2.set_ylabel(r"Relative Phase Speed $-\Phi(\theta)/(C\theta)$ [-]")
ax2.set_title(r"Numerical Dispersion ($C = 0.5, r = 0$)")
ax2.legend(fontsize=8.0, frameon=False)
label_panels(fig)
plt.show()
# Verify at C = 0.5, Upwind has ZERO phase error across all theta in (0, pi)
# Wait: Re(G_upwind) at C=0.5 is 1 - 0.5*(1 - cos(th)) = 0.5*(1 + cos(th)) = cos^2(th/2),
# Im(G_upwind) = -0.5*sin(th) = -sin(th/2)*cos(th/2) => arg(G) = -th/2 = -C*th IDENTICALLY
up_05 = constants.von_neumann_advection_diffusion_amp(th_pos, cfl=0.5, r_diff=0.0, scheme="upwind")
phase_err_up05 = float(np.max(np.abs(up_05["phase_rad"] - up_05["exact_phase_rad"])))
lw_05 = constants.von_neumann_advection_diffusion_amp(0.5 * np.pi, cfl=0.5, r_diff=0.0, scheme="lax_wendroff")
print(f"At C = 0.5: Upwind max phase error across (0, pi) = {phase_err_up05:.2e} rad")
print(f"Lax-Wendroff at theta = pi/2, C = 0.5: relative speed = {-lw_05['phase_rad']/(0.5*0.5*np.pi):.4f} (< 1 => phase lag)")
assert phase_err_up05 < 1.0e-13
assert -lw_05["phase_rad"] / (0.25 * np.pi) < 0.75
Demonstration 3: Polar/Spectral Portrait of Dissipation |G(theta)| & Relative Phase Speed
=========================================================================================

At C = 0.5: Upwind max phase error across (0, pi) = 1.38e-14 rad
Lax-Wendroff at theta = pi/2, C = 0.5: relative speed = 0.7487 (< 1 => phase lag)
Figure 5.2. Von Neumann analysis of pure advection at Courant number 0.5. (a) Magnitude of the amplification factor against the wavenumber for four schemes; the exact value is 1. (b) Numerical phase speed relative to the exact one.
What Demonstration 3 shows. Two points:
Why Lax–Wendroff grows trailing wiggles behind shocks: Its amplitude stays near 1, so short waves survive, but its relative phase speed drops steeply below 1 at high , causing short-wavelength Fourier components to lag behind the main front.
Exact symmetry of Upwind at : Because , first-order upwind has identically zero phase dispersion at , suffering purely from amplitude damping .
4. Modified-Equation Truncation Analysis & Live Wave-Packet Propagation¶
Expanding and in Taylor series around and replacing shows what PDE first-order upwind actually solves:
We propagate a Gaussian pulse for one full periodic revolution on ( steps) and verify that "upwind" peak decay matches exact diffusive spreading .
heading("Demonstration 4: Periodic Gaussian Wave-Packet Evolution & Modified-Equation Peak Verification")
N_p = 160
dx_p = 1.0 / N_p
u_p, cfl_p = 1.0, 0.5
dt_p = cfl_p * dx_p / u_p
n_steps = int(round(1.0 / (u_p * dt_p))) # 320 steps -> exact T = 1.0 period
x_p = np.arange(N_p) * dx_p
sigma0 = 0.06
phi_init = np.exp(-((x_p - 0.5) ** 2) / (sigma0 ** 2))
phi_up = phi_init.copy()
phi_lw = phi_init.copy()
for _ in range(n_steps):
phi_up = phi_up - cfl_p * (phi_up - np.roll(phi_up, 1))
phi_lw = (
phi_lw
- 0.5 * cfl_p * (np.roll(phi_lw, -1) - np.roll(phi_lw, 1))
+ 0.5 * (cfl_p ** 2) * (np.roll(phi_lw, -1) - 2.0 * phi_lw + np.roll(phi_lw, 1))
)
gamma_mod = 0.5 * u_p * dx_p * (1.0 - cfl_p)
peak_mod_theory = sigma0 / np.sqrt(sigma0 ** 2 + 4.0 * gamma_mod * 1.0)
print("Initial Gaussian peak = 1.0000 | Exact T=1.0 peak = 1.0000")
print(f"Upwind peak after 1 period = {np.max(phi_up):.4f} vs Modified-Eq prediction = {peak_mod_theory:.4f}")
print(f"Lax-Wendroff peak after 1 period = {np.max(phi_lw):.4f} (2nd-order preservation)")
assert np.isclose(np.max(phi_up), peak_mod_theory, atol=5.0e-3)
assert np.max(phi_lw) > 0.98
Demonstration 4: Periodic Gaussian Wave-Packet Evolution & Modified-Equation Peak Verification
==============================================================================================
Initial Gaussian peak = 1.0000 | Exact T=1.0 peak = 1.0000
Upwind peak after 1 period = 0.6044 vs Modified-Eq prediction = 0.6046
Lax-Wendroff peak after 1 period = 0.9814 (2nd-order preservation)
Inside the algorithm¶
We check in NumPy that constants.von_neumann_advection_diffusion_amp is the eigenvalue, in the discrete Fourier basis (np.fft.fft), of one explicit time step applied to an arbitrary random vector on a periodic mesh.
Check against the library¶
heading("Inside the Algorithm: G(theta) == Exact FFT Single-Step Multiplier Across All 4 Schemes")
print(show_source(constants.von_neumann_advection_diffusion_amp))
rng = np.random.default_rng(314)
N_fft = 64
phi_0 = rng.standard_normal(N_fft) + 0.5
c_f, r_f = 0.45, 0.12
thetas_fft = 2.0 * np.pi * np.fft.fftfreq(N_fft) # signed wavenumbers in [-pi, pi)
def step_periodic(u: np.ndarray, c: float, r: float, sc: str) -> np.ndarray:
um, up = np.roll(u, 1), np.roll(u, -1)
diff = r * (up - 2.0 * u + um)
if sc == "upwind":
return u - c * (u - um) + diff
if sc == "ftcs":
return u - 0.5 * c * (up - um) + diff
if sc == "lax_wendroff":
return u - 0.5 * c * (up - um) + 0.5 * (c ** 2) * (up - 2.0 * u + um) + diff
if sc == "lax_friedrichs":
return 0.5 * (up + um) - 0.5 * c * (up - um) + diff
raise ValueError(sc)
hat_0 = np.fft.fft(phi_0)
for sc in ("upwind", "ftcs", "lax_wendroff", "lax_friedrichs"):
phi_1 = step_periodic(phi_0, c_f, r_f, sc)
g_emp = np.fft.fft(phi_1) / hat_0
g_lib = constants.von_neumann_advection_diffusion_amp(thetas_fft, cfl=c_f, r_diff=r_f, scheme=sc)["G"]
err_g = float(np.max(np.abs(g_emp - g_lib)))
print(f"Scheme {sc:15s}: max |FFT(u^1)/FFT(u^0) - G_lib(theta)| = {err_g:.2e}")
assert np.allclose(g_emp, g_lib, rtol=1e-14, atol=1e-14)
Inside the Algorithm: G(theta) == Exact FFT Single-Step Multiplier Across All 4 Schemes
=======================================================================================
def von_neumann_advection_diffusion_amp(
theta_rad: float | np.ndarray,
cfl: float,
r_diff: float = 0.0,
scheme: str = "upwind",
) -> dict:
"""Evaluate complex von Neumann amplification factor G(theta) for explicit 1-D advection-diffusion schemes."""
th = np.asarray(theta_rad, dtype=float)
key = scheme.strip().lower()
visc = 2.0 * r_diff * (np.cos(th) - 1.0)
if key == "upwind":
g_val = 1.0 - cfl * (1.0 - np.cos(th)) + visc - 1j * cfl * np.sin(th)
elif key == "ftcs":
g_val = 1.0 + visc - 1j * cfl * np.sin(th)
elif key == "lax_wendroff":
g_val = 1.0 - (cfl**2) * (1.0 - np.cos(th)) + visc - 1j * cfl * np.sin(th)
elif key == "lax_friedrichs":
g_val = np.cos(th) + visc - 1j * cfl * np.sin(th)
else:
raise ValueError(f"Unsupported von Neumann scheme: {scheme!r}.")
mag = np.abs(g_val)
exact_phase = -cfl * th
num_phase = np.angle(g_val)
if np.ndim(theta_rad) == 0:
return {
"G": complex(g_val),
"magnitude": float(mag),
"phase_rad": float(num_phase),
"exact_phase_rad": float(exact_phase),
"stable": bool(mag <= 1.0 + 1e-12),
}
return {
"G": g_val,
"magnitude": mag,
"phase_rad": num_phase,
"exact_phase_rad": exact_phase,
"stable": bool(np.all(mag <= 1.0 + 1e-12)),
}
Scheme upwind : max |FFT(u^1)/FFT(u^0) - G_lib(theta)| = 1.04e-15
Scheme ftcs : max |FFT(u^1)/FFT(u^0) - G_lib(theta)| = 1.54e-15
Scheme lax_wendroff : max |FFT(u^1)/FFT(u^0) - G_lib(theta)| = 6.66e-16
Scheme lax_friedrichs : max |FFT(u^1)/FFT(u^0) - G_lib(theta)| = 1.79e-15
Exercises¶
Worked solutions are in 05_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify that at ,
"upwind","lax_wendroff", and"lax_friedrichs"all satisfy across , and confirm to for .Find how it fails. Quantify over one periodic transit ( cells, steps, ) both (a) total mode amplification in
"ftcs"at , and (b) the damping of a 16-cell wave in"lax_friedrichs"when is shrunk from down to . VerifyValueErroron unknown scheme names.Implement it yourself. Implement
ftcs_advection_diffusion_limits(pe_cell)returning exact for explicit 1-D"ftcs"given , and verify across that isstable == Truewhile isstable == False.
heading("Self-check for the exercises")
th_chk = np.linspace(0.0, np.pi, 129)
for sc in ("upwind", "lax_wendroff", "lax_friedrichs"):
d1 = constants.von_neumann_advection_diffusion_amp(th_chk, cfl=1.0, r_diff=0.0, scheme=sc)
assert np.allclose(d1["G"], np.exp(-1j * th_chk), atol=1e-14)
assert np.allclose(d1["magnitude"], 1.0, atol=1e-14)
for c_lw in (0.35, 0.70):
dlw = constants.von_neumann_advection_diffusion_amp(th_chk, cfl=c_lw, r_diff=0.0, scheme="lax_wendroff")
exact_mag2 = 1.0 - 4.0 * (c_lw ** 2) * (1.0 - c_lw ** 2) * (np.sin(0.5 * th_chk) ** 4)
assert np.allclose(dlw["magnitude"] ** 2, exact_mag2, atol=1e-14)
print("Unit-CFL shift identity and 4th-order Lax-Wendroff modulus verified")
Self-check for the exercises
============================
Unit-CFL shift identity and 4th-order Lax-Wendroff modulus verified