Solutions · 12. Start-up of viscoelastic channel flow: the Waters–King solution and Brownian configuration fields
Worked solutions to the three exercises of Lecture 12. 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 Waters-King solution for several elasticity numbers")
y_wk = np.linspace(-1.0, 1.0, 49)
t_wk = np.linspace(0.0, 12.0, 241)
el_cases = [0.0, 0.35, 1.20, 4.00] # Since rho=1, H=1, eta_0=1 -> El == lam
wk_runs = {}
for lam_v in el_cases:
wk_runs[lam_v] = constants_benchmarks.waters_king_startup_poiseuille(
y_wk, t_wk, dpdx_neg=2.0, H_half=1.0, rho=1.0, eta_s=0.10, eta_p=0.90, lam=lam_v
)
uc = wk_runs[lam_v]["u_centerline"]
u_inf = wk_runs[lam_v]["u_centerline_steady"]
print(
f"El = {wk_runs[lam_v]['elasticity_number']:4.2f} | "
f"peak u(0,t)/U_inf = {np.max(uc)/u_inf:.4f} | "
f"post-peak min/U_inf = {np.min(uc[np.argmax(uc):])/u_inf:.4f}"
)
# Compute microchannel Elasticity number of benchmark Boger PIB fluid in H = 1 mm slit:
boger = constants_benchmarks.BENCHMARK_FLUIDS_DB["BOGER_PIB"]
eta0_boger = boger["eta_s_Pas"] + boger["eta_p_Pas"]
el_boger_1mm = boger["lam_s"] * eta0_boger / (boger["rho_kgm3"] * (1.0e-3 ** 2))
print(f"BOGER_PIB at H = 1.0 mm: El = {el_boger_1mm:.1f} (elasticity dominates inertia)")
assert np.max(wk_runs[0.0]["u_centerline"]) <= wk_runs[0.0]["u_centerline_steady"] + 1e-9
assert np.max(wk_runs[1.20]["u_centerline"]) > 1.25 * wk_runs[1.20]["u_centerline_steady"]
assert np.max(wk_runs[4.00]["u_centerline"]) > np.max(wk_runs[1.20]["u_centerline"])
assert el_boger_1mm > 1000.0
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.1))
colors = ["#6B7280", "#0F766E", "#E08214", "#7B4FA3"]
for lam_v, col in zip(el_cases, colors):
lbl = "Newtonian (El = 0)" if lam_v == 0.0 else f"Oldroyd-B (El = {lam_v:.2f})"
ls = "--" if lam_v == 0.0 else "-"
ax1.plot(t_wk, wk_runs[lam_v]["u_centerline"], color=col, lw=2.1, ls=ls, label=lbl)
ax1.axhline(1.0, color="black", lw=1.0, ls=":", label="Steady Poiseuille $U_\\infty$")
ax1.set_xlabel("Time t [s, viscous units]")
ax1.set_ylabel("Centreline velocity u(0, t) / $U_\\infty$")
ax1.set_title(r"Centreline velocity ($\beta_s = 0.1$)")
ax1.legend(fontsize=8.2)
snap_times = [0.25, 0.75, 1.35, 2.25, 11.5]
for ts in snap_times:
idx = int(np.argmin(np.abs(t_wk - ts)))
ax2.plot(wk_runs[1.20]["u_yt"][idx], y_wk, lw=2.0, label=f"t = {t_wk[idx]:.2f}")
ax2.plot(wk_runs[1.20]["u_steady"], y_wk, "k--", lw=1.4, label="Exact parabola $u_\\infty$(y)")
ax2.set_xlabel("Axial velocity u(y, t)")
ax2.set_ylabel("Position y / H")
ax2.set_title(r"Velocity profiles ($\mathrm{El} = 1.2$)")
ax2.legend(fontsize=8.0)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. The lowest mode of the Waters–King solution, with wavenumber , oscillates when is negative, where . Find the two roots of and plot them for . Check with waters_king_startup_poiseuille at that the centreline velocity is monotonic for an elasticity number below and exceeds its steady value for one between the two roots.
heading("Exercise 1: the range of elasticity numbers with velocity overshoot")
kappa0 = (math.pi**2) / 4.0
betas = np.linspace(0.02, 0.98, 120)
# Solve beta_s^2 * (kappa0*El)^2 + (2*beta_s - 4)*(kappa0*El) + 1 = 0:
disc_q = (2.0 * betas - 4.0) ** 2 - 4.0 * (betas**2) # = 16 * (1 - beta_s) > 0 for all beta_s < 1
el_minus = ((4.0 - 2.0 * betas) - 4.0 * np.sqrt(1.0 - betas)) / (2.0 * (betas**2) * kappa0)
el_plus = ((4.0 - 2.0 * betas) + 4.0 * np.sqrt(1.0 - betas)) / (2.0 * (betas**2) * kappa0)
beta_test = 0.20
el_lo_crit = float(((4.0 - 2.0 * beta_test) - 4.0 * math.sqrt(1.0 - beta_test)) / (2.0 * (beta_test**2) * kappa0))
el_hi_crit = float(((4.0 - 2.0 * beta_test) + 4.0 * math.sqrt(1.0 - beta_test)) / (2.0 * (beta_test**2) * kappa0))
y_g = np.linspace(-1.0, 1.0, 33)
t_g = np.linspace(0.0, 14.0, 351)
wk_sub = constants_benchmarks.waters_king_startup_poiseuille(y_g, t_g, dpdx_neg=2.0, H_half=1.0, rho=1.0, eta_s=beta_test, eta_p=1.0 - beta_test, lam=0.70 * el_lo_crit)
wk_mid = constants_benchmarks.waters_king_startup_poiseuille(y_g, t_g, dpdx_neg=2.0, H_half=1.0, rho=1.0, eta_s=beta_test, eta_p=1.0 - beta_test, lam=3.50 * el_lo_crit)
print(f"At beta_s = {beta_test:.2f}: El_-* = {el_lo_crit:.4f}, El_+* = {el_hi_crit:.2f}")
print(f"Subcritical El = {0.70*el_lo_crit:.4f} -> max u(0,t)/U_inf = {np.max(wk_sub['u_centerline']):.5f} (overdamped)")
print(f"Underdamped El = {3.50*el_lo_crit:.4f} -> max u(0,t)/U_inf = {np.max(wk_mid['u_centerline']):.5f} (shear wave overshoot)")
assert np.max(wk_sub["u_centerline"]) <= 1.0 + 1e-6
assert np.max(wk_mid["u_centerline"]) > 1.08
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 4.0))
ax1.semilogy(betas, el_minus, color="#2166AC", lw=2.2, label="Lower bound $\\mathrm{El}_-^*(\\beta_s)$")
ax1.semilogy(betas, el_plus, color="#C0392B", lw=2.2, label="Upper bound $\\mathrm{El}_+^*(\\beta_s)$")
ax1.fill_between(betas, el_minus, el_plus, color="#A9C9E8", alpha=0.30, label="Oscillating")
ax1.scatter([beta_test, beta_test], [0.70 * el_lo_crit, 3.50 * el_lo_crit], c=["#0F766E", "#C0392B"], s=55, zorder=5)
ax1.set_xlabel("Solvent viscosity ratio $\\beta_s$ = $\\eta_s$ / $\\eta_0$")
ax1.set_ylabel("Elasticity number $\\mathrm{El} = \\lambda\\eta_0/(\\rho H^2)$")
ax1.set_title(r"Underdamped range of the first mode")
ax1.legend(fontsize=8.0)
ax2.plot(t_g, wk_sub["u_centerline"], color="#0F766E", lw=2.2, label=f"Overdamped, El = {0.70*el_lo_crit:.3f} $< \\mathrm{{El}}_-^*$")
ax2.plot(t_g, wk_mid["u_centerline"], color="#C0392B", lw=2.2, label=f"Underdamped, El = {3.50*el_lo_crit:.3f} $> \\mathrm{{El}}_-^*$")
ax2.axhline(1.0, color="k", ls=":", lw=1.2)
ax2.set_xlabel("Time t [s]")
ax2.set_ylabel("Centreline velocity u(0, t) / $U_\\infty$")
ax2.set_title(r"Centreline velocity at $\beta_s = 0.2$")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
Exercise 1: the range of elasticity numbers with velocity overshoot
===================================================================
At beta_s = 0.20: El_-* = 0.1129, El_+* = 36.36
Subcritical El = 0.0791 -> max u(0,t)/U_inf = 1.00000 (overdamped)
Underdamped El = 0.3953 -> max u(0,t)/U_inf = 1.19233 (shear wave overshoot)

