This project applies the methods of the book to one screening calculation. A polymer fluid is fed through a square duct into a slit with wavy walls, and the question is which operating conditions avoid five problems: a wrong description of the polymer at the molecular level; a feed duct that is blocked or has stagnant corners, if the fluid has a yield stress; shear banding or shear thickening in the slit; a velocity overshoot at start-up; and an elastic instability at the constriction.
The calculation has four stages and uses all nine modules of the package. All material parameters and all limits (for example the admissible value of the Pakdel–McKinley number) are assumed. The result illustrates how the methods fit together; it is not a design.
Learning objectives¶
Stage 1: characterize the model polymer with Brownian dynamics (
brownian_chains), a closure (entangled_tubes), the free energy (tensors_kinematics), microrheology and a fitted stress model (microrheology_rheoml).Stage 2: check the feed duct for flow with the augmented Lagrangian method (
viscoplastic_admm), and the fluid for shear banding (shear_banding_instabilities) and discontinuous shear thickening (mesoscopic_suspensions_dpd).Stage 3: compute the start-up of flow in the slit and the flow through the constriction (
constants_benchmarks,viscoelastic_fvm_2d).Stage 4: map the pressure drop and the largest Pakdel–McKinley number , and select the conditions within the assumed limits.
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. Stage 1: the model polymer¶
The first stage describes the model polymer with four of the methods of the book and checks that they agree with one another.
| Method | Module | What it provides |
|---|---|---|
| Probe microrheology (Lecture 16) | microrheology_rheoml | , and the longest relaxation time |
| Brownian dynamics of FENE dumbbells with a control variate (Lectures 3 and 4) | brownian_chains | the mean-square extension and the stress |
| FENE-P and Rolie-Poly models in the log-conformation form (Lectures 2, 6 and 7) | entangled_tubes, tensors_kinematics | and the free energy |
| Tensor-basis stress model (Lecture 16) | microrheology_rheoml | a frame-indifferent function with weights |
The demonstration below applies these methods to the model polymer ().
heading("Stage 1: the model polymer")
# 1. Passive thermal microrheology check of relaxation time lam = 0.45 s (matching BOGER_PIB timescale):
boger_p = constants_benchmarks.BENCHMARK_FLUIDS_DB["BOGER_PIB"]
t_probe = np.concatenate([[0.0], np.geomspace(1e-3, 6.0, 45)])
gle_cap = microrheology_rheoml.simulate_gle_thermal_probe(
[(boger_p["eta_p_Pas"] / boger_p["lam_s"], boger_p["lam_s"])], t_probe, eta_s=0.02, n_probes=900, seed=12
)
gser_cap = microrheology_rheoml.mason_gser_moduli(gle_cap["t"][1:], gle_cap["msd_exact"][1:])
# 2. Semi-implicit FENE Brownian Dynamics against FENE-P Log-Conformation startup at Wi = 2.0 (b = 36):
t_cap = np.linspace(0.0, 4.0, 51)
L_sh_cap = np.array([[0.0, 2.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
bd_cap = brownian_chains.simulate_dumbbell_bd(lambda _t: L_sh_cap, t_cap, model="fene", b_ext=36.0, n_trajectories=700, control_variate=True, seed=7)
fp_cap = entangled_tubes.solve_fenep_fenecr(lambda _t: L_sh_cap, t_cap, lam=1.0, eta_p=1.0, b_ext=36.0, variant="fenep")
rp_cap = entangled_tubes.solve_rolie_poly(lambda _t: L_sh_cap, t_cap, G0=1.0, tau_d=1.0, tau_R=0.25, beta_ccr=0.5)
# 3. Verify SPD thermodynamics & calibrate frame-invariant TC-RheoML surrogate on FENE-P states:
spd_cap = tensors_kinematics.check_spd_conformation(fp_cap["C"][-1], G0=1.0)
tc_cap = microrheology_rheoml.fit_thermodynamic_tensor_rheoml(fp_cap["C"][2:], fp_cap["tau_p"][2:])
print(f"FENE BD overstretches = {bd_cap['overstretched_count']} | VRF = {bd_cap['variance_reduction_factor']:.1f}x | steady tau_xy = {bd_cap['tau_xy'][-1]:.3f}")
print(f"FENE-P SPD verified = {spd_cap['is_spd']} (psi = {spd_cap['free_energy_hookean']:.3f}) | steady tau_xy = {fp_cap['tau_p'][-1, 0, 1]:.3f}")
print(f"Tensor-basis model R^2 = {tc_cap['r2_score']:.5f} | SO(3) err = {tc_cap['rotation_equivariance_err']:.2e}")
assert bd_cap["overstretched_count"] == 0
assert spd_cap["is_spd"] and spd_cap["free_energy_hookean"] > 0.0
assert tc_cap["is_thermodynamically_admissible"] and tc_cap["r2_score"] > 0.995
assert gser_cap["kramers_kronig_tan_err"] < 1e-13
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
ax1.loglog(gser_cap["omega"], gser_cap["G_prime"], "o-", ms=3.5, color="#2166AC", lw=2.0, label="GSER storage $G'$($\\omega$)")
ax1.loglog(gser_cap["omega"], gser_cap["G_double_prime"], "s--", ms=3.5, color="#C0392B", lw=1.9, label="GSER loss $G''$($\\omega$)")
ax1.axvline(1.0 / boger_p["lam_s"], color="k", ls=":", lw=1.4, label=f"Relaxation 1/$\\lambda$ = {1/boger_p['lam_s']:.2f} rad/s")
ax1.set_xlabel("Frequency $\\omega$ [rad/s]"); ax1.set_ylabel("Moduli [Pa]")
ax1.set_title(r"Moduli from a simulated probe")
ax1.legend(fontsize=7.9)
ax2.plot(t_cap, bd_cap["tau_xy"], color="#0F766E", lw=2.1, label="FENE Brownian dynamics (b=36)")
ax2.plot(t_cap, fp_cap["tau_p"][:, 0, 1], "--", color="#2166AC", lw=2.1, label="FENE-P closure (log-$\\psi$)")
ax2.plot(t_cap[::3], tc_cap["predict_fn"](fp_cap["C"][::3])[:, 0, 1], "o", ms=4.2, color="#C0392B", label="Fitted tensor-basis model")
ax2.plot(t_cap, rp_cap["tau_xy"], ":", color="#7B4FA3", lw=2.0, label="Entangled Rolie-Poly reference")
ax2.set_xlabel("Dimensionless time t / $\\lambda$"); ax2.set_ylabel("Dimensionless shear stress $\\tau_{xy}$")
ax2.set_title(r"Shear stress in start-up")
ax2.legend(fontsize=7.8)
label_panels(fig)
plt.show()
Stage 1: the model polymer
==========================
FENE BD overstretches = 0 | VRF = 15.8x | steady tau_xy = 1.472
FENE-P SPD verified = True (psi = 1.914) | steady tau_xy = 1.765
Tensor-basis model R^2 = 1.00000 | SO(3) err = 2.41e-16

Figure 17.1. Stage 1. (a) Storage and loss moduli from a simulated probe; the dotted line is . (b) Start-up shear stress from FENE Brownian dynamics, the FENE-P closure, the fitted tensor-basis model and a Rolie-Poly curve for comparison.
2. Stage 2: the feed duct, shear banding and shear thickening¶
If the fluid has a yield stress (parameter set CARBOPOL_EVP) or contains a high volume fraction of particles (SILICA_DST), three things can go wrong before it reaches the slit. The parameter values of both sets are assumed.
The feed duct (
viscoplastic_admm). In a square duct under the pressure gradient the flow stops when the Bingham number exceeds (Mosolov and Miasnikov, 1965). Below this value the fluid in the four corners is at rest.Shear banding (
shear_banding_instabilities). The flow curve of the Johnson–Segalman model with is non-monotonic if .Shear thickening (
mesoscopic_suspensions_dpd). The wall stress has to stay below the stress , or the volume fraction below , to avoid discontinuous shear thickening.
heading("Stage 2: the feed duct, shear banding and shear thickening")
# 1. Sweep Bingham number Bn in 2-D square feed duct via spectral Glowinski-Dean ADMM:
bn_list = [0.0, 0.25, 0.42, 0.56]
q_duct, uy_frac = [], []
duct_mid = None
for bn_v in bn_list:
d_res = viscoplastic_admm.solve_2d_duct_bingham_admm(nx=26, ny=26, H_half=1.0, dpdz_neg=1.0, tau_y=bn_v, eta_p=1.0, r_aug=0.35 if bn_v < 0.5 else 1.0, max_iter=230)
q_duct.append(d_res["flow_rate"])
uy_frac.append(d_res["unyielded_area_fraction"])
if bn_v == 0.25:
duct_mid = d_res
print(f"Feed-duct Bn = {bn_v:4.2f} (Bn_crit = {d_res['mosolov_bn_crit']:.4f}) | flux Q = {d_res['flow_rate']:.4f} | unyielded = {d_res['unyielded_area_fraction']:.1%}")
# 2. Check constitutive shear-banding stability (beta_s = 0.30 > 0.125 safe vs beta_s = 0.05 banding) & filler DST:
g_rates = np.linspace(0.1, 6.0, 80)
js_safe = shear_banding_instabilities.steady_johnson_segalman_curve(g_rates, G0=1.0, lam=1.0, eta_s=0.30, xi_slip=0.2)
js_band = shear_banding_instabilities.steady_johnson_segalman_curve(g_rates, G0=1.0, lam=1.0, eta_s=0.05, xi_slip=0.2)
wc_safe = mesoscopic_suspensions_dpd.wyart_cates_dst_flow_curve(np.logspace(-0.3, 2.3, 80), phi=0.45, phi_0=0.64, phi_m=0.55, tau_star=18.0)
wc_risk = mesoscopic_suspensions_dpd.wyart_cates_dst_flow_curve(np.logspace(-0.3, 2.3, 80), phi=0.542, phi_0=0.64, phi_m=0.55, tau_star=18.0)
print(f"Shear-banding spinodal check : beta_s=0.30 non_mono={js_safe['is_non_monotonic']} against beta_s=0.05 non_mono={js_band['is_non_monotonic']}")
print(f"Silica filler DST check : phi=0.45 DST={wc_safe['is_s_shaped_dst']} against phi=0.542 DST={wc_risk['is_s_shaped_dst']}")
assert q_duct[0] > 0.55 and q_duct[-1] < 1e-5
assert (not js_safe["is_non_monotonic"]) and js_band["is_non_monotonic"]
assert (not wc_safe["is_s_shaped_dst"]) and wc_risk["is_s_shaped_dst"]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
ax1.plot(bn_list, q_duct, "o-", color="#2166AC", lw=2.3, ms=6.5, label="Flow rate Q(Bn)")
ax1.axvline(constants_benchmarks.MOSOLOV_SQUARE_DUCT_BN_CRIT, color="#C0392B", ls="--", lw=1.8, label=f"Critical Bn = {constants_benchmarks.MOSOLOV_SQUARE_DUCT_BN_CRIT:.3f}")
ax1_r = ax1.twinx()
ax1_r.plot(bn_list, uy_frac, "s:", color="#E08214", lw=2.0, label="Unyielded area fraction")
ax1_r.set_ylabel("Unyielded fraction", color="#E08214")
ax1.set_xlabel("Bingham number of the feed duct, $\\mathrm{Bn} = \\tau_y/(G_p H)$")
ax1.set_ylabel("Flow rate Q")
ax1.set_title(r"Feed duct: flow rate and unyielded fraction")
ax1.legend(loc="center left", fontsize=7.8)
ax2.plot(g_rates, js_safe["tau_total"], "-", color="#0F766E", lw=2.3, label="Fluid A: $\\beta_s$ = 0.30 (monotonic)")
ax2.plot(g_rates, js_band["tau_total"], "--", color="#C0392B", lw=2.2, label="Fluid B: $\\beta_s$ = 0.05 < 1/8 (non-monotonic)")
ax2.set_xlabel("Dimensionless shear rate Wi")
ax2.set_ylabel("Steady total shear stress $\\tau_{\\mathrm{tot}}$")
ax2.set_title(r"Flow curves of two fluids")
ax2.legend(fontsize=8.0)
label_panels(fig)
plt.show()
Stage 2: the feed duct, shear banding and shear thickening
==========================================================
Feed-duct Bn = 0.00 (Bn_crit = 0.5302) | flux Q = 0.5618 | unyielded = 0.1%
Feed-duct Bn = 0.25 (Bn_crit = 0.5302) | flux Q = 0.2216 | unyielded = 17.7%
Feed-duct Bn = 0.42 (Bn_crit = 0.5302) | flux Q = 0.0446 | unyielded = 52.3%
Feed-duct Bn = 0.56 (Bn_crit = 0.5302) | flux Q = 0.0000 | unyielded = 90.7%
Shear-banding spinodal check : beta_s=0.30 non_mono=False against beta_s=0.05 non_mono=True
Silica filler DST check : phi=0.45 DST=False against phi=0.542 DST=True

Figure 17.2. Stage 2. (a) Flow rate (left axis) and unyielded fraction (right axis) of Bingham flow in a square duct against the Bingham number, with the limit 0.530. (b) Johnson–Segalman flow curves: monotonic for , non-monotonic for .
3. Stage 3: start-up and flow through the constriction¶
The fluid with passes the checks of Stage 2. The third stage treats the slit (viscoelastic_fvm_2d):
Start-up. The Waters–King solution (
waters_king_startup_poiseuille) and the configuration-field solver (solve_1d_channel_viscoelastic_startup) give the overshoot of the centreline velocity when the flow is started suddenly.Flow through the constriction. The function
solve_2d_wavy_contraction_channelgives the conformation tensor , the normal stress difference and the Pakdel–McKinley number in the slit with wavy walls. Its velocity field is prescribed, not computed.
heading("Stage 3: start-up and flow through the constriction")
# 1. Transient slit-land startup check (El = 0.90, beta_s = 0.30):
bcf_die = viscoelastic_fvm_2d.solve_1d_channel_viscoelastic_startup(
ny=28, t_end=4.0, dt=0.008, dpdx_neg=2.0, H_half=1.0, rho=1.0, eta_s=0.30, eta_p=0.70, lam=0.90, method="bcf_hookean", n_fields=240, seed=15
)
wk_die = constants_benchmarks.waters_king_startup_poiseuille(
bcf_die["y_nodes"], bcf_die["t"], dpdx_neg=2.0, H_half=1.0, rho=1.0, eta_s=0.30, eta_p=0.70, lam=0.90
)
overshoot_pct = 100.0 * (float(np.max(wk_die["u_centerline"])) / wk_die["u_centerline_steady"] - 1.0)
# 2. 2-D Constricted die CFD comparing gentle taper (eps = 0.18) vs aggressive contraction (eps = 0.38) at Wi = 1.4:
die_gentle = viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel(nx=32, ny=18, constriction_eps=0.18, wi=1.40, beta_s=0.30, n_steps=160, dt=0.006)
die_sharp = viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel(nx=32, ny=18, constriction_eps=0.38, wi=1.40, beta_s=0.30, n_steps=160, dt=0.006)
print(f"Start-up overshoot of the centreline velocity (El=0.90, beta_s=0.30) : +{overshoot_pct:.2f}% above steady velocity")
print(f"Amplitude (eps = 0.18, Wi = 1.4) : max tr(C) = {np.max(die_gentle['trC_field']):.2f}, max M_PM = {np.max(die_gentle['pakdel_M_field']):.3f}")
print(f"Sharp taper (eps = 0.38, Wi = 1.4) : max tr(C) = {np.max(die_sharp['trC_field']):.2f}, max M_PM = {np.max(die_sharp['pakdel_M_field']):.3f}")
assert overshoot_pct > 5.0
assert die_gentle["detC_min"] > 0.0 and die_sharp["detC_min"] > 0.0
assert float(np.max(die_sharp["pakdel_M_field"])) > 1.8 * float(np.max(die_gentle["pakdel_M_field"]))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10.8, 4.0))
ax1.plot(wk_die["t"], wk_die["u_centerline"], "k-", lw=2.3, label=f"Waters-King exact (+{overshoot_pct:.1f}% overshoot)")
ax1.plot(bcf_die["t"][::16], bcf_die["u_centerline_hist"][::16], "o", ms=4.2, color="#2166AC", label="Configuration fields")
ax1.axhline(1.0, color="#6B7280", ls=":", lw=1.3)
ax1.set_xlabel("Start-up time t [s]"); ax1.set_ylabel("Centreline velocity u(0, t) / $U_\\infty$")
ax1.set_title(r"Centreline velocity in start-up")
ax1.legend(fontsize=8.0)
ax2.plot(die_gentle["x_grid"][:, 0], np.max(die_gentle["pakdel_M_field"], axis=1), "o-", ms=3.8, color="#0F766E", lw=2.2, label="Amplitude ($\\varepsilon$ = 0.18)")
ax2.plot(die_sharp["x_grid"][:, 0], np.max(die_sharp["pakdel_M_field"], axis=1), "s-", ms=3.8, color="#C0392B", lw=2.2, label="Sharp contraction ($\\varepsilon$ = 0.38)")
ax2.set_xlabel("Axial position x (narrowest at 0 and $2\\pi$)")
ax2.set_ylabel("Largest $M$ over the cross-section")
ax2.set_title(r"Largest $M$ along the channel")
ax2.legend(fontsize=8.0)
label_panels(fig)
plt.show()
Stage 3: start-up and flow through the constriction
===================================================
Start-up overshoot of the centreline velocity (El=0.90, beta_s=0.30) : +40.86% above steady velocity
Amplitude (eps = 0.18, Wi = 1.4) : max tr(C) = 6.56, max M_PM = 0.254
Sharp taper (eps = 0.38, Wi = 1.4) : max tr(C) = 15.75, max M_PM = 0.529

Figure 17.3. Stage 3. (a) Start-up of the slit flow: the exact solution overshoots the steady velocity by 41 %; symbols are configuration fields. (b) Largest Pakdel–McKinley number across the channel against axial position for two wall amplitudes.
4. Stage 4: operating conditions within the assumed limits¶
The last stage evaluates a grid of amplitudes of the constriction and of Weissenberg numbers. For each point it computes the largest Pakdel–McKinley number, which must not exceed the assumed limit , and an estimate of the dimensionless pressure drop, . The first term is the lubrication result, with ; the second is an assumed allowance for the normal stress, and its coefficient 0.35 is not derived.
Among the points within the limit, the demonstration selects the one with the largest Weissenberg number, and among those with the same Weissenberg number the one with the smallest pressure drop.
heading("Stage 4: operating conditions within the assumed limits")
eps_cands = [0.15, 0.28, 0.42]
wi_cands = [0.6, 1.2, 1.8, 2.4]
M_allow = 0.42
records_design = []
for ep_c in eps_cands:
# Exact lubrication hydraulic resistance factor (2 + eps^2) / (2 * (1 - eps^2)^(5/2)):
lub_fac = (2.0 + ep_c**2) / (2.0 * ((1.0 - ep_c**2) ** 2.5))
for wi_c in wi_cands:
sim = viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel(
nx=26, ny=14, constriction_eps=ep_c, wi=wi_c, beta_s=0.30, n_steps=130, dt=0.006
)
m_pk = float(np.max(sim["pakdel_M_field"]))
n1_pk = float(np.max(sim["N1_field"]))
# Dimensionless total die pressure drop (viscous lubrication + Couette-Bagley elastic entrance penalty):
dp_tot = wi_c * lub_fac + 0.35 * ep_c * n1_pk
safe_ok = (m_pk <= M_allow) and (sim["detC_min"] > 0.0)
records_design.append((ep_c, wi_c, dp_tot, m_pk, safe_ok))
safe_designs = [r for r in records_design if r[4]]
rejected_designs = [r for r in records_design if not r[4]]
best_design = max(safe_designs, key=lambda r: (r[1], -r[2]))
print("Candidates (M_allow = 0.42):")
for ep_c, wi_c, dp_v, m_v, ok in records_design[::2]:
print(f" eps={ep_c:.2f}, Wi={wi_c:.1f} | dP_dim={dp_v:6.2f} | M_max={m_v:5.3f} | {'within the limit' if ok else 'outside the limit'}")
print(f"Selected operating point: eps* = {best_design[0]:.2f}, Wi* = {best_design[1]:.2f}, dP* = {best_design[2]:.2f}, M_max = {best_design[3]:.3f}")
assert len(safe_designs) >= 4 and len(rejected_designs) >= 2
assert best_design[3] <= M_allow
assert best_design[1] >= 1.5
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.0, 4.1))
for ep_c, col in zip(eps_cands, ["#0F766E", "#2166AC", "#C0392B"]):
sub = [r for r in records_design if r[0] == ep_c]
ax1.plot([r[2] for r in sub], [r[3] for r in sub], "o-", lw=2.0, color=col, label=f"Amplitude $\\varepsilon$ = {ep_c:.2f}")
ax1.axhline(M_allow, color="k", ls="--", lw=1.6, label=f"Assumed limit $M_{{\\mathrm{{allow}}}}$ = {M_allow:.2f}")
ax1.scatter([best_design[2]], [best_design[3]], s=130, marker="*", color="#F2C744", edgecolors="black", zorder=6, label=f"Selected ($\\varepsilon$ = {best_design[0]:.2f}, Wi = {best_design[1]:.1f})")
ax1.set_xlabel("Dimensionless pressure drop")
ax1.set_ylabel("Largest Pakdel-McKinley index $M_{\\max}$")
ax1.set_title(r"Largest $M$ against pressure drop")
ax1.legend(fontsize=7.7)
# Scatter feasible vs infeasible designs in (Throughput Wi, Efficiency Wi / dP) Pareto space:
for r in records_design:
c_pt = "#0F766E" if r[4] else "#C0392B"
mk_pt = "o" if r[4] else "x"
ax2.scatter(r[2], r[1], color=c_pt, marker=mk_pt, s=55)
ax2.scatter([best_design[2]], [best_design[1]], s=150, marker="*", color="#F2C744", edgecolors="black", zorder=6, label="Selected point")
ax2.scatter([], [], color="#0F766E", marker="o", label="Admissible ($M_{\\max} \\leq M_{\\mathrm{allow}}$)")
ax2.scatter([], [], color="#C0392B", marker="x", label="Rejected (exceeds $M_{\\mathrm{allow}}$)")
ax2.set_xlabel("Dimensionless pressure drop")
ax2.set_ylabel("Weissenberg number Wi")
ax2.set_title(r"Candidates in the plane of pressure drop and rate")
ax2.legend(fontsize=8.0)
label_panels(fig)
plt.show()
Stage 4: operating conditions within the assumed limits
=======================================================
Candidates (M_allow = 0.42):
eps=0.15, Wi=0.6 | dP_dim= 0.76 | M_max=0.148 | within the limit
eps=0.15, Wi=1.8 | dP_dim= 1.99 | M_max=0.192 | within the limit
eps=0.28, Wi=0.6 | dP_dim= 1.18 | M_max=0.254 | within the limit
eps=0.28, Wi=1.8 | dP_dim= 2.52 | M_max=0.329 | within the limit
eps=0.42, Wi=0.6 | dP_dim= 2.47 | M_max=0.415 | within the limit
eps=0.42, Wi=1.8 | dP_dim= 3.97 | M_max=0.536 | outside the limit
Selected operating point: eps* = 0.15, Wi* = 2.40, dP* = 2.62, M_max = 0.198

