Worked solutions to the three exercises of Lecture 8. 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: flow curves of the Johnson-Segalman model and the condition beta_s < 1/8")
wlm_db = constants_benchmarks.BENCHMARK_FLUIDS_DB["WLM_CPYCL"]
beta_wlm = wlm_db["eta_s_Pas"] / (wlm_db["G0_Pa"] * wlm_db["lam_s"])
print(f"Parameter set WLM_CPYCL solvent viscosity ratio beta_s = {beta_wlm:.5f} << 1/8 = 0.125")
assert beta_wlm < 0.01
rates_js = np.linspace(0.0, 9.0, 450)
betas_test = [0.03, 0.06, 0.125, 0.20]
colors_js = ["#C0392B", "#E08214", "#2E8B57", "#2166AC"]
fig, ax = plt.subplots(figsize=(7.6, 4.2))
for b_val, col in zip(betas_test, colors_js):
res = shear_banding_instabilities.steady_johnson_segalman_curve(rates_js, G0=1.0, lam=1.0, eta_s=b_val, xi_slip=0.2)
dtau = np.diff(res["tau_total"])
has_neg_slope = bool(np.any(dtau < -1e-9))
print(f"beta_s = {b_val:5.3f} | is_non_monotonic = {str(res['is_non_monotonic']):5s} | spinodal_rates = {res['spinodal_rates']}")
if b_val < 0.125 - 1e-9:
assert res["is_non_monotonic"] is True and has_neg_slope is True
r_lo, r_hi = res["spinodal_rates"]
ax.scatter([r_lo, r_hi], np.interp([r_lo, r_hi], rates_js, res["tau_total"]), color=col, s=45, zorder=5)
else:
assert res["is_non_monotonic"] is False and has_neg_slope is False
ax.plot(rates_js, res["tau_total"], lw=2.1, color=col, label=f"$\\beta_s = {b_val:.3f}$ ({'non-monotonic' if res['is_non_monotonic'] else 'monotonic'})")
ax.set_xlabel(r"Dimensionless shear rate $\mathrm{Wi} = \lambda\dot{\gamma}$")
ax.set_ylabel(r"Dimensionless total shear stress $\Sigma / G_0$")
ax.set_title(r"Flow curves of the Johnson–Segalman model ($\xi = 0.2$)")
ax.legend(fontsize=8)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Show that the flow curve of the Johnson–Segalman model is non-monotonic below for every slip parameter between 0 and 2, and that at the inflection is at the shear rate . Check both results with steady_johnson_segalman_curve for .
heading("Exercise 1: the limit beta_s = 1/8 and the inflection rate")
xi_vals = [0.1, 0.3, 0.6, 1.0]
g_grid = np.linspace(0.0, 10.0, 4001)
inflection_num, inflection_exact = [], []
fig, axes = plt.subplots(1, 2, figsize=(9.8, 3.8))
for xi_v in xi_vals:
# Just below 1/8 -> non-monotonic; at 1/8 -> monotonic with horizontal inflection at w = sqrt(3):
below = shear_banding_instabilities.steady_johnson_segalman_curve(g_grid, G0=1.0, lam=1.0, eta_s=0.124, xi_slip=xi_v)
crit = shear_banding_instabilities.steady_johnson_segalman_curve(g_grid, G0=1.0, lam=1.0, eta_s=0.125, xi_slip=xi_v)
assert below["is_non_monotonic"] is True
assert crit["is_non_monotonic"] is False
slope = np.gradient(crit["tau_total"], g_grid)
idx_min = int(np.argmin(slope))
g_star_num = float(g_grid[idx_min])
g_star_ex = math.sqrt(3.0 / (xi_v * (2.0 - xi_v)))
inflection_num.append(g_star_num)
inflection_exact.append(g_star_ex)
print(f"xi = {xi_v:3.1f} | min(dSigma/dgdot) at beta=1/8 = {slope[idx_min]:.2e} | gdot* = {g_star_num:.4f} (exact = {g_star_ex:.4f})")
assert abs(slope[idx_min]) < 2e-5
assert abs(g_star_num - g_star_ex) < 0.01
axes[0].plot(g_grid, crit["tau_total"], lw=2.0, label=f"$\\xi = {xi_v:.1f}$ ($\\dot{{\\gamma}}_* = {g_star_ex:.2f}$)")
axes[0].scatter([g_star_ex], [np.interp(g_star_ex, g_grid, crit["tau_total"])], s=45, zorder=5)
axes[0].set_xlabel(r"Dimensionless rate $\lambda\dot{\gamma}$")
axes[0].set_ylabel(r"Critical flow curve $\Sigma(\dot{\gamma})$ at $\beta_s = 1/8$")
axes[0].set_title(r"Flow curves at $\beta_s = 1/8$")
axes[0].legend(fontsize=8)
xi_cont = np.linspace(0.06, 1.94, 200)
axes[1].plot(xi_cont, np.sqrt(3.0 / (xi_cont * (2.0 - xi_cont))), "k-", lw=2.0, label=r"Exact $\sqrt{3 / [\xi(2-\xi)]}$")
axes[1].plot(xi_vals, inflection_num, "ro", ms=6, label="Numerical minimum-slope point")
axes[1].set_xlabel(r"Gordon–Schowalter slip parameter $\xi$")
axes[1].set_ylabel(r"Inflection rate $\lambda\dot{\gamma}_*$")
axes[1].set_title(r"Rate at the inflection point")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 1: the limit beta_s = 1/8 and the inflection rate
==========================================================
xi = 0.1 | min(dSigma/dgdot) at beta=1/8 = 5.86e-08 | gdot* = 3.9725 (exact = 3.9736)
xi = 0.3 | min(dSigma/dgdot) at beta=1/8 = 1.06e-07 | gdot* = 2.4250 (exact = 2.4254)
xi = 0.6 | min(dSigma/dgdot) at beta=1/8 = 1.66e-07 | gdot* = 1.8900 (exact = 1.8898)
xi = 1.0 | min(dSigma/dgdot) at beta=1/8 = 2.14e-07 | gdot* = 1.7325 (exact = 1.7321)

