Worked solutions to the three exercises of Lecture 14. 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: shift of the vortex centre with Weissenberg number (Re = 0.01)")
wi_sweep = [0.0, 0.4, 0.8, 1.2]
cav_sweep = {}
vx_hist, vy_hist, peak_tr = [], [], []
for wi_v in wi_sweep:
res_c = viscoelastic_fvm_2d.solve_2d_viscoelastic_cavity(
nx=25, ny=25, wi=wi_v, beta_s=0.35, re=0.01, alpha_devss=0.55, n_steps=210, dt=0.007, regularized_lid=True
)
cav_sweep[wi_v] = res_c
vx, vy = res_c["vortex_center"]
vx_hist.append(vx)
vy_hist.append(vy)
peak_tr.append(float(np.max(res_c["trC"])))
print(f"Wi = {wi_v:4.2f} | vortex centre (x_c, y_c) = ({vx:.4f}, {vy:.4f}) | max tr(C) = {peak_tr[-1]:.3f} | detC_min = {res_c['detC_min']:.4f}")
# Creeping Stokes (Wi=0) is symmetric around x_c = 0.50; elasticity shifts x_c monotonically upstream (< 0.50)
assert abs(vx_hist[0] - 0.50) < 0.015
assert vx_hist[-1] < vx_hist[1] < vx_hist[0]
assert peak_tr[-1] > 4.0
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.1))
ax1.plot(wi_sweep, vx_hist, "o-", color="#2166AC", lw=2.3, ms=6.5, label="Vortex centre $x_c$ / L")
ax1.axhline(0.50, color="k", ls=":", lw=1.2, label="Creeping Stokes symmetry $x_c$ = 0.50")
ax1_r = ax1.twinx()
ax1_r.plot(wi_sweep, peak_tr, "s--", color="#C0392B", lw=2.0, ms=5.5, label="Peak lid stretch max $\\mathrm{tr}\\,\\mathbf{C}$")
ax1_r.set_ylabel("Peak conformation trace max $\\mathrm{tr}\\,\\mathbf{C}$", color="#C0392B")
ax1_r.tick_params(axis="y", colors="#C0392B")
ax1.set_xlabel("Weissenberg number Wi")
ax1.set_ylabel("Primary vortex horizontal position $x_c$ / L")
ax1.set_title(r"Vortex position and largest stretch")
ax1.legend(fontsize=8.0, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=1)
Xg, Yg = np.meshgrid(cav_sweep[1.2]["x"], cav_sweep[1.2]["y"], indexing="xy")
ax2.contour(Xg, Yg, cav_sweep[0.0]["streamfunction"].T, levels=8, colors="#6B7280", linestyles="--", linewidths=1.1)
ax2.contour(Xg, Yg, cav_sweep[1.2]["streamfunction"].T, levels=8, colors="#2166AC", linewidths=1.5)
ax2.plot(vx_hist[0], vy_hist[0], "k+", ms=10, mew=2.0, label=f"Stokes Wi=0 ({vx_hist[0]:.3f}, {vy_hist[0]:.3f})")
ax2.plot(vx_hist[-1], vy_hist[-1], "ro", ms=7.0, label=f"Elastic Wi=1.2 ({vx_hist[-1]:.3f}, {vy_hist[-1]:.3f})")
ax2.set_aspect("equal")
ax2.set_xlabel("x / L")
ax2.set_ylabel("y / L")
ax2.set_title(r"Streamlines at $\mathrm{Wi} = 0$ and 1.2")
ax2.legend(fontsize=8.0, loc="lower left")
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. For flow of an Oldroyd-B fluid with curved streamlines in a gap of width and radius of curvature , derive the critical Weissenberg number from the Pakdel–McKinley criterion with . Evaluate it for between 0.02 and 0.40 for the assumed parameters BOGER_PIB () and for a dilute solution (), and check each value with pakdel_mckinley_criterion.
heading("Exercise 1: critical Weissenberg number against curvature and viscosity ratio")
curv_ratios = np.linspace(0.02, 0.40, 40)
boger_db = constants_benchmarks.BENCHMARK_FLUIDS_DB["BOGER_PIB"]
beta_boger = boger_db["eta_s_Pas"] / (boger_db["eta_s_Pas"] + boger_db["eta_p_Pas"])
beta_dil = 0.85
m_c = 5.92
wi_crit_boger = m_c / np.sqrt(2.0 * (1.0 - beta_boger) * curv_ratios)
wi_crit_dil = m_c / np.sqrt(2.0 * (1.0 - beta_dil) * curv_ratios)
# Verify exact threshold M == 5.92 when Wi == Wi_crit_boger via pakdel_mckinley_criterion:
d_val = 1.0
R_vals = d_val / curv_ratios
U_crit = wi_crit_boger * d_val / boger_db["lam_s"]
gdot_c = U_crit / d_val
eta0_b = boger_db["eta_s_Pas"] + boger_db["eta_p_Pas"]
tau11_c = 2.0 * boger_db["eta_p_Pas"] * boger_db["lam_s"] * (gdot_c**2)
pm_verify = shear_banding_instabilities.pakdel_mckinley_criterion(U_crit, R_vals, boger_db["lam_s"], tau11_c, eta0_b * gdot_c, m_crit=m_c)
print(f"BOGER_PIB beta_s = {beta_boger:.2f} | Wi_crit at d/R=0.10 : {m_c/math.sqrt(2*(1-beta_boger)*0.10):.3f}")
print(f"Dilute beta_s = {beta_dil:.2f} | Wi_crit at d/R=0.10 : {m_c/math.sqrt(2*(1-beta_dil)*0.10):.3f}")
print(f"Max verification residual |M(Wi_crit) - M_crit| : {np.max(np.abs(pm_verify['M_pakdel'] - m_c)):.3e}")
assert np.allclose(pm_verify["M_pakdel"], m_c, atol=1e-12)
assert np.all(wi_crit_dil > 1.9 * wi_crit_boger)
fig, ax = plt.subplots(figsize=(7.2, 4.0))
ax.plot(curv_ratios, wi_crit_boger, color="#C0392B", lw=2.3, label=f"Boger fluid ($\\beta_s$ = {beta_boger:.2f})")
ax.plot(curv_ratios, wi_crit_dil, color="#2166AC", lw=2.3, label=f"Dilute polymer solution ($\\beta_s$ = {beta_dil:.2f})")
ax.fill_between(curv_ratios, wi_crit_boger, 60.0, color="#C0392B", alpha=0.12, label="Unstable region of the Boger fluid")
ax.set_ylim(0, 45)
ax.set_xlabel("Dimensionless streamline curvature ratio d / R")
ax.set_ylabel("Critical Weissenberg number $\\mathrm{Wi}_{\\mathrm{crit}}$")
ax.set_title(r"Critical Weissenberg number against curvature")
ax.legend(fontsize=8.1)
plt.show()
Exercise 1: critical Weissenberg number against curvature and viscosity ratio
=============================================================================
BOGER_PIB beta_s = 0.40 | Wi_crit at d/R=0.10 : 17.090
Dilute beta_s = 0.85 | Wi_crit at d/R=0.10 : 34.179
Max verification residual |M(Wi_crit) - M_crit| : 1.776e-15

