For many years calculations of viscoelastic flow failed to converge above a Weissenberg number of order 1, whatever the constitutive model and however fine the grid. This is known as the high Weissenberg number problem. Near stagnation points and corners the conformation tensor grows exponentially in space and in time; a polynomial discretization cannot follow this growth, and a time step or an interpolation produces a tensor that is not positive definite.
Fattal and Kupferman (2004) proposed to evolve the logarithm instead. An exponential profile of is a linear profile of , and is positive definite whatever the numerical error. This lecture derives the equation for , treats the case of equal eigenvalues, and compares the two formulations.
Learning objectives¶
Explain the two causes of the high Weissenberg number problem: exponential growth of the conformation tensor, and discretizations that produce .
Derive the decomposition of the velocity gradient and apply it with
tensors_kinematics.log_conformation_decomposeandexp_conformation.Show that the factor of the rotation term has a finite limit inside the commutator when two eigenvalues coincide.
Map the stability of the direct update and of the logarithmic update in the plane , and check second-order convergence.
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. Why direct integration fails: exponential profiles and polynomial approximations¶
Near a stagnation point or a re-entrant corner, where the local rate of extension is , the conformation tensor grows exponentially along a streamline, . Finite-volume and finite-element schemes and explicit time steps approximate fields by polynomials. When a polynomial represents an exponential profile on a step or that is not small, it undershoots. The undershoot is largest relative to the smallest eigenvalue, which decays as , and it can make this eigenvalue zero or negative (det C <= 0); the calculation then diverges.
Fattal and Kupferman (2004) removed both difficulties with the one-to-one map between positive definite matrices and symmetric matrices:
The map has two consequences:
An exponential profile becomes a linear one: if then , which a scheme of first or second order represents accurately.
Positive definiteness cannot be lost: for every finite symmetric the eigenvalues of are positive, and .
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()
Demonstration 1: exponential stretch, its logarithm, and a reversal of the flow
===============================================================================
Exponential range at t=2.2: C_xx = 81.02, C_yy = 0.4197 | log-space Psi_xx = 4.39, Psi_yy = -0.87
Coarse reversal (dt=0.5): direct_euler diverged: True (min det C = -9.308e+02)
Coarse reversal (dt=0.5): log_psi diverged: False (min det C = 1.000e+00 > 0)

