Worked solutions to the three exercises of Lecture 1. 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: 1-D & 2-D Cell-Centered FVM Mesh Invariants & Midpoint Quadrature")
g1 = grids_fvm.uniform_fvm_grid_1d(x_min=0.0, x_max=2.0, n_cells=8)
g2 = grids_fvm.uniform_fvm_grid_2d(Lx=2.0, Ly=1.5, nx=12, ny=8)
print(f"1-D FVM: {g1['n_cells']} cells, {g1['x_faces'].size} faces, dx = {g1['dx']:.4f}")
print(f"First/last centroids: x_0 = {g1['x_centers'][0]:.4f}, x_{{N-1}} = {g1['x_centers'][-1]:.4f} (half-cell inset dx/2 = {0.5*g1['dx']:.4f})")
print(f"2-D FVM: XC shape = {g2['XC'].shape}, cell_area = {g2['cell_area']:.5f}, total area = {g2['nx']*g2['ny']*g2['cell_area']:.4f}")
# Exactness of FVM midpoint quadrature on any bilinear field f(x, y) = 3 + 2x - 4y + 1.5xy:
f_2d = 3.0 + 2.0 * g2["XC"] - 4.0 * g2["YC"] + 1.5 * g2["XC"] * g2["YC"]
int_fvm = float(np.sum(f_2d) * g2["cell_area"])
Lx, Ly = 2.0, 1.5
int_exact = 3.0 * Lx * Ly + 1.0 * (Lx ** 2) * Ly - 2.0 * Lx * (Ly ** 2) + 0.375 * (Lx ** 2) * (Ly ** 2)
print(f"Bilinear 2-D integral: FVM = {int_fvm:.12f} vs Exact = {int_exact:.12f}")
assert np.isclose(np.sum(g1["volumes"]), 2.0, rtol=1e-15)
assert np.isclose(g1["x_centers"][0], 0.5 * g1["dx"], rtol=1e-15)
assert np.isclose(int_fvm, int_exact, rtol=1e-14)
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Verify the uniform limit (beta_cluster=1e-5) and two_sided=True mirror symmetry of tanh_stretched_grid_1d, then confirm convergence of verify_discrete_gauss_divergence_2d against analytical for across .
heading("Exercise 1: Asymptotic Tanh Grid Identities & O(h^2) 2-D Divergence Convergence")
u_ref = grids_fvm.uniform_fvm_grid_1d(0.0, 1.0, 20)
for two_s in (True, False):
t_lim = grids_fvm.tanh_stretched_grid_1d(0.0, 1.0, 20, beta_cluster=1.0e-5, two_sided=two_s)
err = float(np.max(np.abs(t_lim["x_faces"] - u_ref["x_faces"])))
print(f"two_sided={str(two_s):5s} | beta=1e-5 max face diff vs uniform = {err:.2e}")
assert err < 1.0e-10
t_sym = grids_fvm.tanh_stretched_grid_1d(-1.0, 1.0, 30, beta_cluster=3.0, two_sided=True)
assert np.allclose(t_sym["volumes"], t_sym["volumes"][::-1], rtol=1e-14)
assert np.allclose(t_sym["x_centers"], -t_sym["x_centers"][::-1], atol=1e-15)
errs = []
ns = [16, 32, 64, 128]
for n in ns:
g = grids_fvm.uniform_fvm_grid_2d(1.0, 1.0, n, n)
xf, ycx = np.meshgrid(g["x_faces"], g["yc"], indexing="ij")
xcy, yf = np.meshgrid(g["xc"], g["y_faces"], indexing="ij")
fx = np.sin(2.0 * xf) * np.cos(ycx)
fy = np.cos(xcy) * np.sin(2.0 * yf)
out = grids_fvm.verify_discrete_gauss_divergence_2d(fx, fy, g["dx"], g["dy"])
div_exact = 2.0 * np.cos(2.0 * g["XC"]) * np.cos(g["YC"]) + 2.0 * np.cos(g["XC"]) * np.cos(2.0 * g["YC"])
errs.append(float(np.max(np.abs(out["div_cells"] - div_exact))))
assert out["discrepancy"] < 1.0e-14
orders = [np.log2(errs[k] / errs[k + 1]) for k in range(len(ns) - 1)]
for n, e in zip(ns, errs):
print(f"N = {n:3d}x{n:<3d} | max |div_h - div_exact| = {e:.4e}")
print("Observed convergence orders:", [round(float(p), 4) for p in orders])
assert all(p > 1.99 for p in orders)
Exercise 1: Asymptotic Tanh Grid Identities & O(h^2) 2-D Divergence Convergence
===============================================================================
two_sided=True | beta=1e-5 max face diff vs uniform = 6.40e-12
two_sided=False | beta=1e-5 max face diff vs uniform = 1.28e-11
N = 16x16 | max |div_h - div_exact| = 2.5973e-03
N = 32x32 | max |div_h - div_exact| = 6.5061e-04
N = 64x64 | max |div_h - div_exact| = 1.6273e-04
N = 128x128 | max |div_h - div_exact| = 4.0688e-05
Observed convergence orders: [1.9971, 1.9993, 1.9998]
Explanation. Since , the stretching map differs from uniform spacing by at . On staggered face midpoints, centered differences approximate at cell centroids with clean truncation error (observed order 2.000).
Exercise 2¶
Problem. Demonstrate across a discontinuous shock-like step , on that conservative FVM flux telescoping reproduces the exact momentum flux jump on every grid , whereas non-conservative fails with an conservation error that never vanishes as . Also verify staggered shape ValueError guards.
heading("Exercise 2: Conservative Telescoping vs Non-Conservative Shock Failure")
u_L, u_R = 2.0, 0.5
exact_flux_jump = 0.5 * (u_R ** 2 - u_L ** 2) # -1.875
for n in (20, 200, 2000):
g = grids_fvm.uniform_fvm_grid_1d(0.0, 1.0, n)
u_cell = np.where(g["x_centers"] < 0.5, u_L, u_R)
# Upwind interface state (since u > 0 everywhere):
u_face = np.empty(n + 1)
u_face[0] = u_L
u_face[1:] = u_cell
flux_face = 0.5 * (u_face ** 2)
cons_integral = float(np.sum(flux_face[1:] - flux_face[:-1]))
noncons_integral = float(np.sum(u_cell * (u_face[1:] - u_face[:-1])))
print(f"N = {n:4d} | Conservative = {cons_integral:+.6f} (exact {exact_flux_jump:+.6f}) | Non-conservative = {noncons_integral:+.6f} (spurious source = {noncons_integral - exact_flux_jump:+.6f})")
assert np.isclose(cons_integral, exact_flux_jump, rtol=1e-14)
assert abs(noncons_integral - exact_flux_jump) > 1.0 # O(1) Hou-LeFloch conservation error
# Verify staggered shape guard in verify_discrete_gauss_divergence_2d:
caught_shape = False
try:
grids_fvm.verify_discrete_gauss_divergence_2d(np.zeros((10, 8)), np.zeros((10, 8)), 0.1, 0.1)
except ValueError:
caught_shape = True
assert caught_shape
Exercise 2: Conservative Telescoping vs Non-Conservative Shock Failure
======================================================================
N = 20 | Conservative = -1.875000 (exact -1.875000) | Non-conservative = -0.750000 (spurious source = +1.125000)
N = 200 | Conservative = -1.875000 (exact -1.875000) | Non-conservative = -0.750000 (spurious source = +1.125000)
N = 2000 | Conservative = -1.875000 (exact -1.875000) | Non-conservative = -0.750000 (spurious source = +1.125000)
Explanation. At the jump cell where and , the non-conservative product misses the true Rankine–Hugoniot average by , no matter how fine becomes. That is why shock-capturing solvers (Lectures 8 to 10) must discretize the divergence (flux) form.
Exercise 3¶
Problem. Implement design_channel_mesh_for_yplus(H_m, n_cells, u_tau_m_s, nu_m2_s, target_yplus=1.0) using bisection on beta_cluster in tanh_stretched_grid_1d(..., two_sided=True) so , and test on a water channel ().
heading("Exercise 3: Implement It Yourself — Automated y+ <= 1 Turbulent Channel Mesh Designer")
def design_channel_mesh_for_yplus(
H_m: float,
n_cells: int,
u_tau_m_s: float,
nu_m2_s: float,
target_yplus: float = 1.0,
) -> dict:
"""Find two-sided tanh beta_cluster achieving first-centroid wall coordinate y1+ = target_yplus."""
unif = grids_fvm.uniform_fvm_grid_1d(0.0, H_m, n_cells)
yplus_unif = u_tau_m_s * unif["x_centers"][0] / nu_m2_s
if yplus_unif <= target_yplus:
return {"beta_opt": 0.0, "y1_plus": yplus_unif, "y1_plus_uniform": yplus_unif, "grid": unif}
lo, hi = 1.0e-4, 8.0
for _ in range(60):
mid = 0.5 * (lo + hi)
g = grids_fvm.tanh_stretched_grid_1d(0.0, H_m, n_cells, beta_cluster=mid, two_sided=True)
yp = u_tau_m_s * g["x_centers"][0] / nu_m2_s
if yp > target_yplus:
lo = mid
else:
hi = mid
beta_opt = 0.5 * (lo + hi)
g_opt = grids_fvm.tanh_stretched_grid_1d(0.0, H_m, n_cells, beta_cluster=beta_opt, two_sided=True)
y1_opt = u_tau_m_s * g_opt["x_centers"][0] / nu_m2_s
return {"beta_opt": beta_opt, "y1_plus": y1_opt, "y1_plus_uniform": yplus_unif, "grid": g_opt}
nu_water = constants.FLUIDS_DB["water_298K"]["nu_m2_s"]
design = design_channel_mesh_for_yplus(H_m=0.04, n_cells=64, u_tau_m_s=0.045, nu_m2_s=nu_water, target_yplus=1.0)
print(f"Uniform N=64 water channel y1+ = {design['y1_plus_uniform']:.2f} (far in buffer layer)")
print(f"Optimal two-sided tanh beta = {design['beta_opt']:.4f} -> y1+ = {design['y1_plus']:.6f}, stretching_ratio = {design['grid']['stretching_ratio']:.2f}")
assert design["y1_plus_uniform"] > 15.0
assert np.isclose(design["y1_plus"], 1.0, rtol=1e-10)
assert np.isclose(np.sum(design["grid"]["volumes"]), 0.04, rtol=1e-15)
Exercise 3: Implement It Yourself — Automated y+ <= 1 Turbulent Channel Mesh Designer
=====================================================================================
Uniform N=64 water channel y1+ = 15.75 (far in buffer layer)
Optimal two-sided tanh beta = 2.5875 -> y1+ = 1.000000, stretching_ratio = 41.14
Summary. On cells, a uniform grid lands in the turbulent buffer layer (), whereas a smooth two-sided mesh with hits inside the linear viscous sublayer () without adding a single extra unknown.