Figure S14.1. Critical Weissenberg number of the Pakdel–McKinley criterion with against the ratio of gap to radius of curvature, for two solvent viscosity ratios. The shaded region is above the criterion for .
Explanation. The critical Weissenberg number is proportional to : a stronger curvature or a larger polymer contribution to the viscosity lowers it, and in a straight channel () it is infinite. At it is 17.1 for and 34.2 for , a factor of 2, as the ratio requires. The function pakdel_mckinley_criterion returns at each of these points to .
Exercise 2¶
Problem. (1) Run solve_2d_viscoelastic_cavity at on grids of cells in each direction with regularized_lid=False and with True, and compare the trace of the conformation tensor at the corner of the lid. (2) Compare the largest Pakdel–McKinley number in solve_2d_wavy_contraction_channel for a straight channel () and for at .
heading("Exercise 2: corner stretch with and without a regularized lid, and the effect of a constriction")
meshes = [16, 22, 28]
corner_raw_n, corner_reg_n = [], []
for nm in meshes:
c_raw = viscoelastic_fvm_2d.solve_2d_viscoelastic_cavity(nx=nm, ny=nm, wi=0.75, beta_s=0.40, re=0.01, n_steps=140, dt=0.006, regularized_lid=False)
c_reg = viscoelastic_fvm_2d.solve_2d_viscoelastic_cavity(nx=nm, ny=nm, wi=0.75, beta_s=0.40, re=0.01, n_steps=140, dt=0.006, regularized_lid=True)
corner_raw_n.append(float(max(c_raw["trC"][0, -1], c_raw["trC"][-1, -1])))
corner_reg_n.append(float(max(c_reg["trC"][0, -1], c_reg["trC"][-1, -1])))
w_straight = viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel(nx=32, ny=18, constriction_eps=0.0, wi=1.6, beta_s=0.30, n_steps=160)
w_curved = viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel(nx=32, ny=18, constriction_eps=0.38, wi=1.6, beta_s=0.30, n_steps=160)
m_straight = float(np.max(w_straight["pakdel_M_field"]))
m_curved = float(np.max(w_curved["pakdel_M_field"]))
print(f"Unregularized corner tr(C) across N={meshes} : {[round(v, 2) for v in corner_raw_n]} (diverges with mesh)")
print(f"Regularized corner tr(C) across N={meshes} : {[round(v, 3) for v in corner_reg_n]} (bounded)")
print(f"Straight slit M_max = {m_straight:.4f} against constricted eps=0.38 M_max = {m_curved:.4f} ({m_curved/max(m_straight,1e-9):.1f}x higher)")
assert corner_raw_n[-1] > corner_raw_n[0]
assert corner_reg_n[-1] < 6.5 and corner_raw_n[-1] > 15.0 * corner_reg_n[-1]
assert m_curved > 8.0 * m_straight
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 3.9))
ax1.plot(meshes, corner_raw_n, "s-", color="#C0392B", lw=2.2, label="Unregularized $u_{\\mathrm{lid}}$ = 1 (singular)")
ax1.plot(meshes, corner_reg_n, "o-", color="#2166AC", lw=2.2, label="Regularized 16 x$^2$(1-x)$^2$ (convergent)")
ax1.set_xlabel("Cells in each direction $N$")
ax1.set_ylabel("Top-corner conformation trace $\\mathrm{tr}\\,\\mathbf{C}$")
ax1.set_title(r"Corner stretch against grid size")
ax1.legend(fontsize=8.0)
ax2.bar(["Straight slit\n($\\varepsilon = 0.00$)", "Curved contraction\n($\\varepsilon = 0.38$)"], [m_straight, m_curved], color=["#6B7280", "#C0392B"], width=0.48)
ax2.set_ylabel("Largest Pakdel-McKinley $M_{\\max}$")
ax2.set_title(r"Largest $M$ in two channels")
label_panels(fig)
plt.show()
Exercise 2: corner stretch with and without a regularized lid, and the effect of a constriction
===============================================================================================
Unregularized corner tr(C) across N=[16, 22, 28] : [78.79, 149.04, 234.68] (diverges with mesh)
Regularized corner tr(C) across N=[16, 22, 28] : [4.485, 4.087, 3.638] (bounded)
Straight slit M_max = 0.0156 against constricted eps=0.38 M_max = 0.4749 (30.3x higher)

