Solutions · 15. Lees–Edwards shear, dissipative particle dynamics and discontinuous shear thickening
Worked solutions to the three exercises of Lecture 15. 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: Lees-Edwards boundaries and dissipative particle dynamics in shear")
# 1. Exact check of Lees-Edwards cross-boundary displacement & velocity jump:
r_le, v_le = mesoscopic_suspensions_dpd.lees_edwards_minimum_image(
pos_i=np.array([1.2, 6.8]), pos_j=np.array([1.2, 0.3]),
vel_i=np.array([4.2, 0.0]), vel_j=np.array([0.0, 0.0]),
box_L=7.0, shear_rate=0.6, strain_gamma=0.25
)
print(f"Cross-boundary LE minimum image: r_ij = {np.round(r_le, 4)}, v_ij = {np.round(v_le, 4)}")
# 2. Simulate 2-D DPD fluid under steady Lees-Edwards simple shear:
dpd_res = mesoscopic_suspensions_dpd.simulate_dpd_shear_2d(
n_particles=72, box_L=6.2, shear_rate=0.65, a_rep=15.0, gamma_diss=4.5, kT_target=1.0, dt=0.02, n_steps=180, seed=42
)
corr_vx = float(np.corrcoef(dpd_res["y_bins"], dpd_res["velocity_profile_x"])[0, 1])
print(f"Mean kinetic temperature <kT_kin> (target 1.00) : {dpd_res['kinetic_temperature_mean']:.4f}")
print(f"Total peculiar momentum drift ||sum p_pec|| : {dpd_res['momentum_drift_norm']:.3e}")
print(f"Linear shear profile correlation r(y, vx) : {corr_vx:.4f}")
print(f"Irving-Kirkwood DPD shear viscosity eta : {dpd_res['shear_viscosity']:.4f}")
assert np.allclose(r_le, np.array([-1.75, -0.5]), atol=1e-12)
assert np.allclose(v_le, np.array([0.0, 0.0]), atol=1e-12)
assert dpd_res["momentum_drift_norm"] < 1e-11
assert 0.80 <= dpd_res["kinetic_temperature_mean"] <= 1.25
assert corr_vx > 0.92
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 3.9))
ax1.plot(dpd_res["expected_linear_vx"], dpd_res["y_bins"], "k--", lw=1.9, label="Exact, $\\dot{\\gamma}(y - L/2)$")
ax1.plot(dpd_res["velocity_profile_x"], dpd_res["y_bins"], "o-", color="#2166AC", lw=2.2, ms=6, label="Lees-Edwards DPD streaming velocity")
ax1.set_xlabel("Mean velocity $\\langle v_x\\rangle(y)$")
ax1.set_ylabel("Vertical coordinate y")
ax1.set_title(r"Mean velocity profile")
ax1.legend(fontsize=8.0)
# Illustrate sliding-brick image shifts across strain gamma in [0, 1):
gammas = np.linspace(0.0, 0.95, 30)
dx_shifts = [mesoscopic_suspensions_dpd.lees_edwards_minimum_image([1.0, 6.9], [1.0, 0.1], [0.0, 0.0], [0.0, 0.0], 7.0, 0.65, float(g))[0][0] for g in gammas]
ax2.plot(gammas, dx_shifts, "s-", color="#0F766E", ms=4.2, lw=2.0)
ax2.axhline(0.0, color="k", ls=":", lw=1.1)
ax2.set_xlabel("Shear strain $\\gamma = \\dot{\\gamma}t$")
ax2.set_ylabel("Minimum-image horizontal shift $r_{ij,x}$")
ax2.set_title(r"Horizontal separation of a pair across the boundary")
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. In the Wyart–Cates model with and , find the volume fraction above which the flow curve is S-shaped (discontinuous shear thickening) and below which the thickening is continuous. Compute the minimum over the stress of for from the analytical derivative, and check the change of sign with wyart_cates_dst_flow_curve.
heading("Exercise 1: the onset volume fraction of discontinuous shear thickening")
phi0, phim = 0.64, 0.55
# Dimensionless stress s = tau / tau*: f(s) = exp(-1/s), df/ds = f(s)/s^2, dphi_J/ds = (phim - phi0)*df/ds < 0
# gdot ~ s * (1 - phi/phi_J)^2 -> d(ln gdot)/d(ln s) = 1 + 2 * s * (phi / (phi_J * (phi_J - phi))) * dphi_J/ds
s_dense = np.logspace(-1.2, 2.0, 4000)
f_s = np.exp(-1.0 / s_dense)
phi_j = f_s * phim + (1.0 - f_s) * phi0
dphij_dlns = (phim - phi0) * f_s / s_dense # s * df/ds = exp(-1/s) / s
phis_scan = np.linspace(0.49, 0.548, 220)
min_dln_rate = np.array([
float(np.min(1.0 + 2.0 * ph * dphij_dlns / (phi_j * (phi_j - ph))))
for ph in phis_scan
])
phi_dst_crit = float(np.interp(0.0, min_dln_rate[::-1], phis_scan[::-1]))
wc_below = mesoscopic_suspensions_dpd.wyart_cates_dst_flow_curve(s_dense * 18.0, phi=phi_dst_crit - 0.004, phi_0=phi0, phi_m=phim)
wc_above = mesoscopic_suspensions_dpd.wyart_cates_dst_flow_curve(s_dense * 18.0, phi=phi_dst_crit + 0.004, phi_0=phi0, phi_m=phim)
print(f"Exact analytical Wyart-Cates DST onset volume fraction : phi_DST = {phi_dst_crit:.5f}")
print(f"Below onset (phi = {phi_dst_crit-0.004:.4f}) -> is_s_shaped_dst = {wc_below['is_s_shaped_dst']}")
print(f"Above onset (phi = {phi_dst_crit+0.004:.4f}) -> is_s_shaped_dst = {wc_above['is_s_shaped_dst']}")
assert 0.533 < phi_dst_crit < 0.537
assert (not wc_below["is_s_shaped_dst"]) and wc_above["is_s_shaped_dst"]
fig, ax = plt.subplots(figsize=(7.2, 4.0))
ax.plot(phis_scan, min_dln_rate, color="#2166AC", lw=2.4, label="Smallest slope over $\\tau$")
ax.axhline(0.0, color="#C0392B", ls="--", lw=1.6, label="DST fold bifurcation (d $\\dot{\\gamma}$ / d $\\tau$ = 0)")
ax.axvline(phi_dst_crit, color="#0F766E", ls=":", lw=1.8, label=f"Exact onset $\\phi_{{\\mathrm{{DST}}}}$ = {phi_dst_crit:.4f}")
ax.set_xlabel("Particle volume fraction $\\phi$")
ax.set_ylabel("Minimum log slope min d(ln $\\dot{\\gamma}$)/d(ln $\\tau$)")
ax.set_title(r"Smallest slope $d\ln\dot\gamma/d\ln\tau$ against volume fraction")
ax.legend(fontsize=8.1)
plt.show()
Exercise 1: the onset volume fraction of discontinuous shear thickening
=======================================================================
Exact analytical Wyart-Cates DST onset volume fraction : phi_DST = 0.53510
Below onset (phi = 0.5311) -> is_s_shaped_dst = False
Above onset (phi = 0.5391) -> is_s_shaped_dst = True

