Worked solutions to the three exercises of Lecture 5. 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: relaxation times of Rouse and Zimm chains")
N8 = 8
A_rouse = np.zeros((N8, N8), dtype=float)
for i in range(N8):
if i > 0:
A_rouse[i, i] += 1.0; A_rouse[i, i - 1] -= 1.0
if i < N8 - 1:
A_rouse[i, i] += 1.0; A_rouse[i, i + 1] -= 1.0
evals_A = np.sort(np.linalg.eigvalsh(A_rouse))[1:] # Drop p=0 center-of-mass translation mode
tau_from_laplacian = 1.0 / (2.0 * evals_A)
rz8_r = brownian_chains.simulate_rouse_zimm_chain_bd(n_beads=8, h_star=0.0, n_steps=1, n_chains=1, use_hi=False)
rz8_z = brownian_chains.simulate_rouse_zimm_chain_bd(n_beads=8, h_star=0.25, n_steps=1, n_chains=1, use_hi=True)
assert np.allclose(tau_from_laplacian, rz8_r["relaxation_modes"], atol=1e-13)
n_beads_sweep = np.array([6, 10, 16, 24, 36])
tau1_rouse_n, tau1_zimm_n = [], []
for nb in n_beads_sweep:
rr = brownian_chains.simulate_rouse_zimm_chain_bd(n_beads=int(nb), h_star=0.0, n_steps=1, n_chains=1, use_hi=False)
rz = brownian_chains.simulate_rouse_zimm_chain_bd(n_beads=int(nb), h_star=0.25, n_steps=1, n_chains=1, use_hi=True)
tau1_rouse_n.append(float(rr["relaxation_modes"][0]))
tau1_zimm_n.append(float(rz["relaxation_modes"][0]))
exp_rouse = float(np.polyfit(np.log(n_beads_sweep[-3:]), np.log(tau1_rouse_n[-3:]), 1)[0])
exp_zimm = float(np.polyfit(np.log(n_beads_sweep[-3:]), np.log(tau1_zimm_n[-3:]), 1)[0])
print(f"8-bead Laplacian against package Rouse modes max diff: {np.max(np.abs(tau_from_laplacian - rz8_r['relaxation_modes'])):.3e}")
print(f"Exponent of tau_1 ~ N^nu fitted over N = 16, 24, 36 -> Rouse: {exp_rouse:.3f} (limit 2), Zimm: {exp_zimm:.3f} (limit 3/2)")
assert 1.98 < exp_rouse < 2.02
assert 1.45 < exp_zimm < 1.56
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
p_idx = np.arange(1, N8)
axes[0].semilogy(p_idx, rz8_r["relaxation_modes"], "-o", color="#2166AC", lw=2.0, ms=5.5, label="Rouse ($h^*=0$)")
axes[0].semilogy(p_idx, rz8_z["relaxation_modes"], "-s", color="#2E8B57", lw=2.0, ms=5.5, label="Zimm ($h^*=0.25$)")
axes[0].set_xlabel("Normal mode index $p$")
axes[0].set_ylabel(r"Mode relaxation time $\tau_p$")
axes[0].set_title(r"Relaxation times of an 8-bead chain")
axes[0].legend(fontsize=8.5)
axes[1].loglog(n_beads_sweep, tau1_rouse_n, "-o", color="#2166AC", lw=2.1, ms=5.5, label=rf"Rouse $\tau_1 \propto N^{{{exp_rouse:.2f}}}$")
axes[1].loglog(n_beads_sweep, tau1_zimm_n, "-s", color="#2E8B57", lw=2.1, ms=5.5, label=rf"Zimm $\tau_1 \propto N^{{{exp_zimm:.2f}}}$")
axes[1].set_xlabel("Chain length $N$ [beads]")
axes[1].set_ylabel(r"Longest relaxation time $\tau_1(N)$")
axes[1].set_title(r"Longest relaxation time against chain length")
axes[1].legend(fontsize=8.5)
log_ticks(axes[1], "x", [6, 10, 16, 24, 36])
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Check by sampling Gaussian chains (35 000 chains for each ) with beads that , and , which tends to 6 for long chains.
heading("Exercise 1: end-to-end distance and radius of gyration of Gaussian chains")
rng_g = np.random.default_rng(501)
n_vals_g = np.array([4, 8, 16, 32, 64])
ree2_emp, rg2_emp, ratio_emp = [], [], []
for nb in n_vals_g:
bonds = rng_g.normal(0.0, 1.0, size=(35000, int(nb) - 1, 3))
pos = np.zeros((35000, int(nb), 3), dtype=float)
pos[:, 1:, :] = np.cumsum(bonds, axis=1)
pos -= np.mean(pos, axis=1, keepdims=True)
ree = float(np.mean(np.sum((pos[:, -1, :] - pos[:, 0, :]) ** 2, axis=1)))
rg = float(np.mean(np.sum(pos**2, axis=(1, 2)) / nb))
ree2_emp.append(ree)
rg2_emp.append(rg)
ratio_emp.append(ree / rg)
ree2_ex = 3.0 * (n_vals_g - 1.0)
rg2_ex = (n_vals_g**2 - 1.0) / (2.0 * n_vals_g)
ratio_ex = 6.0 * n_vals_g / (n_vals_g + 1.0)
max_rel_err = float(np.max(np.abs(np.array(ratio_emp) - ratio_ex) / ratio_ex))
print(f"Max relative error on <Ree^2>/<Rg^2> across N in [4, 64]: {max_rel_err:.4f}")
print(f"N=4 ratio = {ratio_emp[0]:.3f} (exact 4.800) -> N=64 ratio = {ratio_emp[-1]:.3f} (exact {ratio_ex[-1]:.3f} -> 6.0)")
assert max_rel_err < 1.5e-2
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
axes[0].loglog(n_vals_g, ree2_ex, "-k", lw=2.0, label=r"Exact $\langle R_{ee}^2\rangle = 3(N-1)$")
axes[0].loglog(n_vals_g, ree2_emp, "o", color="#2166AC", ms=5.5, label="Monte Carlo $\\langle R_{ee}^2\\rangle$")
axes[0].loglog(n_vals_g, rg2_ex, "--k", lw=2.0, label=r"Exact $\langle R_g^2\rangle = (N^2-1)/(2N)$")
axes[0].loglog(n_vals_g, rg2_emp, "s", color="#2E8B57", ms=5.5, label="Monte Carlo $\\langle R_g^2\\rangle$")
axes[0].set_xlabel("Bead count $N$")
axes[0].set_ylabel("Mean-square size")
axes[0].set_title(r"Mean-square end-to-end distance and radius of gyration")
axes[0].legend(fontsize=8)
axes[1].semilogx(n_vals_g, ratio_ex, "-k", lw=2.0, label=r"Exact $6N / (N + 1)$")
axes[1].semilogx(n_vals_g, ratio_emp, "o", color="#C0392B", ms=6, label="Monte Carlo ratio")
axes[1].axhline(6.0, color="gray", ls=":", label="Limit 6")
axes[1].set_xlabel("Bead count $N$")
axes[1].set_ylabel(r"Ratio $\langle R_{ee}^2\rangle / \langle R_g^2\rangle$")
axes[1].set_title(r"Their ratio")
axes[1].legend(fontsize=8.5)
log_ticks(axes[0], "x", [4, 8, 16, 32, 64])
log_ticks(axes[1], "x", [4, 8, 16, 32, 64])
label_panels(fig)
plt.show()
Exercise 1: end-to-end distance and radius of gyration of Gaussian chains
=========================================================================
Max relative error on <Ree^2>/<Rg^2> across N in [4, 64]: 0.0047
N=4 ratio = 4.799 (exact 4.800) -> N=64 ratio = 5.922 (exact 5.908 -> 6.0)

