The log-conformation formulation of Lecture 2 keeps the conformation tensor positive definite in a given velocity field. When the polymer stress is coupled to the momentum equation, a second difficulty appears if the solvent contributes little to the viscosity (): the viscous term , which makes the momentum equation elliptic in the velocity, becomes small, and an iteration that treats the polymer stress explicitly stops converging.
The DEVSS method of Guénette and Fortin (1995) adds a viscous term to the implicit side of the momentum equation and subtracts the same term on the explicit side; in the variant DEVSS-G of Liu, Bornside, Armstrong and Brown (1998) the subtracted term is computed from the velocity gradient. The converged solution is unchanged and the iteration is stabilized. This lecture treats the building blocks of a two-dimensional solver (a Poisson solver and the projection step, a log-conformation step, and DEVSS-G) and applies the solver of the package, which works with the stream function, to cavity flow.
Learning objectives¶
Explain why the coupled iteration fails as .
Derive the DEVSS-G terms, with the effective viscosity ratio , and show that they cancel in a converged solution.
Check the Poisson solver based on the discrete cosine transform, the projection step and the two-dimensional log-conformation step against exact solutions.
Compute cavity flow at small solvent viscosity ratios, with everywhere.
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 projection step and the Poisson solver¶
With lengths scaled by , velocities by and stresses with the total viscosity , the equations of two-dimensional viscoelastic flow are
with the polymer stress . To make a velocity field divergence free, or to obtain the pressure from the momentum balance, one solves a Poisson problem with Neumann conditions on a cell-centred grid. The problem has a solution only if has zero mean, and the solution is fixed by requiring that has zero mean as well.
The function viscoelastic_fvm_2d._dct2_poisson_neumann_2d uses the discrete cosine transform. The cosine modes correspond to an even reflection of the cell values across the four walls, and they are the eigenvectors of the five-point Laplacian with Neumann conditions, with the eigenvalues
A velocity field is made divergence free by subtracting , where (the projection step). The cost is of order operations.
heading("Demonstration 1: the Poisson solver and the projection step")
# 1. Verify exact discrete 5-point Neumann Laplacian inversion to machine precision (~1e-14):
nx_p, ny_p = 32, 32
hx_p, hy_p = 1.0 / nx_p, 1.0 / ny_p
xp = (np.arange(nx_p) + 0.5) * hx_p
yp = (np.arange(ny_p) + 0.5) * hy_p
Xp, Yp = np.meshgrid(xp, yp, indexing="ij")
rhs_raw = np.cos(math.pi * Xp) * np.cos(2.0 * math.pi * Yp) + 0.4 * np.cos(3.0 * math.pi * Xp)
rhs_zm = rhs_raw - float(np.mean(rhs_raw))
p_sol = viscoelastic_fvm_2d._dct2_poisson_neumann_2d(rhs_zm, hx_p, hy_p)
# Apply discrete 5-point zero-flux Neumann Laplacian (ghost cells equal boundary cells -> mode='edge'):
p_pad = np.pad(p_sol, 1, mode="edge")
neg_lap_p = -(
(p_pad[2:, 1:-1] - 2.0 * p_pad[1:-1, 1:-1] + p_pad[:-2, 1:-1]) / (hx_p**2)
+ (p_pad[1:-1, 2:] - 2.0 * p_pad[1:-1, 1:-1] + p_pad[1:-1, :-2]) / (hy_p**2)
)
alg_err = float(np.max(np.abs(neg_lap_p - rhs_zm)))
# 2. Second-order O(h^2) grid convergence against exact smooth eigenmode p_ex = cos(pi*x)*cos(2*pi*y):
errs_h2 = []
grids = [16, 32, 64]
for ng in grids:
hg = 1.0 / ng
xg = (np.arange(ng) + 0.5) * hg
Xg, Yg = np.meshgrid(xg, xg, indexing="ij")
p_true = np.cos(math.pi * Xg) * np.cos(2.0 * math.pi * Yg)
f_true = (5.0 * (math.pi**2)) * p_true
p_num = viscoelastic_fvm_2d._dct2_poisson_neumann_2d(f_true, hg, hg)
errs_h2.append(float(np.max(np.abs(p_num - p_true))))
rate_p = math.log(errs_h2[-2] / errs_h2[-1]) / math.log(2.0)
print(f"Discrete 5-point Neumann Poisson residual ||-Lap_h(p) - rhs||_inf : {alg_err:.3e}")
print(f"Grid errors (N=16, 32, 64): {[round(e, 6) for e in errs_h2]} -> observed order = {rate_p:.3f}")
assert alg_err < 1e-11
assert abs(float(np.mean(p_sol))) < 1e-14
assert 1.95 < rate_p < 2.05
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 4.0))
im = ax1.imshow(p_sol.T, extent=[0, 1, 0, 1], origin="lower", cmap="coolwarm", aspect="equal")
fig.colorbar(im, ax=ax1, fraction=0.046, pad=0.04, label="Zero-mean pressure p(x, y)")
ax1.set_xlabel("x")
ax1.set_ylabel("y")
ax1.set_title(r"Solution of the Neumann problem")
ax2.loglog(grids, errs_h2, "o-", color="#2166AC", lw=2.2, ms=6, label=f"$L_\\infty$ error (order = {rate_p:.2f})")
ax2.loglog(grids, [errs_h2[0] * (grids[0] / g) ** 2 for g in grids], "k--", lw=1.5, label="Reference slope $\\mathcal{O}(h^2)$")
ax2.set_xlabel("Grid resolution N (h = 1/N)")
ax2.set_ylabel("Max norm error $\\Vert p_h - p_{\\mathrm{exact}}\\Vert_\\infty$")
ax2.set_title(r"Error against grid size")
ax2.legend(fontsize=8.2)
label_panels(fig)
plt.show()
Demonstration 1: the Poisson solver and the projection step
===========================================================
Discrete 5-point Neumann Poisson residual ||-Lap_h(p) - rhs||_inf : 2.309e-14
Grid errors (N=16, 32, 64): [0.010726, 0.002719, 0.000682] -> observed order = 1.995

