Solutions · 16. Passive microrheology and a frame-invariant, thermodynamically consistent stress model
Worked solutions to the three exercises of Lecture 16. 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: mean-square displacement of a probe over five decades of time")
t_lag = np.concatenate([[0.0], np.geomspace(1.0e-4, 10.0, 65)])
modes_gel = [(3.2, 0.18), (0.8, 1.50)] # Two-mode viscoelastic network [Pa, s]
gle = microrheology_rheoml.simulate_gle_thermal_probe(
modes_gel, t_lag, probe_radius_a=0.5e-6, kT=4.11e-21, eta_s=3.0e-3, n_probes=1200, seed=42
)
rel_err_msd = float(np.mean(np.abs(gle["msd_simulated"][1:] - gle["msd_exact"][1:]) / gle["msd_exact"][1:]))
alpha_curve = np.gradient(np.log(gle["msd_exact"][1:]), np.log(gle["t"][1:]))
print(f"Ensemble against exact normal-mode MSD mean relative error : {rel_err_msd:.4f}")
print(f"Minimum subdiffusive caging slope min d(ln MSD)/d(ln t): {np.min(alpha_curve):.4f}")
print(f"Terminal logarithmic slope at t = 10 s : {alpha_curve[-1]:.4f}")
assert rel_err_msd < 0.08
assert float(np.min(alpha_curve)) < 0.22
assert alpha_curve[-1] > 0.85
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
ax1.loglog(gle["t"][1:], gle["msd_exact"][1:] * 1e12, "k-", lw=2.3, label="Exact (generalized Langevin equation)")
ax1.loglog(gle["t"][1::3], gle["msd_simulated"][1::3] * 1e12, "o", ms=4.5, color="#2166AC", label="Simulated probes (N = 1200)")
ax1.set_xlabel("Lag time t [s]")
ax1.set_ylabel(r"Mean-square displacement $\langle\Delta x^2\rangle$ [$\mu$m$^2$]")
ax1.set_title(r"Mean-square displacement")
ax1.legend(fontsize=8.1)
ax2.semilogx(gle["t"][1:], alpha_curve, color="#C0392B", lw=2.3, label="Logarithmic slope $\\alpha$(t) = d ln(MSD) / d ln(t)")
ax2.axhline(1.0, color="k", ls=":", lw=1.2, label="Viscous diffusion limit ($\\alpha$ = 1)")
ax2.axhline(0.0, color="#6B7280", ls="--", lw=1.2, label="Elastic solid ($\\alpha$ = 0)")
ax2.set_xlabel("Lag time t [s]")
ax2.set_ylabel("Subdiffusive exponent $\\alpha$(t)")
ax2.set_title(r"Its logarithmic slope")
ax2.legend(fontsize=8.0, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=1)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. A probe of radius at moves in one dimension in a medium with one Maxwell mode and a solvent (). Derive the plateau of the mean-square displacement at intermediate times, , and its slope at long times, , and compare both with simulate_gle_thermal_probe.
heading("Exercise 1: plateau and long-time slope of the mean-square displacement")
a_j, kT_j, es_j = 0.5e-6, 4.11e-21, 2.0e-3
G0_j, tau1_j = 4.0, 0.25
t_j = np.concatenate([[0.0], np.geomspace(1e-4, 25.0, 120)])
gle_j = microrheology_rheoml.simulate_gle_thermal_probe([(G0_j, tau1_j)], t_j, probe_radius_a=a_j, kT=kT_j, eta_s=es_j, n_probes=1500, seed=11)
# Equipartition: at t >> zeta_s/k_1 and t << tau_1, bath dashpot y_1 is frozen at initial thermal spread N(0, kT/k_1)
# AND x equilibrates to y_1 with thermal variance kT/k_1 -> <x^2>_plat = 2 * (kT / k_1) = kT / (3 * pi * a * G_0)
msd_plat_exact = kT_j / (3.0 * math.pi * a_j * G0_j)
D_inf_exact = kT_j / (6.0 * math.pi * a_j * (es_j + G0_j * tau1_j))
idx_plat = int(np.argmin(np.abs(gle_j["t"] - 0.012)))
slope_long = float((gle_j["msd_exact"][-1] - gle_j["msd_exact"][-10]) / (gle_j["t"][-1] - gle_j["t"][-10]))
print(f"Analytical 1-D caging plateau kT/(3*pi*a*G0) : {msd_plat_exact*1e12:.5f} um^2 against GLE(12 ms) = {gle_j['msd_exact'][idx_plat]*1e12:.5f} um^2")
print(f"Analytical terminal slope 2*D_inf : {2*D_inf_exact*1e12:.5f} um^2/s against GLE(25 s) = {slope_long*1e12:.5f} um^2/s")
assert math.isclose(gle_j["msd_exact"][idx_plat], msd_plat_exact, rel_tol=0.08)
assert math.isclose(slope_long, 2.0 * D_inf_exact, rel_tol=1e-3)
fig, ax = plt.subplots(figsize=(7.4, 4.1))
ax.loglog(gle_j["t"][1:], gle_j["msd_exact"][1:] * 1e12, "k-", lw=2.3, label="Exact (generalized Langevin equation)")
ax.loglog(gle_j["t"][1::3], gle_j["msd_simulated"][1::3] * 1e12, "o", ms=4.2, color="#2166AC", label="Simulated Brownian probes")
ax.axhline(msd_plat_exact * 1e12, color="#C0392B", ls="--", lw=1.8, label="Plateau $k_BT/(3\\pi a G_0)$")
ax.loglog(gle_j["t"][40:], 2.0 * D_inf_exact * gle_j["t"][40:] * 1e12, ":", color="#0F766E", lw=2.2, label="Long-time diffusion $2D_\\infty t$")
ax.set_xlabel("Lag time t [s]")
ax.set_ylabel("Mean-square displacement $\\langle\\Delta x^2\\rangle$ [$\\mu$m$^2$]")
ax.set_title(r"Mean-square displacement in a single-mode medium")
ax.legend(fontsize=8.0)
plt.show()
Exercise 1: plateau and long-time slope of the mean-square displacement
=======================================================================
Analytical 1-D caging plateau kT/(3*pi*a*G0) : 0.00022 um^2 against GLE(12 ms) = 0.00023 um^2
Analytical terminal slope 2*D_inf : 0.00087 um^2/s against GLE(25 s) = 0.00087 um^2/s

