The moduli and of a sample of a few microlitres cannot be measured in a rheometer. Mason and Weitz (1995) showed that they can be obtained from the thermal motion of a small probe particle: the mean-square displacement of the probe is related to the modulus of the medium by a generalized Stokes–Einstein relation. The first half of this lecture simulates a probe in a viscoelastic medium and recovers the moduli.
The second half concerns stress models fitted to data. A neural network that maps the components of to the components of the stress can fit its training data closely and still fail when the axes are rotated, because nothing in it expresses frame indifference. A model built on a tensor basis, as the derivative of a free energy with non-negative weights, is frame indifferent and has non-negative dissipation by construction. The data used in this lecture are synthetic.
Learning objectives¶
Simulate a probe particle in a medium with several Maxwell modes, with one auxiliary variable for each mode.
Obtain and from the mean-square displacement with the local power-law form of the generalized Stokes–Einstein relation (Mason, 2000), and check for a power law.
Write a stress model on a tensor basis, with weights .
Compare this model with a network that maps components to components (
fit_naive_component_mlp) under a rotation of the axes.
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. A probe particle in a viscoelastic medium¶
A spherical probe of radius , without inertia, moves in a medium that consists of a solvent of viscosity and Maxwell modes . Its position obeys a generalized Langevin equation with a memory kernel. The equation is equivalent to a system of equations without memory, in which each mode is a spring of stiffness whose other end moves against the friction (microrheology_rheoml.simulate_gle_thermal_probe):
The system is linear. After a symmetrizing transformation with the friction matrix its normal modes give the exact mean-square displacement and an exact update over a time step of any size, so that five decades of time can be covered. The mean-square displacement has three regimes, described by the local exponent :
Short times, : diffusion in the solvent, and .
Intermediate times, : the elastic modes hold the probe, the mean-square displacement has a plateau, and .
Long times, : diffusion with the coefficient , set by the zero-shear viscosity, and .
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()
Demonstration 1: mean-square displacement of a probe over five decades of time
==============================================================================
Ensemble against exact normal-mode MSD mean relative error : 0.0326
Minimum subdiffusive caging slope min d(ln MSD)/d(ln t): 0.0304
Terminal logarithmic slope at t = 10 s : 0.8951

Figure 16.1. A probe in a viscoelastic medium. (a) Mean-square displacement of 1800 simulated probes against the exact result. (b) Logarithmic slope of the exact result: near 1 at short times, 0.03 at its minimum, rising again at long times.
2. Moduli from the mean-square displacement¶
The moduli follow from the Laplace transform of the mean-square displacement, which is difficult to compute from noisy data. Mason (2000) approximated the mean-square displacement around the time by a power law, with between 0 and 1. This gives algebraic formulas for the moduli, in , 2 or 3 dimensions:
The formulas give . Where (the plateau), and the medium responds as an elastic solid; where (diffusion), and it responds as a viscous liquid.
heading("Demonstration 2: moduli from the generalized Stokes-Einstein relation against the exact moduli")
gser_ex = microrheology_rheoml.mason_gser_moduli(gle["t"][1:], gle["msd_exact"][1:], probe_radius_a=0.5e-6, kT=4.11e-21, dim=1)
gser_sim = microrheology_rheoml.mason_gser_moduli(gle["t"][1:], gle["msd_simulated"][1:], probe_radius_a=0.5e-6, kT=4.11e-21, dim=1)
om = gser_ex["omega"]
gp_mech = sum(g * ((om * tau) ** 2) / (1.0 + (om * tau) ** 2) for g, tau in modes_gel)
gpp_mech = 3.0e-3 * om + sum(g * (om * tau) / (1.0 + (om * tau) ** 2) for g, tau in modes_gel)
plat_mask = (om > 12.0) & (om < 80.0)
plat_rel_err = float(np.mean(np.abs(gser_ex["G_prime"][plat_mask] - gp_mech[plat_mask]) / gp_mech[plat_mask]))
print(f"Local Kramers-Kronig |G''/G' - tan(pi*alpha/2)| error : {gser_ex['kramers_kronig_tan_err']:.3e}")
print(f"Plateau storage modulus G'(omega) mean error against exact : {plat_rel_err:.4f}")
print(f"Terminal regime liquid check G''(0.2) > G'(0.2) : {gser_ex['G_double_prime'][3]:.3f} > {gser_ex['G_prime'][3]:.3f} Pa")
assert gser_ex["kramers_kronig_tan_err"] < 1e-13
assert plat_rel_err < 0.12
assert bool(np.all(gser_ex["G_prime"][plat_mask] > gser_ex["G_double_prime"][plat_mask]))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
ax1.loglog(om, gp_mech, "k-", lw=2.1, label="Exact mechanical $G'$($\\omega$)")
ax1.loglog(om, gpp_mech, "k--", lw=1.9, label="Exact mechanical $G''$($\\omega$)")
ax1.loglog(om[::2], gser_ex["G_prime"][::2], "o", ms=4.5, color="#2166AC", label="Mason GSER $G'$($\\omega$) [exact MSD]")
ax1.loglog(om[::2], gser_ex["G_double_prime"][::2], "s", ms=4.2, color="#C0392B", label="Mason GSER $G''$($\\omega$) [exact MSD]")
ax1.set_xlabel("Angular frequency $\\omega$ = 1/t [rad/s]")
ax1.set_ylabel("Viscoelastic moduli $G'$, $G''$ [Pa]")
ax1.set_title(r"Moduli from the exact displacement")
ax1.legend(fontsize=7.8)
ax2.loglog(om, gp_mech, "k-", lw=1.8, alpha=0.7, label="Exact $G'$($\\omega$)")
ax2.loglog(gser_sim["omega"][::2], gser_sim["G_prime"][::2], "^", ms=4.5, color="#0F766E", label="Finite ensemble, GSER $G'$")
ax2.loglog(gser_sim["omega"][::2], gser_sim["G_double_prime"][::2], "v", ms=4.5, color="#E08214", label="Finite ensemble, GSER $G''$")
ax2.set_xlabel("Angular frequency $\\omega$ [rad/s]")
ax2.set_ylabel("Recovered moduli [Pa]")
ax2.set_title(r"Moduli from the simulated displacement")
ax2.legend(fontsize=8.0)
label_panels(fig)
plt.show()
Demonstration 2: moduli from the generalized Stokes-Einstein relation against the exact moduli
==============================================================================================
Local Kramers-Kronig |G''/G' - tan(pi*alpha/2)| error : 1.776e-15
Plateau storage modulus G'(omega) mean error against exact : 0.0663
Terminal regime liquid check G''(0.2) > G'(0.2) : 0.265 > 0.066 Pa

