Worked solutions to the three exercises of Lecture 10. Each solution is computed here and checked with assert statements against an exact identity or an independent calculation. The first code cell sets up the notebook and runs Demonstration 1 of the lecture without showing its output, because some of the solutions use its variables.
try: # use the installed package, or the copy in this repository
import engcomprheo
except ImportError:
import pathlib, subprocess, sys
for _root in [pathlib.Path.cwd(), *pathlib.Path.cwd().parents]:
if (_root / "engcomprheo" / "__init__.py").exists():
sys.path.insert(0, str(_root))
break
else: # on Google Colab: install from GitHub
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"git+https://github.com/ktwyw/engcomprheo.git"], check=True)
import engcomprheo
import inspect
import math
import numpy as np
import matplotlib.pyplot as plt
from engcomprheo import (brownian_chains, constants_benchmarks, entangled_tubes, mesoscopic_suspensions_dpd,
microrheology_rheoml, shear_banding_instabilities, tensors_kinematics,
viscoelastic_fvm_2d, viscoplastic_admm)
from engcomprheo.plotting import label_panels, log_ticks, panel_label, use_style
use_style()
trapezoid = getattr(np, "trapezoid", None) or np.trapz # NumPy 2 renamed trapz to trapezoid
def show_source(obj):
"""Return the source code of a function or class of the package."""
return inspect.getsource(obj)
def heading(text):
print(f"\n{text}\n" + "=" * len(text))
# Demonstration 1 of the lecture, run without output: the solutions use its variables.
import contextlib, io
_show, plt.show = plt.show, lambda *args, **kwargs: None
_stdout = contextlib.redirect_stdout(io.StringIO()); _stdout.__enter__()
heading("Demonstration 1: Newtonian flow in a square duct against the series solution")
m_idx = np.arange(0, 40, dtype=float)
odd = 2.0 * m_idx + 1.0
q_boussinesq = (16.0 / 12.0) * (1.0 - (192.0 / (math.pi**5)) * float(np.sum(np.tanh(0.5 * math.pi * odd) / (odd**5))))
grids = [16, 32, 64]
q_errs = []
for ng in grids:
sol0 = viscoplastic_admm.solve_2d_duct_bingham_admm(nx=ng, ny=ng, H_half=1.0, dpdz_neg=1.0, tau_y=0.0, eta_p=1.0, r_aug=0.05, max_iter=25, tol=1e-10)
err = abs(sol0["flow_rate"] - q_boussinesq) / q_boussinesq
q_errs.append(err)
print(f"Grid {ng:2d}x{ng:2d} | ADMM Q = {sol0['flow_rate']:.7f} | series solution = {q_boussinesq:.7f} | rel err = {err:.3e}")
order_h = math.log(q_errs[0] / q_errs[2]) / math.log((64 + 1) / (16 + 1))
print(f"Observed spatial convergence order p = {order_h:.2f} (expected 2nd-order Q1 accuracy ~ 2.0)")
assert q_errs[-1] < 5e-4
assert 1.85 < order_h < 2.15
fig, axes = plt.subplots(1, 2, figsize=(10.2, 4.0))
im0 = axes[0].contourf(sol0["x"], sol0["y"], sol0["u"].T, levels=18, cmap="Blues")
plt.colorbar(im0, ax=axes[0], label="Velocity $u(x, y)$")
axes[0].set_aspect("equal")
axes[0].set_xlabel("$x / H$")
axes[0].set_ylabel("$y / H$")
axes[0].set_title(r"Newtonian velocity in a square duct")
h_vals = 2.0 / (np.array(grids) + 1.0)
axes[1].loglog(h_vals, q_errs, "ro-", lw=2.1, ms=7, label=f"Error of the flow rate (slope $= {order_h:.2f}$)")
axes[1].loglog(h_vals, q_errs[0] * ((h_vals / h_vals[0]) ** 2), "k--", lw=1.5, label=r"Reference $\mathcal{O}(h^2)$")
axes[1].set_xlabel("Grid spacing $h / H$")
axes[1].set_ylabel("Relative volumetric flux error")
axes[1].set_title(r"Error of the flow rate")
axes[1].legend(fontsize=8)
log_ticks(axes[1], "x", [0.03, 0.06, 0.12])
label_panels(fig)
plt.show()
_stdout.__exit__(None, None, None); plt.show = _show; plt.close("all")Exercise 1¶
Problem. A region with rounded corners of radius inside a square duct of half-width has the area and the perimeter . Maximize over to obtain and , and explain why the square () and the inscribed circle () both give .
heading("Exercise 1: the critical Bingham number of a square duct")
H_v = 1.0
R_grid = np.linspace(0.0, H_v, 2001)
area_R = 4.0 * (H_v**2) - (4.0 - math.pi) * (R_grid**2)
perim_R = 8.0 * H_v - 2.0 * (4.0 - math.pi) * R_grid
phi_R = area_R / (H_v * perim_R)
idx_opt = int(np.argmax(phi_R))
R_num = float(R_grid[idx_opt])
bn_num = float(phi_R[idx_opt])
R_exact = 2.0 * H_v / (2.0 + math.sqrt(math.pi))
bn_exact = constants_benchmarks.MOSOLOV_SQUARE_DUCT_BN_CRIT
print(f"Square boundary (R = 0) ratio A/(H*P) = {phi_R[0]:.6f}")
print(f"Inscribed circle (R = H) ratio A/(H*P) = {phi_R[-1]:.6f}")
print(f"Optimal Mosolov arc R* = {R_num:.6f} (exact = {R_exact:.6f}) -> Bn_crit = {bn_num:.8f} (exact = {bn_exact:.8f})")
assert abs(R_num - R_exact) < 1e-3
assert abs(bn_num - bn_exact) < 1e-7
assert np.isclose(phi_R[0], 0.5) and np.isclose(phi_R[-1], 0.5)
# Draw the exact critical Mosolov yield surface inside [-1, 1]^2:
theta = np.linspace(0.0, 0.5 * math.pi, 80)
c_xy = H_v - R_exact
arc_q1_x = c_xy + R_exact * np.cos(theta)
arc_q1_y = c_xy + R_exact * np.sin(theta)
fig, axes = plt.subplots(1, 2, figsize=(9.8, 4.0))
axes[0].plot(R_grid, phi_R, "b-", lw=2.2, label=r"Trial ratio $\Phi(R) = A(R) / [H\,P(R)]$")
axes[0].scatter([R_exact], [bn_exact], color="#C0392B", s=70, zorder=5, label=f"Maximum $(R_*, \\mathrm{{Bn}}_{{\\mathrm{{crit}}}}) = ({R_exact:.3f}, {bn_exact:.4f})$")
axes[0].axhline(0.5, color="gray", ls=":", lw=1.3, label="Hydraulic diameter estimate $0.5000$")
axes[0].set_xlabel("Corner rounding radius $R / H$")
axes[0].set_ylabel(r"Yield balance ratio $\Phi(R)$")
axes[0].set_title(r"Ratio $A/(HP)$ against corner radius")
axes[0].legend(fontsize=8, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=1)
for sx in [-1.0, 1.0]:
for sy in [-1.0, 1.0]:
axes[1].plot(sx * arc_q1_x, sy * arc_q1_y, "r-", lw=2.3)
axes[1].plot([-c_xy, c_xy], [1.0, 1.0], "r-", lw=2.3, label="Critical yield surface")
axes[1].plot([-c_xy, c_xy], [-1.0, -1.0], "r-", lw=2.3)
axes[1].plot([1.0, 1.0], [-c_xy, c_xy], "r-", lw=2.3)
axes[1].plot([-1.0, -1.0], [-c_xy, c_xy], "r-", lw=2.3)
axes[1].plot([-1, 1, 1, -1, -1], [-1, -1, 1, 1, -1], "k--", lw=1.3, label="Square duct walls")
axes[1].set_aspect("equal")
axes[1].set_xlabel("$x / H$")
axes[1].set_ylabel("$y / H$")
axes[1].set_title(r"The critical plug")
axes[1].legend(fontsize=8, loc="center")
label_panels(fig)
plt.show()
Exercise 1: the critical Bingham number of a square duct
========================================================
Square boundary (R = 0) ratio A/(H*P) = 0.500000
Inscribed circle (R = H) ratio A/(H*P) = 0.500000
Optimal Mosolov arc R* = 0.530000 (exact = 0.530159) -> Bn_crit = 0.53015890 (exact = 0.53015890)

