Worked solutions to the three exercises of Lecture 1. 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: the conformation tensor of an ensemble and its free energy")
rng_c = np.random.default_rng(101)
n_ens = 25000
Q_eq = rng_c.normal(0.0, 1.0, size=(n_ens, 3))
F_def_ens = np.array([[1.65, 0.75, 0.0], [0.0, 0.80, 0.0], [0.0, 0.0, 1.0 / (1.65 * 0.80)]])
Q_def = Q_eq @ F_def_ens.T
C_emp = (Q_def.T @ Q_def) / n_ens
spd_eq = tensors_kinematics.check_spd_conformation(np.eye(3), G0=1.0)
spd_emp = tensors_kinematics.check_spd_conformation(C_emp, G0=1.0)
minor1 = C_emp[0, 0]
minor2 = float(np.linalg.det(C_emp[:2, :2]))
minor3 = float(np.linalg.det(C_emp))
print(f"Equilibrium C = I : is_spd={spd_eq['is_spd']}, psi/G0={spd_eq['free_energy_hookean']:.3e}")
print(f"Deformed ensemble : is_spd={spd_emp['is_spd']}, min_eig={spd_emp['min_eigenvalue']:.4f}, psi/G0={spd_emp['free_energy_hookean']:.4f}")
print(f"Sylvester minors : Delta_1={minor1:.4f} > 0, Delta_2={minor2:.4f} > 0, Delta_3={minor3:.4f} > 0")
assert spd_eq["free_energy_hookean"] == 0.0
assert spd_emp["is_spd"] and spd_emp["free_energy_hookean"] > 0.4
assert minor1 > 0.0 and minor2 > 0.0 and minor3 > 0.0
c12_grid = np.linspace(-1.95, 1.95, 160)
c11_fixed = 2.0
c22_grid = np.linspace(0.05, 3.0, 160)
C12, C22 = np.meshgrid(c12_grid, c22_grid)
DET2 = c11_fixed * C22 - C12**2
PSI2 = np.where(DET2 > 1e-4, 0.5 * (c11_fixed + C22 - np.log(np.maximum(DET2, 1e-4)) - 2.0), np.nan)
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.9))
cf = axes[0].contourf(C12, C22, PSI2, levels=np.linspace(0.0, 3.5, 15), cmap="viridis")
plt.colorbar(cf, ax=axes[0], label=r"Free energy $\psi / G_0$")
axes[0].plot(c12_grid, (c12_grid**2) / c11_fixed, "r-", lw=2.2, label=r"Boundary $\det\mathbf{C} = 0$")
axes[0].fill_between(c12_grid, 0.0, np.minimum(3.0, (c12_grid**2) / c11_fixed), color="#C0392B", alpha=0.18, label="Not positive definite")
axes[0].set_xlim(-1.95, 1.95)
axes[0].set_ylim(0.05, 3.0)
axes[0].set_xlabel(r"Shear conformation $C_{12}$")
axes[0].set_ylabel(r"Transverse conformation $C_{22}$ (at $C_{11}=2$)")
axes[0].set_title(r"Free energy on a slice of the cone")
axes[0].legend(fontsize=8, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=2)
lam_vals = np.logspace(-1.2, 1.0, 200)
axes[1].plot(lam_vals, 0.5 * (lam_vals - np.log(lam_vals) - 1.0), color="#2166AC", lw=2.2, label=r"1-D mode $\frac{1}{2}(\lambda_i - \ln\lambda_i - 1)$")
axes[1].axvline(1.0, color="gray", ls=":", label=r"Equilibrium $\lambda_i = 1$ ($\psi=0$)")
axes[1].set_xlabel(r"Principal conformation eigenvalue $\lambda_i > 0$")
axes[1].set_ylabel(r"Modal free energy $\psi_i / G_0$")
axes[1].set_title(r"Free energy of one principal direction")
axes[1].legend(fontsize=8.5)
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Check with tensors_kinematics.integrate_homogeneous_constitutive that the Trouton ratio of an Oldroyd-B fluid is in uniaxial extension and in planar extension, for .
heading("Exercise 1: Trouton ratios in uniaxial and planar extension")
wi_ex1 = np.linspace(0.02, 0.40, 9)
t_ex1 = np.linspace(0.0, 42.0, 221)
tr_uni_num, tr_pl_num = [], []
for w in wi_ex1:
L_u = np.diag([float(w), -0.5 * float(w), -0.5 * float(w)])
L_p = np.diag([float(w), -float(w), 0.0])
su = tensors_kinematics.integrate_homogeneous_constitutive(lambda _t, L=L_u: L, t_ex1, lam=1.0, eta_p=1.0, model="oldroyd_b")
sp = tensors_kinematics.integrate_homogeneous_constitutive(lambda _t, L=L_p: L, t_ex1, lam=1.0, eta_p=1.0, model="oldroyd_b")
tr_uni_num.append(float(su["tau_p_hist"][-1, 0, 0] - su["tau_p_hist"][-1, 1, 1]) / float(w))
tr_pl_num.append(float(sp["tau_p_hist"][-1, 0, 0] - sp["tau_p_hist"][-1, 1, 1]) / float(w))
tr_uni_ex = 3.0 / ((1.0 - 2.0 * wi_ex1) * (1.0 + wi_ex1))
tr_pl_ex = 4.0 / (1.0 - 4.0 * (wi_ex1**2))
err_u = float(np.max(np.abs(np.array(tr_uni_num[:-1]) - tr_uni_ex[:-1]) / tr_uni_ex[:-1]))
err_p = float(np.max(np.abs(np.array(tr_pl_num[:-1]) - tr_pl_ex[:-1]) / tr_pl_ex[:-1]))
print(f"Low-Wi Trouton limits (Wi=0.02): uniaxial = {tr_uni_num[0]:.3f} (exact {tr_uni_ex[0]:.3f}), planar = {tr_pl_num[0]:.3f} (exact {tr_pl_ex[0]:.3f})")
print(f"Max relative error across Wi <= 0.40: uniaxial = {err_u:.3e}, planar = {err_p:.3e}")
assert err_u < 5e-3 and err_p < 5e-3
fig, ax = plt.subplots(figsize=(7.2, 3.8))
w_curve = np.linspace(0.0, 0.48, 200)
ax.semilogy(w_curve, 3.0 / ((1.0 - 2.0 * w_curve) * (1.0 + w_curve)), "-", color="#2166AC", lw=2.0, label="Exact uniaxial $3/[(1-2\\mathrm{Wi})(1+\\mathrm{Wi})]$")
ax.semilogy(wi_ex1, tr_uni_num, "o", color="#2166AC", ms=5, label="Numerical uniaxial")
ax.semilogy(w_curve, 4.0 / (1.0 - 4.0 * w_curve**2), "-", color="#C0392B", lw=2.0, label="Exact planar $4/(1 - 4\\mathrm{Wi}^2)$")
ax.semilogy(wi_ex1, tr_pl_num, "s", color="#C0392B", ms=5, label="Numerical planar")
ax.axvline(0.5, color="gray", ls=":", label=r"Divergence at $\mathrm{Wi} = 0.5$")
ax.set_xlabel(r"Extensional Weissenberg number $\mathrm{Wi} = \lambda\dot{\varepsilon}$")
ax.set_ylabel("Trouton ratio")
ax.set_title(r"Uniaxial and planar Trouton ratios")
ax.legend(fontsize=8)
log_ticks(ax, "y", [3, 6, 10, 20, 40])
plt.show()
Exercise 1: Trouton ratios in uniaxial and planar extension
===========================================================
Low-Wi Trouton limits (Wi=0.02): uniaxial = 3.064 (exact 3.064), planar = 4.006 (exact 4.006)
Max relative error across Wi <= 0.40: uniaxial = 3.786e-06, planar = 3.580e-06