Figure 16.2. Moduli from the generalized Stokes–Einstein relation in Mason’s form. (a) From the exact mean-square displacement, against the moduli of the medium; the method is approximate where the slope changes quickly. (b) From the simulated probes, where the noise is amplified.
3. A stress model on a tensor basis with non-negative weights¶
Suppose that simulations of the microstructure provide pairs of the conformation tensor and the polymer stress. A function fitted to them should satisfy three conditions, for every positive definite and every rotation :
Zero stress at equilibrium and symmetry: and .
Frame indifference: .
Non-negative dissipation (Grmela and Öttinger, 1997). If the stress is derived from a free energy that is a sum of convex functions of the invariants with non-negative weights, with , through
then the dissipation, which is proportional to , is non-negative for every positive definite .
heading("Demonstration 3: fit of a tensor-basis stress model to synthetic data")
rng_tc = np.random.default_rng(77)
n_samples = 64
C_data = np.zeros((n_samples, 3, 3))
tau_data = np.zeros((n_samples, 3, 3))
true_w = np.array([2.40, 0.35, 0.18, 0.04])
# Generate training data restricted to small angles near laboratory shear axes (+/- 6 deg) with slight measurement noise:
for i in range(n_samples):
ev = np.array([rng_tc.uniform(1.1, 4.2), rng_tc.uniform(0.42, 0.95), rng_tc.uniform(0.65, 1.15)])
th = rng_tc.uniform(-0.10, 0.10)
Qr = np.array([[math.cos(th), -math.sin(th), 0.0], [math.sin(th), math.cos(th), 0.0], [0.0, 0.0, 1.0]])
Ci = (Qr * ev[None, :]) @ Qr.T
s1 = float(np.trace(Ci)) - 3.0
noise = rng_tc.normal(0.0, 0.015, size=(3, 3))
noise = 0.5 * (noise + noise.T)
C_data[i] = Ci
tau_data[i] = (
true_w[0] * (Ci - np.eye(3))
+ true_w[1] * s1 * Ci
+ true_w[2] * (Ci @ Ci - Ci)
+ true_w[3] * (s1**2) * Ci
+ noise
)
tc_fit = microrheology_rheoml.fit_thermodynamic_tensor_rheoml(C_data, tau_data)
print(f"True basis weights w_true : {true_w}")
print(f"Learned NNLS weights w_hat : {np.round(tc_fit['weights'], 4)}")
print(f"Training R^2 score : {tc_fit['r2_score']:.6f}")
print(f"SO(3) equivariance error : {tc_fit['rotation_equivariance_err']:.3e}")
print(f"Min Clausius-Duhem rate >= 0 : {tc_fit['min_dissipation_rate']:.4f} (admissible = {tc_fit['is_thermodynamically_admissible']})")
assert tc_fit["r2_score"] > 0.999
assert tc_fit["is_thermodynamically_admissible"]
assert np.linalg.norm(tc_fit["weights"] - true_w) < 0.05
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 3.9))
ax1.scatter(tau_data.ravel(), tc_fit["predicted_tau"].ravel(), s=16, alpha=0.65, color="#2166AC", label=f"Tensor-basis model (R$^2$ = {tc_fit['r2_score']:.5f})")
lims = [float(np.min(tau_data)), float(np.max(tau_data))]
ax1.plot(lims, lims, "k--", lw=1.6, label="y = x")
ax1.set_xlabel("Ground-truth noisy stress components $\\tau_{ij}$ [Pa]")
ax1.set_ylabel("Tensor-basis model predicted stress components [Pa]")
ax1.set_title(r"Fitted against given stress components")
ax1.legend(fontsize=8.2)
x_idx = np.arange(4)
ax2.bar(x_idx - 0.17, true_w, width=0.34, color="#0F766E", label="Ground-truth potential weights")
ax2.bar(x_idx + 0.17, tc_fit["weights"], width=0.34, color="#2166AC", label="Fitted weights ($w_k \\geq 0$)")
ax2.set_xticks(x_idx, [r"$\mathbf{C}-\mathbf{I}$", r"$(I_1-3)\mathbf{C}$", r"$\mathbf{C}^2-\mathbf{C}$", r"$(I_1-3)^2\mathbf{C}$"])
ax2.set_ylabel("Potential coefficient $w_k$ [Pa]")
ax2.set_title(r"Weights of the four basis tensors")
ax2.legend(fontsize=8.1)
label_panels(fig)
plt.show()
Demonstration 3: fit of a tensor-basis stress model to synthetic data
=====================================================================
True basis weights w_true : [2.4 0.35 0.18 0.04]
Learned NNLS weights w_hat : [2.4056 0.3487 0.1773 0.041 ]
Training R^2 score : 0.999979
SO(3) equivariance error : 1.986e-15
Min Clausius-Duhem rate >= 0 : 0.3660 (admissible = True)