Figure S8.1. (a) At the flow curve has a horizontal inflection point for every (circles). (b) The rate at that point against , with .
Explanation. With the slope of the polymer contribution to the shear stress is proportional to . With this is , whose derivative vanishes at , that is , where the value is . The slope of the total stress is therefore non-negative everywhere when , whatever the value of ; the slip parameter enters the position of the inflection through alone. The computed minimum slope at is between and , and the inflection rates agree with the formula to 0.03 %.
Exercise 2¶
Problem. Run solve_1d_diffusive_johnson_segalman at , and without stress diffusion () and with , for amplitudes of the initial perturbation (init_perturbation) between 0.01 and 0.18. Compare the spread of the steady total stress in the two cases.
heading("Exercise 2: the selected stress with and without stress diffusion")
perts = [0.01, 0.18]
plat_ld0, plat_ld_pos = [], []
prof_ld0, prof_ld_pos = [], []
for p_amp in perts:
s0 = shear_banding_instabilities.solve_1d_diffusive_johnson_segalman(
wi_applied=3.0, beta_s=0.05, xi_slip=0.2, l_diff=0.0, ny=32, t_end=68.0, dt=0.025, init_perturbation=p_amp
)
sp = shear_banding_instabilities.solve_1d_diffusive_johnson_segalman(
wi_applied=3.0, beta_s=0.05, xi_slip=0.2, l_diff=0.025, ny=32, t_end=68.0, dt=0.025, init_perturbation=p_amp
)
plat_ld0.append(s0["total_stress_plateau"])
plat_ld_pos.append(sp["total_stress_plateau"])
prof_ld0.append(s0["shear_rate_profile"])
prof_ld_pos.append(sp["shear_rate_profile"])
print(f"init_pert = {p_amp:4.2f} | l_d = 0.000 plateau = {s0['total_stress_plateau']:.8f} | l_d = 0.025 plateau = {sp['total_stress_plateau']:.8f}")
spread_0 = float(max(plat_ld0) - min(plat_ld0))
spread_pos = float(max(plat_ld_pos) - min(plat_ld_pos))
print(f"Plateau spread across initial perturbations: l_d = 0 -> {spread_0:.4e} against l_d = 0.025 -> {spread_pos:.4e}")
assert spread_0 > 0.01
assert spread_pos < 1e-8
fig, axes = plt.subplots(1, 2, figsize=(10.0, 3.9))
yg = np.linspace(0.5 / 32, 1.0 - 0.5 / 32, 32)
for p_amp, g0, gp in zip(perts, prof_ld0, prof_ld_pos):
axes[0].plot(yg, g0, lw=1.8, label=f"Perturbation {p_amp:.2f} ($\\Sigma={plat_ld0[perts.index(p_amp)]:.4f}$)")
axes[1].plot(yg, gp, lw=1.8, label=f"Perturbation {p_amp:.2f} ($\\Sigma={plat_ld_pos[perts.index(p_amp)]:.4f}$)")
axes[0].set_xlabel(r"Gap coordinate $y / H$")
axes[0].set_ylabel(r"Local shear rate $\dot{\gamma}(y)$")
axes[0].set_title(r"Without stress diffusion")
axes[0].legend(fontsize=8)
axes[1].set_xlabel(r"Gap coordinate $y / H$")
axes[1].set_ylabel(r"Local shear rate $\dot{\gamma}(y)$")
axes[1].set_title(r"With stress diffusion ($\ell_d = 0.025$)")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 2: the selected stress with and without stress diffusion
=================================================================
init_pert = 0.01 | l_d = 0.000 plateau = 0.80848294 | l_d = 0.025 plateau = 0.80872453
init_pert = 0.18 | l_d = 0.000 plateau = 0.77590236 | l_d = 0.025 plateau = 0.80872453
Plateau spread across initial perturbations: l_d = 0 -> 3.2581e-02 against l_d = 0.025 -> 1.5465e-13