Figure S1.1. Oldroyd-B Trouton ratios in uniaxial and planar extension, computed (symbols) and exact (lines). Both diverge at .
Explanation. In planar extension (, , ) the steady conformation is , , , so that and the Trouton ratio tends to 4 at low rates, against 3 in uniaxial extension. The largest rate of stretching is in both flows, and both ratios diverge at . The integrator reproduces both formulas with a relative error below .
Exercise 2¶
Problem. Take the family of tensors , which is positive definite for . For up to 0.95 compute the leading minor , the smallest eigenvalue , whether the Cholesky factorization fails, and the dissipation of the Oldroyd-B model.
heading("Exercise 2: a conformation tensor that is not positive definite")
s_crit = math.sqrt(2.2 * 0.30)
s_sweep = np.linspace(0.0, 0.98, 120)
min_eigs, delta2_vals, phi_vals = [], [], []
for s_val in s_sweep:
C_s = np.array([[2.2, float(s_val), 0.0], [float(s_val), 0.30, 0.0], [0.0, 0.0, 1.0]])
ev = np.linalg.eigvalsh(C_s)
min_eigs.append(float(np.min(ev)))
delta2_vals.append(float(np.linalg.det(C_s[:2, :2])))
if abs(np.prod(ev)) > 1e-4:
phi_vals.append(0.5 * float(np.sum(((ev - 1.0) ** 2) / ev)))
else:
phi_vals.append(np.nan)
C_broken = np.array([[2.2, 0.95, 0.0], [0.95, 0.30, 0.0], [0.0, 0.0, 1.0]])
audit_broken = tensors_kinematics.check_spd_conformation(C_broken, G0=1.0)
chol_failed = False
try:
np.linalg.cholesky(C_broken)
except np.linalg.LinAlgError:
chol_failed = True
ev_b = audit_broken["eigenvalues"]
phi_broken = 0.5 * float(np.sum(((ev_b - 1.0) ** 2) / ev_b))
print(f"Critical SPD shear bound s_crit = {s_crit:.4f}")
print(f"At s = 0.95: is_spd={audit_broken['is_spd']}, min_eig={audit_broken['min_eigenvalue']:.4f}, det(C)={audit_broken['det_C']:.4f}")
print(f"Cholesky LinAlgError raised: {chol_failed} | dissipation Phi_diss = {phi_broken:.3f} < 0")
assert not audit_broken["is_spd"]
assert chol_failed
assert audit_broken["min_eigenvalue"] < -0.08
assert phi_broken < -3.0
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
axes[0].plot(s_sweep, delta2_vals, color="#2166AC", lw=2.0, label=r"Sylvester minor $\Delta_2 = C_{11}C_{22} - s^2$")
axes[0].plot(s_sweep, min_eigs, color="#C0392B", lw=2.0, label=r"Minimum eigenvalue $\lambda_{\min}$")
axes[0].axhline(0.0, color="k", lw=1.0)
axes[0].axvline(s_crit, color="gray", ls="--", label=rf"$s_{{\mathrm{{crit}}}} = {s_crit:.3f}$")
axes[0].set_xlabel(r"Off-diagonal shear component $s = C_{12}$")
axes[0].set_ylabel("Minor and eigenvalue")
axes[0].set_title(r"Second minor and smallest eigenvalue")
axes[0].legend(fontsize=8)
axes[1].plot(s_sweep, phi_vals, color="#7B4FA3", lw=2.1, label=r"$\Phi_{\mathrm{diss}} / (G_0/\lambda)$")
axes[1].axhline(0.0, color="k", lw=1.0)
axes[1].axvline(s_crit, color="gray", ls="--")
axes[1].set_ylim(-15.0, 15.0)
axes[1].set_xlabel(r"Off-diagonal shear component $s = C_{12}$")
axes[1].set_ylabel(r"Normalized dissipation $\Phi_{\mathrm{diss}}\lambda / G_0$")
axes[1].set_title(r"Dissipation computed from $\mathbf{C}$")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 2: a conformation tensor that is not positive definite
===============================================================
Critical SPD shear bound s_crit = 0.8124
At s = 0.95: is_spd=False, min_eig=-0.0935, det(C)=-0.2425
Cholesky LinAlgError raised: True | dissipation Phi_diss = -5.905 < 0

