Suppose you solve steady convective heat or species transport between an inlet at and a heated outlet wall at using textbook second-order central differencing. Everything looks fine at slow speeds, until the cell Péclet number crosses 2.0, at which point your predicted concentration oscillates below 0 (negative mass) and above 1. Switching to first-order upwind eliminates the wiggles, but adds a numerical diffusivity . In this lecture, we analyze M-matrix positivity, audit all five schemes in convection_diffusion ("central", "upwind", "hybrid", Patankar’s "power_law", and Scharfetter–Gummel "exponential"), and explore multi-dimensional cross-wind false diffusion.
Learning objectives¶
Evaluate the overflow-safe analytical outflow boundary-layer solution
exact_steady_convection_diffusion_1dacross .Prove from discrete M-matrix positivity () why
"central"differencing produces unphysical spatial oscillations whenever .Derive the artificial numerical diffusivity of first-order
"upwind"and compare"hybrid", Patankar"power_law", and nodal-exact"exponential"weighting functions .Simulate 2-D oblique advection–diffusion–reaction with
fvm_convection_diffusion_2d_steadyand diagnose cross-wind false diffusion.
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. Exact Outflow Boundary Layers in 1-D Convection–Diffusion¶
1.1 Analytical Two-Point Boundary-Value Solution¶
Steady 1-D conservation of a scalar convected at constant velocity against molecular diffusivity on with and satisfies:
As , L’Hôpital’s rule recovers pure linear conduction .
For (), inlet fluid sweeps almost all the way across the domain until a thin exponential outflow boundary layer of thickness forms right against . A direct evaluation of overflows in double precision for ;
exact_steady_convection_diffusion_1drewrites the ratio in overflow-safe form .
heading("Demonstration 1: Overflow-Safe Analytical Outflow/Inflow Boundary Layers Across Pe")
xg = np.linspace(0.0, 1.0, 400)
pe_list = [-40.0, 1.0e-9, 5.0, 25.0, 200.0, 800.0]
for pe in pe_list:
phi_ex = convection_diffusion.exact_steady_convection_diffusion_1d(xg, L=1.0, u=pe, Gamma=1.0, phi_0=0.0, phi_L=1.0)
assert np.all(np.isfinite(phi_ex))
assert np.isclose(phi_ex[0], 0.0, atol=1e-14) and np.isclose(phi_ex[-1], 1.0, atol=1e-14)
x_90 = float(xg[np.searchsorted(phi_ex, 0.90)]) if pe > 0 else float(xg[np.searchsorted(phi_ex, 0.10)])
print(f"Pe = {pe:8.1e} | phi(0.5) = {phi_ex[200]:.6e} | 90% transition x = {x_90:.4f}")
# Verify Pe -> 0 linear limit:
phi_zero = convection_diffusion.exact_steady_convection_diffusion_1d(xg, L=1.0, u=1.0e-10, Gamma=1.0, phi_0=2.0, phi_L=5.0)
assert np.allclose(phi_zero, 2.0 + 3.0 * xg, atol=1e-9)
Demonstration 1: Overflow-Safe Analytical Outflow/Inflow Boundary Layers Across Pe
==================================================================================
Pe = -4.0e+01 | phi(0.5) = 1.000000e+00 | 90% transition x = 0.0050
Pe = 1.0e-09 | phi(0.5) = 5.012531e-01 | 90% transition x = 0.9023
Pe = 5.0e+00 | phi(0.5) = 7.637761e-02 | 90% transition x = 0.9799
Pe = 2.5e+01 | phi(0.5) = 3.845237e-06 | 90% transition x = 0.9975
Pe = 2.0e+02 | phi(0.5) = 4.779666e-44 | 90% transition x = 1.0000
Pe = 8.0e+02 | phi(0.5) = 5.219035e-174 | 90% transition x = 1.0000
What Demonstration 1 shows. At (where np.exp(800) would return inf), exact_steady_convection_diffusion_1d remains smooth and finite: stays essentially zero across of the tube and jumps from 0 to 1 inside the final .
2. Cell Péclet Number & Why Central Differencing Oscillates for ¶
Integrating over cell with convective flux and diffusive conductance defines the cell Péclet number . Writing :
Central differencing (
"central"): interpolates , giving east neighbor coefficient:
Whenever , . Increasing downstream now decreases , violating Scarborough’s discrete maximum principle and generating sawtooth spatial oscillations.
heading("Demonstration 2: Benchmarking All 5 FVM Schemes at Pe = 50 on N = 10 Cells (Pe_dx = 5.0 > 2)")
schemes = ["central", "upwind", "hybrid", "power_law", "exponential"]
results_s = {}
print(f"{'Scheme':13s} | {'Pe_cell':>7s} | {'min(phi)':>10s} | {'max(phi)':>10s} | {'Bounded [0,1]?':>14s} | {'Max Nodal Err':>13s}")
print("-" * 82)
for sc in schemes:
res = convection_diffusion.fvm_convection_diffusion_1d(
n_cells=10, L=1.0, u=50.0, Gamma=1.0, phi_0=0.0, phi_L=1.0, scheme=sc
)
results_s[sc] = res
print(
f"{sc:13s} | {res['cell_peclet']:7.2f} | {np.min(res['phi']):+10.5f} | {np.max(res['phi']):+10.5f} | "
f"{str(res['bounded_no_overshoot']):>14s} | {res['max_error']:13.3e}"
)
assert results_s["central"]["bounded_no_overshoot"] is False
assert np.min(results_s["central"]["phi"]) < -0.10 # severe unphysical negative concentration
for pos_sc in ("upwind", "hybrid", "power_law", "exponential"):
assert results_s[pos_sc]["bounded_no_overshoot"] is True
assert results_s["exponential"]["max_error"] < 1.0e-13
assert results_s["power_law"]["max_error"] < 5.0e-3
Demonstration 2: Benchmarking All 5 FVM Schemes at Pe = 50 on N = 10 Cells (Pe_dx = 5.0 > 2)
============================================================================================
Scheme | Pe_cell | min(phi) | max(phi) | Bounded [0,1]? | Max Nodal Err
----------------------------------------------------------------------------------
central | 5.00 | -0.11110 | +0.04762 | False | 1.932e-01
upwind | 5.00 | +0.00000 | +0.28571 | True | 2.036e-01
hybrid | 5.00 | +0.00000 | +0.00000 | True | 8.208e-02
power_law | 5.00 | +0.00000 | +0.08669 | True | 4.608e-03
exponential | 5.00 | +0.00000 | +0.08208 | True | 3.903e-18
n_list = np.array([5, 10, 20, 40, 80, 160, 320])
fig, ax = plt.subplots(figsize=(6.4, 4.2))
for scheme_name, style in [("central", "s--"), ("upwind", "^:"), ("hybrid", "d-."), ("power_law", "o-")]:
pe_cells, errors = [], []
for n_c in n_list:
sol_c = convection_diffusion.fvm_convection_diffusion_1d(n_cells=int(n_c), L=1.0, u=1.0, Gamma=0.02, scheme=scheme_name)
pe_cells.append(sol_c["cell_peclet"]); errors.append(sol_c["max_error"])
ax.loglog(pe_cells, errors, style, label=scheme_name)
ax.axvline(2.0, color="0.5", ls=":", lw=1.0)
ax.set_xlabel(r"cell Péclet number $\mathrm{Pe}_{\Delta x}$ [-]"); ax.set_ylabel(r"largest error of $\phi$ [-]")
ax.legend(loc="upper left")
plt.show()
Figure 4.1. Largest error of four schemes against the cell Péclet number for a problem with , obtained by changing the number of cells from 5 to 320. The dotted line marks , above which the central scheme is unbounded.
What Demonstration 2 shows. At :
"central"predicts an unphysical negative concentration (bounded_no_overshoot == False)."upwind"restores strict positivity ([0, 1]), but smears the boundary layer (max_error = 2.04e-1) because Taylor-expanding reveals artificial numerical diffusivity ."exponential"(Scharfetter–Gummel 1969) is exact at the cell centers to rounding error ().Patankar’s
"power_law"() achievesmax_error = 4.61e-3( more accurate than upwind) using only cheap algebraic multiplications.
3. Patankar’s Generalized Weighting Framework¶
In convection_diffusion, all five schemes share a unified neighbor formula:
We plot across alongside the boundary-layer profiles from Demonstration 2.
heading("Demonstration 3: Visualizing Patankar Weighting Functions A(|Pe|) & Outflow Profiles")
pe_axis = np.linspace(0.0, 12.0, 300)
styles = {
"central": ("--", "#d62728", "Central: $1 - 0.5|\\mathrm{Pe}|$"),
"upwind": (":", "#7f7f7f", "Upwind: $1$"),
"hybrid": ("-.", "#ff7f0e", "Hybrid: $\\max(0, 1 - 0.5|\\mathrm{Pe}|)$"),
"power_law": ("-", "#1f77b4", "Power-Law: $\\max(0, (1 - 0.1|\\mathrm{Pe}|)^5)$"),
"exponential": ("-", "#111111", "Exponential: $|\\mathrm{Pe}|/(e^{|\\mathrm{Pe}|}-1)$"),
}
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.4, 4.3))
for sc in ["exponential", "power_law", "hybrid", "upwind", "central"]:
ls, col, lbl = styles[sc]
lw = 2.4 if sc == "exponential" else 1.8
a_vals = np.array([convection_diffusion._peclet_weighting_A(float(p), sc) for p in pe_axis])
ax1.plot(pe_axis, a_vals, ls=ls, color=col, lw=lw, label=lbl)
ax1.axhline(0.0, color="black", lw=0.8)
ax1.set_ylim(-1.2, 1.15)
ax1.set_xlabel(r"Cell Péclet Magnitude $|\mathrm{Pe}_{\Delta x}|$ [-]")
ax1.set_ylabel(r"Diffusive Weighting $A(|\mathrm{Pe}_{\Delta x}|)$ [-]")
ax1.set_title("Generalized Patankar Weighting Functions")
ax1.legend(fontsize=7.8, frameon=False)
xf_plot = np.linspace(0.0, 1.0, 400)
phi_plot = convection_diffusion.exact_steady_convection_diffusion_1d(xf_plot, 1.0, 50.0, 1.0)
ax2.plot(xf_plot, phi_plot, "-", color="#111111", lw=2.2, label=r"Exact PDE ($\mathrm{Pe}=50$)")
ax2.plot(results_s["central"]["x_centers"], results_s["central"]["phi"], "s--", color="#d62728", ms=5.5, label="Central (oscillates < 0)")
ax2.plot(results_s["upwind"]["x_centers"], results_s["upwind"]["phi"], "^:", color="#7f7f7f", ms=5.5, label="Upwind (smeared)")
ax2.plot(results_s["power_law"]["x_centers"], results_s["power_law"]["phi"], "o-", color="#1f77b4", ms=5.5, label="Patankar Power-Law")
ax2.set_xlabel("Position $x/L$ [-]")
ax2.set_ylabel(r"Scalar $\phi(x)$ [-]")
ax2.set_title("Outflow Boundary Layer ($N=10, \\mathrm{Pe}_{\\Delta x}=5$)")
ax2.legend(fontsize=8.2, frameon=False)
label_panels(fig)
plt.show()
# Verify Patankar power-law approximates exponential to < 0.015 across ALL |Pe| >= 0:
a_pow = np.array([convection_diffusion._peclet_weighting_A(float(p), "power_law") for p in pe_axis])
a_exp = np.array([convection_diffusion._peclet_weighting_A(float(p), "exponential") for p in pe_axis])
max_a_gap = float(np.max(np.abs(a_pow - a_exp)))
print(f"Max |A_power_law - A_exponential| over [0, 12] = {max_a_gap:.5f}")
assert max_a_gap < 0.015
Demonstration 3: Visualizing Patankar Weighting Functions A(|Pe|) & Outflow Profiles
====================================================================================

