Worked solutions to the three exercises of Lecture 2. 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: exponential stretch, its logarithm, and a reversal of the flow")
t_exp = np.linspace(0.0, 2.2, 45)
eps_rate = 1.4 # Wi = 1.4 > 0.5 -> exponential growth
L_el = np.diag([eps_rate, -0.5 * eps_rate, -0.5 * eps_rate])
sol_exp = tensors_kinematics.integrate_homogeneous_constitutive(
lambda _t: L_el, t_exp, lam=1.0, eta_p=1.0, model="oldroyd_b", formulation="log_psi"
)
c_xx = sol_exp["C_hist"][:, 0, 0]
c_yy = sol_exp["C_hist"][:, 1, 1]
psi_xx = np.log(c_xx)
psi_yy = np.log(c_yy)
# Stiff elongation followed by sudden reversal on a coarse step (dt = 0.5, lam = 0.22):
t_coarse = np.linspace(0.0, 3.0, 7)
L_stiff_base = np.diag([2.5, -1.25, -1.25])
L_rev_stiff = lambda tv: L_stiff_base if tv < 1.0 else -1.8 * L_stiff_base
eul_bad = tensors_kinematics.integrate_homogeneous_constitutive(
L_rev_stiff, t_coarse, lam=0.22, eta_p=1.0, model="oldroyd_b", formulation="direct_euler"
)
log_good = tensors_kinematics.integrate_homogeneous_constitutive(
L_rev_stiff, t_coarse, lam=0.22, eta_p=1.0, model="oldroyd_b", formulation="log_psi"
)
print(f"Exponential range at t=2.2: C_xx = {c_xx[-1]:.2f}, C_yy = {c_yy[-1]:.4f} | log-space Psi_xx = {psi_xx[-1]:.2f}, Psi_yy = {psi_yy[-1]:.2f}")
print(f"Coarse reversal (dt=0.5): direct_euler diverged: {eul_bad['blew_up']} (min det C = {eul_bad['min_det_C']:.3e})")
print(f"Coarse reversal (dt=0.5): log_psi diverged: {log_good['blew_up']} (min det C = {log_good['min_det_C']:.3e} > 0)")
assert eul_bad["blew_up"] or eul_bad["min_det_C"] <= 0.0
assert (not log_good["blew_up"]) and log_good["min_det_C"] > 0.0
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
axes[0].plot(t_exp, c_xx, color="#C0392B", lw=2.0, label=r"Exponential $C_{xx}(t)$")
axes[0].plot(t_exp, psi_xx, "--", color="#2166AC", lw=2.2, label=r"Quasi-linear $\Psi_{xx}(t) = \ln C_{xx}$")
axes[0].plot(t_exp, np.abs(psi_yy), ":", color="#2E8B57", lw=2.0, label=r"$|\Psi_{yy}(t)| = |\ln C_{yy}|$")
axes[0].set_xlabel("Dimensionless time $t / \\lambda$")
axes[0].set_ylabel("Component magnitude")
axes[0].set_title(r"A growing component and its logarithm")
axes[0].legend(fontsize=8)
det_log_hist = [float(np.linalg.det(Cm)) for Cm in log_good["C_hist"]]
det_eul_hist = [float(np.linalg.det(Cm)) for Cm in eul_bad["C_hist"]]
eig_log_hist = [float(np.min(np.linalg.eigvalsh(Cm))) for Cm in log_good["C_hist"]]
eig_eul_hist = [float(np.min(np.linalg.eigvalsh(Cm))) for Cm in eul_bad["C_hist"]]
axes[1].plot(t_coarse, eig_log_hist, "-o", color="#2E8B57", lw=2.1, label="Log-conformation")
axes[1].plot(t_coarse, eig_eul_hist, "--s", color="#C0392B", lw=2.0, label="Direct Euler update")
axes[1].axhline(0.0, color="k", lw=1.1)
axes[1].set_yscale("symlog", linthresh=1e-2)
axes[1].set_xlabel("Time $t$ [s]")
axes[1].set_ylabel(r"Smallest eigenvalue of $\mathbf{C}$")
axes[1].set_title(r"Smallest eigenvalue with a coarse step")
axes[1].legend(fontsize=8, loc="lower left")
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. Check numerically that the time derivative of , approximated by the central difference with from the log-conformation equation, equals the right-hand side of the conformation equation, for the Oldroyd-B, FENE-P and Giesekus models.
heading("Exercise 1: the log-conformation equation against the conformation equation")
C_ex1 = np.array([[3.5, -1.1, 0.4], [-1.1, 1.4, -0.3], [0.4, -0.3, 0.9]], dtype=float)
L_ex1 = np.array([[0.5, 2.2, -0.4], [-0.6, -0.3, 0.5], [0.2, -0.3, -0.2]], dtype=float)
dec_ex1 = tensors_kinematics.log_conformation_decompose(C_ex1, L_ex1)
Psi_0 = dec_ex1["Psi"]
C_inv_ex1 = np.linalg.inv(C_ex1)
lam_m, alpha_m, b_m = 0.8, 0.25, 40.0
cm1 = C_ex1 - np.eye(3)
fp_fac = 1.0 / (1.0 - (float(np.trace(C_ex1)) - 3.0) / b_m)
relax_laws = {
"Oldroyd-B": -cm1 / lam_m,
"FENE-P": -(fp_fac * C_ex1 - np.eye(3)) / lam_m,
"Giesekus": -(cm1 + alpha_m * (cm1 @ cm1)) / lam_m,
}
eps_t = 1e-6
errs_frechet = {}
for name, f_rel in relax_laws.items():
# Commutativity check [C, f_rel(C)] == 0:
comm_err = float(np.linalg.norm(C_ex1 @ f_rel - f_rel @ C_ex1, ord="fro"))
assert comm_err < 1e-13
dPsi_tot = dec_ex1["dPsi_dt_kinematic"] + 0.5 * (C_inv_ex1 @ f_rel + (C_inv_ex1 @ f_rel).T)
dC_frechet = (
tensors_kinematics.exp_conformation(Psi_0 + eps_t * dPsi_tot)
- tensors_kinematics.exp_conformation(Psi_0 - eps_t * dPsi_tot)
) / (2.0 * eps_t)
dC_exact = L_ex1 @ C_ex1 + C_ex1 @ L_ex1.T + f_rel
errs_frechet[name] = float(np.linalg.norm(dC_frechet - dC_exact, ord="fro"))
print(f"{name:12s} | ||[C, f_rel]||_F = {comm_err:.2e} | ||d/dt exp(Psi) - dC/dt||_F = {errs_frechet[name]:.3e}")
assert errs_frechet[name] < 1e-8
fig, ax = plt.subplots(figsize=(6.8, 3.5))
ax.bar(list(errs_frechet.keys()), list(errs_frechet.values()), color=["#2166AC", "#2E8B57", "#C0392B"], width=0.45)
ax.set_yscale("log")
ax.set_ylabel(r"Fréchet equivalence residual $\|\frac{d}{dt}e^{\Psi} - \dot{\mathbf{C}}\|_F$")
ax.set_title(r"Difference between $\frac{d}{dt}e^{\mathbf{\Psi}}$ and $\dot{\mathbf{C}}$")
log_ticks(ax, "y", [3e-10, 1e-09, 2e-09])
plt.show()
Exercise 1: the log-conformation equation against the conformation equation
===========================================================================
Oldroyd-B | ||[C, f_rel]||_F = 1.26e-15 | ||d/dt exp(Psi) - dC/dt||_F = 1.072e-09
FENE-P | ||[C, f_rel]||_F = 0.00e+00 | ||d/dt exp(Psi) - dC/dt||_F = 3.130e-10
Giesekus | ||[C, f_rel]||_F = 7.02e-16 | ||d/dt exp(Psi) - dC/dt||_F = 1.596e-09