Figure S12.1. (a) Elasticity numbers between which the first mode of the start-up is underdamped (shaded), against ; the two symbols are the cases of panel (b). (b) Centreline velocity below and inside the range.
Explanation. For the equation has two positive roots, and the lowest mode oscillates only between them. Below the fluid responds almost as a Newtonian fluid; above the solvent brings the velocity to its steady profile before the polymer stress has changed. At the roots are 0.113 and 36.4. The centreline velocity does not exceed its steady value at and exceeds it by 19 % at . Without solvent () the lower root tends to and the upper root to infinity.
Exercise 2¶
Problem. Compare independent ensembles in each cell (the CONNFFESSIT approach) with Brownian configuration fields at a fixed ensemble size on grids of cells (t_end=2.2, dt=0.006). Compute the roughness of the stress profile (spatial_stress_roughness, the norm of ) and the root-mean-square error of , the force that enters the momentum equation, relative to the solution of the Oldroyd-B equation.
heading("Exercise 2: independent ensembles against configuration fields on finer grids")
ny_grid = [16, 28, 44]
rough_bcf, rough_con, err_div_bcf, err_div_con = [], [], [], []
for ny_v in ny_grid:
dy_v = 2.0 / ny_v
kw = dict(ny=ny_v, t_end=2.2, dt=0.006, dpdx_neg=2.0, H_half=1.0, rho=1.0, eta_s=0.25, eta_p=0.75, lam=0.8)
r_pde = viscoelastic_fvm_2d.solve_1d_channel_viscoelastic_startup(**kw, method="oldroyd_b_pde")
r_bcf = viscoelastic_fvm_2d.solve_1d_channel_viscoelastic_startup(**kw, method="bcf_hookean", n_fields=180, seed=42)
r_con = viscoelastic_fvm_2d.solve_1d_channel_viscoelastic_startup(**kw, method="connfessit_hookean", n_fields=180, seed=42)
rough_bcf.append(r_bcf["spatial_stress_roughness"])
rough_con.append(r_con["spatial_stress_roughness"])
div_pde = np.diff(r_pde["tau_xy_final"]) / dy_v
div_bcf = np.diff(r_bcf["tau_xy_final"]) / dy_v
div_con = np.diff(r_con["tau_xy_final"]) / dy_v
err_div_bcf.append(float(np.sqrt(np.mean((div_bcf - div_pde) ** 2))))
err_div_con.append(float(np.sqrt(np.mean((div_con - div_pde) ** 2))))
print(
f"Ny = {ny_v:2d} | roughness: BCF = {rough_bcf[-1]:6.3f}, CONNFFESSIT = {rough_con[-1]:8.2f} "
f"| RMSE(dtau/dy): BCF = {err_div_bcf[-1]:.4f}, CONNFFESSIT = {err_div_con[-1]:.4f}"
)
# Uncorrelated cell noise differentiated grows with Ny in CONNFFESSIT while BCF remains smooth
assert rough_con[-1] > 4.0 * rough_con[0]
assert rough_con[-1] > 200.0 * rough_bcf[-1]
assert err_div_con[-1] > 1.8 * err_div_con[0] and err_div_con[-1] > 3.0 * err_div_bcf[-1]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 4.0))
ax1.semilogy(ny_grid, rough_con, "s-", color="#C0392B", lw=2.2, label="Independent ensembles (grows with $N_y$)")
ax1.semilogy(ny_grid, rough_bcf, "o-", color="#2166AC", lw=2.2, label="Configuration fields (bounded)")
ax1.set_xlabel("Grid cells $N_y$")
ax1.set_ylabel("Roughness $\\Vert\\partial^2\\tau_{xy}/\\partial y^2\\Vert_2$")
ax1.set_title(r"Roughness of the stress profile")
ax1.legend(fontsize=8.0, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=1)
ax2.plot(ny_grid, err_div_con, "s--", color="#C0392B", lw=2.1, label="Independent ensembles")
ax2.plot(ny_grid, err_div_bcf, "o-", color="#2166AC", lw=2.1, label="Configuration fields")
ax2.set_xlabel("Grid cells $N_y$")
ax2.set_ylabel("RMS error of $\\partial\\tau_{xy}/\\partial y$")
ax2.set_title(r"Error of the stress gradient")
ax2.legend(fontsize=8.0)
label_panels(fig)
plt.show()
Exercise 2: independent ensembles against configuration fields on finer grids
=============================================================================
Ny = 16 | roughness: BCF = 0.025, CONNFFESSIT = 6.71 | RMSE(dtau/dy): BCF = 0.2243, CONNFFESSIT = 0.6009
Ny = 28 | roughness: BCF = 0.036, CONNFFESSIT = 21.96 | RMSE(dtau/dy): BCF = 0.2214, CONNFFESSIT = 1.0359
Ny = 44 | roughness: BCF = 0.041, CONNFFESSIT = 54.49 | RMSE(dtau/dy): BCF = 0.2200, CONNFFESSIT = 1.4018

