The stress of an ensemble of dumbbells is an average of over the trajectories (the Kramers expression). At equilibrium each component of this product fluctuates with a standard deviation of order 1 in units of , while the shear stress at a Weissenberg number of 0.05 is about 0.05 in the same units. With 2000 trajectories the statistical error is then about half of the signal. Because the error decreases as , an error ten times smaller needs a hundred times more trajectories.
A control variate removes most of this error at little cost. A Hookean dumbbell, whose stress is known exactly, is simulated with the same random numbers as the FENE dumbbell; the difference between its simulated and its exact stress estimates the statistical error, which is then subtracted. This lecture derives the method and measures the reduction of the variance.
Learning objectives¶
Write the Kramers expression and explain why its relative statistical error grows as the Weissenberg number decreases.
Derive the Hookean control variate driven by the same random numbers, and measure the variance reduction factor with
brownian_chains.simulate_dumbbell_bd.Check that the standard error decreases as and that the variance reduction factor is , with the correlation between the two stresses.
Show that a control variate with independent random numbers increases the variance.
Time: about 60 min
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))1. The Kramers expression and its statistical error at low Weissenberg number¶
In the kinetic theory of polymers the polymer stress is given by the Kramers expression (in units in which and ):
At rest , but the variance is about 1. The standard error of the shear stress from trajectories is therefore about , whatever the Weissenberg number, and the ratio of the stress to its error decreases as when .
To remove this error without a closure approximation, a Hookean dumbbell is simulated next to each trajectory , with the same random increments . The exact second moment of Hookean dumbbells, , obeys the deterministic equation and is integrated alongside. The estimator of the stress is
The expectation of is zero, so the estimator is unbiased for the FENE and wormlike-chain springs. Its variance is smaller than that of the plain estimator by the variance reduction factor , where is the correlation between the two terms.
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()
Demonstration 1: shear stress with and without the control variate at Wi = 0.08
===============================================================================
FENE (b=40, Wi=0.08, N_tr=1500):
Without control variate mean std error : 2.6813e-02 (noise ~ 33.5% of signal)
Control-variate mean std error : 2.9492e-03
Achieved variance reduction factor : 89.2x (equivalent to 133,802 raw trajectories)

