Worked solutions to the three exercises of Lecture 11. 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: creep below and above the yield stress (CARBOPOL_EVP)")
carb = constants_benchmarks.BENCHMARK_FLUIDS_DB["CARBOPOL_EVP"]
G0_c, ty_c, etas_c = carb["G0_Pa"], carb["tau_y_Pa"], carb["eta_s_Pas"]
etap_c = 12.0
# Choose dt = 0.0005 s so explicit Kelvin-Voigt stiffness G0 * dt / eta_s = 0.38 < 1
t_evp1 = np.linspace(0.0, 0.60, 1201)
evp_sub = viscoplastic_admm.solve_saramito_evp_1d(
t_evp1, lambda _t: 30.0, G0=G0_c, tau_y=ty_c, eta_p=etap_c, eta_s=etas_c, mode="stress_controlled"
)
evp_sup = viscoplastic_admm.solve_saramito_evp_1d(
t_evp1, lambda _t: 75.0, G0=G0_c, tau_y=ty_c, eta_p=etap_c, eta_s=etas_c, mode="stress_controlled"
)
gamma_hooke_exact = 30.0 / G0_c
print(f"Sub-yield load (30 Pa < tau_y=45 Pa) : final strain = {evp_sub['strain'][-1]:.6f} (exact sigma/G0 = {gamma_hooke_exact:.6f}), final rate = {evp_sub['shear_rate'][-1]:.2e} s^-1, ever yielded? {bool(np.any(evp_sub['yielded_mask']))}")
print(f"Super-yield load (75 Pa > tau_y=45 Pa): final strain = {evp_sup['strain'][-1]:.4f}, steady flow rate = {evp_sup['shear_rate'][-1]:.3f} s^-1, yielded? {bool(evp_sup['yielded_mask'][-1])}")
assert np.isclose(evp_sub["strain"][-1], gamma_hooke_exact, rtol=1e-5)
assert abs(evp_sub["shear_rate"][-1]) < 1e-10
assert not bool(np.any(evp_sub["yielded_mask"]))
assert bool(evp_sup["yielded_mask"][-1]) and evp_sup["shear_rate"][-1] > 1.5
fig, axes = plt.subplots(1, 2, figsize=(10.2, 4.0))
axes[0].plot(t_evp1, evp_sub["strain"], color="#2166AC", lw=2.2, label=r"Sub-yield $\sigma_0 = 30$ Pa ($<\tau_y$)")
axes[0].axhline(gamma_hooke_exact, color="#2166AC", ls=":", lw=1.4, label=r"Hookean plateau $\sigma_0 / G_0$")
axes[0].plot(t_evp1, evp_sup["strain"], color="#C0392B", lw=2.2, label=r"Super-yield $\sigma_0 = 75$ Pa ($>\tau_y$)")
axes[0].set_xlabel("Time $t$ [s]")
axes[0].set_ylabel(r"Shear strain $\gamma(t)$")
axes[0].set_title(r"Strain under constant stress")
axes[0].legend(fontsize=8)
axes[1].plot(t_evp1, evp_sub["shear_rate"], color="#2166AC", lw=2.0, label=r"$\sigma_0 = 30$ Pa ($\dot{\gamma} \to 0$)")
axes[1].plot(t_evp1, evp_sup["shear_rate"], color="#C0392B", lw=2.0, label=r"$\sigma_0 = 75$ Pa (steady viscoplastic)")
axes[1].set_ylim(-2.0, 22.0)
axes[1].set_xlabel("Time $t$ [s]")
axes[1].set_ylabel(r"Shear rate $\dot{\gamma}(t)$ [s$^{-1}$]")
axes[1].set_title(r"Shear rate")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Derive the strain of the Saramito model for a stress of , below the yield stress , applied for and removed for (assumed parameters CARBOPOL_EVP). Below the yield stress the model is a Kelvin–Voigt solid. Compare with the numerical solution, and check that no strain remains after unloading.
heading("Exercise 1: creep and recovery below the yield stress")
carb_e1 = constants_benchmarks.BENCHMARK_FLUIDS_DB["CARBOPOL_EVP"]
G0_e1, ty_e1, etas_e1 = carb_e1["G0_Pa"], carb_e1["tau_y_Pa"], carb_e1["eta_s_Pas"]
sig0_sub = 32.0
t_cut = 0.25
t_e1 = np.linspace(0.0, 0.55, 2201)
sol_kv = viscoplastic_admm.solve_saramito_evp_1d(
t_e1, lambda t: sig0_sub if t < t_cut else 0.0, G0=G0_e1, tau_y=ty_e1, eta_p=12.0, eta_s=etas_e1, mode="stress_controlled"
)
rate_kv = G0_e1 / etas_e1
gam_at_cut = (sig0_sub / G0_e1) * (1.0 - math.exp(-rate_kv * t_cut))
gam_exact = np.where(
t_e1 < t_cut,
(sig0_sub / G0_e1) * (1.0 - np.exp(-rate_kv * t_e1)),
gam_at_cut * np.exp(-rate_kv * (t_e1 - t_cut)),
)
max_kv_err = float(np.max(np.abs(sol_kv["strain"] - gam_exact)))
perm_set = abs(float(sol_kv["strain"][-1]))
print(f"Max |Saramito EVP - exact Kelvin-Voigt| strain error = {max_kv_err:.3e}")
print(f"Peak elastic strain = {np.max(sol_kv['strain']):.6f} -> final permanent set = {perm_set:.3e}")
assert not bool(np.any(sol_kv["yielded_mask"]))
assert max_kv_err < 5e-4
assert perm_set < 1e-12
fig, ax = plt.subplots(figsize=(7.2, 3.9))
ax.plot(t_e1, gam_exact, "k-", lw=2.3, label="Exact analytical Kelvin–Voigt $\\gamma_{\\mathrm{KV}}(t)$")
ax.plot(t_e1[::55], sol_kv["strain"][::55], "ro", ms=5, label="Saramito EVP ($\\sigma_0 = 32 < \\tau_y = 45$ Pa)")
ax.axvline(t_cut, color="gray", ls=":", lw=1.3, label="Unloading $t = 0.25$ s")
ax.set_xlabel("Time $t$ [s]")
ax.set_ylabel(r"Strain $\gamma(t)$")
ax.set_title(r"Loading and unloading below the yield stress")
ax.legend(fontsize=8)
plt.show()
Exercise 1: creep and recovery below the yield stress
=====================================================
Max |Saramito EVP - exact Kelvin-Voigt| strain error = 2.154e-04
Peak elastic strain = 0.084211 -> final permanent set = 1.364e-16

