In a turbulent channel flow at friction Reynolds number , of the velocity drop occurs inside a viscous wall sublayer thinner than of the channel height. Covering the whole domain with uniform cells fine enough to put 5 points inside that sublayer would waste of the CPU budget in the quiescent core. Yet if we stretch the mesh non-uniformly, how do we prevent geometric metric errors from creating fake mass or momentum out of thin air? In this lecture, we build cell-centered Finite-Volume meshes (uniform_fvm_grid_1d, uniform_fvm_grid_2d, and Vinokur’s tanh_stretched_grid_1d) and show that telescoping face fluxes satisfy the 2-D discrete Gauss divergence theorem (verify_discrete_gauss_divergence_2d) to rounding error on any flux field.
Learning objectives¶
Distinguish cell-centered FVM control volumes (where centroids sit inside walls) from vertex-centered grids using
uniform_fvm_grid_1danduniform_fvm_grid_2d.Cluster wall-normal FVM cells into thin viscous or concentration boundary layers via
tanh_stretched_grid_1d(one-sided and two-sided) while preserving exact volume partition .Quantify boundary-layer quadrature and wall-gradient resolution improvements on stretched vs. uniform FVM grids.
Prove exact telescoping flux cancellation and free-stream preservation in 2-D using
verify_discrete_gauss_divergence_2d.
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. Cell-Centered Finite-Volume Grids vs. Vertex Grids¶
1.1 Partitioning Space into Control Volumes¶
In a cell-centered Finite-Volume Method (FVM) on , we first place cell faces:
Cell occupies control volume (or in zero-based array indexing, faces[i] to faces[i+1]) with exact cell volume and geometric centroid:
Unlike vertex-centered finite differences, which store unknowns directly on walls, cell-centered FVM stores cell averages at interior centroids () and enforces boundary fluxes directly on the exterior faces faces[0] and faces[-1].
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)
Demonstration 1: 1-D & 2-D Cell-Centered FVM Mesh Invariants & Midpoint Quadrature
==================================================================================
1-D FVM: 8 cells, 9 faces, dx = 0.2500
First/last centroids: x_0 = 0.1250, x_{N-1} = 1.8750 (half-cell inset dx/2 = 0.1250)
2-D FVM: XC shape = (12, 8), cell_area = 0.03125, total area = 3.0000
Bilinear 2-D integral: FVM = 9.375000000000 vs Exact = 9.375000000000
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9.6, 4.2))
x_uniform = grids_fvm.uniform_fvm_grid_1d(0.0, 1.0, 16)["x_faces"]
y_two = grids_fvm.tanh_stretched_grid_1d(0.0, 1.0, 16, beta_cluster=2.8, two_sided=True)["x_faces"]
y_one = grids_fvm.tanh_stretched_grid_1d(0.0, 1.0, 16, beta_cluster=2.8, two_sided=False)["x_faces"]
for ax, y_faces, title in [(ax1, y_two, "two-sided stretching"), (ax2, y_one, "one-sided stretching")]:
for xf in x_uniform:
ax.plot([xf, xf], [0.0, 1.0], color="C0", lw=0.7)
for yf in y_faces:
ax.plot([0.0, 1.0], [yf, yf], color="C0", lw=0.7)
ax.set_xlabel("$x$ [-]"); ax.set_ylabel("$y$ [-]"); ax.set_title(title); ax.set_aspect("equal")
label_panels(fig)
plt.show()
Figure 1.1. Finite-volume grids of cells, uniform in and stretched in with . (a) Cells clustered at both walls. (b) Cells clustered at the wall .
What Demonstration 1 shows. Because every cell centroid is the exact first-moment center of mass of , cell-centered FVM integrates linear and bilinear fields to machine precision () even on coarse grids, and its total volume equals the physical domain size without boundary trapezoid half-weights.
2. Boundary-Layer Clustering via Hyperbolic-Tangent Stretching¶
To pack cells near walls smoothly ( mapping so metric derivatives remain smooth and preserve second-order accuracy), grids_fvm.tanh_stretched_grid_1d implements Vinokur’s hyperbolic-tangent transformations parameterized by clustering strength :
two_sided=Trueclusters faces symmetrically against both walls and (plane Poiseuille / turbulent channel / cavity flow).two_sided=Falseclusters faces near and expands smoothly toward (external flat-plate boundary layer).
heading("Demonstration 2: Vinokur Hyperbolic-Tangent Boundary-Layer Meshes (N = 32)")
N_bl = 32
delta_sub = 0.02 # thin viscous sublayer thickness delta/L = 2%
print(f"{'Mesh Mode':22s} | {'beta':>5s} | {'min_dx':>10s} | {'max_dx':>10s} | {'Ratio':>8s} | {'Sum(dV)':>9s} | {'Cells in y<=0.02':>16s}")
print("-" * 96)
u_mesh = grids_fvm.uniform_fvm_grid_1d(0.0, 1.0, N_bl)
n_in_u = int(np.sum(u_mesh["x_centers"] <= delta_sub))
print(f"{'Uniform':22s} | {'0.0':>5s} | {u_mesh['dx']:10.6f} | {u_mesh['dx']:10.6f} | {1.0:8.2f} | {np.sum(u_mesh['volumes']):9.6f} | {n_in_u:16d}")
for mode_label, two_s in [("Two-sided (channel)", True), ("One-sided (flat plate)", False)]:
for beta in (1.5, 2.5, 3.2):
sg = grids_fvm.tanh_stretched_grid_1d(0.0, 1.0, N_bl, beta_cluster=beta, two_sided=two_s)
n_in = int(np.sum(sg["x_centers"] <= delta_sub))
vol_sum = float(np.sum(sg["volumes"]))
assert np.isclose(vol_sum, 1.0, rtol=1e-15)
print(
f"{mode_label:22s} | {beta:5.1f} | {sg['min_dx']:10.6f} | {sg['max_dx']:10.6f} | "
f"{sg['stretching_ratio']:8.2f} | {vol_sum:9.6f} | {n_in:16d}"
)
sg_strong = grids_fvm.tanh_stretched_grid_1d(0.0, 1.0, N_bl, beta_cluster=3.2, two_sided=False)
assert n_in_u == 1 and int(np.sum(sg_strong["x_centers"] <= delta_sub)) >= 8
Demonstration 2: Vinokur Hyperbolic-Tangent Boundary-Layer Meshes (N = 32)
==========================================================================
Mesh Mode | beta | min_dx | max_dx | Ratio | Sum(dV) | Cells in y<=0.02
------------------------------------------------------------------------------------------------
Uniform | 0.0 | 0.031250 | 0.031250 | 1.00 | 1.000000 | 1
Two-sided (channel) | 1.5 | 0.010193 | 0.051636 | 5.07 | 1.000000 | 2
Two-sided (channel) | 2.5 | 0.002466 | 0.078547 | 31.85 | 1.000000 | 4
Two-sided (channel) | 3.2 | 0.000817 | 0.099016 | 121.26 | 1.000000 | 6
One-sided (flat plate) | 1.5 | 0.009765 | 0.051749 | 5.30 | 1.000000 | 2
One-sided (flat plate) | 2.5 | 0.002277 | 0.079024 | 34.71 | 1.000000 | 6
One-sided (flat plate) | 3.2 | 0.000735 | 0.100000 | 135.97 | 1.000000 | 10
What Demonstration 2 shows. With total cells, a uniform grid places only 1 cell centroid inside the wall sublayer (), so that the wall shear stress cannot be resolved. Turning on tanh_stretched_grid_1d with shrinks the wall cell to (6 centroids inside ) while keeping to 10-16 because FVM cell volumes are defined directly as .
3. Resolving Steep Wall Shear Layers on Stretched vs. Uniform Meshes¶
Consider a Hartmann / turbulent-like steep channel velocity profile on () with thin wall layers of thickness ():
We compare wall-shear estimation (for no-slip ) and bulk flow-rate integration across uniform vs. stretched meshes.
heading("Demonstration 3: Resolving Steep Channel Wall Layers (Ha = 40) with N = 24 Cells")
Ha = 40.0
H_chan = 1.0
def exact_channel_u(y: np.ndarray) -> np.ndarray:
# Overflow-safe hyperbolic ratio cosh(Ha*(2y-1))/cosh(Ha):
z = np.abs(2.0 * y / H_chan - 1.0)
num = np.exp(Ha * (z - 1.0)) + np.exp(-Ha * (z + 1.0))
den = 1.0 + np.exp(-2.0 * Ha)
return 1.0 - num / den
du_dy_exact = (2.0 * Ha / H_chan) * np.tanh(Ha)
q_bulk_exact = H_chan * (1.0 - np.tanh(Ha) / Ha)
g_unif = grids_fvm.uniform_fvm_grid_1d(0.0, H_chan, 24)
g_tanh = grids_fvm.tanh_stretched_grid_1d(0.0, H_chan, 24, beta_cluster=2.8, two_sided=True)
u_unif = exact_channel_u(g_unif["x_centers"])
u_tanh = exact_channel_u(g_tanh["x_centers"])
du_unif = u_unif[0] / g_unif["x_centers"][0]
du_tanh = u_tanh[0] / g_tanh["x_centers"][0]
q_unif = float(np.sum(u_unif * g_unif["volumes"]))
q_tanh = float(np.sum(u_tanh * g_tanh["volumes"]))
print(f"Exact wall gradient du/dy|_0 = {du_dy_exact:.4f} s^-1 | Uniform (N=24): {du_unif:.4f} (err {100*abs(du_unif-du_dy_exact)/du_dy_exact:.1f}%) | Tanh (beta=2.8): {du_tanh:.4f} (err {100*abs(du_tanh-du_dy_exact)/du_dy_exact:.2f}%)")
print(f"Exact bulk flow rate Q = {q_bulk_exact:.6f} m^2/s | Uniform err = {abs(q_unif-q_bulk_exact):.2e} | Tanh err = {abs(q_tanh-q_bulk_exact):.2e}")
y_fine = np.linspace(0.0, H_chan, 600)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.2, 4.2))
ax1.plot(y_fine, exact_channel_u(y_fine), "-", color="#111111", lw=2.0, label="Exact Hartmann/BL profile")
ax1.plot(g_unif["x_centers"], u_unif, "s--", color="#d62728", ms=5, label="Uniform FVM ($N=24$)")
ax1.plot(g_tanh["x_centers"], u_tanh, "o-", color="#1f77b4", ms=5, label=r"Tanh stretched ($\beta=2.8, N=24$)")
ax1.set_xlim(0.0, 0.15)
ax1.set_xlabel("Wall Distance $y$ [m] (zoom near $y=0$)")
ax1.set_ylabel("Velocity $u(y)/U_0$ [-]")
ax1.set_title("Near-Wall Centroid Resolution ($N=24$)")
ax1.legend(fontsize=8.5, frameon=False)
ax2.plot(np.arange(25), g_unif["x_faces"], "--", color="#d62728", lw=1.8, label="Uniform faces")
ax2.plot(np.arange(25), g_tanh["x_faces"], "o-", color="#1f77b4", ms=4, label=r"Two-sided $\tanh$ ($\beta=2.8$)")
g_one = grids_fvm.tanh_stretched_grid_1d(0.0, H_chan, 24, beta_cluster=2.8, two_sided=False)
ax2.plot(np.arange(25), g_one["x_faces"], "^-.", color="#2ca02c", ms=4, label=r"One-sided $\tanh$ ($\beta=2.8$)")
ax2.set_xlabel("Face Index $i$ [-]")
ax2.set_ylabel("Physical Coordinate $y_{i+1/2}$ [m]")
ax2.set_title("Vinokur Stretching Maps $s(\\xi)$")
ax2.legend(fontsize=8.5, frameon=False)
label_panels(fig)
plt.show()
assert abs(du_unif - du_dy_exact) / du_dy_exact > 0.50
assert abs(du_tanh - du_dy_exact) / du_dy_exact < 0.05
Demonstration 3: Resolving Steep Channel Wall Layers (Ha = 40) with N = 24 Cells
================================================================================
Exact wall gradient du/dy|_0 = 80.0000 s^-1 | Uniform (N=24): 38.9340 (err 51.3%) | Tanh (beta=2.8): 76.5897 (err 4.26%)
Exact bulk flow rate Q = 0.975000 m^2/s | Uniform err = 8.68e-03 | Tanh err = 5.53e-04

