Worked solutions to the three exercises of Lecture 17. 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("Stage 1: the model polymer")
# 1. Passive thermal microrheology check of relaxation time lam = 0.45 s (matching BOGER_PIB timescale):
boger_p = constants_benchmarks.BENCHMARK_FLUIDS_DB["BOGER_PIB"]
t_probe = np.concatenate([[0.0], np.geomspace(1e-3, 6.0, 45)])
gle_cap = microrheology_rheoml.simulate_gle_thermal_probe(
[(boger_p["eta_p_Pas"] / boger_p["lam_s"], boger_p["lam_s"])], t_probe, eta_s=0.02, n_probes=900, seed=12
)
gser_cap = microrheology_rheoml.mason_gser_moduli(gle_cap["t"][1:], gle_cap["msd_exact"][1:])
# 2. Semi-implicit FENE Brownian Dynamics against FENE-P Log-Conformation startup at Wi = 2.0 (b = 36):
t_cap = np.linspace(0.0, 4.0, 51)
L_sh_cap = np.array([[0.0, 2.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
bd_cap = brownian_chains.simulate_dumbbell_bd(lambda _t: L_sh_cap, t_cap, model="fene", b_ext=36.0, n_trajectories=700, control_variate=True, seed=7)
fp_cap = entangled_tubes.solve_fenep_fenecr(lambda _t: L_sh_cap, t_cap, lam=1.0, eta_p=1.0, b_ext=36.0, variant="fenep")
rp_cap = entangled_tubes.solve_rolie_poly(lambda _t: L_sh_cap, t_cap, G0=1.0, tau_d=1.0, tau_R=0.25, beta_ccr=0.5)
# 3. Verify SPD thermodynamics & calibrate frame-invariant TC-RheoML surrogate on FENE-P states:
spd_cap = tensors_kinematics.check_spd_conformation(fp_cap["C"][-1], G0=1.0)
tc_cap = microrheology_rheoml.fit_thermodynamic_tensor_rheoml(fp_cap["C"][2:], fp_cap["tau_p"][2:])
print(f"FENE BD overstretches = {bd_cap['overstretched_count']} | VRF = {bd_cap['variance_reduction_factor']:.1f}x | steady tau_xy = {bd_cap['tau_xy'][-1]:.3f}")
print(f"FENE-P SPD verified = {spd_cap['is_spd']} (psi = {spd_cap['free_energy_hookean']:.3f}) | steady tau_xy = {fp_cap['tau_p'][-1, 0, 1]:.3f}")
print(f"Tensor-basis model R^2 = {tc_cap['r2_score']:.5f} | SO(3) err = {tc_cap['rotation_equivariance_err']:.2e}")
assert bd_cap["overstretched_count"] == 0
assert spd_cap["is_spd"] and spd_cap["free_energy_hookean"] > 0.0
assert tc_cap["is_thermodynamically_admissible"] and tc_cap["r2_score"] > 0.995
assert gser_cap["kramers_kronig_tan_err"] < 1e-13
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
ax1.loglog(gser_cap["omega"], gser_cap["G_prime"], "o-", ms=3.5, color="#2166AC", lw=2.0, label="GSER storage $G'$($\\omega$)")
ax1.loglog(gser_cap["omega"], gser_cap["G_double_prime"], "s--", ms=3.5, color="#C0392B", lw=1.9, label="GSER loss $G''$($\\omega$)")
ax1.axvline(1.0 / boger_p["lam_s"], color="k", ls=":", lw=1.4, label=f"Relaxation 1/$\\lambda$ = {1/boger_p['lam_s']:.2f} rad/s")
ax1.set_xlabel("Frequency $\\omega$ [rad/s]"); ax1.set_ylabel("Moduli [Pa]")
ax1.set_title(r"Moduli from a simulated probe")
ax1.legend(fontsize=7.9)
ax2.plot(t_cap, bd_cap["tau_xy"], color="#0F766E", lw=2.1, label="FENE Brownian dynamics (b=36)")
ax2.plot(t_cap, fp_cap["tau_p"][:, 0, 1], "--", color="#2166AC", lw=2.1, label="FENE-P closure (log-$\\psi$)")
ax2.plot(t_cap[::3], tc_cap["predict_fn"](fp_cap["C"][::3])[:, 0, 1], "o", ms=4.2, color="#C0392B", label="Fitted tensor-basis model")
ax2.plot(t_cap, rp_cap["tau_xy"], ":", color="#7B4FA3", lw=2.0, label="Entangled Rolie-Poly reference")
ax2.set_xlabel("Dimensionless time t / $\\lambda$"); ax2.set_ylabel("Dimensionless shear stress $\\tau_{xy}$")
ax2.set_title(r"Shear stress in start-up")
ax2.legend(fontsize=7.8)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Check the lubrication result for the pressure drop in a slit whose gap varies as , relative to a straight slit, , for with the trapezoidal rule. Then compute the smallest pressure gradient at which the assumed gel CARBOPOL_EVP () flows in a square duct of side , .
heading("Exercise 1: pressure drop of a wavy slit and the minimum pressure gradient of the feed duct")
eps_vec = np.linspace(0.0, 0.65, 28)
x_quad = np.linspace(0.0, 2.0 * math.pi, 512, endpoint=False)
lam_quad = np.array([float(np.mean((1.0 - ep * np.cos(x_quad)) ** -3.0)) for ep in eps_vec])
lam_exact = (2.0 + eps_vec**2) / (2.0 * ((1.0 - eps_vec**2) ** 2.5))
quad_err = float(np.max(np.abs(lam_quad - lam_exact)))
carb = constants_benchmarks.BENCHMARK_FLUIDS_DB["CARBOPOL_EVP"]
H_runner = 5.0e-3 # 5 mm half-width (10 mm x 10 mm square runner)
bn_crit = constants_benchmarks.MOSOLOV_SQUARE_DUCT_BN_CRIT
Gp_min_pa_per_m = carb["tau_y_Pa"] / (H_runner * bn_crit)
Gp_planar_naive = carb["tau_y_Pa"] / H_runner # Naive 1-D slit estimate misses 4-wall Mosolov factor
print(f"Max quadrature against exact (2+eps^2)/[2(1-eps^2)^(5/2)] error : {quad_err:.3e}")
print(f"Pressure amplification at eps = 0.50 : {float((2+0.25)/(2*0.75**2.5)):.4f}x straight slit")
print(f"CARBOPOL_EVP minimum square-runner -dp/dz : {Gp_min_pa_per_m/1e3:.3f} kPa/m (plane-channel formula: {Gp_planar_naive/1e3:.3f} kPa/m)")
assert quad_err < 1e-13
assert Gp_min_pa_per_m > 1.85 * Gp_planar_naive
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 3.9))
ax1.plot(eps_vec, lam_exact, "k-", lw=2.3, label="Exact $(2+\\varepsilon^2)/[2(1-\\varepsilon^2)^{5/2}]$")
ax1.plot(eps_vec[::2], lam_quad[::2], "o", ms=5.0, color="#2166AC", label="Trapezoidal rule")
ax1.set_xlabel("Amplitude $\\varepsilon$")
ax1.set_ylabel("Pressure-drop factor dP($\\varepsilon$)/dP(0)")
ax1.set_title(r"Pressure-drop factor of a wavy channel")
ax1.legend(fontsize=8.0)
ax2.bar(["Plane channel\n$\\tau_y/H$", "Square duct\n$\\tau_y/(H\\,\\mathrm{Bn}_{\\mathrm{crit}})$"], [Gp_planar_naive / 1e3, Gp_min_pa_per_m / 1e3], color=["#C0392B", "#0F766E"], width=0.46)
ax2.set_ylabel("Smallest pressure gradient with flow [kPa/m]")
ax2.set_title(r"Pressure gradient needed to start the flow")
label_panels(fig)
plt.show()
Exercise 1: pressure drop of a wavy slit and the minimum pressure gradient of the feed duct
===========================================================================================
Max quadrature against exact (2+eps^2)/[2(1-eps^2)^(5/2)] error : 8.882e-16
Pressure amplification at eps = 0.50 : 2.3094x straight slit
CARBOPOL_EVP minimum square-runner -dp/dz : 16.976 kPa/m (plane-channel formula: 9.000 kPa/m)

Figure S17.1. (a) Lubrication pressure drop of a channel with wall amplitude divided by that of a straight channel: quadrature against . (b) Smallest pressure gradient that moves CARBOPOL_EVP (assumed parameters): 9.0 kPa/m from the plane-channel formula, 17.0 kPa/m in a square duct.
Explanation. The trapezoidal rule, which converges very quickly for a periodic integrand, reproduces the formula to . At the pressure drop is 2.31 times that of a straight slit of the same mean gap, because the local pressure gradient is proportional to the inverse cube of the gap. The square duct needs 17.0 kPa/m to flow, against 9.0 kPa/m from the plane-channel formula ; the ratio is .
Exercise 2¶
Problem. A design calculation that treats the fluid as Newtonian () is applied to a wavy slit with that is operated at and fed by a square duct at . Compare its predictions with solve_2d_wavy_contraction_channel and with solve_2d_duct_bingham_admm.
heading("Exercise 2: a Newtonian calculation for a viscoelastic fluid with a yield stress")
# Legacy Newtonian assumptions: Wi = 0 in die, tau_y = 0 in square feed runner
newt_die = viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel(nx=32, ny=18, constriction_eps=0.42, wi=0.0, beta_s=0.30)
true_die = viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel(nx=32, ny=18, constriction_eps=0.42, wi=2.0, beta_s=0.30, n_steps=180)
newt_duct = viscoplastic_admm.solve_2d_duct_bingham_admm(nx=26, ny=26, H_half=1.0, dpdz_neg=1.0, tau_y=0.0, eta_p=1.0, max_iter=120)
true_duct = viscoplastic_admm.solve_2d_duct_bingham_admm(nx=26, ny=26, H_half=1.0, dpdz_neg=1.0, tau_y=0.56, eta_p=1.0, r_aug=1.0, max_iter=260)
print(f"Largest Pakdel-McKinley number: Newtonian {np.max(newt_die['pakdel_M_field']):.3f} against viscoelastic {np.max(true_die['pakdel_M_field']):.3f}")
print(f"Largest N1 : Newtonian {np.max(newt_die['N1_field']):.3f} against viscoelastic {np.max(true_die['N1_field']):.3f}")
print(f"Flow rate of the feed duct : Newtonian {newt_duct['flow_rate']:.4f} against Bingham (Bn=0.56) {true_duct['flow_rate']:.2e} (no flow)")
assert float(np.max(newt_die["pakdel_M_field"])) == 0.0
assert float(np.max(true_die["pakdel_M_field"])) > 0.50
assert newt_duct["flow_rate"] > 0.55 and true_duct["flow_rate"] < 1e-5
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 3.9))
ax1.bar(["Newtonian\n(M = 0)", "Viscoelastic\n($\\varepsilon = 0.42$, Wi = 2.0)"], [float(np.max(newt_die["pakdel_M_field"])), float(np.max(true_die["pakdel_M_field"]))], color=["#A9C9E8", "#C0392B"], width=0.46)
ax1.axhline(0.42, color="k", ls="--", lw=1.4, label="Assumed limit $M_{\\mathrm{allow}}$ = 0.42")
ax1.set_ylabel("Largest Pakdel-McKinley $M_{\\max}$")
ax1.set_title(r"Largest $M$ in the die")
ax1.legend(fontsize=8.0)
ax2.bar(["Newtonian\n(Bn = 0)", "Bingham\n(Bn = 0.56)"], [newt_duct["flow_rate"], true_duct["flow_rate"]], color=["#0F766E", "#C0392B"], width=0.46)
ax2.set_ylabel("Flow rate of the square duct Q")
ax2.set_title(r"Flow rate in the feed duct")
label_panels(fig)
plt.show()
Exercise 2: a Newtonian calculation for a viscoelastic fluid with a yield stress
================================================================================
Largest Pakdel-McKinley number: Newtonian 0.000 against viscoelastic 0.610
Largest N1 : Newtonian 0.000 against viscoelastic 6.774
Flow rate of the feed duct : Newtonian 0.5618 against Bingham (Bn=0.56) 2.73e-07 (no flow)

