A viscoelastic flow solver stores a symmetric tensor in each cell: the conformation tensor , the second moment of the end-to-end vector of the polymer molecules, scaled so that at equilibrium. As a second moment it must be positive definite. The free energy of the polymer and the rate at which it dissipates energy are functions of , and both lose their meaning when an eigenvalue of becomes negative.
This lecture builds from an ensemble of dumbbells, derives its free energy and the balance between the work done by the flow, the stored energy and the dissipation, and examines two limits: the divergence of the Oldroyd-B stress in extension at , which the FENE-P and Giesekus models remove, and the loss of positive definiteness through numerical error.
Learning objectives¶
Form the conformation tensor from an ensemble of dumbbells and test its positive definiteness with
tensors_kinematics.check_spd_conformation.Derive the free energy and check the balance , with , in a transient flow.
Compute the Trouton ratio of the Oldroyd-B model, which diverges at , and compare it with the FENE-P and Giesekus models.
Find what happens to the eigenvalues and to the dissipation when is not positive definite.
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. The conformation tensor as a second moment, and positive definiteness¶
Consider a dilute solution with polymer molecules per unit volume. Each molecule is described by its end-to-end vector in dimensions ( or 3), whose components have the variance at equilibrium. The dimensionless conformation tensor is the second moment of divided by this variance,
For any non-zero vector , , provided the thermal fluctuations of have components in all directions. The tensor is therefore symmetric and positive definite. Two equivalent statements are:
All eigenvalues are positive. Their square roots are the stretch ratios of the molecules along the principal axes.
All leading principal minors are positive (Sylvester’s criterion): , , .
The free-energy density of Hookean dumbbells is
It is zero at equilibrium and tends to as , that is when the smallest eigenvalue tends to zero: a state in which the molecules have no extension in one direction has an infinite entropic cost.
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()
Demonstration 1: the conformation tensor of an ensemble and its free energy
===========================================================================
Equilibrium C = I : is_spd=True, psi/G0=0.000e+00
Deformed ensemble : is_spd=True, min_eig=0.5122, psi/G0=0.7513
Sylvester minors : Delta_1=3.3004 > 0, Delta_2=1.7567 > 0, Delta_3=1.0166 > 0