Figure 17.4. Stage 4. (a) Largest Pakdel–McKinley number against dimensionless pressure drop for three wall amplitudes; the dashed line is the limit 0.42 assumed here. (b) The candidates that pass and fail the limit; the star is the passing candidate with the highest rate.
Inside the algorithm: the prescribed velocity field and the list of models and methods¶
The cell below prints the source of viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel and checks in NumPy that its velocity field, written in the coordinate , is divergence free, , that the normal stress at the wall of the constriction agrees with the formula for low , and that every function named in RHEO_ATLAS_DB exists.
Check against the package¶
For and , differentiating along constant physical (using ) yields:
confirming exact solenoidal mass conservation everywhere in the wavy contraction.
heading("Inside the algorithm: the prescribed velocity field and the list of models and methods")
print(show_source(viscoelastic_fvm_2d.solve_2d_wavy_contraction_channel))
# 1. Verify exact analytical solenoidal identity du/dx + dv/dy == 0 across wavy channel:
x_t = np.linspace(0.0, 2.0 * math.pi, 64, endpoint=False)
eta_t = np.linspace(-0.95, 0.95, 32)[None, :]
eps_t, Q0_t = 0.33, 4.0 / 3.0
H_t = (1.0 - eps_t * np.cos(x_t))[:, None]
dH_t = (eps_t * np.sin(x_t))[:, None]
du_dx_exact = (0.75 * Q0_t * dH_t / (H_t**2)) * (3.0 * (eta_t**2) - 1.0)
dv_dy_exact = (0.75 * Q0_t * dH_t / (H_t**2)) * (1.0 - 3.0 * (eta_t**2))
div_exact = float(np.max(np.abs(du_dx_exact + dv_dy_exact)))
# 2. Verify all 24 laws in constants_benchmarks.RHEO_ATLAS_DB resolve cleanly across Parts I..VI:
atlas = constants_benchmarks.RHEO_ATLAS_DB
resolved = [
callable(getattr(getattr(engcomprheo, e["module_fn"].split(".")[0]), e["module_fn"].split(".")[1]))
for e in atlas
]
print(f"Analytical wavy-contraction solenoidal residual |du/dx + dv/dy| : {div_exact:.3e}")
print(f"Resolved RHEO_ATLAS_DB callables across Parts I..VI : {sum(resolved)} / {len(atlas)}")
assert div_exact < 1e-15
assert len(atlas) == 24 and all(resolved)
Inside the algorithm: the prescribed velocity field and the list of models and methods
======================================================================================
def solve_2d_wavy_contraction_channel(
nx: int = 40,
ny: int = 24,
constriction_eps: float = 0.30,
wi: float = 1.2,
beta_s: float = 0.4,
n_steps: int = 260,
dt: float = 0.005,
) -> dict:
"""Log-conformation solution in a periodic channel with wavy walls and a prescribed velocity field; returns N1 and the Pakdel-McKinley number M(x, y)."""
if nx < 12 or ny < 8 or not (0.0 <= constriction_eps < 0.7) or wi < 0.0 or not (0.0 < beta_s <= 1.0):
raise ValueError("Invalid parameters for solve_2d_wavy_contraction_channel.")
L_len = 2.0 * math.pi
hx = L_len / float(nx)
x = (np.arange(nx, dtype=float) + 0.5) * hx
xi_y = (np.arange(ny, dtype=float) + 0.5) / float(ny) # mapped transverse coordinate in (0, 1)
# Smooth symmetric wavy half-height H(x) = 1 - eps * cos(x), throat at x = 0 & 2*pi, expansion at x = pi:
H_x = 1.0 - float(constriction_eps) * np.cos(x)
dH_dx = float(constriction_eps) * np.sin(x)
y_phys = (2.0 * xi_y[None, :] - 1.0) * H_x[:, None]
x_phys = np.broadcast_to(x[:, None], (nx, ny))
# Lubrication-consistent incompressible base kinematics + viscoelastic Log-Conformation evolution:
# Volumetric flow Q0 = 4/3 -> u(x, y) = (3 * Q0 / (4 * H(x))) * (1 - (y/H)^2), v = u * (y/H) * dH/dx
eta_norm = 2.0 * xi_y[None, :] - 1.0 # in (-1, 1)
q0 = 4.0 / 3.0
u = (0.75 * q0 / H_x[:, None]) * (1.0 - eta_norm**2)
v = u * eta_norm * dH_dx[:, None]
# Exact incompressible velocity gradients L_ij:
du_dx = (np.roll(u, -1, axis=0) - np.roll(u, 1, axis=0)) / (2.0 * hx) - (
eta_norm * dH_dx[:, None] / H_x[:, None]
) * (-1.5 * q0 * eta_norm / H_x[:, None])
du_dy = -1.5 * q0 * eta_norm / (H_x[:, None] ** 2)
dv_dx = (np.roll(v, -1, axis=0) - np.roll(v, 1, axis=0)) / (2.0 * hx)
dv_dy = -du_dx # Exact incompressibility div(u) == 0
Psi_xx = np.zeros((nx, ny), dtype=float)
Psi_yy = np.zeros((nx, ny), dtype=float)
Psi_xy = np.zeros((nx, ny), dtype=float)
C_xx = np.ones((nx, ny), dtype=float)
C_yy = np.ones((nx, ny), dtype=float)
C_xy = np.zeros((nx, ny), dtype=float)
hy_avg = 2.0 * float(np.mean(H_x)) / float(ny)
if wi > 1e-6:
for _ in range(n_steps):
Psi_xx, Psi_yy, Psi_xy, C_xx, C_yy, C_xy = _log_step_2d_field(
Psi_xx, Psi_yy, Psi_xy, u, v, du_dx, du_dy, dv_dx, dv_dy, hx, hy_avg, dt, wi=wi, periodic_x=True
)
g_mod = (1.0 - float(beta_s)) / max(float(wi), 1e-6) if wi > 1e-6 else 0.0
tau_xx = g_mod * (C_xx - 1.0)
tau_yy = g_mod * (C_yy - 1.0)
tau_xy = g_mod * C_xy
n1_field = tau_xx - tau_yy
tr_c = C_xx + C_yy
# Streamline curvature |d^2 y_stream / dx^2| = |eta_norm * d^2H/dx^2| -> R_curv = 1 / max(|kappa|, 1e-3):
d2H_dx2 = float(constriction_eps) * np.cos(x)
kappa = np.abs(eta_norm * d2H_dx2[:, None])
r_curv = 1.0 / np.maximum(kappa, 1e-3)
speed = np.hypot(u, v)
gdot_mag = np.sqrt(2.0 * (du_dx**2 + dv_dy**2) + (du_dy + dv_dx) ** 2)
pm = pakdel_mckinley_criterion(speed, r_curv, lam=wi, tau_11=np.maximum(n1_field, 0.0), eta0_shear_rate=gdot_mag)
return {
"x_grid": x_phys,
"y_grid": y_phys,
"H_wall": H_x,
"u": u,
"v": v,
"N1_field": n1_field,
"tau_xy_field": tau_xy,
"trC_field": tr_c,
"detC_min": float(np.min(np.exp(Psi_xx + Psi_yy))),
"pakdel_M_field": pm["M_pakdel"],
}
Analytical wavy-contraction solenoidal residual |du/dx + dv/dy| : 0.000e+00
Resolved RHEO_ATLAS_DB callables across Parts I..VI : 24 / 24
Exercises¶
Worked solutions are in 17_solutions.ipynb. The cell below the list is a short self-check to start from.
Verify a result. Check the lubrication result for the pressure drop in a slit whose gap varies as , relative to a straight slit, , for with the trapezoidal rule. Then compute the smallest pressure gradient at which the assumed gel
CARBOPOL_EVP() flows in a square duct of side , .Find how it fails. A design calculation that treats the fluid as Newtonian () is applied to a wavy slit with that is operated at and fed by a square duct at . Compare its predictions with
solve_2d_wavy_contraction_channeland withsolve_2d_duct_bingham_admm.Implement it yourself. Write
find_max_safe_throughput(eps_list, bn_feed, m_allow)in NumPy. The function first checks withsolve_2d_duct_bingham_admmthat the feed duct flows, and then finds by bisection on , withsolve_2d_wavy_contraction_channel, the largest Weissenberg number for which (an assumed limit), for .
heading("Self-check for the exercises")
assert bd_cap["overstretched_count"] == 0 and tc_cap["is_thermodynamically_admissible"]
assert q_duct[-1] < 1e-5 and (not js_safe["is_non_monotonic"])
assert best_design[3] <= M_allow and best_design[1] >= 1.5
assert len(atlas) == 24 and all(resolved)
print("All checks passed.")
Self-check for the exercises
============================
All checks passed.