In creeping flow of a Newtonian fluid in a lid-driven cavity the main vortex is centred at , by the symmetry of Stokes flow. Inertia moves it downstream. A polymer solution at negligible Reynolds number moves it upstream, and the shift grows with the Weissenberg number. At higher Weissenberg numbers, flows with curved streamlines become unstable although inertia is negligible.
Both effects come from the tension along curved streamlines. Pakdel and McKinley (1996) combined the curvature of the streamlines and the normal stress into one dimensionless number , which is large where such an instability is expected. This lecture computes the shift of the vortex, shows why the lid velocity must be regularized at the corners, and evaluates in a channel with wavy walls.
Learning objectives¶
Explain why a lid that moves at a uniform velocity gives a stress singularity at the corners, and use the regularized velocity .
Compute the upstream shift of the vortex centre as the Weissenberg number increases (
re=0.01).Define the Pakdel–McKinley number and evaluate it in a channel with wavy walls.
Map the largest value of against the amplitude of the constriction and the Weissenberg number.
Time: about 60 min
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))1. Cavity flow and the upstream shift of the vortex¶
Flow in a square cavity driven by its lid is a standard test of viscoelastic solvers (Fattal and Kupferman, 2005; Sousa et al., 2016). If the lid moves at a uniform velocity, the shear rate of a Newtonian fluid diverges as at the two upper corners, and the normal stress of an Oldroyd-B fluid, , diverges as . The singularity is removed by a lid velocity that vanishes smoothly at the corners:
At a negligible Reynolds number (), consider the Weissenberg number increasing from 0 to 1.2:
The fluid that is carried along the lid from left to right is sheared, and its polymer acquires a tension along the streamlines, ().
Near the downstream corner the streamlines turn downwards with a radius of curvature . A tension along a curved streamline acts as a force towards the centre of curvature, which resists the turn. The recirculation changes, and the centre of the main vortex moves upstream, to .
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()
Demonstration 1: shift of the vortex centre with Weissenberg number (Re = 0.01)
===============================================================================
Wi = 0.00 | vortex centre (x_c, y_c) = (0.5000, 0.7788) | max tr(C) = 2.000 | detC_min = 1.0000
Wi = 0.40 | vortex centre (x_c, y_c) = (0.4750, 0.7944) | max tr(C) = 7.834 | detC_min = 1.0000
Wi = 0.80 | vortex centre (x_c, y_c) = (0.4624, 0.8059) | max tr(C) = 18.052 | detC_min = 1.0000
Wi = 1.20 | vortex centre (x_c, y_c) = (0.4594, 0.8115) | max tr(C) = 25.151 | detC_min = 1.0000

Figure 14.1. Cavity flow at . (a) Horizontal position of the vortex centre (left axis) and the largest trace of (right axis) against . (b) Streamlines of the Newtonian flow (grey) and at (blue), with the two vortex centres.
2. Regularization of the lid velocity¶
Consider the choice regularized_lid=False, that is up to the side walls and . At the two upper corners the velocity changes from 1 on the lid to 0 on the side wall within one grid spacing , so that : the velocity gradient there grows without limit as the grid is refined.
The demonstration compares the stretch in the row of cells under the lid for the regularized lid velocity and for the uniform one, at the same .
heading("Demonstration 2: regularized and uniform lid velocity")
cav_reg = viscoelastic_fvm_2d.solve_2d_viscoelastic_cavity(
nx=21, ny=21, wi=0.85, beta_s=0.35, re=0.01, alpha_devss=0.55, n_steps=150, dt=0.007, regularized_lid=True
)
cav_raw = viscoelastic_fvm_2d.solve_2d_viscoelastic_cavity(
nx=21, ny=21, wi=0.85, beta_s=0.35, re=0.01, alpha_devss=0.55, n_steps=150, dt=0.007, regularized_lid=False
)
corner_tr_reg = float(max(cav_reg["trC"][0, -1], cav_reg["trC"][-1, -1]))
corner_tr_raw = float(max(cav_raw["trC"][0, -1], cav_raw["trC"][-1, -1]))
print(f"Regularized lid top-corner tr(C) : {corner_tr_reg:.3f} (bounded)")
print(f"Unregularized lid top-corner tr(C) : {corner_tr_raw:.3f} (grows as the grid is refined)")
assert corner_tr_reg < 7.0
assert corner_tr_raw > 15.0 * corner_tr_reg
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
x_c = cav_reg["x"]
ax1.plot(x_c, 16.0 * (x_c**2) * ((1.0 - x_c) ** 2), color="#2166AC", lw=2.3, label="Regularized $u_{\\mathrm{lid}}$ = 16 x$^2$ (1-x)$^2$")
ax1.plot(x_c, np.ones_like(x_c), "--", color="#C0392B", lw=2.0, label="Unregularized discontinuous $u_{\\mathrm{lid}}$ = 1")
ax1.set_xlabel("x / L")
ax1.set_ylabel("Prescribed lid velocity $u_{\\mathrm{lid}}$(x)")
ax1.set_title(r"Lid velocity")
ax1.legend(fontsize=8.1)
ax2.plot(x_c, cav_raw["trC"][:, -1], "s-", ms=4.0, color="#C0392B", lw=1.9, label="Unregularized top-row $\\mathrm{tr}\\,\\mathbf{C}$ (corner spikes)")
ax2.plot(x_c, cav_reg["trC"][:, -1], "o-", ms=4.0, color="#2166AC", lw=2.2, label="Regularized top-row $\\mathrm{tr}\\,\\mathbf{C}$ (smooth interior peak)")
ax2.set_xlabel("x / L")
ax2.set_ylabel("Trace $\\mathrm{tr}\\,\\mathbf{C}$ in the top row of cells")
ax2.set_title(r"Trace of $\mathbf{C}$ under the lid ($\mathrm{Wi} = 0.85$)")
ax2.legend(fontsize=8.0)
label_panels(fig)
plt.show()
Demonstration 2: regularized and uniform lid velocity
=====================================================
Regularized lid top-corner tr(C) : 5.673 (bounded)
Unregularized lid top-corner tr(C) : 177.143 (grows as the grid is refined)