Figure S5.1. Gaussian chains of beads sampled directly. (a) and . (b) Their ratio , which tends to 6.
Explanation. For independent Gaussian steps , and the double sum is the mean-square radius of gyration. The sampled ratio differs from by at most 0.5 %: 4.799 against 4.800 for and 5.922 against 5.908 for . These are equilibrium averages, which depend on the spring potential alone; hydrodynamic interaction changes the dynamics and leaves them unchanged.
Exercise 2¶
Problem. Compare the Oseen mobility (oseen_unsafe=True) with the Rotne–Prager–Yamakawa mobility (oseen_unsafe=False) for three beads of radius at the corners of an equilateral triangle of side , , for between 0.20 and 2.50. Count the failures of the Cholesky factorization and plot the smallest eigenvalue against .
heading("Exercise 2: Cholesky factorization of the Oseen and Rotne-Prager-Yamakawa mobilities")
base_tri = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.5, math.sqrt(3.0) / 2.0, 0.0]])
s_vals = np.linspace(0.20, 2.50, 47)
chol_ok_rpy, chol_ok_oseen = [], []
eig_min_r3, eig_min_o3 = [], []
for sv in s_vals:
pts = float(sv) * base_tri
Dr = brownian_chains.rpy_mobility_tensor(pts, bead_radius_a=1.0, oseen_unsafe=False)
Do = brownian_chains.rpy_mobility_tensor(pts, bead_radius_a=1.0, oseen_unsafe=True)
eig_min_r3.append(float(np.min(np.linalg.eigvalsh(Dr))))
eig_min_o3.append(float(np.min(np.linalg.eigvalsh(Do))))
try:
L_r = np.linalg.cholesky(Dr)
assert np.allclose(L_r @ L_r.T, Dr, atol=1e-13)
chol_ok_rpy.append(1)
except np.linalg.LinAlgError:
chol_ok_rpy.append(0)
try:
np.linalg.cholesky(Do)
chol_ok_oseen.append(1)
except np.linalg.LinAlgError:
chol_ok_oseen.append(0)
n_fail_oseen = len(chol_ok_oseen) - sum(chol_ok_oseen)
n_fail_rpy = len(chol_ok_rpy) - sum(chol_ok_rpy)
first_ok_s = float(s_vals[chol_ok_oseen.index(1)])
print(f"Cholesky factorization fails at: Oseen {n_fail_oseen}/47 spacings | RPY {n_fail_rpy}/47 spacings")
print(f"3-bead equilateral Oseen requires s >= {first_ok_s:.2f}a for a positive definite mobility (two beads: 1.5a).")
assert n_fail_rpy == 0
assert n_fail_oseen >= 25
assert 1.75 <= first_ok_s <= 2.05
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
axes[0].plot(s_vals, eig_min_r3, "-", color="#2E8B57", lw=2.2, label="RPY $\\lambda_{\\min}(\\mathbf{D}) > 0$")
axes[0].plot(s_vals, np.clip(eig_min_o3, -0.15, 0.08), "--", color="#C0392B", lw=2.0, label="Oseen $\\lambda_{\\min}(\\mathbf{D})$")
axes[0].axhline(0.0, color="k", lw=1.0)
axes[0].set_xlabel("Inter-bead spacing $s / a$")
axes[0].set_ylabel(r"Minimum mobility eigenvalue $\lambda_{\min}$")
axes[0].set_title(r"Smallest eigenvalue of the three-bead mobility")
axes[0].legend(fontsize=8)
axes[1].step(s_vals, chol_ok_rpy, where="mid", color="#2E8B57", lw=2.4, label="RPY: factorization succeeds")
axes[1].step(s_vals, chol_ok_oseen, where="mid", ls="--", color="#C0392B", lw=2.0, label="Oseen: factorization fails")
axes[1].set_yticks([0, 1], ["fails", "succeeds"])
axes[1].set_xlabel("Inter-bead spacing $s / a$")
axes[1].set_title(r"Outcome of the Cholesky factorization")
axes[1].legend(fontsize=8, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=1)
label_panels(fig)
plt.show()
Exercise 2: Cholesky factorization of the Oseen and Rotne-Prager-Yamakawa mobilities
====================================================================================
Cholesky factorization fails at: Oseen 34/47 spacings | RPY 0/47 spacings
3-bead equilateral Oseen requires s >= 1.90a for a positive definite mobility (two beads: 1.5a).