Figure 2.1. (a) In a stretching flow grows exponentially while grows linearly. (b) A flow that reverses at s, integrated with the step s for s: the smallest eigenvalue of from the direct Euler update becomes negative, that of the log-conformation update stays positive (symmetric logarithmic axis).
2. The log-conformation decomposition and the limit of equal eigenvalues¶
The equation for cannot be obtained from by writing , because matrices do not commute (). Fattal and Kupferman (2004) showed that for any positive definite tensor and any velocity gradient there is a unique decomposition
When this is substituted into , the terms with cancel, . What remains is a rotation of the principal axes, , and a stretch along them, , in which commutes with . In the principal axes, with ,
At equilibrium, , the eigenvalues are equal, , and the rotation term contains a division by zero. The commutator in which it appears nevertheless has a finite limit:
Together with the diagonal part, , this gives in the limit, without a singularity.
heading("Demonstration 2: the logarithm and its inverse, and the limit of equal eigenvalues")
L_gen = np.array([[0.3, 2.4, -0.5], [-0.7, -0.1, 0.8], [0.2, -0.4, -0.2]])
Q_rot, _ = np.linalg.qr(np.array([[1.0, 2.0, -1.0], [0.5, -1.0, 2.0], [-1.5, 0.5, 1.0]]))
gaps = np.logspace(-13, 0, 27)
kin_diffs_from_2D = []
naive_omega_norms = []
safe_omega_norms = []
for eps in gaps:
lam_vec = np.array([1.0 + eps, 1.0, 1.0 - 0.5 * min(eps, 0.9)])
C_eps = (Q_rot * lam_vec[None, :]) @ Q_rot.T
dec = tensors_kinematics.log_conformation_decompose(C_eps, L_gen)
C_rec = tensors_kinematics.exp_conformation(dec["Psi"])
assert np.linalg.norm(C_rec - C_eps) < 1e-12
assert np.linalg.norm(dec["Omega"] + dec["Omega"].T) < 1e-8
kin_diffs_from_2D.append(float(np.linalg.norm(dec["dPsi_dt_kinematic"] - (L_gen + L_gen.T), ord="fro")))
safe_omega_norms.append(float(np.linalg.norm(dec["Omega"], ord="fro")))
# Naive unguarded formula for Omega_12 blows up as 1 / eps:
M_t = Q_rot.T @ L_gen @ Q_rot
naive_omega_norms.append(abs((lam_vec[1] * M_t[0, 1] + lam_vec[0] * M_t[1, 0]) / (lam_vec[1] - lam_vec[0])))
dec_exact_I = tensors_kinematics.log_conformation_decompose(np.eye(3), L_gen)
err_exact_I = float(np.linalg.norm(dec_exact_I["dPsi_dt_kinematic"] - (L_gen + L_gen.T), ord="fro"))
print(f"Exact C = I kinematic rate error ||dPsi/dt - (L + L^T)||_F: {err_exact_I:.3e}")
print(f"At gap 1e-13: dPsi_kin diff from 2D = {kin_diffs_from_2D[0]:.3e}, and |Omega_12| = {naive_omega_norms[0]:.3e}")
assert err_exact_I < 1e-14
assert kin_diffs_from_2D[0] < 1e-9
assert naive_omega_norms[0] > 1e11
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
axes[0].loglog(gaps, naive_omega_norms, "--", color="#C0392B", lw=2.0, label=r"Without the limit, $|\tilde{\Omega}_{12}| \propto (\lambda_2 - \lambda_1)^{-1}$")
axes[0].loglog(gaps, safe_omega_norms, "-o", color="#2166AC", ms=4, lw=1.9, label=r"Package, $\|\Omega\|_F$")
axes[0].set_xlabel(r"Eigenvalue separation $\epsilon = \lambda_1 - \lambda_2$")
axes[0].set_ylabel("Rotation operator magnitude [1/s]")
axes[0].set_title(r"Rotation rate near equal eigenvalues")
axes[0].legend(fontsize=8)
axes[1].loglog(gaps, np.maximum(kin_diffs_from_2D, 1e-16), "-s", color="#2E8B57", ms=4, lw=2.0, label=r"$\|\dot{\Psi}_{\mathrm{kin}}(\epsilon) - 2\mathbf{D}\|_F$")
axes[1].set_xlabel(r"Eigenvalue separation $\epsilon = \lambda_1 - \lambda_2$")
axes[1].set_ylabel(r"Distance to isotropic limit $2\mathbf{D}$ [1/s]")
axes[1].set_title(r"Distance of $\dot{\mathbf{\Psi}}$ from its isotropic limit")
axes[1].legend(fontsize=8.5)
label_panels(fig)
plt.show()
Demonstration 2: the logarithm and its inverse, and the limit of equal eigenvalues
==================================================================================
Exact C = I kinematic rate error ||dPsi/dt - (L + L^T)||_F: 0.000e+00
At gap 1e-13: dPsi_kin diff from 2D = 1.492e-15, and |Omega_12| = 6.394e+12

