Worked solutions to the three exercises of Lecture 13. 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 engcomprheo
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engcomprheo" / "__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/engcomprheo.git"], check=True)
import engcomprheo
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engcomprheo import (brownian_chains, constants_benchmarks, entangled_tubes, mesoscopic_suspensions_dpd,
microrheology_rheoml, shear_banding_instabilities, tensors_kinematics,
viscoelastic_fvm_2d, viscoplastic_admm)
from engcomprheo.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
trapezoid = getattr(np, "trapezoid", None) or np.trapz # NumPy 2 renamed trapz to trapezoid
def show_source(obj):
"""Return the source code of a function or class of the package."""
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: the Poisson solver and the projection step")
# 1. Verify exact discrete 5-point Neumann Laplacian inversion to machine precision (~1e-14):
nx_p, ny_p = 32, 32
hx_p, hy_p = 1.0 / nx_p, 1.0 / ny_p
xp = (np.arange(nx_p) + 0.5) * hx_p
yp = (np.arange(ny_p) + 0.5) * hy_p
Xp, Yp = np.meshgrid(xp, yp, indexing="ij")
rhs_raw = np.cos(math.pi * Xp) * np.cos(2.0 * math.pi * Yp) + 0.4 * np.cos(3.0 * math.pi * Xp)
rhs_zm = rhs_raw - float(np.mean(rhs_raw))
p_sol = viscoelastic_fvm_2d._dct2_poisson_neumann_2d(rhs_zm, hx_p, hy_p)
# Apply discrete 5-point zero-flux Neumann Laplacian (ghost cells equal boundary cells -> mode='edge'):
p_pad = np.pad(p_sol, 1, mode="edge")
neg_lap_p = -(
(p_pad[2:, 1:-1] - 2.0 * p_pad[1:-1, 1:-1] + p_pad[:-2, 1:-1]) / (hx_p**2)
+ (p_pad[1:-1, 2:] - 2.0 * p_pad[1:-1, 1:-1] + p_pad[1:-1, :-2]) / (hy_p**2)
)
alg_err = float(np.max(np.abs(neg_lap_p - rhs_zm)))
# 2. Second-order O(h^2) grid convergence against exact smooth eigenmode p_ex = cos(pi*x)*cos(2*pi*y):
errs_h2 = []
grids = [16, 32, 64]
for ng in grids:
hg = 1.0 / ng
xg = (np.arange(ng) + 0.5) * hg
Xg, Yg = np.meshgrid(xg, xg, indexing="ij")
p_true = np.cos(math.pi * Xg) * np.cos(2.0 * math.pi * Yg)
f_true = (5.0 * (math.pi**2)) * p_true
p_num = viscoelastic_fvm_2d._dct2_poisson_neumann_2d(f_true, hg, hg)
errs_h2.append(float(np.max(np.abs(p_num - p_true))))
rate_p = math.log(errs_h2[-2] / errs_h2[-1]) / math.log(2.0)
print(f"Discrete 5-point Neumann Poisson residual ||-Lap_h(p) - rhs||_inf : {alg_err:.3e}")
print(f"Grid errors (N=16, 32, 64): {[round(e, 6) for e in errs_h2]} -> observed order = {rate_p:.3f}")
assert alg_err < 1e-11
assert abs(float(np.mean(p_sol))) < 1e-14
assert 1.95 < rate_p < 2.05
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 4.0))
im = ax1.imshow(p_sol.T, extent=[0, 1, 0, 1], origin="lower", cmap="coolwarm", aspect="equal")
fig.colorbar(im, ax=ax1, fraction=0.046, pad=0.04, label="Zero-mean pressure p(x, y)")
ax1.set_xlabel("x")
ax1.set_ylabel("y")
ax1.set_title(r"Solution of the Neumann problem")
ax2.loglog(grids, errs_h2, "o-", color="#2166AC", lw=2.2, ms=6, label=f"$L_\\infty$ error (order = {rate_p:.2f})")
ax2.loglog(grids, [errs_h2[0] * (grids[0] / g) ** 2 for g in grids], "k--", lw=1.5, label="Reference slope $\\mathcal{O}(h^2)$")
ax2.set_xlabel("Grid resolution N (h = 1/N)")
ax2.set_ylabel("Max norm error $\\Vert p_h - p_{\\mathrm{exact}}\\Vert_\\infty$")
ax2.set_title(r"Error against grid size")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Check that the DEVSS-G terms do not change the steady solution. Run solve_2d_viscoelastic_cavity with nx=21, ny=21, wi=0.55, beta_s=0.30, re=0.02, n_steps=200 for , and compare the velocity fields and the position of the vortex centre.
heading("Exercise 1: the steady solution for three values of alpha_devss")
al_vals = [0.25, 0.55, 0.95]
runs_inv = {
al: viscoelastic_fvm_2d.solve_2d_viscoelastic_cavity(
nx=21, ny=21, wi=0.55, beta_s=0.30, re=0.02, alpha_devss=al, n_steps=200, dt=0.007
)
for al in al_vals
}
u_ref = runs_inv[0.55]["u"]
vc_ref = runs_inv[0.55]["vortex_center"]
for al in al_vals:
du_rms = float(np.sqrt(np.mean((runs_inv[al]["u"] - u_ref) ** 2)))
vc = runs_inv[al]["vortex_center"]
dvc = abs(vc[0] - vc_ref[0])
print(f"alpha_devss = {al:.2f} | vortex = ({vc[0]:.4f}, {vc[1]:.4f}) | |dx_c| = {dvc:.3e} | RMSE(u - u_0.55) = {du_rms:.3e}")
assert dvc < 2e-3
assert du_rms < 5e-3
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 3.9))
for al, mk, col in zip(al_vals, ["o", "s", "^"], ["#2166AC", "#0F766E", "#C0392B"]):
ax1.plot(runs_inv[al]["u"][10, :], runs_inv[al]["y"], marker=mk, ms=4.2, lw=1.8, color=col, label=f"$\\alpha$ = {al:.2f}")
ax2.plot(runs_inv[al]["x"], runs_inv[al]["trC"][:, -2], marker=mk, ms=4.2, lw=1.8, color=col, label=f"$\\alpha$ = {al:.2f}")
ax1.set_xlabel("Midline velocity u(0.5, y)"); ax1.set_ylabel("y / L")
ax1.set_title(r"Velocity on the vertical midline"); ax1.legend(fontsize=8.2)
ax2.set_xlabel("x / L"); ax2.set_ylabel("Trace $\\mathrm{tr}\\,\\mathbf{C}$ under the lid")
ax2.set_title(r"Trace of $\mathbf{C}$ under the lid"); ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
Exercise 1: the steady solution for three values of alpha_devss
===============================================================
alpha_devss = 0.25 | vortex = (0.4680, 0.7987) | |dx_c| = 2.193e-04 | RMSE(u - u_0.55) = 3.027e-03
alpha_devss = 0.55 | vortex = (0.4678, 0.8008) | |dx_c| = 0.000e+00 | RMSE(u - u_0.55) = 0.000e+00
alpha_devss = 0.95 | vortex = (0.4681, 0.8024) | |dx_c| = 2.956e-04 | RMSE(u - u_0.55) = 3.225e-03