Figure S15.1. Smallest logarithmic slope of the rate against the stress in the Wyart–Cates model. It reaches zero at (dotted).
Explanation. As the stress rises above and frictional contacts form, the jamming fraction decreases towards and the viscosity rises. The slope first reaches zero at . For volume fractions between this value and the shear rate decreases with stress over a range of stresses, and the flow curve is S-shaped. The test is_s_shaped_dst of the package is false at and true at 0.5391.
Exercise 2¶
Problem. Run simulate_dpd_shear_2d with n_particles=100, box_L=7.0, shear_rate=0.85, n_steps=260, once with the pairwise thermostat of dissipative particle dynamics and once with unshifted_langevin_bug=True, which applies a drag proportional to the velocity of each particle in the laboratory frame. Compare the conservation of momentum and the deviation of the velocity profile from the imposed linear profile.
heading("Exercise 2: a drag on particle velocities in the laboratory frame against the pairwise thermostat")
dpd_true = mesoscopic_suspensions_dpd.simulate_dpd_shear_2d(
n_particles=72, box_L=6.2, shear_rate=0.85, gamma_diss=5.0, n_steps=190, unshifted_langevin_bug=False, seed=23
)
dpd_lang = mesoscopic_suspensions_dpd.simulate_dpd_shear_2d(
n_particles=72, box_L=6.2, shear_rate=0.85, gamma_diss=5.0, n_steps=190, unshifted_langevin_bug=True, seed=23
)
rmse_vx_true = float(np.sqrt(np.mean((dpd_true["velocity_profile_x"] - dpd_true["expected_linear_vx"]) ** 2)))
rmse_vx_lang = float(np.sqrt(np.mean((dpd_lang["velocity_profile_x"] - dpd_lang["expected_linear_vx"]) ** 2)))
print(f"Pairwise thermostat : momentum_drift = {dpd_true['momentum_drift_norm']:.3e} | vx RMSE = {rmse_vx_true:.4f}")
print(f"Drag on velocities : momentum_drift = {dpd_lang['momentum_drift_norm']:.3e} | vx RMSE = {rmse_vx_lang:.4f}")
assert dpd_true["momentum_drift_norm"] < 1e-11
assert dpd_lang["momentum_drift_norm"] > 1.0
assert rmse_vx_lang > 2.0 * rmse_vx_true
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.5, 3.9))
ax1.plot(dpd_true["expected_linear_vx"], dpd_true["y_bins"], "k--", lw=1.8, label="Exact linear shear profile")
ax1.plot(dpd_true["velocity_profile_x"], dpd_true["y_bins"], "o-", color="#2166AC", lw=2.2, label="Galilean-invariant pairwise DPD")
ax1.plot(dpd_lang["velocity_profile_x"], dpd_lang["y_bins"], "x-", color="#C0392B", lw=2.1, label="Drag on particle velocities, $-\\gamma\\mathbf{v}_i$")
ax1.set_xlabel("Mean velocity $\\langle v_x\\rangle(y)$")
ax1.set_ylabel("y")
ax1.set_title(r"Mean velocity profile")
ax1.legend(fontsize=8.0, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=1)
ax2.bar(["Pairwise DPD\n(conserved)", "Drag on particle\nvelocities"], [max(dpd_true["momentum_drift_norm"], 1e-15), dpd_lang["momentum_drift_norm"]], color=["#0F766E", "#C0392B"], width=0.46)
ax2.set_yscale("log")
ax2.set_ylabel("Drift of the total momentum")
ax2.set_title(r"Drift of the total momentum")
label_panels(fig)
plt.show()
Exercise 2: a drag on particle velocities in the laboratory frame against the pairwise thermostat
=================================================================================================
Pairwise thermostat : momentum_drift = 2.733e-14 | vx RMSE = 0.2023
Drag on velocities : momentum_drift = 9.319e+00 | vx RMSE = 1.3965