Figure 2.2. The decomposition as the two eigenvalues of approach each other. (a) The formula for diverges as ; the package switches to the limiting form below a gap of about 10-7. (b) The kinematic part of tends to in proportion to the gap.
3. Stability in the plane and second-order convergence¶
Two numerical experiments compare log_psi with direct_euler:
Stability. The Weissenberg number is varied between 0.5 and 9.5 and the time step between 0.10 and 1.50, ten values of each, in a flow that combines extension with a reversal. For each pair the experiment records whether stays positive during the whole run.
Order of convergence. The error of
log_psi, which uses a midpoint scheme, is measured in start-up of shear of the Oldroyd-B model at against the exact solution , , for decreasing . The expected order is 2.
heading("Demonstration 3: stability map and order of convergence")
wi_map = np.linspace(0.5, 9.5, 10)
dt_map = np.linspace(0.10, 1.50, 10)
ok_euler = np.zeros((dt_map.size, wi_map.size), dtype=float)
ok_log = np.zeros((dt_map.size, wi_map.size), dtype=float)
for i_d, dtr in enumerate(dt_map):
n_pts = max(4, int(round(4.0 / dtr)) + 1)
t_m = np.linspace(0.0, 4.0, n_pts)
for j_w, wv in enumerate(wi_map):
L_base = np.diag([0.6 * wv, -0.3 * wv, -0.3 * wv])
L_fn_m = lambda tv, Lb=L_base: Lb if tv < 1.5 else -1.5 * Lb
re_m = tensors_kinematics.integrate_homogeneous_constitutive(L_fn_m, t_m, lam=1.0, eta_p=1.0, formulation="direct_euler")
rl_m = tensors_kinematics.integrate_homogeneous_constitutive(L_fn_m, t_m, lam=1.0, eta_p=1.0, formulation="log_psi")
ok_euler[i_d, j_w] = 0.0 if (re_m["blew_up"] or re_m["min_det_C"] <= 0.0) else 1.0
ok_log[i_d, j_w] = 0.0 if (rl_m["blew_up"] or rl_m["min_det_C"] <= 0.0) else 1.0
# RK2 convergence study on Oldroyd-B simple shear startup (Wi = 3.0):
gdot_conv = 3.0
L_sh_conv = np.array([[0.0, gdot_conv, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
dt_conv = np.array([0.10, 0.05, 0.025, 0.0125])
err_n1_rk2 = []
for dtc in dt_conv:
tc = np.linspace(0.0, 2.0, int(round(2.0 / dtc)) + 1)
sc = tensors_kinematics.integrate_homogeneous_constitutive(lambda _t: L_sh_conv, tc, lam=1.0, eta_p=1.0, formulation="log_psi")
n1_num = sc["tau_p_hist"][:, 0, 0] - sc["tau_p_hist"][:, 1, 1]
n1_ex = 2.0 * (gdot_conv**2) * (1.0 - (1.0 + tc) * np.exp(-tc))
err_n1_rk2.append(float(np.max(np.abs(n1_num - n1_ex))))
slope_rk2 = float(np.polyfit(np.log(dt_conv), np.log(err_n1_rk2), 1)[0])
print(f"Stability survival fraction across 100 (Wi, dt) cells -> direct_euler: {np.mean(ok_euler)*100:.1f}%, log_psi: {np.mean(ok_log)*100:.1f}%")
print(f"Measured log_psi global convergence order on N1(t): p = {slope_rk2:.3f} (theoretical RK2 = 2.00)")
assert np.mean(ok_log) == 1.0
assert np.mean(ok_euler) < 0.70
assert 1.90 < slope_rk2 < 2.15
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
im = axes[0].imshow(ok_euler, origin="lower", aspect="auto", extent=[wi_map[0], wi_map[-1], dt_map[0], dt_map[-1]], cmap="RdYlGn", vmin=0.0, vmax=1.0)
plt.colorbar(im, ax=axes[0], ticks=[0, 1], label="1: positive definite, 0: not")
axes[0].set_xlabel(r"Weissenberg number $\mathrm{Wi}$")
axes[0].set_ylabel(r"Step size $\Delta t / \lambda$")
axes[0].set_title(r"Where the direct Euler update keeps $\mathbf{C}$ positive definite")
axes[1].loglog(dt_conv, err_n1_rk2, "-o", color="#2166AC", lw=2.0, ms=5.5, label=rf"Log-conformation, RK2 error (slope = {slope_rk2:.2f})")
axes[1].loglog(dt_conv, err_n1_rk2[0] * (dt_conv / dt_conv[0]) ** 2, "k--", lw=1.6, label=r"Reference $\mathcal{O}(\Delta t^2)$")
axes[1].set_xlabel(r"Time step $\Delta t / \lambda$")
axes[1].set_ylabel(r"Max error $\|N_1^{\mathrm{num}} - N_1^{\mathrm{exact}}\|_\infty$")
axes[1].set_title(r"Error of the log-conformation RK2 scheme")
axes[1].legend(fontsize=8.5)
log_ticks(axes[1], "x", [0.0125, 0.025, 0.05, 0.1])
label_panels(fig)
plt.show()
Demonstration 3: stability map and order of convergence
=======================================================
Stability survival fraction across 100 (Wi, dt) cells -> direct_euler: 10.0%, log_psi: 100.0%
Measured log_psi global convergence order on N1(t): p = 1.941 (theoretical RK2 = 2.00)

Figure 2.3. (a) Map over the Weissenberg number and the time step: the direct Euler update keeps positive definite in the green cells only (10 of 100); the log-conformation update does so in all 100. (b) Error of for the second-order log-conformation scheme against the time step; the fitted order is 1.94.
4. A mixed flow at high Weissenberg number¶
In contraction dies and in microfluidic cross-slots at high Weissenberg number a fluid element is sheared and extended at the same time. Flow birefringence measures two quantities in the plane of such a flow:
the principal stress difference , which is proportional to the optical retardation by the stress-optical rule, and
the extinction angle , the angle between the principal axis of the stress and the streamline.
The demonstration integrates the FENE-P model with through a pulse of shear and extension that reaches , with the method log_psi, and checks that the trace stays below and the determinant positive.
heading("Demonstration 4: a pulse of mixed flow at Wi = 24")
t_pulse = np.linspace(0.0, 4.0, 801)
def L_contraction_pulse(tv: float, wi_peak: float = 24.0) -> np.ndarray:
bell = math.exp(-((tv - 1.5) / 0.55) ** 2)
g_sh = wi_peak * (0.25 + 0.75 * bell)
eps_p = 0.35 * wi_peak * bell
return np.array([[eps_p, g_sh, 0.0], [0.0, -eps_p, 0.0], [0.0, 0.0, 0.0]], dtype=float)
sol_hi = tensors_kinematics.integrate_homogeneous_constitutive(
L_contraction_pulse, t_pulse, lam=1.0, eta_p=1.0, model="fenep", b_fenep=60.0, formulation="log_psi"
)
C_hi = sol_hi["C_hist"]
tau_hi = sol_hi["tau_p_hist"]
tr_C_hi = np.trace(C_hi, axis1=1, axis2=2)
det_C_hi = np.linalg.det(C_hi)
delta_tau = np.sqrt((tau_hi[:, 0, 0] - tau_hi[:, 1, 1]) ** 2 + 4.0 * (tau_hi[:, 0, 1] ** 2))
chi_deg = 0.5 * np.degrees(np.arctan2(2.0 * tau_hi[:, 0, 1], np.maximum(tau_hi[:, 0, 0] - tau_hi[:, 1, 1], 1e-12)))
print(f"Wi=24 FENE-P pulse -> peak tr(C) = {np.max(tr_C_hi):.2f} (< b+3 = 63.0), min det(C) = {np.min(det_C_hi):.3e} > 0")
print(f"Peak birefringence anisotropy Delta_tau = {np.max(delta_tau):.1f}, min alignment angle chi = {np.min(chi_deg):.2f} deg")
assert not sol_hi["blew_up"]
assert float(np.min(det_C_hi)) > 0.0
assert float(np.max(tr_C_hi)) < 63.0
assert float(np.min(chi_deg)) < 12.0 # Strong chain alignment toward x-axis during pulse
fig, axes = plt.subplots(1, 2, figsize=(10.5, 3.8))
axes[0].plot(t_pulse, tr_C_hi, color="#2166AC", lw=2.1, label=r"Stretch trace $\mathrm{tr}\,\mathbf{C}(t)$")
axes[0].axhline(63.0, color="#C0392B", ls="--", label="Limit $b + 3 = 63$")
axes[0].set_xlabel("Dimensionless time $t / \\lambda$")
axes[0].set_ylabel(r"Conformation trace $\mathrm{tr}\,\mathbf{C}$")
axes[0].set_title(r"Trace of $\mathbf{C}$")
axes[0].legend(fontsize=8)
ax2_twin = axes[1].twinx()
ax2_twin.spines["right"].set_visible(True)
l1 = axes[1].plot(t_pulse, delta_tau, color="#2E8B57", lw=2.1, label=r"Principal stress $\Delta\tau$")
l2 = ax2_twin.plot(t_pulse[8:], chi_deg[8:], "--", color="#7B4FA3", lw=2.0, label=r"Extinction angle $\chi$ [degrees]")
axes[1].set_xlabel("Dimensionless time $t / \\lambda$")
axes[1].set_ylabel(r"Stress anisotropy $\Delta\tau$", color="#2E8B57")
ax2_twin.set_ylabel(r"Extinction angle $\chi$ [degrees]", color="#7B4FA3")
axes[1].set_title(r"Stress difference and extinction angle")
lines_all = l1 + l2
axes[1].legend(lines_all, [ln.get_label() for ln in lines_all], fontsize=8, loc="upper right")
label_panels(fig)
plt.show()
Demonstration 4: a pulse of mixed flow at Wi = 24
=================================================
Wi=24 FENE-P pulse -> peak tr(C) = 59.44 (< b+3 = 63.0), min det(C) = 1.069e-01 > 0
Peak birefringence anisotropy Delta_tau = 999.7, min alignment angle chi = 0.00 deg

Figure 2.4. FENE-P model () in a pulse of mixed shear and planar extension with a peak rate of . (a) The trace of stays below . (b) Principal stress difference (left axis) and extinction angle (right axis).
Inside the algorithm¶
The cell below prints the source of tensors_kinematics.log_conformation_decompose and tensors_kinematics.exp_conformation. The function log_conformation_decompose computes comm_tilde[i, j] = om_ij * (log_lam[j] - log_lam[i]) when the relative difference of two eigenvalues exceeds 1e-7, and uses the limit m_ij + m_ji when the eigenvalues are closer.
Check against the package¶
The evolution of does not need the tensor , because its contributions cancel, . The check below constructs it nevertheless, , in NumPy, and verifies that holds to 10-13 and that .
heading("Inside the algorithm: the decomposition of the velocity gradient")
print(show_source(tensors_kinematics.log_conformation_decompose))
print(show_source(tensors_kinematics.exp_conformation))
C_fk = np.array([[4.2, 1.3, -0.6], [1.3, 1.5, 0.4], [-0.6, 0.4, 0.8]], dtype=float)
L_fk = np.array([[0.4, 3.1, -0.7], [-0.9, -0.2, 0.6], [0.3, -0.5, -0.2]], dtype=float)
dec_fk = tensors_kinematics.log_conformation_decompose(C_fk, L_fk)
R_fk = dec_fk["eigenvectors"]
ev_fk = dec_fk["eigenvalues"]
M_tilde = R_fk.T @ L_fk @ R_fk
N_tilde = np.zeros((3, 3), dtype=float)
for i in range(3):
for j in range(i + 1, 3):
nij = (M_tilde[i, j] + M_tilde[j, i]) / ((1.0 / ev_fk[j]) - (1.0 / ev_fk[i]))
N_tilde[i, j] = nij
N_tilde[j, i] = -nij
N_fk = R_fk @ N_tilde @ R_fk.T
Omega_fk = dec_fk["Omega"]
B_fk = dec_fk["B_stretch"]
L_reconstructed = Omega_fk + B_fk + N_fk @ np.linalg.inv(C_fk)
dC_uc = L_fk @ C_fk + C_fk @ L_fk.T
dC_fk = (Omega_fk @ C_fk - C_fk @ Omega_fk) + 2.0 * (B_fk @ C_fk)
err_L_decomp = float(np.linalg.norm(L_reconstructed - L_fk, ord="fro"))
err_dC_id = float(np.linalg.norm(dC_fk - dC_uc, ord="fro"))
err_B_comm = float(np.linalg.norm(B_fk @ C_fk - C_fk @ B_fk, ord="fro"))
print(f"Exact decomposition residual ||(Omega + B + N C^-1) - L||_F : {err_L_decomp:.3e}")
print(f"Upper-convected identity ||([Omega, C] + 2BC) - (LC+CL^T)||_F: {err_dC_id:.3e}")
print(f"Commutativity check ||[B, C]||_F : {err_B_comm:.3e}")
assert err_L_decomp < 1e-13 and err_dC_id < 1e-13 and err_B_comm < 1e-13
assert np.linalg.norm(N_fk + N_fk.T) < 1e-13
Inside the algorithm: the decomposition of the velocity gradient
================================================================
def log_conformation_decompose(C: np.ndarray, L_grad_u: np.ndarray) -> dict:
"""The decomposition L = Omega + B + N C^-1 of Fattal and Kupferman (2004), in two or three dimensions."""
C_sym = 0.5 * (np.asarray(C, dtype=float) + np.asarray(C, dtype=float).T)
L = np.asarray(L_grad_u, dtype=float)
if C_sym.shape != L.shape or C_sym.ndim != 2 or C_sym.shape[0] not in (2, 3):
raise ValueError("Require matching 2x2 or 3x3 conformation C and velocity gradient L.")
evals, R = np.linalg.eigh(C_sym)
if np.any(evals <= 0.0):
raise ValueError(
"log_conformation_decompose requires strictly SPD conformation tensor C (all eigenvalues > 0)."
)
log_lam = np.log(evals)
Psi = (R * log_lam[None, :]) @ R.T
Psi = 0.5 * (Psi + Psi.T)
M_tilde = R.T @ L @ R
d = C_sym.shape[0]
B_tilde = np.diag(np.diag(M_tilde))
Omega_tilde = np.zeros((d, d), dtype=float)
# Advectless logarithmic kinematics: dPsi/dt_kin = [Omega, Psi] + 2 B.
# Notice [Omega_tilde, diag(log_lam)]_ij = Omega_tilde_ij * (log_lam_j - log_lam_i).
# For lam_i -> lam_j, (log_lam_j - log_lam_i)/(lam_j - lam_i) -> 1/lam_i, so the commutator
# smoothly approaches (M_tilde_ij + M_tilde_ji) = 2 D_tilde_ij with zero division-by-zero singularity
comm_tilde = np.zeros((d, d), dtype=float)
for i in range(d):
for j in range(i + 1, d):
li, lj = float(evals[i]), float(evals[j])
m_ij, m_ji = float(M_tilde[i, j]), float(M_tilde[j, i])
rel_gap = abs(lj - li) / (0.5 * (li + lj))
if rel_gap > 1e-7:
om_ij = (lj * m_ij + li * m_ji) / (lj - li)
Omega_tilde[i, j] = om_ij
Omega_tilde[j, i] = -om_ij
c_ij = om_ij * (log_lam[j] - log_lam[i])
comm_tilde[i, j] = c_ij
comm_tilde[j, i] = c_ij
else:
# Exact analytical isotropic limit:
om_ij = 0.5 * (m_ij - m_ji)
Omega_tilde[i, j] = om_ij
Omega_tilde[j, i] = -om_ij
c_ij = m_ij + m_ji
comm_tilde[i, j] = c_ij
comm_tilde[j, i] = c_ij
B_stretch = R @ B_tilde @ R.T
Omega = R @ Omega_tilde @ R.T
dPsi_kin = R @ (comm_tilde + 2.0 * B_tilde) @ R.T
dPsi_kin = 0.5 * (dPsi_kin + dPsi_kin.T)
return {
"Psi": Psi,
"Omega": Omega,
"B_stretch": 0.5 * (B_stretch + B_stretch.T),
"dPsi_dt_kinematic": dPsi_kin,
"eigenvalues": evals,
"eigenvectors": R,
}
def exp_conformation(Psi: np.ndarray) -> np.ndarray:
"""Matrix exponential C = exp(Psi) of a symmetric matrix; C is positive definite for every finite Psi."""
Psi_sym = 0.5 * (np.asarray(Psi, dtype=float) + np.asarray(Psi, dtype=float).T)
evals, R = np.linalg.eigh(Psi_sym)
C = (R * np.exp(np.clip(evals, -80.0, 80.0))[None, :]) @ R.T
return 0.5 * (C + C.T)
Exact decomposition residual ||(Omega + B + N C^-1) - L||_F : 3.791e-15
Upper-convected identity ||([Omega, C] + 2BC) - (LC+CL^T)||_F: 4.023e-15
Commutativity check ||[B, C]||_F : 4.003e-16
Exercises¶
Worked solutions are in 02_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. 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.
Find how it fails. Compare the methods
direct_eulerandlog_psiin a uniaxial extension that reverses:lam = 0.22, for and -1.8 times this tensor for , on the gridnp.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 wheredirect_eulerbecomes stable.Implement it yourself. 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("Self-check for the exercises")
atlas_02 = [entry for entry in constants_benchmarks.RHEO_ATLAS_DB if entry["lecture"] == "02"]
assert len(atlas_02) == 1
assert err_L_decomp < 1e-13 and err_exact_I < 1e-14
assert np.mean(ok_log) == 1.0 and 1.90 < slope_rk2 < 2.15
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.