Figure S13.1. Steady cavity flow for three values of . (a) Horizontal velocity on the vertical midline. (b) Trace of in the row of cells under the lid. The results agree to within the discretization error.
Explanation. DEVSS-G adds to the implicit side of the momentum equation and the same quantity, computed from the velocity gradient , to the explicit side. In a converged solution the two cancel except for the difference between their discretizations, which is of second order in the grid spacing. Between the three values of the vortex centre moves by less than in and by 0.004 in , and the velocity fields differ by in the root-mean-square sense. In this respect the method differs from an added artificial viscosity, which changes the solution.
Exercise 2¶
Problem. Reduce the solvent viscosity ratio, , at on a grid of cells, and compare the final residual of the velocity without stabilization (alpha_devss=0.0) and with DEVSS-G (alpha_devss=0.80).
heading("Exercise 2: convergence without stabilization as beta_s decreases")
betas_audit = [0.50, 0.12, 0.025]
res_no_devss, res_with_devss = [], []
for bs in betas_audit:
r0 = viscoelastic_fvm_2d.solve_2d_viscoelastic_cavity(nx=18, ny=18, wi=0.40, beta_s=bs, re=0.01, alpha_devss=0.0, n_steps=75, dt=0.012)
r1 = viscoelastic_fvm_2d.solve_2d_viscoelastic_cavity(nx=18, ny=18, wi=0.40, beta_s=bs, re=0.01, alpha_devss=0.80, n_steps=75, dt=0.012)
res_no_devss.append(float(r0["residual_hist"][-1]))
res_with_devss.append(float(r1["residual_hist"][-1]))
print(f"beta_s = {bs:5.3f} | unstabilized res = {res_no_devss[-1]:.3e} | DEVSS-G (0.80) res = {res_with_devss[-1]:.3e} | detC_min = {r1['detC_min']:.4f}")
assert r1["detC_min"] > 0.0
assert res_no_devss[-1] > 100.0 * res_with_devss[-1]
assert res_with_devss[-1] < 1e-3
fig, ax = plt.subplots(figsize=(7.2, 4.0))
x_pos = np.arange(len(betas_audit))
ax.bar(x_pos - 0.17, res_no_devss, width=0.34, color="#C0392B", label="Unstabilized ($\\alpha$ = 0.0)")
ax.bar(x_pos + 0.17, res_with_devss, width=0.34, color="#2166AC", label="DEVSS-G stabilized ($\\alpha$ = 0.80)")
ax.set_yscale("log")
ax.set_xticks(x_pos, [f"$\\beta_s$ = {b:.2f}" for b in betas_audit])
ax.set_ylabel("Final velocity residual $\\|u^{k+1} - u^k\\|_2$")
ax.set_title(r"Final residual against solvent viscosity ratio")
ax.legend(fontsize=8.3)
plt.show()
Exercise 2: convergence without stabilization as beta_s decreases
=================================================================
beta_s = 0.500 | unstabilized res = 9.188e-05 | DEVSS-G (0.80) res = 9.708e-05 | detC_min = 1.0001
beta_s = 0.120 | unstabilized res = 7.690e-05 | DEVSS-G (0.80) res = 9.193e-05 | detC_min = 1.0001
beta_s = 0.025 | unstabilized res = 2.584e-01 | DEVSS-G (0.80) res = 2.465e-04 | detC_min = 1.0001