Figure S16.1. Mean-square displacement of a probe in a Jeffreys medium: simulation and exact result, with the plateau and the long-time diffusion line.
Explanation. The Maxwell mode acts on the probe as a spring of stiffness attached to a point that itself relaxes. At intermediate times the probe has equilibrated in the spring and the attachment point has not yet moved, so that with . The simulation starts with and with drawn from its equilibrium distribution of variance ; the plateau is therefore , which is also the value given by the generalized Stokes–Einstein relation in one dimension. The simulation gives at 12 ms against , and a long-time slope of , equal to the formula to the two digits printed.
Exercise 2¶
Problem. (1) Compare the error of fit_naive_component_mlp and of fit_thermodynamic_tensor_rheoml on test data in the frame of the training data and in a frame rotated by . (2) Fit the weights of the tensor basis by ordinary least squares (np.linalg.lstsq, without the condition ) to noisy synthetic data at small stretch, and evaluate the dissipation in uniaxial stretch, , for between 1.1 and 3.2. Compare with the fit with non-negative weights.
heading("Exercise 2: a rotated frame, and a fit without the constraint of non-negative weights")
# Part A: Self-contained axis-aligned training set -> 42-deg rotation failure of naive MLP vs TC-RheoML:
rng_ex2 = np.random.default_rng(77)
C_ex2 = np.zeros((56, 3, 3))
tau_ex2 = np.zeros((56, 3, 3))
for idx_s in range(56):
ev_s = np.array([rng_ex2.uniform(1.1, 4.2), rng_ex2.uniform(0.42, 0.95), rng_ex2.uniform(0.65, 1.15)])
th_s = rng_ex2.uniform(-0.10, 0.10)
Qr_s = np.array([[math.cos(th_s), -math.sin(th_s), 0.0], [math.sin(th_s), math.cos(th_s), 0.0], [0.0, 0.0, 1.0]])
Ci_s = (Qr_s * ev_s[None, :]) @ Qr_s.T
C_ex2[idx_s] = Ci_s
tau_ex2[idx_s] = 2.40 * (Ci_s - np.eye(3)) + 0.35 * (float(np.trace(Ci_s)) - 3.0) * Ci_s + 0.18 * (Ci_s @ Ci_s - Ci_s)
tc_ex2 = microrheology_rheoml.fit_thermodynamic_tensor_rheoml(C_ex2, tau_ex2)
mlp_ex2 = microrheology_rheoml.fit_naive_component_mlp(C_ex2, tau_ex2, hidden_dim=24, seed=77)
rad42 = math.radians(42.0)
Q42 = np.array([[math.cos(rad42), -math.sin(rad42), 0.0], [math.sin(rad42), math.cos(rad42), 0.0], [0.0, 0.0, 1.0]])
C_rot42 = np.einsum("ij,njk,lk->nil", Q42, C_ex2, Q42)
tau_rot42 = np.einsum("ij,njk,lk->nil", Q42, tau_ex2, Q42)
rmse_mlp_0 = float(np.sqrt(np.mean((mlp_ex2(C_ex2) - tau_ex2) ** 2)))
rmse_mlp_42 = float(np.sqrt(np.mean((mlp_ex2(C_rot42) - tau_rot42) ** 2)))
rmse_tc_42 = float(np.sqrt(np.mean((tc_ex2["predict_fn"](C_rot42) - tau_rot42) ** 2)))
# Part B: Unconstrained OLS on noisy small-stretch Neo-Hookean data -> negative cubic weight w_4 < 0
rng_n = np.random.default_rng(5)
C_small = np.array([np.diag([1.0 + 0.25 * k, 0.92, 0.95]) for k in range(1, 9)])
tau_noisy = 2.0 * (C_small - np.eye(3)[None, :, :])
# Perturb largest training sample downward so unconstrained polynomial fit bends downward (w_4 < 0):
tau_noisy[-1] -= 0.45 * C_small[-1]
_, T_st = microrheology_rheoml._basis_potentials_and_stresses(C_small)
X_ols = np.transpose(T_st, (0, 2, 3, 1)).reshape(-1, 4)
w_ols, *_ = np.linalg.lstsq(X_ols, tau_noisy.reshape(-1), rcond=None)
tc_safe = microrheology_rheoml.fit_thermodynamic_tensor_rheoml(C_small, tau_noisy)
lams_hi = np.linspace(1.1, 3.2, 40)
diss_ols, diss_nnls = [], []
for lv in lams_hi:
Ch = np.diag([lv**2, 1.0 / lv, 1.0 / lv])
_, Ts_h = microrheology_rheoml._basis_potentials_and_stresses(Ch[None, :, :])
tau_o = np.tensordot(Ts_h[0], w_ols, axes=([0], [0]))
tau_n = tc_safe["predict_fn"](Ch)
cinv = np.linalg.inv(Ch)
diss_ols.append(float(np.sum(tau_o * (np.eye(3) - cinv))))
diss_nnls.append(float(np.sum(tau_n * (np.eye(3) - cinv))))
print(f"Component-wise network RMSE: 0 deg = {rmse_mlp_0:.4f} Pa -> 42 deg = {rmse_mlp_42:.4f} Pa ({rmse_mlp_42/rmse_mlp_0:.1f}x jump)")
print(f"Tensor-basis model RMSE: 42 deg = {rmse_tc_42:.4f} Pa (invariant)")
print(f"Unconstrained OLS weights : {np.round(w_ols, 3)} -> min dissipation = {min(diss_ols):.2f} (negative)")
print(f"Tensor-basis model NNLS weights : {np.round(tc_safe['weights'], 3)} -> min dissipation = {min(diss_nnls):.2f} (non-negative)")
assert rmse_mlp_42 > 15.0 * rmse_mlp_0
assert min(diss_ols) < -1.0
assert min(diss_nnls) >= 0.0
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 3.9))
ax1.bar(["Network,\nnot rotated", "Network,\nrotated 42 degrees", "Tensor-basis model,\nrotated 42 degrees"], [rmse_mlp_0, rmse_mlp_42, rmse_tc_42], color=["#A9C9E8", "#C0392B", "#2166AC"], width=0.48)
ax1.set_ylabel("Stress prediction RMSE [Pa]")
ax1.set_title(r"Error before and after rotation")
ax2.plot(lams_hi, diss_ols, "--", color="#C0392B", lw=2.2, label="Unconstrained least squares (negative dissipation)")
ax2.plot(lams_hi, diss_nnls, "-", color="#0F766E", lw=2.3, label="Tensor-basis model, $w_k \\geq 0$")
ax2.axhline(0.0, color="k", ls=":", lw=1.3)
ax2.set_xlabel("Extrapolated uniaxial stretch $\\lambda_E$")
ax2.set_ylabel("Dissipation measure $\\mathrm{tr}[\\tau_p(\\mathbf{I}-\\mathbf{C}^{-1})]$")
ax2.set_title(r"Dissipation in extrapolation")
ax2.legend(fontsize=7.9)
label_panels(fig)
plt.show()
Exercise 2: a rotated frame, and a fit without the constraint of non-negative weights
=====================================================================================
Component-wise network RMSE: 0 deg = 0.0048 Pa -> 42 deg = 1.4976 Pa (310.3x jump)
Tensor-basis model RMSE: 42 deg = 0.0000 Pa (invariant)
Unconstrained OLS weights : [ 1.798 0.338 0.087 -0.285] -> min dissipation = -89.64 (negative)
Tensor-basis model NNLS weights : [1.794 0. 0. 0. ] -> min dissipation = 0.10 (non-negative)

