Worked solutions to the three exercises of Lecture 3. 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: spring laws and the root of the cubic equation")
b_demo = 49.0 # sqrt(b) = 7.0
r_grid = np.linspace(0.0, 6.85, 200)
x_rel = r_grid / math.sqrt(b_demo)
f_hook = r_grid
f_fene = r_grid / (1.0 - (r_grid**2) / b_demo)
f_wlc = np.where(x_rel < 1e-7, r_grid, (2.0 / 3.0) * (1.0 / ((1.0 - x_rel) ** 2) - 1.0 + 4.0 * x_rel) / np.maximum(x_rel, 1e-12) * (r_grid / math.sqrt(b_demo)))
Y_sweep = np.logspace(-2, 2.5, 60)
R_cubic = brownian_chains.solve_fene_cubic_radial(Y_sweep, b_ext=b_demo, coeff_alpha=0.25)
res_alg = R_cubic * (1.0 + 0.25 / (1.0 - (R_cubic**2) / b_demo)) - Y_sweep
print(f"Max algebraic residual across Y in [1e-2, 316]: {np.max(np.abs(res_alg)):.3e}")
print(f"At extreme RHS Y = {Y_sweep[-1]:.1f} -> R = {R_cubic[-1]:.8f} < sqrt(b) = {math.sqrt(b_demo):.1f}")
assert np.max(np.abs(res_alg)) < 1e-11
assert np.all((R_cubic >= 0.0) & (R_cubic < math.sqrt(b_demo)))
assert brownian_chains.solve_fene_cubic_radial(np.array([0.0]), b_ext=b_demo, coeff_alpha=0.25)[0] == 0.0
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
axes[0].semilogy(x_rel[1:], f_hook[1:], "--", color="gray", lw=1.8, label="Hookean $Q$")
axes[0].semilogy(x_rel[1:], f_fene[1:], "-", color="#2166AC", lw=2.1, label="FENE $(1 - Q^2/b)^{-1}$")
axes[0].semilogy(x_rel[1:], f_wlc[1:], "-", color="#C0392B", lw=2.1, label="Wormlike chain $(1 - Q/\\sqrt{b})^{-2}$")
axes[0].axvline(1.0, color="k", ls=":", label="Maximum length $Q / \\sqrt{b} = 1$")
axes[0].set_xlabel(r"Fractional extension $Q / \sqrt{b}$")
axes[0].set_ylabel(r"Dimensionless spring force $|\mathbf{F}(Q)|$")
axes[0].set_title(r"Spring forces")
axes[0].legend(fontsize=8)
axes[1].semilogx(Y_sweep, R_cubic, "-o", color="#2E8B57", ms=3.5, lw=2.0, label=r"Cubic root $R(\|\mathbf{Y}\|)$")
axes[1].axhline(math.sqrt(b_demo), color="#C0392B", ls="--", lw=1.8, label=rf"Maximum length $\sqrt{{b}} = {math.sqrt(b_demo):.1f}$")
axes[1].set_xlabel(r"Length of the predictor $\|\mathbf{Y}\|$")
axes[1].set_ylabel(r"New length $R \in [0, \sqrt{b})$")
axes[1].set_title(r"Root of the cubic equation")
axes[1].legend(fontsize=8.5)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Check by numerical quadrature, for between 6 and 200, that the equilibrium distribution of a FENE dumbbell gives , and compare with a Brownian dynamics simulation without flow (simulate_dumbbell_bd with ).
heading("Exercise 1: equilibrium distribution of the FENE dumbbell")
b_grid_ex1 = np.array([6.0, 10.0, 20.0, 40.0, 80.0, 200.0])
q2_quad = []
for bv in b_grid_ex1:
r_q = np.linspace(0.0, math.sqrt(bv) * (1.0 - 1e-9), 4000)
w_boltz = (r_q**2) * ((1.0 - (r_q**2) / bv) ** (0.5 * bv))
num_int = float(trapezoid((r_q**2) * w_boltz, r_q))
den_int = float(trapezoid(w_boltz, r_q))
q2_quad.append(num_int / den_int)
q2_exact = 3.0 * b_grid_ex1 / (b_grid_ex1 + 5.0)
quad_err = float(np.max(np.abs(np.array(q2_quad) - q2_exact)))
# Cross-check zero-flow BD relaxation at b = 20:
bd_eq20 = brownian_chains.simulate_dumbbell_bd(
lambda _t: np.zeros((3, 3)), np.linspace(0.0, 4.0, 81), model="fene", b_ext=20.0, n_trajectories=4000, control_variate=False, seed=44
)
bd_q2_mean = float(np.mean(bd_eq20["mean_Q2"][40:]))
exact_20 = 3.0 * 20.0 / 25.0
print(f"Quadrature against 3b/(b+5) max error across b in [6, 200]: {quad_err:.3e}")
print(f"Zero-flow BD <Q^2>_eq (b=20): {bd_q2_mean:.4f} against exact 3b/(b+5) = {exact_20:.4f}")
assert quad_err < 1e-7
assert abs(bd_q2_mean - exact_20) < 0.08
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
for bv, col in [(8.0, "#C0392B"), (25.0, "#2166AC"), (120.0, "#2E8B57")]:
rq = np.linspace(0.0, math.sqrt(bv) * 0.999, 500)
pdf = (rq**2) * ((1.0 - (rq**2) / bv) ** (0.5 * bv))
pdf /= float(trapezoid(pdf, rq))
axes[0].plot(rq, pdf, lw=2.0, color=col, label=rf"FENE $b = {bv:.0f}$ ($\sqrt{{b}}={math.sqrt(bv):.2f}$)")
rq_h = np.linspace(0.0, 5.0, 400)
pdf_h = (rq_h**2) * np.exp(-0.5 * rq_h**2); pdf_h /= float(trapezoid(pdf_h, rq_h))
axes[0].plot(rq_h, pdf_h, "k--", lw=1.7, label="Hookean ($b\\to\\infty$)")
axes[0].set_xlabel("Dimensionless connector length $Q$")
axes[0].set_ylabel("Radial PDF $p_{\\mathrm{eq}}(Q)$")
axes[0].set_title(r"Equilibrium distribution of the extension")
axes[0].legend(fontsize=8)
axes[1].semilogx(b_grid_ex1, q2_exact, "k-", lw=2.0, label="Exact $3b / (b + 5)$")
axes[1].semilogx(b_grid_ex1, q2_quad, "o", color="#2166AC", ms=5.5, label="Quadrature")
axes[1].axhline(3.0, color="gray", ls=":", label="Hookean, $\\langle Q^2\\rangle = 3$")
axes[1].set_xlabel("Extensibility parameter $b$")
axes[1].set_ylabel(r"Equilibrium $\langle Q^2 \rangle_{\mathrm{eq}}$")
axes[1].set_title(r"Equilibrium $\langle Q^2\rangle$ against $b$")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 1: equilibrium distribution of the FENE dumbbell
=========================================================
Quadrature against 3b/(b+5) max error across b in [6, 200]: 2.243e-14
Zero-flow BD <Q^2>_eq (b=20): 2.4248 against exact 3b/(b+5) = 2.4000