Figure S10.1. (a) Area of a square with rounded corners divided by times its perimeter, against the corner radius; the maximum 0.5302 is at . (b) The corresponding plug boundary inside the duct.
Explanation. A region of area and perimeter can move only if the pressure force exceeds the yield force , that is if . The flow stops when no region can move, so the critical Bingham number is the largest value of . For the square and for the inscribed circle the ratio is 0.5. A square with rounded corners has a larger ratio, with the maximum at , 6 % above 0.5. The search over a grid of radii gives 0.53015890, in agreement with the formula to eight digits.
Exercise 2¶
Problem. For , , and (), compare the flow rate estimated from the plane-channel formula, , with the result of the two-dimensional solver for the square duct (r_aug=2.0). Compute the smallest pressure gradient at which the duct flows, , and check that there is flow at .
heading("Exercise 2: the plane-channel estimate for a blocked square duct")
H_d, ty_d, etap_d = 1.0, 0.58, 1.0
G_design = 1.0 # Gives Bn = 0.58: below the plane-channel limit 1.0 but above the square-duct limit 0.5302
naive_1d = viscoplastic_admm.buckingham_reiner_exact_1d(
np.linspace(-1.0, 1.0, 101), dpdz_neg=G_design, H_or_R=H_d, tau_y=ty_d, eta_p=etap_d, geometry="planar"
)
q_naive_2d = 2.0 * H_d * naive_1d["flow_rate"]
admm_plugged = viscoplastic_admm.solve_2d_duct_bingham_admm(
nx=34, ny=34, H_half=H_d, dpdz_neg=G_design, tau_y=ty_d, eta_p=etap_d, r_aug=2.0, max_iter=300, tol=1e-9
)
G_min_exact = ty_d / (H_d * constants_benchmarks.MOSOLOV_SQUARE_DUCT_BN_CRIT)
G_fixed = 1.35 # Safely above G_min_exact ~ 1.094 -> Bn = 0.4296 < 0.5302
admm_restarted = viscoplastic_admm.solve_2d_duct_bingham_admm(
nx=34, ny=34, H_half=H_d, dpdz_neg=G_fixed, tau_y=ty_d, eta_p=etap_d, r_aug=0.25, max_iter=320, tol=1e-7
)
print(f"Plane-channel formula at G=1.0 (Bn=0.58) : Q = {q_naive_2d:.5f}")
print(f"Square duct, 2-D solver, at G=1.0 (Bn=0.58) : Q = {admm_plugged['flow_rate']:.5f}, unyielded = {100*admm_plugged['unyielded_area_fraction']:.1f}%")
print(f"Smallest pressure gradient with flow, G_min : {G_min_exact:.4f} | restarted Q at G={G_fixed:.2f} = {admm_restarted['flow_rate']:.5f}")
assert q_naive_2d > 0.25
assert admm_plugged["flow_rate"] == 0.0 and admm_plugged["unyielded_area_fraction"] == 1.0
assert G_fixed > G_min_exact and admm_restarted["flow_rate"] > 0.03
fig, axes = plt.subplots(1, 2, figsize=(9.8, 3.8))
axes[0].bar(
["Plane channel\n($G=1.0$)", "Square duct\n($G=1.0$)", f"Square duct\n($G={G_fixed:.2f}$)"],
[q_naive_2d, admm_plugged["flow_rate"], admm_restarted["flow_rate"]],
color=["#C0392B", "#1F2933", "#2E8B57"],
)
axes[0].set_ylabel("Volumetric discharge $Q$")
axes[0].set_title(r"Flow rate at $\tau_y = 0.58$")
im_ok = axes[1].contourf(admm_restarted["x"], admm_restarted["y"], admm_restarted["u"].T, levels=16, cmap="viridis")
plt.colorbar(im_ok, ax=axes[1], label="Velocity $u(x, y)$")
axes[1].set_aspect("equal")
axes[1].set_title(r"Velocity after raising the pressure gradient")
label_panels(fig)
plt.show()
Exercise 2: the plane-channel estimate for a blocked square duct
================================================================
Plane-channel formula at G=1.0 (Bn=0.58) : Q = 0.30341
Square duct, 2-D solver, at G=1.0 (Bn=0.58) : Q = 0.00000, unyielded = 100.0%
Smallest pressure gradient with flow, G_min : 1.0940 | restarted Q at G=1.35 = 0.05136

