Every Newton iteration solves one linear system . From pymrm
3.0.0, newton does this with a direct sparse LU factorisation
(scipy.sparse.linalg.splu) at every problem size, unless you ask for
something else. Direct LU is robust: it does not depend on a preconditioner or
an iterative tolerance, and newton reuses the factorisation for its damping
test. Its cost is the fill-in of the factors. On a 1-D or 2-D grid that
fill-in is modest, but on a 3-D grid it grows quickly, and the factorisation
can then dominate the run time and the memory.
This example solves the same steady diffusion-reaction problem in 2-D and in 3-D with three linear solvers:
| solver | what it is | how it is passed |
|---|---|---|
| direct LU | the default | nothing, or solver="lu" |
| ILU + GMRES | incomplete LU as preconditioner of GMRES, SciPy only | an object with a factorize method |
| AMG + CG | algebraic multigrid as preconditioner of conjugate gradients (pyamg, optional) | an object with a factorize method |
An object with a factorize(jac) method that returns an object with a
.solve(rhs) method is pymrm’s protocol for a user-supplied linear solver.
newton calls factorize once per Jacobian and solve for every right-hand
side, including those of the damping test. A plain function
solver(jac, rhs) also works, but then newton cannot tell factorising from
solving.
Imports¶
import math
import time
import numpy as np
from scipy.sparse import diags_array, linalg as sla
from pymrm import construct_div, construct_grad, newton
from pymrm.checks import residual_check
try:
import pyamg
except ImportError: # pip install pyamg to run the AMG solver
pyamg = NoneThe model¶
A cube (or square) of catalyst with unit side, surface concentration on every face, and Langmuir-Hinshelwood kinetics, in dimensionless form:
with and . The residual is , and its Jacobian is symmetric and positive definite on this uniform grid: the Laplacian part is symmetric negative definite and the rate derivative is positive. That is what makes conjugate gradients applicable. A convective term or a coupled multi-component rate would make non-symmetric; use GMRES or BiCGSTAB then.
The diffusion operator is constant, so it is assembled once.
PHI2, K_ADS = 50.0, 5.0
def build_model(n, dim):
# Residual and Jacobian of the steady pellet on an n**dim grid.
shape = (n,) * dim + (1,)
x_f = np.linspace(0.0, 1.0, n + 1)
x_c = 0.5 * (x_f[1:] + x_f[:-1])
# a dc/dn + b c = d with the outward normal: a = 0, b = 1, d = 1 is c = 1 on both ends
bc = {"a": 0.0, "b": 1.0, "d": 1.0}
lap, lap_bc = None, None
for axis in range(dim):
grad, grad_bc = construct_grad(shape, x_f, x_c, bc=(bc, bc), axis=axis)
div = construct_div(shape, x_f, nu=0, axis=axis) # nu = 0: Cartesian
lap = div @ grad if lap is None else lap + div @ grad
lap_bc = div @ grad_bc if lap_bc is None else lap_bc + div @ grad_bc
jac_diff = (-lap).tocsr()
g_diff = -np.asarray(lap_bc.todense()).reshape(-1, 1)
def residual(c):
c = c.reshape(-1, 1)
rate = PHI2 * c / (1.0 + K_ADS * c)
d_rate = PHI2 / (1.0 + K_ADS * c) ** 2
return jac_diff @ c + g_diff + rate, (jac_diff + diags_array(d_rate.ravel())).tocsr()
return residual, shapeTwo factorize objects¶
Each factorize builds the preconditioner for the current Jacobian and returns
an object whose solve runs the Krylov iteration. Two rules matter:
Solve tightly. The iterative solve must be accurate well below the Newton tolerance (here a relative residual of 10-10). A loose inner solve makes Newton converge linearly instead of quadratically, and
newton’s backward-error test then keeps iterating.Raise on failure. A Krylov method that stops at its iteration limit returns an approximate answer with
info != 0. Raise an exception instead of returning it, so that a failed solve cannot pass as a Newton step.
class IluGmres:
# Incomplete-LU preconditioned GMRES (SciPy only).
def factorize(self, jac):
ilu = sla.spilu(jac.tocsc(), drop_tol=1e-4, fill_factor=10)
precond = sla.LinearOperator(jac.shape, ilu.solve)
class Factor:
def solve(self, rhs):
x, info = sla.gmres(jac, rhs, M=precond, rtol=1e-10, atol=0.0,
restart=50, maxiter=20)
if info != 0:
raise RuntimeError(f"GMRES did not converge (info={info})")
return x
return Factor()
class AmgCg:
# Smoothed-aggregation AMG preconditioned conjugate gradients (needs pyamg).
def factorize(self, jac):
a = jac.tocsr()
a.indptr = a.indptr.astype(np.int32) # pyamg's kernels take 32-bit indices
a.indices = a.indices.astype(np.int32)
precond = pyamg.smoothed_aggregation_solver(a).aspreconditioner(cycle="V")
class Factor:
def solve(self, rhs):
x, info = sla.cg(jac, rhs, M=precond, rtol=1e-10, atol=0.0, maxiter=200)
if info != 0:
raise RuntimeError(f"CG did not converge (info={info})")
return x
return Factor()Comparison¶
The same Newton iteration (default options, tol=1e-9) from , on a
2-D grid of 1502 and a 3-D grid of 323 cells. The table reports the wall
time, the Newton iterations and the largest difference from the direct-LU
solution.
solvers = {"direct LU": None, "ILU + GMRES": IluGmres()}
if pyamg is not None:
solvers["AMG + CG"] = AmgCg()
else:
print("pyamg is not installed: the AMG solver is skipped (pip install pyamg)")
results = {}
print(f"{'grid':>8s} {'unknowns':>9s} {'solver':>12s} {'time':>8s} {'nit':>4s} {'diff to LU':>11s}")
for dim, n in [(2, 150), (3, 32)]:
residual, shape = build_model(n, dim)
reference = None
for name, solver in solvers.items():
t0 = time.perf_counter()
sol = newton(residual, np.ones(shape), tol=1e-9, solver=solver)
elapsed = time.perf_counter() - t0
assert sol.success, sol.message
if reference is None:
reference = sol.x
diff = float(np.max(np.abs(sol.x - reference)))
results[(dim, name)] = (sol, residual)
print(f"{n:>4d}^{dim} {math.prod(shape):>9d} {name:>12s} {elapsed:7.2f}s {sol.nit:>4d} {diff:11.1e}") grid unknowns solver time nit diff to LU
150^2 22500 direct LU 0.30s 5 0.0e+00
150^2 22500 ILU + GMRES 6.14s 5 4.6e-15
150^2 22500 AMG + CG 0.45s 5 4.7e-15
32^3 32768 direct LU 20.33s 4 0.0e+00
32^3 32768 ILU + GMRES 6.46s 4 1.1e-15
32^3 32768 AMG + CG 0.62s 4 1.1e-15
All solvers reach the same solution, to round-off, in the same number of Newton iterations: the linear solver changes the cost of an iteration, not the iteration.
Timings on one machine at larger sizes (same model and solver classes,
tol=1e-9; they depend on the machine and its load, so compare ratios, not
seconds):
| grid | unknowns | direct LU | ILU + GMRES | AMG + CG |
|---|---|---|---|---|
| 1502 | 22 500 | 0.32 s | 6.0 s | 0.36 s |
| 2002 | 40 000 | 0.65 s | 15 s | 0.58 s |
| 5002 | 250 000 | 7.2 s | fails (GMRES limit) | 3.8 s |
| 303 | 27 000 | 12.8 s | 4.5 s | 0.43 s |
| 503 | 125 000 | 432 s | 48 s | 2.1 s |
In 2-D, direct LU and AMG are equally fast up to 40 000 unknowns, and AMG is twice as fast at 250 000. In 3-D the LU factors fill in: at 27 000 unknowns AMG is already 30 times faster than LU, and at 125 000 unknowns 200 times. ILU-preconditioned Krylov solvers are the weakest choice: in 2-D they are 20 times slower than LU, in 3-D they beat LU but stay 10 to 20 times slower than AMG, they need a drop tolerance tuned to the problem, and GMRES ran out of iterations on the largest 2-D grid. This is why pymrm 3.0.0 dropped its automatic switch from LU to ILU-preconditioned BiCGSTAB above 50 000 unknowns.
Rule of thumb. Keep the default direct LU for 1-D and 2-D models: it
needs no tuning, and AMG gains at most a factor of two there. For a 3-D model,
plug in AMG through a factorize object, with a tight inner tolerance and an
exception on failure. CG requires a symmetric positive-definite Jacobian, as
here; with convection or coupled kinetics, test AMG with GMRES or BiCGSTAB on
the problem itself.
Checking the result¶
Agreement between solvers shows that each linear solver did its job, but all three solve the same discrete equations, so it cannot reveal an error in those equations. Two independent checks follow:
residual_checkconfirms that the returned solution satisfies the discrete equations: its backward error must be at round-off level.Mass balance: at steady state, the diffusive flux into the pellet through its faces equals the total reaction rate inside. Both sides are computed independently: the flux from the boundary faces and the rate from the cell values. The face gradients come from the same
construct_gradoperators, so the balance tests the conservation of the discretisation and the convergence of the solve, not the gradient formula itself.
for (dim, name), (sol, residual) in results.items():
check = residual_check(residual, sol.x)
assert check["ok"], (dim, name, check)
print("residual_check passes for every solver and grid")
# Mass balance for the 3-D direct-LU solution.
n, dim = 32, 3
sol, residual = results[(dim, "direct LU")]
c = sol.x.reshape((n,) * dim)
shape = (n,) * dim + (1,)
h = 1.0 / n
x_f = np.linspace(0.0, 1.0, n + 1)
x_c = 0.5 * (x_f[1:] + x_f[:-1])
bc = {"a": 0.0, "b": 1.0, "d": 1.0}
total_rate = float(np.sum(PHI2 * c / (1.0 + K_ADS * c))) * h**dim
# Inflow -grad(c).n_inward: +dc/dx at x = 0 (inward normal +x) and -dc/dx at x = 1.
face_flux = 0.0
for axis in range(dim):
grad, grad_bc = construct_grad(shape, x_f, x_c, bc=(bc, bc), axis=axis)
face_shape = list(shape)
face_shape[axis] += 1
dc = (grad @ c.reshape(-1, 1) + grad_bc).reshape(face_shape)
inflow = np.take(dc, 0, axis=axis).sum() - np.take(dc, -1, axis=axis).sum()
face_flux += -float(inflow) * h ** (dim - 1)
rel_error = abs(face_flux - total_rate) / total_rate
print(f"reaction {total_rate:.6f}, inflow {face_flux:.6f}, relative difference {rel_error:.1e}")
assert rel_error < 1e-8residual_check passes for every solver and grid
reaction 8.053434, inflow 8.053434, relative difference 1.3e-15