Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

4. The Kramers stress and variance reduction with control variates

The stress of an ensemble of dumbbells is an average of QF\mathbf{Q}\mathbf{F} over the trajectories (the Kramers expression). At equilibrium each component of this product fluctuates with a standard deviation of order 1 in units of npkBTn_p k_B T, 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 Ntr−1/2N_{\mathrm{tr}}^{-1/2}, 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

  1. Write the Kramers expression τp=np⟨Q⊗F(Q)⟩−npkBT I\boldsymbol{\tau}_p = n_p\langle \mathbf{Q}\otimes\mathbf{F}(\mathbf{Q})\rangle - n_p k_B T\,\mathbf{I} and explain why its relative statistical error grows as the Weissenberg number decreases.

  2. Derive the Hookean control variate driven by the same random numbers, and measure the variance reduction factor with brownian_chains.simulate_dumbbell_bd.

  3. Check that the standard error decreases as Ntr−1/2N_{\mathrm{tr}}^{-1/2} and that the variance reduction factor is (1−ρ2)−1(1 - \rho^2)^{-1}, with ρ\rho the correlation between the two stresses.

  4. Show that a control variate with independent random numbers increases the variance.

Time: about 60 min

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 npkBT=1n_p k_B T = 1 and λH=1\lambda_H = 1):

τp(t)=⟨Q(t)⊗F(Q(t))⟩−I≈1Ntr∑m=1Ntr[Q(m)(t)F(Q(m)(t))⊤−I].\boldsymbol{\tau}_p(t) = \langle \mathbf{Q}(t) \otimes \mathbf{F}(\mathbf{Q}(t)) \rangle - \mathbf{I} \approx \frac{1}{N_{\mathrm{tr}}}\sum_{m=1}^{N_{\mathrm{tr}}} \left[\mathbf{Q}^{(m)}(t)\mathbf{F}(\mathbf{Q}^{(m)}(t))^\top - \mathbf{I}\right].

At rest ⟨QxFy⟩=0\langle Q_x F_y \rangle = 0, but the variance Var⁡(QxFy)=⟨Qx2Fy2⟩\operatorname{Var}(Q_x F_y) = \langle Q_x^2 F_y^2 \rangle is about 1. The standard error of the shear stress from NtrN_{\mathrm{tr}} trajectories is therefore about Ntr−1/2N_{\mathrm{tr}}^{-1/2}, whatever the Weissenberg number, and the ratio of the stress to its error decreases as WiNtr\mathrm{Wi}\sqrt{N_{\mathrm{tr}}} when Wi→0\mathrm{Wi} \to 0.

To remove this error without a closure approximation, a Hookean dumbbell Qcv(m)(t)\mathbf{Q}_{\mathrm{cv}}^{(m)}(t) is simulated next to each trajectory mm, with the same random increments dW(m)(t)d\mathbf{W}^{(m)}(t). The exact second moment of Hookean dumbbells, Cdet\mathbf{C}_{\mathrm{det}}, obeys the deterministic equation C˙det=LCdet+CdetL⊤−(Cdet−I)\dot{\mathbf{C}}_{\mathrm{det}} = \mathbf{L}\mathbf{C}_{\mathrm{det}} + \mathbf{C}_{\mathrm{det}}\mathbf{L}^\top - (\mathbf{C}_{\mathrm{det}} - \mathbf{I}) and is integrated alongside. The estimator of the stress is

τ^xy(t)=1Ntr∑m=1Ntr[Qx(m)Fy(Q(m))⏟Unbiased nonlinear virial−β∗(Qcv,x(m)Qcv,y(m)−Cdet,xy(t)⏟Exact mean zero)],β∗=Cov⁡(τraw,τcv)Var⁡(τcv).\hat{\tau}_{xy}(t) = \frac{1}{N_{\mathrm{tr}}}\sum_{m=1}^{N_{\mathrm{tr}}} \Bigl[\underbrace{Q_x^{(m)} F_y(\mathbf{Q}^{(m)})}_{\text{Unbiased nonlinear virial}} - \beta^*\bigl(\underbrace{Q_{\mathrm{cv},x}^{(m)} Q_{\mathrm{cv},y}^{(m)} - C_{\mathrm{det},xy}(t)}_{\text{Exact mean zero}}\bigr)\Bigr], \qquad \beta^* = \frac{\operatorname{Cov}(\tau_{\mathrm{raw}}, \tau_{\mathrm{cv}})}{\operatorname{Var}(\tau_{\mathrm{cv}})}.

The expectation of Qcv,xQcv,y−Cdet,xyQ_{\mathrm{cv},x} Q_{\mathrm{cv},y} - C_{\mathrm{det},xy} is zero, so the estimator τ^xy\hat{\tau}_{xy} is unbiased for the FENE and wormlike-chain springs. Its variance is smaller than that of the plain estimator by the variance reduction factor VRF=(1−ρ2)−1\mathrm{VRF} = (1 - \rho^2)^{-1}, where ρ\rho is the correlation between the two terms.


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 size 1155x418 with 2 Axes>