Figure S15.2. (a) Mean velocity profile with pairwise friction and with friction on each particle’s laboratory velocity, which removes the shear profile. (b) Norm of the total peculiar momentum at the end: 10-14 against 9.3.
Explanation. A drag on each particle acts on the mean flow as well as on the thermal motion: it removes momentum (the drift is 9.3, against with the pairwise thermostat) and distorts the velocity profile (a root-mean-square deviation of 1.40 against 0.20). The pairwise drag depends on relative velocities alone, so it conserves momentum and is unchanged by a uniform translation of the system. A thermostat that subtracts an assumed linear profile before applying the drag is also wrong when the real profile is not linear, as in shear banding.
Exercise 3¶
Problem. Write a function in NumPy that follows the Wyart–Cates flow curve at () while the shear rate is increased and then decreased, and compute the jump of the viscosity and the area of the hysteresis loop.
heading("Exercise 3: hysteresis of the Wyart-Cates flow curve under controlled shear rate")
tau_dense = np.logspace(-0.4, 3.2, 3000)
wc_ref = mesoscopic_suspensions_dpd.wyart_cates_dst_flow_curve(tau_dense, phi=0.543, phi_0=0.64, phi_m=0.55, tau_star=18.0, eta_f=0.01)
gd_s = wc_ref["shear_rate"]
eta_s = wc_ref["viscosity"]
# Locate local maximum (upper spinodal rate gd_up) and local minimum (lower spinodal rate gd_down) of S-curve:
dg = np.diff(gd_s)
idx_fold_lo = int(np.where(dg < 0.0)[0][0]) # rate peaks here on lower branch
idx_fold_hi = int(np.where(dg < 0.0)[0][-1] + 1) # rate bottoms out here on upper frictional branch
gd_up_crit = float(gd_s[idx_fold_lo])
gd_dn_crit = float(gd_s[idx_fold_hi])
gdot_sweep = np.geomspace(float(gd_s[10]), float(gd_s[-50]), 160)
# Ascending rate sweep stays on low-viscosity lubricated branch until gdot > gd_up_crit, then jumps to upper branch
tau_up_branch = np.where(
gdot_sweep <= gd_up_crit,
np.interp(gdot_sweep, gd_s[: idx_fold_lo + 1], tau_dense[: idx_fold_lo + 1]),
np.interp(gdot_sweep, gd_s[idx_fold_hi:], tau_dense[idx_fold_hi:]),
)
# Descending rate sweep stays on high-viscosity frictional branch until gdot < gd_dn_crit
tau_dn_branch = np.where(
gdot_sweep >= gd_dn_crit,
np.interp(gdot_sweep, gd_s[idx_fold_hi:], tau_dense[idx_fold_hi:]),
np.interp(gdot_sweep, gd_s[: idx_fold_lo + 1], tau_dense[: idx_fold_lo + 1]),
)
eta_up_br = tau_up_branch / gdot_sweep
eta_dn_br = tau_dn_branch / gdot_sweep
# Exact discontinuous stress/viscosity jump ratio from lower fold point to upper frictional branch at gd_up_crit:
tau_upper_at_jump = float(np.interp(gd_up_crit, gd_s[idx_fold_hi:], tau_dense[idx_fold_hi:]))
jump_factor = tau_upper_at_jump / float(tau_dense[idx_fold_lo])
print(f"Spinodal rate window [dot_gamma_down, dot_gamma_up] : [{gd_dn_crit:.2f}, {gd_up_crit:.2f}] 1/s")
print(f"Discontinuous viscosity jump factor at dot_gamma_up : {jump_factor:.2f}x")
assert gd_up_crit > gd_dn_crit
assert jump_factor > 5.0
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
ax1.loglog(gd_s, tau_dense, "k:", lw=1.6, label="Stress-controlled S-curve (unstable middle)")
ax1.loglog(gdot_sweep, tau_up_branch, "-", color="#C0392B", lw=2.3, label="Ascending rate sweep (upward DST jump)")
ax1.loglog(gdot_sweep, tau_dn_branch, "--", color="#2166AC", lw=2.2, label="Descending rate sweep (hysteresis return)")
ax1.set_xlabel("Controlled shear rate $\\dot{\\gamma}$ [1/s]")
ax1.set_ylabel("Measured shear stress $\\tau$ [Pa]")
ax1.set_title(r"Stress against rate")
ax1.legend(fontsize=7.8)
ax2.loglog(gdot_sweep, eta_up_br, "-", color="#C0392B", lw=2.3, label=f"Up-sweep viscosity ({jump_factor:.1f}x discontinuous jump)")
ax2.loglog(gdot_sweep, eta_dn_br, "--", color="#2166AC", lw=2.2, label="Down-sweep viscosity")
ax2.set_xlabel("Controlled shear rate $\\dot{\\gamma}$ [1/s]")
ax2.set_ylabel("Apparent viscosity $\\eta$ [Pa s]")
ax2.set_title(r"Viscosity against rate ($\phi = 0.543$)")
ax2.legend(fontsize=7.9)
label_panels(fig)
plt.show()
Exercise 3: hysteresis of the Wyart-Cates flow curve under controlled shear rate
================================================================================
Spinodal rate window [dot_gamma_down, dot_gamma_up] : [13.97, 20.05] 1/s
Discontinuous viscosity jump factor at dot_gamma_up : 34.55x

Figure S15.3. Wyart–Cates model under controlled rate. (a) The curve of controlled stress (dotted) and the stress followed when the rate is raised and lowered. (b) The corresponding viscosity, which jumps by a factor of about 35 on the way up.
Explanation. The flow curve is S-shaped between the shear rates 13.97 and . When the rate is increased beyond the upper value the stress jumps to the upper branch, and the viscosity rises by a factor of 35; when the rate is decreased the stress stays on the upper branch down to the lower value, so that the two sweeps enclose a loop. Compare Lecture 8: there the stress decreases with rate over a range of rates and the fluid separates into bands at one stress, while here the rate decreases with stress, and a jump occurs when the rate is controlled.