Figure S8.2. Shear-rate profiles from two initial perturbations. (a) Without stress diffusion the position of the interface and the stress depend on the perturbation. (b) With stress diffusion the two runs coincide.
Explanation. Without the term the layers of fluid are coupled through the total stress alone, and any stress within the range of coexistence gives a steady state. The stress then depends on the initial perturbation (0.808 for an amplitude of 0.01 and 0.776 for 0.18, a spread of 0.033) and also on the grid. With all runs give 0.80872453, with a spread of . A calculation of shear banding without stress diffusion does not predict the stress.
Exercise 3¶
Problem. Write measure_djs_interface_width(l_diff, ny=96) in NumPy: a solver of the diffusive Johnson–Segalman model in one dimension that returns the width of the interface between the bands, . Evaluate it for , and check that the width is proportional to and that the total stress does not depend on it.
heading("Exercise 3: width of the interface between shear bands")
def measure_djs_interface_width(l_diff: float, ny: int = 96, wi: float = 3.0, beta_s: float = 0.05, xi: float = 0.2) -> dict:
"""This solver, NumPy 1-D Couette dJS solver measuring intrinsic band interface width."""
dy = 1.0 / ny
y = (np.arange(ny) + 0.5) * dy
a = 1.0 - xi
w2 = xi * (2.0 - xi) * (wi**2)
txy = np.full(ny, wi / (1.0 + w2)) + 0.04 * np.cos(math.pi * y)
txx = np.full(ny, (1.0 + a) * (wi**2) / (1.0 + w2))
tyy = np.full(ny, -(1.0 - a) * (wi**2) / (1.0 + w2))
dt = 0.04
alpha = dt * ((l_diff / dy) ** 2)
M_neu = np.diag(np.full(ny, 1.0 + 2.0 * alpha)) - np.diag(np.full(ny - 1, alpha), 1) - np.diag(np.full(ny - 1, alpha), -1)
M_neu[0, 0] = 1.0 + alpha
M_neu[-1, -1] = 1.0 + alpha
M_inv = np.linalg.inv(M_neu)
for _ in range(1500):
sig = beta_s * wi + float(np.mean(txy))
gd = (sig - txy) / beta_s
txx_m = txx + 0.5 * dt * (-txx + (1.0 + a) * gd * txy)
tyy_m = tyy + 0.5 * dt * (-tyy - (1.0 - a) * gd * txy)
txy_m = txy + 0.5 * dt * (-txy + gd + 0.5 * ((1.0 + a) * tyy - (1.0 - a) * txx) * gd)
sig_m = beta_s * wi + float(np.mean(txy_m))
gd_m = (sig_m - txy_m) / beta_s
txx = M_inv @ (txx + dt * (-txx_m + (1.0 + a) * gd_m * txy_m))
tyy = M_inv @ (tyy + dt * (-tyy_m - (1.0 - a) * gd_m * txy_m))
txy = M_inv @ (txy + dt * (-txy_m + gd_m + 0.5 * ((1.0 + a) * tyy_m - (1.0 - a) * txx_m) * gd_m))
sig_f = beta_s * wi + float(np.mean(txy))
gd_f = (sig_f - txy) / beta_s
max_grad = float(np.max(np.abs(np.gradient(gd_f, y))))
width = float((np.max(gd_f) - np.min(gd_f)) / max_grad)
return {"y": y, "gdot": gd_f, "width": width, "plateau": sig_f}
ld_list = np.array([0.025, 0.040, 0.065])
widths, plateaus = [], []
fig, axes = plt.subplots(1, 2, figsize=(10.0, 3.9))
for ld_v in ld_list:
out_l = measure_djs_interface_width(float(ld_v), ny=88)
widths.append(out_l["width"])
plateaus.append(out_l["plateau"])
print(f"l_d = {ld_v:.3f} | interface width delta_int = {out_l['width']:.4f} (ratio delta/l_d = {out_l['width']/ld_v:.2f}) | Sigma = {out_l['plateau']:.5f}")
axes[0].plot(out_l["y"], out_l["gdot"], lw=2.0, label=f"$\\ell_d = {ld_v:.3f}$ ($\\delta={out_l['width']:.3f}$)")
widths_arr = np.array(widths)
ratios = widths_arr / ld_list
assert np.max(np.abs(ratios - np.mean(ratios))) / np.mean(ratios) < 0.08
assert np.max(plateaus) - np.min(plateaus) < 0.008
axes[0].set_xlabel(r"Gap coordinate $y / H$")
axes[0].set_ylabel(r"Shear rate $\dot{\gamma}(y)$")
axes[0].set_title(r"Shear rate across the interface")
axes[0].legend(fontsize=8)
axes[1].plot(ld_list, widths_arr, "ro-", lw=2.1, ms=7, label="Measured $\\delta_{\\mathrm{int}}$")
axes[1].plot(ld_list, float(np.mean(ratios)) * ld_list, "k--", lw=1.5, label=f"Proportional fit $\\delta \\approx {np.mean(ratios):.2f}\\,\\ell_d$")
axes[1].set_xlabel(r"Stress-diffusion length $\ell_d / H$")
axes[1].set_ylabel(r"Interface thickness $\delta_{\mathrm{int}} / H$")
axes[1].set_title(r"Interface width against $\ell_d$")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 3: width of the interface between shear bands
======================================================
l_d = 0.025 | interface width delta_int = 0.0544 (ratio delta/l_d = 2.17) | Sigma = 0.80492
l_d = 0.040 | interface width delta_int = 0.0853 (ratio delta/l_d = 2.13) | Sigma = 0.80485
l_d = 0.065 | interface width delta_int = 0.1360 (ratio delta/l_d = 2.09) | Sigma = 0.80481

Figure S8.3. (a) Shear-rate profiles for three diffusion lengths. (b) Interface width against , with a proportional fit of slope 2.13.
Explanation. The width of the interface is 0.054, 0.085 and 0.136, that is 2.17, 2.13 and 2.09 times , while the total stress changes by 0.01 % (from 0.80492 to 0.80481). The stress selected by diffusion therefore has a limit as , although a calculation with selects no stress (Exercise 2). A grid has to resolve the interface: with a width of about , the spacing should be no larger than about .