Figure 4.1. FENE dumbbells (, 1500 trajectories) at a low shear rate. (a) The raw estimate of the shear stress with its 95 % interval, and the estimate with the Hookean control variate. (b) Standard error of the two estimates.
2. The Hookean control variate and the law¶
A first test applies control_variate=True to an ensemble of Hookean dumbbells (model="hookean"). The control variate is then identical to the simulated dumbbell at every step, , so that , the optimal weight is , and the fluctuations cancel completely. What remains is the deterministic solution , reproduced to better than 10-4 even with a very small ensemble. For FENE springs the cancellation is incomplete; the remaining error still decreases as , with a much smaller prefactor.
heading("Demonstration 2: the Hookean dumbbell and the dependence of the standard error on N_tr")
bd_hook_cv = brownian_chains.simulate_dumbbell_bd(
lambda _t: L_low, t_cv, model="hookean", n_trajectories=600, control_variate=True, seed=11
)
exact_hook_low = wi_low * (1.0 - np.exp(-t_cv))
hook_err = float(np.max(np.abs(bd_hook_cv["tau_xy"] - exact_hook_low)))
ntr_list = np.array([120, 240, 480, 960, 1920])
se_raw_n, se_cv_n = [], []
L_w015 = np.array([[0.0, 0.15, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
t_short = np.linspace(0.0, 1.6, 33)
for n_tr in ntr_list:
r_run = brownian_chains.simulate_dumbbell_bd(lambda _t: L_w015, t_short, model="fene", b_ext=45.0, n_trajectories=int(n_tr), control_variate=True, seed=25)
se_raw_n.append(float(np.mean(r_run["raw_std_err_tau_xy"][8:])))
se_cv_n.append(float(np.mean(r_run["std_err_tau_xy"][8:])))
slope_raw = float(np.polyfit(np.log(ntr_list), np.log(se_raw_n), 1)[0])
slope_cv = float(np.polyfit(np.log(ntr_list), np.log(se_cv_n), 1)[0])
print(f"Hookean CV max |tau_xy - Wi*(1 - e^-t)| with N_tr=600: {hook_err:.3e}")
print(f"Monte Carlo SE slopes against N_tr -> raw: {slope_raw:.3f}, CV: {slope_cv:.3f} (exact = -0.500)")
assert hook_err < 1e-4
assert -0.58 < slope_raw < -0.42 and -0.58 < slope_cv < -0.42
assert se_cv_n[-1] < 0.22 * se_raw_n[-1]
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
axes[0].plot(t_cv, exact_hook_low, "k-", lw=2.2, label=r"Exact $0.08(1 - e^{-t})$")
axes[0].plot(t_cv[::3], bd_hook_cv["tau_xy"][::3], "o", color="#2E8B57", ms=5, label="Hookean, with control variate ($N_{\\mathrm{tr}}=600$)")
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"Hookean dumbbells with the control variate")
axes[0].legend(fontsize=8.5)
axes[1].loglog(ntr_list, se_raw_n, "--o", color="#2166AC", lw=2.0, ms=5, label=rf"Without control variate (slope={slope_raw:.2f})")
axes[1].loglog(ntr_list, se_cv_n, "-s", color="#C0392B", lw=2.1, ms=5, label=rf"With control variate (slope={slope_cv:.2f})")
axes[1].loglog(ntr_list, se_cv_n[0] * np.sqrt(ntr_list[0] / ntr_list), "k:", lw=1.5, label=r"Reference $N_{\mathrm{tr}}^{-1/2}$")
axes[1].set_xlabel(r"Ensemble size $N_{\mathrm{tr}}$")
axes[1].set_ylabel(r"Mean standard error $\mathrm{SE}(\tau_{xy})$")
axes[1].set_title(r"Standard error against ensemble size")
axes[1].legend(fontsize=8)
log_ticks(axes[1], "x", [150, 300, 600, 1200, 2000])
label_panels(fig)
plt.show()
Demonstration 2: the Hookean dumbbell and the dependence of the standard error on N_tr
======================================================================================
Hookean CV max |tau_xy - Wi*(1 - e^-t)| with N_tr=600: 1.273e-05
Monte Carlo SE slopes against N_tr -> raw: -0.487, CV: -0.510 (exact = -0.500)

Figure 4.2. (a) For Hookean dumbbells the control variate removes the noise and the estimate follows the exact start-up curve. (b) Standard error of the raw and control-variate estimates for FENE dumbbells against the number of trajectories; both fall as .
3. The variance reduction factor against and ¶
A Hookean control variate is most effective at low and large , and loses its correlation with the FENE simulation at high :
For the dumbbells stay close to equilibrium, where . The FENE and the Hookean trajectories are then nearly the same, is close to 1, and the reduction factor is large.
For the FENE dumbbells approach their maximum length while the Hookean ones continue to stretch, and the correlation decreases. At high , however, the stress is large compared with its statistical error, and the plain estimator is already accurate. The control variate is needed where the plain estimator is poor.
heading("Demonstration 3: variance reduction factor against Wi and b")
wi_scan = np.array([0.05, 0.20, 0.6, 1.8, 5.0])
vrf_b25, vrf_b60, vrf_wlc = [], [], []
t_vrf = np.linspace(0.0, 1.6, 33)
for wv in wi_scan:
Lw = np.array([[0.0, float(wv), 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
r25 = brownian_chains.simulate_dumbbell_bd(lambda _t, L=Lw: L, t_vrf, model="fene", b_ext=25.0, n_trajectories=650, control_variate=True, seed=33)
r60 = brownian_chains.simulate_dumbbell_bd(lambda _t, L=Lw: L, t_vrf, model="fene", b_ext=60.0, n_trajectories=650, control_variate=True, seed=33)
rwl = brownian_chains.simulate_dumbbell_bd(lambda _t, L=Lw: L, t_vrf, model="wlc", b_ext=40.0, n_trajectories=650, control_variate=True, seed=33)
vrf_b25.append(r25["variance_reduction_factor"])
vrf_b60.append(r60["variance_reduction_factor"])
vrf_wlc.append(rwl["variance_reduction_factor"])
print(f"Low-Wi=0.05 VRF -> FENE(b=60): {vrf_b60[0]:.1f}x, FENE(b=25): {vrf_b25[0]:.1f}x, WLC(b=40): {vrf_wlc[0]:.1f}x")
print(f"High-Wi=5.0 VRF -> FENE(b=60): {vrf_b60[-1]:.2f}x, FENE(b=25): {vrf_b25[-1]:.2f}x (not below 1)")
assert vrf_b60[0] > vrf_b25[0] > 10.0
assert vrf_wlc[0] > 4.0
assert min(vrf_b25) >= 1.0
fig, ax = plt.subplots(figsize=(7.6, 3.9))
ax.loglog(wi_scan, vrf_b60, "-s", color="#2166AC", lw=2.1, ms=5.5, label="FENE ($b = 60$)")
ax.loglog(wi_scan, vrf_b25, "-o", color="#2E8B57", lw=2.1, ms=5.5, label="FENE ($b = 25$)")
ax.loglog(wi_scan, vrf_wlc, "-^", color="#C0392B", lw=2.1, ms=5.5, label="Wormlike chain ($b = 40$)")
ax.axhline(1.0, color="gray", ls=":", label="VRF = 1")
ax.set_xlabel(r"Weissenberg number $\mathrm{Wi} = \lambda_H\dot{\gamma}$")
ax.set_ylabel("Variance reduction factor (VRF)")
ax.set_title(r"Variance reduction factor")
ax.legend(fontsize=8.5)
plt.show()
Demonstration 3: variance reduction factor against Wi and b
===========================================================
Low-Wi=0.05 VRF -> FENE(b=60): 263.5x, FENE(b=25): 46.7x, WLC(b=40): 78.1x
High-Wi=5.0 VRF -> FENE(b=60): 29.81x, FENE(b=25): 6.86x (not below 1)

Figure 4.3. Variance reduction factor of the Hookean control variate against the Weissenberg number for two FENE models and one wormlike-chain model. It is largest at low rates and stays above 1 (dotted).
4. Flow curves from low to high Weissenberg number¶
With the control variate, flow curves can be computed from the Newtonian plateau () up to with dumbbells for each point, with errors small enough to distinguish Hookean, FENE and wormlike-chain springs.
heading("Demonstration 4: flow curves from Wi = 0.05 to Wi = 4.5")
wi_fc = np.array([0.05, 0.15, 0.45, 1.5, 4.5])
t_fc = np.linspace(0.0, 5.6, 57)
eta_h, eta_f, eta_w, se_f_cv, se_f_raw = [], [], [], [], []
for wv in wi_fc:
Lw = np.array([[0.0, float(wv), 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
rh = brownian_chains.simulate_dumbbell_bd(lambda _t, L=Lw: L, t_fc, model="hookean", n_trajectories=650, control_variate=True, seed=61)
rf = brownian_chains.simulate_dumbbell_bd(lambda _t, L=Lw: L, t_fc, model="fene", b_ext=30.0, n_trajectories=650, control_variate=True, seed=61)
rw = brownian_chains.simulate_dumbbell_bd(lambda _t, L=Lw: L, t_fc, model="wlc", b_ext=30.0, n_trajectories=650, control_variate=True, seed=61)
eta_h.append(float(np.mean(rh["tau_xy"][38:]) / wv))
eta_f.append(float(np.mean(rf["tau_xy"][38:]) / wv))
eta_w.append(float(np.mean(rw["tau_xy"][38:]) / wv))
se_f_cv.append(float(np.mean(rf["std_err_tau_xy"][38:]) / wv))
se_f_raw.append(float(np.mean(rf["raw_std_err_tau_xy"][38:]) / wv))
print(f"Wi=0.05 zero-shear viscosity: Hookean={eta_h[0]:.4f}, FENE(b=30)={eta_f[0]:.4f} +/- {se_f_cv[0]:.4f} (without the control variate: +/- {se_f_raw[0]:.4f})")
assert abs(eta_h[0] - 1.0) < 0.02
assert se_f_cv[0] < 0.25 * se_f_raw[0]
assert eta_f[-1] < eta_f[0] and eta_w[-1] < eta_w[0]
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
axes[0].semilogx(wi_fc, eta_h, "-k", lw=2.0, label="Hookean ($\\eta_p = 1$)")
axes[0].errorbar(wi_fc, eta_f, yerr=1.96 * np.array(se_f_cv), fmt="-o", color="#2166AC", lw=2.0, capsize=3, label="FENE ($b=30$, CV 95% CI)")
axes[0].semilogx(wi_fc, eta_w, "-s", color="#C0392B", lw=2.0, label="Wormlike chain ($b=30$, CV)")
axes[0].set_xlabel(r"Weissenberg number $\mathrm{Wi}$")
axes[0].set_ylabel(r"Dimensionless polymer viscosity $\eta_p(\mathrm{Wi})$")
axes[0].set_title(r"Polymer viscosity")
axes[0].legend(fontsize=8)
axes[1].loglog(wi_fc, se_f_raw, "--o", color="#2166AC", lw=1.9, label="Without control variate, $\\mathrm{SE}(\\tau_{xy})/\\mathrm{Wi}$")
axes[1].loglog(wi_fc, se_f_cv, "-s", color="#2E8B57", lw=2.1, label="With control variate")
axes[1].set_xlabel(r"Weissenberg number $\mathrm{Wi}$")
axes[1].set_ylabel(r"Viscosity standard error $\mathrm{SE}(\eta_p)$")
axes[1].set_title(r"Standard error of the viscosity")
axes[1].legend(fontsize=8)
log_ticks(axes[1], "y", [0.03, 0.1, 0.3, 0.7])
label_panels(fig)
plt.show()
Demonstration 4: flow curves from Wi = 0.05 to Wi = 4.5
=======================================================
Wi=0.05 zero-shear viscosity: Hookean=0.9894, FENE(b=30)=0.7460 +/- 0.1423 (without the control variate: +/- 0.8172)

Figure 4.4. (a) Polymer viscosity from 650 dumbbells with the control variate, for FENE and wormlike-chain springs (), with 95 % intervals for FENE. (b) Standard error of the viscosity with and without the control variate.
Inside the algorithm¶
The cell below prints the source of brownian_chains.simulate_dumbbell_bd. The relevant parts are the function _record and the block if control_variate:.
QandQ_cvare advanced with the same arraydW, drawn once in each step.C_detis advanced with a midpoint scheme, so thatcv_xy = Q_cv[:, 0] * Q_cv[:, 1] - C_det[0, 1]has zero expectation.The weight
beta_opt = Cov(raw_xy, cv_xy) / Var(cv_xy)is computed from the ensemble. It is close to 1 at low Wi and smaller when finite extensibility reduces the correlation.
Check against the package¶
The check below verifies the identity in NumPy for coupled ensembles of FENE and Hookean dumbbells: the measured ratio of variances equals 1 / (1 - rho^2) to rounding error.
heading("Inside the algorithm: the variance reduction factor and 1/(1 - rho^2)")
print(show_source(brownian_chains.simulate_dumbbell_bd))
rng_v = np.random.default_rng(404)
n_v = 5000
Z0 = rng_v.normal(0.0, 1.0, size=(n_v, 3))
b_v = 45.0
Q_f = Z0 * math.sqrt(b_v / (b_v + 5.0))
Q_h = Z0.copy()
# Advance 10 synchronized shear steps at Wi = 0.1, dt = 0.04:
dt_v = 0.04
L_v = np.array([[0.0, 0.10, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
C_d = np.eye(3)
for _ in range(10):
dW_v = rng_v.normal(0.0, math.sqrt(dt_v), size=(n_v, 3))
Ff = Q_f / np.maximum(1.0 - np.sum(Q_f**2, axis=1, keepdims=True) / b_v, 1e-12)
Yv = Q_f + (Q_f @ L_v.T - 0.25 * Ff) * dt_v + dW_v
Yn = np.linalg.norm(Yv, axis=1)
Rn = brownian_chains.solve_fene_cubic_radial(Yn, b_ext=b_v, coeff_alpha=0.25 * dt_v)
Q_f = Rn[:, None] * (Yv / np.maximum(Yn[:, None], 1e-15))
Q_h = (Q_h + (Q_h @ L_v.T - 0.25 * Q_h) * dt_v + dW_v) / (1.0 + 0.25 * dt_v)
C_d = C_d + dt_v * (L_v @ C_d + C_d @ L_v.T - (C_d - np.eye(3)))
X_raw = Q_f[:, 0] * (Q_f[:, 1] / (1.0 - np.sum(Q_f**2, axis=1) / b_v))
Y_cv = Q_h[:, 0] * Q_h[:, 1] - C_d[0, 1]
cov_mat = np.cov(X_raw, Y_cv, ddof=0)
beta_star = cov_mat[0, 1] / cov_mat[1, 1]
rho_xy = cov_mat[0, 1] / math.sqrt(cov_mat[0, 0] * cov_mat[1, 1])
var_ratio_emp = float(np.var(X_raw) / np.var(X_raw - beta_star * Y_cv))
var_ratio_theo = 1.0 / (1.0 - rho_xy**2)
print(f"Correlation rho(X_FENE, Y_Hook) = {rho_xy:.6f}, optimal beta* = {beta_star:.4f}")
print(f"Empirical VRF = {var_ratio_emp:.4f}x against theoretical 1/(1 - rho^2) = {var_ratio_theo:.4f}x")
assert abs(var_ratio_emp - var_ratio_theo) < 1e-10
assert var_ratio_emp > 20.0
Inside the algorithm: the variance reduction factor and 1/(1 - rho^2)
=====================================================================
def simulate_dumbbell_bd(
flow_L_fn: Callable[[float], np.ndarray],
t_grid: np.ndarray,
model: str = "fene",
b_ext: float = 50.0,
n_trajectories: int = 3000,
control_variate: bool = True,
explicit_unsafe: bool = False,
seed: int = 42,
) -> dict:
"""Brownian dynamics of dumbbells in three dimensions (dimensionless: lam = 1, n k_B T = 1), with a Hookean control variate."""
t = np.asarray(t_grid, dtype=float).ravel()
if t.size < 2 or np.any(np.diff(t) <= 0.0) or n_trajectories < 10 or b_ext <= 2.0:
raise ValueError("Require increasing t_grid, n_trajectories >= 10, and b_ext > 2.")
if model not in ("hookean", "fene", "wlc"):
raise ValueError("model must be 'hookean', 'fene', or 'wlc'.")
rng = np.random.default_rng(seed)
n_tr = int(n_trajectories)
# Equilibrium sampling in dimensionless units where Hookean <Q_i^2>_eq = 1 (trace = 3):
Q = rng.normal(0.0, 1.0, size=(n_tr, 3))
if model in ("fene", "wlc"):
# Rescale initial equilibrium variance slightly inside finite extensibility sqrt(b_ext):
scale_eq = math.sqrt(b_ext / (b_ext + 5.0))
Q = Q * scale_eq
norms0 = np.linalg.norm(Q, axis=1, keepdims=True)
max_r0 = 0.92 * math.sqrt(b_ext)
Q = np.where(norms0 > max_r0, Q * (max_r0 / np.maximum(norms0, 1e-12)), Q)
Q_cv = rng.normal(0.0, 1.0, size=(n_tr, 3)) if not control_variate else Q.copy()
if control_variate and model in ("fene", "wlc"):
# Synchronized Hookean control variate starts from exact unit-variance Gaussian using same directions:
Q_cv = Q / math.sqrt(b_ext / (b_ext + 5.0))
C_det = np.eye(3, dtype=float) # Exact deterministic Hookean moment <Q_cv Q_cv^T>
def _spring_force(q_arr: np.ndarray) -> np.ndarray:
if model == "hookean":
return q_arr
r2 = np.sum(q_arr**2, axis=1, keepdims=True)
if model == "fene":
denom = np.where(explicit_unsafe, 1.0 - r2 / b_ext, np.maximum(1.0 - r2 / b_ext, 1e-12))
return q_arr / denom
# Marko-Siggia worm-like chain force interpolated in dimensionless Q / sqrt(b_ext):
x_rel = np.clip(np.sqrt(r2 / b_ext), 0.0, 0.985)
f_wlc = (
(2.0 / 3.0) * (1.0 / ((1.0 - x_rel) ** 2) - 1.0 + 4.0 * x_rel) / np.maximum(x_rel * math.sqrt(b_ext), 1e-12)
)
return np.where(x_rel < 1e-7, q_arr, f_wlc * q_arr)
tau_xy = np.zeros(t.size, dtype=float)
n1 = np.zeros(t.size, dtype=float)
n2 = np.zeros(t.size, dtype=float)
mean_q2 = np.zeros(t.size, dtype=float)
se_tau_xy = np.zeros(t.size, dtype=float)
raw_se_tau_xy = np.zeros(t.size, dtype=float)
overstretched = 0
def _record(step_i: int) -> None:
F_q = _spring_force(Q)
raw_xy = Q[:, 0] * F_q[:, 1]
raw_xx = Q[:, 0] * F_q[:, 0] - 1.0
raw_yy = Q[:, 1] * F_q[:, 1] - 1.0
raw_zz = Q[:, 2] * F_q[:, 2] - 1.0
raw_se = float(np.std(raw_xy, ddof=1) / math.sqrt(n_tr))
raw_se_tau_xy[step_i] = raw_se
if control_variate:
cv_xy = Q_cv[:, 0] * Q_cv[:, 1] - C_det[0, 1]
cv_xx = (Q_cv[:, 0] ** 2 - 1.0) - (C_det[0, 0] - 1.0)
cv_yy = (Q_cv[:, 1] ** 2 - 1.0) - (C_det[1, 1] - 1.0)
cv_zz = (Q_cv[:, 2] ** 2 - 1.0) - (C_det[2, 2] - 1.0)
# Optimal linear control-variate coefficient beta* = Cov(raw, cv) / Var(cv):
var_cv = float(np.var(cv_xy))
beta_opt = float(np.cov(raw_xy, cv_xy, ddof=0)[0, 1] / var_cv) if var_cv > 1e-14 else 1.0
beta_opt = float(np.clip(beta_opt, 0.0, 2.0))
est_xy = raw_xy - beta_opt * cv_xy
tau_xy[step_i] = float(np.mean(est_xy))
se_tau_xy[step_i] = float(np.std(est_xy, ddof=1) / math.sqrt(n_tr))
n1[step_i] = float(np.mean((raw_xx - raw_yy) - beta_opt * (cv_xx - cv_yy)))
n2[step_i] = float(np.mean((raw_yy - raw_zz) - beta_opt * (cv_yy - cv_zz)))
else:
tau_xy[step_i] = float(np.mean(raw_xy))
se_tau_xy[step_i] = raw_se
n1[step_i] = float(np.mean(raw_xx - raw_yy))
n2[step_i] = float(np.mean(raw_yy - raw_zz))
mean_q2[step_i] = float(np.mean(np.sum(Q**2, axis=1)))
_record(0)
for k in range(t.size - 1):
dt = float(t[k + 1] - t[k])
tk = float(t[k])
L_k = np.asarray(flow_L_fn(tk), dtype=float)
L_next = np.asarray(flow_L_fn(float(t[k + 1])), dtype=float)
dW = rng.normal(0.0, math.sqrt(dt), size=(n_tr, 3))
# Dimensionless Ito dumbbell SDE (relaxation time lam = 1, equilibrium <Q_i^2>_H = 1):
# dQ = (L @ Q - 0.5 * F(Q)) dt + dW
if model == "hookean" and not explicit_unsafe:
Q_pred = Q + (Q @ L_k.T - 0.5 * Q) * dt + dW
Q = (Q + 0.5 * (Q @ L_k.T + Q_pred @ L_next.T) * dt - 0.25 * Q * dt + dW) / (1.0 + 0.25 * dt)
elif explicit_unsafe:
F_cur = _spring_force(Q)
Q = Q + (Q @ L_k.T - 0.5 * F_cur) * dt + dW
if model == "fene":
overstretched += int(np.sum(np.sum(Q**2, axis=1) >= b_ext))
elif model == "fene":
# Ottinger (1996) semi-implicit predictor-corrector using exact cubic radial step:
F_cur = _spring_force(Q)
Q_pred = Q + (Q @ L_k.T - 0.5 * F_cur) * dt + dW
# Clamp predictor inside ball if needed before evaluating L_next @ Q_pred:
r_pred = np.linalg.norm(Q_pred, axis=1, keepdims=True)
Q_pred_safe = np.where(
r_pred >= 0.99 * math.sqrt(b_ext),
Q_pred * (0.99 * math.sqrt(b_ext) / np.maximum(r_pred, 1e-12)),
Q_pred,
)
Y_vec = Q + 0.5 * (Q @ L_k.T + Q_pred_safe @ L_next.T) * dt - 0.25 * F_cur * dt + dW
Y_norm = np.linalg.norm(Y_vec, axis=1)
R_new = solve_fene_cubic_radial(Y_norm, b_ext=b_ext, coeff_alpha=0.25 * dt)
unit_dir = Y_vec / np.maximum(Y_norm[:, None], 1e-15)
Q = R_new[:, None] * unit_dir
else:
# Semi-implicit radial step for WLC using 4-step bisection/Newton safeguard inside sqrt(b_ext):
F_cur = _spring_force(Q)
RHS = Q + (Q @ L_k.T - 0.25 * F_cur) * dt + dW
Y_norm = np.linalg.norm(RHS, axis=1)
R_est = solve_fene_cubic_radial(Y_norm, b_ext=b_ext, coeff_alpha=0.25 * dt)
Q = R_est[:, None] * (RHS / np.maximum(Y_norm[:, None], 1e-15))
if control_variate:
# Advance synchronized Hookean ensemble with identical dW and exact deterministic C_det via RK2:
Q_cv_pred = Q_cv + (Q_cv @ L_k.T - 0.5 * Q_cv) * dt + dW
Q_cv = (Q_cv + 0.5 * (Q_cv @ L_k.T + Q_cv_pred @ L_next.T) * dt - 0.25 * Q_cv * dt + dW) / (1.0 + 0.25 * dt)
dC1 = L_k @ C_det + C_det @ L_k.T - (C_det - np.eye(3))
C_mid = C_det + 0.5 * dt * dC1
L_mid = 0.5 * (L_k + L_next)
dC2 = L_mid @ C_mid + C_mid @ L_mid.T - (C_mid - np.eye(3))
C_det = C_det + dt * dC2
_record(k + 1)
vrf = float(np.mean((raw_se_tau_xy[1:] / np.maximum(se_tau_xy[1:], 1e-15)) ** 2))
return {
"t": t,
"tau_xy": tau_xy,
"N1": n1,
"N2": n2,
"mean_Q2": mean_q2,
"std_err_tau_xy": se_tau_xy,
"raw_std_err_tau_xy": raw_se_tau_xy,
"variance_reduction_factor": vrf,
"overstretched_count": overstretched,
}
Correlation rho(X_FENE, Y_Hook) = 0.997136, optimal beta* = 1.0314
Empirical VRF = 174.8157x against theoretical 1/(1 - rho^2) = 174.8157x
Exercises¶
Worked solutions are in 04_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. 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 .
Find how it fails. 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).Implement it yourself. 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("Self-check for the exercises")
atlas_04 = [entry for entry in constants_benchmarks.RHEO_ATLAS_DB if entry["lecture"] == "04"]
assert len(atlas_04) == 1
assert vrf_achieved > 15.0 and hook_err < 1e-4
assert abs(var_ratio_emp - var_ratio_theo) < 1e-10
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.