Figure 1.2. (a) A boundary-layer velocity profile sampled at the cell centers of a uniform grid and of a tanh-stretched grid, both with 24 cells. (b) Position of the cell faces against the face index for the uniform grid and for the two-sided and one-sided stretched grids.
What Demonstration 3 shows. On uniform cells, the first centroid sits at , already outside most of the viscous wall layer, so underpredicts wall shear stress by . Clustering those same 24 cells with cuts the wall-shear error down to and reduces bulk flow-rate quadrature error by over .
4. The 2-D Discrete Gauss Divergence Theorem & Free-Stream Preservation¶
On a 2-D Cartesian mesh of cells with staggered east/west face fluxes of shape (nx + 1, ny) and north/south face fluxes of shape (nx, ny + 1), the cell-averaged discrete divergence in cell is:
Summing over all interior cells cancels every shared interior face flux in exact telescoping pairs, leaving only exterior boundary faces (grids_fvm.verify_discrete_gauss_divergence_2d):
heading("Demonstration 4: 2-D Discrete Gauss Theorem & Free-Stream Preservation")
Lx, Ly, nx, ny = 1.6, 1.2, 24, 18
m2 = grids_fvm.uniform_fvm_grid_2d(Lx, Ly, nx, ny)
# Staggered face midpoint coordinates:
xf_2d, yc_x = np.meshgrid(m2["x_faces"], m2["yc"], indexing="ij") # (nx+1, ny)
xc_y, yf_2d = np.meshgrid(m2["xc"], m2["y_faces"], indexing="ij") # (nx, ny+1)
# 1. Smooth nonlinear vector field F = (x^2*y + sin(pi*x)*cos(pi*y), x*y^2 - cos(pi*x)*sin(pi*y))
# Notice div(F) = 2*x*y + 2*x*y = 4*x*y => exact integral over [0, Lx]x[0, Ly] is Lx^2 * Ly^2
fx_nl = (xf_2d ** 2) * yc_x + np.sin(np.pi * xf_2d) * np.cos(np.pi * yc_x)
fy_nl = xc_y * (yf_2d ** 2) - np.cos(np.pi * xc_y) * np.sin(np.pi * yf_2d)
gauss_nl = grids_fvm.verify_discrete_gauss_divergence_2d(fx_nl, fy_nl, m2["dx"], m2["dy"])
exact_int = (Lx ** 2) * (Ly ** 2)
print(f"Smooth nonlinear F: vol_int = {gauss_nl['volume_integral']:.10f}, bnd_int = {gauss_nl['boundary_integral']:.10f}, discrepancy = {gauss_nl['discrepancy']:.2e}")
print(f"Comparison vs analytical integral Lx^2*Ly^2 = {exact_int:.10f} (O(h^2) midpoint diff = {abs(gauss_nl['volume_integral']-exact_int):.2e})")
# 2. Free-stream preservation: uniform constant vector field F = (3.7, -2.1)
fx_fs = np.full((nx + 1, ny), 3.7)
fy_fs = np.full((nx, ny + 1), -2.1)
gauss_fs = grids_fvm.verify_discrete_gauss_divergence_2d(fx_fs, fy_fs, m2["dx"], m2["dy"])
print(f"Free-stream constant F: max |div_cells| = {np.max(np.abs(gauss_fs['div_cells'])):.2e}, discrepancy = {gauss_fs['discrepancy']:.2e}")
# 3. Non-differentiable random discontinuous face fluxes: telescoping conservation STILL holds
rng = np.random.default_rng(42)
gauss_rng = grids_fvm.verify_discrete_gauss_divergence_2d(
rng.standard_normal((nx + 1, ny)), rng.standard_normal((nx, ny + 1)), m2["dx"], m2["dy"]
)
print(f"Discontinuous random fluxes: vol_int = {gauss_rng['volume_integral']:+.8f}, bnd_int = {gauss_rng['boundary_integral']:+.8f}, discrepancy = {gauss_rng['discrepancy']:.2e}")
assert gauss_nl["discrepancy"] < 1.0e-14
assert np.max(np.abs(gauss_fs["div_cells"])) == 0.0 and gauss_fs["discrepancy"] == 0.0
assert gauss_rng["discrepancy"] < 1.0e-13
Demonstration 4: 2-D Discrete Gauss Theorem & Free-Stream Preservation
======================================================================
Smooth nonlinear F: vol_int = 3.6864000000, bnd_int = 3.6864000000, discrepancy = 8.88e-16
Comparison vs analytical integral Lx^2*Ly^2 = 3.6864000000 (O(h^2) midpoint diff = 0.00e+00)
Free-stream constant F: max |div_cells| = 0.00e+00, discrepancy = 0.00e+00
Discontinuous random fluxes: vol_int = +0.01118185, bnd_int = +0.01118185, discrepancy = 1.73e-18
Inside the algorithm¶
The third test of Demonstration 4 shows that even when the face fluxes are random, the discrete FVM volume integral equals the boundary surface flux integral to 10-14. Because of this telescoping property, finite-volume shock-capturing solvers never create or destroy mass internally. Below we inspect tanh_stretched_grid_1d and verify_discrete_gauss_divergence_2d and reproduce the 2-D divergence stencil from scratch.
Check against the library¶
heading("Inside the Algorithm: NumPy Staggered Divergence vs grids_fvm")
print(show_source(grids_fvm.tanh_stretched_grid_1d))
print(show_source(grids_fvm.verify_discrete_gauss_divergence_2d))
rng = np.random.default_rng(7)
nx_t, ny_t, dx_t, dy_t = 15, 11, 0.08, 0.12
fx_t = rng.uniform(-5.0, 5.0, size=(nx_t + 1, ny_t))
fy_t = rng.uniform(-5.0, 5.0, size=(nx_t, ny_t + 1))
div_np = (fx_t[1:, :] - fx_t[:-1, :]) / dx_t + (fy_t[:, 1:] - fy_t[:, :-1]) / dy_t
vol_np = float(np.sum(div_np) * dx_t * dy_t)
bnd_np = float(np.sum(fx_t[-1, :] - fx_t[0, :]) * dy_t + np.sum(fy_t[:, -1] - fy_t[:, 0]) * dx_t)
lib_out = grids_fvm.verify_discrete_gauss_divergence_2d(fx_t, fy_t, dx_t, dy_t)
assert np.allclose(div_np, lib_out["div_cells"], rtol=1e-15, atol=1e-15)
assert np.isclose(vol_np, lib_out["volume_integral"], rtol=1e-15)
assert np.isclose(bnd_np, lib_out["boundary_integral"], rtol=1e-15)
print("NumPy staggered divergence matches grids_fvm.verify_discrete_gauss_divergence_2d to 1e-15")
Inside the Algorithm: NumPy Staggered Divergence vs grids_fvm
=============================================================
def tanh_stretched_grid_1d(
x_min: float,
x_max: float,
n_cells: int,
beta_cluster: float = 2.0,
two_sided: bool = True,
) -> dict:
"""Generate boundary-layer-clustered 1-D FVM mesh via hyperbolic-tangent stretching."""
if n_cells < 2 or x_max <= x_min or beta_cluster <= 0.0:
raise ValueError("Require x_max > x_min, n_cells >= 2, and beta_cluster > 0.")
xi = np.linspace(0.0, 1.0, int(n_cells) + 1)
if two_sided:
s = 0.5 * (1.0 + np.tanh(beta_cluster * (2.0 * xi - 1.0)) / np.tanh(beta_cluster))
else:
s = 1.0 - np.tanh(beta_cluster * (1.0 - xi)) / np.tanh(beta_cluster)
faces = float(x_min) + (float(x_max) - float(x_min)) * s
centers = 0.5 * (faces[:-1] + faces[1:])
vols = np.diff(faces)
return {
"x_faces": faces,
"x_centers": centers,
"volumes": vols,
"min_dx": float(np.min(vols)),
"max_dx": float(np.max(vols)),
"stretching_ratio": float(np.max(vols) / np.min(vols)),
"n_cells": int(n_cells),
}
def verify_discrete_gauss_divergence_2d(
fx_faces: np.ndarray,
fy_faces: np.ndarray,
dx: float,
dy: float,
) -> dict:
"""Verify exact 2-D FVM telescoping identity sum_{i,j} (div_h F)_{i,j} dx*dy == boundary_flux_integral."""
fx = np.asarray(fx_faces, dtype=float)
fy = np.asarray(fy_faces, dtype=float)
nx = fx.shape[0] - 1
ny = fx.shape[1]
if fy.shape != (nx, ny + 1):
raise ValueError("Require fx_faces shape (nx+1, ny) and fy_faces shape (nx, ny+1).")
div_cells = (fx[1:, :] - fx[:-1, :]) / float(dx) + (fy[:, 1:] - fy[:, :-1]) / float(dy)
vol_int = float(np.sum(div_cells) * dx * dy)
bnd_int = float(
np.sum(fx[-1, :] - fx[0, :]) * dy + np.sum(fy[:, -1] - fy[:, 0]) * dx
)
return {
"div_cells": div_cells,
"volume_integral": vol_int,
"boundary_integral": bnd_int,
"discrepancy": abs(vol_int - bnd_int),
}
NumPy staggered divergence matches grids_fvm.verify_discrete_gauss_divergence_2d to 1e-15
Exercises¶
Worked solutions are in 01_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Verify the uniform limit (
beta_cluster=1e-5) andtwo_sided=Truemirror symmetry oftanh_stretched_grid_1d, then confirm convergence ofverify_discrete_gauss_divergence_2dagainst analytical for across .Find how it fails. 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
ValueErrorguards.Implement it yourself. Implement
design_channel_mesh_for_yplus(H_m, n_cells, u_tau_m_s, nu_m2_s, target_yplus=1.0)using bisection onbeta_clusterintanh_stretched_grid_1d(..., two_sided=True)so , and test on a water channel ().
heading("Self-check for the exercises")
u20 = grids_fvm.uniform_fvm_grid_1d(0.0, 1.0, 20)
for two_s in (True, False):
t20 = grids_fvm.tanh_stretched_grid_1d(0.0, 1.0, 20, beta_cluster=1.0e-5, two_sided=two_s)
assert np.allclose(t20["x_faces"], u20["x_faces"], atol=1.0e-10)
tsym = grids_fvm.tanh_stretched_grid_1d(0.0, 1.0, 20, beta_cluster=2.7, two_sided=True)
assert np.allclose(tsym["volumes"], tsym["volumes"][::-1], rtol=1e-14)
print("Beta -> 0 uniform limit and mirror-symmetry checks passed")
Self-check for the exercises
============================
Beta -> 0 uniform limit and mirror-symmetry checks passed