Figure 16.3. Fit of four non-negative weights of a tensor basis to synthetic stress data with noise. (a) Fitted against given stress components. (b) Recovered weights against the weights used to make the data.
4. Rotation of the axes: tensor-basis model against component-wise network¶
The function fit_thermodynamic_tensor_rheoml is now compared with a network that maps the nine components to the nine components (fit_naive_component_mlp). Both are fitted to the same synthetic data C_data, tau_data, in which the principal axes of are close to the coordinate axes, and both have a small error on these data. The demonstration then rotates the principal axes by an angle between and , as happens to a fluid element along a curved streamline, and measures how far each model departs from .
heading("Demonstration 4: rotation of the axes from 0 to 180 degrees")
mlp_fn = microrheology_rheoml.fit_naive_component_mlp(C_data, tau_data, hidden_dim=24, seed=77)
pred_mlp_train = mlp_fn(C_data)
r2_mlp_train = 1.0 - float(np.sum((tau_data - pred_mlp_train) ** 2) / np.sum((tau_data - np.mean(tau_data)) ** 2))
C_probe = np.diag([3.9, 0.48, 0.85])
angles_deg = np.linspace(0.0, 180.0, 46)
eq_err_tc, eq_err_mlp = [], []
for deg in angles_deg:
rad = math.radians(float(deg))
Qr = np.array([[math.cos(rad), -math.sin(rad), 0.0], [math.sin(rad), math.cos(rad), 0.0], [0.0, 0.0, 1.0]])
C_rot = Qr @ C_probe @ Qr.T
eq_err_tc.append(float(np.linalg.norm(tc_fit["predict_fn"](C_rot) - Qr @ tc_fit["predict_fn"](C_probe) @ Qr.T, ord="fro")) + 1e-16)
eq_err_mlp.append(float(np.linalg.norm(mlp_fn(C_rot) - Qr @ mlp_fn(C_probe) @ Qr.T, ord="fro")) + 1e-16)
idx_42 = int(np.argmin(np.abs(angles_deg - 42.0)))
print(f"Component-wise network in-frame training R^2 : {r2_mlp_train:.5f} (data aligned with the axes)")
print(f"Equivariance error at ~42 deg: MLP = {eq_err_mlp[idx_42]:.4f} Pa against tensor-basis model = {eq_err_tc[idx_42]:.2e} Pa")
assert r2_mlp_train > 0.99
assert eq_err_mlp[idx_42] > 0.25
assert max(eq_err_tc) < 1e-12
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
ax1.semilogy(angles_deg, eq_err_mlp, color="#C0392B", lw=2.3, label="Component-wise network")
ax1.semilogy(angles_deg, eq_err_tc, color="#2166AC", lw=2.3, label="Tensor-basis model (below $10^{-14}$)")
ax1.axvline(42.0, color="k", ls=":", lw=1.3, label="Rotation by 42 degrees")
ax1.set_xlabel("Observer rotation angle $\\theta$ [degrees]")
ax1.set_ylabel("Departure from frame indifference [Pa]")
ax1.set_title(r"Error of rotational equivariance")
ax1.legend(fontsize=7.9)
# Unseen uniaxial elongation stretch lambda_ext in [1.0, 2.2] oriented at 42 degrees
lams_ext = np.linspace(1.0, 2.1, 30)
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]])
n1_true_42, n1_tc_42, n1_mlp_42 = [], [], []
for le in lams_ext:
C_u = np.diag([le**2, 1.0 / le, 1.0 / le])
s1 = float(np.trace(C_u)) - 3.0
tau_u_true = true_w[0] * (C_u - np.eye(3)) + true_w[1] * s1 * C_u + true_w[2] * (C_u @ C_u - C_u) + true_w[3] * (s1**2) * C_u
C_u42 = Q42 @ C_u @ Q42.T
tau_tc_u = Q42.T @ tc_fit["predict_fn"](C_u42) @ Q42
tau_mlp_u = Q42.T @ mlp_fn(C_u42) @ Q42
n1_true_42.append(float(tau_u_true[0, 0] - tau_u_true[1, 1]))
n1_tc_42.append(float(tau_tc_u[0, 0] - tau_tc_u[1, 1]))
n1_mlp_42.append(float(tau_mlp_u[0, 0] - tau_mlp_u[1, 1]))
ax2.plot(lams_ext, n1_true_42, "k-", lw=2.3, label="Exact rotated uniaxial tension")
ax2.plot(lams_ext[::2], n1_tc_42[::2], "o", ms=5.0, color="#2166AC", label="Tensor-basis model prediction at 42 degrees")
ax2.plot(lams_ext, n1_mlp_42, "--", color="#C0392B", lw=2.1, label="Component-wise network prediction at 42 degrees")
ax2.set_xlabel("Uniaxial stretch ratio $\\lambda_E$")
ax2.set_ylabel("Principal tensile stress difference $\\tau_{11}$ - $\\tau_{22}$ [Pa]")
ax2.set_title(r"Uniaxial extension rotated by 42°")
ax2.legend(fontsize=8.0)
label_panels(fig)
plt.show()
Demonstration 4: rotation of the axes from 0 to 180 degrees
===========================================================
Component-wise network in-frame training R^2 : 0.99998 (data aligned with the axes)
Equivariance error at ~42 deg: MLP = 13.8789 Pa against tensor-basis model = 4.28e-15 Pa