Figure S17.2. A Newtonian calculation against the viscoelastic and viscoplastic ones. (a) Largest Pakdel–McKinley number: zero for the Newtonian fluid, 0.61 for the Oldroyd-B fluid, above the assumed limit. (b) Flow rate in the square duct: 0.56 for the Newtonian fluid, zero for the Bingham fluid at .
Explanation. The Newtonian calculation is wrong in two opposite ways. It predicts no normal stress and a Pakdel–McKinley number of zero in the slit, where the viscoelastic calculation gives and . It also predicts a flow rate of 0.562 in the feed duct, where a Bingham fluid at , above the critical value 0.530, does not flow.
Exercise 3¶
Problem. Write find_max_safe_throughput(eps_list, bn_feed, m_allow) in NumPy. The function first checks with solve_2d_duct_bingham_admm that the feed duct flows, and then finds by bisection on , with solve_2d_wavy_contraction_channel, the largest Weissenberg number for which (an assumed limit), for .
heading("Exercise 3: the largest Weissenberg number within an assumed limit, by bisection")
def find_max_safe_throughput(eps_list: list[float], bn_feed: float = 0.28, m_allow: float = 0.28) -> dict:
feed = viscoplastic_admm.solve_2d_duct_bingham_admm(nx=24, ny=24, H_half=1.0, dpdz_neg=1.0, tau_y=bn_feed, eta_p=1.0, r_aug=0.35, max_iter=200)
if feed["flow_rate"] <= 1e-4:
raise RuntimeError("Feed runner arrested above Mosolov limit")
wi_star, dp_star, m_at_star = [], [], []
for ep in eps_list:
lo, hi = 0.15, 3.20
best_m, best_dp = 0.0, 0.0
lub = (2.0 + ep**2) / (2.0 * ((1.0 - ep**2) ** 2.5))
for _ in range(7):
mid = 0.5 * (lo + hi)
w_res = viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel(nx=26, ny=14, constriction_eps=ep, wi=mid, beta_s=0.30, n_steps=130, dt=0.006)
m_cur = float(np.max(w_res["pakdel_M_field"]))
if m_cur <= m_allow and w_res["detC_min"] > 0.0:
lo = mid
best_m = m_cur
best_dp = mid * lub + 0.35 * ep * float(np.max(w_res["N1_field"]))
else:
hi = mid
wi_star.append(lo)
dp_star.append(best_dp)
m_at_star.append(best_m)
return {"feed_flux": feed["flow_rate"], "feed_unyielded": feed["unyielded_area_fraction"], "eps": eps_list, "wi_max": wi_star, "dp_at_wi_max": dp_star, "m_at_wi_max": m_at_star}
opt = find_max_safe_throughput([0.20, 0.30, 0.40], bn_feed=0.28, m_allow=0.28)
print(f"Feed duct (Bn=0.28): Q = {opt['feed_flux']:.4f}, unyielded = {opt['feed_unyielded']:.1%}")
for ep, ws, dps, ms in zip(opt["eps"], opt["wi_max"], opt["dp_at_wi_max"], opt["m_at_wi_max"]):
print(f" Die eps = {ep:.2f} -> largest Wi within the limit = {ws:.3f} (M_max = {ms:.3f} <= 0.28, dP = {dps:.2f})")
# A gentler constriction (smaller eps) gives a larger admissible Wi*.
assert opt["feed_flux"] > 0.15
assert opt["wi_max"][0] > opt["wi_max"][1] > opt["wi_max"][2]
assert all(m <= 0.28 + 1e-6 for m in opt["m_at_wi_max"])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 3.9))
ax1.plot(opt["eps"], opt["wi_max"], "o-", color="#2166AC", lw=2.4, ms=7, label="Largest Wi within the limit, $\\mathrm{Wi}^*(\\varepsilon)$")
ax1.set_xlabel("Amplitude of the constriction $\\varepsilon$")
ax1.set_ylabel("Largest Wi within the limit, $\\mathrm{Wi}^*$")
ax1.set_title(r"Largest admissible $\mathrm{Wi}$")
ax1.legend(fontsize=8.1)
ax2.plot(opt["eps"], opt["dp_at_wi_max"], "s--", color="#0F766E", lw=2.2, ms=6.5, label="Pressure drop at $\\mathrm{Wi}^*$")
ax2.set_xlabel("Amplitude of the constriction $\\varepsilon$")
ax2.set_ylabel("Dimensionless pressure drop at $\\mathrm{Wi}^*$")
ax2.set_title(r"Pressure drop at that rate")
ax2.legend(fontsize=8.1)
label_panels(fig)
plt.show()
Exercise 3: the largest Weissenberg number within an assumed limit, by bisection
================================================================================
Feed duct (Bn=0.28): Q = 0.1846, unyielded = 21.9%
Die eps = 0.20 -> largest Wi within the limit = 3.176 (M_max = 0.255 <= 0.28, dP = 3.66)
Die eps = 0.30 -> largest Wi within the limit = 0.627 (M_max = 0.277 <= 0.28, dP = 1.31)
Die eps = 0.40 -> largest Wi within the limit = 0.293 (M_max = 0.272 <= 0.28, dP = 1.68)

Figure S17.3. (a) Largest Weissenberg number that keeps below 0.28, found by bisection, against the wall amplitude. (b) Dimensionless pressure drop at that rate.
Explanation. The feed duct at flows, with a flow rate of 0.185 and 22 % of its cross-section unyielded. The largest admissible Weissenberg number falls quickly with the amplitude of the constriction: it is 0.63 for and 0.29 for . For the limit is not reached within the range searched ( at ). The calculation uses methods from all six parts of the book. The limit of 0.28 and the material parameters are assumed, so the numbers illustrate the procedure and are not a design.