Figure 13.1. (a) Pressure from the cosine-transform solver for a manufactured right-hand side. (b) Maximum error against the number of cells per side; the fitted order is 2.00.
2. The log-conformation step in two dimensions¶
In a two-dimensional flow the logarithm has three independent components, , and . A call of np.linalg.eigh in a Python loop over all cells would be slow. The function viscoelastic_fvm_2d._log_step_2d_field uses instead the closed-form eigenvalues and eigenvectors of a symmetric matrix, for all cells at once:
The eigenvalues of are , so that in every cell.
The velocity gradient is transformed to the principal axes, . The off-diagonal term of the commutator of Lecture 2, , is replaced by its limit when the two eigenvalues are nearly equal.
The advection term is discretized with first-order upwind differences, which do not produce undershoots.
heading("Demonstration 2: the two-dimensional log-conformation step in plane Poiseuille flow")
nx_ch, ny_ch = 14, 30
hx_c, hy_c = 1.0 / nx_ch, 2.0 / ny_ch # y in [-1, 1]
yc = -1.0 + (np.arange(ny_ch) + 0.5) * hy_c
u_pois = np.broadcast_to((1.0 - yc**2)[None, :], (nx_ch, ny_ch)) # U_max = 1 -> du/dy = -2*y
v_pois = np.zeros_like(u_pois)
L_xx = np.zeros_like(u_pois)
L_xy = np.broadcast_to((-2.0 * yc)[None, :], (nx_ch, ny_ch))
L_yx = np.zeros_like(u_pois)
L_yy = np.zeros_like(u_pois)
wi_ch, beta_ch = 1.25, 0.30
Psi_xx = np.zeros_like(u_pois)
Psi_yy = np.zeros_like(u_pois)
Psi_xy = np.zeros_like(u_pois)
for _ in range(450):
Psi_xx, Psi_yy, Psi_xy, C_xx, C_yy, C_xy = viscoelastic_fvm_2d._log_step_2d_field(
Psi_xx, Psi_yy, Psi_xy, u_pois, v_pois, L_xx, L_xy, L_yx, L_yy, hx_c, hy_c, dt=0.02, wi=wi_ch, periodic_x=True
)
# One final reconstruction at updated Psi:
_, _, _, C_xx, C_yy, C_xy = viscoelastic_fvm_2d._log_step_2d_field(
Psi_xx, Psi_yy, Psi_xy, u_pois, v_pois, L_xx, L_xy, L_yx, L_yy, hx_c, hy_c, dt=0.0, wi=wi_ch, periodic_x=True
)
g_mod = (1.0 - beta_ch) / wi_ch
tau_xy_2d = g_mod * C_xy[0, :]
n1_2d = g_mod * (C_xx[0, :] - C_yy[0, :])
det_c_2d = np.exp(Psi_xx + Psi_yy)
# Exact analytical Oldroyd-B steady state in shear gdot(y) = -2*y:
# C_xy = wi * gdot, C_xx = 1 + 2*(wi*gdot)^2, C_yy = 1 -> det(C) == 1 + 2*wi^2*gdot^2 - wi^2*gdot^2? Wait:
# C_xx*C_yy - C_xy^2 = (1 + 2*w^2)*1 - w^2 = 1 + w^2? Let's check: dC/dt = L C + C L^T - (C-I)/wi:
# L_xy * C_yy - C_xy / wi = 0 -> C_xy = wi * gdot; 2 * L_xy * C_xy - (C_xx - 1)/wi = 0 -> C_xx = 1 + 2*(wi*gdot)^2 -> det(C) = 1 + (wi*gdot)^2? Wait:
# (1 + 2*w^2)*1 - w^2 = 1 + w^2? Let's check in log-space Actually in exact Oldroyd-B: C_xx = 1 + 2*w^2, C_yy = 1, C_xy = w -> C_xx*C_yy - C_xy^2 = 1 + w^2 > 1
tau_xy_ex = (1.0 - beta_ch) * (-2.0 * yc)
n1_ex = 2.0 * (1.0 - beta_ch) * wi_ch * ((-2.0 * yc) ** 2)
err_txy = float(np.max(np.abs(tau_xy_2d - tau_xy_ex)))
err_n1_2d = float(np.max(np.abs(n1_2d - n1_ex)))
print(f"2-D log-conformation Poiseuille max |tau_xy - exact| : {err_txy:.3e}")
print(f"2-D log-conformation Poiseuille max |N1 - exact| : {err_n1_2d:.3e}")
print(f"Minimum conformation determinant min det(C) : {np.min(det_c_2d):.6f} (> 0)")
assert err_txy < 2e-3
assert err_n1_2d < 5e-2
assert float(np.min(det_c_2d)) >= 1.0 - 1e-6
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.6, 4.0))
ax1.plot(yc, tau_xy_ex, "k--", lw=1.8, label="Exact antisymmetric $\\tau_{xy}$(y)")
ax1.plot(yc, tau_xy_2d, "o", ms=4.5, color="#2166AC", label="2-D log-$\\psi$ $\\tau_{xy}$(x0, y)")
ax1.plot(yc, n1_ex, color="#6B7280", ls=":", lw=2.0, label="Exact quadratic $N_1$(y)")
ax1.plot(yc, n1_2d, "^", ms=4.5, color="#C0392B", label="2-D log-$\\psi$ $N_1$(x0, y)")
ax1.set_xlabel("Transverse coordinate y / H")
ax1.set_ylabel("Dimensionless polymer stress")
ax1.set_title(r"Polymer stresses")
ax1.legend(fontsize=8.0)
ax2.plot(yc, 1.0 + (wi_ch * (-2.0 * yc)) ** 2, "k--", lw=1.8, label="Exact Oldroyd-B, $\\det\\mathbf{C} = 1 + (\\mathrm{Wi}\\,\\dot{\\gamma})^2$")
ax2.plot(yc, det_c_2d[0, :], "s", ms=4.5, color="#0F766E", label="Reconstructed exp($\\Psi_{xx}$ + $\\Psi_{yy}$)")
ax2.set_xlabel("Transverse coordinate y / H")
ax2.set_ylabel("Conformation determinant $\\det\\mathbf{C}$")
ax2.set_title(r"Determinant of $\mathbf{C}$")
ax2.legend(fontsize=8.1)
label_panels(fig)
plt.show()
Demonstration 2: the two-dimensional log-conformation step in plane Poiseuille flow
===================================================================================
2-D log-conformation Poiseuille max |tau_xy - exact| : 8.091e-04
2-D log-conformation Poiseuille max |N1 - exact| : 3.556e-02
Minimum conformation determinant min det(C) : 1.006873 (> 0)

