Worked solutions to the three exercises of Lecture 5. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
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))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
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
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify that at , "upwind", "lax_wendroff", and "lax_friedrichs" all satisfy across , and confirm to for .
heading("Exercise 1: Exact Unit-Courant Shift Property & Lax-Wendroff Fourth-Order Modulus")
th = np.linspace(0.0, np.pi, 200)
g_shift = np.exp(-1j * th)
for sc in ("upwind", "lax_wendroff", "lax_friedrichs"):
out = constants.von_neumann_advection_diffusion_amp(th, cfl=1.0, r_diff=0.0, scheme=sc)
err = float(np.max(np.abs(out["G"] - g_shift)))
print(f"C = 1.0 ({sc:14s}): max |G(theta) - exp(-i*theta)| = {err:.2e}")
assert err < 1.0e-14
for c_val in (0.35, 0.70):
out_lw = constants.von_neumann_advection_diffusion_amp(th, cfl=c_val, r_diff=0.0, scheme="lax_wendroff")
mag2_formula = 1.0 - 4.0 * (c_val ** 2) * (1.0 - c_val ** 2) * (np.sin(0.5 * th) ** 4)
diff_lw = float(np.max(np.abs(out_lw["magnitude"] ** 2 - mag2_formula)))
print(f"Lax-Wendroff C = {c_val:.2f}: max ||G|^2 - [1 - 4C^2(1-C^2)sin^4(theta/2)]| = {diff_lw:.2e}")
assert diff_lw < 1.0e-14
Exercise 1: Exact Unit-Courant Shift Property & Lax-Wendroff Fourth-Order Modulus
=================================================================================
C = 1.0 (upwind ): max |G(theta) - exp(-i*theta)| = 1.11e-16
C = 1.0 (lax_wendroff ): max |G(theta) - exp(-i*theta)| = 1.11e-16
C = 1.0 (lax_friedrichs): max |G(theta) - exp(-i*theta)| = 0.00e+00
Lax-Wendroff C = 0.35: max ||G|^2 - [1 - 4C^2(1-C^2)sin^4(theta/2)]| = 4.44e-16
Lax-Wendroff C = 0.70: max ||G|^2 - [1 - 4C^2(1-C^2)sin^4(theta/2)]| = 3.61e-16
Explanation. At , characteristics starting at grid point land exactly on grid point one step later (), eliminating spatial interpolation error across all three stable stencils. For , is fourth-order weakly dissipative.
Exercise 2¶
Problem. 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 . Verify ValueError on unknown scheme names.
heading("Exercise 2: Tiny-dt Pathologies in FTCS & Lax-Friedrichs")
Nx = 100
for c_v in (0.5, 0.1, 0.02):
nt = int(round(Nx / c_v))
g_ftcs = constants.von_neumann_advection_diffusion_amp(0.5 * np.pi, cfl=c_v, r_diff=0.0, scheme="ftcs")["magnitude"]
g_lf = constants.von_neumann_advection_diffusion_amp(np.pi / 8.0, cfl=c_v, r_diff=0.0, scheme="lax_friedrichs")["magnitude"]
tot_ftcs = g_ftcs ** nt
tot_lf = g_lf ** nt
print(f"C = {c_v:4.2f} (Nt = {nt:4d} steps/period) | FTCS |G(pi/2)|^Nt = {tot_ftcs:11.3e} (>1) | Lax-Friedrichs |G(pi/8)|^Nt = {tot_lf:11.3e}")
assert tot_ftcs > 1.0
# Compare Lax-Friedrichs survival at C = 0.9 vs C = 0.02:
g_lf_09 = constants.von_neumann_advection_diffusion_amp(np.pi / 8.0, cfl=0.9, r_diff=0.0, scheme="lax_friedrichs")["magnitude"] ** (Nx / 0.9)
g_lf_002 = constants.von_neumann_advection_diffusion_amp(np.pi / 8.0, cfl=0.02, r_diff=0.0, scheme="lax_friedrichs")["magnitude"] ** (Nx / 0.02)
assert g_lf_09 > 0.15 and g_lf_002 < 1.0e-100
caught_scheme = False
try:
constants.von_neumann_advection_diffusion_amp(0.5, cfl=0.5, scheme="crank_nicolson_unknown")
except ValueError:
caught_scheme = True
assert caught_scheme
Exercise 2: Tiny-dt Pathologies in FTCS & Lax-Friedrichs
========================================================
C = 0.50 (Nt = 200 steps/period) | FTCS |G(pi/2)|^Nt = 4.909e+09 (>1) | Lax-Friedrichs |G(pi/8)|^Nt = 8.852e-06
C = 0.10 (Nt = 1000 steps/period) | FTCS |G(pi/2)|^Nt = 1.448e+02 (>1) | Lax-Friedrichs |G(pi/8)|^Nt = 9.718e-35
C = 0.02 (Nt = 5000 steps/period) | FTCS |G(pi/2)|^Nt = 2.718e+00 (>1) | Lax-Friedrichs |G(pi/8)|^Nt = 1.417e-172
Explanation. Because Lax–Friedrichs replaces with the neighbor average every step regardless of how small is, its modified viscosity scales inversely with . Taking 5000 small steps () damps even a smooth 16-cell wave by 10-173.
Exercise 3¶
Problem. Implement ftcs_advection_diffusion_limits(pe_cell) returning exact for explicit 1-D "ftcs" given , and verify across that is stable == True while is stable == False.
heading("Exercise 3: Implement It Yourself — Exact FTCS Advection-Diffusion Stability Boundary")
def ftcs_advection_diffusion_limits(pe_cell: float) -> dict:
"""Return exact maximum stable (cfl_max, r_max) for explicit 1-D FTCS at cell Peclet pe_cell."""
pe_abs = abs(float(pe_cell))
if pe_abs <= 0.0:
return {"cfl_max": 0.0, "r_max": 0.5}
# From C = pe_abs * r, C^2 <= 2*r => r <= 2 / pe_abs^2, combined with r <= 0.5:
r_max = min(0.5, 2.0 / (pe_abs ** 2))
cfl_max = pe_abs * r_max
return {"cfl_max": float(cfl_max), "r_max": float(r_max)}
th_verify = np.linspace(0.0, np.pi, 1025)
for pe_c in (0.5, 1.0, 2.0, 5.0, 10.0):
lim = ftcs_advection_diffusion_limits(pe_c)
c_m, r_m = lim["cfl_max"], lim["r_max"]
in_bnd = constants.von_neumann_advection_diffusion_amp(th_verify, cfl=0.99 * c_m, r_diff=0.99 * r_m, scheme="ftcs")
out_bnd = constants.von_neumann_advection_diffusion_amp(th_verify, cfl=1.02 * c_m, r_diff=1.02 * r_m, scheme="ftcs")
print(f"|Pe_dx| = {pe_c:4.1f} -> C_max = {c_m:.4f}, r_max = {r_m:.4f} | 0.99*limit stable={in_bnd['stable']} | 1.02*limit stable={out_bnd['stable']}")
assert in_bnd["stable"] is True
assert out_bnd["stable"] is False
# Notice the peak Courant number C_max = 1.0 occurs right at |Pe_dx| = 2.0
assert np.isclose(ftcs_advection_diffusion_limits(2.0)["cfl_max"], 1.0, rtol=1e-14)
Exercise 3: Implement It Yourself — Exact FTCS Advection-Diffusion Stability Boundary
=====================================================================================
|Pe_dx| = 0.5 -> C_max = 0.2500, r_max = 0.5000 | 0.99*limit stable=True | 1.02*limit stable=False
|Pe_dx| = 1.0 -> C_max = 0.5000, r_max = 0.5000 | 0.99*limit stable=True | 1.02*limit stable=False
|Pe_dx| = 2.0 -> C_max = 1.0000, r_max = 0.5000 | 0.99*limit stable=True | 1.02*limit stable=False
|Pe_dx| = 5.0 -> C_max = 0.4000, r_max = 0.0800 | 0.99*limit stable=True | 1.02*limit stable=False
|Pe_dx| = 10.0 -> C_max = 0.2000, r_max = 0.0200 | 0.99*limit stable=True | 1.02*limit stable=False
Summary. Explicit FTCS advection–diffusion achieves its maximum allowable Courant number at the cell Péclet number (, where FTCS algebraically simplifies to exact upwind shifting ), and shrinks as at higher Péclet numbers.