Figure 14.2. (a) The regularized lid velocity and the uniform one. (b) Trace of in the row of cells under the lid: the uniform lid gives a spike at the downstream corner.
3. Channels with wavy walls and the Pakdel–McKinley criterion¶
Viscoelastic flows become unstable at negligible Reynolds number in contractions, in channels with wavy walls, in Taylor–Couette cells and in cone-and-plate rheometers. Pakdel and McKinley (1996) described these elastic instabilities with one criterion. It compares the distance that the fluid travels in one relaxation time with the radius of curvature of the streamline, and the tension along the streamline with the viscous shear stress :
In viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel the fluid flows through a periodic channel of half-height for : the channel is narrowest at and and widest at . The field has the following features:
On the centreline, , the streamline is straight (), and is close to zero although the fluid is stretched there.
At the walls, , the velocity is zero, and so is .
The largest values are found between the centreline and the wall near the narrowest section, where the velocity, the curvature of the streamlines and the normal stress are all large.
heading("Demonstration 3: normal stress and Pakdel-McKinley number in a channel with wavy walls")
wavy = viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel(
nx=36, ny=22, constriction_eps=0.34, wi=1.50, beta_s=0.30, n_steps=190, dt=0.006
)
flux_axial = np.mean(wavy["u"], axis=1) * (2.0 * wavy["H_wall"])
print(f"Axial volumetric flux range [min, max] : [{np.min(flux_axial):.4f}, {np.max(flux_axial):.4f}] (incompressible)")
print(f"Peak conformation trace max tr(C) : {np.max(wavy['trC_field']):.3f}")
print(f"Peak first normal stress max N1 : {np.max(wavy['N1_field']):.3f}")
print(f"Largest Pakdel-McKinley M(x, y) : {np.max(wavy['pakdel_M_field']):.3f} (centreline M = {np.max(wavy['pakdel_M_field'][:, 10:12]):.3f})")
assert wavy["detC_min"] > 0.0
assert float(np.max(flux_axial) - np.min(flux_axial)) < 0.04
assert float(np.max(wavy["pakdel_M_field"])) > 0.25
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.2, 4.1))
ax1.grid(False); ax2.grid(False)
pcm1 = ax1.pcolormesh(wavy["x_grid"], wavy["y_grid"], wavy["N1_field"], cmap="viridis", shading="gouraud")
ax1.plot(wavy["x_grid"][:, 0], wavy["H_wall"], "k-", lw=2.0)
ax1.plot(wavy["x_grid"][:, 0], -wavy["H_wall"], "k-", lw=2.0)
fig.colorbar(pcm1, ax=ax1, fraction=0.046, pad=0.04, label="First normal stress $N_1$(x, y)")
ax1.set_xlabel("Axial coordinate x (narrowest at 0 and $2\\pi$)")
ax1.set_ylabel("Transverse coordinate y")
ax1.set_title(r"First normal stress difference")
pcm2 = ax2.pcolormesh(wavy["x_grid"], wavy["y_grid"], wavy["pakdel_M_field"], cmap="inferno", shading="gouraud")
ax2.plot(wavy["x_grid"][:, 0], wavy["H_wall"], "c-", lw=2.0)
ax2.plot(wavy["x_grid"][:, 0], -wavy["H_wall"], "c-", lw=2.0)
fig.colorbar(pcm2, ax=ax2, fraction=0.046, pad=0.04, label="Pakdel-McKinley M(x, y)")
ax2.set_xlabel("Axial coordinate x")
ax2.set_ylabel("Transverse coordinate y")
ax2.set_title(r"Pakdel–McKinley number")
label_panels(fig)
plt.show()
Demonstration 3: normal stress and Pakdel-McKinley number in a channel with wavy walls
======================================================================================
Axial volumetric flux range [min, max] : [1.3347, 1.3347] (incompressible)
Peak conformation trace max tr(C) : 16.918
Peak first normal stress max N1 : 7.306
Largest Pakdel-McKinley M(x, y) : 0.530 (centreline M = 0.275)

