Worked solutions to the three exercises of Lecture 6. 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: steady shear of the FENE-P and FENE-CR models")
b_demo1 = 50.0
lam_d1, eta_p_d1 = 1.0, 1.0
wi_sweep = np.geomspace(0.25, 14.0, 9)
eta_fp, eta_fcr, eta_fp_exact = [], [], []
n1_fp, n1_fcr = [], []
for wi_val in wi_sweep:
t_end = max(10.0, 18.0 / min(1.0, wi_val))
t_g = np.linspace(0.0, t_end, 220)
L_sh = lambda _t, g=wi_val: np.array([[0.0, g, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
sol_p = entangled_tubes.solve_fenep_fenecr(L_sh, t_g, lam=lam_d1, eta_p=eta_p_d1, b_ext=b_demo1, variant="fenep")
sol_cr = entangled_tubes.solve_fenep_fenecr(L_sh, t_g, lam=lam_d1, eta_p=eta_p_d1, b_ext=b_demo1, variant="fenecr")
eta_fp.append(float(sol_p["tau_p"][-1, 0, 1] / wi_val))
eta_fcr.append(float(sol_cr["tau_p"][-1, 0, 1] / wi_val))
n1_fp.append(float(sol_p["tau_p"][-1, 0, 0] - sol_p["tau_p"][-1, 1, 1]))
n1_fcr.append(float(sol_cr["tau_p"][-1, 0, 0] - sol_cr["tau_p"][-1, 1, 1]))
# Exact real root >= 1 of f^3 - f^2 - 2*Wi^2/b = 0:
roots = np.roots([1.0, -1.0, 0.0, -2.0 * (wi_val**2) / b_demo1])
f_real = float(np.max(roots[np.isclose(roots.imag, 0.0)].real))
eta_fp_exact.append(eta_p_d1 / f_real)
eta_fp = np.array(eta_fp)
eta_fcr = np.array(eta_fcr)
eta_fp_exact = np.array(eta_fp_exact)
print(f"{'Wi':>6s} | {'eta_p (FENE-P)':>15s} | {'Exact Cubic':>12s} | {'eta_p (FENE-CR)':>16s} | {'N1 (FENE-P)':>12s}")
print("-" * 72)
for w, ep, ex, ecr, n1v in zip(wi_sweep, eta_fp, eta_fp_exact, eta_fcr, n1_fp):
print(f"{w:6.2f} | {ep:15.5f} | {ex:12.5f} | {ecr:16.5f} | {n1v:12.4f}")
assert np.allclose(eta_fcr, eta_p_d1, rtol=2e-3, atol=2e-3)
assert np.allclose(eta_fp, eta_fp_exact, rtol=4e-3, atol=4e-3)
assert eta_fp[-1] < 0.45 * eta_p_d1
fig, axes = plt.subplots(1, 2, figsize=(10.2, 4.0))
axes[0].semilogx(wi_sweep, eta_fcr, "s-", color="#2166AC", lw=2.0, label="FENE-CR (constant $\\eta_p$)")
axes[0].semilogx(wi_sweep, eta_fp, "o-", color="#C0392B", lw=2.0, label="FENE-P (log-$\\mathbf{C}$ RK2)")
axes[0].semilogx(wi_sweep, eta_fp_exact, "k--", lw=1.5, label="Exact cubic $f^3 - f^2 = 2\\mathrm{Wi}^2/b$")
axes[0].set_xlabel(r"Weissenberg number $\mathrm{Wi} = \lambda\dot{\gamma}$")
axes[0].set_ylabel(r"Normalized polymer viscosity $\eta_p / \eta_{p,0}$")
axes[0].set_title(r"Polymer viscosity ($b = 50$)")
axes[0].legend(fontsize=8)
axes[1].loglog(wi_sweep, n1_fcr, "s-", color="#2166AC", lw=2.0, label="FENE-CR $N_1$")
axes[1].loglog(wi_sweep, n1_fp, "o-", color="#C0392B", lw=2.0, label="FENE-P $N_1$")
axes[1].set_xlabel(r"Weissenberg number $\mathrm{Wi} = \lambda\dot{\gamma}$")
axes[1].set_ylabel(r"First normal stress difference $N_1 / G_0$")
axes[1].set_title(r"First normal stress difference")
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 cubic equation for in steady shear of the FENE-P model, compare solve_fenep_fenecr with its root for , and check the power laws at high Weissenberg number, and .
heading("Exercise 1: the cubic equation of steady shear and the power laws at high Wi")
b_ex1 = 60.0
wi_dense = np.geomspace(0.2, 5.0e4, 80)
f_cubic = np.array(
[float(np.max(np.roots([1.0, -1.0, 0.0, -2.0 * (w**2) / b_ex1]).real)) for w in wi_dense]
)
eta_cubic = 1.0 / f_cubic
n1_cubic = 2.0 * (wi_dense**2) / (f_cubic**2)
# Verify numerical ODE integration at representative Wi values:
wi_pts = np.array([0.5, 2.5, 10.0, 25.0])
eta_num, n1_num = [], []
for wv in wi_pts:
tg = np.linspace(0.0, max(6.0, 14.0 / min(1.0, wv)), 360)
sol = entangled_tubes.solve_fenep_fenecr(
lambda _t, g=wv: np.array([[0.0, g, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]),
tg,
lam=1.0,
eta_p=1.0,
b_ext=b_ex1,
variant="fenep",
)
eta_num.append(float(sol["tau_p"][-1, 0, 1] / wv))
n1_num.append(float(sol["tau_p"][-1, 0, 0] - sol["tau_p"][-1, 1, 1]))
f_pts = np.array([float(np.max(np.roots([1.0, -1.0, 0.0, -2.0 * (w**2) / b_ex1]).real)) for w in wi_pts])
assert np.allclose(eta_num, 1.0 / f_pts, rtol=5e-3)
assert np.allclose(n1_num, 2.0 * (wi_pts**2) / (f_pts**2), rtol=6e-3)
# Fit asymptotic log-log slopes on Wi in [5e3, 5e4]:
hi_mask = wi_dense >= 5.0e3
slope_eta = float(np.polyfit(np.log(wi_dense[hi_mask]), np.log(eta_cubic[hi_mask]), 1)[0])
slope_n1 = float(np.polyfit(np.log(wi_dense[hi_mask]), np.log(n1_cubic[hi_mask]), 1)[0])
print(f"Asymptotic log-log slope of eta_p(Wi): {slope_eta:+.4f} (exact theory = {-2/3:+.4f})")
print(f"Asymptotic log-log slope of N1(Wi) : {slope_n1:+.4f} (exact theory = {+2/3:+.4f})")
assert abs(slope_eta - (-2.0 / 3.0)) < 0.015
assert abs(slope_n1 - (2.0 / 3.0)) < 0.015
fig, axes = plt.subplots(1, 2, figsize=(9.8, 3.8))
axes[0].loglog(wi_dense, eta_cubic, "k-", lw=2.0, label="Exact cubic $\\eta_p = \\eta_{p,0}/f$")
axes[0].loglog(wi_pts, eta_num, "ro", ms=6, label="Log-$\\mathbf{C}$ ODE steady state")
axes[0].loglog(wi_dense[hi_mask], ((b_ex1 / 2.0) ** (1.0 / 3.0)) * (wi_dense[hi_mask] ** (-2.0 / 3.0)), "b--", lw=1.5, label=r"$(b/2)^{1/3}\mathrm{Wi}^{-2/3}$")
axes[0].set_xlabel(r"$\mathrm{Wi}$")
axes[0].set_ylabel(r"$\eta_p / \eta_{p,0}$")
axes[0].set_title(r"Polymer viscosity")
axes[0].legend(fontsize=8)
axes[1].loglog(wi_dense, n1_cubic, "k-", lw=2.0, label="Exact cubic $N_1 = 2G_0\\mathrm{Wi}^2/f^2$")
axes[1].loglog(wi_pts, n1_num, "ro", ms=6, label="Log-$\\mathbf{C}$ ODE steady state")
axes[1].loglog(wi_dense[hi_mask], 2.0 * ((b_ex1 / 2.0) ** (1.0 / 3.0)) * (wi_dense[hi_mask] ** (2.0 / 3.0)), "b--", lw=1.5, label=r"$2(b/2)^{1/3}\mathrm{Wi}^{2/3}$")
axes[1].set_xlabel(r"$\mathrm{Wi}$")
axes[1].set_ylabel(r"$N_1 / G_0$")
axes[1].set_title(r"First normal stress difference")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 1: the cubic equation of steady shear and the power laws at high Wi
============================================================================
Asymptotic log-log slope of eta_p(Wi): -0.6655 (exact theory = -0.6667)
Asymptotic log-log slope of N1(Wi) : +0.6689 (exact theory = +0.6667)

Figure S6.1. FENE-P in steady shear up to very high : the root of the cubic (line), steady states of the integration (symbols) and the power laws and (dashed). (a) Viscosity. (b) First normal stress difference.
Explanation. In steady shear the FENE-P model gives , and , so that . The definition of gives . Equating the two and multiplying by leaves . At high Weissenberg number ; the fitted slopes are -0.666 for the viscosity and +0.669 for , against and .
Exercise 2¶
Problem. Reproduce two errors of implementation of the FENE-P model and correct them. (1) The function is used with the stress and the initial state , without flow (, ): compute the stress at rest, which should be zero, and follow . (2) The dependence of the drag on the conformation is left out of fenep_planar_extension_hysteresis: compare the area of the hysteresis loop with and without it.
heading("Exercise 2: stress at rest with the wrong FENE-P function, and hysteresis without variable drag")
b_bug, G0_bug, lam_bug = 30.0, 100.0, 1.0
t_rest = np.linspace(0.0, 4.0, 161)
I3 = np.eye(3)
# Unnormalized FENE-P form without flow (L = 0):
C_bug = I3.copy()
tr_bug_hist, p_stress_bug = [], []
dt_r = float(t_rest[1] - t_rest[0])
for _ in t_rest:
f_bad = 1.0 / (1.0 - float(np.trace(C_bug)) / b_bug)
tau_bad = G0_bug * (f_bad * C_bug - I3)
tr_bug_hist.append(float(np.trace(C_bug)))
p_stress_bug.append(float(np.trace(tau_bad) / 3.0))
C_bug = C_bug - dt_r * (f_bad * C_bug - I3) / lam_bug
# Normalized form (Bird) in solve_fenep_fenecr without flow (L = 0):
sol_rest_ok = entangled_tubes.solve_fenep_fenecr(
lambda _t: np.zeros((3, 3)), t_rest, lam=lam_bug, eta_p=G0_bug * lam_bug, b_ext=b_bug, variant="fenep"
)
p_stress_ok = np.trace(sol_rest_ok["tau_p"], axis1=1, axis2=2) / 3.0
expected_spurious_p0 = 3.0 * G0_bug / (b_bug - 3.0)
print(f"Stress at rest with f(I) != 1 : {p_stress_bug[0]:.4f} Pa (exact 3*G0/(b-3) = {expected_spurious_p0:.4f} Pa)")
print(f"Trace with f(I) != 1 : tr(C) changed from 3.0000 to {tr_bug_hist[-1]:.4f} (3*b/(b+3) = {3*b_bug/(b_bug+3):.4f})")
print(f"With f(I) = 1, max |stress at rest| : {np.max(np.abs(sol_rest_ok['tau_p'])):.3e} Pa")
assert np.isclose(p_stress_bug[0], expected_spurious_p0, rtol=1e-12)
assert abs(tr_bug_hist[-1] - 3.0) > 0.24
assert np.max(np.abs(sol_rest_ok["tau_p"])) < 1e-14
assert np.allclose(sol_rest_ok["trace_C"], 3.0, atol=1e-14)
# Part (b): Drag omission destroying coil-stretch hysteresis:
wi_g = np.linspace(0.15, 0.70, 28)
h_bad = entangled_tubes.fenep_planar_extension_hysteresis(wi_g, b_ext=120.0, include_conformation_dependent_drag=False)
h_good = entangled_tubes.fenep_planar_extension_hysteresis(wi_g, b_ext=120.0, include_conformation_dependent_drag=True)
print(f"Hysteresis area with constant drag : {h_bad['hysteresis_area']:.4f} against, with conformation-dependent drag, {h_good['hysteresis_area']:.4f}")
assert h_good["hysteresis_area"] > 40.0 * h_bad["hysteresis_area"]
fig, axes = plt.subplots(1, 2, figsize=(9.8, 3.8))
axes[0].plot(t_rest, tr_bug_hist, "r--", lw=2.0, label=r"$f = (1-\operatorname{tr}\mathbf{C}/b)^{-1}$")
axes[0].plot(t_rest, sol_rest_ok["trace_C"], "b-", lw=2.0, label=r"$f = (b-3)/(b-\operatorname{tr}\mathbf{C})$")
axes[0].set_xlabel("Quiescent time $t / \\lambda$")
axes[0].set_ylabel(r"Quiescent trace $\operatorname{tr}\mathbf{C}(t)$")
axes[0].set_title(r"Trace of $\mathbf{C}$ at rest")
axes[0].legend(fontsize=8)
axes[1].bar(["Constant drag", "Conformation-\ndependent drag"], [h_bad["hysteresis_area"], h_good["hysteresis_area"]], color=["#C5CCD3", "#C0392B"])
axes[1].set_ylabel("Coil–stretch loop area")
axes[1].set_title(r"Area of the hysteresis loop")
label_panels(fig)
plt.show()
Exercise 2: stress at rest with the wrong FENE-P function, and hysteresis without variable drag
===============================================================================================
Stress at rest with f(I) != 1 : 11.1111 Pa (exact 3*G0/(b-3) = 11.1111 Pa)
Trace with f(I) != 1 : tr(C) changed from 3.0000 to 2.7293 (3*b/(b+3) = 2.7273)
With f(I) = 1, max |stress at rest| : 0.000e+00 Pa
Hysteresis area with constant drag : 0.1883 against, with conformation-dependent drag, 18.6369

Figure S6.2. (a) With a spring factor that is not 1 at the trace drifts from 3 to 2.73 with no flow; with the normalized factor it stays at 3. (b) Area between the up and down sweeps of planar extension with constant drag and with drag that grows with extension.
Explanation. The function belongs to the convention in which the equilibrium conformation is . Used with it gives an isotropic stress of Pa at rest, and the trace relaxes from 3 to 2.73, the value of the other convention. With the stress at rest is zero. A constitutive function should be tested for zero stress at equilibrium before it is used in a flow. In the second case the hysteresis loop has an area of 18.6 with the conformation-dependent drag and 0.19 without it: with a constant drag the stretch is a single-valued function of the extension rate.
Exercise 3¶
Problem. Write solve_scurve_all_branches(b_ext=120.0, kappa_drag=4.5) in NumPy to compute all steady states of the model with conformation-dependent drag as the curve , with the fractional extension between 0 and 1. Find the turning points, where , determine which states are stable, and plot the unstable branch together with the result of fenep_planar_extension_hysteresis.
heading("Exercise 3: all steady states of the coil-stretch curve")
def solve_scurve_all_branches(b_ext: float = 120.0, kappa_drag: float = 4.5) -> dict:
"""Parametric steady locus Wi(x) = 1 / [2*(1 - x^2)*(1 + kappa*x^2)] and exact fold turning point."""
x = np.linspace(0.01, 0.992, 600)
wi_locus = 0.5 / ((1.0 - x**2) * (1.0 + kappa_drag * (x**2)))
trC_locus = b_ext * (x**2)
# Derivative d/dx[(1 - x^2)*(1 + k*x^2)] = 2*x*(k - 1 - 2*k*x^2) == 0 -> x_fold^2 = (k - 1)/(2*k):
x_fold = math.sqrt((kappa_drag - 1.0) / (2.0 * kappa_drag)) if kappa_drag > 1.0 else 0.0
wi_fold_min = 0.5 / ((1.0 - x_fold**2) * (1.0 + kappa_drag * (x_fold**2)))
# Jacobian d(dx/dt)/dx at fixed point = 2*Wi - d/dx[x / ((1-x^2)(1+k*x^2))] has sign opposite to dWi/dx:
dwi_dx = np.gradient(wi_locus, x)
is_stable = dwi_dx > 0.0
return {
"x": x,
"wi_locus": wi_locus,
"trC_locus": trC_locus,
"is_stable": is_stable,
"x_fold": x_fold,
"wi_fold_min": wi_fold_min,
"wi_coil_crit": 0.5,
}
sc = solve_scurve_all_branches(b_ext=120.0, kappa_drag=4.5)
wi_ref = np.linspace(0.18, 0.65, 36)
hys_ref = entangled_tubes.fenep_planar_extension_hysteresis(wi_ref, b_ext=120.0, include_conformation_dependent_drag=True)
# Exact analytical lower fold Wi_min = 2 * kappa / (1 + kappa)^2:
wi_min_exact = 2.0 * 4.5 / ((1.0 + 4.5) ** 2)
print(f"Analytical lower stretch->coil fold Wi_min = {sc['wi_fold_min']:.5f} (exact 2k/(1+k)^2 = {wi_min_exact:.5f})")
print(f"Upper coil->stretch threshold Wi_crit = {sc['wi_coil_crit']:.5f}")
# Verify upper stretched branch of fenep_planar_extension_hysteresis tracks stable upper manifold:
upper_mask = (sc["x"] > sc["x_fold"]) & (sc["wi_locus"] >= 0.32) & (sc["wi_locus"] <= 0.65)
tr_interp = np.interp(wi_ref[wi_ref >= 0.34], sc["wi_locus"][upper_mask], sc["trC_locus"][upper_mask])
assert np.isclose(sc["wi_fold_min"], wi_min_exact, rtol=1e-12)
assert np.allclose(hys_ref["trC_down"][wi_ref >= 0.34], tr_interp, rtol=0.04)
fig, ax = plt.subplots(figsize=(7.2, 4.2))
st = sc["is_stable"]
ax.plot(sc["wi_locus"][st & (sc["x"] < sc["x_fold"])], sc["trC_locus"][st & (sc["x"] < sc["x_fold"])], "b-", lw=2.2, label="Analytical stable coil branch")
ax.plot(sc["wi_locus"][~st], sc["trC_locus"][~st], "k:", lw=2.2, label="Analytical unstable saddle branch")
ax.plot(sc["wi_locus"][st & (sc["x"] > sc["x_fold"])], sc["trC_locus"][st & (sc["x"] > sc["x_fold"])], "r-", lw=2.2, label="Analytical stable stretched branch")
ax.plot(hys_ref["wi"], hys_ref["trC_up"], "bo", ms=4, alpha=0.7, label="Continuation up-sweep")
ax.plot(hys_ref["wi"], hys_ref["trC_down"], "rs", ms=4, alpha=0.7, label="Continuation down-sweep")
ax.scatter([sc["wi_fold_min"]], [120.0 * (sc["x_fold"] ** 2)], color="gold", edgecolor="black", s=70, zorder=5, label=f"Saddle-node fold $\\mathrm{{Wi}}_{{\\min}}={wi_min_exact:.3f}$")
ax.set_xlim(0.15, 0.70)
ax.set_xlabel(r"Extensional Weissenberg number $\mathrm{Wi}_{\mathrm{ext}}$")
ax.set_ylabel(r"Conformation trace $\operatorname{tr}\mathbf{C}$")
ax.set_title(r"Steady states in planar extension")
ax.legend(fontsize=8)
plt.show()
Exercise 3: all steady states of the coil-stretch curve
=======================================================
Analytical lower stretch->coil fold Wi_min = 0.29752 (exact 2k/(1+k)^2 = 0.29752)
Upper coil->stretch threshold Wi_crit = 0.50000

Figure S6.3. The three branches of steady states with drag that grows with extension, from the closed form, with the turning point at and the states reached by sweeping the rate up and down.
Explanation. With the fractional extension as the parameter, the steady states are given by one explicit function, , and no root finding is needed. The coiled branch ends at , and the stretched branch ends at the minimum of this function, for . The states between the two turning points, where decreases with , are unstable. Between 0.2975 and 0.5 a coiled state and a stretched state are both stable, and the one that is reached depends on the history of the flow.