Figure 1.1. (a) Free energy on the plane at . The shaded region below the curve contains no positive-definite tensor. (b) Contribution of one eigenvalue: zero at equilibrium and unbounded as .
2. Work, free energy and dissipation¶
In an isothermal flow the power of the polymer stress, , must equal the rate of change of the stored free energy, , plus a dissipation that is never negative. For the Oldroyd-B model the conformation tensor obeys . Differentiating along this evolution gives the stress as a derivative of the free energy, , and the balance
In start-up of shear the work of the flow increases the free energy () until the steady state, in which and all the power is dissipated, . When the flow stops (), the power is zero and the stored energy decreases monotonically, .
heading("Demonstration 2: work, free energy and dissipation in start-up and cessation of shear")
G0_cd = 4.0
lam_cd = 0.8
eta_p_cd = G0_cd * lam_cd
t_cd = np.linspace(0.0, 3.2, 321)
t_stop = 1.6
L_cess_fn = lambda tv: np.array([[0.0, 3.0 if tv < t_stop else 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
sol_cd = tensors_kinematics.integrate_homogeneous_constitutive(
L_cess_fn, t_cd, lam=lam_cd, eta_p=eta_p_cd, model="oldroyd_b", formulation="log_psi"
)
psi_t = np.zeros_like(t_cd)
p_stress = np.zeros_like(t_cd)
phi_diss = np.zeros_like(t_cd)
for k, tv in enumerate(t_cd):
Ck = sol_cd["C_hist"][k]
chk = tensors_kinematics.check_spd_conformation(Ck, G0=G0_cd)
assert chk["is_spd"]
psi_t[k] = chk["free_energy_hookean"]
Lk = L_cess_fn(float(tv))
Dk = 0.5 * (Lk + Lk.T)
p_stress[k] = float(np.sum(sol_cd["tau_p_hist"][k] * Dk))
C_inv = np.linalg.inv(Ck)
phi_diss[k] = (0.5 * G0_cd / lam_cd) * float(np.trace(Ck + C_inv - 2.0 * np.eye(3)))
dpsi_dt = np.gradient(psi_t, t_cd)
# Exclude the discontinuous shear-rate jump neighborhood around t_stop for smooth FD budget check:
smooth_mask = (np.abs(t_cd - t_stop) > 0.04) & (t_cd > 0.02) & (t_cd < 3.18)
budget_err = float(np.max(np.abs(p_stress[smooth_mask] - (dpsi_dt[smooth_mask] + phi_diss[smooth_mask]))))
work_in = float(trapezoid(p_stress, t_cd))
diss_tot = float(trapezoid(phi_diss, t_cd)) + float(psi_t[-1] - psi_t[0])
print(f"Pointwise Clausius-Duhem residual max |P - (dpsi/dt + Phi_diss)|: {budget_err:.3e} W/m^3")
print(f"Integrated mechanical work = {work_in:.4f} J/m^3 against (diss + Delta_psi) = {diss_tot:.4f} J/m^3")
assert budget_err < 2e-2
assert abs(work_in - diss_tot) / work_in < 5e-3
assert np.all(phi_diss >= -1e-14)
assert np.all(dpsi_dt[t_cd > t_stop + 0.05] <= 1e-12)
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
axes[0].plot(t_cd, p_stress, color="#2166AC", lw=2.0, label=r"Stress power $\tau_p : \mathbf{D}$")
axes[0].plot(t_cd, dpsi_dt, color="#2E8B57", lw=2.0, label=r"Storage rate $d\psi / dt$")
axes[0].plot(t_cd, phi_diss, color="#C0392B", lw=2.0, label=r"Dissipation $\Phi_{\mathrm{diss}} \geq 0$")
axes[0].axvline(t_stop, color="gray", ls=":", label="Cessation $t=1.6$ s")
axes[0].set_xlabel("Time $t$ [s]")
axes[0].set_ylabel(r"Power density [$\mathrm{W/m^3}$]")
axes[0].set_title(r"Power balance")
axes[0].legend(fontsize=8)
axes[1].plot(t_cd, psi_t, color="#7B4FA3", lw=2.2, label=r"Stored free energy $\psi(t)$")
axes[1].axvline(t_stop, color="gray", ls=":")
axes[1].set_xlabel("Time $t$ [s]")
axes[1].set_ylabel(r"Free-energy density $\psi(\mathbf{C})$ [$\mathrm{J/m^3}$]")
axes[1].set_title(r"Stored free energy")
axes[1].legend(fontsize=8.5)
label_panels(fig)
plt.show()
Demonstration 2: work, free energy and dissipation in start-up and cessation of shear
=====================================================================================
Pointwise Clausius-Duhem residual max |P - (dpsi/dt + Phi_diss)|: 1.937e-03 W/m^3
Integrated mechanical work = 26.0313 J/m^3 against (diss + Delta_psi) = 26.1562 J/m^3

Figure 1.2. Start-up of shear until s, then cessation. (a) Stress power, rate of change of the free energy and dissipation; the dissipation is never negative. (b) Free energy density, which rises during the flow and decays after it stops.
3. Uniaxial extension: the divergence at ¶
The Oldroyd-B model, with its linear spring, fails in extension whatever the accuracy of the solver. In steady uniaxial extension, , with the Weissenberg number , the equation for the axial component is
For the Trouton ratio tends to the Newtonian value 3. At the rate of stretching by the flow, , equals the rate of relaxation, , and and the extensional viscosity diverge. Two modifications available in integrate_homogeneous_constitutive remove this divergence:
The FENE-P model (finite extensibility with the approximation of Peterlin) replaces the relaxation term by . The trace then stays below , and the Trouton ratio approaches a plateau of order at high .
The Giesekus (1982) model adds the quadratic term , with , which stands for a drag that depends on the orientation. The Trouton ratio then tends to .
heading("Demonstration 3: Trouton ratios of the Oldroyd-B, FENE-P and Giesekus models")
wi_ext_ob = np.linspace(0.02, 0.40, 8)
wi_ext_nl = np.linspace(0.02, 1.60, 12)
t_ext_ob = np.linspace(0.0, 42.0, 221)
t_ext = np.linspace(0.0, 10.0, 121)
tr_ob_num = []
for w in wi_ext_ob:
L_u = np.diag([float(w), -0.5 * float(w), -0.5 * float(w)])
res = tensors_kinematics.integrate_homogeneous_constitutive(lambda _t, L=L_u: L, t_ext_ob, lam=1.0, eta_p=1.0, model="oldroyd_b")
tr_ob_num.append(float(res["tau_p_hist"][-1, 0, 0] - res["tau_p_hist"][-1, 1, 1]) / float(w))
tr_fenep_50, tr_fenep_120, tr_gies_02 = [], [], []
for w in wi_ext_nl:
L_u = np.diag([float(w), -0.5 * float(w), -0.5 * float(w)])
rf50 = tensors_kinematics.integrate_homogeneous_constitutive(lambda _t, L=L_u: L, t_ext, lam=1.0, eta_p=1.0, model="fenep", b_fenep=50.0)
rf120 = tensors_kinematics.integrate_homogeneous_constitutive(lambda _t, L=L_u: L, t_ext, lam=1.0, eta_p=1.0, model="fenep", b_fenep=120.0)
rg02 = tensors_kinematics.integrate_homogeneous_constitutive(lambda _t, L=L_u: L, t_ext, lam=1.0, eta_p=1.0, model="giesekus", alpha_giesekus=0.2)
tr_fenep_50.append(float(rf50["tau_p_hist"][-1, 0, 0] - rf50["tau_p_hist"][-1, 1, 1]) / float(w))
tr_fenep_120.append(float(rf120["tau_p_hist"][-1, 0, 0] - rf120["tau_p_hist"][-1, 1, 1]) / float(w))
tr_gies_02.append(float(rg02["tau_p_hist"][-1, 0, 0] - rg02["tau_p_hist"][-1, 1, 1]) / float(w))
tr_ob_exact = 3.0 / ((1.0 - 2.0 * wi_ext_ob) * (1.0 + wi_ext_ob))
rel_err_ob = float(np.max(np.abs(np.array(tr_ob_num[:-1]) - tr_ob_exact[:-1]) / tr_ob_exact[:-1]))
print(f"Oldroyd-B Trouton ratio (Wi <= 0.42) max rel err: {rel_err_ob:.3e}")
print(f"Wi -> 0 Trouton limit (FENE-P b=120): {tr_fenep_120[0]:.3f} (exact Newtonian = 3.0)")
print(f"Wi = 1.6 Trouton ratios -> FENE-P(b=50): {tr_fenep_50[-1]:.1f}, FENE-P(b=120): {tr_fenep_120[-1]:.1f}, Giesekus(a=0.2): {tr_gies_02[-1]:.2f}")
assert rel_err_ob < 1e-2
assert 2.95 < tr_fenep_120[0] < 3.25
assert tr_fenep_120[-1] > 2.0 * tr_fenep_50[-1]
assert 7.5 < tr_gies_02[-1] < 10.0 # Approaches 2 / alpha = 10 from below
wi_fine = np.linspace(0.0, 0.485, 200)
fig, ax = plt.subplots(figsize=(7.6, 4.0))
ax.semilogy(wi_fine, 3.0 / ((1.0 - 2.0 * wi_fine) * (1.0 + wi_fine)), "k-", lw=2.0, label="Exact Oldroyd-B $3/[(1-2\\mathrm{Wi})(1+\\mathrm{Wi})]$")
ax.semilogy(wi_ext_ob, tr_ob_num, "ko", ms=5, label="Oldroyd-B numerical")
ax.semilogy(wi_ext_nl, tr_fenep_120, "-s", color="#2166AC", ms=4.5, lw=1.9, label="FENE-P ($b = 120$)")
ax.semilogy(wi_ext_nl, tr_fenep_50, "-^", color="#2E8B57", ms=4.5, lw=1.9, label="FENE-P ($b = 50$)")
ax.semilogy(wi_ext_nl, tr_gies_02, "-d", color="#C0392B", ms=4.5, lw=1.9, label=r"Giesekus ($\alpha = 0.2 \to 2/\alpha = 10$)")
ax.axvline(0.5, color="gray", ls="--", lw=1.5, label=r"Divergence at $\mathrm{Wi} = 1/2$")
ax.set_xlabel(r"Extensional Weissenberg number $\mathrm{Wi} = \lambda\dot{\varepsilon}$")
ax.set_ylabel(r"Trouton ratio $\eta_{E,p} / \eta_p$")
ax.set_title(r"Trouton ratio in uniaxial extension")
ax.legend(fontsize=8)
plt.show()
Demonstration 3: Trouton ratios of the Oldroyd-B, FENE-P and Giesekus models
============================================================================
Oldroyd-B Trouton ratio (Wi <= 0.42) max rel err: 2.133e-06
Wi -> 0 Trouton limit (FENE-P b=120): 3.063 (exact Newtonian = 3.0)
Wi = 1.6 Trouton ratios -> FENE-P(b=50): 74.4, FENE-P(b=120): 170.7, Giesekus(a=0.2): 8.09

Figure 1.3. Polymer Trouton ratio against the extensional Weissenberg number. The Oldroyd-B value diverges at ; the FENE-P model ( and 120) and the Giesekus model () stay finite beyond it.
4. FENE-P and Giesekus models in simple shear¶
Both the FENE-P and the Giesekus model keep the extensional stress finite and predict shear thinning in simple shear, but they differ in the second normal stress difference :
In the FENE-P model the relaxation term is a scalar function times , so that and in simple shear. The model is used for dilute solutions.
In the Giesekus model the quadratic term couples into , which becomes smaller than , so that . The model is used for concentrated solutions and melts, with ; for larger the shear stress decreases with shear rate.
heading("Demonstration 4: FENE-P and Giesekus models in simple shear")
wi_sh_grid = np.logspace(-1.0, 1.2, 10)
t_sh_long = np.linspace(0.0, 14.0, 161)
eta_fp, eta_gk, n2n1_fp, n2n1_gk = [], [], [], []
for w in wi_sh_grid:
L_s = np.array([[0.0, float(w), 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
s_fp = tensors_kinematics.integrate_homogeneous_constitutive(lambda _t, L=L_s: L, t_sh_long, lam=1.0, eta_p=1.0, model="fenep", b_fenep=40.0)
s_gk = tensors_kinematics.integrate_homogeneous_constitutive(lambda _t, L=L_s: L, t_sh_long, lam=1.0, eta_p=1.0, model="giesekus", alpha_giesekus=0.25)
tfp, tgk = s_fp["tau_p_hist"][-1], s_gk["tau_p_hist"][-1]
eta_fp.append(float(tfp[0, 1] / w))
eta_gk.append(float(tgk[0, 1] / w))
n2n1_fp.append(float((tfp[1, 1] - tfp[2, 2]) / max(tfp[0, 0] - tfp[1, 1], 1e-12)))
n2n1_gk.append(float((tgk[1, 1] - tgk[2, 2]) / max(tgk[0, 0] - tgk[1, 1], 1e-12)))
print(f"FENE-P (b=40) at Wi=10 -> eta/eta_p={eta_fp[-2]:.3f}, N2/N1={n2n1_fp[-2]:.3e}")
print(f"Giesekus (a=0.25) at Wi=10 -> eta/eta_p={eta_gk[-2]:.3f}, N2/N1={n2n1_gk[-2]:.3f}")
assert max(abs(x) for x in n2n1_fp) < 1e-8
assert n2n1_gk[0] < -0.10 and eta_gk[-1] < 0.25 and eta_fp[-1] < 0.55
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
axes[0].loglog(wi_sh_grid, eta_fp, "-o", color="#2166AC", lw=2.0, ms=4.5, label="FENE-P ($b=40$)")
axes[0].loglog(wi_sh_grid, eta_gk, "-s", color="#C0392B", lw=2.0, ms=4.5, label=r"Giesekus ($\alpha=0.25$)")
axes[0].axhline(1.0, color="gray", ls=":", label="Oldroyd-B constant $\\eta_p$")
axes[0].set_xlabel(r"Shear Weissenberg number $\mathrm{Wi} = \lambda\dot{\gamma}$")
axes[0].set_ylabel(r"Normalized shear viscosity $\eta_p(\mathrm{Wi}) / \eta_{p,0}$")
axes[0].set_title(r"Shear viscosity")
axes[0].legend(fontsize=8.5)
axes[1].semilogx(wi_sh_grid, n2n1_fp, "-o", color="#2166AC", lw=2.0, ms=4.5, label=r"FENE-P ($N_2 \equiv 0$)")
axes[1].semilogx(wi_sh_grid, n2n1_gk, "-s", color="#C0392B", lw=2.0, ms=4.5, label=r"Giesekus ($N_2 < 0$)")
axes[1].axhline(-0.125, color="gray", ls="--", label=r"Low-$\mathrm{Wi}$ Giesekus limit $-\alpha / 2 = -0.125$")
axes[1].set_xlabel(r"Shear Weissenberg number $\mathrm{Wi} = \lambda\dot{\gamma}$")
axes[1].set_ylabel(r"Normal stress ratio $N_2 / N_1$")
axes[1].set_title(r"Normal-stress ratio")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Demonstration 4: FENE-P and Giesekus models in simple shear
===========================================================
FENE-P (b=40) at Wi=10 -> eta/eta_p=0.507, N2/N1=-3.417e-15
Giesekus (a=0.25) at Wi=10 -> eta/eta_p=0.153, N2/N1=-0.064

Figure 1.4. Steady shear of the FENE-P model () and the Giesekus model (). (a) Polymer viscosity divided by its zero-shear value. (b) The ratio : zero for FENE-P, negative for Giesekus with the low-rate limit (dashed).
Inside the algorithm¶
The cell below prints the source of tensors_kinematics.check_spd_conformation. The function computes the symmetry error and the smallest eigenvalue of the symmetric part of , and evaluates the logarithm of the determinant as only if that eigenvalue exceeds a tolerance.
Check against the package¶
The check below verifies the relation numerically. It differentiates by central differences in all symmetric directions , for an anisotropic positive definite , and compares the result with ; the difference is below 10-10.
heading("Inside the algorithm: the free energy and the stress derived from it")
print(show_source(tensors_kinematics.check_spd_conformation))
C_probe = np.array([[2.6, 0.85, -0.25], [0.85, 1.15, 0.20], [-0.25, 0.20, 0.75]], dtype=float)
G0_probe = 3.5
def psi_pure_numpy(C_mat: np.ndarray, G0_val: float) -> float:
return 0.5 * G0_val * (float(np.trace(C_mat)) - math.log(float(np.linalg.det(C_mat))) - C_mat.shape[0])
eps_fd = 1e-6
dpsi_dC = np.zeros((3, 3), dtype=float)
for i in range(3):
for j in range(3):
E = np.zeros((3, 3), dtype=float)
E[i, j] = 1.0
# Differentiate on the unrestricted GL+(3) matrix manifold so (dpsi/dC)_ij = (G0/2)*(delta_ij - (C^-1)_ji):
p_plus = psi_pure_numpy(C_probe + eps_fd * E, G0_probe)
p_minus = psi_pure_numpy(C_probe - eps_fd * E, G0_probe)
dpsi_dC[i, j] = (p_plus - p_minus) / (2.0 * eps_fd)
tau_from_thermodynamics = 2.0 * (C_probe @ dpsi_dC.T)
tau_kramers_exact = G0_probe * (C_probe - np.eye(3))
grad_err = float(np.linalg.norm(tau_from_thermodynamics - tau_kramers_exact, ord="fro"))
pkg_psi = tensors_kinematics.check_spd_conformation(C_probe, G0=G0_probe)["free_energy_hookean"]
print(f"NumPy psi(C) = {psi_pure_numpy(C_probe, G0_probe):.8f} against package = {pkg_psi:.8f}")
print(f"Thermodynamic stress ||2 C (dpsi/dC)^T - G0(C - I)||_F = {grad_err:.3e}")
assert abs(psi_pure_numpy(C_probe, G0_probe) - pkg_psi) < 1e-14
assert grad_err < 1e-8
Inside the algorithm: the free energy and the stress derived from it
====================================================================
def check_spd_conformation(C: np.ndarray, G0: float = 1.0, tol: float = 1e-12) -> dict:
"""Test the symmetry and positive definiteness of C and return its dimensionless Hookean free energy."""
C_m = np.asarray(C, dtype=float)
if C_m.ndim != 2 or C_m.shape[0] != C_m.shape[1]:
raise ValueError("Conformation tensor C must be a square 2-D matrix.")
sym_err = float(np.max(np.abs(C_m - C_m.T)))
C_sym = 0.5 * (C_m + C_m.T)
evals = np.linalg.eigvalsh(C_sym)
min_ev = float(np.min(evals))
det_c = float(np.prod(evals))
tr_c = float(np.sum(evals))
is_spd = (sym_err <= 1e-9) and (min_ev > tol)
d = C_m.shape[0]
psi = 0.5 * float(G0) * (tr_c - float(np.sum(np.log(np.maximum(evals, 1e-300)))) - d) if is_spd else math.nan
return {
"is_spd": is_spd,
"min_eigenvalue": min_ev,
"eigenvalues": evals,
"det_C": det_c,
"trace_C": tr_c,
"free_energy_hookean": psi,
}
NumPy psi(C) = 1.98717840 against package = 1.98717840
Thermodynamic stress ||2 C (dpsi/dC)^T - G0(C - I)||_F = 3.714e-09
Exercises¶
Worked solutions are in 01_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Check with
tensors_kinematics.integrate_homogeneous_constitutivethat the Trouton ratio of an Oldroyd-B fluid is in uniaxial extension and in planar extension, for .Find how it fails. 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.
Implement it yourself. 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("Self-check for the exercises")
atlas_01 = [entry for entry in constants_benchmarks.RHEO_ATLAS_DB if entry["lecture"] == "01"]
assert len(atlas_01) == 1
assert budget_err < 2e-2 and grad_err < 1e-8
assert max(abs(x) for x in n2n1_fp) < 1e-8 and n2n1_gk[0] < -0.10
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.