Figure 14.3. Oldroyd-B fluid in a periodic channel with wavy walls. (a) First normal stress difference, largest near the walls at the throats. (b) Local Pakdel–McKinley number , largest (0.53) where curved streamlines carry a high tensile stress.
4. A map in the plane ¶
In the design of an extrusion die the amplitude of the constriction, , is weighed against the speed of the line, which sets . The demonstration computes the largest value for , 0.15, 0.30 and 0.45 and , 0.9, 1.5 and 2.2. A smaller amplitude allows a larger Weissenberg number at the same .
heading("Demonstration 4: largest Pakdel-McKinley number against amplitude and Weissenberg number")
eps_grid = [0.0, 0.15, 0.30, 0.45]
wi_map = [0.4, 0.9, 1.5, 2.2]
M_peak_mat = np.zeros((len(eps_grid), len(wi_map)))
for i, ep_v in enumerate(eps_grid):
for j, wi_v in enumerate(wi_map):
w_ij = viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel(
nx=28, ny=16, constriction_eps=ep_v, wi=wi_v, beta_s=0.30, n_steps=140, dt=0.006
)
M_peak_mat[i, j] = float(np.max(w_ij["pakdel_M_field"]))
print(f"eps = {ep_v:4.2f} | peak M across Wi {wi_map}: {[round(x, 3) for x in M_peak_mat[i]]}")
# Straight channel (eps = 0) has near-zero curvature M, while M grows monotonically with both eps and Wi
assert np.all(M_peak_mat[0, :] < 0.08)
assert M_peak_mat[-1, -1] > 0.45
assert np.all(np.diff(M_peak_mat[-1, :]) > 0.0)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
for i, (ep_v, col) in enumerate(zip(eps_grid, ["#6B7280", "#0F766E", "#E08214", "#C0392B"])):
lbl = "Straight channel ($\\varepsilon = 0$)" if ep_v == 0.0 else f"Wavy walls ($\\varepsilon$ = {ep_v:.2f})"
ax1.plot(wi_map, M_peak_mat[i], "o-", lw=2.2, color=col, label=lbl)
ax1.axhline(0.38, color="k", ls="--", lw=1.3, label="Assumed limit")
ax1.set_xlabel("Weissenberg number Wi")
ax1.set_ylabel("Peak spatial Pakdel-McKinley number max M(x, y)")
ax1.set_title(r"Largest $M$ against $\mathrm{Wi}$")
ax1.legend(fontsize=8.0, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=2)
im = ax2.imshow(M_peak_mat, origin="lower", cmap="magma", aspect="auto")
ax2.set_xticks(range(len(wi_map)), [f"{w:.1f}" for w in wi_map])
ax2.set_yticks(range(len(eps_grid)), [f"{e:.2f}" for e in eps_grid])
for i in range(len(eps_grid)):
for j in range(len(wi_map)):
ax2.text(j, i, f"{M_peak_mat[i, j]:.2f}", ha="center", va="center", color="white" if M_peak_mat[i, j] < 0.38 else "black", fontsize=8.5, fontweight="bold")
fig.colorbar(im, ax=ax2, fraction=0.046, pad=0.04, label="Largest $M$")
ax2.set_xlabel("Weissenberg number Wi")
ax2.set_ylabel("Constriction amplitude $\\varepsilon$")
ax2.set_title(r"Largest $M$ over amplitude and $\mathrm{Wi}$")
label_panels(fig)
plt.show()
Demonstration 4: largest Pakdel-McKinley number against amplitude and Weissenberg number
========================================================================================
eps = 0.00 | peak M across Wi [0.4, 0.9, 1.5, 2.2]: [np.float64(0.01), np.float64(0.014), np.float64(0.016), np.float64(0.017)]
eps = 0.15 | peak M across Wi [0.4, 0.9, 1.5, 2.2]: [np.float64(0.129), np.float64(0.179), np.float64(0.201), np.float64(0.213)]
eps = 0.30 | peak M across Wi [0.4, 0.9, 1.5, 2.2]: [np.float64(0.238), np.float64(0.329), np.float64(0.368), np.float64(0.389)]
eps = 0.45 | peak M across Wi [0.4, 0.9, 1.5, 2.2]: [np.float64(0.394), np.float64(0.54), np.float64(0.604), np.float64(0.638)]