Figure S2.1. Frobenius norm of the difference between the time derivative of , by finite differences, and from the conformation equation, for three models. The values are of the size of the finite-difference error.
Explanation. The derivative of equals only when commutes with . The log-conformation equation splits into a rotation of the principal axes, , whose effect on is , and the terms , which commute with because is an isotropic function of (the commutator is zero to 10-15 in the output). The two right-hand sides agree to between and for the three models; differences of this size are expected from the central difference itself.
Exercise 2¶
Problem. Compare the methods direct_euler and log_psi in a uniaxial extension that reverses: lam = 0.22, for and -1.8 times this tensor for , on the grid np.linspace(0.0, 3.0, 7), which has a step of 0.50. Record the smallest and the largest eigenvalue and the determinant of at each step, and then reduce the step to find where direct_euler becomes stable.
heading("Exercise 2: loss of positive definiteness after a reversal of the flow")
L_b2 = np.diag([2.5, -1.25, -1.25])
L_step2 = lambda tv: L_b2 if tv < 1.0 else -1.8 * L_b2
t_c2 = np.linspace(0.0, 3.0, 7)
eul_c2 = tensors_kinematics.integrate_homogeneous_constitutive(L_step2, t_c2, lam=0.22, eta_p=1.0, formulation="direct_euler")
log_c2 = tensors_kinematics.integrate_homogeneous_constitutive(L_step2, t_c2, lam=0.22, eta_p=1.0, formulation="log_psi")
ref_fine = tensors_kinematics.integrate_homogeneous_constitutive(L_step2, np.linspace(0.0, 3.0, 601), lam=0.22, eta_p=1.0, formulation="log_psi")
min_eig_eul = [float(np.min(np.linalg.eigvalsh(Cm))) for Cm in eul_c2["C_hist"]]
min_eig_log = [float(np.min(np.linalg.eigvalsh(Cm))) for Cm in log_c2["C_hist"]]
min_eig_ref = [float(np.min(np.linalg.eigvalsh(Cm))) for Cm in ref_fine["C_hist"]]
dt_scan = np.linspace(0.02, 0.50, 25)
min_det_vs_dt_eul = []
min_det_vs_dt_log = []
for dts in dt_scan:
ts = np.linspace(0.0, 3.0, max(3, int(round(3.0 / dts)) + 1))
re_s = tensors_kinematics.integrate_homogeneous_constitutive(L_step2, ts, lam=0.22, eta_p=1.0, formulation="direct_euler")
rl_s = tensors_kinematics.integrate_homogeneous_constitutive(L_step2, ts, lam=0.22, eta_p=1.0, formulation="log_psi")
min_det_vs_dt_eul.append(re_s["min_det_C"])
min_det_vs_dt_log.append(rl_s["min_det_C"])
print(f"Coarse dt=0.50 -> direct_euler min_eig = {min(min_eig_eul):.3f} (diverged: {eul_c2['blew_up']})")
print(f"Coarse dt=0.50 -> log_psi min_eig = {min(min_eig_log):.4f} (diverged: {log_c2['blew_up']})")
assert min(min_eig_eul) <= 0.0 and eul_c2["blew_up"]
assert min(min_eig_log) > 0.0 and not log_c2["blew_up"]
assert all(d > 0.0 for d in min_det_vs_dt_log)
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
axes[0].plot(np.linspace(0.0, 3.0, 601), min_eig_ref, "k-", lw=1.8, label="Fine reference $\\lambda_{\\min}(t)$")
axes[0].plot(t_c2, min_eig_log, "-o", color="#2E8B57", lw=2.0, label="Log-conformation ($\\Delta t=0.5$)")
axes[0].plot(t_c2, min_eig_eul, "--s", color="#C0392B", lw=2.0, label="Direct Euler update ($\\Delta t=0.5$)")
axes[0].axhline(0.0, color="k", ls=":")
axes[0].set_xlabel("Time $t$ [s]")
axes[0].set_ylabel(r"Minimum conformation eigenvalue $\lambda_{\min}$")
axes[0].set_title(r"Smallest eigenvalue during the reversal")
axes[0].legend(fontsize=8)
axes[1].plot(dt_scan / 0.22, np.clip(min_det_vs_dt_eul, -2.0, 2.0), "--s", color="#C0392B", ms=4.5, lw=1.9, label="Direct Euler update")
axes[1].plot(dt_scan / 0.22, min_det_vs_dt_log, "-o", color="#2E8B57", ms=4.5, lw=1.9, label="Log-conformation")
axes[1].axhline(0.0, color="k", ls=":")
axes[1].set_xlabel(r"Dimensionless step $\Delta t / \lambda$")
axes[1].set_ylabel(r"Minimum determinant $\min_t \det\mathbf{C}$")
axes[1].set_title(r"Smallest determinant against the time step")
axes[1].legend(fontsize=8, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=2)
label_panels(fig)
plt.show()
Exercise 2: loss of positive definiteness after a reversal of the flow
======================================================================
Coarse dt=0.50 -> direct_euler min_eig = -35.644 (diverged: True)
Coarse dt=0.50 -> log_psi min_eig = 0.3386 (diverged: False)