Figure S12.2. Refinement of the grid at 180 dumbbells per cell. (a) Norm of the second difference of the polymer shear stress. (b) Root-mean-square error of against the Oldroyd-B solver. Both grow with the number of cells for independent ensembles and not for configuration fields.
Explanation. The momentum equation contains the derivative of the stress. With independent random numbers in each cell, the statistical error of the stress differs from cell to cell, and its derivative grows as the grid is refined: the error of rises from 0.60 to 1.40 between 16 and 44 cells, and the roughness from 6.7 to 54. To keep the error constant, the ensemble would have to grow in proportion to . With configuration fields every cell receives the same random numbers, the statistical error is a smooth function of position, and the error of the derivative stays at 0.22 on all three grids.
Exercise 3¶
Problem. Write a solver in NumPy for start-up of channel flow with Hookean configuration fields: assemble the tridiagonal matrix of the implicit solvent term, and advance fields in antithetic pairs with random increments that are uniform in space. Compare with solve_1d_channel_viscoelastic_startup, with which it should agree to rounding error, and with waters_king_startup_poiseuille.
heading("Exercise 3: a configuration-field solver for start-up of channel flow")
ny_s, nf_s = 32, 400
t_end_s, dt_s = 3.6, 0.006
Gp_s, H_s, rho_s, es_s, ep_s, lam_s = 2.0, 1.0, 1.0, 0.25, 0.75, 0.80
dy_s = 2.0 * H_s / ny_s
n_steps_s = int(round(t_end_s / dt_s))
t_arr = np.linspace(0.0, n_steps_s * dt_s, n_steps_s + 1)
G0_s = ep_s / lam_s
# Assemble interior (ny_s - 1) x (ny_s - 1) implicit solvent diffusion matrix I - alpha * D2:
n_i = ny_s - 1
alpha_s = es_s * dt_s / (rho_s * dy_s**2)
A_solv = (1.0 + 2.0 * alpha_s) * np.eye(n_i) - alpha_s * np.eye(n_i, k=1) - alpha_s * np.eye(n_i, k=-1)
A_inv = np.linalg.inv(A_solv)
rng_s = np.random.default_rng(21)
q_half = rng_s.normal(0.0, 1.0, size=(1, nf_s // 2, 2))
Q_f = np.repeat(np.concatenate([q_half, -q_half], axis=1), ny_s, axis=0)
u_s = np.zeros(ny_s + 1)
tau_xy_s = np.zeros(ny_s)
u_c_scratch = np.zeros(n_steps_s + 1)
ds = dt_s / lam_s
for step in range(n_steps_s):
div_tau = (tau_xy_s[1:] - tau_xy_s[:-1]) / dy_s
u_s[1:-1] = A_inv @ (u_s[1:-1] + (dt_s / rho_s) * (Gp_s + div_tau))
gdot_s = (u_s[1:] - u_s[:-1]) / dy_s
dw_h = rng_s.normal(0.0, math.sqrt(ds), size=(1, nf_s // 2, 2))
dW_u = np.broadcast_to(np.concatenate([dw_h, -dw_h], axis=1), (ny_s, nf_s, 2))
Qy_next = (Q_f[:, :, 1] * (1.0 - 0.25 * ds) + dW_u[:, :, 1]) / (1.0 + 0.25 * ds)
Qx_next = (Q_f[:, :, 0] * (1.0 - 0.25 * ds) + lam_s * gdot_s[:, None] * 0.5 * (Q_f[:, :, 1] + Qy_next) * ds + dW_u[:, :, 0]) / (1.0 + 0.25 * ds)
Q_f[:, :, 0], Q_f[:, :, 1] = Qx_next, Qy_next
Qx_c = Qx_next - np.mean(Qx_next, axis=1, keepdims=True)
Qy_c = Qy_next - np.mean(Qy_next, axis=1, keepdims=True)
tau_xy_s = G0_s * np.mean(Qx_c * Qy_c, axis=1)
u_c_scratch[step + 1] = u_s[ny_s // 2]
y_nodes_s = -H_s + np.arange(ny_s + 1) * dy_s
wk_s = constants_benchmarks.waters_king_startup_poiseuille(y_nodes_s, t_arr, dpdx_neg=Gp_s, H_half=H_s, rho=rho_s, eta_s=es_s, eta_p=ep_s, lam=lam_s)
lib_bcf = viscoelastic_fvm_2d.solve_1d_channel_viscoelastic_startup(ny=ny_s, t_end=t_end_s, dt=dt_s, dpdx_neg=Gp_s, H_half=H_s, rho=rho_s, eta_s=es_s, eta_p=ep_s, lam=lam_s, method="bcf_hookean", n_fields=nf_s, seed=21)
rel_err_wk = float(np.linalg.norm(u_c_scratch - wk_s["u_centerline"]) / np.linalg.norm(wk_s["u_centerline"]))
rel_err_lib = float(np.linalg.norm(u_c_scratch - lib_bcf["u_centerline_hist"]) / np.linalg.norm(lib_bcf["u_centerline_hist"]))
print(f"This solver against Waters-King solution, relative L2 error : {rel_err_wk:.4f}")
print(f"This solver against the package relative L2 error : {rel_err_lib:.4e}")
assert rel_err_wk < 0.08
assert rel_err_lib < 1e-12
fig, ax = plt.subplots(figsize=(7.2, 3.9))
ax.plot(t_arr, wk_s["u_centerline"], "k-", lw=2.3, label="Waters and King (1970) exact analytical")
ax.plot(t_arr[::16], lib_bcf["u_centerline_hist"][::16], "s", ms=5.0, color="#0F766E", label="Package solver")
ax.plot(t_arr[::16], u_c_scratch[::16], "o", ms=3.4, color="#C0392B", label="This solver")
ax.set_xlabel("Time t [s]")
ax.set_ylabel("Centreline velocity u(0, t)")
ax.set_title(r"Centreline velocity")
ax.legend(fontsize=8.2)
plt.show()
Exercise 3: a configuration-field solver for start-up of channel flow
=====================================================================
This solver against Waters-King solution, relative L2 error : 0.0522
This solver against the package relative L2 error : 1.0793e-14

Figure S12.3. A separate implementation of configuration fields (circles) coincides with the package (squares) and follows the exact solution to within the statistical error.
Explanation. Two choices make the method work. The fields are generated in pairs , which removes the odd moments of the ensemble exactly, and each field receives one random increment for all cells, so that the noise has no spatial derivative. The solver reproduces the result of the package to , and with 400 fields it differs from the Waters–King solution by 5.2 % in the norm. No constitutive equation is used.