Figure S16.2. (a) Root-mean-square error of the component-wise network in the training frame and after a rotation by 42°, and of the tensor-basis model after the rotation. (b) Dissipation rate against stretch beyond the training range: negative for unconstrained least squares, positive for non-negative weights.
Explanation. The network that maps components to components has an error of 0.005 Pa in the frame of its training data and 1.50 Pa after a rotation by , 310 times larger: nothing in it expresses that the stress must rotate with the conformation tensor. The tensor-basis model has this property by construction, and its error does not change. The unconstrained fit returns the weights (1.798, 0.338, 0.087, -0.285); the negative weight of the highest term has no visible effect at small stretch and makes the dissipation negative at large stretch, down to -89.6 at . The fit with non-negative weights returns (1.794, 0, 0, 0), and its dissipation stays positive (the smallest value is 0.10). A stress model with negative dissipation inside a flow solver adds energy to the flow.
Exercise 3¶
Problem. Combine the log-conformation equation with a fitted stress model. Generate training data with entangled_tubes.solve_fenep_fenecr(..., b_ext=28.0, variant="fenep") at the shear rates , fit the tensor-basis model for , then integrate at the shear rate , which is outside the training data, with the relaxation term , and compare with the FENE-P model.
heading("Exercise 3: the log-conformation equation with a fitted stress model")
t_tr = np.linspace(0.0, 5.0, 121)
snaps_C, snaps_tau = [], []
for g_tr in [1.0, 2.5]:
L_g = np.array([[0.0, g_tr, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
fp_tr = entangled_tubes.solve_fenep_fenecr(lambda _t, L=L_g: L, t_tr, lam=1.0, eta_p=2.0, b_ext=28.0, variant="fenep")
snaps_C.append(fp_tr["C"][1::3])
snaps_tau.append(fp_tr["tau_p"][1::3])
C_tr_all = np.concatenate(snaps_C, axis=0)
tau_tr_all = np.concatenate(snaps_tau, axis=0)
tc_fenep = microrheology_rheoml.fit_thermodynamic_tensor_rheoml(C_tr_all, tau_tr_all)
# Integrate unseen startup shear at gdot_test = 3.4 in Log-Conformation space using learned TC-RheoML stress
g_test = 3.4
L_test_m = np.array([[0.0, g_test, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
fp_truth = entangled_tubes.solve_fenep_fenecr(lambda _t: L_test_m, t_tr, lam=1.0, eta_p=2.0, b_ext=28.0, variant="fenep")
G0_est = float(np.sum(tc_fenep["weights"][:1])) # Leading Neo-Hookean modulus ~ G0
G0_true = 2.0 # eta_p / lam
def rhs_hybrid_psi(Psi_m: np.ndarray) -> np.ndarray:
C_m = tensors_kinematics.exp_conformation(Psi_m)
dec = tensors_kinematics.log_conformation_decompose(C_m, L_test_m)
tau_pred = tc_fenep["predict_fn"](C_m)
# In FENE-P, dC/dt_rel = -(tau_p / G0) / lam
rel_C = -tau_pred / G0_true
ev, R = dec["eigenvalues"], dec["eigenvectors"]
rel_psi = R @ ((1.0 / ev)[:, None] * (R.T @ rel_C @ R)) @ R.T
out = dec["dPsi_dt_kinematic"] + 0.5 * (rel_psi + rel_psi.T)
return 0.5 * (out + out.T)
Psi_cur = np.zeros((3, 3))
tau_hyb = np.zeros((t_tr.size, 3, 3))
for k in range(t_tr.size - 1):
dt = float(t_tr[k + 1] - t_tr[k])
k1 = rhs_hybrid_psi(Psi_cur)
k2 = rhs_hybrid_psi(Psi_cur + 0.5 * dt * k1)
Psi_cur = Psi_cur + dt * k2
tau_hyb[k + 1] = tc_fenep["predict_fn"](tensors_kinematics.exp_conformation(Psi_cur))
rel_err_txy = float(np.linalg.norm(tau_hyb[:, 0, 1] - fp_truth["tau_p"][:, 0, 1]) / np.linalg.norm(fp_truth["tau_p"][:, 0, 1]))
rel_err_n1 = float(np.linalg.norm((tau_hyb[:, 0, 0] - tau_hyb[:, 1, 1]) - (fp_truth["tau_p"][:, 0, 0] - fp_truth["tau_p"][:, 1, 1])) / np.linalg.norm(fp_truth["tau_p"][:, 0, 0] - fp_truth["tau_p"][:, 1, 1]))
print(f"Tensor-basis model fit R^2 on FENE-P training trajectories : {tc_fenep['r2_score']:.5f}")
print(f"Unseen Wi = {g_test} start-up of shear stress rel L2 err : {rel_err_txy:.4f}")
print(f"Unseen Wi = {g_test} startup N1(t) rel L2 err : {rel_err_n1:.4f}")
assert tc_fenep["r2_score"] > 0.995
assert rel_err_txy < 0.08
assert rel_err_n1 < 0.10
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 3.9))
ax1.plot(t_tr, fp_truth["tau_p"][:, 0, 1], "k-", lw=2.3, label="Exact FENE-P (unseen Wi = 3.4)")
ax1.plot(t_tr[::3], tau_hyb[::3, 0, 1], "o", ms=4.5, color="#2166AC", label="Log-conformation with tensor-basis model")
ax1.set_xlabel("Time t [s]"); ax1.set_ylabel("Shear stress $\\tau_{xy}$(t) [Pa]")
ax1.set_title(r"Shear stress")
ax1.legend(fontsize=8.0)
ax2.plot(t_tr, fp_truth["tau_p"][:, 0, 0] - fp_truth["tau_p"][:, 1, 1], "k-", lw=2.3, label="Exact FENE-P $N_1$(t)")
ax2.plot(t_tr[::3], tau_hyb[::3, 0, 0] - tau_hyb[::3, 1, 1], "s", ms=4.5, color="#C0392B", label="Log-conformation with tensor-basis model")
ax2.set_xlabel("Time t [s]"); ax2.set_ylabel("First normal stress $N_1$(t) [Pa]")
ax2.set_title(r"First normal stress difference")
ax2.legend(fontsize=8.0)
label_panels(fig)
plt.show()
Exercise 3: the log-conformation equation with a fitted stress model
====================================================================
Tensor-basis model fit R^2 on FENE-P training trajectories : 1.00000
Unseen Wi = 3.4 start-up of shear stress rel L2 err : 0.0035
Unseen Wi = 3.4 startup N1(t) rel L2 err : 0.0057

Figure S16.3. Log-conformation integration with the fitted stress model at , which was not in the training data, against the FENE-P model. (a) Shear stress. (b) First normal stress difference.
Explanation. The kinematic part of the equation, , is known exactly and is not fitted; only the function is. The conformation tensor then stays positive definite, and the model frame indifferent, whatever the fit. The fit reproduces the training data (), and at the shear rate 3.4 the predicted start-up differs from the FENE-P model by 0.35 % in the shear stress and by 0.57 % in (relative norm). The test is a favourable one: the data come from a model whose stress is a function of alone, and the new rate is 36 % above the largest rate of the training data.