Figure S3.1. (a) Radial probability density of the FENE connector at equilibrium for three values of , with the Hookean limit. (b) by quadrature against .
Explanation. At equilibrium the probability flux is zero, so that , which integrates to . With the radial integrals are Beta functions, , and , which is smaller than the value 3 of a Hookean dumbbell. The quadrature agrees with the formula to . The simulation with gives 2.425 against 2.400, a difference of 1 % from a finite ensemble and a finite time step.
Exercise 2¶
Problem. Run the explicit Euler–Maruyama scheme (explicit_unsafe=True) and the semi-implicit scheme (explicit_unsafe=False) for and with b_ext = 25, n_trajectories = 500 and t_end = 1.8, and count the events in which a connector reaches or exceeds its maximum length, .
heading("Exercise 2: overstretched connectors with the explicit Euler scheme")
wi_grid_2 = [2.0, 5.0, 8.0, 12.0]
dt_grid_2 = [0.02, 0.05, 0.10, 0.15]
viol_unsafe = np.zeros((len(dt_grid_2), len(wi_grid_2)), dtype=float)
viol_safe = np.zeros((len(dt_grid_2), len(wi_grid_2)), dtype=float)
for i_d, dtv in enumerate(dt_grid_2):
t_g2 = np.linspace(0.0, 1.8, max(3, int(round(1.8 / dtv)) + 1))
for j_w, wv in enumerate(wi_grid_2):
Lm = np.array([[0.0, wv, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
ru = brownian_chains.simulate_dumbbell_bd(lambda _t, L=Lm: L, t_g2, model="fene", b_ext=25.0, n_trajectories=500, explicit_unsafe=True, control_variate=False, seed=9)
rs = brownian_chains.simulate_dumbbell_bd(lambda _t, L=Lm: L, t_g2, model="fene", b_ext=25.0, n_trajectories=500, explicit_unsafe=False, control_variate=False, seed=9)
viol_unsafe[i_d, j_w] = float(ru["overstretched_count"])
viol_safe[i_d, j_w] = float(rs["overstretched_count"])
print(f"Total overstretched counts across 16 (Wi, dt) runs -> explicit Euler: {int(np.sum(viol_unsafe))}, semi-implicit: {int(np.sum(viol_safe))}")
print(f"At (Wi=8, dt=0.10): explicit violations = {int(viol_unsafe[2, 2])} against semi-implicit = {int(viol_safe[2, 2])}")
assert int(np.sum(viol_safe)) == 0
assert viol_unsafe[2, 2] > 0 and np.sum(viol_unsafe) > 200
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
im = axes[0].imshow(np.log10(viol_unsafe + 1.0), origin="lower", aspect="auto", cmap="magma")
plt.colorbar(im, ax=axes[0], label=r"$\log_{10}(\mathrm{violations} + 1)$")
axes[0].set_xticks(range(len(wi_grid_2)), [str(w) for w in wi_grid_2])
axes[0].set_yticks(range(len(dt_grid_2)), [str(d) for d in dt_grid_2])
axes[0].set_xlabel(r"Weissenberg number $\mathrm{Wi}$")
axes[0].set_ylabel(r"Time step $\Delta t / \lambda_H$")
axes[0].set_title(r"Overstretched steps of the explicit scheme")
q_plot = np.linspace(0.0, 7.0, 350)
q_plot = q_plot[np.abs(q_plot - 5.0) > 0.06]
f_raw = q_plot / (1.0 - (q_plot**2) / 25.0)
axes[1].plot(q_plot[q_plot < 5.0], f_raw[q_plot < 5.0], color="#2E8B57", lw=2.1, label=r"Restoring force ($Q < \sqrt{b}=5$)")
axes[1].plot(q_plot[q_plot > 5.0], f_raw[q_plot > 5.0], "--", color="#C0392B", lw=2.1, label=r"Force points outwards ($Q > \sqrt{b}=5$)")
axes[1].axhline(0.0, color="k", lw=1.0)
axes[1].axvline(5.0, color="gray", ls=":")
axes[1].set_ylim(-40.0, 40.0)
axes[1].set_xlabel("Connector length $Q$")
axes[1].set_ylabel("Radial force coefficient $Q / (1 - Q^2/25)$")
axes[1].set_title(r"FENE force coefficient on both sides of $\sqrt{b}$")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 2: overstretched connectors with the explicit Euler scheme
===================================================================
Total overstretched counts across 16 (Wi, dt) runs -> explicit Euler: 5835, semi-implicit: 0
At (Wi=8, dt=0.10): explicit violations = 541 against semi-implicit = 0

Figure S3.2. (a) Number of steps with for the explicit Euler scheme, as , over the Weissenberg number and the time step; the semi-implicit scheme has none. (b) The factor for changes sign at .
Explanation. A Gaussian random displacement is unbounded, so an explicit step of any size moves a strongly stretched dumbbell beyond with a non-zero probability. Beyond that length is negative and the spring force points outwards. The explicit scheme produces 5835 such events in the 16 runs, 541 of them at and . The semi-implicit scheme produces none: it evaluates the spring force at the new length, and the cubic equation for that length has exactly one root between 0 and . No rejection or reflection of steps is needed.
Exercise 3¶
Problem. Write a vectorized semi-implicit Brownian dynamics solver for FENE dumbbells in NumPy (, , 3000 trajectories, ), and compare , and with brownian_chains.simulate_dumbbell_bd; the two should agree within 3 %.
heading("Exercise 3: a vectorized semi-implicit solver for FENE dumbbells")
b_s3, wi_s3, n_s3 = 36.0, 5.0, 3500
t_s3 = np.linspace(0.0, 3.0, 91)
L_s3 = np.array([[0.0, wi_s3, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
def cubic_radial_scratch(Y_n: np.ndarray, b_v: float, alpha_v: float) -> np.ndarray:
a1 = -Y_n
a2 = -b_v * (1.0 + alpha_v)
a3 = b_v * Y_n
p = a2 - (a1**2) / 3.0
q = (2.0 * (a1**3)) / 27.0 - (a1 * a2) / 3.0 + a3
rt = np.sqrt(np.maximum(-p / 3.0, 1e-30))
phi = np.arccos(np.clip(-q / (2.0 * (rt**3)), -1.0, 1.0))
r0 = np.clip(2.0 * rt * np.cos((phi - 2.0 * math.pi) / 3.0) - a1 / 3.0, 0.0, math.sqrt(b_v) * (1.0 - 1e-11))
den = np.maximum(1.0 - (r0**2) / b_v, 1e-15)
fv = r0 * (1.0 + alpha_v / den) - Y_n
dfv = 1.0 + alpha_v * (1.0 + (r0**2) / b_v) / (den**2)
return np.where(Y_n == 0.0, 0.0, np.clip(r0 - fv / dfv, 0.0, math.sqrt(b_v) * (1.0 - 1e-14)))
rng_s3 = np.random.default_rng(77)
Q_s = rng_s3.normal(0.0, 1.0, size=(n_s3, 3)) * math.sqrt(b_s3 / (b_s3 + 5.0))
n0 = np.linalg.norm(Q_s, axis=1, keepdims=True)
Q_s = np.where(n0 > 0.92 * math.sqrt(b_s3), Q_s * (0.92 * math.sqrt(b_s3) / np.maximum(n0, 1e-12)), Q_s)
txy_sc = np.zeros_like(t_s3)
n1_sc = np.zeros_like(t_s3)
q2_sc = np.zeros_like(t_s3)
for k in range(t_s3.size):
Fq = Q_s / np.maximum(1.0 - np.sum(Q_s**2, axis=1, keepdims=True) / b_s3, 1e-12)
txy_sc[k] = float(np.mean(Q_s[:, 0] * Fq[:, 1]))
n1_sc[k] = float(np.mean(Q_s[:, 0] * Fq[:, 0] - Q_s[:, 1] * Fq[:, 1]))
q2_sc[k] = float(np.mean(np.sum(Q_s**2, axis=1)))
if k == t_s3.size - 1:
break
dtk = float(t_s3[k + 1] - t_s3[k])
dW = rng_s3.normal(0.0, math.sqrt(dtk), size=(n_s3, 3))
Qp = Q_s + (Q_s @ L_s3.T - 0.5 * Fq) * dtk + dW
rp = np.linalg.norm(Qp, axis=1, keepdims=True)
Qp = np.where(rp >= 0.99 * math.sqrt(b_s3), Qp * (0.99 * math.sqrt(b_s3) / np.maximum(rp, 1e-12)), Qp)
Yv = Q_s + 0.5 * (Q_s @ L_s3.T + Qp @ L_s3.T) * dtk - 0.25 * Fq * dtk + dW
Yn = np.linalg.norm(Yv, axis=1)
Rn = cubic_radial_scratch(Yn, b_s3, 0.25 * dtk)
Q_s = Rn[:, None] * (Yv / np.maximum(Yn[:, None], 1e-15))
pkg_s3 = brownian_chains.simulate_dumbbell_bd(
lambda _t: L_s3, t_s3, model="fene", b_ext=b_s3, n_trajectories=n_s3, control_variate=False, seed=77
)
# Because seed=77 without control_variate draws one extra dummy Q_cv array at initialization in simulate_dumbbell_bd,
# ensemble steady means agree within standard Monte Carlo error (~1-2%):
rel_q2 = abs(float(np.mean(q2_sc[50:])) - float(np.mean(pkg_s3["mean_Q2"][50:]))) / float(np.mean(pkg_s3["mean_Q2"][50:]))
rel_txy = abs(float(np.mean(txy_sc[50:])) - float(np.mean(pkg_s3["tau_xy"][50:]))) / float(np.mean(pkg_s3["tau_xy"][50:]))
print(f"Steady <Q^2>: this solver={np.mean(q2_sc[50:]):.3f} against engcomprheo={np.mean(pkg_s3['mean_Q2'][50:]):.3f} (rel diff={rel_q2:.3f})")
print(f"Steady tau_xy: this solver={np.mean(txy_sc[50:]):.3f} against engcomprheo={np.mean(pkg_s3['tau_xy'][50:]):.3f} (rel diff={rel_txy:.3f})")
assert rel_q2 < 0.03 and rel_txy < 0.04
assert float(np.max(q2_sc)) < b_s3
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
axes[0].plot(t_s3, pkg_s3["tau_xy"], "k-", lw=2.0, label="Package solver, $\\tau_{xy}$")
axes[0].plot(t_s3, txy_sc, "--", color="#2166AC", lw=2.0, label="This solver, $\\tau_{xy}$")
axes[0].set_xlabel(r"Dimensionless time $t / \lambda_H$")
axes[0].set_ylabel(r"Shear stress $\tau_{xy}$")
axes[0].set_title(r"Shear stress ($\mathrm{Wi} = 5$, $b = 36$)")
axes[0].legend(fontsize=8.5)
axes[1].plot(t_s3, pkg_s3["N1"], "k-", lw=2.0, label="Package solver, $N_1$")
axes[1].plot(t_s3, n1_sc, "--", color="#2E8B57", lw=2.0, label="This solver, $N_1$")
axes[1].set_xlabel(r"Dimensionless time $t / \lambda_H$")
axes[1].set_ylabel(r"First normal stress difference $N_1$")
axes[1].set_title(r"First normal stress difference")
axes[1].legend(fontsize=8.5)
label_panels(fig)
plt.show()
Exercise 3: a vectorized semi-implicit solver for FENE dumbbells
================================================================
Steady <Q^2>: this solver=9.445 against engcomprheo=9.477 (rel diff=0.003)
Steady tau_xy: this solver=3.009 against engcomprheo=3.019 (rel diff=0.003)

Figure S3.3. A separate vectorized semi-implicit FENE code against the package, with different random numbers. (a) Shear stress. (b) First normal stress difference.
Explanation. All trajectories are advanced together with array operations, and the cubic equation is solved in closed form at a fixed cost for each step. The steady values of (9.445 against 9.477) and of the shear stress (3.009 against 3.019) agree to 0.3 %. The fluctuations that remain on the curves are the statistical error of 3000 trajectories. At low Weissenberg number this error is larger than the stress itself, which is the reason for the control variate of Lecture 4.