Figure S10.2. (a) Flow rate from the plane-channel formula, from the square-duct solver at the same pressure gradient (zero), and from the solver at . (b) Velocity in the duct at .
Explanation. A plane channel flows at any Bingham number below 1, and its formula predicts a flow rate of 0.303 here. In the square duct the side walls carry part of the load, the critical Bingham number is 0.530, and at the solver gives no flow: the whole cross-section is unyielded. Flow starts at , and at the flow rate is 0.051. An estimate from the plane-channel formula predicts flow here in a duct that is blocked.
Exercise 3¶
Problem. Write solve_1d_channel_bingham_admm(nx, H_half, dpdz_neg, tau_y, eta_p, r_aug), the augmented Lagrangian method for a plane channel without regularization: a Poisson problem solved with the discrete sine transform, followed by the shrinkage step for the strain rate. Compare the velocity and the flow rate with buckingham_reiner_exact_1d for and , and check that the velocity is zero for .
heading("Exercise 3: the augmented Lagrangian method in a plane channel")
def solve_1d_channel_bingham_admm(
nx: int = 160, H_half: float = 1.0, dpdz_neg: float = 2.0, tau_y: float = 0.7, eta_p: float = 1.0, r_aug: float = 1.0
) -> dict:
"""NumPy 1-D ADMM Bingham solver on [-H_half, +H_half] using exact DST-I Poisson steps."""
h = (2.0 * H_half) / (nx + 1.0)
y_nodes = -H_half + np.arange(1, nx + 1, dtype=float) * h
eig_1d = (4.0 / (h**2)) * (np.sin(0.5 * math.pi * np.arange(1, nx + 1) / (nx + 1.0)) ** 2)
denom = (eta_p + r_aug) * eig_1d
scale_idst = 2.0 / (nx + 1.0)
u = np.zeros(nx)
d = np.zeros(nx + 1)
lam = np.zeros(nx + 1)
f_rhs = np.full(nx, float(dpdz_neg))
for _ in range(450):
# Adjoint of forward cell gradient (u_pad[1:] - u_pad[:-1])/h is (p[:-1] - p[1:])/h:
p = lam - r_aug * d
rhs = f_rhs - (p[:-1] - p[1:]) / h
u = scale_idst * viscoplastic_admm._dst1_1d(viscoplastic_admm._dst1_1d(rhs) / denom)
u = np.maximum(u, 0.0)
u_pad = np.pad(u, 1, mode="constant", constant_values=0.0)
grad_u = (u_pad[1:] - u_pad[:-1]) / h
s = lam + r_aug * grad_u
d_new = (np.maximum(0.0, np.abs(s) - tau_y) * np.sign(s)) / r_aug
lam = lam + r_aug * (1.5 * grad_u - 0.5 * d - d_new)
if max(float(np.max(np.abs(grad_u - d_new))), float(r_aug * np.max(np.abs(d_new - d)))) < 1e-10:
d = d_new
break
d = d_new
q_admm = float(np.sum(u) * h)
return {"y": y_nodes, "u": u, "d": d, "flow_rate": q_admm}
sol_1d_y = solve_1d_channel_bingham_admm(nx=199, H_half=1.0, dpdz_neg=2.0, tau_y=0.7, eta_p=1.0, r_aug=1.2)
ref_1d_y = viscoplastic_admm.buckingham_reiner_exact_1d(sol_1d_y["y"], dpdz_neg=2.0, H_or_R=1.0, tau_y=0.7, eta_p=1.0, geometry="planar")
sol_1d_sub = solve_1d_channel_bingham_admm(nx=99, H_half=1.0, dpdz_neg=0.56, tau_y=0.7, eta_p=1.0, r_aug=2.0)
u_err_1d = float(np.max(np.abs(sol_1d_y["u"] - ref_1d_y["velocity"])))
q_err_1d = abs(sol_1d_y["flow_rate"] - ref_1d_y["flow_rate"]) / ref_1d_y["flow_rate"]
print(f"Yielded test : max |u_ADMM - u_exact| = {u_err_1d:.4e}, rel flux err = {q_err_1d:.4e}")
print(f"Sub-yield test : max |u_ADMM| at tau_w = 0.8*tau_y = {np.max(np.abs(sol_1d_sub['u'])):.3e}")
assert u_err_1d < 5e-4 and q_err_1d < 5e-4
assert np.max(np.abs(sol_1d_sub["u"])) < 1e-14
yc = np.linspace(-1.0 + 1.0 / 200.0, 1.0 - 1.0 / 200.0, 200)
fig, axes = plt.subplots(1, 2, figsize=(9.8, 3.8))
axes[0].plot(ref_1d_y["velocity"], sol_1d_y["y"], "k-", lw=2.3, label="Exact Buckingham–Reiner")
axes[0].plot(sol_1d_y["u"][::8], sol_1d_y["y"][::8], "ro", ms=5, label="Augmented Lagrangian solver")
axes[0].plot(sol_1d_sub["u"], sol_1d_sub["y"], "b--", lw=2.0, label=r"Solver at $\tau_w = 0.8\tau_y$ ($u \equiv 0$)")
axes[0].set_xlabel("Velocity $u(y)$")
axes[0].set_ylabel("$y / H$")
axes[0].set_title(r"Velocity")
axes[0].legend(fontsize=8, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=1)
axes[1].plot(yc, np.abs(sol_1d_y["d"]), color="#7B4FA3", lw=2.1, label=r"Computed $|d(y)|$")
axes[1].axvspan(-0.35, 0.35, color="#d4e6f1", alpha=0.55, label=r"Exact plug $[-0.35, 0.35]$")
axes[1].set_xlabel("$y / H$")
axes[1].set_ylabel(r"Strain rate $|d(y)|$")
axes[1].set_title(r"Rate of strain")
axes[1].legend(fontsize=8)
label_panels(fig)
plt.show()
Exercise 3: the augmented Lagrangian method in a plane channel
==============================================================
Yielded test : max |u_ADMM - u_exact| = 3.5947e-11, rel flux err = 3.2733e-05
Sub-yield test : max |u_ADMM| at tau_w = 0.8*tau_y = 2.439e-17

Figure S10.3. One-dimensional augmented Lagrangian solver. (a) Velocity against the exact Bingham solution, and zero velocity at . (b) The variable is zero across the plug (shaded).
Explanation. Each iteration solves a linear problem with the constant operator and then applies the shrinkage step, which sets the strain rate to exactly zero wherever the stress is below the yield stress. The velocity agrees with the exact solution to at the grid points, and the flow rate to a relative error of . Below the yield stress the largest velocity is , in contrast with the creep of order of the regularized model of Lecture 9.