Exercise: iterative linear solvers in depth
Goal
By the end of this exercise you should be able to:
- write Jacobi and Gauss–Seidel as splittings \(\mathbf{x} \leftarrow \mathbf{x} + M^{-1}(\mathbf{b} - A\mathbf{x})\) and run them by hand on a tiny grid,
- predict their speed from the spectral radius of the iteration matrix, and explain why they slow down by a factor 4 each time the grid is refined,
- count conjugate gradient iterations as the grid grows and relate them to \(\sqrt{\kappa}\),
- run CG by hand on a small system and see the Krylov space and the minimisation at work; estimate CG iteration counts from \(\sqrt{\kappa}\),
- use a preconditioner (diagonal, incomplete Cholesky) and say when it helps,
- recognise a nonsymmetric system, see CG fail on it, and solve it with GMRES,
- see restarted GMRES stall, detect it, and try BiCGSTAB, the short-recurrence alternative.
The by-hand part needs pen and paper (and a calculator for B2–B4 and B7). The code part builds on the jacobi and cg functions you wrote in C8 of Structure: symmetric, banded, sparse (there they stopped on an absolute residual of \(10^{-10}\); here on a relative one, fact 7). The solutions define every function they use.
Background
The chamber. (Not the lid chamber of Steady state in two dimensions: a different, scaled problem with the same five-point matrix.) Oxygen in a 1 mm × 1 mm cell-laden gel, supplied through all four walls (concentration 1 = ambient) and consumed uniformly by the cells. The oxygen deficit \(u = 1 - c\) solves \(-\Delta u = \Phi\) with \(u = 0\) on the walls, \(\Phi = 12\). On an \(m \times m\) grid of interior points with spacing \(h = 1/(m+1)\), multiplied through by \(h^2\): \[4u_{ij} - u_{i-1,j} - u_{i+1,j} - u_{i,j-1} - u_{i,j+1} = \Phi h^2,\] a sparse SPD system \(A\mathbf{u} = \mathbf{b}\) with \(n = m^2\) unknowns and five non-zeros per row. The unknowns are numbered row by row: \(u_{ij}\) is entry \(i + m(j-1)\).
Facts used below:
- Splitting. With \(A = M - N\): \(\mathbf{x}_{k+1} = \mathbf{x}_k + M^{-1}(\mathbf{b} - A\mathbf{x}_k)\). Jacobi: \(M = D\) (diagonal). Gauss–Seidel: \(M\) = lower triangle of \(A\) including the diagonal; in a sweep, each point uses the neighbours’ newest values.
- Error and spectral radius. \(\mathbf{e}_{k+1} = T\mathbf{e}_k\) with \(T = I - M^{-1}A\). The iteration converges for every start if and only if \(\rho(T) = \max_i |\lambda_i(T)| < 1\); the error shrinks by about \(\rho\) per step, so one digit takes \(\ln 10 / (-\ln \rho)\) steps.
- On this grid: \(\rho_J = \cos \pi h\), \(\rho_{GS} = \cos^2 \pi h\), and \(\kappa(A) = \cot^2(\pi h/2) \approx 4/(\pi^2 h^2)\).
- CG (SPD only) needs about \(\tfrac12\sqrt{\kappa}\,\ln(2/\text{tol})\) iterations at most; in practice the count grows like \(\sqrt{\kappa} \sim 1/h\).
- Preconditioned CG replaces \(\mathbf{z} = \mathbf{r}\) by \(\mathbf{z} = M^{-1}\mathbf{r}\) with \(M \approx A\) SPD. Jacobi: \(M = D\). Incomplete Cholesky IC(0): \(M = LL^T\) where \(L\) has the pattern of the lower triangle of \(A\) (fill-in dropped).
- GMRES finds the \(\mathbf{x}_k\) in the Krylov space \(\text{span}\{\mathbf{b}, A\mathbf{b}, \dots, A^{k-1}\mathbf{b}\}\) with the smallest residual; it works for nonsymmetric \(A\) but stores all \(k\) basis vectors.
- Stopping: in this exercise every method stops when the relative residual \(\|\mathbf{b} - A\mathbf{x}\| / \|\mathbf{b}\| < 10^{-6}\).
- Restarted GMRES(\(k\)) keeps at most \(k\) basis vectors, then starts again from the current iterate. It converges for every \(k\) if \(\mathbf{v}^TA\mathbf{v} > 0\) for all \(\mathbf{v} \ne \mathbf{0}\) (the symmetric part \((A + A^T)/2\) is positive definite); otherwise it can stall: the residual stops decreasing.
- BiCGSTAB handles nonsymmetric \(A\) with short recurrences: fixed memory (seven vectors), two products with \(A\) per step. Its residual is not monotone, and it can stagnate or break down.
Building the matrix and solving directly:
library(Matrix)
lap1 <- function(m) bandSparse(m, k = -1:1,
diagonals = list(rep(-1, m - 1), rep(2, m), rep(-1, m - 1)))
lap2 <- function(m) { I <- Diagonal(m); T <- lap1(m); kronecker(I, T) + kronecker(T, I) }
chamber_rhs <- function(m, Phi = 12) rep(Phi / (m + 1)^2, m^2)
m <- 63; A <- lap2(m); b <- chamber_rhs(m)
c(n = nrow(A), nnz = nnzero(A))
u <- solve(A, b) # sparse direct solve
1 - u[(m^2 + 1) / 2] # oxygen in the centre
# Output:
# n nnz
# 3969 19593
# [1] 0.1161138import numpy as np
from scipy import sparse
from scipy.sparse.linalg import spsolve
def lap1(m):
return sparse.diags([-np.ones(m - 1), 2 * np.ones(m), -np.ones(m - 1)], [-1, 0, 1])
def lap2(m):
I, T = sparse.identity(m), lap1(m)
return (sparse.kron(I, T) + sparse.kron(T, I)).tocsr()
def chamber_rhs(m, Phi=12):
return np.full(m * m, Phi / (m + 1) ** 2)
m = 63; A = lap2(m); b = chamber_rhs(m)
print(A.shape[0], A.nnz)
u = spsolve(A, b) # sparse direct solve
print(1 - u[(m * m - 1) // 2]) # oxygen in the centre
# Output:
# 3969 19593
# 0.1161137741104935// rust/examples/iterative_solvers_background.rs — cargo run --example iterative_solvers_background
// The chamber matrix in sprs. sprs has no sparse direct solver, so the
// reference solution comes from (hand-written) CG with a tight tolerance.
include!("iterative_solvers_shared/defs.rs");
fn main() {
let m = 63;
let (a, b) = (lap2(m), chamber_rhs(m, 12.0));
println!("{} {}", a.rows(), a.nnz());
let (u, _) = pcg(&a, &b, |r| r.to_vec(), 1e-12, 10_000);
println!("{}", 1.0 - u[(m * m - 1) / 2]); // oxygen in the centre
}
// Output:
// 3969 19593
// 0.11611377411051838R’s solve on a sparse SPD matrix runs a sparse Cholesky with a fill-reducing ordering (Python: scipy.sparse.linalg.spsolve, a sparse LU). The Rust crate sprs has no sparse direct solver, so the Rust background solves with the hand-written CG of rust/examples/iterative_solvers_shared/defs.rs (shared by all Rust files of this exercise: lap2, chamber_rhs, matvec, dot, norm, diagonal and pcg) to a tolerance of \(10^{-12}\); it agrees with the direct solve to 14 digits.
By hand
B1. Jacobi and Gauss–Seidel on four points. Take \(m = 2\) (four interior points, numbered 1 2 in the bottom row and 3 4 in the top row) and \(\mathbf{b} = (1, 1, 1, 1)\). (a) Write down \(A\). Check that \(\mathbf{x} = (0.5, 0.5, 0.5, 0.5)\) solves \(A\mathbf{x} = \mathbf{b}\). (b) Do three Jacobi steps from \(\mathbf{x}_0 = \mathbf{0}\). By what factor does the error shrink per step? (c) Do two Gauss–Seidel sweeps from \(\mathbf{0}\), in the order 1, 2, 3, 4. Give the error of point 4 after each sweep and their ratio. (d) Compare (b) and (c) with fact 3 (\(h = 1/3\)).
B2. A spectral radius. For a row of three cells, \(A = \begin{pmatrix}2&-1&0\\-1&2&-1\\0&-1&2\end{pmatrix}\). (a) Write down the Jacobi iteration matrix \(T_J = I - D^{-1}A\). Show that \((1, \sqrt2, 1)\) is an eigenvector and find all three eigenvalues (the trace and the other two eigenvectors \((1, 0, -1)\) and \((1, -\sqrt2, 1)\) help). (b) What is \(\rho(T_J)\)? Compare with \(\cos(\pi h)\), \(h = 1/4\). How many Jacobi steps per digit? (c) For the chamber with \(m = 63\): \(\rho_J = \cos(\pi/64) = 0.998795\). How many sweeps per digit, and how many for six digits? Gauss–Seidel? (d) Why does Jacobi diverge for \(\begin{pmatrix}1&2\\2&1\end{pmatrix}\) but converge for \(\begin{pmatrix}2&1\\1&2\end{pmatrix}\)?
B3. Cost of refining. On the chamber, CG took 100 iterations and Jacobi 11 302 sweeps at \(m = 63\). (a) Predict both counts for \(m = 127\) and \(m = 255\) (use \(1/h = m + 1\)). (b) One iteration of either costs about \(2\,\text{nnz} \approx 10n\) floating-point operations for the matrix–vector product. Estimate the total work of CG and of Jacobi at \(m = 255\). (c) A 1 mm³ tissue block at 10 µm resolution: \(m = 100\) in 3D, \(n = 10^6\), seven non-zeros per row. CG’s iteration count depends on \(h\), not on the dimension. Estimate the iterations, the work, and the memory for \(A\) (12 bytes per non-zero) plus four vectors. Compare with the Cholesky factor of about \(6\times10^8\) non-zeros.
B4. A small step is not a small error. A Jacobi run on the chamber with \(\rho = 0.9988\) is stopped when the largest change in one step falls below \(10^{-6}\). (a) Assume each later step is \(\rho\) times the previous one. Sum the geometric series to estimate the distance from the true solution. (b) How many more sweeps would it take to make that error 1000 times smaller? (c) Why is a test on the residual safer? Why is it still not a test on the error?
B5. What a diagonal preconditioner can do. (a) \(A = \begin{pmatrix}100&1\\1&1\end{pmatrix}\). Compute its eigenvalues and \(\kappa(A)\). Then compute \(\kappa\) of \(D^{-1/2}AD^{-1/2}\), \(D = \text{diag}(100, 1)\). (For CG, preconditioning with \(D\) is equivalent to running CG on \(D^{-1/2}AD^{-1/2}\).) (b) For the chamber matrix, \(D = 4I\). What does Jacobi preconditioning change?
B6. CG by hand on three cells. The row of three cells of B2, now with a source in every cell: \(A = \begin{pmatrix}2&-1&0\\-1&2&-1\\0&-1&2\end{pmatrix}\), \(\mathbf{b} = (1, 1, 1)\). CG from \(\mathbf{x}_0 = \mathbf{0}\): \(\mathbf{r}_0 = \mathbf{p}_0 = \mathbf{b}\), and in every step \[\alpha_k = \frac{\mathbf{r}_k^T\mathbf{r}_k}{\mathbf{p}_k^TA\mathbf{p}_k},\quad \mathbf{x}_{k+1} = \mathbf{x}_k + \alpha_k\mathbf{p}_k,\quad \mathbf{r}_{k+1} = \mathbf{r}_k - \alpha_kA\mathbf{p}_k,\quad \beta_k = \frac{\mathbf{r}_{k+1}^T\mathbf{r}_{k+1}}{\mathbf{r}_k^T\mathbf{r}_k},\quad \mathbf{p}_{k+1} = \mathbf{r}_{k+1} + \beta_k\mathbf{p}_k.\] (a) Do two steps. Check that \(A\mathbf{x}_2 = \mathbf{b}\). (b) Check that \(\mathbf{r}_1 \perp \mathbf{r}_0\) and that \(\mathbf{p}_1^TA\mathbf{p}_0 = 0\) (the directions are \(A\)-conjugate). (c) Show that \(\mathbf{x}_1 \in \text{span}\{\mathbf{b}\}\) and \(\mathbf{x}_2 \in \text{span}\{\mathbf{b}, A\mathbf{b}\}\). Show that \(\mathbf{x}_1\) minimises \(f(\mathbf{x}) = \tfrac12\mathbf{x}^TA\mathbf{x} - \mathbf{b}^T\mathbf{x}\) on the line \(\mathbf{x} = t\mathbf{b}\), and compute \(f(\mathbf{x}_0)\), \(f(\mathbf{x}_1)\), \(f(\mathbf{x}_2)\). (d) CG finishes an \(n \times n\) SPD system in at most \(n\) steps (in exact arithmetic). Why did it need only two here? Use the eigenvectors of B2. How many steps would CG need for B1, and why?
B7. The \(\sqrt{\kappa}\) estimate. The CG error bound is \(2q^k\) with \(q = (\sqrt\kappa - 1)/(\sqrt\kappa + 1)\). (a) The chamber at \(m = 63\) has \(\kappa = 1659\). Compute \(q\) and the number of iterations \(k\) for which \(2q^k = 10^{-6}\). Compare with Jacobi’s \(\ln(10^{-6})/\ln(\cos\pi h)\) and with the 100 CG iterations measured in C3. (b) Show that \(\ln q \approx -2/\sqrt\kappa\) for large \(\kappa\), and hence \(k \approx \tfrac12\sqrt\kappa\,\ln(2/\text{tol})\) (fact 4). (c) In C4 the aggregate makes the diagonal range from 0.4 to 4. If that made \(\kappa\) ten times larger, by what factor should the CG count grow? (Measured: 100 → 197.) IC(0) needs 40 iterations instead of 100: if counts scale like \(\sqrt\kappa\), roughly what is \(\kappa(M^{-1}A)\)?
B8. Flow around a loop: when restarts stall. The most extreme nonsymmetric matrix is pure transport without diffusion: three compartments in a closed loop, each receiving from the previous one, \((A\mathbf{x})_i = x_{i-1}\) (with \(x_0 = x_3\)): \[A = \begin{pmatrix}0&0&1\\1&0&0\\0&1&0\end{pmatrix}, \qquad \mathbf{b} = (1, 0, 0).\] (a) Compute \(A\mathbf{b}\) and \(A^2\mathbf{b}\). Solve \(A\mathbf{x} = \mathbf{b}\). In which Krylov spaces \(\mathcal{K}_1, \mathcal{K}_2, \mathcal{K}_3\) does the solution lie? (b) GMRES picks \(\mathbf{x}_k \in \mathcal{K}_k\) with the smallest \(\|\mathbf{b} - A\mathbf{x}_k\|\). Show that for \(k = 1\) and \(k = 2\) the best choice is \(\mathbf{x}_k = \mathbf{0}\), with residual 1. What do GMRES(1) and GMRES(2) do after a restart? And full GMRES? (c) Compute \(\mathbf{v}^TA\mathbf{v}\) for \(\mathbf{v} = (1, 0, 0)\) and \(\mathbf{v} = (1, 1, 1)\). The symmetric part \((A + A^T)/2\) has eigenvalues \(1, -\tfrac12, -\tfrac12\). Connect to fact 8.
In code
C1. Jacobi and Gauss–Seidel as splittings. Write splitting(A, b, M, tol, maxit) that iterates \(\mathbf{x} \leftarrow \mathbf{x} + M^{-1}\mathbf{r}\) and returns the solution, the number of iterations and the history of relative residuals. Run it with \(M = D\) and \(M\) = lower triangle (R: tril; Python: scipy.sparse.tril and spsolve_triangular) for \(m = 7, 15, 31\). Compare with the predictions \(\ln(10^{-6})/\ln(\cos\pi h)\) and half of that. For \(m = 31\), print the ratio of the last few successive residuals.
C2. The spectral radius. For \(m = 7\), form \(T_J = I - D^{-1}A\) and \(T_{GS} = I - M^{-1}A\) as dense matrices and compute their spectral radii (R: eigen; Python: np.linalg.eigvals). Compare with fact 3 and with B2. Also compute \(\rho(T_J)\) for the \(2\times2\) matrix of B2(d).
C3. CG against grid size. Count CG iterations for \(m = 31, 63, 127, 255\). In R and Rust use your hand-written CG with a relative tolerance; in Python use scipy.sparse.linalg.cg with rtol=1e-6 and a callback that counts. Print \(\kappa = \cot^2(\pi h / 2)\) and \(\sqrt\kappa\) next to the counts, and the oxygen in the centre. Fit the slope of log(iterations) against \(\log(m+1)\).
C4. Preconditioning. The second chamber has a cell aggregate of radius 0.3 mm in the middle, where \(D\) is 10 times lower: \(A = -\nabla\cdot(D\nabla\,\cdot)\) with \(D\) evaluated between grid points. Use the starter code below. For \(m = 63\), on the uniform and the aggregate chamber, count iterations of plain CG, Jacobi-preconditioned CG and IC(0)-preconditioned CG. Print the smallest and largest diagonal entry. Check that \(LL^T \ne A\), and that \(L\) has as many non-zeros as the lower triangle of \(A\). (Python: pass the preconditioner to cg as M=, a LinearOperator whose matvec applies \(M^{-1}\).)
lapD <- function(m, Dfun) { # -div(D grad u), D on cell faces
h <- 1 / (m + 1); I <- Diagonal(m)
G1 <- bandSparse(m + 1, m, k = c(0, -1), diagonals = list(rep(1, m), rep(-1, m)))
Gx <- kronecker(I, G1); Gy <- kronecker(G1, I)
fx <- expand.grid(x = (1:(m + 1) - 0.5) * h, y = (1:m) * h) # x-faces
fy <- expand.grid(x = (1:m) * h, y = (1:(m + 1) - 0.5) * h) # y-faces
t(Gx) %*% Diagonal(x = Dfun(fx$x, fx$y)) %*% Gx +
t(Gy) %*% Diagonal(x = Dfun(fy$x, fy$y)) %*% Gy
}
aggregate_D <- function(x, y) ifelse((x - 0.5)^2 + (y - 0.5)^2 < 0.3^2, 0.1, 1)
ic0 <- function(A, m) { # incomplete Cholesky, five-point pattern
n <- nrow(A); d <- lw <- ls <- numeric(n); dA <- diag(A)
w <- c(0, diag(A[-1, -n])); s <- c(rep(0, m), diag(A[-(1:m), -((n - m + 1):n)]))
for (k in 1:n) {
if (k > 1) lw[k] <- w[k] / d[k - 1]
if (k > m) ls[k] <- s[k] / d[k - m]
d[k] <- sqrt(dA[k] - lw[k]^2 - ls[k]^2)
}
bandSparse(n, k = c(0, -1, -m), diagonals = list(d, lw[-1], ls[-(1:m)]))
}def lapD(m, Dfun): # -div(D grad u), D on cell faces
h = 1 / (m + 1); I = sparse.identity(m)
G1 = sparse.diags([np.ones(m), -np.ones(m)], [0, -1], shape=(m + 1, m))
Gx = sparse.kron(I, G1); Gy = sparse.kron(G1, I)
faces, nodes = (np.arange(1, m + 2) - 0.5) * h, np.arange(1, m + 1) * h
Dx = Dfun(*[g.ravel() for g in np.meshgrid(faces, nodes)]) # x-faces
Dy = Dfun(*[g.ravel() for g in np.meshgrid(nodes, faces)]) # y-faces
return (Gx.T @ sparse.diags(Dx) @ Gx + Gy.T @ sparse.diags(Dy) @ Gy).tocsr()
def aggregate_D(x, y):
return np.where((x - 0.5) ** 2 + (y - 0.5) ** 2 < 0.3 ** 2, 0.1, 1.0)
def ic0(A, m): # incomplete Cholesky, five-point pattern
n = A.shape[0]; d = np.zeros(n); lw = np.zeros(n); ls = np.zeros(n)
dA = A.diagonal(); w = A.diagonal(-1); s = A.diagonal(-m)
for k in range(n):
if k > 0: lw[k] = w[k - 1] / d[k - 1]
if k >= m: ls[k] = s[k - m] / d[k - m]
d[k] = np.sqrt(dA[k] - lw[k] ** 2 - ls[k] ** 2)
return sparse.diags([d, lw[1:], ls[m:]], [0, -1, -m], format="csr")// rust/examples/iterative_solvers_c4.rs — cargo run --release --example iterative_solvers_c4
// The starter functions are lap_d, aggregate_d, ic0 and ic_solve in that file
// (shown in full in the C4 solution). ic0 returns the diagonal d and the
// west / south entries lw, ls of L; ic_solve applies (L L^T)^{-1}.IC(0) for the five-point matrix: row \(k\) of \(L\) has entries only at \(k-1\) (west neighbour), \(k-m\) (south neighbour) and \(k\). Cholesky’s formulas then reduce to \(\ell_{k,k-1} = a_{k,k-1}/d_{k-1}\), \(\ell_{k,k-m} = a_{k,k-m}/d_{k-m}\), \(d_k = \sqrt{a_{kk} - \ell_{k,k-1}^2 - \ell_{k,k-m}^2}\); the products that would create fill-in are never formed.
C5. A nonsymmetric system: the perfused chamber. Medium flows through the chamber from left to right with Péclet number 50. With upwind differences (Flow plus diffusion), the row for point \((i, j)\) becomes \((4 + \text{Pe}\,h)u_{ij} - (1 + \text{Pe}\,h)u_{i-1,j} - u_{i+1,j} - u_{i,j-1} - u_{i,j+1} = \Phi h^2\). For \(m = 63\): (a) Build \(A\) and check whether it is symmetric. (b) Run plain CG for 50, 100 and 300 iterations and print the true relative residual. (c) Solve with GMRES (R: hand-written as on the slide; pracma::gmres exists but needs a dense matrix. Python: scipy.sparse.linalg.gmres with restart=300 and a callback with callback_type="pr_norm"). Report iterations and relative residual. In Python, also run with the default restart=20. (d) Run GMRES on the symmetric chamber and compare the count with C3.
C6. Restarted GMRES, and when it stalls. (a) Write gmres_k(A, b, k, tol, maxit): restarted GMRES(\(k\)). Each cycle runs the GMRES of C5 for at most \(k\) steps on the current residual and adds the correction to \(\mathbf{x}\); stop at the tolerance or after maxit = 3000 steps in total. (Python: scipy.sparse.linalg.gmres with restart=k and maxiter=3000 // k; maxiter counts cycles.) On the perfused chamber of C5, count the iterations for \(k = 10, 20, 50\) and 300 (full GMRES). (b) The signal chamber. Cells in the perfused chamber release a signalling molecule and, through positive feedback, release more where the signal is high (linearised: an extra source \(\sigma u\) with \(\sigma = 100\) in scaled units). The matrix becomes \(A - \sigma h^2 I\); the right-hand side stays the same. Repeat (a) and print the final relative residual. (c) For the smooth bump \(v_{ij} = \sin(\pi x_i)\sin(\pi y_j)\) compute \(\mathbf{v}^TA\mathbf{v}/\mathbf{v}^T\mathbf{v}\) for both matrices. What does the sign tell you (fact 8, B8)?
C7. BiCGSTAB. Write BiCGSTAB as on the slide (12 lines). R and Rust have no ready-made sparse BiCGSTAB in our setup (the CRAN package Rlinsolve has one but is not installed; pracma::gmres is for dense matrices), so hand-write it; in Python, also compare with scipy.sparse.linalg.bicgstab. On the perfused chamber with feedback \(\sigma = 0, 100, 200\), print the number of BiCGSTAB steps, the number of products with \(A\), the true relative residual of the result, and the iterations of full GMRES. Which method would you choose when \(n = 10^6\)?
Hints
Each row of \(A\) for \(m = 2\) has 4 on the diagonal and \(-1\) for the two neighbours inside the grid (point 1 touches 2 and 3, point 4 touches 2 and 3). So one update of point \(i\) is \(x_i = (1 + \text{sum of its two neighbours})/4\). Jacobi uses only old values; Gauss–Seidel overwrites \(x_1\) first and uses the new \(x_1\) when it updates \(x_2\) and \(x_3\).
Multiply \(T_J\) by the vector and see if you get a multiple of it. The eigenvalues of \(T_J\) add up to its trace, 0. A \(2\times2\) matrix \(\begin{pmatrix}0&a\\a&0\end{pmatrix}\) has eigenvalues \(\pm a\). In code, max(Mod(eigen(T)$values)) (R) or np.max(np.abs(np.linalg.eigvals(T))) (Python); use Mod/abs because a nonsymmetric \(T\) may have complex eigenvalues.
Doubling \(m + 1\) halves \(h\). Jacobi’s count grows like \(1/h^2\), CG’s like \(1/h\). At \(m = 255\), \(n = 65\,025\). For memory, 1 GB \(= 10^9\) bytes, and a vector of \(10^6\) doubles is 8 MB.
If the last step was \(s\) and every later step is \(\rho\) times the previous one, the remaining distance is \(s(\rho + \rho^2 + \dots) = s\rho/(1-\rho)\). To shrink the error by a factor \(F\) takes \(\ln F / (-\ln\rho)\) steps.
R: solve(M, r) with M <- Diagonal(x = diag(A)) or M <- tril(A) dispatches to a cheap diagonal or triangular solve; wrap it in as.vector. Python: for Jacobi use r / A.diagonal(); for Gauss–Seidel spsolve_triangular(sparse.tril(A, format="csr"), r, lower=True). Pass the solve as a function so one splitting serves both.
scipy calls callback(xk) once per CG iteration; keep a counter in a list (count = [0], count[0] += 1) so the inner function can change it. In scipy 1.12 and later the tolerance argument is rtol (formerly tol). info = 0 means converged, info > 0 means the iteration limit was reached. For gmres, callback_type="pr_norm" calls the callback once per inner iteration with the residual norm; maxiter counts restart cycles.
Jacobi: Minv = function(r) r / d with d <- diag(A). IC(0): with L <- ic0(A, m) and Lt <- t(L), apply \(M^{-1} = (LL^T)^{-1}\) by two triangular solves, solve(Lt, solve(L, r)). Python: LinearOperator(A.shape, matvec=lambda r: spsolve_triangular(Lt, spsolve_triangular(L, r, lower=True), lower=False)) with Lt = L.T.tocsr().
Add Pe * h times a lower bidiagonal matrix (1 on the diagonal, \(-1\) below it) to the 1D operator in \(x\) only, then combine with the \(y\) operator by kronecker as in lap2. Symmetric? isSymmetric(A) (R), abs(A - A.T).max() == 0 (Python). To see CG fail, compute the residual \(\|\mathbf{b} - A\mathbf{x}\|\) from the returned \(\mathbf{x}\), not CG’s internal residual.
Compute \(A\mathbf{p}_k\) first; everything else is dot products. \(A\mathbf{b} = (1, 0, 1)\). At the solution, \(f(\mathbf{x}^*) = -\tfrac12\mathbf{b}^T\mathbf{x}^*\). For (d): write \(\mathbf{b}\) in the eigenvectors of \(A\) (the same as those of \(T_J\) in B2) and look at its component along \((1, 0, -1)\); in B1, compute \(A\mathbf{b}\).
With \(\varepsilon = 1/\sqrt\kappa\), \(q = (1 - \varepsilon)/(1 + \varepsilon)\) and \(\ln(1 \pm \varepsilon) \approx \pm\varepsilon\). Solve \(2q^k = \text{tol}\) for \(k\).
\(A\) moves entry 1 to position 2, 2 to 3, 3 to 1. If \(\mathbf{x} \in \text{span}\{\mathbf{e}_1, \mathbf{e}_2\}\), where can \(A\mathbf{x}\) have non-zeros? Then \(\|\mathbf{b} - A\mathbf{x}\|^2 = 1 + \|A\mathbf{x}\|^2\). A restart throws the Krylov space away and starts from the same residual.
One cycle: r <- b - A x; g <- gmres(A, r, k, tol * norm(b) / norm(r)); x <- x + g$x. The tolerance is rescaled because C5’s gmres measures its residual relative to its own right-hand side, here \(\mathbf{r}\). The bump: v <- as.vector(outer(s, s)) with s <- sin(pi * (1:m) * h) (Python: np.outer(s, s).ravel(); the ordering does not matter for a symmetric bump); then sum(v * (A %*% v)) / sum(v^2).
Each step has two products with \(A\) (v and t). Return NA (Python None) when maxit is reached, and compute the true residual \(\|\mathbf{b} - A\mathbf{x}\|/\|\mathbf{b}\|\) from the returned \(\mathbf{x}\). scipy’s bicgstab calls callback(xk) once per step and also tests the residual halfway through a step, so its count can differ by one or two.
Solutions
B1. (a) \(A = \begin{pmatrix}4&-1&-1&0\\-1&4&0&-1\\-1&0&4&-1\\0&-1&-1&4\end{pmatrix}\). Each row: \(4(0.5) - 0.5 - 0.5 = 1\). ✓ (b) By symmetry all four values stay equal, \(x \leftarrow (1 + 2x)/4\): \(0 \to 0.25 \to 0.375 \to 0.4375\). Errors \(0.5, 0.25, 0.125, 0.0625\): the factor is \(\tfrac12\) per step. (c) Sweep 1: \(x_1 = 1/4 = 0.25\), \(x_2 = (1 + 0.25 + 0)/4 = 0.3125\), \(x_3 = 0.3125\), \(x_4 = (1 + 0.3125 + 0.3125)/4 = 0.40625\). Sweep 2: \(x_1 = (1 + 0.625)/4 = 0.40625\), \(x_2 = x_3 = (1 + 0.40625 + 0.40625)/4 = 0.453125\), \(x_4 = (1 + 0.90625)/4 = 0.4765625\). Errors of point 4: \(0.09375\), then \(0.0234375\): ratio \(\tfrac14\). (d) \(\cos(\pi/3) = 0.5 = \rho_J\) and \(\cos^2(\pi/3) = 0.25 = \rho_{GS}\): one Gauss–Seidel sweep is worth two Jacobi steps.
B2. (a) \(D = 2I\), so \(T_J = \begin{pmatrix}0&\frac12&0\\\frac12&0&\frac12\\0&\frac12&0\end{pmatrix}\). \(T_J(1, \sqrt2, 1)^T = (\tfrac{\sqrt2}{2}, 1, \tfrac{\sqrt2}{2})^T = \tfrac{1}{\sqrt2}(1, \sqrt2, 1)^T\): eigenvalue \(1/\sqrt2\). \((1, 0, -1)\) gives 0, \((1, -\sqrt2, 1)\) gives \(-1/\sqrt2\). Sum 0 = trace. ✓ (b) \(\rho = 1/\sqrt2 = 0.7071 = \cos(\pi/4)\). Steps per digit: \(\ln 10 / (-\ln 0.7071) = 2.3026 / 0.3466 = 6.6\). (c) \(-\ln(0.998795) = 0.0012057\), so \(2.3026/0.0012057 = 1910\) sweeps per digit, about \(11\,460\) for six (the measured count is 11 302). Gauss–Seidel: \(\rho^2\), half as many: about 955 per digit, \(5730\) for six (measured 5652). (d) \(\begin{pmatrix}1&2\\2&1\end{pmatrix}\): \(T_J = \begin{pmatrix}0&-2\\-2&0\end{pmatrix}\), eigenvalues \(\pm2\), \(\rho = 2 > 1\): the error doubles each step. \(\begin{pmatrix}2&1\\1&2\end{pmatrix}\): \(T_J = \begin{pmatrix}0&-\frac12\\-\frac12&0\end{pmatrix}\), \(\rho = \tfrac12\). The second matrix is diagonally dominant, the first is not.
B3. (a) \(m = 127\): CG \(\approx 200\), Jacobi \(\approx 45\,200\). \(m = 255\): CG \(\approx 400\), Jacobi \(\approx 181\,000\). (Measured: CG 203 and 409; Jacobi 45 193 at \(m = 127\).) (b) \(10n = 6.5\times10^5\) operations per iteration. CG: \(400 \times 6.5\times10^5 \approx 2.6\times10^8\) (a fraction of a second compiled). Jacobi: \(181\,000 \times 6.5\times10^5 \approx 1.2\times10^{11}\), about 500 times more. (c) \(h = 1/101\), between the 2D runs at \(m = 63\) and \(127\): about 200 iterations (a run in R gives 203). Work: \(200 \times 2 \times 7\times10^6 \approx 3\times10^9\) operations, seconds. Memory: \(7\times10^6 \times 12\) bytes \(= 84\) MB for \(A\), plus \(4 \times 8\) MB for vectors: about 120 MB. The Cholesky factor: \(6\times10^8 \times 12 \approx 7\) GB, roughly 60 times more.
B4. (a) \(10^{-6} \times 0.9988 / 0.0012 \approx 8.3\times10^{-4}\): the iterate is still about \(10^{-3}\) away, 830 times more than the step. (The lecture’s run: error \(8.29\times10^{-4}\).) (b) \(\ln 1000 / (-\ln 0.9988) = 6.908/0.0012007 \approx 5750\) more sweeps. (c) The residual measures how well the equations are satisfied, independently of how fast the method moves; a slow method has small steps but not a small residual. Still, relative error \(\le \kappa(A) \times\) relative residual (Pivoting, norms and conditioning), and here \(\kappa \approx 1659\), so a residual of \(10^{-6}\) guarantees only about \(2\times10^{-3}\) relative error in the worst case.
B5. (a) Trace 101, determinant 99: \(\lambda = (101 \pm \sqrt{101^2 - 4\cdot99})/2 = (101 \pm 99.02)/2\), so \(100.01\) and \(0.990\), \(\kappa \approx 101\). \(D^{-1/2}AD^{-1/2} = \begin{pmatrix}1&0.1\\0.1&1\end{pmatrix}\), eigenvalues \(1.1\) and \(0.9\), \(\kappa = 1.22\). The diagonal scaling removes the bad scaling of the first unknown. (b) \(D^{-1/2}AD^{-1/2} = A/4\): same eigenvectors, same \(\kappa\). Nothing changes; CG takes exactly the same steps (C4 confirms).
B6. (a) Step 1: \(A\mathbf{p}_0 = (1, 0, 1)\), \(\mathbf{r}_0^T\mathbf{r}_0 = 3\), \(\mathbf{p}_0^TA\mathbf{p}_0 = 2\), so \(\alpha_0 = \tfrac32\), \(\mathbf{x}_1 = (1.5, 1.5, 1.5)\), \(\mathbf{r}_1 = (1, 1, 1) - 1.5(1, 0, 1) = (-0.5, 1, -0.5)\). \(\beta_0 = 1.5/3 = 0.5\), \(\mathbf{p}_1 = (-0.5, 1, -0.5) + 0.5(1, 1, 1) = (0, 1.5, 0)\). Step 2: \(A\mathbf{p}_1 = (-1.5, 3, -1.5)\), \(\mathbf{p}_1^TA\mathbf{p}_1 = 4.5\), \(\alpha_1 = 1.5/4.5 = \tfrac13\), \(\mathbf{x}_2 = (1.5, 2, 1.5)\), \(\mathbf{r}_2 = (-0.5, 1, -0.5) - \tfrac13(-1.5, 3, -1.5) = \mathbf{0}\). Check: \(A\mathbf{x}_2 = (3 - 2,\ -1.5 + 4 - 1.5,\ -2 + 3) = (1, 1, 1)\) ✓. (b) \(\mathbf{r}_1^T\mathbf{r}_0 = -0.5 + 1 - 0.5 = 0\) ✓. \(\mathbf{p}_1^TA\mathbf{p}_0 = (0, 1.5, 0)\cdot(1, 0, 1) = 0\) ✓. (c) \(\mathbf{x}_1 = 1.5\,\mathbf{b}\). \(\mathbf{x}_2 = 2\mathbf{b} - 0.5A\mathbf{b} = (2, 2, 2) - (0.5, 0, 0.5) = (1.5, 2, 1.5)\) ✓. On the line, \(f(t\mathbf{b}) = \tfrac12t^2\,\mathbf{b}^TA\mathbf{b} - t\,\mathbf{b}^T\mathbf{b} = t^2 - 3t\), smallest at \(t = 1.5\): that is \(\mathbf{x}_1\). \(f(\mathbf{x}_0) = 0\), \(f(\mathbf{x}_1) = 2.25 - 4.5 = -2.25\), \(f(\mathbf{x}_2) = -\tfrac12\mathbf{b}^T\mathbf{x}_2 = -2.5\), the minimum. Each step minimises \(f\) over a larger space. (d) \(\mathbf{b} = (1, 1, 1)\) is orthogonal to the eigenvector \((1, 0, -1)\), so it is a combination of only two eigenvectors, \((1, \sqrt2, 1)\) and \((1, -\sqrt2, 1)\). Then \(\mathcal{K}_2\) already contains \(A^{-1}\mathbf{b}\), and CG, which finds the best point of \(\mathcal{K}_k\), finds it exactly. In general CG needs at most as many steps as there are distinct eigenvalues among the components of \(\mathbf{b}\). In B1, \(A\mathbf{b} = 2\mathbf{b}\): \(\mathbf{b}\) is an eigenvector, and CG finishes in one step (\(\alpha_0 = \tfrac12\), \(\mathbf{x}_1 = (0.5, 0.5, 0.5, 0.5)\)), while Jacobi only halves the error in every step.
B7. (a) \(\sqrt{1659} = 40.73\), \(q = 39.73/41.73 = 0.95207\), \(\ln q = -0.04911\). \(k = \ln(2\times10^6)/0.04911 = 14.51/0.04911 \approx 295\). Jacobi: \(\ln(10^{-6})/\ln\cos(\pi/64) \approx 11\,460\). The bound is three times the measured 100, but forty times better than Jacobi; and it has the right scaling. (b) \(\ln q = \ln(1 - \varepsilon) - \ln(1 + \varepsilon) \approx -2\varepsilon = -2/\sqrt\kappa\). From \(2q^k = \text{tol}\): \(k = \ln(2/\text{tol}) / (-\ln q) \approx \tfrac12\sqrt\kappa\ln(2/\text{tol})\); here \(\tfrac12 \times 40.73 \times 14.51 = 295.5\), the same as (a). (c) \(\sqrt{10} = 3.2\): about 320 instead of 100. Measured 197: the bound is a worst case, and only a part of the spectrum moves (the aggregate covers a quarter of the chamber). IC(0): \(100/40 = 2.5\), so \(\kappa\) is about \(2.5^2 = 6.25\) times smaller, \(\kappa(M^{-1}A) \approx 1659/6.25 \approx 270\). (A rough estimate: CG counts also depend on how the eigenvalues are spread, not only on \(\kappa\).)
B8. (a) \(A\mathbf{b} = (0, 1, 0)\), \(A^2\mathbf{b} = (0, 0, 1)\). \(\mathbf{x} = (0, 0, 1)\): \(A\mathbf{x}\) is the third column, \((1, 0, 0)\) ✓. \(\mathcal{K}_1 = \text{span}\{\mathbf{e}_1\}\) and \(\mathcal{K}_2 = \text{span}\{\mathbf{e}_1, \mathbf{e}_2\}\) do not contain \(\mathbf{e}_3\); \(\mathcal{K}_3\) is all of \(\mathbb{R}^3\) and does. (b) For \(\mathbf{x} \in \text{span}\{\mathbf{e}_1, \mathbf{e}_2\}\), \(A\mathbf{x} \in \text{span}\{\mathbf{e}_2, \mathbf{e}_3\}\), orthogonal to \(\mathbf{b} = \mathbf{e}_1\), so \(\|\mathbf{b} - A\mathbf{x}\|^2 = 1 + \|A\mathbf{x}\|^2 \ge 1\), smallest for \(\mathbf{x} = \mathbf{0}\). So after one or two steps GMRES has made no progress at all; a restart begins again from \(\mathbf{x} = \mathbf{0}\) with the same residual \(\mathbf{e}_1\), and GMRES(1) and GMRES(2) stall forever. Full GMRES finds the exact solution at step 3. (c) \(\mathbf{e}_1^TA\mathbf{e}_1 = a_{11} = 0\); \((1, 1, 1)A(1, 1, 1)^T = 3\). The symmetric part is indefinite, so fact 8’s guarantee does not hold, and (b) shows it failing. A GMRES(1) step from residual \(\mathbf{r}\) moves by \(t = \mathbf{r}^TA\mathbf{r}/\|A\mathbf{r}\|^2\), which is 0 here. Diffusion makes \(\mathbf{v}^TA\mathbf{v}\) positive; flow alone does not, and anything that subtracts from the diagonal (C6) can make it negative.
C1.
# lap1(), lap2(), chamber_rhs() as in the Background
splitting <- function(A, b, M, tol = 1e-6, maxit = 1e5) {
x <- numeric(length(b)); nb <- sqrt(sum(b^2)); res <- numeric(0)
for (it in 0:maxit) {
r <- b - (A %*% x)[, 1]
res <- c(res, sqrt(sum(r^2)) / nb)
if (res[it + 1] < tol) break
x <- x + as.vector(solve(M, r)) # x <- x + M^{-1} r
}
list(x = x, it = it, res = res)
}
for (m in c(7, 15, 31)) {
A <- lap2(m); b <- chamber_rhs(m); h <- 1 / (m + 1)
jac <- splitting(A, b, Diagonal(x = diag(A)))
gs <- splitting(A, b, tril(A))
pred <- log(1e-6) / log(cos(pi * h))
cat(m, jac$it, gs$it, round(pred), round(pred / 2), "\n")
}
r <- jac$res; round(tail(r, 3) / head(tail(r, 4), 3), 5) # residual ratios, m = 31
cos(pi / 32)
# Output:
# 7 174 88 174 87
# 15 705 354 712 356
# 31 2825 1414 2862 1431
# [1] 0.99518 0.99518 0.99518
# [1] 0.9951847# imports, lap1(), lap2(), chamber_rhs() as in the Background
from scipy.sparse.linalg import spsolve_triangular
def splitting(A, b, Msolve, tol=1e-6, maxit=100000):
x = np.zeros(len(b)); nb = np.linalg.norm(b); res = []
for it in range(maxit + 1):
r = b - A @ x
res.append(np.linalg.norm(r) / nb)
if res[-1] < tol:
break
x = x + Msolve(r) # x <- x + M^{-1} r
return x, it, np.array(res)
for m in [7, 15, 31]:
A = lap2(m); b = chamber_rhs(m); h = 1 / (m + 1)
d = A.diagonal(); L = sparse.tril(A, format="csr")
xj, itj, rj = splitting(A, b, lambda r: r / d)
xg, itg, rg = splitting(A, b, lambda r: spsolve_triangular(L, r, lower=True))
pred = np.log(1e-6) / np.log(np.cos(np.pi * h))
print(m, itj, itg, round(pred), round(pred / 2))
print(np.round(rj[-3:] / rj[-4:-1], 5)) # residual ratios, m = 31
print(np.cos(np.pi / 32))
# Output:
# 7 174 88 174 87
# 15 705 354 712 356
# 31 2825 1414 2862 1431
# [0.99518 0.99518 0.99518]
# 0.9951847266721969// rust/examples/iterative_solvers_c1.rs — cargo run --release --example iterative_solvers_c1
// C1: Jacobi and Gauss-Seidel as splittings x <- x + M^{-1} (b - A x).
// Gauss-Seidel's M = lower triangle of A, solved by forward substitution.
include!("iterative_solvers_shared/defs.rs");
fn splitting(a: &CsMat<f64>, b: &[f64], msolve: impl Fn(&[f64]) -> Vec<f64>,
tol: f64, maxit: usize) -> (Vec<f64>, usize, Vec<f64>) {
let mut x = vec![0.0; b.len()];
let (nb, mut res) = (norm(b), Vec::new());
let mut it = 0;
loop {
let ax = matvec(a, &x);
let r: Vec<f64> = b.iter().zip(&ax).map(|(p, q)| p - q).collect();
res.push(norm(&r) / nb);
if *res.last().unwrap() < tol || it == maxit { break; }
let dx = msolve(&r);
for i in 0..x.len() { x[i] += dx[i]; }
it += 1;
}
(x, it, res)
}
fn forward_solve(a: &CsMat<f64>, r: &[f64]) -> Vec<f64> { // (lower triangle of A) y = r
let mut y = vec![0.0; r.len()];
for (i, row) in a.outer_iterator().enumerate() {
let (mut s, mut d) = (r[i], 0.0);
for (j, v) in row.iter() {
if j < i { s -= v * y[j]; } else if j == i { d = *v; }
}
y[i] = s / d;
}
y
}
fn main() {
let mut rj = Vec::new();
for m in [7, 15, 31] {
let (a, b) = (lap2(m), chamber_rhs(m, 12.0));
let h = 1.0 / (m + 1) as f64;
let d = diagonal(&a);
let (_, itj, r) = splitting(&a, &b, |r| r.iter().zip(&d).map(|(p, q)| p / q).collect(), 1e-6, 100_000);
let (_, itg, _) = splitting(&a, &b, |r| forward_solve(&a, r), 1e-6, 100_000);
let pred = 1e-6_f64.ln() / (std::f64::consts::PI * h).cos().ln();
println!("{} {} {} {} {}", m, itj, itg, pred.round(), (pred / 2.0).round());
rj = r;
}
let k = rj.len();
let ratios: Vec<f64> = (k - 3..k).map(|i| (rj[i] / rj[i - 1] * 1e5).round() / 1e5).collect();
println!("{:?}", ratios); // residual ratios, m = 31
println!("{}", (std::f64::consts::PI / 32.0).cos());
}
// Output:
// 7 174 88 174 87
// 15 705 354 712 356
// 31 2825 1414 2862 1431
// [0.99518, 0.99518, 0.99518]
// 0.9951847266721969Jacobi needs \(4\times\) more sweeps each time \(m + 1\) doubles, Gauss–Seidel exactly half of Jacobi, and the prediction from \(\rho\) is within 2 %. The residual ratio settles at \(0.99518 = \cos(\pi/32)\): the iteration behaves like power iteration on \(T\) (Power iteration and friends), and the residual ratio is the spectral radius.
C2.
# lap1(), lap2(), chamber_rhs() as in the Background
m <- 7; A <- as.matrix(lap2(m)); I <- diag(m^2)
TJ <- I - diag(1 / diag(A)) %*% A # Jacobi iteration matrix
TGS <- I - solve(A * lower.tri(A, diag = TRUE), A) # Gauss-Seidel
rho <- function(T) max(Mod(eigen(T, only.values = TRUE)$values))
c(rho(TJ), cos(pi / 8), rho(TGS), cos(pi / 8)^2)
log(10) / -log(c(rho(TJ), rho(TGS))) # iterations per digit
rho(diag(2) - matrix(c(1, 2, 2, 1), 2)) # the 2 x 2 failure (D = I)
# Output:
# [1] 0.9238795 0.9238795 0.8535534 0.8535534
# [1] 29.08274 14.54137
# [1] 2# imports, lap1(), lap2(), chamber_rhs() as in the Background
m = 7; A = lap2(m).toarray(); I = np.eye(m * m)
TJ = I - np.diag(1 / np.diag(A)) @ A # Jacobi iteration matrix
TGS = I - np.linalg.solve(np.tril(A), A) # Gauss-Seidel
rho = lambda T: np.max(np.abs(np.linalg.eigvals(T)))
print(rho(TJ), np.cos(np.pi / 8), rho(TGS), np.cos(np.pi / 8) ** 2)
print(np.log(10) / -np.log([rho(TJ), rho(TGS)])) # iterations per digit
print(rho(np.eye(2) - np.array([[1.0, 2], [2, 1]]))) # the 2 x 2 failure (D = I)
# Output:
# 0.9238795325112874 0.9238795325112867 0.8535533905932753 0.8535533905932737
# [29.08274132 14.54137066]
# 2.0000000000000004// rust/examples/iterative_solvers_c2.rs — cargo run --example iterative_solvers_c2
// C2: spectral radius of the Jacobi and Gauss-Seidel iteration matrices (dense, nalgebra).
use nalgebra::DMatrix;
use std::f64::consts::PI;
fn lap2_dense(m: usize) -> DMatrix<f64> {
let n = m * m;
DMatrix::from_fn(n, n, |k, l| {
let (i, j, p, q) = (k % m, k / m, l % m, l / m);
if k == l { 4.0 }
else if (i == p && j.abs_diff(q) == 1) || (j == q && i.abs_diff(p) == 1) { -1.0 }
else { 0.0 }
})
}
fn rho(t: &DMatrix<f64>) -> f64 { // largest |eigenvalue|
t.complex_eigenvalues().iter().map(|z| z.norm()).fold(0.0, f64::max)
}
fn main() {
let m = 7;
let a = lap2_dense(m);
let id = DMatrix::<f64>::identity(m * m, m * m);
let tj = &id - &a / 4.0; // I - D^{-1} A, D = 4 I
let low = a.lower_triangle();
let tgs = &id - low.solve_lower_triangular(&a).unwrap();
let (rj, rg) = (rho(&tj), rho(&tgs));
println!("{} {} {} {}", rj, (PI / 8.0).cos(), rg, (PI / 8.0).cos().powi(2));
println!("{} {}", 10f64.ln() / -rj.ln(), 10f64.ln() / -rg.ln()); // iterations per digit
let b2 = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 2.0, 1.0]);
println!("{}", rho(&(DMatrix::<f64>::identity(2, 2) - b2))); // the 2 x 2 failure
}
// Output:
// 0.9238795325112974 0.9238795325112867 0.853553390593282 0.8535533905932737
// 29.08274132120184 14.541370660599684
// 1.9999999999999996Both spectral radii match fact 3 to all printed digits (Rust differs in the 14th digit). Gauss–Seidel needs 14.5 sweeps per digit at \(m = 7\), Jacobi 29. The \(2\times2\) matrix has \(\rho = 2\).
C3.
# lap1(), lap2(), chamber_rhs() as in the Background
cg <- function(A, b, tol = 1e-6, maxit = 1e4) {
x <- numeric(length(b)); r <- b; p <- r; rr <- sum(r^2); nb <- sqrt(rr)
for (it in 1:maxit) {
Ap <- (A %*% p)[, 1]; alpha <- rr / sum(p * Ap)
x <- x + alpha * p; r <- r - alpha * Ap
rr_new <- sum(r^2)
if (sqrt(rr_new) < tol * nb) return(list(x = x, it = it))
p <- r + (rr_new / rr) * p; rr <- rr_new
}
list(x = x, it = NA)
}
ms <- c(31, 63, 127, 255); its <- numeric(0)
for (m in ms) {
A <- lap2(m); b <- chamber_rhs(m)
t <- system.time(out <- cg(A, b))[3]
its <- c(its, out$it)
kappa <- 1 / tan(pi / (2 * (m + 1)))^2 # cond(A) = cot^2(pi h / 2)
cat(m, out$it, round(kappa), round(sqrt(kappa)), 1 - out$x[(m^2 + 1) / 2], "\n")
}
coef(lm(log(its) ~ log(ms + 1)))[2] # slope: iterations ~ (1/h)^slope
# Output:
# 31 50 414 20 0.1166232
# 63 100 1659 41 0.1161138
# 127 203 6640 81 0.1159863
# 255 409 26560 163 0.1159544
# log(ms + 1)
# 1.011778 # imports, lap1(), lap2(), chamber_rhs() as in the Background
from scipy.sparse.linalg import cg
ms = [31, 63, 127, 255]; its = []
for m in ms:
A = lap2(m); b = chamber_rhs(m)
count = [0]
def callback(xk): # called once per iteration
count[0] += 1
x, info = cg(A, b, rtol=1e-6, callback=callback) # info = 0: converged
its.append(count[0])
kappa = 1 / np.tan(np.pi / (2 * (m + 1))) ** 2 # cond(A) = cot^2(pi h / 2)
print(m, count[0], round(kappa), round(np.sqrt(kappa)), 1 - x[(m * m - 1) // 2], info)
print(np.polyfit(np.log(np.array(ms) + 1), np.log(its), 1)[0]) # slope
# Output:
# 31 50 414 20 0.11662316507538717 0
# 63 100 1659 41 0.11611379757785456 0
# 127 203 6640 81 0.11598628740221895 0
# 255 409 26560 163 0.11595439924028783 0
# 1.0117782256911525// rust/examples/iterative_solvers_c3.rs — cargo run --release --example iterative_solvers_c3
// C3: hand-written CG (pcg with no preconditioner, in the shared defs) on sprs:
// iterations vs grid size, and the slope on log-log axes.
include!("iterative_solvers_shared/defs.rs");
use std::f64::consts::PI;
fn main() {
let ms = [31usize, 63, 127, 255];
let mut its = Vec::new();
for &m in &ms {
let (a, b) = (lap2(m), chamber_rhs(m, 12.0));
let (x, it) = pcg(&a, &b, |r| r.to_vec(), 1e-6, 10_000);
let it = it.unwrap();
its.push(it as f64);
let kappa = 1.0 / (PI / (2.0 * (m + 1) as f64)).tan().powi(2); // cot^2(pi h / 2)
println!("{} {} {} {} {}", m, it, kappa.round(), kappa.sqrt().round(), 1.0 - x[(m * m - 1) / 2]);
}
// least-squares slope of log(its) against log(m + 1)
let lx: Vec<f64> = ms.iter().map(|&m| ((m + 1) as f64).ln()).collect();
let ly: Vec<f64> = its.iter().map(|v| v.ln()).collect();
let (mx, my) = (lx.iter().sum::<f64>() / 4.0, ly.iter().sum::<f64>() / 4.0);
let sxy: f64 = lx.iter().zip(&ly).map(|(x, y)| (x - mx) * (y - my)).sum();
let sxx: f64 = lx.iter().map(|x| (x - mx).powi(2)).sum();
println!("{}", sxy / sxx);
}
// Output:
// 31 50 414 20 0.11662316507539405
// 63 100 1659 41 0.1161137975778912
// 127 203 6640 81 0.11598628740222672
// 255 409 26560 163 0.11595439924035622
// 1.0117782256911527The counts double with \(m + 1\) (slope 1.01), and are about \(2.5\sqrt\kappa\); the bound of fact 4, \(\tfrac12\sqrt\kappa\,\ln(2\times10^6) \approx 7.3\sqrt\kappa\), is pessimistic but has the right slope. scipy’s cg performs the same iterations as the hand-written version. The oxygen in the centre converges to about 0.1160 as the grid is refined (the discretisation error is \(O(h^2)\), a change of \(3\times10^{-5}\) from \(m = 127\) to 255).
C4.
# lap1(), lap2(), chamber_rhs() as in the Background
lapD <- function(m, Dfun) { # -div(D grad u), D on cell faces
h <- 1 / (m + 1); I <- Diagonal(m)
G1 <- bandSparse(m + 1, m, k = c(0, -1), diagonals = list(rep(1, m), rep(-1, m)))
Gx <- kronecker(I, G1); Gy <- kronecker(G1, I)
fx <- expand.grid(x = (1:(m + 1) - 0.5) * h, y = (1:m) * h) # x-faces
fy <- expand.grid(x = (1:m) * h, y = (1:(m + 1) - 0.5) * h) # y-faces
t(Gx) %*% Diagonal(x = Dfun(fx$x, fx$y)) %*% Gx +
t(Gy) %*% Diagonal(x = Dfun(fy$x, fy$y)) %*% Gy
}
aggregate_D <- function(x, y) ifelse((x - 0.5)^2 + (y - 0.5)^2 < 0.3^2, 0.1, 1)
ic0 <- function(A, m) { # incomplete Cholesky, five-point pattern
n <- nrow(A); d <- lw <- ls <- numeric(n); dA <- diag(A)
w <- c(0, diag(A[-1, -n])); s <- c(rep(0, m), diag(A[-(1:m), -((n - m + 1):n)]))
for (k in 1:n) {
if (k > 1) lw[k] <- w[k] / d[k - 1]
if (k > m) ls[k] <- s[k] / d[k - m]
d[k] <- sqrt(dA[k] - lw[k]^2 - ls[k]^2)
}
bandSparse(n, k = c(0, -1, -m), diagonals = list(d, lw[-1], ls[-(1:m)]))
}
pcg <- function(A, b, Minv = function(r) r, tol = 1e-6, maxit = 1e4) {
x <- numeric(length(b)); r <- b; z <- Minv(r); p <- z; rz <- sum(r * z)
nb <- sqrt(sum(b^2))
for (it in 1:maxit) {
Ap <- (A %*% p)[, 1]; alpha <- rz / sum(p * Ap)
x <- x + alpha * p; r <- r - alpha * Ap
if (sqrt(sum(r^2)) < tol * nb) return(list(x = x, it = it))
z <- Minv(r); rz_new <- sum(r * z)
p <- z + (rz_new / rz) * p; rz <- rz_new
}
list(x = x, it = NA)
}
m <- 63; b <- chamber_rhs(m)
for (A in list(lap2(m), lapD(m, aggregate_D))) {
d <- diag(A); L <- ic0(A, m); Lt <- t(L)
cat(range(d), pcg(A, b)$it, pcg(A, b, function(r) r / d)$it,
pcg(A, b, function(r) as.vector(solve(Lt, solve(L, r))))$it, "\n")
}
A <- lapD(m, aggregate_D); L <- ic0(A, m)
nnzero(L); max(abs(L %*% t(L) - A)) # same pattern as A, but not exact
# Output:
# 4 4 100 100 40
# 0.4 4 197 103 49
# [1] 11781
# [1] 0.4669796# imports, lap1(), lap2(), chamber_rhs() as in the Background
from scipy.sparse.linalg import cg, LinearOperator, spsolve_triangular
def lapD(m, Dfun): # -div(D grad u), D on cell faces
h = 1 / (m + 1); I = sparse.identity(m)
G1 = sparse.diags([np.ones(m), -np.ones(m)], [0, -1], shape=(m + 1, m))
Gx = sparse.kron(I, G1); Gy = sparse.kron(G1, I)
faces, nodes = (np.arange(1, m + 2) - 0.5) * h, np.arange(1, m + 1) * h
Dx = Dfun(*[g.ravel() for g in np.meshgrid(faces, nodes)]) # x-faces
Dy = Dfun(*[g.ravel() for g in np.meshgrid(nodes, faces)]) # y-faces
return (Gx.T @ sparse.diags(Dx) @ Gx + Gy.T @ sparse.diags(Dy) @ Gy).tocsr()
def aggregate_D(x, y):
return np.where((x - 0.5) ** 2 + (y - 0.5) ** 2 < 0.3 ** 2, 0.1, 1.0)
def ic0(A, m): # incomplete Cholesky, five-point pattern
n = A.shape[0]; d = np.zeros(n); lw = np.zeros(n); ls = np.zeros(n)
dA = A.diagonal(); w = A.diagonal(-1); s = A.diagonal(-m)
for k in range(n):
if k > 0: lw[k] = w[k - 1] / d[k - 1]
if k >= m: ls[k] = s[k - m] / d[k - m]
d[k] = np.sqrt(dA[k] - lw[k] ** 2 - ls[k] ** 2)
return sparse.diags([d, lw[1:], ls[m:]], [0, -1, -m], format="csr")
def iterations(A, b, M=None):
count = [0]
def callback(xk): count[0] += 1
x, info = cg(A, b, rtol=1e-6, M=M, callback=callback)
return count[0]
m = 63; b = chamber_rhs(m)
for A in [lap2(m), lapD(m, aggregate_D)]:
d = A.diagonal(); L = ic0(A, m); Lt = L.T.tocsr()
M_jac = LinearOperator(A.shape, matvec=lambda r: r / d)
M_ic = LinearOperator(A.shape, matvec=lambda r: spsolve_triangular(
Lt, spsolve_triangular(L, r, lower=True), lower=False))
print(d.min(), d.max(), iterations(A, b), iterations(A, b, M_jac), iterations(A, b, M_ic))
A = lapD(m, aggregate_D); L = ic0(A, m)
print(L.nnz, abs(L @ L.T - A).max()) # same pattern as A, but not exact
# Output:
# 4.0 4.0 100 100 40
# 0.4 4.0 197 103 49
# 11781 0.4669795587343442// rust/examples/iterative_solvers_c4.rs — cargo run --release --example iterative_solvers_c4
// C4: CG, Jacobi-preconditioned CG and IC(0)-preconditioned CG on the uniform
// chamber and on the chamber with a cell aggregate (D = 0.1 inside).
include!("iterative_solvers_shared/defs.rs");
fn lap_d(m: usize, dfun: impl Fn(f64, f64) -> f64) -> CsMat<f64> { // -div(D grad u)
let (n, h) = (m * m, 1.0 / (m + 1) as f64);
let mut t = TriMat::new((n, n));
for j in 0..m {
for i in 0..m {
let k = i + m * j;
let (x, y) = ((i + 1) as f64 * h, (j + 1) as f64 * h); // node
let (xw, xe) = ((i as f64 + 0.5) * h, (i as f64 + 1.5) * h); // its faces
let (ys, yn) = ((j as f64 + 0.5) * h, (j as f64 + 1.5) * h);
let faces = [(dfun(xw, y), i > 0, k.wrapping_sub(1)),
(dfun(xe, y), i < m - 1, k + 1),
(dfun(x, ys), j > 0, k.wrapping_sub(m)),
(dfun(x, yn), j < m - 1, k + m)];
for (d, inside, l) in faces {
t.add_triplet(k, k, d); // every face adds D to the diagonal
if inside { t.add_triplet(k, l, -d); }
}
}
}
t.to_csr()
}
fn aggregate_d(x: f64, y: f64) -> f64 {
if (x - 0.5).powi(2) + (y - 0.5).powi(2) < 0.3f64.powi(2) { 0.1 } else { 1.0 }
}
// IC(0) for the five-point pattern: diagonal d, west and south entries of L
fn ic0(a: &CsMat<f64>, m: usize) -> (Vec<f64>, Vec<f64>, Vec<f64>) {
let n = a.rows();
let (mut d, mut lw, mut ls) = (vec![0.0; n], vec![0.0; n], vec![0.0; n]);
let g = |i: usize, j: usize| *a.get(i, j).unwrap_or(&0.0);
for k in 0..n {
if k > 0 { lw[k] = g(k, k - 1) / d[k - 1]; }
if k >= m { ls[k] = g(k, k - m) / d[k - m]; }
d[k] = (g(k, k) - lw[k].powi(2) - ls[k].powi(2)).sqrt();
}
(d, lw, ls)
}
// z = (L L^T)^{-1} r by a forward and a backward substitution
fn ic_solve(l: &(Vec<f64>, Vec<f64>, Vec<f64>), m: usize, r: &[f64]) -> Vec<f64> {
let (d, lw, ls) = l;
let n = r.len();
let mut y = r.to_vec();
for k in 0..n {
if k > 0 { y[k] -= lw[k] * y[k - 1]; }
if k >= m { y[k] -= ls[k] * y[k - m]; }
y[k] /= d[k];
}
for k in (0..n).rev() {
if k + 1 < n { y[k] -= lw[k + 1] * y[k + 1]; }
if k + m < n { y[k] -= ls[k + m] * y[k + m]; }
y[k] /= d[k];
}
y
}
fn main() {
let m = 63;
let b = chamber_rhs(m, 12.0);
for a in [lap2(m), lap_d(m, aggregate_d)] {
let d = diagonal(&a);
let l = ic0(&a, m);
let it = |minv: &dyn Fn(&[f64]) -> Vec<f64>| pcg(&a, &b, minv, 1e-6, 10_000).1.unwrap();
let dmin = d.iter().cloned().fold(f64::INFINITY, f64::min);
let dmax = d.iter().cloned().fold(0.0, f64::max);
println!("{} {} {} {} {}", dmin, dmax,
it(&|r| r.to_vec()),
it(&|r| r.iter().zip(&d).map(|(p, q)| p / q).collect()),
it(&|r| ic_solve(&l, m, r)));
}
}
// Output:
// 4 4 100 100 40
// 0.4 4 198 103 49| CG iterations, \(m = 63\) | uniform | aggregate |
|---|---|---|
| no preconditioner | 100 | 197 |
| Jacobi | 100 | 103 |
| IC(0) | 40 | 49 |
On the uniform chamber the diagonal is constant (4 everywhere) and Jacobi preconditioning changes nothing. With the aggregate, the diagonal ranges from 0.4 to 4, plain CG needs twice as many iterations, and the diagonal scaling removes almost all of that. IC(0) is 2.5–4 times better than plain CG; \(L\) has the same 11 781 non-zeros as the lower triangle of \(A\), and \(LL^T\) differs from \(A\) by up to 0.47 (the dropped fill-in). Rust needs 198 instead of 197 plain CG iterations on the aggregate: at iteration 197 the residual is \(0.99994\times10^{-6}\), right at the tolerance, and a different order of summation in assembling \(A\) tips it over. Counts near a tolerance can differ by one between implementations.
C5.
# lap1(), lap2(), chamber_rhs() as in the Background
adv2 <- function(m, Pe) { # flow in +x, upwind differences
h <- 1 / (m + 1)
Tx <- lap1(m) + Pe * h * bandSparse(m, k = c(0, -1),
diagonals = list(rep(1, m), rep(-1, m - 1)))
kronecker(Diagonal(m), Tx) + kronecker(lap1(m), Diagonal(m))
}
gmres <- function(A, b, k = 300, tol = 1e-6) {
n <- length(b); Q <- matrix(0, n, k + 1); H <- matrix(0, k + 1, k)
beta <- sqrt(sum(b^2)); Q[, 1] <- b / beta
for (j in 1:k) {
w <- (A %*% Q[, j])[, 1] # one product with A
for (i in 1:j) { H[i, j] <- sum(Q[, i] * w); w <- w - H[i, j] * Q[, i] }
H[j + 1, j] <- sqrt(sum(w^2)); Q[, j + 1] <- w / H[j + 1, j]
e1 <- c(beta, rep(0, j)); Hj <- H[1:(j + 1), 1:j, drop = FALSE]
y <- qr.solve(Hj, e1) # small least-squares problem
if (sqrt(sum((e1 - Hj %*% y)^2)) < tol * beta) break
}
list(x = as.vector(Q[, 1:j] %*% y), it = j)
}
cg <- function(A, b, maxit) { # plain CG, fixed number of steps
x <- numeric(length(b)); r <- b; p <- r; rr <- sum(r^2)
for (it in 1:maxit) {
Ap <- (A %*% p)[, 1]; alpha <- rr / sum(p * Ap)
x <- x + alpha * p; r <- r - alpha * Ap
rr_new <- sum(r^2); p <- r + (rr_new / rr) * p; rr <- rr_new
}
x
}
relres <- function(A, b, x) sqrt(sum((b - A %*% x)^2)) / sqrt(sum(b^2))
m <- 63; b <- chamber_rhs(m)
A <- adv2(m, Pe = 50)
isSymmetric(A)
sapply(c(50, 100, 300), function(k) relres(A, b, cg(A, b, k)))
g <- gmres(A, b); c(g$it, relres(A, b, g$x))
gs <- gmres(lap2(m), b); gs$it # GMRES on the symmetric chamber
xd <- solve(A, b); max(abs(g$x - xd)); 1 - xd[(m^2 + 1) / 2]
# Output:
# [1] FALSE
# [1] 52.67222 105.26163 313.69948
# [1] 1.160000e+02 9.631911e-07
# [1] 99
# [1] 6.110142e-08
# [1] 0.8800808# imports, lap1(), lap2(), chamber_rhs() as in the Background
from scipy.sparse.linalg import cg, gmres, spsolve
def adv2(m, Pe): # flow in +x, upwind differences
h = 1 / (m + 1)
Tx = lap1(m) + Pe * h * sparse.diags([np.ones(m), -np.ones(m - 1)], [0, -1])
return (sparse.kron(sparse.identity(m), Tx) + sparse.kron(lap1(m), sparse.identity(m))).tocsr()
relres = lambda A, b, x: np.linalg.norm(b - A @ x) / np.linalg.norm(b)
m = 63; b = chamber_rhs(m)
A = adv2(m, Pe=50)
print(abs(A - A.T).max() == 0) # symmetric?
print([relres(A, b, cg(A, b, rtol=1e-12, maxiter=k)[0]) for k in [50, 100, 300]])
def run_gmres(A, b, restart):
count = [0]
def callback(pr_norm): count[0] += 1 # once per inner iteration
x, info = gmres(A, b, rtol=1e-6, restart=restart, maxiter=1000,
callback=callback, callback_type="pr_norm")
return x, count[0], info
x, its, info = run_gmres(A, b, restart=300) # full GMRES
print(its, relres(A, b, x), info)
print(run_gmres(A, b, restart=20)[1]) # restarted GMRES(20)
print(run_gmres(lap2(m), b, restart=300)[1]) # GMRES on the symmetric chamber
xd = spsolve(A, b); print(abs(x - xd).max(), 1 - xd[(m * m - 1) // 2])
# Output:
# False
# [np.float64(52.6722164382221), np.float64(105.26162881388188), np.float64(313.69947889855973)]
# 116 9.631910941186645e-07 0
# 187
# 99
# 6.110142478088498e-08 0.8800807721698659// rust/examples/iterative_solvers_c5.rs — cargo run --release --example iterative_solvers_c5
// C5: the perfused chamber (advection-diffusion, nonsymmetric). CG fails;
// hand-written GMRES (Arnoldi on sprs, small least squares by nalgebra QR) works.
include!("iterative_solvers_shared/defs.rs");
use nalgebra::{DMatrix, DVector};
fn adv2(m: usize, pe: f64) -> CsMat<f64> { // flow in +x, upwind differences
let (n, ph) = (m * m, pe / (m + 1) as f64);
let mut t = TriMat::new((n, n));
for j in 0..m {
for i in 0..m {
let k = i + m * j;
t.add_triplet(k, k, 4.0 + ph);
if i > 0 { t.add_triplet(k, k - 1, -1.0 - ph); }
if i < m - 1 { t.add_triplet(k, k + 1, -1.0); }
if j > 0 { t.add_triplet(k, k - m, -1.0); }
if j < m - 1 { t.add_triplet(k, k + m, -1.0); }
}
}
t.to_csr()
}
fn relres(a: &CsMat<f64>, b: &[f64], x: &[f64]) -> f64 {
let ax = matvec(a, x);
norm(&b.iter().zip(&ax).map(|(p, q)| p - q).collect::<Vec<_>>()) / norm(b)
}
fn cg_fixed(a: &CsMat<f64>, b: &[f64], steps: usize) -> Vec<f64> { // plain CG, no stopping
let n = b.len();
let (mut x, mut r, mut p) = (vec![0.0; n], b.to_vec(), b.to_vec());
let mut rr = dot(&r, &r);
for _ in 0..steps {
let ap = matvec(a, &p);
let alpha = rr / dot(&p, &ap);
for i in 0..n { x[i] += alpha * p[i]; r[i] -= alpha * ap[i]; }
let rr_new = dot(&r, &r);
for i in 0..n { p[i] = r[i] + (rr_new / rr) * p[i]; }
rr = rr_new;
}
x
}
fn gmres(a: &CsMat<f64>, b: &[f64], k: usize, tol: f64) -> (Vec<f64>, usize) {
let beta = norm(b);
let mut q: Vec<Vec<f64>> = vec![b.iter().map(|v| v / beta).collect()];
let mut h = DMatrix::<f64>::zeros(k + 1, k);
let mut y = DVector::<f64>::zeros(0);
let mut jlast = 0;
for j in 0..k {
let mut w = matvec(a, &q[j]); // one product with A
for i in 0..=j {
h[(i, j)] = dot(&q[i], &w);
for (wl, ql) in w.iter_mut().zip(&q[i]) { *wl -= h[(i, j)] * ql; }
}
h[(j + 1, j)] = norm(&w);
q.push(w.iter().map(|v| v / h[(j + 1, j)]).collect());
// small least-squares problem: minimise || beta e1 - H y ||
let hj = h.view((0, 0), (j + 2, j + 1)).into_owned();
let mut e1 = DVector::<f64>::zeros(j + 2);
e1[0] = beta;
let qr = hj.clone().qr();
y = qr.r().solve_upper_triangular(&(qr.q().transpose() * &e1)).unwrap();
jlast = j + 1;
if (&e1 - &hj * &y).norm() < tol * beta { break; }
}
let mut x = vec![0.0; b.len()];
for (l, yl) in y.iter().enumerate() {
for (xi, qi) in x.iter_mut().zip(&q[l]) { *xi += yl * qi; }
}
(x, jlast)
}
fn main() {
let m = 63;
let b = chamber_rhs(m, 12.0);
let a = adv2(m, 50.0);
let at: CsMat<f64> = a.transpose_view().to_csr();
println!("{}", a == at); // symmetric?
let res: Vec<f64> = [50, 100, 300].iter().map(|&s| relres(&a, &b, &cg_fixed(&a, &b, s))).collect();
println!("{:?}", res);
let (x, it) = gmres(&a, &b, 300, 1e-6);
println!("{} {:e}", it, relres(&a, &b, &x));
println!("{}", gmres(&lap2(m), &b, 300, 1e-6).1); // GMRES on the symmetric chamber
println!("{}", 1.0 - x[(m * m - 1) / 2]);
}
// Output:
// false
// [52.67221643822255, 105.26162881388326, 313.6994788985633]
// 116 9.631910948911138e-7
// 99
// 0.8800807605276728- Not symmetric. (b) CG does not converge: the true relative residual is 53 after 50 iterations and 314 after 300, and grows. Nothing in CG’s own arithmetic signals the problem; only the check of symmetry, or of the true residual, does. (c) Full GMRES converges in 116 iterations to a relative residual of \(9.6\times10^{-7}\), and agrees with the direct solve to \(6\times10^{-8}\). Restarted GMRES(20) needs 187 iterations: restarting saves memory (20 basis vectors instead of 116) at the price of more iterations. (d) On the symmetric chamber GMRES takes 99 iterations, CG 100: for SPD matrices the two minimise different norms over the same Krylov space and need about the same count, but CG does it with four vectors instead of a growing basis. The perfused chamber is much better oxygenated: 0.880 in the centre instead of 0.116. (Rust prints the centre from the GMRES solution, which agrees with the direct solve to 7 digits.)
C6.
# continues C5 (lap1, lap2, chamber_rhs, adv2, gmres, relres)
gmres_k <- function(A, b, k, tol = 1e-6, maxit = 3000) { # restarted GMRES(k)
x <- numeric(length(b)); nb <- sqrt(sum(b^2)); it <- 0
repeat {
r <- b - (A %*% x)[, 1]; nr <- sqrt(sum(r^2))
if (nr < tol * nb || it >= maxit) break
g <- gmres(A, r, k = min(k, maxit - it), tol = tol * nb / nr) # one cycle
x <- x + g$x; it <- it + g$it
}
list(x = x, it = it, relres = nr / nb)
}
m <- 63; b <- chamber_rhs(m); h <- 1 / (m + 1)
A <- adv2(m, Pe = 50) # perfused chamber
S <- A - 100 * h^2 * Diagonal(m^2) # signal with positive feedback
for (k in c(10, 20, 50, 300)) {
g1 <- gmres_k(A, b, k); g2 <- gmres_k(S, b, k)
cat(k, g1$it, g2$it, signif(g2$relres, 3), "\n")
}
v <- as.vector(outer(sin(pi * (1:m) * h), sin(pi * (1:m) * h))) # smooth bump
c(sum(v * (A %*% v)), sum(v * (S %*% v))) / sum(v^2) # v'Av / v'v
# Output:
# 10 147 3000 0.976
# 20 187 3000 0.973
# 50 284 800 8.44e-07
# 300 116 123 5.53e-07
# [1] 0.005759225 -0.018654837# continues C5 (imports, lap1, lap2, chamber_rhs, adv2, relres)
from scipy.sparse.linalg import gmres
def gmres_k(A, b, k, maxit=3000): # restarted GMRES(k), at most maxit steps
count = [0]
def callback(pr_norm): count[0] += 1
x, info = gmres(A, b, rtol=1e-6, restart=k, maxiter=maxit // k,
callback=callback, callback_type="pr_norm")
return x, count[0], relres(A, b, x)
m = 63; b = chamber_rhs(m); h = 1 / (m + 1)
A = adv2(m, Pe=50) # perfused chamber
S = (A - 100 * h ** 2 * sparse.identity(m * m)).tocsr() # signal with positive feedback
for k in [10, 20, 50, 300]:
x1, it1, _ = gmres_k(A, b, k); x2, it2, r2 = gmres_k(S, b, k)
print(k, it1, it2, float(f"{r2:.3g}"))
s = np.sin(np.pi * np.arange(1, m + 1) * h)
v = np.outer(s, s).ravel() # smooth bump
print(v @ (A @ v) / (v @ v), v @ (S @ v) / (v @ v)) # v'Av / v'v
# Output:
# 10 147 3000 0.976
# 20 187 3000 0.973
# 50 284 800 8.44e-07
# 300 116 123 5.53e-07
# 0.005759225019019523 -0.018654837480980496// rust/examples/iterative_solvers_c6.rs — cargo run --release --example iterative_solvers_c6
// C6: restarted GMRES(k) on the perfused chamber and on the signal chamber
// (positive feedback, sigma = 100), where short restarts stall. Hand-written
// GMRES as in C5, plus a restart loop; the smooth bump v tests v'Av > 0.
include!("iterative_solvers_shared/defs.rs");
use nalgebra::{DMatrix, DVector};
fn adv2(m: usize, pe: f64, sigma: f64) -> CsMat<f64> { // flow in +x, upwind; minus sigma h^2 I
let (n, h) = (m * m, 1.0 / (m + 1) as f64);
let ph = pe * h;
let mut t = TriMat::new((n, n));
for j in 0..m {
for i in 0..m {
let k = i + m * j;
t.add_triplet(k, k, 4.0 + ph - sigma * h * h);
if i > 0 { t.add_triplet(k, k - 1, -1.0 - ph); }
if i < m - 1 { t.add_triplet(k, k + 1, -1.0); }
if j > 0 { t.add_triplet(k, k - m, -1.0); }
if j < m - 1 { t.add_triplet(k, k + m, -1.0); }
}
}
t.to_csr()
}
fn residual(a: &CsMat<f64>, b: &[f64], x: &[f64]) -> Vec<f64> {
let ax = matvec(a, x);
b.iter().zip(&ax).map(|(p, q)| p - q).collect()
}
// one GMRES cycle of at most k steps from x = 0; stops when ||b - A x|| < tol ||b||
fn gmres(a: &CsMat<f64>, b: &[f64], k: usize, tol: f64) -> (Vec<f64>, usize) {
let beta = norm(b);
let mut q: Vec<Vec<f64>> = vec![b.iter().map(|v| v / beta).collect()];
let mut h = DMatrix::<f64>::zeros(k + 1, k);
let mut y = DVector::<f64>::zeros(0);
let mut jlast = 0;
for j in 0..k {
let mut w = matvec(a, &q[j]); // one product with A
for i in 0..=j {
h[(i, j)] = dot(&q[i], &w);
for (wl, ql) in w.iter_mut().zip(&q[i]) { *wl -= h[(i, j)] * ql; }
}
h[(j + 1, j)] = norm(&w);
q.push(w.iter().map(|v| v / h[(j + 1, j)]).collect());
let hj = h.view((0, 0), (j + 2, j + 1)).into_owned();
let mut e1 = DVector::<f64>::zeros(j + 2);
e1[0] = beta;
let qr = hj.clone().qr();
y = qr.r().solve_upper_triangular(&(qr.q().transpose() * &e1)).unwrap();
jlast = j + 1;
if (&e1 - &hj * &y).norm() < tol * beta { break; }
}
let mut x = vec![0.0; b.len()];
for (l, yl) in y.iter().enumerate() {
for (xi, qi) in x.iter_mut().zip(&q[l]) { *xi += yl * qi; }
}
(x, jlast)
}
// restarted GMRES(k): at most maxit steps in total; returns iterations and relative residual
fn gmres_k(a: &CsMat<f64>, b: &[f64], k: usize, tol: f64, maxit: usize) -> (usize, f64) {
let (mut x, nb, mut it) = (vec![0.0; b.len()], norm(b), 0);
loop {
let r = residual(a, b, &x);
let nr = norm(&r);
if nr < tol * nb || it >= maxit { return (it, nr / nb); }
let (dx, j) = gmres(a, &r, k.min(maxit - it), tol * nb / nr); // one cycle
for (xi, d) in x.iter_mut().zip(&dx) { *xi += d; }
it += j;
}
}
fn sig3(v: f64) -> f64 { // round to 3 significant digits
let e = 10f64.powi(2 - v.abs().log10().floor() as i32);
(v * e).round() / e
}
fn main() {
let m = 63;
let h = 1.0 / (m + 1) as f64;
let b = chamber_rhs(m, 12.0);
let a = adv2(m, 50.0, 0.0); // perfused chamber
let s = adv2(m, 50.0, 100.0); // signal with positive feedback
for k in [10, 20, 50, 300] {
let (it1, _) = gmres_k(&a, &b, k, 1e-6, 3000);
let (it2, r2) = gmres_k(&s, &b, k, 1e-6, 3000);
if r2 > 1e-3 { println!("{} {} {} {}", k, it1, it2, sig3(r2)); }
else { println!("{} {} {} {:e}", k, it1, it2, sig3(r2)); }
}
let sv: Vec<f64> = (1..=m).map(|i| (std::f64::consts::PI * i as f64 * h).sin()).collect();
let v: Vec<f64> = (0..m * m).map(|k| sv[k % m] * sv[k / m]).collect(); // smooth bump
let vv = dot(&v, &v);
println!("{} {}", dot(&v, &matvec(&a, &v)) / vv, dot(&v, &matvec(&s, &v)) / vv);
}
// Output:
// 10 147 3000 0.976
// 20 187 3000 0.973
// 50 284 800 8.44e-7
// 300 116 123 5.53e-7
// 0.005759225019019527 -0.018654837480980534| iterations to \(10^{-6}\) | GMRES(10) | GMRES(20) | GMRES(50) | full GMRES |
|---|---|---|---|---|
| perfused chamber | 147 | 187 | 284 | 116 |
| signal chamber, \(\sigma = 100\) | stalls (0.976) | stalls (0.973) | 800 | 123 |
On the perfused chamber every restart length converges, but not in the order you might expect: GMRES(10) beats GMRES(50). With positive feedback, GMRES(10) and GMRES(20) are still at a relative residual of 0.97 after 3000 iterations: they stall. The residual curve is flat, which is the check (fig. on the slide “Restarted GMRES can stall”). Full GMRES needs only 123 iterations, but stores 123 vectors. (c) The bump gives \(\mathbf{v}^TA\mathbf{v}/\mathbf{v}^T\mathbf{v} = 0.0058 > 0\) for the perfused chamber and \(0.0058 - 100h^2 = -0.0187 < 0\) for the signal chamber: its symmetric part is indefinite, and fact 8’s guarantee is lost, as for the loop of B8. The matrix itself is fine: its eigenvalues still have positive real parts and the steady signal is positive everywhere (check with a direct solve); the trouble is only for short restarts.
C7.
# continues C6 (A, S, b, h, m, gmres, relres)
bicgstab <- function(A, b, tol = 1e-6, maxit = 5000) {
x <- v <- p <- numeric(length(b)); r <- rh <- b; rho <- alpha <- omega <- 1
for (it in 1:maxit) {
rho_new <- sum(rh * r); beta <- (rho_new / rho) * (alpha / omega); rho <- rho_new
p <- r + beta * (p - omega * v)
v <- (A %*% p)[, 1]; alpha <- rho / sum(rh * v); s <- r - alpha * v
t <- (A %*% s)[, 1]; omega <- sum(t * s) / sum(t * t) # a GMRES(1) step
x <- x + alpha * p + omega * s; r <- s - omega * t
if (sqrt(sum(r^2)) < tol * sqrt(sum(b^2))) return(list(x = x, it = it))
}
list(x = x, it = NA)
}
for (sigma in c(0, 100, 200)) {
B <- A - sigma * h^2 * Diagonal(m^2)
bs <- bicgstab(B, b); gf <- gmres(B, b, k = 300)
cat(sigma, bs$it, 2 * bs$it, signif(relres(B, b, bs$x), 3), gf$it, "\n")
}
# Output:
# 0 88 176 4.68e-07 116
# 100 103 206 7.57e-08 123
# 200 NA NA 3.29 133 # continues C6 (A, b, h, m, gmres_k, relres)
from scipy.sparse.linalg import bicgstab as scipy_bicgstab
def bicgstab(A, b, tol=1e-6, maxit=5000):
x = np.zeros(len(b)); v = np.zeros(len(b)); p = np.zeros(len(b))
r = b.copy(); rh = b.copy(); rho = alpha = omega = 1.0
for it in range(1, maxit + 1):
rho_new = rh @ r; beta = (rho_new / rho) * (alpha / omega); rho = rho_new
p = r + beta * (p - omega * v)
v = A @ p; alpha = rho / (rh @ v); s = r - alpha * v
t = A @ s; omega = (t @ s) / (t @ t) # a GMRES(1) step
x = x + alpha * p + omega * s; r = s - omega * t
if np.linalg.norm(r) < tol * np.linalg.norm(b):
return x, it
return x, None
for sigma in [0, 100, 200]:
B = (A - sigma * h ** 2 * sparse.identity(m * m)).tocsr()
x, it = bicgstab(B, b)
print(sigma, it, 2 * it if it else None, float(f"{relres(B, b, x):.3g}"), gmres_k(B, b, 300)[1])
count = [0]
def cb(xk): count[0] += 1
xs, info = scipy_bicgstab(B, b, rtol=1e-6, maxiter=5000, callback=cb)
print(" scipy:", count[0], info)
# Output:
# 0 86 172 5.99e-07 116
# scipy: 85 0
# 100 100 200 7.92e-07 123
# scipy: 100 0
# 200 None None 99.4 133
# scipy: 5000 5000// rust/examples/iterative_solvers_c7.rs — cargo run --release --example iterative_solvers_c7
// C7: hand-written BiCGSTAB (short recurrences, two products with A per step)
// against full GMRES on the perfused chamber with feedback sigma = 0, 100, 200.
include!("iterative_solvers_shared/defs.rs");
use nalgebra::{DMatrix, DVector};
fn adv2(m: usize, pe: f64, sigma: f64) -> CsMat<f64> { // flow in +x, upwind; minus sigma h^2 I
let (n, h) = (m * m, 1.0 / (m + 1) as f64);
let ph = pe * h;
let mut t = TriMat::new((n, n));
for j in 0..m {
for i in 0..m {
let k = i + m * j;
t.add_triplet(k, k, 4.0 + ph - sigma * h * h);
if i > 0 { t.add_triplet(k, k - 1, -1.0 - ph); }
if i < m - 1 { t.add_triplet(k, k + 1, -1.0); }
if j > 0 { t.add_triplet(k, k - m, -1.0); }
if j < m - 1 { t.add_triplet(k, k + m, -1.0); }
}
}
t.to_csr()
}
fn relres(a: &CsMat<f64>, b: &[f64], x: &[f64]) -> f64 {
let ax = matvec(a, x);
norm(&b.iter().zip(&ax).map(|(p, q)| p - q).collect::<Vec<_>>()) / norm(b)
}
fn bicgstab(a: &CsMat<f64>, b: &[f64], tol: f64, maxit: usize) -> (Vec<f64>, Option<usize>) {
let n = b.len();
let (mut x, mut r, rh) = (vec![0.0; n], b.to_vec(), b.to_vec());
let nb = norm(b);
let (mut rho, mut alpha, mut omega) = (1.0, 1.0, 1.0);
let (mut v, mut p) = (vec![0.0; n], vec![0.0; n]);
for it in 1..=maxit {
let rho_new = dot(&rh, &r);
let beta = (rho_new / rho) * (alpha / omega);
rho = rho_new;
for i in 0..n { p[i] = r[i] + beta * (p[i] - omega * v[i]); }
v = matvec(a, &p);
alpha = rho / dot(&rh, &v);
let s: Vec<f64> = (0..n).map(|i| r[i] - alpha * v[i]).collect();
let t = matvec(a, &s);
omega = dot(&t, &s) / dot(&t, &t); // a GMRES(1) step
for i in 0..n {
x[i] += alpha * p[i] + omega * s[i];
r[i] = s[i] - omega * t[i];
}
if norm(&r) < tol * nb { return (x, Some(it)); }
}
(x, None)
}
// full GMRES (no restart), as in C5; returns the number of iterations
fn gmres_its(a: &CsMat<f64>, b: &[f64], k: usize, tol: f64) -> usize {
let beta = norm(b);
let mut q: Vec<Vec<f64>> = vec![b.iter().map(|v| v / beta).collect()];
let mut h = DMatrix::<f64>::zeros(k + 1, k);
for j in 0..k {
let mut w = matvec(a, &q[j]);
for i in 0..=j {
h[(i, j)] = dot(&q[i], &w);
for (wl, ql) in w.iter_mut().zip(&q[i]) { *wl -= h[(i, j)] * ql; }
}
h[(j + 1, j)] = norm(&w);
q.push(w.iter().map(|v| v / h[(j + 1, j)]).collect());
let hj = h.view((0, 0), (j + 2, j + 1)).into_owned();
let mut e1 = DVector::<f64>::zeros(j + 2);
e1[0] = beta;
let qr = hj.clone().qr();
let y = qr.r().solve_upper_triangular(&(qr.q().transpose() * &e1)).unwrap();
if (&e1 - &hj * &y).norm() < tol * beta { return j + 1; }
}
k
}
fn main() {
let m = 63;
let b = chamber_rhs(m, 12.0);
for sigma in [0.0, 100.0, 200.0] {
let a = adv2(m, 50.0, sigma);
let (x, it) = bicgstab(&a, &b, 1e-6, 5000);
let its = match it { Some(i) => format!("{} {}", i, 2 * i), None => "NA NA".to_string() };
println!("{} {} {:.2e} {}", sigma, its, relres(&a, &b, &x), gmres_its(&a, &b, 300, 1e-6));
}
}
// Output:
// 0 88 176 9.91e-7 116
// 100 101 202 9.55e-7 123
// 200 NA NA 2.96e0 133| perfused (\(\sigma = 0\)) | \(\sigma = 100\) | \(\sigma = 200\) | |
|---|---|---|---|
| BiCGSTAB steps, R / Python / Rust | 88 / 86 / 88 | 103 / 100 / 101 | fails in all three |
| products with \(A\) (R) | 176 | 206 | — |
| full GMRES | 116 | 123 | 133 |
BiCGSTAB converges where GMRES(10) and GMRES(20) stalled (\(\sigma = 100\)), with fixed memory, at the price of two products per step. At \(\sigma = 200\) it stagnates: after 5000 steps the residual is still of order 1 to 100, and the value it ends on depends on rounding (R 3.29, Python 99.4, Rust 2.96). Its \(\omega\) step is a GMRES(1) step, which gets no grip when \(\mathbf{v}^TA\mathbf{v} \le 0\) for the current residual. Full GMRES converges in 133 iterations. The step counts differ by up to three between R, Python and Rust (and scipy’s version, which also tests halfway through a step, needs 85 and 100): BiCGSTAB’s residual jumps up and down by orders of magnitude, so tiny rounding differences in \(A\mathbf{x}\) shift the step at which it first falls below the tolerance. For \(n = 10^6\), full GMRES with 133 vectors needs about 1 GB for the basis; BiCGSTAB needs 56 MB. In practice: try BiCGSTAB or GMRES(\(k\)) with a preconditioner, watch the residual, and keep full GMRES (or a direct solve on a small grid) as the reference.
Where this leads
- Reaction–diffusion and pattern formation, the next unit, adds reactions to diffusion. Self-activation puts a \(-\sigma I\) term into the Jacobian, as in the signal chamber of C6; with walls instead of its periodic FFT box, and on a large grid, every implicit or Newton step would be a preconditioned Krylov solve.
- Steady state in two dimensions produces these matrices; with Newton’s method for nonlinear uptake, every Newton step is a linear solve with an SPD Jacobian, and inside a large 3D model that solve is preconditioned CG.
- Beyond rectangles: finite elements and flow (Part 12): finite-element meshes give sparse matrices without a grid structure; there, algebraic multigrid and ILU replace the hand-written IC(0) for the five-point pattern used here.
- How
eigen()works, and big problems (Part 5): Lanczos and Arnoldi, the eigenvalue versions of the Krylov recurrences in CG and GMRES.