Figure 13.2. The two-dimensional log-conformation step in plane Poiseuille flow. (a) Shear stress and first normal stress difference across the channel against the Oldroyd-B values. (b) Determinant of against .
3. DEVSS-G stabilization as ¶
The polymer stress is now coupled to the momentum equation. In the simplest iteration the velocity is obtained from , with the polymer stress of the previous iterate. When the divergence of the polymer stress is divided by a small number, and an error of the stress is amplified by the factor in each iteration.
The discrete elastic-viscous split stress method (DEVSS, Guénette and Fortin, 1995; in the variant DEVSS-G of Liu, Bornside, Armstrong and Brown, 1998) adds the viscous term to the implicit left-hand side and subtracts the same quantity, computed from the velocity gradient of the previous iterate as , on the right-hand side:
The function solve_2d_viscoelastic_cavity works with the stream function. Taking the curl of the momentum equation removes the pressure and leaves, in each iteration, a biharmonic equation with conditions on and on its normal derivative at the walls. It is solved with the two-dimensional discrete sine transform; the condition on the normal derivative is imposed through a matrix of size that relates the vorticity at the walls to the velocity there (a capacitance matrix). As , a value of between 0.5 and 1 keeps of order 1.
heading("Demonstration 3: DEVSS-G at a small solvent viscosity ratio")
# Low-solvent polymer melt/concentrated solution regime: beta_s = 0.025, Wi = 0.40:
alphas = [0.0, 0.35, 0.80]
devss_runs = {}
for al in alphas:
devss_runs[al] = viscoelastic_fvm_2d.solve_2d_viscoelastic_cavity(
nx=18, ny=18, wi=0.40, beta_s=0.025, re=0.01, alpha_devss=al, n_steps=75, dt=0.012
)
beff = 0.025 + al * (1.0 - 0.025)
print(
f"alpha_devss = {al:4.2f} (beta_eff = {beff:5.3f}) | "
f"final velocity residual = {devss_runs[al]['residual_hist'][-1]:.3e} | "
f"detC_min = {devss_runs[al]['detC_min']:.4f}"
)
# Without stabilization (alpha_devss = 0) at beta_s = 0.025 the iteration oscillates; with alpha_devss = 0.80 it does not
res_unstab = float(devss_runs[0.0]["residual_hist"][-1])
res_stab = float(devss_runs[0.80]["residual_hist"][-1])
gain_factor = res_unstab / max(res_stab, 1e-16)
print(f"Residual reduction from DEVSS-G stabilization (alpha = 0.80 against 0.0): {gain_factor:.1f}x")
assert res_stab < 1e-3
assert gain_factor > 100.0
assert devss_runs[0.80]["detC_min"] > 0.0
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
cols_d = {0.0: "#C0392B", 0.35: "#E08214", 0.80: "#2166AC"}
for al in alphas:
lbl = f"alpha_devss = {al:.2f} (unstabilized)" if al == 0.0 else f"DEVSS-G alpha = {al:.2f}"
ax1.semilogy(devss_runs[al]["residual_hist"], color=cols_d[al], lw=2.0, label=lbl)
ax1.set_xlabel("Iteration")
ax1.set_ylabel("Velocity step residual $\\|u^{k+1} - u^k\\|_2$")
ax1.set_title(r"Residual ($\beta_s = 0.025$, $\mathrm{Wi} = 0.4$)")
ax1.legend(fontsize=8.0)
# Compare mid-cavity vertical centerline horizontal velocity u(0.5, y) across alpha_devss:
mid_i = 9
ax2.plot(devss_runs[0.0]["u"][mid_i, :], devss_runs[0.0]["y"], "x--", color="#C0392B", lw=1.6, label="Unstabilized $\\alpha$ = 0.0")
ax2.plot(devss_runs[0.35]["u"][mid_i, :], devss_runs[0.35]["y"], "s-", color="#E08214", ms=4.2, lw=1.9, label="DEVSS-G $\\alpha$ = 0.35")
ax2.plot(devss_runs[0.80]["u"][mid_i, :], devss_runs[0.80]["y"], "o-", color="#2166AC", ms=3.8, lw=2.0, label="DEVSS-G $\\alpha$ = 0.80")
ax2.set_xlabel("Horizontal velocity u(x = 0.5, y)")
ax2.set_ylabel("Vertical coordinate y / L")
ax2.set_title(r"Velocity on the vertical midline")
ax2.legend(fontsize=8.0)
label_panels(fig)
plt.show()
Demonstration 3: DEVSS-G at a small solvent viscosity ratio
===========================================================
alpha_devss = 0.00 (beta_eff = 0.025) | final velocity residual = 2.584e-01 | detC_min = 1.0003
alpha_devss = 0.35 (beta_eff = 0.366) | final velocity residual = 1.283e-04 | detC_min = 1.0001
alpha_devss = 0.80 (beta_eff = 0.805) | final velocity residual = 2.465e-04 | detC_min = 1.0001
Residual reduction from DEVSS-G stabilization (alpha = 0.80 against 0.0): 1048.5x