Figure S2.2. (a) Smallest eigenvalue of for the fine reference, the coarse log-conformation run and the coarse direct Euler run (values below -35 are clipped in the plot). (b) Smallest determinant over the run against , clipped at -2: the direct Euler update stays positive definite up to and fails from 0.36 on.
Explanation. The explicit update of a diagonal component is . After the reversal , and with the factor in brackets is . The large value of built up during the stretch therefore becomes negative in one step, and the smallest eigenvalue reaches -35.6. In the logarithmic variable the same compression lowers , and stays positive: the smallest eigenvalue is 0.34. When the step is reduced, the direct update stays positive definite up to (); at the determinant is already negative (Figure S2.2b).
Exercise 3¶
Problem. Write a second-order Runge–Kutta solver of the log-conformation equation in NumPy for the FENE-P model (, , ) in a three-dimensional flow with , , , for , and compare the conformation tensors with those of tensors_kinematics.integrate_homogeneous_constitutive.
heading("Exercise 3: a log-conformation solver for the FENE-P model in three dimensions")
lam_3, eta_p_3, b_3 = 0.75, 1.5, 45.0
G0_3 = eta_p_3 / lam_3
t_3 = np.linspace(0.0, 2.0, 101)
def L_3d_mixed(tv: float) -> np.ndarray:
g_t = 6.0 * math.sin(0.5 * math.pi * tv)
return np.array([[-0.8, g_t, 0.25], [0.0, 0.3, -0.15], [0.0, 0.0, 0.5]], dtype=float)
def exp_sym_scratch(Psi_m: np.ndarray) -> np.ndarray:
P_s = 0.5 * (Psi_m + Psi_m.T)
ev, R = np.linalg.eigh(P_s)
C_o = (R * np.exp(np.clip(ev, -80.0, 80.0))[None, :]) @ R.T
return 0.5 * (C_o + C_o.T)
def rhs_psi_fenep_scratch(Psi_m: np.ndarray, tv: float) -> np.ndarray:
C_m = exp_sym_scratch(Psi_m)
L_m = L_3d_mixed(tv)
ev, R = np.linalg.eigh(C_m)
log_ev = np.log(ev)
M_t = R.T @ L_m @ R
B_t = np.diag(np.diag(M_t))
comm_t = np.zeros((3, 3), dtype=float)
for i in range(3):
for j in range(i + 1, 3):
gap = abs(ev[j] - ev[i]) / (0.5 * (ev[i] + ev[j]))
if gap > 1e-7:
om_ij = (ev[j] * M_t[i, j] + ev[i] * M_t[j, i]) / (ev[j] - ev[i])
c_ij = om_ij * (log_ev[j] - log_ev[i])
else:
c_ij = M_t[i, j] + M_t[j, i]
comm_t[i, j] = c_ij
comm_t[j, i] = c_ij
dPsi_kin = R @ (comm_t + 2.0 * B_t) @ R.T
fp = 1.0 / max(1e-12, 1.0 - (float(np.trace(C_m)) - 3.0) / b_3)
rel_C = -(fp * C_m - np.eye(3)) / lam_3
rel_psi = R @ ((1.0 / ev)[:, None] * (R.T @ rel_C @ R)) @ R.T
out = 0.5 * (dPsi_kin + dPsi_kin.T) + 0.5 * (rel_psi + rel_psi.T)
return 0.5 * (out + out.T)
Psi_cur = np.zeros((3, 3), dtype=float)
C_scratch = np.zeros((t_3.size, 3, 3), dtype=float)
C_scratch[0] = np.eye(3)
for k in range(t_3.size - 1):
dtk = float(t_3[k + 1] - t_3[k])
tk = float(t_3[k])
k1 = rhs_psi_fenep_scratch(Psi_cur, tk)
k2 = rhs_psi_fenep_scratch(Psi_cur + 0.5 * dtk * k1, tk + 0.5 * dtk)
Psi_cur = Psi_cur + dtk * k2
C_scratch[k + 1] = exp_sym_scratch(Psi_cur)
pkg_3 = tensors_kinematics.integrate_homogeneous_constitutive(
L_3d_mixed, t_3, lam=lam_3, eta_p=eta_p_3, model="fenep", b_fenep=b_3, formulation="log_psi"
)
max_diff_C = float(np.max(np.abs(C_scratch - pkg_3["C_hist"])))
min_det_3 = float(np.min(np.linalg.det(C_scratch)))
print(f"Max |C_scratch - C_engcomprheo| across all 101 3x3 tensors: {max_diff_C:.3e}")
print(f"Minimum det(C) during 3-D mixed flow : {min_det_3:.4f} > 0")
assert max_diff_C < 1e-11
assert min_det_3 > 0.5
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
axes[0].plot(t_3, pkg_3["C_hist"][:, 0, 1], "k-", lw=2.2, label="Package solver, $C_{xy}$")
axes[0].plot(t_3[::4], C_scratch[::4, 0, 1], "o", color="#2166AC", ms=4.5, label="This solver, $C_{xy}$")
axes[0].plot(t_3, C_scratch[:, 2, 2], "--", color="#2E8B57", lw=2.0, label="This solver, $C_{zz}$")
axes[0].set_xlabel("Time $t$ [s]")
axes[0].set_ylabel("Conformation components")
axes[0].set_title(r"Components of $\mathbf{C}$")
axes[0].legend(fontsize=8)
evals_hist = np.linalg.eigvalsh(C_scratch)
for m_i, col in enumerate(["#C0392B", "#E08214", "#2166AC"]):
axes[1].semilogy(t_3, evals_hist[:, m_i], lw=2.0, color=col, label=rf"Eigenvalue $\lambda_{m_i+1}(t)$")
axes[1].set_xlabel("Time $t$ [s]")
axes[1].set_ylabel(r"Principal stretch eigenvalues $\lambda_i > 0$")
axes[1].set_title(r"Eigenvalues of $\mathbf{C}$")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 3: a log-conformation solver for the FENE-P model in three dimensions
==============================================================================
Max |C_scratch - C_engcomprheo| across all 101 3x3 tensors: 0.000e+00
Minimum det(C) during 3-D mixed flow : 1.0000 > 0

Figure S2.3. Three-dimensional FENE-P model in a mixed flow, integrated with a separate log-conformation code. (a) Two components against the package. (b) The three eigenvalues, all positive.
Explanation. The solver needs one symmetric eigenvalue problem (np.linalg.eigh) for each stage, uses the limit of the off-diagonal formula when two eigenvalues are equal, and returns with positive eigenvalues for any velocity gradient. It reproduces the result of the package exactly (the difference over the 101 tensors is zero), and the smallest determinant during the flow is 1.0000, the value at the start. The same step is applied in every cell of the two-dimensional solver of Lectures 13, 14 and 17.