Figure S5.2. Three beads on an equilateral triangle of side . (a) Smallest eigenvalue of the mobility matrix (Oseen values clipped at -0.15). (b) Whether the Cholesky factorization succeeds: the Oseen matrix fails below , the Rotne–Prager–Yamakawa matrix never.
Explanation. The Cholesky factorization of the Oseen mobility fails at 34 of the 47 spacings, and that of the Rotne–Prager–Yamakawa mobility at none. For three beads the Oseen mobility is positive definite only for , a larger distance than the limit for two beads. In a simulation of a chain without excluded volume, beads often come closer than this (with the bead radius is in units of the spring length), and a simulation with the Oseen mobility stops at the first such configuration. The Rotne–Prager–Yamakawa form for accounts for the overlap of the two spheres and is positive definite at all distances.
Exercise 3¶
Problem. Write a Brownian dynamics integrator in NumPy for chains with Rotne–Prager–Yamakawa hydrodynamic interaction that generates the correlated random displacements with a Cholesky factor of the diffusion matrix (np.linalg.cholesky). Use 6-bead chains with , and , and compare and the shear stress with brownian_chains.simulate_rouse_zimm_chain_bd.
heading("Exercise 3: a chain integrator with a Cholesky factor of the diffusion matrix")
nb_3, hs_3, sr_3, dt_3, n_steps_3, n_ch_3 = 6, 0.24, 1.0, 0.015, 60, 18
a_3 = hs_3 * math.sqrt(math.pi)
eta_3 = 1.0 / (6.0 * math.pi * a_3)
rng_3 = np.random.default_rng(88)
st0 = rng_3.normal(0.0, 1.0, size=(n_ch_3, nb_3 - 1, 3))
chains_chol = np.zeros((n_ch_3, nb_3, 3), dtype=float)
chains_chol[:, 1:, :] = np.cumsum(st0, axis=1)
chains_chol -= np.mean(chains_chol, axis=1, keepdims=True)
stress_acc = 0.0
n_stat_3 = n_steps_3 // 2
chol_calls = 0
for st_i in range(n_steps_3):
for c_i in range(n_ch_3):
R_c = chains_chol[c_i]
diff = R_c[1:] - R_c[:-1]
Fb = np.zeros_like(R_c)
Fb[:-1] += diff
Fb[1:] -= diff
if st_i >= n_steps_3 - n_stat_3:
stress_acc += float(np.sum(diff[:, 0] * diff[:, 1]))
vf = np.zeros_like(R_c)
vf[:, 0] = sr_3 * R_c[:, 1]
D_m = brownian_chains.rpy_mobility_tensor(R_c, bead_radius_a=a_3, eta_s=eta_3, oseen_unsafe=False)
# Strict Cholesky factorization D = L_c @ L_c.T (faster O(n^3/3) than eigendecomposition):
L_c = np.linalg.cholesky(D_m)
chol_calls += 1
dW = rng_3.normal(0.0, math.sqrt(2.0 * dt_3), size=3 * nb_3)
disp = (D_m @ Fb.ravel()) * dt_3 + L_c @ dW
Rn = R_c + vf * dt_3 + disp.reshape(nb_3, 3)
chains_chol[c_i] = Rn - np.mean(Rn, axis=0, keepdims=True)
rg2_chol = float(np.mean(np.sum(chains_chol**2, axis=(1, 2)) / nb_3))
txy_chol = stress_acc / (n_ch_3 * n_stat_3)
pkg_rz3 = brownian_chains.simulate_rouse_zimm_chain_bd(
n_beads=nb_3, h_star=hs_3, shear_rate=sr_3, n_steps=n_steps_3, dt=dt_3, n_chains=n_ch_3, use_hi=True, seed=88
)
# Note: L_chol @ dW vs V @ sqrt(Lambda) @ V^T @ dW are two distinct matrix square roots (L L^T == B B^T == D),
# so both generate the same multivariate Gaussian law N(0, 2*dt*D)
rel_rg = abs(rg2_chol - pkg_rz3["rg2_mean"]) / pkg_rz3["rg2_mean"]
rel_tx = abs(txy_chol - pkg_rz3["intrinsic_stress_xy"]) / pkg_rz3["intrinsic_stress_xy"]
print(f"Completed {chol_calls:,d} Cholesky factorizations without failure")
print(f"<Rg^2>: Cholesky={rg2_chol:.3f} against eigh={pkg_rz3['rg2_mean']:.3f} (rel diff={rel_rg:.3f})")
print(f"tau_xy: Cholesky={txy_chol:.3f} against eigh={pkg_rz3['intrinsic_stress_xy']:.3f} (rel diff={rel_tx:.3f})")
assert chol_calls == n_steps_3 * n_ch_3
assert rel_rg < 0.22 and rel_tx < 0.28
# Verify exact covariance identity L_c @ L_c.T == V @ Lambda @ V.T on final configuration:
D_last = brownian_chains.rpy_mobility_tensor(chains_chol[0], bead_radius_a=a_3, eta_s=eta_3)
Lc_last = np.linalg.cholesky(D_last)
ev_l, V_l = np.linalg.eigh(D_last)
B_sym = (V_l * np.sqrt(ev_l)[None, :]) @ V_l.T
cov_err = float(np.linalg.norm(Lc_last @ Lc_last.T - B_sym @ B_sym.T, ord="fro"))
assert cov_err < 1e-12
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
axes[0].imshow(D_last, cmap="viridis")
axes[0].set_title(r"Mobility matrix of a 6-bead chain")
axes[0].set_xlabel("3N coordinate index")
axes[0].set_ylabel("3N coordinate index")
axes[1].bar(["Cholesky factor", "Symmetric square root"], [txy_chol, pkg_rz3["intrinsic_stress_xy"]], color=["#2166AC", "#2E8B57"], width=0.45)
axes[1].set_ylabel(r"Shear stress $\tau_{xy}$")
axes[1].set_title(r"Shear stress with two matrix square roots")
label_panels(fig)
plt.show()
Exercise 3: a chain integrator with a Cholesky factor of the diffusion matrix
=============================================================================
Completed 1,080 Cholesky factorizations without failure
<Rg^2>: Cholesky=3.497 against eigh=3.517 (rel diff=0.006)
tau_xy: Cholesky=1.243 against eigh=1.304 (rel diff=0.047)

Figure S5.3. (a) The Rotne–Prager–Yamakawa mobility matrix of the last configuration. (b) Shear stress from runs that take the Cholesky factor and the symmetric square root of the mobility; the 5 % difference is statistical.
Explanation. Any matrix with gives random displacements with the required covariance, so the Cholesky factor used here and the symmetric square root that the package computes with eigh are equivalent, and the Cholesky factor is cheaper to compute. All 1080 factorizations succeed. The two integrators agree to 0.6 % in (3.497 against 3.517) and to 4.7 % in the shear stress (1.243 against 1.304); they use different random numbers, so differences of this size are expected from the statistical error. Lecture 6 compares simulations of this kind with the FENE-P and FENE-CR closures.