Figure S13.2. Change of the velocity in the last step, without stabilization and with , for three solvent viscosity ratios. Without stabilization the run at does not converge.
Explanation. For and 0.12 both calculations reach a residual of about 10-4. At the calculation without stabilization does not converge (its residual is 0.26), while with DEVSS-G the residual is , a factor of 1000 smaller. The conformation tensor stays positive definite in all cases (the smallest determinant is 1.0001). The log-conformation formulation keeps the tensor admissible; a second measure, here DEVSS-G, is needed to keep the momentum equation well conditioned when the solvent viscosity is small.
Exercise 3¶
Problem. Write a projection step on a staggered grid ( on vertical faces, on horizontal faces, the potential at cell centres) with your own Poisson solver based on the discrete cosine transform for Neumann conditions. Check that the divergence after the projection is at the level of rounding error, and compare the Poisson solver with viscoelastic_fvm_2d._dct2_poisson_neumann_2d.
heading("Exercise 3: a cosine-transform Poisson solver and the projection step")
def dct2_neumann_scratch(rhs: np.ndarray, hx: float, hy: float) -> np.ndarray:
nx, ny = rhs.shape
f0 = rhs - float(np.mean(rhs))
def dct1d(a: np.ndarray) -> np.ndarray:
n = a.shape[0]
ext = np.concatenate([a, a[::-1, :]], axis=0)
k = np.arange(n, dtype=float)[:, None]
return (np.fft.fft(ext, axis=0)[:n, :] * np.exp(-1j * math.pi * k / (2.0 * n))).real
def idct1d(c: np.ndarray) -> np.ndarray:
n = c.shape[0]
k = np.arange(n, dtype=float)[:, None]
sp = np.zeros((2 * n, c.shape[1]), dtype=complex)
sp[:n, :] = c * np.exp(1j * math.pi * k / (2.0 * n))
sp[n + 1 :, :] = np.conj(sp[1:n, :][::-1, :])
return np.fft.ifft(sp, axis=0)[:n, :].real
hat = dct1d(dct1d(f0).T).T
kx = np.arange(nx, dtype=float)[:, None]
ky = np.arange(ny, dtype=float)[None, :]
lam = (4.0 / hx**2) * (np.sin(math.pi * kx / (2.0 * nx)) ** 2) + (4.0 / hy**2) * (np.sin(math.pi * ky / (2.0 * ny)) ** 2)
lam[0, 0] = 1.0
p_hat = hat / lam
p_hat[0, 0] = 0.0
out = idct1d(idct1d(p_hat.T).T)
return out - float(np.mean(out))
nx_m, ny_m = 32, 32
hm = 1.0 / nx_m
xf = np.linspace(0.0, 1.0, nx_m + 1)
xc = (np.arange(nx_m) + 0.5) * hm
# Tentative velocity u* on (nx+1, ny) vertical faces, v* on (nx, ny+1) horizontal faces (zero normal wall flux):
Xu, Yu = np.meshgrid(xf, xc, indexing="ij")
Xv, Yv = np.meshgrid(xc, xf, indexing="ij")
u_star = np.sin(math.pi * Xu) * np.cos(math.pi * Yu) + 0.6 * np.sin(2.0 * math.pi * Xu) * np.sin(math.pi * Yu)
v_star = -np.cos(math.pi * Xv) * np.sin(math.pi * Yv) + 0.5 * np.sin(math.pi * Xv) * np.sin(2.0 * math.pi * Yv)
u_star[[0, -1], :] = 0.0
v_star[:, [0, -1]] = 0.0
div_before = (u_star[1:, :] - u_star[:-1, :]) / hm + (v_star[:, 1:] - v_star[:, :-1]) / hm
# Solve -Lap_h(phi) = -div_before -> grad(phi) cancels divergent part of (u*, v*):
phi_sc = dct2_neumann_scratch(-div_before, hm, hm)
phi_lib = viscoelastic_fvm_2d._dct2_poisson_neumann_2d(-div_before, hm, hm)
u_proj = u_star.copy()
v_proj = v_star.copy()
u_proj[1:-1, :] -= (phi_sc[1:, :] - phi_sc[:-1, :]) / hm
v_proj[:, 1:-1] -= (phi_sc[:, 1:] - phi_sc[:, :-1]) / hm
div_after = (u_proj[1:, :] - u_proj[:-1, :]) / hm + (v_proj[:, 1:] - v_proj[:, :-1]) / hm
print(f"Max divergence before Chorin projection : {np.max(np.abs(div_before)):.4f}")
print(f"Max divergence after Chorin projection : {np.max(np.abs(div_after)):.3e}")
print(f"This solver against the package, Poisson : {np.max(np.abs(phi_sc - phi_lib)):.3e}")
assert np.allclose(phi_sc, phi_lib, atol=1e-13)
assert float(np.max(np.abs(div_after))) < 1e-12
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.2, 3.9))
im_a = ax1.imshow(div_before.T, extent=[0, 1, 0, 1], origin="lower", cmap="RdBu_r")
fig.colorbar(im_a, ax=ax1, fraction=0.046, pad=0.04)
ax1.set_title(r"Divergence before the projection")
ax1.set_xlabel("x"); ax1.set_ylabel("y")
u_cell = 0.5 * (u_proj[:-1, :] + u_proj[1:, :])
v_cell = 0.5 * (v_proj[:, :-1] + v_proj[:, 1:])
Xc_m, Yc_m = np.meshgrid(xc, xc, indexing="xy")
ax2.streamplot(xc, xc, u_cell.T, v_cell.T, color="#2166AC", density=1.1)
ax2.set_xlim(0, 1); ax2.set_ylim(0, 1); ax2.set_aspect("equal")
ax2.set_title(r"Velocity after the projection")
ax2.set_xlabel("x"); ax2.set_ylabel("y")
label_panels(fig)
plt.show()
Exercise 3: a cosine-transform Poisson solver and the projection step
=====================================================================
Max divergence before Chorin projection : 6.8589
Max divergence after Chorin projection : 1.661e-13
This solver against the package, Poisson : 0.000e+00

Figure S13.3. (a) Divergence of a test velocity field on the staggered grid. (b) Streamlines of the projected field, whose discrete divergence is at most.
Explanation. On the staggered grid, the divergence of the discrete gradient is exactly the five-point Laplacian with Neumann conditions, which the cosine transform inverts. One projection therefore removes the divergence to rounding error: it falls from 6.9 to . The Poisson solver written here and that of the package give identical results.