Worked solutions to the three exercises of Lecture 4. 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: shear stress with and without the control variate at Wi = 0.08")
t_cv = np.linspace(0.0, 3.0, 61)
wi_low = 0.08
L_low = np.array([[0.0, wi_low, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
bd_raw = brownian_chains.simulate_dumbbell_bd(
lambda _t: L_low, t_cv, model="fene", b_ext=40.0, n_trajectories=1500, control_variate=False, seed=12
)
bd_cv = brownian_chains.simulate_dumbbell_bd(
lambda _t: L_low, t_cv, model="fene", b_ext=40.0, n_trajectories=1500, control_variate=True, seed=12
)
vrf_achieved = bd_cv["variance_reduction_factor"]
mean_se_raw = float(np.mean(bd_raw["std_err_tau_xy"][1:]))
mean_se_cv = float(np.mean(bd_cv["std_err_tau_xy"][1:]))
print("FENE (b=40, Wi=0.08, N_tr=1500):")
print(f" Without control variate mean std error : {mean_se_raw:.4e} (noise ~ {mean_se_raw/wi_low*100:.1f}% of signal)")
print(f" Control-variate mean std error : {mean_se_cv:.4e}")
print(f" Achieved variance reduction factor : {vrf_achieved:.1f}x (equivalent to {int(1500*vrf_achieved):,d} raw trajectories)")
assert vrf_achieved > 15.0
assert mean_se_cv < 0.25 * mean_se_raw
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
axes[0].plot(t_cv, bd_raw["tau_xy"], color="#A9C9E8", lw=1.5, label="Without control variate")
axes[0].fill_between(t_cv, bd_raw["tau_xy"] - 1.96 * bd_raw["std_err_tau_xy"], bd_raw["tau_xy"] + 1.96 * bd_raw["std_err_tau_xy"], color="#2166AC", alpha=0.15, label="95 % interval, without control variate")
axes[0].plot(t_cv, bd_cv["tau_xy"], color="#C0392B", lw=2.2, label=rf"With control variate (VRF = {vrf_achieved:.1f}x)")
axes[0].plot(t_cv, (40.0 / 45.0) * wi_low * (1.0 - np.exp(-t_cv)), "k--", lw=1.4, label="Linear estimate")
axes[0].set_xlabel(r"Dimensionless time $t / \lambda_H$")
axes[0].set_ylabel(r"Shear stress $\tau_{xy}(t)$")
axes[0].set_title(r"Shear stress at $\mathrm{Wi} = 0.08$")
axes[0].legend(fontsize=8)
axes[1].semilogy(t_cv[1:], bd_raw["std_err_tau_xy"][1:], "--", color="#2166AC", lw=1.9, label="Without control variate")
axes[1].semilogy(t_cv[1:], bd_cv["std_err_tau_xy"][1:], "-", color="#C0392B", lw=2.1, label="With control variate")
axes[1].set_xlabel(r"Dimensionless time $t / \lambda_H$")
axes[1].set_ylabel(r"Standard error $\mathrm{SE}(\tau_{xy})$")
axes[1].set_title(r"Standard error")
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 radial quadrature that for a FENE dumbbell with , although is smaller than 3, the mean equals 3 (that is, ), so that the Kramers expression gives zero polymer stress at rest. Repeat for other values of .
heading("Exercise 1: the equilibrium mean of Q.F for the FENE spring")
b_vals_eq = np.array([8.0, 15.0, 30.0, 60.0, 120.0])
q2_means, qf_means = [], []
for bv in b_vals_eq:
rq = np.linspace(0.0, math.sqrt(bv) * (1.0 - 1e-8), 5000)
# U(r) = -(b/2)*ln(1 - r^2/b) -> exp(-U) = (1 - r^2/b)^(b/2), F(r) = r / (1 - r^2/b)
boltz = (rq**2) * ((1.0 - (rq**2) / bv) ** (0.5 * bv))
z_norm = float(trapezoid(boltz, rq))
q2_m = float(trapezoid((rq**2) * boltz, rq)) / z_norm
qf_m = float(trapezoid((rq**2 / (1.0 - (rq**2) / bv)) * boltz, rq)) / z_norm
q2_means.append(q2_m)
qf_means.append(qf_m)
max_virial_err = float(np.max(np.abs(np.array(qf_means) - 3.0)))
print(f"At b = 15: <Q^2>_eq = {q2_means[1]:.6f} (< 3.0), yet <Q . F(Q)>_eq = {qf_means[1]:.8f} == 3.0")
print(f"Max |<Q . F>_eq - 3| across all b: {max_virial_err:.3e}")
assert max_virial_err < 1e-6
assert all(q2 < 2.95 for q2 in q2_means[:-1])
fig, ax = plt.subplots(figsize=(7.2, 3.7))
ax.semilogx(b_vals_eq, qf_means, "-o", color="#2E8B57", lw=2.2, ms=5.5, label=r"$\langle \mathbf{Q}\cdot\mathbf{F}(\mathbf{Q})\rangle_{\mathrm{eq}} \equiv 3$")
ax.semilogx(b_vals_eq, q2_means, "--s", color="#2166AC", lw=2.0, ms=5.5, label=r"$\langle Q^2\rangle_{\mathrm{eq}} = 3b/(b+5) < 3$")
ax.set_xlabel("Extensibility parameter $b$")
ax.set_ylabel("Equilibrium average")
ax.set_title(r"$\langle\mathbf{Q}\cdot\mathbf{F}\rangle_{\mathrm{eq}}$ and $\langle Q^2\rangle_{\mathrm{eq}}$")
ax.legend(fontsize=8.5)
log_ticks(ax, "x", [8, 15, 30, 60, 120])
plt.show()
Exercise 1: the equilibrium mean of Q.F for the FENE spring
===========================================================
At b = 15: <Q^2>_eq = 2.250000 (< 3.0), yet <Q . F(Q)>_eq = 3.00000000 == 3.0
Max |<Q . F>_eq - 3| across all b: 2.309e-14

Figure S4.1. Equilibrium averages of the FENE dumbbell against , by quadrature: for every , while is below 3.
Explanation. Integration by parts gives whenever vanishes on the boundary, as does at . Finite extensibility reduces , and the larger spring force compensates exactly: the quadrature gives 3.00000000 at and differs from 3 by at most for the other values of . The result holds for any spring law, which is why the isotropic term of the Kramers expression is for all of them.
Exercise 2¶
Problem. Show the effect of a control variate that is not driven by the same random numbers as the simulation. At , and 1500 trajectories compare (1) the FENE simulation alone (seed=12), (2) the Hookean control variate with the same random numbers (seed=12), and (3) an estimator that subtracts an independent Hookean simulation (seed=99) and adds the exact Hookean result . Compute the variance reduction factor of (2) and of (3).
heading("Exercise 2: a control variate with independent random numbers")
t_bug = np.linspace(0.0, 3.0, 61)
wi_b = 0.08
L_b = np.array([[0.0, wi_b, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
fene_raw = brownian_chains.simulate_dumbbell_bd(lambda _t: L_b, t_bug, model="fene", b_ext=40.0, n_trajectories=1500, control_variate=False, seed=12)
fene_sync = brownian_chains.simulate_dumbbell_bd(lambda _t: L_b, t_bug, model="fene", b_ext=40.0, n_trajectories=1500, control_variate=True, seed=12)
hook_indep = brownian_chains.simulate_dumbbell_bd(lambda _t: L_b, t_bug, model="hookean", b_ext=40.0, n_trajectories=1500, control_variate=False, seed=99)
exact_c_xy = wi_b * (1.0 - np.exp(-t_bug))
# Unbiased control-variate subtraction (beta = 1) with uncorrelated random numbers:
tau_buggy = fene_raw["tau_xy"] - (hook_indep["tau_xy"] - exact_c_xy)
se_buggy = np.sqrt(fene_raw["std_err_tau_xy"] ** 2 + hook_indep["std_err_tau_xy"] ** 2)
# Detrend smooth startup curvature to measure temporal fluctuation jitter directly:
smooth_trend = (40.0 / 45.0) * exact_c_xy
var_raw_time = float(np.var(fene_raw["tau_xy"][15:] - smooth_trend[15:]))
var_bug_time = float(np.var(tau_buggy[15:] - smooth_trend[15:]))
var_sync_time = float(np.var(fene_sync["tau_xy"][15:] - smooth_trend[15:]))
var_inflation = float(np.mean((se_buggy[1:] / fene_raw["std_err_tau_xy"][1:]) ** 2))
vrf_bug = 1.0 / var_inflation
print(f"Estimator VRF -> same random numbers: {fene_sync['variance_reduction_factor']:.1f}x | independent random numbers: {vrf_bug:.3f}x ({var_inflation:.2f} times the variance)")
print(f"Detrended fluctuation variance -> raw: {var_raw_time:.3e}, independent random numbers: {var_bug_time:.3e}, control variate: {var_sync_time:.3e}")
assert 0.35 < vrf_bug < 0.65 and var_inflation > 1.80
assert fene_sync["variance_reduction_factor"] > 15.0 and var_sync_time < 0.15 * var_raw_time
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
axes[0].plot(t_bug, tau_buggy, color="#E08214", lw=1.4, alpha=0.85, label="Independent random numbers")
axes[0].plot(t_bug, fene_raw["tau_xy"], color="#2166AC", lw=1.5, alpha=0.85, label="Without control variate")
axes[0].plot(t_bug, fene_sync["tau_xy"], color="#2E8B57", lw=2.3, label=rf"Control variate ({fene_sync['variance_reduction_factor']:.1f}x reduction)")
axes[0].set_xlabel(r"Dimensionless time $t / \lambda_H$")
axes[0].set_ylabel(r"Shear stress $\tau_{xy}(t)$")
axes[0].set_title(r"Three estimates of the shear stress")
axes[0].legend(fontsize=8)
labels = ["Independent\nrandom numbers", "Without\ncontrol variate", "With\ncontrol variate"]
vrfs = [vrf_bug, 1.0, fene_sync["variance_reduction_factor"]]
axes[1].bar(labels, vrfs, color=["#C0392B", "#2166AC", "#2E8B57"], width=0.5)
axes[1].set_yscale("log")
axes[1].axhline(1.0, color="k", ls=":")
axes[1].set_ylabel("Variance reduction factor (VRF)")
axes[1].set_title(r"Variance reduction factor")
label_panels(fig)
plt.show()
Exercise 2: a control variate with independent random numbers
=============================================================
Estimator VRF -> same random numbers: 89.2x | independent random numbers: 0.528x (1.89 times the variance)
Detrended fluctuation variance -> raw: 1.887e-04, independent random numbers: 3.425e-04, control variate: 3.792e-06

Figure S4.2. (a) Shear stress from the raw estimate, from a control variate driven by the same random numbers, and from one driven by independent random numbers. (b) Variance reduction factor: 89 with the same random numbers, 0.53 with independent ones.
Explanation. For a weight of 1, . With independent random numbers the covariance is zero and the variances add: the variance is 1.9 times that of the simulation alone (a reduction factor of 0.53), at twice the cost. With the same random numbers the variance falls by a factor of 89. The function simulate_dumbbell_bd computes the weight as Cov(raw, cv) / Var(cv), which tends to zero when the two simulations are uncorrelated, so the estimator of the package does not increase the variance in that case.
Exercise 3¶
Problem. Use the control variate (model="fene", b_ext=80, n_trajectories=1600) to simulate small-amplitude oscillatory shear, with and . Obtain and by projecting the stress of the steady cycles on and , and compare them with the Maxwell moduli and of a Hookean dumbbell with effective constants.
heading("Exercise 3: storage and loss moduli from oscillatory shear with a control variate")
gam0 = 0.08
b_saos = 80.0
freqs = np.array([0.4, 1.0, 2.5])
gp_cv, gpp_cv, gp_raw, gpp_raw = [], [], [], []
for om in freqs:
period = 2.0 * math.pi / float(om)
t_osc = np.linspace(0.0, 3.0 * period, 121)
L_osc_fn = lambda tv, w=float(om): np.array([[0.0, gam0 * w * math.cos(w * tv), 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
res_cv = brownian_chains.simulate_dumbbell_bd(L_osc_fn, t_osc, model="fene", b_ext=b_saos, n_trajectories=1000, control_variate=True, seed=51)
res_rw = brownian_chains.simulate_dumbbell_bd(L_osc_fn, t_osc, model="fene", b_ext=b_saos, n_trajectories=1000, control_variate=False, seed=51)
# Project final 2 cycles (t >= period) onto gamma0*sin(om*t) [G'] and gamma0*cos(om*t) [G'']:
t_ss = t_osc[40:]
s_b = np.sin(om * t_ss)
c_b = np.cos(om * t_ss)
gp_cv.append(float(2.0 * trapezoid(res_cv["tau_xy"][40:] * s_b, t_ss) / (2.0 * period * gam0)))
gpp_cv.append(float(2.0 * trapezoid(res_cv["tau_xy"][40:] * c_b, t_ss) / (2.0 * period * gam0)))
gp_raw.append(float(2.0 * trapezoid(res_rw["tau_xy"][40:] * s_b, t_ss) / (2.0 * period * gam0)))
gpp_raw.append(float(2.0 * trapezoid(res_rw["tau_xy"][40:] * c_b, t_ss) / (2.0 * period * gam0)))
# Analytical FENE-P linear viscoelastic limit at b=80: lam_eff = b/(b+5), eta_eff = b/(b+5) -> G_eff = 1:
lam_eff = b_saos / (b_saos + 5.0)
gp_theo = ((freqs * lam_eff) ** 2) / (1.0 + (freqs * lam_eff) ** 2)
gpp_theo = (freqs * lam_eff) / (1.0 + (freqs * lam_eff) ** 2)
err_cv_mod = float(np.max(np.abs(np.array(gp_cv) - gp_theo)) + np.max(np.abs(np.array(gpp_cv) - gpp_theo)))
err_raw_mod = float(np.max(np.abs(np.array(gp_raw) - gp_theo)) + np.max(np.abs(np.array(gpp_raw) - gpp_theo)))
print(f"SAOS moduli error sum |Delta G'| + |Delta G''| -> control variate: {err_cv_mod:.4f} against, without it, {err_raw_mod:.4f}")
assert err_cv_mod < 0.06
assert err_cv_mod < 0.45 * err_raw_mod
om_fine = np.logspace(-0.6, 0.6, 100)
fig, ax = plt.subplots(figsize=(7.4, 3.8))
ax.loglog(om_fine, ((om_fine * lam_eff) ** 2) / (1.0 + (om_fine * lam_eff) ** 2), "-", color="#2166AC", lw=2.0, label=r"Analytical $G'(\omega)$")
ax.loglog(om_fine, (om_fine * lam_eff) / (1.0 + (om_fine * lam_eff) ** 2), "-", color="#C0392B", lw=2.0, label=r"Analytical $G''(\omega)$")
ax.loglog(freqs, gp_cv, "o", color="#2166AC", ms=6.5, label=r"With control variate, $G'(\omega)$ ($\gamma_0=0.08$)")
ax.loglog(freqs, gpp_cv, "s", color="#C0392B", ms=6.5, label=r"With control variate, $G''(\omega)$ ($\gamma_0=0.08$)")
ax.loglog(freqs, np.abs(gp_raw), "x", color="#2166AC", ms=7, mew=1.8, label=r"Without control variate, $|G'|$")
ax.set_xlabel(r"Dimensionless frequency $\omega\lambda_H$")
ax.set_ylabel(r"Dynamic moduli $G', G'' / (n_p k_B T)$")
ax.set_title(r"Storage and loss moduli from oscillatory shear")
ax.legend(fontsize=8)
log_ticks(ax, "x", [0.3, 0.5, 1, 2, 4])
plt.show()
Exercise 3: storage and loss moduli from oscillatory shear with a control variate
=================================================================================
SAOS moduli error sum |Delta G'| + |Delta G''| -> control variate: 0.0292 against, without it, 0.2165

Figure S4.3. Storage and loss moduli of FENE dumbbells () from oscillatory shear of amplitude 0.08 with the control variate (filled symbols), against the single-mode Maxwell curves; crosses are the raw estimate of .
Explanation. At a strain amplitude of 0.08 the shear stress is small compared with its statistical error, and the moduli from the simulation alone scatter around the Maxwell curves. With the control variate the summed error of and over the three frequencies is 0.029, against 0.217 without it. The same idea, one set of random numbers shared by two calculations, is used by the Brownian configuration fields of Lecture 12, where the random numbers are shared by all positions in the flow.