Figure 4.1. FENE dumbbells (b=40b = 40, 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 Ntr−1/2N_{\mathrm{tr}}^{-1/2} 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, Q(m)(t)=Qcv(m)(t)\mathbf{Q}^{(m)}(t) = \mathbf{Q}_{\mathrm{cv}}^{(m)}(t), so that ρ=1\rho = 1, the optimal weight is β∗=1\beta^* = 1, and the fluctuations cancel completely. What remains is the deterministic solution τxy(t)=Wi(1−e−t)\tau_{xy}(t) = \mathrm{Wi}(1 - e^{-t}), 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 Ntr−1/2N_{\mathrm{tr}}^{-1/2}, with a much smaller prefactor.


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 size 1155x418 with 2 Axes>

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 Ntr−1/2N_{\mathrm{tr}}^{-1/2}.

3. The variance reduction factor against Wi\mathrm{Wi} and bb

A Hookean control variate is most effective at low Wi\mathrm{Wi} and large bb, and loses its correlation with the FENE simulation at high Wi\mathrm{Wi}:

  • For Wi≪1\mathrm{Wi} \ll 1 the dumbbells stay close to equilibrium, where 1−Q2/b≈1−3/b1 - Q^2/b \approx 1 - 3/b. The FENE and the Hookean trajectories are then nearly the same, ρ\rho is close to 1, and the reduction factor is large.

  • For Wi≫1\mathrm{Wi} \gg 1 the FENE dumbbells approach their maximum length while the Hookean ones continue to stretch, and the correlation decreases. At high Wi\mathrm{Wi}, 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.


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 size 836x429 with 1 Axes>

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 (Wi=0.05\mathrm{Wi} = 0.05) up to Wi=4.5\mathrm{Wi} = 4.5 with Ntr=650N_{\mathrm{tr}} = 650 dumbbells for each point, with errors small enough to distinguish Hookean, FENE and wormlike-chain springs.


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 size 1155x418 with 2 Axes>

Figure 4.4. (a) Polymer viscosity from 650 dumbbells with the control variate, for FENE and wormlike-chain springs (b=30b = 30), 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:.

  1. Q and Q_cv are advanced with the same array dW, drawn once in each step.

  2. C_det is advanced with a midpoint scheme, so that cv_xy = Q_cv[:, 0] * Q_cv[:, 1] - C_det[0, 1] has zero expectation.

  3. 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 Var⁡(X−β∗Y)=(1−ρXY2)Var⁡(X)\operatorname{Var}(X - \beta^* Y) = (1 - \rho_{XY}^2)\operatorname{Var}(X) in NumPy for coupled ensembles of FENE and Hookean dumbbells: the measured ratio of variances equals 1 / (1 - rho^2) to rounding error.


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.

  1. Verify a result. Check by radial quadrature that for a FENE dumbbell with b=15b = 15, although ⟨Q2⟩eq=3bb+5=2.25\langle Q^2\rangle_{\mathrm{eq}} = \frac{3b}{b+5} = 2.25 is smaller than 3, the mean ⟨Q⋅F(Q)⟩eq\langle \mathbf{Q}\cdot\mathbf{F}(\mathbf{Q})\rangle_{\mathrm{eq}} equals 3 (that is, ⟨QiFj⟩eq=δij\langle Q_i F_j\rangle_{\mathrm{eq}} = \delta_{ij}), so that the Kramers expression gives zero polymer stress at rest. Repeat for other values of bb.

  2. Find how it fails. Show the effect of a control variate that is not driven by the same random numbers as the simulation. At Wi=0.08\mathrm{Wi} = 0.08, b=40b = 40 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 Cdet,xy(t)C_{\mathrm{det},xy}(t). Compute the variance reduction factor of (2) and of (3).

  3. Implement it yourself. Use the control variate (model="fene", b_ext=80, n_trajectories=1600) to simulate small-amplitude oscillatory shear, γ˙(t)=γ0ωcos⁡(ωt)\dot{\gamma}(t) = \gamma_0\omega\cos(\omega t) with γ0=0.08\gamma_0 = 0.08 and ω∈{0.4,1.0,2.5}\omega \in \{0.4, 1.0, 2.5\}. Obtain G′(ω)G'(\omega) and G′′(ω)G''(\omega) by projecting the stress of the steady cycles on sin⁡(ωt)\sin(\omega t) and cos⁡(ωt)\cos(\omega t), and compare them with the Maxwell moduli Geff(ωλeff)21+(ωλeff)2G_{\mathrm{eff}}\frac{(\omega\lambda_{\mathrm{eff}})^2}{1 + (\omega\lambda_{\mathrm{eff}})^2} and Geffωλeff1+(ωλeff)2G_{\mathrm{eff}}\frac{\omega\lambda_{\mathrm{eff}}}{1 + (\omega\lambda_{\mathrm{eff}})^2} of a Hookean dumbbell with effective constants.


Self-check for the exercises
============================
All checks passed.