Figure S14.2. (a) Trace of at the downstream top corner against the grid size: it grows without limit for the uniform lid and stays bounded for the regularized lid. (b) Largest in a straight channel and in a wavy one ().
Explanation. With a lid that moves at a uniform velocity, the velocity is discontinuous at the corners, and the trace of the conformation tensor there grows without limit as the grid is refined (79, 149 and 235 on the three grids). With the regularized lid it stays bounded (4.5, 4.1 and 3.6). A convergence study of viscoelastic cavity flow is meaningful only with a regularized lid. In the channel, the largest Pakdel–McKinley number is 0.016 without the constriction and 0.475 with it, 30 times larger: the criterion depends on the curvature of the streamlines, which a calculation for a straight channel does not contain.
Exercise 3¶
Problem. Write in NumPy a function that locates the minimum of the stream function between grid points by fitting a parabola in each direction, and a function for the vorticity . Compare the position of the vortex centre with that returned by solve_2d_viscoelastic_cavity for .
heading("Exercise 3: vortex centre between grid points, and the vorticity")
def locate_vortex_and_vorticity_scratch(x: np.ndarray, y: np.ndarray, psi: np.ndarray) -> tuple[float, float, np.ndarray]:
hx, hy = float(x[1] - x[0]), float(y[1] - y[0])
nx, ny = psi.shape
i0, j0 = np.unravel_index(int(np.argmin(psi)), psi.shape)
xc, yc = float(x[i0]), float(y[j0])
if 1 <= i0 <= nx - 2:
d2x = psi[i0 + 1, j0] - 2.0 * psi[i0, j0] + psi[i0 - 1, j0]
if d2x > 1e-12:
xc -= 0.5 * hx * float(psi[i0 + 1, j0] - psi[i0 - 1, j0]) / float(d2x)
if 1 <= j0 <= ny - 2:
d2y = psi[i0, j0 + 1] - 2.0 * psi[i0, j0] + psi[i0, j0 - 1]
if d2y > 1e-12:
yc -= 0.5 * hy * float(psi[i0, j0 + 1] - psi[i0, j0 - 1]) / float(d2y)
p_pad = np.pad(psi, 1, mode="constant", constant_values=0.0)
omega = -(
(p_pad[2:, 1:-1] - 2.0 * p_pad[1:-1, 1:-1] + p_pad[:-2, 1:-1]) / (hx**2)
+ (p_pad[1:-1, 2:] - 2.0 * p_pad[1:-1, 1:-1] + p_pad[1:-1, :-2]) / (hy**2)
)
return xc, yc, omega
wis_ex3 = [0.0, 0.35, 0.75, 1.15]
xc_sc, yc_sc = [], []
omega_hi = None
for w_v in wis_ex3:
res = viscoelastic_fvm_2d.solve_2d_viscoelastic_cavity(nx=23, ny=23, wi=w_v, beta_s=0.35, re=0.01, n_steps=190, dt=0.007)
xs, ys, om = locate_vortex_and_vorticity_scratch(res["x"], res["y"], res["streamfunction"])
xc_sc.append(xs); yc_sc.append(ys)
omega_hi = (res["x"], res["y"], om)
err_vc = math.hypot(xs - res["vortex_center"][0], ys - res["vortex_center"][1])
print(f"Wi = {w_v:4.2f} | vortex centre = ({xs:.5f}, {ys:.5f}) | difference from the package = {err_vc:.2e}")
assert err_vc < 1e-12
assert xc_sc[-1] < xc_sc[0] - 0.015
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.4, 3.9))
ax1.plot(xc_sc, yc_sc, "o-", color="#2166AC", lw=2.2, ms=6.5)
for w_v, xv, yv in zip(wis_ex3, xc_sc, yc_sc):
ax1.annotate(f"Wi = {w_v}", (xv, yv), textcoords="offset points", xytext=(8, -2) if xv < max(xc_sc) else (-42, 6), fontsize=8.2)
ax1.set_xlabel("Vortex centre $x_c$ / L")
ax1.set_ylabel("Vortex centre $y_c$ / L")
ax1.set_title(r"Vortex centre for four values of $\mathrm{Wi}$")
im = ax2.imshow(omega_hi[2].T, extent=[0, 1, 0, 1], origin="lower", cmap="RdBu_r", vmin=-8, vmax=8, aspect="equal")
fig.colorbar(im, ax=ax2, fraction=0.046, pad=0.04, label="Vorticity $\\omega = -\\nabla^2\\psi$")
ax2.plot(xc_sc[-1], yc_sc[-1], "ko", ms=6)
ax2.set_xlabel("x / L"); ax2.set_ylabel("y / L")
ax2.set_title(r"Vorticity at $\mathrm{Wi} = 1.15$")
label_panels(fig)
plt.show()
Exercise 3: vortex centre between grid points, and the vorticity
================================================================
Wi = 0.00 | vortex centre = (0.50002, 0.77856) | difference from the package = 0.00e+00
Wi = 0.35 | vortex centre = (0.47820, 0.79104) | difference from the package = 0.00e+00
Wi = 0.75 | vortex centre = (0.46548, 0.80440) | difference from the package = 0.00e+00
Wi = 1.15 | vortex centre = (0.46259, 0.81038) | difference from the package = 0.00e+00

Figure S14.3. (a) Position of the vortex centre from a parabolic fit around the minimum of the stream function. (b) Vorticity from the discrete Laplacian of the stream function, with the vortex centre.
Explanation. The grid spacing is about 0.04, and between and 1.15 the vortex centre moves from (0.500, 0.779) to (0.463, 0.810), that is by 0.037 in and 0.032 in . Without interpolation between grid points a shift smaller than one cell could not be followed. The function written here returns the same positions as the package.