Figure 13.3. Cavity flow at a low solvent viscosity ratio for three values of the DEVSS-G parameter . (a) Change of the velocity per step: it grows for and decays for and 0.8. (b) Horizontal velocity on the vertical midline at the end of the runs.
4. Cavity flow: stream function, pressure and stretch¶
With DEVSS-G in the momentum equation and the log-conformation step for the polymer, the solver returns the stream function, the velocity, the pressure, and :
The velocity derived from the stream function, and , is divergence free in the interior, and it matches the velocity of the lid, .
The pressure follows from the divergence of the momentum equation, with
_dct2_poisson_neumann_2d.The stretch is largest in the sheared layer under the lid and is carried towards the downstream corner. The determinant is positive in every cell.
heading("Demonstration 4: cavity flow at Wi = 0.90")
cav2d = viscoelastic_fvm_2d.solve_2d_viscoelastic_cavity(
nx=25, ny=25, wi=0.90, beta_s=0.30, re=0.03, alpha_devss=0.60, n_steps=200, dt=0.007
)
det_field = np.exp(cav2d["Psi_xx"] + cav2d["Psi_yy"])
vx_c, vy_c = cav2d["vortex_center"]
print(f"Primary vortex centre (x_c, y_c) : ({vx_c:.4f}, {vy_c:.4f})")
print(f"Stream function min psi_min : {np.min(cav2d['streamfunction']):.5f}")
print(f"Peak conformation trace max tr(C) : {np.max(cav2d['trC']):.3f}")
print(f"Conformation determinant range : [{np.min(det_field):.4f}, {np.max(det_field):.4f}]")
assert cav2d["detC_min"] > 0.5
assert float(np.max(cav2d["trC"])) > 3.0
assert float(np.min(cav2d["streamfunction"])) < -0.02
Xc, Yc = np.meshgrid(cav2d["x"], cav2d["y"], indexing="xy")
fig, axes = plt.subplots(2, 2, figsize=(9.6, 8.2))
axes = axes.ravel()
im0 = axes[0].contourf(Xc, Yc, cav2d["streamfunction"].T, levels=14, cmap="Blues_r")
axes[0].contour(Xc, Yc, cav2d["streamfunction"].T, levels=10, colors="black", linewidths=0.6, alpha=0.5)
axes[0].plot(vx_c, vy_c, "ro", ms=6, label=f"Vortex centre ({vx_c:.2f}, {vy_c:.2f})")
fig.colorbar(im0, ax=axes[0], fraction=0.046, pad=0.04)
axes[0].set_title(r"Stream function")
axes[0].set_xlabel("x / L"); axes[0].set_ylabel("y / L"); axes[0].legend(fontsize=7.8, loc="lower left")
im1 = axes[1].imshow(cav2d["trC"].T, extent=[0, 1, 0, 1], origin="lower", cmap="magma", aspect="equal")
fig.colorbar(im1, ax=axes[1], fraction=0.046, pad=0.04)
axes[1].set_title(r"Trace of $\mathbf{C}$")
axes[1].set_xlabel("x / L"); axes[1].set_ylabel("y / L")
im2 = axes[2].imshow(cav2d["p"].T, extent=[0, 1, 0, 1], origin="lower", cmap="RdBu_r", aspect="equal")
fig.colorbar(im2, ax=axes[2], fraction=0.046, pad=0.04)
axes[2].set_title(r"Pressure")
axes[2].set_xlabel("x / L"); axes[2].set_ylabel("y / L")
# Fourth panel: the residual of the coupled iteration
axes[3].semilogy(np.arange(1, len(cav2d["residual_hist"]) + 1), cav2d["residual_hist"], color="#2166AC", lw=1.8)
axes[3].set_xlabel("Time step")
axes[3].set_ylabel("Residual of the velocity update")
axes[3].set_title(r"Change of the velocity per step")
label_panels(fig)
plt.show()
Demonstration 4: cavity flow at Wi = 0.90
=========================================
Primary vortex centre (x_c, y_c) : (0.4583, 0.8104)
Stream function min psi_min : -0.06347
Peak conformation trace max tr(C) : 19.002
Conformation determinant range : [1.0000, 5.9868]