Figure 16.4. (a) Norm of against the rotation angle for the component-wise network and for the tensor-basis model. (b) Principal stress difference in uniaxial extension rotated by 42°: the tensor-basis model follows the exact curve, the network does not.
Inside the algorithm: Mason’s relation for a power-law medium¶
The cell below prints the source of microrheology_rheoml.mason_gser_moduli and checks it on a medium with a power-law mean-square displacement, for which Mason’s relation is exact.
Check against the package¶
In a medium at the gel point the mean-square displacement of a probe is a power law at all times, with , and the moduli are known in closed form:
Because is linear in , the local power-law approximation is exact for such a medium, and the function reproduces these moduli to rounding error (< 1e-14).
heading("Inside the algorithm: Mason's relation for a power-law medium")
print(show_source(microrheology_rheoml.mason_gser_moduli))
alpha_gel = 0.62
A_gel = 2.5e-13
a_p, kT_p = 0.5e-6, 4.11e-21
t_pow = np.geomspace(1e-3, 1e1, 41)
msd_pow = A_gel * (t_pow**alpha_gel)
gser_gel = microrheology_rheoml.mason_gser_moduli(t_pow, msd_pow, probe_radius_a=a_p, kT=kT_p, dim=1)
om_g = gser_gel["omega"]
pref = kT_p / (3.0 * math.pi * a_p * A_gel * math.gamma(1.0 + alpha_gel))
gp_exact_gel = pref * (om_g**alpha_gel) * math.cos(0.5 * math.pi * alpha_gel)
gpp_exact_gel = pref * (om_g**alpha_gel) * math.sin(0.5 * math.pi * alpha_gel)
err_gp_gel = float(np.max(np.abs(gser_gel["G_prime"] - gp_exact_gel)))
err_gpp_gel = float(np.max(np.abs(gser_gel["G_double_prime"] - gpp_exact_gel)))
print(f"Critical gel (alpha = {alpha_gel}) |G'_GSER - G'_exact|_inf : {err_gp_gel:.3e} Pa")
print(f"Critical gel (alpha = {alpha_gel}) |G''_GSER - G''_exact|_inf : {err_gpp_gel:.3e} Pa")
assert np.allclose(gser_gel["G_prime"], gp_exact_gel, rtol=1e-13, atol=1e-14)
assert np.allclose(gser_gel["G_double_prime"], gpp_exact_gel, rtol=1e-13, atol=1e-14)
Inside the algorithm: Mason's relation for a power-law medium
=============================================================
def mason_gser_moduli(
t_lag: np.ndarray,
msd: np.ndarray,
probe_radius_a: float = 0.5e-6,
kT: float = 4.11e-21,
dim: int = 1,
) -> dict:
"""G'(omega) and G''(omega) from a mean-square displacement with the local power-law relation of Mason (2000)."""
t = np.asarray(t_lag, dtype=float).ravel()
m = np.asarray(msd, dtype=float).ravel()
mask = (t > 0.0) & (m > 0.0)
t_p = t[mask]
m_p = m[mask]
if t_p.size < 5 or probe_radius_a <= 0.0 or kT <= 0.0 or dim not in (1, 2, 3):
raise ValueError("Require >= 5 positive lag times/MSD points, probe_radius_a > 0, kT > 0, and dim in {1,2,3}.")
log_t = np.log(t_p)
log_m = np.log(m_p)
# Central finite-difference logarithmic slope alpha(omega = 1/t) = d(ln MSD)/d(ln t) in [0, 1]:
alpha = np.clip(np.gradient(log_m, log_t), 1e-4, 0.9999)
omega = 1.0 / t_p
gamma_val = np.array([math.gamma(1.0 + float(al)) for al in alpha])
# In d dimensions, <Delta r^2(t)> = (d * kT) / (3 * pi * a * |G*(omega)| * Gamma(1 + alpha)):
g_abs = (float(dim) * float(kT)) / (3.0 * math.pi * float(probe_radius_a) * m_p * gamma_val)
g_prime = g_abs * np.cos(0.5 * math.pi * alpha)
g_double_prime = g_abs * np.sin(0.5 * math.pi * alpha)
# Local Kramers-Kronig consistency check: tan(delta) == G'' / G' == tan(pi * alpha / 2):
kk_err = float(np.max(np.abs((g_double_prime / np.maximum(g_prime, 1e-30)) - np.tan(0.5 * math.pi * alpha))))
order = np.argsort(omega)
return {
"omega": omega[order],
"G_prime": g_prime[order],
"G_double_prime": g_double_prime[order],
"alpha_log_slope": alpha[order],
"kramers_kronig_tan_err": kk_err,
}
Critical gel (alpha = 0.62) |G'_GSER - G'_exact|_inf : 3.109e-15 Pa
Critical gel (alpha = 0.62) |G''_GSER - G''_exact|_inf : 1.693e-15 Pa
Exercises¶
Worked solutions are in 16_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. 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.Find how it fails. (1) Compare the error of
fit_naive_component_mlpand offit_thermodynamic_tensor_rheomlon 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.Implement it yourself. 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("Self-check for the exercises")
assert rel_err_msd < 0.08
assert gser_ex["kramers_kronig_tan_err"] < 1e-13
assert tc_fit["is_thermodynamically_admissible"]
assert eq_err_mlp[idx_42] > 0.25 and max(eq_err_tc) < 1e-12
assert err_gp_gel < 1e-12
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.