Worked solutions to the three exercises of Lecture 0. 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: frame indifference of time derivatives in a rotating frame")
A_sample = np.array([[2.4, 0.7, -0.2], [0.7, 1.1, 0.3], [-0.2, 0.3, 0.9]])
L_sample = np.array([[0.2, 1.8, -0.4], [-0.3, -0.1, 0.5], [0.1, -0.2, -0.1]])
dA_sample = np.array([[0.3, -0.2, 0.1], [-0.2, 0.4, -0.1], [0.1, -0.1, -0.2]])
operators = {
"Upper-convected (xi=0)": lambda A, L, dA: tensors_kinematics.convected_derivatives(A, L, dA, xi_slip=0.0)["upper_convected"],
"Gordon-Schowalter (xi=0.35)": lambda A, L, dA: tensors_kinematics.convected_derivatives(A, L, dA, xi_slip=0.35)["gordon_schowalter"],
"Corotational (xi=1)": lambda A, L, dA: tensors_kinematics.convected_derivatives(A, L, dA, xi_slip=1.0)["corotational"],
"Lower-convected (xi=2)": lambda A, L, dA: tensors_kinematics.convected_derivatives(A, L, dA, xi_slip=2.0)["lower_convected"],
"Partial dA/dt": lambda A, L, dA: dA,
}
omega_vals = np.linspace(0.25, 5.0, 20)
err_curves = {name: [] for name in operators}
for name, fn in operators.items():
for om in omega_vals:
res = tensors_kinematics.audit_frame_indifference(fn, A_sample, L_sample, dA_sample, theta_rad=0.72, omega_spin=float(om))
err_curves[name].append(max(res["discrepancy_frobenius"], 1e-16))
for name in operators:
res_ref = tensors_kinematics.audit_frame_indifference(operators[name], A_sample, L_sample, dA_sample, theta_rad=0.65, omega_spin=2.3)
print(f"{name:30s} | passed={str(res_ref['objective_passed']):5s} | ||D* - Q D Q^T||_F = {res_ref['discrepancy_frobenius']:.3e}")
assert max(err_curves["Upper-convected (xi=0)"]) < 1e-12
assert max(err_curves["Gordon-Schowalter (xi=0.35)"]) < 1e-12
assert max(err_curves["Corotational (xi=1)"]) < 1e-12
assert max(err_curves["Lower-convected (xi=2)"]) < 1e-12
assert err_curves["Partial dA/dt"][-1] > 5.0
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
for name, vals in err_curves.items():
ls = "--" if "Partial" in name else "-"
lw = 2.2 if "Partial" in name else 1.8
axes[0].semilogy(omega_vals, vals, linestyle=ls, linewidth=lw, label=name)
axes[0].set_xlabel(r"Rate of rotation of the frame $\omega_{\mathrm{spin}}$ [rad/s]")
axes[0].set_ylabel(r"Departure from frame indifference $\|\mathcal{D}_t^* - \mathbf{Q}\mathcal{D}_t\mathbf{Q}^\top\|_F$")
axes[0].set_title(r"Objectivity error against observer spin")
axes[0].legend(fontsize=8)
cd_xi0 = tensors_kinematics.convected_derivatives(A_sample, L_sample, dA_sample, xi_slip=0.0)
cd_xi1 = tensors_kinematics.convected_derivatives(A_sample, L_sample, dA_sample, xi_slip=1.0)
cd_xi2 = tensors_kinematics.convected_derivatives(A_sample, L_sample, dA_sample, xi_slip=2.0)
interp_errs = [
np.linalg.norm(cd_xi0["gordon_schowalter"] - cd_xi0["upper_convected"]),
np.linalg.norm(cd_xi1["gordon_schowalter"] - cd_xi1["corotational"]),
np.linalg.norm(cd_xi2["gordon_schowalter"] - cd_xi2["lower_convected"]),
]
assert max(interp_errs) < 1e-14
xi_grid = np.linspace(0.0, 2.0, 41)
gs_fro = [
np.linalg.norm(tensors_kinematics.convected_derivatives(A_sample, L_sample, dA_sample, xi_slip=float(x))["gordon_schowalter"], ord="fro")
for x in xi_grid
]
axes[1].plot(xi_grid, gs_fro, color="#2166AC", lw=2.0, label=r"$\|\mathcal{D}_{\xi}\mathbf{A}\|_F$")
axes[1].scatter([0.0, 1.0, 2.0], [gs_fro[0], gs_fro[20], gs_fro[-1]], color="#C0392B", zorder=5, label=r"$\xi = 0$, 1 and 2")
axes[1].set_xlabel(r"Gordon–Schowalter slip parameter $\xi$")
axes[1].set_ylabel(r"Norm of the derivative $\|\mathcal{D}_{\xi}\mathbf{A}\|_F$ [1/s]")
axes[1].set_title(r"Norm of the Gordon–Schowalter derivative against $\xi$")
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 numerically, for between 0 and 2 and between 0.1 and 6, that (1) the Gordon–Schowalter derivative is the weighted mean of the upper- and lower-convected derivatives, and (2) the steady shear solution of the Johnson–Segalman model satisfies and .
heading("Exercise 1: the Gordon-Schowalter derivative and the viscometric functions")
rng_ex1 = np.random.default_rng(100)
A_r = rng_ex1.normal(size=(3, 3)); A_r = A_r @ A_r.T + np.eye(3)
L_r = rng_ex1.normal(size=(3, 3))
dA_r = rng_ex1.normal(size=(3, 3)); dA_r = 0.5 * (dA_r + dA_r.T)
cd_base = tensors_kinematics.convected_derivatives(A_r, L_r, dA_r, xi_slip=0.0)
uc_ref, lc_ref = cd_base["upper_convected"], cd_base["lower_convected"]
xi_list = np.linspace(0.0, 2.0, 21)
combo_errs = []
for xv in xi_list:
gs_v = tensors_kinematics.convected_derivatives(A_r, L_r, dA_r, xi_slip=float(xv))["gordon_schowalter"]
lin_combo = (1.0 - 0.5 * xv) * uc_ref + (0.5 * xv) * lc_ref
combo_errs.append(float(np.linalg.norm(gs_v - lin_combo, ord="fro")))
wi_vals = np.linspace(0.1, 6.0, 60)
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
for xv, col in [(0.0, "#2166AC"), (0.25, "#2E8B57"), (0.6, "#E08214"), (1.0, "#C0392B")]:
eta_num, ratio_num = [], []
for w in wi_vals:
L_w = np.array([[0.0, float(w), 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
# Analytical steady stress plugged back into convected_derivatives residual check:
denom = 1.0 + xv * (2.0 - xv) * (w**2)
txy = w / denom
txx = (2.0 - xv) * w * txy
tyy = -xv * w * txy
tau_mat = np.array([[txx, txy, 0.0], [txy, tyy, 0.0], [0.0, 0.0, 0.0]])
res_mat = tau_mat + tensors_kinematics.convected_derivatives(tau_mat, L_w, xi_slip=xv)["gordon_schowalter"] - (L_w + L_w.T)
assert np.linalg.norm(res_mat) < 1e-13
eta_num.append(txy / w)
ratio_num.append(tyy / (txx - tyy))
axes[0].plot(wi_vals, eta_num, lw=2.0, color=col, label=rf"$\xi = {xv:.2f}$")
axes[1].plot(wi_vals, ratio_num, lw=2.0, color=col, label=rf"$\xi = {xv:.2f} \to N_2/N_1 = {-0.5*xv + 0.0:.3f}$")
assert max(combo_errs) < 1e-14
print(f"Max convex-combination error across xi in [0, 2]: {max(combo_errs):.3e}")
axes[0].set_xlabel(r"Weissenberg number $\mathrm{Wi}$")
axes[0].set_ylabel(r"Normalized polymer viscosity $\eta_p(\mathrm{Wi}) / \eta_{p,0}$")
axes[0].set_title(r"Viscosity $[1 + \xi(2-\xi)\mathrm{Wi}^2]^{-1}$")
axes[0].legend(fontsize=8)
axes[1].set_xlabel(r"Weissenberg number $\mathrm{Wi}$")
axes[1].set_ylabel(r"Normal stress ratio $N_2 / N_1$")
axes[1].set_title(r"Ratio $N_2 / N_1$")
axes[1].legend(fontsize=8, loc="upper center", bbox_to_anchor=(0.5, -0.2), ncol=2, frameon=False)
label_panels(fig)
plt.show()
Exercise 1: the Gordon-Schowalter derivative and the viscometric functions
==========================================================================
Max convex-combination error across xi in [0, 2]: 3.134e-15

Figure S0.1. Steady shear of the Johnson–Segalman model for four values of . (a) Polymer viscosity divided by . (b) The ratio , which does not depend on the shear rate.
Explanation. Writing shows that the Gordon–Schowalter derivative interpolates linearly between the upper-convected derivative () and the lower-convected derivative (); the computed difference between the two sides is . The viscosity depends on through the product alone: it is constant for and for , and decreases with shear rate for every value in between. When the solvent viscosity is small, the total shear stress then has a maximum, which is the subject of Lecture 8.
Exercise 2¶
Problem. A sample with the initial stress and the relaxation time rests without deformation () on a turntable that rotates at . Integrate in the laboratory frame (a) the equation with a partial time derivative, , and (b) the upper-convected Maxwell equation . For each, compute the shear stress in axes that rotate with the sample.
heading("Exercise 2: a sample at rest on a turntable")
lam_tt = 1.0
omega_tt = 4.0
L_tt = np.array([[0.0, -omega_tt, 0.0], [omega_tt, 0.0, 0.0], [0.0, 0.0, 0.0]]) # Pure rigid rotation (D == 0)
tau0 = np.diag([20.0, -10.0, -10.0])
t_tt = np.linspace(0.0, 2.0, 401)
dt_tt = float(t_tt[1] - t_tt[0])
tau_naive_lab = np.zeros((t_tt.size, 3, 3))
tau_ucm_lab = np.zeros((t_tt.size, 3, 3))
tau_naive_lab[0] = tau0
tau_ucm_lab[0] = tau0
def rhs_ucm_tt(T_m: np.ndarray) -> np.ndarray:
return L_tt @ T_m + T_m @ L_tt.T - T_m / lam_tt
for k in range(t_tt.size - 1):
# Naive partial derivative: since D == 0, d(tau)/dt = -tau / lam in lab coordinates
tau_naive_lab[k + 1] = tau0 * math.exp(-t_tt[k + 1] / lam_tt)
# Objective UCM RK4 step in lab coordinates:
T_c = tau_ucm_lab[k]
k1 = rhs_ucm_tt(T_c)
k2 = rhs_ucm_tt(T_c + 0.5 * dt_tt * k1)
k3 = rhs_ucm_tt(T_c + 0.5 * dt_tt * k2)
k4 = rhs_ucm_tt(T_c + dt_tt * k3)
tau_ucm_lab[k + 1] = T_c + (dt_tt / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)
body_xy_naive = np.zeros_like(t_tt)
body_xy_ucm = np.zeros_like(t_tt)
body_xx_naive = np.zeros_like(t_tt)
body_xx_ucm = np.zeros_like(t_tt)
for k, tv in enumerate(t_tt):
th = omega_tt * tv
Q_t = np.array([[math.cos(th), -math.sin(th), 0.0], [math.sin(th), math.cos(th), 0.0], [0.0, 0.0, 1.0]])
T_body_bad = Q_t.T @ tau_naive_lab[k] @ Q_t
T_body_ok = Q_t.T @ tau_ucm_lab[k] @ Q_t
body_xy_naive[k] = T_body_bad[0, 1]
body_xy_ucm[k] = T_body_ok[0, 1]
body_xx_naive[k] = T_body_bad[0, 0]
body_xx_ucm[k] = T_body_ok[0, 0]
peak_spurious_xy = float(np.max(np.abs(body_xy_naive)))
max_ucm_xy = float(np.max(np.abs(body_xy_ucm)))
exact_xx_decay = 20.0 * np.exp(-t_tt / lam_tt)
print(f"Largest body-frame |tau_xy| (partial d/dt) : {peak_spurious_xy:.3f} Pa")
print(f"Max body-frame |tau_xy| (UCM) : {max_ucm_xy:.3e} Pa")
print(f"Max |tau_xx_body(UCM) - 20*exp(-t/lam)| : {np.max(np.abs(body_xx_ucm - exact_xx_decay)):.3e} Pa")
assert peak_spurious_xy > 8.0
assert max_ucm_xy < 1e-5
assert np.allclose(body_xx_ucm, exact_xx_decay, atol=1e-5)
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
axes[0].plot(t_tt, body_xy_ucm, "k-", lw=2.2, label="Upper-convected Maxwell (0 Pa)")
axes[0].plot(t_tt, body_xy_naive, "--", color="#C0392B", lw=2.0, label=r"Partial derivative $\partial_t\tau_p$")
axes[0].set_xlabel("Time $t$ [s]")
axes[0].set_ylabel(r"Shear stress in the rotating sample $\tau_{xy}^{\mathrm{body}}$ [Pa]")
axes[0].set_title(r"Shear stress seen in the rotating sample")
axes[0].legend(fontsize=8)
axes[1].plot(t_tt, body_xx_ucm, "k-", lw=2.2, label=r"Upper-convected Maxwell, $20\,e^{-t/\lambda}$")
axes[1].plot(t_tt, body_xx_naive, "--", color="#E08214", lw=2.0, label=r"Partial derivative $\partial_t\tau_p$")
axes[1].set_xlabel("Time $t$ [s]")
axes[1].set_ylabel(r"Normal stress in the rotating sample $\tau_{xx}^{\mathrm{body}}$ [Pa]")
axes[1].set_title(r"Normal stress seen in the rotating sample")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 2: a sample at rest on a turntable
===========================================
Largest body-frame |tau_xy| (partial d/dt) : 12.422 Pa
Max body-frame |tau_xy| (UCM) : 8.177e-07 Pa
Max |tau_xx_body(UCM) - 20*exp(-t/lam)| : 5.457e-07 Pa

Figure S0.2. A pre-stressed sample at rest on a turntable. (a) Shear stress in the frame of the sample: zero for the upper-convected Maxwell equation, oscillating with an amplitude above 12 Pa for the equation written with the partial time derivative. (b) Normal stress in the same frame, against the exact relaxation Pa.
Explanation. The sample does not deform, so a gauge fixed to it must record , with no shear stress. The upper-convected Maxwell equation gives this result to Pa. The equation with the partial time derivative keeps the principal axes of the stress fixed in the laboratory while the sample rotates under them, and the gauge records a shear stress of up to 12.4 Pa. The terms , which every convected derivative contains, rotate the principal axes of the stress with the material.
Exercise 3¶
Problem. Write a NumPy solver of the Lodge integral for a shear rate that is piecewise constant: for and for , with and . Use the accumulated strain in the relative deformation gradient , and compare the stresses with tensors_kinematics.integrate_homogeneous_constitutive.
heading("Exercise 3: the Lodge integral for a shear rate that reverses")
G0_ex3 = 5.0
lam_ex3 = 0.8
eta_p_ex3 = G0_ex3 * lam_ex3
t_switch = 1.0
def rate_protocol(tv: float) -> float:
return 3.0 if tv <= t_switch else -2.0
def integrated_strain(t_val: float) -> np.ndarray:
tv = np.asarray(t_val, dtype=float)
return np.where(tv <= t_switch, 3.0 * tv, 3.0 * t_switch - 2.0 * (tv - t_switch))
t_grid_ex3 = np.linspace(0.0, 2.5, 251)
L_rev_fn = lambda tv: np.array([[0.0, rate_protocol(tv), 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
ucm_rev = tensors_kinematics.integrate_homogeneous_constitutive(
L_rev_fn, t_grid_ex3, lam=lam_ex3, eta_p=eta_p_ex3, model="oldroyd_b", formulation="log_psi"
)
txy_lodge_rev = np.zeros_like(t_grid_ex3)
n1_lodge_rev = np.zeros_like(t_grid_ex3)
for i, tv in enumerate(t_grid_ex3):
if tv == 0.0:
continue
# Split quadrature cleanly at t_switch if tv > t_switch to avoid slope kink error:
if tv <= t_switch:
tp_nodes = np.linspace(0.0, tv, 121)
gam_rel = integrated_strain(tv) - integrated_strain(tp_nodes)
w = (G0_ex3 / lam_ex3) * np.exp(-(tv - tp_nodes) / lam_ex3)
int_xy = float(trapezoid(w * gam_rel, tp_nodes))
int_n1 = float(trapezoid(w * (gam_rel**2), tp_nodes))
else:
tp1 = np.linspace(0.0, t_switch, 101)
tp2 = np.linspace(t_switch, tv, 101)
g1 = integrated_strain(tv) - integrated_strain(tp1)
g2 = integrated_strain(tv) - integrated_strain(tp2)
w1 = (G0_ex3 / lam_ex3) * np.exp(-(tv - tp1) / lam_ex3)
w2 = (G0_ex3 / lam_ex3) * np.exp(-(tv - tp2) / lam_ex3)
int_xy = float(trapezoid(w1 * g1, tp1) + trapezoid(w2 * g2, tp2))
int_n1 = float(trapezoid(w1 * (g1**2), tp1) + trapezoid(w2 * (g2**2), tp2))
gam_total = float(integrated_strain(tv))
tail = G0_ex3 * math.exp(-tv / lam_ex3)
txy_lodge_rev[i] = int_xy + tail * gam_total
n1_lodge_rev[i] = int_n1 + tail * (gam_total**2)
txy_ref = ucm_rev["tau_p_hist"][:, 0, 1]
n1_ref = ucm_rev["tau_p_hist"][:, 0, 0] - ucm_rev["tau_p_hist"][:, 1, 1]
err_rev_xy = float(np.max(np.abs(txy_lodge_rev - txy_ref)))
err_rev_n1 = float(np.max(np.abs(n1_lodge_rev - n1_ref)))
print(f"Step-reversal max |tau_xy(Lodge) - tau_xy(UCM)|: {err_rev_xy:.3e} Pa")
print(f"Step-reversal max |N1(Lodge) - N1(UCM)| : {err_rev_n1:.3e} Pa")
assert err_rev_xy < 2e-2 and err_rev_n1 < 5e-2
assert float(np.min(txy_lodge_rev)) < -2.0 # Stress reverses sign under negative shear
fig, axes = plt.subplots(1, 2, figsize=(10.2, 3.7))
axes[0].plot(t_grid_ex3, txy_ref, "k-", lw=2.2, label="Upper-convected Maxwell")
axes[0].plot(t_grid_ex3[::5], txy_lodge_rev[::5], "o", color="#2166AC", ms=4.5, label="Piecewise Lodge integral")
axes[0].axvline(t_switch, color="gray", ls=":", label="Shear reversal $t=1.0$ s")
axes[0].set_xlabel("Time $t$ [s]")
axes[0].set_ylabel(r"Shear stress $\tau_{xy}(t)$ [Pa]")
axes[0].set_title(r"Shear stress")
axes[0].legend(fontsize=8)
axes[1].plot(t_grid_ex3, n1_ref, "k-", lw=2.2, label="Upper-convected Maxwell $N_1$")
axes[1].plot(t_grid_ex3[::5], n1_lodge_rev[::5], "s", color="#2E8B57", ms=4.5, label="Piecewise Lodge $N_1$")
axes[1].axvline(t_switch, color="gray", ls=":")
axes[1].set_xlabel("Time $t$ [s]")
axes[1].set_ylabel(r"First normal stress difference $N_1(t)$ [Pa]")
axes[1].set_title(r"First normal stress difference")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 3: the Lodge integral for a shear rate that reverses
=============================================================
Step-reversal max |tau_xy(Lodge) - tau_xy(UCM)|: 8.004e-04 Pa
Step-reversal max |N1(Lodge) - N1(UCM)| : 3.384e-03 Pa

Figure S0.3. Shear at for 1 s followed by : the Lodge integral with the accumulated strain (symbols) against the differential equation (lines). (a) Shear stress. (b) First normal stress difference, which passes through a minimum after the reversal.
Explanation. The integral and the differential equation agree to Pa in the shear stress and to Pa in . After the reversal at the strain accumulated since an earlier time decreases, and , which depends on the square of that strain, falls before it grows again. The comparison shows that the upper-convected Maxwell equation contains the whole history of the deformation, weighted by , without storing it.