Figure 13.4. Cavity flow at on a grid with a regularized lid. (a) Stream function, with the vortex centre at (0.46, 0.81). (b) Trace of , largest under the lid near the downstream corner. (c) Pressure. (d) Change of the velocity per time step.
Inside the algorithm: the log-conformation step¶
The cell below prints the source of viscoelastic_fvm_2d._log_step_2d_field and compares its closed-form decomposition with the general functions tensors_kinematics.log_conformation_decompose and exp_conformation, applied cell by cell, on a grid on which the deformation varies in space.
Check against the package¶
A symmetric matrix has the eigenvalues , and its principal axes are at the angle . The grid of the check includes the point , where the two eigenvalues are equal. The two implementations agree to rounding error (< 1e-12).
heading("Inside the algorithm: the 2 x 2 log-conformation step against a cell-by-cell reference")
print(show_source(viscoelastic_fvm_2d._log_step_2d_field))
rng_k = np.random.default_rng(7)
nx_k, ny_k = 6, 6
Psi_xx_k = rng_k.uniform(-0.6, 0.9, size=(nx_k, ny_k))
Psi_yy_k = rng_k.uniform(-0.6, 0.9, size=(nx_k, ny_k))
Psi_xy_k = rng_k.uniform(-0.5, 0.5, size=(nx_k, ny_k))
# Force cell (0, 0) to exact isotropic equilibrium Psi == 0 to verify zero-gap branch:
Psi_xx_k[0, 0] = Psi_yy_k[0, 0] = Psi_xy_k[0, 0] = 0.0
L_xx_k = rng_k.uniform(-0.8, 0.8, size=(nx_k, ny_k))
L_yy_k = -L_xx_k
L_xy_k = rng_k.uniform(-1.5, 1.5, size=(nx_k, ny_k))
L_yx_k = rng_k.uniform(-0.5, 0.5, size=(nx_k, ny_k))
zero_u = np.zeros((nx_k, ny_k))
dt_k, wi_k = 0.01, 0.8
# Vectorized 2-D field step (with u = v = 0 to isolate local kinematic + Oldroyd-B log source):
Pxx_v, Pyy_v, Pxy_v, Cxx_v, Cyy_v, Cxy_v = viscoelastic_fvm_2d._log_step_2d_field(
Psi_xx_k, Psi_yy_k, Psi_xy_k, zero_u, zero_u, L_xx_k, L_xy_k, L_yx_k, L_yy_k, 0.1, 0.1, dt_k, wi=wi_k
)
# This solver, cell-by-cell reference using tensors_kinematics.exp_conformation & log_conformation_decompose:
Pxx_ref = np.zeros_like(Psi_xx_k)
Pyy_ref = np.zeros_like(Psi_yy_k)
Pxy_ref = np.zeros_like(Psi_xy_k)
for i in range(nx_k):
for j in range(ny_k):
Psi_ij = np.array([[Psi_xx_k[i, j], Psi_xy_k[i, j]], [Psi_xy_k[i, j], Psi_yy_k[i, j]]])
L_ij = np.array([[L_xx_k[i, j], L_xy_k[i, j]], [L_yx_k[i, j], L_yy_k[i, j]]])
C_ij = tensors_kinematics.exp_conformation(Psi_ij)
dec = tensors_kinematics.log_conformation_decompose(C_ij, L_ij)
ev, R = dec["eigenvalues"], dec["eigenvectors"]
# Oldroyd-B relaxation -(C - I)/wi mapped to Psi space via C^-1 * relax(C) = -(I - C^-1)/wi:
rel_psi = -(np.eye(2) - np.linalg.inv(C_ij)) / wi_k
Psi_next = Psi_ij + dt_k * (dec["dPsi_dt_kinematic"] + rel_psi)
Pxx_ref[i, j], Pyy_ref[i, j], Pxy_ref[i, j] = Psi_next[0, 0], Psi_next[1, 1], Psi_next[0, 1]
max_log_err = float(max(np.max(np.abs(Pxx_v - Pxx_ref)), np.max(np.abs(Pyy_v - Pyy_ref)), np.max(np.abs(Pxy_v - Pxy_ref))))
print(f"Max discrepancy between vectorized 2-D kernel and cell-wise eigh reference: {max_log_err:.3e}")
assert np.allclose(Pxx_v, Pxx_ref, atol=1e-12)
assert np.allclose(Pyy_v, Pyy_ref, atol=1e-12)
assert np.allclose(Pxy_v, Pxy_ref, atol=1e-12)
Inside the algorithm: the 2 x 2 log-conformation step against a cell-by-cell reference
======================================================================================
def _log_step_2d_field(
Psi_xx: np.ndarray,
Psi_yy: np.ndarray,
Psi_xy: np.ndarray,
u: np.ndarray,
v: np.ndarray,
L_xx: np.ndarray,
L_xy: np.ndarray,
L_yx: np.ndarray,
L_yy: np.ndarray,
hx: float,
hy: float,
dt: float,
wi: float,
periodic_x: bool = False,
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""One step of the two-dimensional log-conformation equation: upwind advection, stretching and Oldroyd-B relaxation."""
# 1. Reconstruct C = exp(Psi) analytically for 2x2 symmetric field:
half_tr = 0.5 * (Psi_xx + Psi_yy)
diff = 0.5 * (Psi_xx - Psi_yy)
r_rad = np.hypot(diff, Psi_xy)
psi_1 = np.clip(half_tr + r_rad, -30.0, 30.0)
psi_2 = np.clip(half_tr - r_rad, -30.0, 30.0)
lam_1 = np.exp(psi_1)
lam_2 = np.exp(psi_2)
# Orthonormal eigenvectors of Psi (and C): [cos th, -sin th; sin th, cos th]
th = 0.5 * np.arctan2(2.0 * Psi_xy, Psi_xx - Psi_yy)
ct = np.cos(th)
st = np.sin(th)
C_xx = (ct**2) * lam_1 + (st**2) * lam_2
C_yy = (st**2) * lam_1 + (ct**2) * lam_2
C_xy = ct * st * (lam_1 - lam_2)
# 2. Transform velocity gradient L into eigenbasis M = R^T L R:
# R = [[ct, -st], [st, ct]] -> R^T = [[ct, st], [-st, ct]]
t00 = ct * L_xx + st * L_yx
t01 = ct * L_xy + st * L_yy
t10 = -st * L_xx + ct * L_yx
t11 = -st * L_xy + ct * L_yy
m11 = t00 * ct + t01 * st
m12 = -t00 * st + t01 * ct
m21 = t10 * ct + t11 * st
m22 = -t10 * st + t11 * ct
# Fattal-Kupferman commutator [Omega_tilde, diag(psi)]_12 = om_12 * (psi_2 - psi_1):
gap = np.abs(lam_2 - lam_1) / (0.5 * (lam_1 + lam_2))
safe_dl = np.where(gap > 1e-6, lam_2 - lam_1, 1.0)
om_12 = np.where(gap > 1e-6, (lam_2 * m12 + lam_1 * m21) / safe_dl, 0.5 * (m12 - m21))
comm_12 = np.where(gap > 1e-6, om_12 * (psi_2 - psi_1), m12 + m21)
# Oldroyd-B relaxation -(C - I) / wi in Psi-eigenbasis: -(1 - 1/lam_i) / wi on diagonal
inv_wi = 1.0 / max(float(wi), 1e-6)
d1_eig = 2.0 * m11 - (1.0 - 1.0 / lam_1) * inv_wi
d2_eig = 2.0 * m22 - (1.0 - 1.0 / lam_2) * inv_wi
d12_eig = comm_12
# Rotate source back to Cartesian: R @ [[d1, d12], [d12, d2]] @ R^T:
src_xx = (ct**2) * d1_eig + (st**2) * d2_eig - 2.0 * ct * st * d12_eig
src_yy = (st**2) * d1_eig + (ct**2) * d2_eig + 2.0 * ct * st * d12_eig
src_xy = ct * st * (d1_eig - d2_eig) + (ct**2 - st**2) * d12_eig
# 3. First-order upwind advection - (u dPsi/dx + v dPsi/dy):
def _advect(f: np.ndarray) -> np.ndarray:
if periodic_x:
f_xm = np.roll(f, 1, axis=0)
f_xp = np.roll(f, -1, axis=0)
else:
f_xm = np.vstack([f[0:1, :], f[:-1, :]])
f_xp = np.vstack([f[1:, :], f[-1:, :]])
f_ym = np.hstack([f[:, 0:1], f[:, :-1]])
f_yp = np.hstack([f[:, 1:], f[:, -1:]])
df_dx = np.where(u >= 0.0, (f - f_xm) / hx, (f_xp - f) / hx)
df_dy = np.where(v >= 0.0, (f - f_ym) / hy, (f_yp - f) / hy)
return -(u * df_dx + v * df_dy)
Psi_xx_new = np.clip(Psi_xx + dt * (_advect(Psi_xx) + src_xx), -18.0, 18.0)
Psi_yy_new = np.clip(Psi_yy + dt * (_advect(Psi_yy) + src_yy), -18.0, 18.0)
Psi_xy_new = np.clip(Psi_xy + dt * (_advect(Psi_xy) + src_xy), -18.0, 18.0)
return Psi_xx_new, Psi_yy_new, Psi_xy_new, C_xx, C_yy, C_xy
Max discrepancy between vectorized 2-D kernel and cell-wise eigh reference: 5.551e-17
Exercises¶
Worked solutions are in 13_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Check that the DEVSS-G terms do not change the steady solution. Run
solve_2d_viscoelastic_cavitywithnx=21, ny=21, wi=0.55, beta_s=0.30, re=0.02, n_steps=200for , and compare the velocity fields and the position of the vortex centre.Find how it fails. Reduce the solvent viscosity ratio, , at on a grid of cells, and compare the final residual of the velocity without stabilization (
alpha_devss=0.0) and with DEVSS-G (alpha_devss=0.80).Implement it yourself. Write a projection step on a staggered grid ( on vertical faces, on horizontal faces, the potential at cell centres) with your own Poisson solver based on the discrete cosine transform for Neumann conditions. Check that the divergence after the projection is at the level of rounding error, and compare the Poisson solver with
viscoelastic_fvm_2d._dct2_poisson_neumann_2d.
heading("Self-check for the exercises")
assert alg_err < 1e-11
assert err_n1_2d < 5e-2
assert gain_factor > 100.0
assert cav2d["detC_min"] > 0.5
assert max_log_err < 1e-12
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.