Figure 14.4. (a) Largest Pakdel–McKinley number in the channel against for four wall amplitudes ; the dashed line is the limit 0.38 used here for illustration. (b) The same values as a table.
Inside the algorithm: the Pakdel–McKinley number in Taylor–Couette flow¶
The cell below prints the source of shear_banding_instabilities.pakdel_mckinley_criterion and checks it against the formula for an Oldroyd-B fluid in a viscometric flow with curved streamlines.
Check against the package¶
In steady shear of an Oldroyd-B fluid along streamlines of radius in a gap of width , the shear rate is and the tension is . Substituting these into the definition gives
This is the scaling of the elastic instability of Taylor–Couette flow (Larson, Shaqfeh and Muller, 1990). The function reproduces the formula to rounding error (< 1e-14).
heading("Inside the algorithm: the Pakdel-McKinley number in Taylor-Couette flow")
print(show_source(shear_banding_instabilities.pakdel_mckinley_criterion))
# Verify exact identity M == Wi * sqrt(2 * (1 - beta_s) * (d / R)) for Oldroyd-B Taylor-Couette flow:
d_gap, R_cyl, beta_tc = 0.04, 0.80, 0.25
eta0_tc, lam_tc = 2.0, 0.60
U_wall = np.linspace(0.5, 12.0, 25)
gdot_tc = U_wall / d_gap
wi_tc = lam_tc * gdot_tc
tau11_tc = 2.0 * (1.0 - beta_tc) * eta0_tc * lam_tc * (gdot_tc**2)
pm_lib = shear_banding_instabilities.pakdel_mckinley_criterion(
speed=U_wall, radius_of_curvature=R_cyl, lam=lam_tc, tau_11=tau11_tc, eta0_shear_rate=eta0_tc * gdot_tc, m_crit=5.92
)
M_exact_tc = wi_tc * math.sqrt(2.0 * (1.0 - beta_tc) * (d_gap / R_cyl))
max_err_pm = float(np.max(np.abs(pm_lib["M_pakdel"] - M_exact_tc)))
wi_crit_tc = 5.92 / math.sqrt(2.0 * (1.0 - beta_tc) * (d_gap / R_cyl))
print(f"Max discrepancy against exact Larson-Shaqfeh-Muller formula : {max_err_pm:.3e}")
print(f"Predicted critical Weissenberg number at M_crit = 5.92 : Wi_crit = {wi_crit_tc:.3f}")
assert np.allclose(pm_lib["M_pakdel"], M_exact_tc, atol=1e-14)
assert bool(pm_lib["exceeds_critical"][-1])
Inside the algorithm: the Pakdel-McKinley number in Taylor-Couette flow
=======================================================================
def pakdel_mckinley_criterion(
speed: np.ndarray | float,
radius_of_curvature: np.ndarray | float,
lam: float,
tau_11: np.ndarray | float,
eta0_shear_rate: np.ndarray | float,
m_crit: float = 5.92,
) -> dict:
"""The dimensionless number M of the criterion of Pakdel and McKinley (1996) for elastic instability."""
if lam < 0.0 or m_crit <= 0.0:
raise ValueError("Require lam >= 0 and m_crit > 0.")
u_abs = np.abs(np.asarray(speed, dtype=float))
rad = np.maximum(np.abs(np.asarray(radius_of_curvature, dtype=float)), 1e-12)
t11 = np.maximum(np.asarray(tau_11, dtype=float), 0.0)
visc_stress = np.maximum(np.abs(np.asarray(eta0_shear_rate, dtype=float)), 1e-12)
m_val = np.sqrt((float(lam) * u_abs / rad) * (t11 / visc_stress))
return {
"M_pakdel": m_val,
"exceeds_critical": m_val >= float(m_crit),
"M_crit": float(m_crit),
}
Max discrepancy against exact Larson-Shaqfeh-Muller formula : 7.105e-15
Predicted critical Weissenberg number at M_crit = 5.92 : Wi_crit = 21.617
Exercises¶
Worked solutions are in 14_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. 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 withpakdel_mckinley_criterion.Find how it fails. (1) Run
solve_2d_viscoelastic_cavityat on grids of cells in each direction withregularized_lid=Falseand withTrue, and compare the trace of the conformation tensor at the corner of the lid. (2) Compare the largest Pakdel–McKinley number insolve_2d_wavy_contraction_channelfor a straight channel () and for at .Implement it yourself. 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_cavityfor .
heading("Self-check for the exercises")
assert vx_hist[-1] < vx_hist[0] - 0.015
assert corner_tr_raw > 15.0 * corner_tr_reg
assert float(np.max(wavy["pakdel_M_field"])) > 0.25
assert max_err_pm < 1e-14
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.