Max |A_power_law - A_exponential| over [0, 12] = 0.01467
Figure 4.2. (a) The weighting function of the five schemes. (b) The outflow boundary layer at on ten cells: the central scheme oscillates, the upwind scheme is too diffusive and the power-law scheme stays close to the exact solution.
What Demonstration 3 shows. Panel (a) shows why Patankar’s fifth-power formula is widely used: tracks the exact Bose–Einstein / Scharfetter–Gummel curve within 0.0147 everywhere, shutting off molecular diffusion smoothly around instead of prematurely chopping it off at like Spalding’s "hybrid" scheme.
4. Multi-Dimensional Oblique Flow & Cross-Wind False Diffusion¶
If "exponential" and "power_law" are nearly exact in 1-D, why don’t they solve every multi-dimensional CFD problem? We run fvm_convection_diffusion_2d_steady on a square with a diagonal velocity at (), left/top walls at , and bottom/right walls at , comparing "upwind" vs. "power_law" across the anti-diagonal perpendicular to the streamline.
heading("Demonstration 4: 2-D Oblique 45-Degree Advection — Diagnosing Cross-Wind False Diffusion")
sol_2d_up = convection_diffusion.fvm_convection_diffusion_2d_steady(
nx=32, ny=32, Lx=1.0, Ly=1.0, u_vel=1.0, v_vel=1.0, Gamma=0.02,
bc_walls={"left": 1.0, "top": 1.0, "bottom": 0.0, "right": 0.0},
scheme="upwind", tol=1e-10, max_iter=3000,
)
sol_2d_pl = convection_diffusion.fvm_convection_diffusion_2d_steady(
nx=32, ny=32, Lx=1.0, Ly=1.0, u_vel=1.0, v_vel=1.0, Gamma=0.02,
bc_walls={"left": 1.0, "top": 1.0, "bottom": 0.0, "right": 0.0},
scheme="power_law", tol=1e-10, max_iter=3000,
)
idx = np.arange(32)
ad_up = sol_2d_up["phi"][idx, 31 - idx]
ad_pl = sol_2d_pl["phi"][idx, 31 - idx]
w_up = int(np.sum((ad_up > 0.10) & (ad_up < 0.90)))
w_pl = int(np.sum((ad_pl > 0.10) & (ad_pl < 0.90)))
print(f"2-D oblique Upwind ({sol_2d_up['iterations']} sweeps): 10%-90% cross-stream width = {w_up} cells")
print(f"2-D oblique Power-Law ({sol_2d_pl['iterations']} sweeps): 10%-90% cross-stream width = {w_pl} cells")
# Verify boundedness [0, 1] and exact skew-symmetry phi(x, y) + phi(y, x) == 1 across diagonal y = x:
sym_sum = sol_2d_pl["phi"] + sol_2d_pl["phi"].T
print(f"Exact skew-symmetry check max |phi(x,y) + phi(y,x) - 1| = {np.max(np.abs(sym_sum - 1.0)):.2e}")
assert np.min(sol_2d_pl["phi"]) >= -1.0e-12 and np.max(sol_2d_pl["phi"]) <= 1.0 + 1.0e-12
assert w_up >= w_pl >= 6
assert np.allclose(sym_sum, 1.0, atol=1e-7)
Demonstration 4: 2-D Oblique 45-Degree Advection — Diagnosing Cross-Wind False Diffusion
========================================================================================
2-D oblique Upwind (60 sweeps): 10%-90% cross-stream width = 10 cells
2-D oblique Power-Law (80 sweeps): 10%-90% cross-stream width = 8 cells
Exact skew-symmetry check max |phi(x,y) + phi(y,x) - 1| = 4.06e-13
Inside the algorithm¶
Below we inspect convection_diffusion._peclet_weighting_A and convection_diffusion.fvm_convection_diffusion_1d, and verify the formal asymptotic orders of accuracy ( for "upwind" vs. for "central", "power_law", and "exponential" in the resolved regime ).
Check against the library¶
heading("Inside the Algorithm: Asymptotic Convergence Orders of Upwind O(dx) vs Power-Law/Central O(dx^2)")
print(show_source(convection_diffusion._peclet_weighting_A))
print(show_source(convection_diffusion.fvm_convection_diffusion_1d))
# Global Pe = 10 -> for N = 40, 80, 160, 320 we have Pe_dx = 0.25, 0.125, 0.0625, 0.03125 (< 2)
ns_ord = [40, 80, 160, 320]
for sc, min_ord, max_ord in [("upwind", 0.95, 1.05), ("central", 1.98, 2.02), ("power_law", 1.95, 2.05)]:
errs = [convection_diffusion.fvm_convection_diffusion_1d(n, 1.0, 10.0, 1.0, scheme=sc)["max_error"] for n in ns_ord]
p_est = np.log2(errs[-2] / errs[-1])
print(f"Scheme {sc:10s} | N=40->320 max_error: {errs[0]:.3e} -> {errs[-1]:.3e} | asymptotic order = {p_est:.3f}")
assert min_ord < p_est < max_ord
Inside the Algorithm: Asymptotic Convergence Orders of Upwind O(dx) vs Power-Law/Central O(dx^2)
================================================================================================
def _peclet_weighting_A(pe_abs: float, scheme: str) -> float:
"""Evaluate Patankar generalized neighbor-conductance weighting function A(|Pe|)."""
key = scheme.strip().lower()
if key == "central":
return 1.0 - 0.5 * pe_abs
if key == "upwind":
return 1.0
if key == "hybrid":
return max(0.0, 1.0 - 0.5 * pe_abs)
if key == "power_law":
return max(0.0, (1.0 - 0.1 * pe_abs) ** 5)
if key == "exponential":
if pe_abs < 1e-8:
return 1.0 - 0.5 * pe_abs + (pe_abs**2) / 12.0
if pe_abs > 60.0:
return 0.0
return pe_abs / (np.exp(pe_abs) - 1.0)
raise ValueError(f"Unsupported convection-diffusion scheme: {scheme!r}.")
def fvm_convection_diffusion_1d(
n_cells: int,
L: float,
u: float,
Gamma: float,
phi_0: float = 0.0,
phi_L: float = 1.0,
scheme: str = "power_law",
) -> dict:
"""Solve 1-D steady FVM convection-diffusion u*dphi/dx = Gamma*d^2phi/dx^2 on n_cells uniform cells."""
if n_cells < 2 or L <= 0.0 or Gamma <= 0.0:
raise ValueError("Require n_cells >= 2, L > 0, and Gamma > 0.")
dx = float(L) / int(n_cells)
xc = (np.arange(n_cells, dtype=float) + 0.5) * dx
f_conv = float(u)
d_int = float(Gamma) / dx
pe_cell = f_conv / d_int
a_wt = _peclet_weighting_A(abs(pe_cell), scheme)
a_west = d_int * a_wt + max(f_conv, 0.0)
a_east = d_int * a_wt + max(-f_conv, 0.0)
# Half-cell boundary distances dx/2 -> boundary diffusive conductance D_b = 2*Gamma/dx, Pe_b = Pe_cell / 2:
d_bnd = 2.0 * d_int
a_wt_bnd = _peclet_weighting_A(0.5 * abs(pe_cell), scheme)
a_left_bnd = d_bnd * a_wt_bnd + max(f_conv, 0.0)
a_right_bnd = d_bnd * a_wt_bnd + max(-f_conv, 0.0)
lower = np.full(n_cells - 1, -a_west, dtype=float)
upper = np.full(n_cells - 1, -a_east, dtype=float)
diag = np.full(n_cells, a_west + a_east, dtype=float)
rhs = np.zeros(n_cells, dtype=float)
diag[0] = a_east + a_left_bnd
rhs[0] = a_left_bnd * float(phi_0)
diag[-1] = a_west + a_right_bnd
rhs[-1] = a_right_bnd * float(phi_L)
phi = solve_tridiagonal(lower, diag, upper, rhs)
phi_exact = exact_steady_convection_diffusion_1d(xc, L=L, u=u, Gamma=Gamma, phi_0=phi_0, phi_L=phi_L)
lo_b, hi_b = min(phi_0, phi_L), max(phi_0, phi_L)
bounded = bool(np.all((phi >= lo_b - 1e-12) & (phi <= hi_b + 1e-12)))
return {
"x_centers": xc,
"phi": phi,
"phi_exact": phi_exact,
"cell_peclet": pe_cell,
"max_error": float(np.max(np.abs(phi - phi_exact))),
"bounded_no_overshoot": bounded,
}
Scheme upwind | N=40->320 max_error: 3.938e-02 -> 5.626e-03 | asymptotic order = 0.971
Scheme central | N=40->320 max_error: 1.754e-03 -> 2.957e-05 | asymptotic order = 1.983
Scheme power_law | N=40->320 max_error: 3.008e-04 -> 5.804e-06 | asymptotic order = 1.956
Exercises¶
Worked solutions are in 04_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify nodal machine-precision exactness () of
scheme="exponential"on cells across , and verify reflection symmetry across all five schemes.Find how it fails. Verify the oscillation threshold of
scheme="central"across on cells, and check numerically that"upwind"at () matches the exact analytical profile at over more closely than at true .Implement it yourself. Implement
fvm_convection_diffusion_reaction_1d(n_cells, L, u, Gamma, k_react, source, phi_0, phi_L, scheme="power_law")solving , and verify against the exact analytical characteristic-root solution for .
heading("Self-check for the exercises")
for pe_t in (-80.0, -10.0, -1.0, 0.0, 1.0, 10.0, 80.0):
r_exp = convection_diffusion.fvm_convection_diffusion_1d(8, 1.0, pe_t, 1.0, scheme="exponential")
assert r_exp["max_error"] < 1.0e-13
r_fwd = convection_diffusion.fvm_convection_diffusion_1d(10, 1.0, 25.0, 1.0, phi_0=0.0, phi_L=1.0, scheme="power_law")
r_rev = convection_diffusion.fvm_convection_diffusion_1d(10, 1.0, -25.0, 1.0, phi_0=1.0, phi_L=0.0, scheme="power_law")
assert np.allclose(r_rev["phi"], r_fwd["phi"][::-1], atol=1e-13)
print("Scharfetter-Gummel nodal exactness and flow-reversal symmetry verified")
Self-check for the exercises
============================
Scharfetter-Gummel nodal exactness and flow-reversal symmetry verified