Figure S1.2. The tensor of the exercise as its shear component increases. (a) The second leading minor and the smallest eigenvalue change sign together at . (b) The dissipation formula diverges at and is negative beyond it.
Explanation. When passes through zero the smallest eigenvalue changes sign, and its contribution to the dissipation jumps from to . At the smallest eigenvalue is -0.094, the Cholesky factorization fails and the dissipation is -5.9. A tensor of this kind in a flow calculation returns energy to the flow instead of dissipating it, and the calculation diverges. Replacing negative eigenvalues by a small positive number changes the stress without a physical basis; Lecture 2 avoids the problem by evolving .
Exercise 3¶
Problem. Write a fourth-order Runge–Kutta solver in NumPy for the Giesekus model (, , ) in start-up of shear at followed by cessation at . Compare the shear stress with integrate_homogeneous_constitutive, and check that the dissipation is never negative.
heading("Exercise 3: a Runge-Kutta solver for the Giesekus model, and its dissipation")
G0_g, lam_g, alpha_g = 2.5, 0.6, 0.3
eta_p_g = G0_g * lam_g
t_g = np.linspace(0.0, 2.4, 481)
dt_g = float(t_g[1] - t_g[0])
L_g_fn = lambda tv: np.array([[0.0, 5.0 if tv < 1.2 else 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
def rhs_giesekus(C_m: np.ndarray, tv: float) -> np.ndarray:
L_m = L_g_fn(tv)
cm1 = C_m - np.eye(3)
return L_m @ C_m + C_m @ L_m.T - (cm1 + alpha_g * (cm1 @ cm1)) / lam_g
C_rk4 = np.zeros((t_g.size, 3, 3), dtype=float)
C_rk4[0] = np.eye(3)
for k in range(t_g.size - 1):
tk = float(t_g[k])
Ck = C_rk4[k]
k1 = rhs_giesekus(Ck, tk)
k2 = rhs_giesekus(Ck + 0.5 * dt_g * k1, tk + 0.5 * dt_g)
k3 = rhs_giesekus(Ck + 0.5 * dt_g * k2, tk + 0.5 * dt_g)
k4 = rhs_giesekus(Ck + dt_g * k3, tk + dt_g)
C_rk4[k + 1] = 0.5 * ((Ck + (dt_g / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)) + (Ck + (dt_g / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)).T)
pkg_g = tensors_kinematics.integrate_homogeneous_constitutive(
L_g_fn, t_g, lam=lam_g, eta_p=eta_p_g, model="giesekus", alpha_giesekus=alpha_g, formulation="log_psi"
)
tau_rk4 = G0_g * (C_rk4 - np.eye(3)[None, :, :])
err_tau_g = float(np.max(np.abs(tau_rk4[:, 0, 1] - pkg_g["tau_p_hist"][:, 0, 1])))
phi_hook = np.zeros_like(t_g)
phi_gies = np.zeros_like(t_g)
for k in range(t_g.size):
Ck = C_rk4[k]
ev = np.linalg.eigvalsh(Ck)
assert np.all(ev > 0.0)
phi_hook[k] = (0.5 * G0_g / lam_g) * float(np.sum(((ev - 1.0) ** 2) / ev))
phi_gies[k] = (0.5 * G0_g / lam_g) * float(np.sum(((ev - 1.0) ** 2) * (1.0 + alpha_g * (ev - 1.0)) / ev))
print(f"Max |tau_xy(RK4) - tau_xy(engcomprheo log_psi)|: {err_tau_g:.3e} Pa")
print(f"Min Giesekus dissipation: {np.min(phi_gies):.3e} W/m^3 (strictly >= 0 for alpha in [0, 1])")
assert err_tau_g < 1e-2
assert np.all(phi_gies >= -1e-14)
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
axes[0].plot(t_g, pkg_g["tau_p_hist"][:, 0, 1], "k-", lw=2.2, label="Package solver (log-conformation)")
axes[0].plot(t_g[::10], tau_rk4[::10, 0, 1], "o", color="#2166AC", ms=4.5, label="This solver, RK4 $\\tau_{xy}$")
axes[0].plot(t_g, tau_rk4[:, 1, 1] - tau_rk4[:, 2, 2], "--", color="#C0392B", lw=1.8, label="This solver, RK4 $N_2(t) < 0$")
axes[0].set_xlabel("Time $t$ [s]")
axes[0].set_ylabel("Stress [Pa]")
axes[0].set_title(r"Stresses")
axes[0].legend(fontsize=8)
axes[1].plot(t_g, phi_gies, color="#2E8B57", lw=2.1, label=r"Total Giesekus $\Phi_{\mathrm{diss}}^{\mathrm{G}}$")
axes[1].plot(t_g, phi_hook, "--", color="#7B4FA3", lw=1.8, label=r"Linear part $\Phi_{\mathrm{diss}}^{\mathrm{Hookean}}$")
axes[1].set_xlabel("Time $t$ [s]")
axes[1].set_ylabel(r"Dissipation [$\mathrm{W/m^3}$]")
axes[1].set_title(r"Dissipation")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 3: a Runge-Kutta solver for the Giesekus model, and its dissipation
============================================================================
Max |tau_xy(RK4) - tau_xy(engcomprheo log_psi)|: 6.543e-03 Pa
Min Giesekus dissipation: 0.000e+00 W/m^3 (strictly >= 0 for alpha in [0, 1])

Figure S1.3. Giesekus model in start-up of shear and after cessation at 1.2 s, integrated with a separate fourth-order Runge–Kutta code. (a) Shear stress against the package, and the second normal stress difference, which is negative. (b) Total dissipation and the part that the Oldroyd-B model would give.
Explanation. In principal axes the Giesekus term multiplies the dissipation of each eigenvalue by , which is positive for and . The dissipation is therefore non-negative for every positive definite conformation tensor; the computed minimum is zero, the value at rest. The shear stresses of the two integrators differ by at most Pa.