Figure S11.1. Strain under 32 Pa until 0.25 s and no stress afterwards: the Saramito model (symbols) follows the Kelvin–Voigt solution (line) and the strain is fully recovered.
Explanation. The stress stays below the yield stress throughout, so the plastic term is zero and the model is a spring of modulus in parallel with the solvent viscosity. The strain approaches under load and returns to zero after unloading (the strain that remains is 10-16). The numerical strain differs from the exact one by at most , which is 0.3 % of the peak strain.
Exercise 2¶
Problem. Compare the Saramito model (CARBOPOL_EVP: ) with a Bingham model without elasticity for a pulse of stress of the kind applied in a dispensing nozzle: for , then until . Compute the strain that is recovered after the stress is removed and the most negative shear rate.
heading("Exercise 2: recoil after a stress pulse, with and without elasticity")
t_diw = np.linspace(0.0, 0.70, 1401)
t_stop = 0.35
idx_s = int(np.searchsorted(t_diw, t_stop))
sig_pulse = lambda t: 85.0 if t < t_stop else 0.0
evp_diw = viscoplastic_admm.solve_saramito_evp_1d(
t_diw, sig_pulse, G0=G0_c, tau_y=ty_c, eta_p=etap_c, eta_s=etas_c, mode="stress_controlled"
)
# Purely viscous Bingham model (G0 -> inf): gdot = max(0, sigma - tau_y) / (eta_p + eta_s)
gdot_bing = np.array([max(0.0, sig_pulse(float(tv)) - ty_c) / (etap_c + etas_c) for tv in t_diw])
dt_d = float(t_diw[1] - t_diw[0])
strain_bing = np.concatenate([[0.0], np.cumsum(0.5 * (gdot_bing[:-1] + gdot_bing[1:])) * dt_d])
rec_evp = float(evp_diw["strain"][-1] - evp_diw["strain"][idx_s])
rec_bing = float(strain_bing[-1] - strain_bing[idx_s])
print(f"Saramito EVP post-shutoff recoil : dgamma = {rec_evp:+.5f}, min rate = {np.min(evp_diw['shear_rate'][idx_s:]):+.2f} s^-1")
print(f"Purely viscous Bingham prediction: dgamma = {rec_bing:+.5f}, min rate = {np.min(gdot_bing[idx_s:]):+.2f} s^-1")
assert rec_bing == 0.0
assert rec_evp < -0.10
assert np.min(evp_diw["shear_rate"][idx_s:]) < -100.0
fig, axes = plt.subplots(1, 2, figsize=(9.8, 3.8))
axes[0].plot(t_diw, strain_bing, "r--", lw=2.1, label="Bingham model, no elasticity")
axes[0].plot(t_diw, evp_diw["strain"], "b-", lw=2.2, label=f"Saramito model ($\\Delta\\gamma={rec_evp:.3f}$)")
axes[0].axvline(t_stop, color="gray", ls=":", lw=1.3)
axes[0].set_xlabel("Time $t$ [s]")
axes[0].set_ylabel(r"Cumulative nozzle shear strain $\gamma(t)$")
axes[0].set_title(r"Strain")
axes[0].legend(fontsize=8)
axes[1].plot(t_diw, gdot_bing, "r--", lw=2.1, label="Viscous Bingham $\\dot{\\gamma} \\geq 0$")
axes[1].plot(t_diw, evp_diw["shear_rate"], "b-", lw=2.0, label="Saramito EVP recoil spike")
axes[1].axvline(t_stop, color="gray", ls=":", lw=1.3)
axes[1].set_ylim(-165.0, 25.0)
axes[1].set_xlabel("Time $t$ [s]")
axes[1].set_ylabel(r"Shear rate $\dot{\gamma}(t)$ [s$^{-1}$]")
axes[1].set_title(r"Shear rate")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 2: recoil after a stress pulse, with and without elasticity
====================================================================
Saramito EVP post-shutoff recoil : dgamma = -0.21808, min rate = -166.64 s^-1
Purely viscous Bingham prediction: dgamma = +0.00000, min rate = +0.00 s^-1

Figure S11.2. Removal of the stress at 0.35 s. (a) Strain of the Saramito model, which recoils, and of a viscous Bingham model, which does not. (b) Shear rate.
Explanation. The Bingham model stores no elastic energy, and its strain stays constant after the stress is removed. The Saramito model recovers a strain of 0.218, with a shear rate that reaches just after the stress is removed. This rate is close to : the model has no inertia, and the recoil is resisted by the solvent viscosity alone. In dispensing, the recoil appears as material drawn back into the nozzle when the pressure is removed, which a model without elasticity cannot describe.
Exercise 3¶
Problem. Write solve_channel_saramito_evp_1d(ny, H_half, dpdz_fn, t_grid, G0, tau_y, eta_p, eta_s) in NumPy for flow without inertia in a plane channel, , with the shear stress and the velocity . Use the parameters CARBOPOL_EVP with and (a wall stress of ) for and afterwards. Check that the yield surface is at and that the centreline velocity is negative after the pressure gradient is removed.
heading("Exercise 3: start-up and stopping of channel flow of the Saramito model")
def solve_channel_saramito_evp_1d(
ny: int, H_half: float, dpdz_fn, t_grid: np.ndarray, G0: float, tau_y: float, eta_p: float, eta_s: float
) -> dict:
"""Vectorized 1-D planar channel Saramito EVP solver reconstructing u(y, t) across [0, H_half]."""
y = np.linspace(0.0, H_half, ny)
dy = float(y[1] - y[0])
lam = eta_p / G0
txx = np.zeros(ny)
txy = np.zeros(ny)
u_center_hist = np.zeros(t_grid.size)
u_profiles = {}
def rhs_vec(xx: np.ndarray, xy: np.ndarray, te: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
sig_y = float(dpdz_fn(te)) * y # Exact creeping stress distribution sigma(y) = G(t) * y
gd = (sig_y - xy) / eta_s # gd = -du/dy >= 0 during forward pumping
vm = np.sqrt(0.5 * (xx**2) + (xy**2))
yf = np.maximum(0.0, (vm - tau_y) / np.maximum(vm, 1e-15))
return 2.0 * gd * xy - (yf / lam) * xx, G0 * gd - (yf / lam) * xy, gd
for k in range(t_grid.size):
tk = float(t_grid[k])
_, _, gd_cur = rhs_vec(txx, txy, tk)
# Integrate -du/dy = gd_cur inward from wall y = H_half (u(H_half) == 0):
u_prof = np.zeros(ny)
u_prof[:-1] = np.cumsum(0.5 * (gd_cur[:-1] + gd_cur[1:])[::-1])[::-1] * dy
u_center_hist[k] = float(u_prof[0])
if k in (int(0.48 * t_grid.size), int(0.51 * t_grid.size)):
u_profiles[k] = (tk, u_prof.copy(), np.sqrt(0.5 * txx**2 + txy**2) > tau_y)
if k == t_grid.size - 1:
break
dt = float(t_grid[k + 1] - t_grid[k])
k1x, k1y, _ = rhs_vec(txx, txy, tk)
k2x, k2y, _ = rhs_vec(txx + 0.5 * dt * k1x, txy + 0.5 * dt * k1y, tk + 0.5 * dt)
txx = txx + dt * k2x
txy = txy + dt * k2y
return {"y": y, "t": t_grid, "u_centerline": u_center_hist, "snapshots": u_profiles}
t_ch = np.linspace(0.0, 0.70, 1401)
ch_sol = solve_channel_saramito_evp_1d(
ny=81,
H_half=0.01,
dpdz_fn=lambda t: 9000.0 if t < 0.35 else 0.0,
t_grid=t_ch,
G0=G0_c,
tau_y=ty_c,
eta_p=etap_c,
eta_s=etas_c,
)
k_pump, k_recoil = sorted(ch_sol["snapshots"].keys())
t_p, u_p, y_mask_p = ch_sol["snapshots"][k_pump]
t_r, u_r, _ = ch_sol["snapshots"][k_recoil]
min_u0 = float(np.min(ch_sol["u_centerline"]))
# During pumping at G = 9000 Pa/m, tau_y / G = 45 / 9000 = 0.005 m == 0.5 * H_half:
y_yield_num = float(ch_sol["y"][int(np.argmax(y_mask_p))])
print(f"Forward pumping (t={t_p:.3f} s): u(0) = +{u_p[0]*1e3:.2f} mm/s | yield boundary y_p = {y_yield_num*1e3:.2f} mm (exact 5.00 mm)")
print(f"Post-shutoff recoil : min centreline velocity u(0) = {min_u0*1e3:.2f} mm/s")
assert abs(y_yield_num - 0.005) <= 0.0003
assert u_p[0] > 0.008
assert min_u0 < -0.25 and u_r[0] < 0.0
y_sym = np.concatenate([-ch_sol["y"][::-1], ch_sol["y"][1:]]) * 1e3
u_p_sym = np.concatenate([u_p[::-1], u_p[1:]]) * 1e3
u_r_sym = np.concatenate([u_r[::-1], u_r[1:]]) * 1e3
fig, axes = plt.subplots(1, 2, figsize=(10.2, 4.0))
axes[0].plot(u_p_sym, y_sym, "b-", lw=2.2, label=f"Flow ($t={t_p:.2f}$ s)")
axes[0].plot(u_r_sym, y_sym, "r-", lw=2.2, label=f"Shutoff ($t={t_r:.2f}$ s, reverse recoil)")
axes[0].axvline(0.0, color="black", lw=1.0)
axes[0].axhspan(-5.0, 5.0, color="#d4e6f1", alpha=0.45, label="Unyielded region $[-5, +5]$ mm")
axes[0].set_xlabel("Axial velocity $u(y, t)$ [mm/s]")
axes[0].set_ylabel("Channel coordinate $y$ [mm]")
axes[0].set_title(r"Velocity profiles")
axes[0].legend(fontsize=8, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=1)
axes[1].plot(t_ch, ch_sol["u_centerline"] * 1e3, color="#7B4FA3", lw=2.1)
axes[1].axhline(0.0, color="black", lw=1.0)
axes[1].axvline(0.35, color="gray", ls=":", lw=1.3, label="Pressure shutoff $G: 9000 \\to 0$")
axes[1].set_ylim(-500.0, 60.0)
axes[1].set_xlabel("Time $t$ [s]")
axes[1].set_ylabel("Centreline velocity $u(0, t)$ [mm/s]")
axes[1].set_title(r"Centreline velocity")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 3: start-up and stopping of channel flow of the Saramito model
=======================================================================
Forward pumping (t=0.336 s): u(0) = +9.51 mm/s | yield boundary y_p = 5.00 mm (exact 5.00 mm)
Post-shutoff recoil : min centreline velocity u(0) = -890.49 mm/s

Figure S11.3. Saramito model in a plane channel. (a) Velocity while the pressure gradient is applied, with the unyielded core (shaded), and just after it is removed. (b) Centreline velocity, negative after the removal (the axis is cut at -500 mm/s).
Explanation. During the flow the fluid is yielded for mm, and the centreline velocity is 9.5 mm/s. When the pressure gradient is removed, the elastic strain stored across the whole gap is released and the centreline moves backwards, with a velocity that reaches -890 mm/s. This magnitude is a property of a model without inertia, in which the recoil is resisted by the solvent viscosity alone (Exercise 2); in a real flow the inertia of the fluid limits the velocity. The result that does not depend on this simplification is the sign: the flow reverses.