Module contents
Lesson 7 of 26Advanced 115 min

Sparse matrices and Krylov iterative methods

For a matrix with millions of rows and mostly zero entries, use sparse representations and matrix–vector products in place of direct factorization. Study the limits of stationary methods, conjugate gradients and GMRES in Krylov spaces, and preconditioners that change practical convergence by orders of magnitude.

After this lesson you can

  • Implement CSR matrix–vector multiplication and select a sparse format for the operation.
  • Implement Jacobi, Gauss–Seidel, conjugate gradient and preconditioned conjugate gradient.
  • Derive conjugate gradient and relate its convergence to √κ and spectral distribution.
  • Use restarted GMRES with ILU preconditioning on nonsymmetric problems.
  • Set up matrix-free solvers using LinearOperator and estimate extreme eigenvalues with Lanczos.

Before you start

Motivation: one million unknowns, five million numbers

You want the equilibrium temperature of a square plate with fixed-temperature edges, the electric potential in a region, or the pressure field enforcing fluid incompressibility at each simulation step. All three are Poisson’s equation, −Δu=f-\Delta u = f. Discretize it on a grid of m×mm \times m interior points with spacing h=1/(m+1)h = 1/(m+1) and the five-point stencil:

4uij−ui−1,j−ui+1,j−ui,j−1−ui,j+1h2=fij.\frac{4u_{ij} - u_{i-1,j} - u_{i+1,j} - u_{i,j-1} - u_{i,j+1}}{h^2} = f_{ij}.

Numbering points by rows gives system Au=b\mat{A}\vb{u} = \vb{b} with n=m2n = m^2 unknowns. With m=1000m = 1000, n=106n = 10^6. Each row of A\mat{A} has at most five nonzero entries, with 5n−4m≈5⋅1065n - 4m \approx 5\cdot 10^6 in total. The matrix is symmetric positive definite and almost empty: of its 101210^{12} entries, only one in 200 000200\,000 is nonzero.

Now compare solution costs:

  • Dense LU or Cholesky (from lesson 4). Storing A\mat{A} as a dense float64 matrix alone takes 1012×810^{12} \times 8 bytes =8= 8 TB. Cholesky factorization costs about 13n3≈3⋅1017\tfrac13 n^3 \approx 3\cdot 10^{17} flops (the flop count from lesson 4): about four days at one sustained teraflop per second.
  • Store only nonzeros. With float64 values and int32 indices, 5⋅106×125\cdot 10^6 \times 12 bytes plus one pointer per row: about 64 MB. Product Ax\mat{A}\vb{x} costs 2 nnz≈1072\,\text{nnz} \approx 10^7 flops, milliseconds.

Between these extremes lies the lesson. If you can only afford matrix-vector products, how do you solve the system? Iterative methods start with an approximation and improve it using A\mat{A} only through v↦Av\vb{v} \mapsto \mat{A}\vb{v}. Classical methods (Jacobi, Gauss–Seidel) are simple and slow; Krylov methods (conjugate gradient, GMRES) are optimal in a precise sense, and with a good preconditioner turn thousands of iterations into tens (the labs reduce 2792 to 108 and 275 to 9). Direct methods still have a place: with suitable reordering, sparse Cholesky solves this same problem with moderate fill.

Sparse formats

A sparse matrix is stored as a list of nonzeros and a way to locate them. The format determines which operations are cheap.

CSR compresses COO’s row array: instead of repeating the row number for every nonzero, it stores where each row begins. With 4-byte indices it occupies 12 nnz+4(m+1)12\,\text{nnz} + 4(m+1) bytes versus COO’s 16 nnz16\,\text{nnz}.

InteractiveAnatomy of CSR
0011223344554152163728193
data
40
11
52
23
14
65
36
77
28
89
110
911
312
indices
00
21
12
43
04
25
36
37
18
49
510
211
512
column of each nonzero
indptr
00
21
42
73
84
115
136
the row rr occupies positions indptr[r] to indptr[r+1] − 1; indptr[6] = nnz
Format
Mode
nonzeros13
memory CSR (float64, indices int32)184 B
dense memory288 B
The row 2 occupies data[4:7], between indptr[2] = 4 and indptr[3] = 7. Its entry a2,3=3a_{2,3} = 3 is at position 6, with indices[6] = 3.
A 6×66\times 6 matrix with 13 nonzeros and its arrays. In Explore, click a nonzero to highlight its position in data and indices, its row segment, and the two indptr pointers delimiting it. Switch to CSC and the same entry moves to another position. Under Insert or delete, click an empty cell in CSR row 0 and count what shifts; compare row 5 and COO. Under Product, step through y=Ax\vb{y} = \mat{A}\vb{x} in CSR (contiguous segments, one write per row) and CSC (scattered writes to y\vb{y}).

CSR matrix-vector multiplication loops over rows, each a dot product of a contiguous segment of data with entries of x\vb{x} pointed to by indices:

yi=∑k=indptr[i]indptr[i+1]−1data[k]  xindices[k].y_i = \sum_{k = \texttt{indptr}[i]}^{\texttt{indptr}[i+1] - 1} \texttt{data}[k]\; x_{\texttt{indices}[k]}.

This takes 2 nnz2\,\text{nnz} flops, but each nonzero reads 12 matrix bytes plus an xjx_j at an arbitrary position. Arithmetic intensity is below 1/61/6 flop per byte: sparse multiplication is limited by memory bandwidth, not arithmetic (the roofline model quantifies this). Practical consequences:

OperationCOOCSRCSC
Build by adding entriescheap (append)expensive (shift and index)expensive
Ax\mat{A}\vb{x}works, no row localitybestscattered writes
A⊤x\mat{A}\T\vb{x}samescattered writesbest
Extract row iiscan allO(nnz de la fila)\bigO(\text{nnz de la fila})scan all
Extract column jjscan allscan allO(nnz de la columna)\bigO(\text{nnz de la columna})
Factor (sparse LU, Cholesky)noyesusual (SuperLU, CHOLMOD)

Rule of thumb: build in COO (or LIL, lists per row, for incremental insertion), convert once to CSR or CSC, and operate. Other formats suit specific structures: DIA stores whole diagonals (ideal for regular-grid stencils), BSR stores small dense blocks (finite elements with several unknowns per node), and ELLPACK pads rows to equal nonzero counts for regular GPU access.

[ ]2D Poisson in sparse formatBrowser
import numpy as np
import scipy.sparse as sp

def poisson2d(m):
    """Matriz de la plantilla de 5 puntos en una malla m x m con contorno nulo (sin el factor 1/h^2)."""
    T = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(m, m))
    I = sp.identity(m)
    A = (sp.kron(I, T) + sp.kron(T, I)).tocsr()
    A.eliminate_zeros()      # kron puede guardar bloques con ceros explícitos: fuera
    return A

A = poisson2d(3)
print(A.toarray().astype(int))          # toarray solo con matrices diminutas
print("data   :", A.data.astype(int))
print("indices:", A.indices)
print("indptr :", A.indptr)

for m in [100, 300]:
    A = poisson2d(m)
    n = m * m
    print(f"\nm = {m}: n = {n}, nnz = {A.nnz} (5n - 4m = {5 * n - 4 * m})")
    print(f"  CSR: {A.data.nbytes + A.indices.nbytes + A.indptr.nbytes:,} bytes   densa: {8 * n * n:,} bytes")

m = 1000; n = m * m; nnz = 5 * n - 4 * m
print(f"\nm = 1000: nnz = {nnz:,}, CSR con int32 = {12 * nnz + 4 * (n + 1):,} bytes, densa = {8 * n * n:.1e} bytes")

Sum I⊗T+T⊗I\mat{I} \otimes \mat{T} + \mat{T} \otimes \mat{I}, with T=tridiag⁡(−1,2,−1)\mat{T} = \operatorname{tridiag}(-1, 2, -1), compactly writes the stencil: the first term couples each point to neighbors in the same grid row, the second to those in the same column. sp.kron builds it and tocsr() converts it. A SciPy detail: when the second factor is small and nearly full, kron works in dense blocks and may store explicit zeros (without eliminate_zeros, the cell’s 9×99\times 9 stored 63 entries instead of 33). These do not change products but inflate memory and cost: A.nnz counts stored entries, not nonzeros. Notice indptr of 9×99\times 9: corner rows have 3 nonzeros, edge rows 4, and the center 5.

Now implement the product from scratch in two ways: Python loops, a literal translation of the formula, and vectorized NumPy. The vectorized version repeats each row index once per nonzero (np.repeat with np.diff(indptr)) and sums by row with np.bincount.

[ ]CSR multiplication from scratchBrowser
import time
import numpy as np

def csr_matvec_bucles(data, indices, indptr, x):
    n = len(indptr) - 1
    y = np.zeros(n)
    for i in range(n):
        s = 0.0
        for k in range(indptr[i], indptr[i + 1]):
            s += data[k] * x[indices[k]]
        y[i] = s
    return y

def csr_matvec(data, indices, indptr, x):
    n = len(indptr) - 1
    filas = np.repeat(np.arange(n), np.diff(indptr))       # fila de cada no nulo
    return np.bincount(filas, weights=data * x[indices], minlength=n)

A = poisson2d(64)
x = np.random.default_rng(0).normal(size=A.shape[0])
ref = A @ x

def mide(f, rep):
    t = time.perf_counter()
    for _ in range(rep):
        y = f()
    return (time.perf_counter() - t) / rep, y

t_b, y_b = mide(lambda: csr_matvec_bucles(A.data, A.indices, A.indptr, x), 1)
t_v, y_v = mide(lambda: csr_matvec(A.data, A.indices, A.indptr, x), 20)
t_s, _ = mide(lambda: A @ x, 200)
print(f"n = {A.shape[0]}, nnz = {A.nnz}")
print(f"bucles de Python : {t_b * 1e3:8.2f} ms   error {np.max(np.abs(y_b - ref)):.1e}")
print(f"NumPy vectorizado: {t_v * 1e3:8.3f} ms   error {np.max(np.abs(y_v - ref)):.1e}")
print(f"scipy A @ x      : {t_s * 1e3:8.3f} ms")
print(f"bucles / scipy = {t_b / t_s:.0f} veces más lento")

All three give the same vector, but the Python loop is several orders of magnitude slower than SciPy’s product (the cell prints the exact ratio in your browser). The interpreter pays for each data[k] * x[indices[k]] as an object operation; SciPy runs the same loop compiled. NumPy lies between because it creates intermediate arrays of size nnz\text{nnz}.

Sparse direct methods: the elimination graph

Before iterating, understand how far direct methods go: they are often the best choice. Lesson 4 showed that eliminating a variable connects all its neighbors and that elimination order determines fill. Graphs provide a clean way to reason about it.

The model is exact because Cholesky needs no pivoting: Cholesky stability analysis guarantees any symmetric permutation PAP⊤\mat{P}\mat{A}\mat{P}\T factors stably, so ordering can be chosen solely to reduce fill. General LU differs: partial pivoting chooses rows for stability during factorization, and sparse LU programs balance both objectives using thresholds.

Actual programs divide work into three phases:

  1. Reordering. Choose P\mat{P} with little fill. Finding the optimum is NP-complete (Yannakakis, 1981), so heuristics are used. Minimum degree eliminates the vertex with fewest neighbors at each step, creating the smallest possible clique; its approximate version AMD (Amestoy, Davis and Duff, 1996) is standard. Nested dissection (George, 1973) finds a small separator splitting the graph into halves without edges between them, numbers the separator last and repeats on each half: the halves are eliminated independently.
  2. Symbolic factorization. Compute the exact pattern of L\mat{L} from the graph without arithmetic and reserve memory. The elimination tree organizes this: parent of column jj is the row of the first nonzero of L\mat{L} below its diagonal. Columns in different branches can be factored in parallel.
  3. Numerical factorization. Fill in numbers. Supernodal programs group consecutive columns with the same pattern into dense blocks and use level-3 BLAS: this is CHOLMOD (Chen, Davis, Hager and Rajamanickam, 2008), used by MATLAB with sparse chol and scikit-sparse in Python.

For a Poisson grid, natural order gives a band matrix with half-width mm: everything inside fills, O(nm)=O(n3/2)\bigO(nm) = \bigO(n^{3/2}) entries and O(nm2)=O(n2)\bigO(nm^2) = \bigO(n^2) flops. George proved in 1973 that nested dissection on a grid of k×kk\times k (that is, n=k2n = k^2) reduces storage to O(nlog⁡n)\bigO(n \log n) and operations to O(n3/2)\bigO(n^{3/2}); Hoffman, Martin and Rose (1973) proved no ordering does asymptotically better on these grids. In three dimensions separators are planes and the same strategy costs O(n4/3)\bigO(n^{4/3}) memory and O(n2)\bigO(n^2) flops: iterative methods become essential.

[ ]Ordering determines fillBrowser
import time
import numpy as np
import scipy.sparse.linalg as spla
from scipy.sparse.csgraph import reverse_cuthill_mckee

m = 48
A = poisson2d(m).tocsc()
n = m * m
print(f"Poisson {m}x{m}: n = {n}, nnz(A) = {A.nnz}, nnz(tril(A)) = {(A.nnz + n) // 2}")

def relleno(M, spec):
    t = time.perf_counter()
    lu = spla.splu(M, permc_spec=spec, diag_pivot_thresh=0.0, options=dict(SymmetricMode=True))
    return lu.L.nnz, time.perf_counter() - t

for spec, nombre in [("NATURAL", "orden natural (banda)"), ("COLAMD", "COLAMD"),
                     ("MMD_ATA", "grado mínimo sobre AᵀA"), ("MMD_AT_PLUS_A", "grado mínimo sobre A + Aᵀ")]:
    nL, t = relleno(A, spec)
    print(f"{nombre:28s} nnz(L) = {nL:7d}   ({nL / ((A.nnz + n) // 2):4.1f} veces tril(A))")

p = reverse_cuthill_mckee(A.tocsr(), symmetric_mode=True)
nL, _ = relleno(A[p][:, p].tocsc(), "NATURAL")
print(f"{'Cuthill-McKee inverso':28s} nnz(L) = {nL:7d}   ({nL / ((A.nnz + n) // 2):4.1f} veces tril(A))")

splu is SuperLU’s sparse LU, also called by spsolve. With diag_pivot_thresh=0 and SymmetricMode it behaves like Cholesky: no pivoting and the same row and column permutation, so nnz(L)\text{nnz}(\mat{L}) measures Cholesky fill. Natural ordering fills the entire band; minimum degree on the graph of A+A⊤\mat{A} + \mat{A}\T, here the grid graph itself, gives a factor about three and a half times smaller. Reverse Cuthill–McKee only reduces profile (band): it numbers the grid by diagonals and removes 30 % of fill, but its remaining profile still fills completely. As theory predicts, reducing fill requires breaking up the graph, not narrowing the band.

Stationary methods: Jacobi, Gauss–Seidel and SOR

The oldest iterative idea splits the matrix into an easily inverted part and the rest.

The solution x∗\vb{x}^* is a fixed point: x∗=Gx∗+c\vb{x}^* = \mat{G}\vb{x}^* + \vb{c}. Subtraction gives error ek=xk−x∗\vb{e}_k = \vb{x}_k - \vb{x}^* satisfying ek+1=Gek\vb{e}_{k+1} = \mat{G}\vb{e}_k, so ek=Gke0\vb{e}_k = \mat{G}^k\vb{e}_0. Everything depends on powers of G\mat{G}.

Proof

If ρ(G)≥1\rho(\mat{G}) \ge 1, take an eigenvector v\vb{v} (complex if needed) with Gv=λv\mat{G}\vb{v} = \lambda\vb{v} and ∣λ∣≥1\abs{\lambda} \ge 1. If v\vb{v} is real, e0=v\vb{e}_0 = \vb{v} gives ∥ek∥=∣λ∣k∥v∥↛0\norm{\vb{e}_k} = \abs{\lambda}^k\norm{\vb{v}} \not\to 0. Otherwise its real or imaginary part is a real e0\vb{e}_0 that does not converge, because Gkv=Gk(Re⁡v)+i Gk(Im⁡v)\mat{G}^k\vb{v} = \mat{G}^k(\operatorname{Re}\vb{v}) + i\,\mat{G}^k(\operatorname{Im}\vb{v}) does not tend to zero. Conversely, if ρ(G)<1\rho(\mat{G}) < 1, for every ε>0\eps > 0 there is an induced norm with ∥G∥≤ρ(G)+ε\norm{\mat{G}} \le \rho(\mat{G}) + \eps (constructed from Jordan form by scaling block ones), so ∥ek∥≤(ρ+ε)k∥e0∥→0\norm{\vb{e}_k} \le (\rho + \eps)^k\norm{\vb{e}_0} \to 0 by choosing ε<1−ρ\eps < 1 - \rho. Equivalently, Gelfand’s formula gives ∥Gk∥1/k→ρ(G)\norm{\mat{G}^k}^{1/k} \to \rho(\mat{G}).

∎

Two easily checked sufficient conditions:

Proof

For (1) with Jacobi, G=−D−1(L+U)\mat{G} = -\mat{D}\inv(\mat{L} + \mat{U}) has row ii containing numbers −aij/aii-a_{ij}/a_{ii} (j≠ij \neq i) and zero on the diagonal. Its infinity norm, maximum absolute row sum, is max⁡i∑j≠i∣aij∣/∣aii∣<1\max_i \sum_{j\neq i}\abs{a_{ij}}/\abs{a_{ii}} < 1, and ρ(G)≤∥G∥∞<1\rho(\mat{G}) \le \norm{\mat{G}}_\infty < 1. The Gauss–Seidel part and case (2) use energy arguments; see Saad chapter 4.

∎

The converse of (1) is false, as our case shows: the Poisson matrix is not strictly dominant (in an interior row, 4=1+1+1+14 = 1 + 1 + 1 + 1), yet Jacobi converges. To find its speed calculate ρ(G)\rho(\mat{G}), which can be done by hand for the model problem.

Analyzing the model problem

Eigenvectors of T=tridiag⁡(−1,2,−1)\mat{T} = \operatorname{tridiag}(-1, 2, -1) of size mm are discrete sines (si)p=sin⁡(ipπh)(\vb{s}_i)_p = \sin(i p \pi h), with eigenvalues 2−2cos⁡(iπh)=4sin⁡2(iπh/2)2 - 2\cos(i\pi h) = 4\sin^2(i\pi h/2), i=1,…,mi = 1, \dots, m. Those of A=I⊗T+T⊗I\mat{A} = \mat{I}\otimes\mat{T} + \mat{T}\otimes\mat{I} are products si⊗sj\vb{s}_i \otimes \vb{s}_j, with eigenvalues

λij=4sin⁡2 ⁣(iπh2)+4sin⁡2 ⁣(jπh2),1≤i,j≤m.\lambda_{ij} = 4\sin^2\!\Big(\frac{i\pi h}{2}\Big) + 4\sin^2\!\Big(\frac{j\pi h}{2}\Big), \qquad 1 \le i, j \le m.

Mode (1,1)(1, 1) is one smooth hump; (m,m)(m, m) is a checkerboard. Since the diagonal is constant, D=4I\mat{D} = 4\mat{I} and Jacobi matrix GJ=I−A/4\mat{G}_J = \mat{I} - \mat{A}/4 has the same eigenvectors, with eigenvalues

μij=1−λij4=cos⁡(iπh)+cos⁡(jπh)2.\mu_{ij} = 1 - \frac{\lambda_{ij}}{4} = \frac{\cos(i\pi h) + \cos(j\pi h)}{2}.

The largest magnitude is ρ(GJ)=cos⁡(πh)≈1−π2h22\rho(\mat{G}_J) = \cos(\pi h) \approx 1 - \tfrac{\pi^2h^2}{2}, reached at both extremes: the smoothest mode and checkerboard. Reducing error by factor 10−610^{-6} takes about ln⁡(106)/(π2h2/2)≈2.8 (m+1)2\ln(10^6)/(\pi^2h^2/2) \approx 2.8\,(m+1)^2 iterations: with m=1000m = 1000, nearly three million. For row ordering, Gauss–Seidel satisfies ρ(GGS)=ρ(GJ)2=cos⁡2(πh)\rho(\mat{G}_{GS}) = \rho(\mat{G}_J)^2 = \cos^2(\pi h) (the matrix is consistently ordered in Young’s terminology), merely doubling speed. SOR with optimal ω\omega, ω∗=2/(1+sin⁡πh)\omega^* = 2/(1 + \sin\pi h), achieves ρ=ω∗−1≈1−2πh\rho = \omega^* - 1 \approx 1 - 2\pi h: iterations fall from O(m2)\bigO(m^2) to O(m)\bigO(m), but ω∗\omega^* must be known and rarely is outside the model problem.

They smooth, but do not solve

ρ\rho approaching 1 does not mean all error decays slowly. Each mode has a different factor: modes with large ii or jj (short waves) have small ∣μij∣\abs{\mu_{ij}} and vanish in a few iterations; those with small i,ji, j (long waves) have μij≈1\mu_{ij} \approx 1 and linger. There is a trap: with pure Jacobi the checkerboard has μmm=−cos⁡πh≈−1\mu_{mm} = -\cos\pi h \approx -1 and also remains, merely changing sign each iteration. Hence weighted Jacobi, xk+1=xk+ωD−1(b−Axk)\vb{x}_{k+1} = \vb{x}_k + \omega\mat{D}\inv(\vb{b} - \mat{A}\vb{x}_k), with factors 1−ω+ωμij1 - \omega + \omega\mu_{ij}. For high-frequency modes (those with max⁡(i,j)≥(m+1)/2\max(i,j) \ge (m+1)/2), μij∈[−1,12]\mu_{ij} \in [-1, \tfrac12], and with ω=2/3\omega = 2/3 factors lie in [−13,23][-\tfrac13, \tfrac23]: each iteration reduces short waves by at least a third. Long waves with μ≈1\mu \approx 1 still have factor ≈1\approx 1.

InteractiveRelaxing the Poisson equation
Error eke_k on the grid
blue negative, red positive; scaled at each step
Modes ∣e^ij∣\abs{\hat e_{ij}}: i↓i \downarrow, j→j \rightarrow
background color: negligible amplitude; blue: large
Method
k = 0
Poisson equation error on a 32×3232\times 32 grid starting from uniform noise. Left, the error field (scale adjusts each step to show its shape). Right, each sine mode's amplitude ∣e^ij∣\abs{\hat e_{ij}} on a fixed logarithmic scale: long waves in the upper left, short waves in the lower right. The figure begins at iteration 50 of weighted Jacobi: error has fallen to 8 % of its initial value, the field is already a superposition of smooth waves, and 99 % of energy lies in the 16 longest waves; press start and replay from noise. Those waves remain after 4000 iterations. Switch to pure Jacobi: at iteration 50, 40 % of energy is in the opposite corner, the checkerboard. Then try Gauss–Seidel and CG and compare the curves below (figures use the initial seed; another random error changes them slightly).

The curves tell the whole story. All three stationary methods fall quickly at first as they remove noise, then crawl with slope log⁡ρ\log\rho (on a logarithmic iteration axis the straight line looks like a late drop): with the initial seed, Gauss–Seidel falls below 10−810^{-8} at iteration 1727, pure Jacobi at 3459, and weighted Jacobi does not reach it in 4000. CG does in 98, as the rest of this lesson explains. This division of labor underlies multigrid: a few stationary iterations leave smooth error, well represented on a grid with twice the spacing, where long waves are no longer as long. See multigrid smoothing.

[ ]Jacobi and Gauss–Seidel on the model problemBrowser
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spla

def jacobi(A, b, tol=1e-6, maxiter=100_000, omega=1.0):
    d = A.diagonal()
    x = np.zeros_like(b)
    nb = np.linalg.norm(b)
    for k in range(maxiter):
        r = b - A @ x
        if np.linalg.norm(r) <= tol * nb:
            return x, k
        x = x + omega * r / d
    return x, maxiter

def gauss_seidel(A, b, tol=1e-6, maxiter=100_000):
    DL = sp.tril(A, format="csr")            # D + L
    U = sp.triu(A, k=1, format="csr")
    x = np.zeros_like(b)
    nb = np.linalg.norm(b)
    for k in range(maxiter):
        if np.linalg.norm(b - A @ x) <= tol * nb:
            return x, k
        x = spla.spsolve_triangular(DL, b - U @ x, lower=True)
    return x, maxiter

print(" m    Jacobi (pred.)   Gauss-Seidel (pred.)   Jacobi/(m+1)^2")
for m in [8, 16, 24]:
    A = poisson2d(m)
    b = np.ones(m * m)
    rho = np.cos(np.pi / (m + 1))
    _, kj = jacobi(A, b)
    _, kg = gauss_seidel(A, b)
    pj = np.log(1e-6) / np.log(rho)
    pg = np.log(1e-6) / np.log(rho**2)
    print(f"{m:2d}   {kj:5d} ({pj:5.0f})      {kg:5d} ({pg:5.0f})          {kj / (m + 1)**2:.2f}")

# rho(G) de Jacobi calculado frente a la fórmula, en m = 16
m = 16
A = poisson2d(m).toarray()
G = np.eye(m * m) - A / 4
print(f"\nm = 16: rho(G_J) = {np.max(np.abs(np.linalg.eigvals(G))):.6f}, cos(pi h) = {np.cos(np.pi / 17):.6f}")

Measured iteration counts closely follow prediction ln⁡(10−6)/ln⁡ρ\ln(10^{-6})/\ln\rho, Gauss–Seidel needs half as many as Jacobi, and the ratio of Jacobi iterations to (m+1)2(m+1)^2 stabilizes: cost grows as m2=nm^2 = n iterations, each costing O(n)\bigO(n). We need to do better.

Krylov subspaces

Consider the space containing a Jacobi iterate. With x0=0\vb{x}_0 = \vb{0} and D=4I\mat{D} = 4\mat{I}, xk\vb{x}_k is a combination of b,Ab,…,Ak−1b\vb{b}, \mat{A}\vb{b}, \dots, \mat{A}^{k-1}\vb{b}, with coefficients fixed in advance by the method. The same holds for any method using A\mat{A} only through products. Naturally, since the iterate belongs to that space, why not choose its best element?

The spaces grow with kk until they stabilize; at that point the solution is guaranteed to lie inside.

Proof

If Kd+1=Kd\mathcal{K}_{d+1} = \mathcal{K}_d, then Adr0=∑j<dcjAjr0\mat{A}^d\vb{r}_0 = \sum_{j<d}c_j\mat{A}^j\vb{r}_0, and by induction AKd⊆Kd\mat{A}\mathcal{K}_d \subseteq \mathcal{K}_d. Since A\mat{A} is invertible, A\mat{A} restricted to Kd\mathcal{K}_d is injective and thus bijective, so r0=Az\vb{r}_0 = \mat{A}\vb{z} for some z∈Kd\vb{z} \in \mathcal{K}_d; that z\vb{z} is A−1r0=x∗−x0\mat{A}\inv\vb{r}_0 = \vb{x}^* - \vb{x}_0. For the bound, write r0=∑ℓvℓ\vb{r}_0 = \sum_{\ell}\vb{v}_\ell as the sum of components in eigenspaces of the ss distinct eigenvalues λℓ\lambda_\ell present. Polynomial p(z)=∏ℓ(z−λℓ)p(z) = \prod_\ell (z - \lambda_\ell) of degree ss annihilates each component, so p(A)r0=0p(\mat{A})\vb{r}_0 = \vb{0}: Asr0\mat{A}^s\vb{r}_0 is a combination of lower powers and d≤sd \le s.

∎

This theorem is the key to everything that follows: if the spectrum has few distinct values or few clusters, a well-chosen Krylov method finishes quickly.

Arnoldi and Lanczos bases

Basis r0,Ar0,A2r0,…\vb{r}_0, \mat{A}\vb{r}_0, \mat{A}^2\vb{r}_0, \dots is the worst possible to work with: vectors align with the dominant eigenvector, exactly as in power iteration, and become nearly parallel. They must be orthonormalized as they are generated. Arnoldi iteration (1951) uses modified Gram–Schmidt, the stable version studied in Gram–Schmidt stability:

  1. q1=r0/∥r0∥\vb{q}_1 = \vb{r}_0/\norm{\vb{r}_0}.
  2. For j=1,2,…j = 1, 2, \dots: w=Aqj\vb{w} = \mat{A}\vb{q}_j; for i=1,…,ji = 1, \dots, j: hij=qi⊤wh_{ij} = \vb{q}_i\T\vb{w} and w←w−hijqi\vb{w} \leftarrow \vb{w} - h_{ij}\vb{q}_i. Then hj+1,j=∥w∥h_{j+1,j} = \norm{\vb{w}} and qj+1=w/hj+1,j\vb{q}_{j+1} = \vb{w}/h_{j+1,j}.

After kk steps, Qk+1=[q1⋯qk+1]\mat{Q}_{k+1} = [\vb{q}_1 \cdots \vb{q}_{k+1}] is an orthonormal basis of Kk+1\mathcal{K}_{k+1} and coefficients form Hessenberg matrix H~k∈R(k+1)×k\tilde{\mat{H}}_k \in \R^{(k+1)\times k} (zeros below the first subdiagonal) with

AQk=Qk+1H~k,Qk⊤AQk=Hk  (las k primeras filas de H~k).\mat{A}\mat{Q}_k = \mat{Q}_{k+1}\tilde{\mat{H}}_k, \qquad \mat{Q}_k\T\mat{A}\mat{Q}_k = \mat{H}_k \;(\text{las } k \text{ primeras filas de } \tilde{\mat{H}}_k).

Step jj costs one product with A\mat{A} and jj dot products: cost and memory grow with kk.

If A\mat{A} is symmetric, so is Hk=Qk⊤AQk\mat{H}_k = \mat{Q}_k\T\mat{A}\mat{Q}_k, and a symmetric Hessenberg matrix is tridiagonal. Almost all hijh_{ij} vanish by construction and an Arnoldi step reduces to a three-term recurrence: Lanczos iteration (1950),

βjqj+1=Aqj−αjqj−βj−1qj−1,αj=qj⊤Aqj,\beta_j\vb{q}_{j+1} = \mat{A}\vb{q}_j - \alpha_j\vb{q}_j - \beta_{j-1}\vb{q}_{j-1}, \qquad \alpha_j = \vb{q}_j\T\mat{A}\vb{q}_j,

with Tk=Qk⊤AQk=tridiag⁡(β,α,β)\mat{T}_k = \mat{Q}_k\T\mat{A}\mat{Q}_k = \operatorname{tridiag}(\beta, \alpha, \beta). The basis need not be stored to continue: constant cost and memory per step. Eigenvalues of Tk\mat{T}_k, the Ritz values, approximate extreme eigenvalues of A\mat{A} long before k=nk = n, sooner when better separated from the rest (Kaniel, Paige and Saad quantify this with Chebyshev polynomials, as for CG). Lanczos is thus standard for a few eigenvalues of a large symmetric matrix (the previous lesson’s symmetric methods use dense matrices; this uses products).

The short recurrence has a floating-point price: qj\vb{q}_j lose orthogonality. Paige (1971) proved this is neither accidental nor uncontrolled error: orthogonality is lost precisely in directions of Ritz vectors that have already converged. The method then “rediscovers” that eigenvalue and spurious copies, ghost eigenvalues, appear. See the second lab.

Conjugate gradient

For symmetric positive definite A\mat{A}, solving Ax=b\mat{A}\vb{x} = \vb{b} is equivalent to minimizing the quadratic form

ϕ(x)=12x⊤Ax−b⊤x,∇ϕ(x)=Ax−b=−r,\phi(\vb{x}) = \tfrac12\vb{x}\T\mat{A}\vb{x} - \vb{b}\T\vb{x}, \qquad \grad\phi(\vb{x}) = \mat{A}\vb{x} - \vb{b} = -\vb{r},

because ϕ\phi is strictly convex and its only critical point is x∗\vb{x}^*. Some algebra gives ϕ(x)−ϕ(x∗)=12∥x−x∗∥A2\phi(\vb{x}) - \phi(\vb{x}^*) = \tfrac12\norm{\vb{x} - \vb{x}^*}_A^2, where ∥v∥A=v⊤Av\norm{\vb{v}}_A = \sqrt{\vb{v}\T\mat{A}\vb{v}} is the energy norm. Minimizing ϕ\phi minimizes error in AA norm.

Steepest descent and its zigzag

The obvious idea is to move along the residual, −∇ϕ=rk-\grad\phi = \vb{r}_k, with a step minimizing ϕ\phi on that line: αk=rk⊤rk/rk⊤Ark\alpha_k = \vb{r}_k\T\vb{r}_k / \vb{r}_k\T\mat{A}\vb{r}_k. With this exact step the new residual is orthogonal to the previous one (rk+1⊤rk=0\vb{r}_{k+1}\T\vb{r}_k = 0): each step turns 90°90° relative to the last. Kantorovich proved the bound

∥ek+1∥A≤κ−1κ+1∥ek∥A,κ=λmax⁡λmin⁡,\norm{\vb{e}_{k+1}}_A \le \frac{\kappa - 1}{\kappa + 1}\norm{\vb{e}_k}_A, \qquad \kappa = \frac{\lambda_{\max}}{\lambda_{\min}},

where κ\kappa is the condition number of A\mat{A}. With κ=100\kappa = 100, each step guarantees only factor 0.980.98.

InteractiveConjugate gradient versus steepest descent
  • steepest descent
  • conjugate gradient (2 steps)
  • contours of ϕ\phi
10.0
Steepest descent: iterations to 10−610^{-6}69
Steepest descent: average factor per step0.818
Bound (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1)0.818
CG: ∥e1∥A/∥e0∥A\norm{\vb{e}_1}_A / \norm{\vb{e}_0}_A, ∥e2∥A/∥e0∥A\norm{\vb{e}_2}_A / \norm{\vb{e}_0}_A0.818, 0
p0⊤Ap1\vb{p}_0\T\mat{A}\vb{p}_1 (normalized)0.000
On-screen angle between CG steps50.7°
On-screen angle between first two descent steps90.0°
Contours of ϕ(x)=12x⊤Ax\phi(\vb{x}) = \tfrac12\vb{x}\T\mat{A}\vb{x} (solution x∗=0\vb{x}^* = \vb{0}) for symmetric positive definite 2×22\times 2 matrix A\mat{A} with condition number κ\kappa you choose. Red is steepest descent with exact steps: each segment is perpendicular to the previous one and the path zigzags. Blue is conjugate gradient: it reaches x∗\vb{x}^* in two exact steps. Initial x0\vb{x}_0 is worst for descent (its residual has equal components in both eigenvectors), where average per-step factor matches bound (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1); increase κ\kappa and watch iterations rise. Drag x0\vb{x}_0 to an ellipse axis: descent improves greatly, CG still needs two steps. Select the A metric: the plane is transformed by A1/2\mat{A}^{1/2}, ellipses become circles, CG's steps appear perpendicular and descent's no longer do.

The figure’s transformation captures the idea. In coordinates y=A1/2x\vb{y} = \mat{A}^{1/2}\vb{x} the function is 12∥y∥2−…\tfrac12\norm{\vb{y}}^2 - \ldots, with circular contours; for a circular problem, move in orthogonal directions and take the exact step in each: nn steps finish it. Returning to x\vb{x}, orthogonality in y\vb{y} means pi⊤Apj=0\vb{p}_i\T\mat{A}\vb{p}_j = 0: directions conjugate with respect to A\mat{A}.

Derivation

Seek xk∈x0+Kk\vb{x}_k \in \vb{x}_0 + \mathcal{K}_k minimizing ∥x−x∗∥A\norm{\vb{x} - \vb{x}^*}_A over the whole Krylov space. Given a basis p0,…,pk−1\vb{p}_0, \dots, \vb{p}_{k-1} of Kk\mathcal{K}_k that is A\mat{A}-conjugate (pi⊤Apj=0\vb{p}_i\T\mat{A}\vb{p}_j = 0 for i≠ji \neq j), write x=x0+∑jcjpj\vb{x} = \vb{x}_0 + \sum_j c_j\vb{p}_j:

ϕ(x)=ϕ(x0)+∑j(12cj2 pj⊤Apj−cj pj⊤r0).\phi(\vb{x}) = \phi(\vb{x}_0) + \sum_j\Big(\tfrac12 c_j^2\,\vb{p}_j\T\mat{A}\vb{p}_j - c_j\,\vb{p}_j\T\vb{r}_0\Big).

Cross terms vanish: the problem decouples into kk one-variable minimizations, cj=pj⊤r0/pj⊤Apjc_j = \vb{p}_j\T\vb{r}_0 / \vb{p}_j\T\mat{A}\vb{p}_j, and already computed cjc_j do not change when adding a direction. Thus the minimum over Kk+1\mathcal{K}_{k+1} follows from the minimum over Kk\mathcal{K}_k in one step, xk+1=xk+αkpk\vb{x}_{k+1} = \vb{x}_k + \alpha_k\vb{p}_k. The minimum condition also says the residual is orthogonal to the entire space: rk⊥Kk\vb{r}_k \perp \mathcal{K}_k (the Galerkin condition).

Directions still need to be constructed cheaply. Hestenes and Stiefel conjugate the new residual against the previous direction: pk=rk+βk−1pk−1\vb{p}_k = \vb{r}_k + \beta_{k-1}\vb{p}_{k-1}, choosing βk−1\beta_{k-1} so pk⊤Apk−1=0\vb{p}_k\T\mat{A}\vb{p}_{k-1} = 0. Remarkably this suffices: pk\vb{p}_k is conjugate to all previous directions. For j≤k−2j \le k - 2, Apj∈Kj+2⊆Kk\mat{A}\vb{p}_j \in \mathcal{K}_{j+2} \subseteq \mathcal{K}_k and rk⊥Kk\vb{r}_k \perp \mathcal{K}_k, so rk⊤Apj=0\vb{r}_k\T\mat{A}\vb{p}_j = 0, and pk−1⊤Apj=0\vb{p}_{k-1}\T\mat{A}\vb{p}_j = 0 by induction. Symmetry of A\mat{A} permits forgetting the past; the same phenomenon turns Arnoldi into Lanczos.

The formulas for αk\alpha_k and βk\beta_k simplify pk⊤rk/pk⊤Apk\vb{p}_k\T\vb{r}_k/\vb{p}_k\T\mat{A}\vb{p}_k and −rk+1⊤Apk/pk⊤Apk-\vb{r}_{k+1}\T\mat{A}\vb{p}_k/\vb{p}_k\T\mat{A}\vb{p}_k using the next theorem’s orthogonality relations; you will prove them in the guided exercise.

Hestenes and Stiefel presented it in 1952 as a direct method finishing in nn steps. It does not finish in floating point and was little used for nearly twenty years. Reid (1971) rehabilitated it as what it is in practice: an iterative method giving a good approximation long before nn steps when A\mat{A} is large and sparse.

Convergence: polynomials, κ\sqrt\kappa and spectral shape

Since xk−x0∈Kk\vb{x}_k - \vb{x}_0 \in \mathcal{K}_k, error is ek=e0+q(A)r0=(I−q(A)A)e0=pk(A)e0\vb{e}_k = \vb{e}_0 + q(\mat{A})\vb{r}_0 = (\mat{I} - q(\mat{A})\mat{A})\vb{e}_0 = p_k(\mat{A})\vb{e}_0, with pkp_k a polynomial of degree ≤k\le k and pk(0)=1p_k(0) = 1. CG optimality says it chooses the best:

∥ek∥A=min⁡p∈Pkp(0)=1∥p(A)e0∥A≤min⁡p∈Pkp(0)=1  max⁡λ∈σ(A)∣p(λ)∣  ∥e0∥A.\norm{\vb{e}_k}_A = \min_{\substack{p \in \mathcal{P}_k\\ p(0) = 1}}\norm{p(\mat{A})\vb{e}_0}_A \le \min_{\substack{p \in \mathcal{P}_k\\ p(0) = 1}}\;\max_{\lambda \in \sigma(\mat{A})}\abs{p(\lambda)}\;\norm{\vb{e}_0}_A.

The inequality follows by writing e0=∑icivi\vb{e}_0 = \sum_i c_i\vb{v}_i in the orthonormal eigenvector basis: ∥p(A)e0∥A2=∑iλici2p(λi)2≤max⁡ip(λi)2 ∥e0∥A2\norm{p(\mat{A})\vb{e}_0}_A^2 = \sum_i\lambda_i c_i^2 p(\lambda_i)^2 \le \max_i p(\lambda_i)^2\,\norm{\vb{e}_0}_A^2. CG convergence is a polynomial approximation problem: find a degree-kk polynomial equal to 1 at the origin and small at all eigenvalues. Two immediate consequences:

  • Few distinct eigenvalues. If A\mat{A} has ss distinct eigenvalues, p(λ)=∏ℓ(1−λ/λℓ)p(\lambda) = \prod_\ell(1 - \lambda/\lambda_\ell) has degree ss, equals 1 at 0 and vanishes on the whole spectrum: CG finishes in ss steps.
  • Clustered eigenvalues. If the spectrum lies in ss narrow clusters, the same polynomial is small on all of them and CG converges in a few iterations per cluster.

If all you know is that the spectrum lies in [λmin⁡,λmax⁡][\lambda_{\min}, \lambda_{\max}], the best polynomial for the whole interval is a rescaled Chebyshev polynomial, p(λ)=Tk ⁣(λmax⁡+λmin⁡−2λλmax⁡−λmin⁡)/Tk(z0)p(\lambda) = T_k\!\big(\tfrac{\lambda_{\max} + \lambda_{\min} - 2\lambda}{\lambda_{\max} - \lambda_{\min}}\big)\big/T_k(z_0) with z0=κ+1κ−1z_0 = \tfrac{\kappa + 1}{\kappa - 1}. On the interval its numerator lies between −1-1 and 11, so the maximum is 1/Tk(z0)1/T_k(z_0). For z≥1z \ge 1, Tk(z)=12[(z+z2−1)k+(z−z2−1)k]≥12(z+z2−1)kT_k(z) = \tfrac12\big[(z + \sqrt{z^2 - 1})^k + (z - \sqrt{z^2-1})^k\big] \ge \tfrac12(z + \sqrt{z^2-1})^k, and with z0z_0:

z0+z02−1=κ+1+2κκ−1=(κ+1)2(κ+1)(κ−1)=κ+1κ−1.z_0 + \sqrt{z_0^2 - 1} = \frac{\kappa + 1 + 2\sqrt\kappa}{\kappa - 1} = \frac{(\sqrt\kappa + 1)^2}{(\sqrt\kappa + 1)(\sqrt\kappa - 1)} = \frac{\sqrt\kappa + 1}{\sqrt\kappa - 1}.

This gives the classical bound:

∥ek∥A∥e0∥A≤2(κ−1κ+1)k.\frac{\norm{\vb{e}_k}_A}{\norm{\vb{e}_0}_A} \le 2\left(\frac{\sqrt\kappa - 1}{\sqrt\kappa + 1}\right)^k.

Compare steepest descent: κ\sqrt\kappa instead of κ\kappa. To reduce error by factor ε\eps, descent needs about κ2ln⁡1ε\tfrac{\kappa}{2}\ln\tfrac1\eps iterations and CG about κ2ln⁡2ε\tfrac{\sqrt\kappa}{2}\ln\tfrac2\eps. For Poisson, κ=λmm/λ11≈4(m+1)2/π2\kappa = \lambda_{mm}/\lambda_{11} \approx 4(m+1)^2/\pi^2, so CG needs O(m)\bigO(m) iterations versus Jacobi’s O(m2)\bigO(m^2). But the bound only uses spectral extremes, which limits it.

InteractiveDesign the spectrum and watch CG converge
  • eigenvalues λi\lambda_i (log scale)
  • residual polynomial Rk(λ)R_k(\lambda), Rk(0)=1R_k(0) = 1
  • CG: ‖e_k‖_A / ‖e_0‖_A
  • bound 2((√κ−1)/(√κ+1))^k
Spectrum
3
± 0.01
6
nn eigenvalues36
κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min}1047.1
CG: iterations to 10−810^{-8}25
κ\sqrt{\kappa} bound: iterations310
max⁡i∣Rk(λi)∣\max_i \abs{R_k(\lambda_i)}1.757
CG needs 25 iterations; the κ\sqrt{\kappa} bound predicts 310. Spectrum shape matters more than κ\kappa.
Top: eigenvalues of a diagonal matrix on a logarithmic scale (blue ticks; circles below are cluster handles), and CG's residual polynomial after kk steps, Rk(λ)R_k(\lambda), with ek=Rk(A)e0\vb{e}_k = R_k(\mat{A})\vb{e}_0 and Rk(0)=1R_k(0) = 1. Bottom: relative AA-norm error versus the κ\sqrt\kappa bound (dashed). Initially there are three clusters of 12 eigenvalues, each width ±1 %\pm 1\,\%, with κ≈1050\kappa \approx 1050: CG converges in 25 iterations, the bound requires 310. Move kk from 0: initial polynomial roots miss the clusters, but by k=6k = 6 there is one in each. Set width to 0 (CG finishes in 3 steps), then widen it; drag the handles. Select Distributed to see when the bound is accurate, Outliers to see each isolated eigenvalue's cost, and 2D Poisson to compare preconditioners. Model: b\vb{b} has equal components in every eigenvector and x0=0\vb{x}_0 = \vb{0}.

The figure shows three distinct regimes:

  1. Spectrum filling the interval. With 500 eigenvalues at Chebyshev nodes of [1,κ][1, \kappa], the κ\sqrt\kappa bound is nearly exact (with κ=1000\kappa = 1000, 297 iterations versus 302): eigenvalues are everywhere and the Chebyshev polynomial is almost optimal.
  2. Clustered spectrum. CG eventually places roots on each cluster, and iteration count depends on relative cluster width, not κ\kappa. Zero width (three distinct values) takes 3 iterations; with ±1 %\pm 1\,\%, 25 versus the bound’s 310.
  3. A few outliers. With 200 eigenvalues in [1,2][1, 2], CG needs 11 iterations; adding outliers at 10210^2, 10310^3, 103.510^{3.5} and 10410^4 sends κ\kappa and the bound soaring (11 to 956), but iterations only rise to 13, 16, 19 and 23. In exact arithmetic each outlier costs at most one iteration (the polynomial dedicates a root to it): full reorthogonalization, mimicking exact arithmetic, gives 12, 13, 14 and 15. The difference is the orthogonality loss described next. A preconditioner leaving a few isolated eigenvalues can still be excellent.

These figures come from the model used by the figure, reproducible here:

[ ]The spectrum figure's modelBrowser
import numpy as np

def cg_diagonal(lam, tol=1e-8, maxiter=600, reortogonalizar=False):
    """CG sobre diag(lam) con b = 1 y x0 = 0; devuelve la primera k con ||e_k||_A <= tol ||e_0||_A."""
    lam = np.asarray(lam, dtype=float)
    xs = 1 / lam
    x = np.zeros_like(lam); r = np.ones_like(lam); p = r.copy(); rr = r @ r
    e0 = np.sqrt(np.sum(lam * xs**2))
    P = []
    for k in range(1, maxiter + 1):
        if reortogonalizar:                       # conjuga p contra todas las direcciones anteriores
            for q in P:
                p = p - (q @ (lam * p)) / (q @ (lam * q)) * q
            P.append(p.copy())
        Ap = lam * p
        alpha = (r @ p if reortogonalizar else rr) / (p @ Ap)
        x += alpha * p
        r = 1 - lam * x if reortogonalizar else r - alpha * Ap
        if np.sqrt(np.sum(lam * (x - xs) ** 2)) <= tol * e0:
            return k
        rr_nuevo = r @ r
        p = r + (rr_nuevo / rr) * p
        rr = rr_nuevo
    return None

def cota(kappa, tol=1e-8):
    s = np.sqrt(kappa)
    return int(np.ceil(np.log(tol / 2) / np.log((s - 1) / (s + 1))))

for ancho in [0.0, 0.01]:
    lam = [10 ** (c + ancho * (2 * i / 11 - 1)) for c in [0, 1.5, 3] for i in range(12)]
    print(f"tres grupos, anchura ±{ancho:4.2f} décadas: CG {cg_diagonal(lam)}, cota {cota(max(lam) / min(lam))}")
kappa = 1000
lam = (kappa + 1) / 2 - (kappa - 1) / 2 * np.cos(np.pi * (np.arange(500) + 0.5) / 500)
print(f"500 nodos de Chebyshev en [1, 1000]: CG {cg_diagonal(lam)}, cota {cota(lam[-1] / lam[0])}")
base = list(1 + np.arange(200) / 199)
atipicos = [1e2, 1e3, 10**3.5, 1e4]
for s in range(5):
    lam = base + atipicos[:s]
    print(f"{s} atípicos: CG {cg_diagonal(lam)}, con reortogonalización {cg_diagonal(lam, reortogonalizar=True)}, "
          f"cota {cota(max(lam) / min(lam))}")

This behavior, where convergence accelerates as Ritz values capture extreme eigenvalues, is called superlinear convergence and was analyzed by van der Sluis and van der Vorst (1986).

[ ]CG from scratch on the Poisson problemBrowser
import numpy as np

def cg(A_mv, b, tol=1e-8, maxiter=None):
    """Gradiente conjugado con x0 = 0. A_mv(v) devuelve A v. Criterio: ||r|| <= tol ||b||."""
    n = len(b)
    maxiter = maxiter or 10 * n
    x = np.zeros(n)
    r = b.copy()
    p = r.copy()
    rr = r @ r
    nb = np.linalg.norm(b)
    historia = [1.0]
    for k in range(1, maxiter + 1):
        Ap = A_mv(p)
        alpha = rr / (p @ Ap)
        x += alpha * p
        r -= alpha * Ap
        rr_nuevo = r @ r
        historia.append(np.sqrt(rr_nuevo) / nb)
        if historia[-1] <= tol:
            break
        p = r + (rr_nuevo / rr) * p
        rr = rr_nuevo
    return x, np.array(historia)

print("  m      n    iteraciones   iter/(m+1)   cota sqrt(kappa) para 1e-8")
for m in [16, 32, 64, 128]:
    A = poisson2d(m)
    b = np.ones(m * m)
    x, h = cg(lambda v: A @ v, b)
    kappa = (np.sin(m * np.pi / (2 * (m + 1))) / np.sin(np.pi / (2 * (m + 1)))) ** 2
    cota = np.ceil(np.log(1e-8 / 2) / np.log((np.sqrt(kappa) - 1) / (np.sqrt(kappa) + 1)))
    res = np.linalg.norm(b - A @ x) / np.linalg.norm(b)
    print(f"{m:4d} {m*m:6d}   {len(h) - 1:6d}       {(len(h) - 1) / (m + 1):.2f}       {cota:6.0f}   (kappa = {kappa:7.1f}, residuo {res:.1e})")

# en coma flotante CG no termina en n pasos: 48 autovalores muy desigualmente repartidos (Strakoš)
nS = 48
i = np.arange(1, nS + 1)
lam = 0.1 + (i - 1) / (nS - 1) * (100 - 0.1) * 0.8 ** (nS - i)
_, hS = cg(lambda v: lam * v, np.ones(nS), tol=1e-10, maxiter=500)
print(f"\nmatriz diagonal de Strakoš con n = {nS}: CG necesita {len(hS) - 1} iteraciones para 1e-10")

Iterations grow linearly with mm (column “iter/(m+1)” is nearly constant), as κ≈2(m+1)/π\sqrt\kappa \approx 2(m+1)/\pi predicts, and remain below the bound due to superlinear convergence. With m=128m = 128, 16 38416\,384 unknowns are solved in a few hundred matrix-vector products; Jacobi would need order 2.8×1292⋅ln⁡(108)/ln⁡(106)≈6⋅1042.8 \times 129^2 \cdot \ln(10^8)/\ln(10^6) \approx 6\cdot 10^4. The final line shows floating-point effects: Strakoš’s matrix has eigenvalues tightly clustered near 0.10.1 and widely separated near 100100, and CG needs more iterations than its dimension, impossible in exact arithmetic.

GMRES and methods for nonsymmetric matrices

If A\mat{A} is nonsymmetric, ϕ\phi no longer makes sense (its gradient would be 12(A+A⊤)x−b\tfrac12(\mat{A} + \mat{A}\T)\vb{x} - \vb{b}), and AA norm does not exist. The natural criterion becomes the residual.

H~k\tilde{\mat{H}}_k is Hessenberg, so its QR is updated at each step with one Givens rotation, and residual norm comes for free without forming xk\vb{x}_k. GMRES residual never grows and in exact arithmetic it terminates in at most nn steps. Cost is the problem: Arnoldi step kk costs O(kn)\bigO(kn) and stores kk vectors of length nn. With n=106n = 10^6 and k=500k = 500 the basis occupies 4 GB.

The practical solution is restart: GMRES(rr) takes rr steps, computes xr\vb{x}_r, uses it as new x0\vb{x}_0 and discards the basis. Memory is bounded, but global optimality is lost and stagnation is possible: if residual does not fall in a cycle of rr steps, it never will (the classic example is a cyclic permutation matrix with r<nr < n). Choosing rr is a tradeoff without a universal rule; SciPy defaults to 20.

Why not a short-recurrence method like CG for the nonsymmetric case? Faber and Manteuffel (1984) proved none exists: a Krylov method with fixed-length recurrences that also minimizes error in a fixed norm exists, apart from exceptional cases, only for matrices of form eiθ(T+σI)e^{i\theta}(\mat{T} + \sigma\mat{I}) with T\mat{T} Hermitian (in that inner product): essentially symmetric matrices. Choose between optimality (GMRES, growing cost) and short recurrences without optimality:

  • MINRES (Paige and Saunders, 1975): for symmetric indefinite matrices. Minimizes residual like GMRES, but uses the Lanczos basis and short recurrences.
  • BiCGSTAB (van der Vorst, 1992): for nonsymmetric matrices, constant memory. It starts from BiCG, which recovers short recurrences by giving up orthogonality (using Petrov–Galerkin conditions with a second Krylov space, that of A⊤\mat{A}\T), avoids products with A⊤\mat{A}\T and smooths BiCG’s irregular convergence with a local minimum-residual step. It uses two products with A\mat{A} per iteration, minimizes nothing globally and can break down, but is cheap when it works.

GMRES convergence can also be written with polynomials: ∥rk∥=min⁡p(0)=1∥p(A)r0∥\norm{\vb{r}_k} = \min_{p(0) = 1}\norm{p(\mat{A})\vb{r}_0}, and if A=VΛV−1\mat{A} = \mat{V}\mat{\Lambda}\mat{V}\inv is diagonalizable,

∥rk∥2∥r0∥2≤κ2(V)min⁡p(0)=1max⁡λ∈σ(A)∣p(λ)∣.\frac{\norm{\vb{r}_k}_2}{\norm{\vb{r}_0}_2} \le \kappa_2(\mat{V})\min_{p(0)=1}\max_{\lambda\in\sigma(\mat{A})}\abs{p(\lambda)}.

For normal matrices, κ2(V)=1\kappa_2(\mat{V}) = 1 and eigenvalues tell the whole story. For highly non-normal matrices they do not: Greenbaum, Pták and Strakoš (1996) proved any nonincreasing GMRES convergence curve is possible with any eigenvalue set. Eigenvalues of a non-normal matrix may say nothing about GMRES.

[ ]GMRES from scratch and CG on a nonsymmetric matrixBrowser
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spla

def conveccion_difusion(m, c):
    """-Δu + c (u_x + u_y) en la malla m x m, convección con diferencias hacia atrás (upwind)."""
    h = 1 / (m + 1)
    T = sp.diags([-1.0, 2.0, -1.0], [-1, 0, 1], shape=(m, m))
    B = sp.diags([-1.0, 1.0], [-1, 0], shape=(m, m))
    I = sp.identity(m)
    return (sp.kron(I, T) + sp.kron(T, I) + c * h * (sp.kron(I, B) + sp.kron(B, I))).tocsr()

def gmres_desde_cero(A_mv, b, k_max, tol=1e-8):
    """GMRES sin reinicio con x0 = 0: Arnoldi (Gram-Schmidt modificado) y mínimos cuadrados con H."""
    n = len(b)
    beta = np.linalg.norm(b)
    Q = np.zeros((n, k_max + 1))
    H = np.zeros((k_max + 1, k_max))
    Q[:, 0] = b / beta
    residuos = [1.0]
    for j in range(k_max):
        w = A_mv(Q[:, j])
        for i in range(j + 1):
            H[i, j] = Q[:, i] @ w
            w -= H[i, j] * Q[:, i]
        H[j + 1, j] = np.linalg.norm(w)
        Q[:, j + 1] = w / H[j + 1, j]
        e1 = np.zeros(j + 2); e1[0] = beta
        y = np.linalg.lstsq(H[: j + 2, : j + 1], e1, rcond=None)[0]
        residuos.append(np.linalg.norm(e1 - H[: j + 2, : j + 1] @ y) / beta)
        if residuos[-1] <= tol:
            break
    return Q[:, : j + 1] @ y, np.array(residuos), Q[:, : j + 2], H[: j + 2, : j + 1]

m, c = 64, 100
A = conveccion_difusion(m, c)
b = np.ones(m * m)
print(f"n = {m * m}, ||A - Aᵀ||_F / ||A||_F = {spla.norm(A - A.T) / spla.norm(A):.2f}")

x, res, Q, H = gmres_desde_cero(lambda v: A @ v, b, 300)
print(f"GMRES desde cero: {len(res) - 1} iteraciones, residuo real {np.linalg.norm(b - A @ x) / np.linalg.norm(b):.1e}")
print(f"  comprobaciones: ||A Q_k - Q_(k+1) H|| = {np.linalg.norm(A @ Q[:, :-1] - Q @ H):.1e},  ||QᵀQ - I|| = {np.linalg.norm(Q.T @ Q - np.eye(Q.shape[1])):.1e}")

# CG aplicado a una matriz no simétrica: no hay ninguna garantía
cuenta = [0]
x_cg, info = spla.cg(A, b, rtol=1e-8, maxiter=2000, callback=lambda xk: cuenta.__setitem__(0, cuenta[0] + 1))
print(f"CG (scipy) en la matriz no simétrica: {cuenta[0]} iteraciones, info = {info}, residuo {np.linalg.norm(b - A @ x_cg) / np.linalg.norm(b):.1e}")

def iteraciones_gmres(A, b, restart, M=None):
    cuenta = [0]
    x, info = spla.gmres(A, b, rtol=1e-8, restart=restart, maxiter=500, M=M,
                         callback=lambda r: cuenta.__setitem__(0, cuenta[0] + 1), callback_type="pr_norm")
    return cuenta[0], info, np.linalg.norm(b - A @ x) / np.linalg.norm(b)

for r in [10, 30, 300]:
    it, info, rr = iteraciones_gmres(A, b, r)
    print(f"GMRES({r:3d}) de scipy: {it:4d} iteraciones, info = {info}, residuo {rr:.1e}")
cuenta = [0]
x_b, info = spla.bicgstab(A, b, rtol=1e-8, maxiter=2000, callback=lambda xk: cuenta.__setitem__(0, cuenta[0] + 1))
print(f"BiCGSTAB: {cuenta[0]} iteraciones (dos productos con A en cada una), info = {info}")

The cell prints:

  • Scratch GMRES and unrestarted SciPy GMRES agree: 138 iterations each. Arnoldi’s relation holds to machine precision (4⋅10−144\cdot 10^{-14}), but the basis is not orthonormal to that precision: ∥Q⊤Q−I∥≈2⋅10−3\norm{\mat{Q}\T\mat{Q} - \mat{I}} \approx 2\cdot 10^{-3}. This is modified Gram–Schmidt’s loss of orthogonality, growing as residual falls. It is not serious: Paige, Rozložník and Strakoš (2006) proved modified-Gram–Schmidt GMRES is backward stable despite it, confirmed by the true residual.
  • CG diverges on the nonsymmetric matrix. It does not raise an error: it returns info > 0 (tolerance not reached) and a huge residual. Ignoring info risks using a meaningless result.
  • Restarting costs iterations, but not monotonically: GMRES(10) can require fewer total iterations than GMRES(30) on this matrix, though neither beats full GMRES. Each GMRES(rr) iteration is cheaper for smaller rr.

Preconditioning

With convergence tied to the spectrum, the idea is to replace the system with an equivalent one having a better spectrum. If M≈A\mat{M} \approx \mat{A} and solving with M\mat{M} is cheap, M−1Ax=M−1b\mat{M}\inv\mat{A}\vb{x} = \mat{M}\inv\vb{b} has the same solution, and if M−1A≈I\mat{M}\inv\mat{A} \approx \mat{I} its spectrum clusters near 1.

The extremes clarify the tradeoff: M=I\mat{M} = \mat{I} is free and does not help; M=A\mat{M} = \mat{A} solves in one iteration, but applying it solves the original problem. Useful preconditioners lie between.

For CG there is a subtlety: M−1A\mat{M}\inv\mat{A} is not symmetric. If M\mat{M} is symmetric positive definite with M=LL⊤\mat{M} = \mat{L}\mat{L}\T, CG on A^=L−1AL−⊤\hat{\mat{A}} = \mat{L}\inv\mat{A}\mat{L}^{-\top} (symmetric, similar to M−1A\mat{M}\inv\mat{A}) can be rewritten in original variables, and L\mat{L} disappears. The result is preconditioned CG (PCG): like CG, with zk=M−1rk\vb{z}_k = \mat{M}\inv\vb{r}_k instead of rk\vb{r}_k in two places,

αk=rk⊤zkpk⊤Apk,βk=rk+1⊤zk+1rk⊤zk,pk+1=zk+1+βkpk.\alpha_k = \frac{\vb{r}_k\T\vb{z}_k}{\vb{p}_k\T\mat{A}\vb{p}_k}, \qquad \beta_k = \frac{\vb{r}_{k+1}\T\vb{z}_{k+1}}{\vb{r}_k\T\vb{z}_k}, \qquad \vb{p}_{k+1} = \vb{z}_{k+1} + \beta_k\vb{p}_k.

Its convergence is that of CG with κ(M−1A)\kappa(\mat{M}\inv\mat{A}) and the spectrum of M−1A\mat{M}\inv\mat{A}. M\mat{M} must be symmetric positive definite; a nonsymmetric preconditioner breaks the theory and, as you will see, practice.

Classical algebraic preconditioners, from cheapest to most expensive:

  • Jacobi: M=diag⁡(A)\mat{M} = \operatorname{diag}(\mat{A}). Free. Corrects scale differences among unknowns (different units, coefficients varying orders of magnitude), nothing more. With constant diagonal, as in Poisson, it does nothing.
  • Incomplete Cholesky IC(0) (Meijerink and van der Vorst, 1977): performs Cholesky but discards all fill, so L\mat{L} has the lower-triangular pattern of A\mat{A} and LL⊤\mat{L}\mat{L}\T agrees with A\mat{A} on that pattern. Applying it takes two sparse triangular solves. For M-matrices (such as Poisson) it exists and is positive definite; generally it can encounter nonpositive pivots, addressed by diagonal shifts like lesson 4’s jitter.
  • ILU (incomplete LU): the same for nonsymmetric matrices. ILU(0) preserves the pattern of A\mat{A}; ILUT drops entries below a relative threshold and limits fill per row. scipy.sparse.linalg.spilu calls SuperLU’s threshold ILU.
  • Beyond these: SSOR, sparse approximate inverses, algebraic multigrid (giving iteration counts independent of hh for elliptic problems), and problem-specific preconditioners.

Remember the criterion. A good preconditioner is not the one closest to A\mat{A} in norm, but the one that clusters the spectrum of M−1A\mat{M}\inv\mat{A}: if most eigenvalues lie near 1 and only a few are isolated, CG benefits even if κ\kappa remains large. In the spectrum figure, “2D Poisson” uses exact eigenvalues of the matrix for grid 24×2424\times 24 and the preconditioned ones computed in the next cell.

[ ]Spectra in the figure: Jacobi, IC(0), and a poorly scaled matrixBrowser
import numpy as np
import scipy.sparse as sp

def ic0(A):
    """Cholesky incompleta sin relleno: L con el patrón de tril(A), L Lᵀ = A en ese patrón."""
    Lo = sp.tril(A, format="csr")
    Lo.sort_indices()
    data, ind, ptr = Lo.data.copy(), Lo.indices, Lo.indptr
    n = A.shape[0]
    pos = [dict(zip(ind[ptr[i]:ptr[i + 1]].tolist(), range(ptr[i], ptr[i + 1]))) for i in range(n)]
    for i in range(n):
        for kk in range(ptr[i], ptr[i + 1]):
            j = ind[kk]
            s = data[kk]
            for k2 in range(ptr[i], kk):              # resta sum_{k<j} L[i,k] L[j,k] en el patrón
                q = pos[j].get(ind[k2])
                if q is not None:
                    s -= data[k2] * data[q]
            if j < i:
                data[kk] = s / data[ptr[j + 1] - 1]  # L[j,j] es la última entrada de la fila j
            else:
                if s <= 0:
                    raise ValueError(f"pivote no positivo en la fila {i}")
                data[kk] = np.sqrt(s)
    return sp.csr_matrix((data, ind, ptr), shape=A.shape)

m = 24
A = poisson2d(m)
n = m * m
L = ic0(A)
print("max |L Lᵀ - A| en el patrón de A:", abs((L @ L.T - A).multiply(A != 0)).max())
print("nnz(L) =", L.nnz, " nnz(tril(A)) =", sp.tril(A).nnz)

Ad = A.toarray()
Li = np.linalg.inv(L.toarray())
s = 10.0 ** np.random.default_rng(7).uniform(-1, 1, n)   # escalas de las incógnitas
casos = {
    "A (Poisson 24x24)": np.linalg.eigvalsh(Ad),
    "D⁻¹A (Jacobi)": np.linalg.eigvalsh(Ad / 4),
    "L⁻¹AL⁻ᵀ (IC(0))": np.linalg.eigvalsh(Li @ Ad @ Li.T),
    "SAS (mal escalada)": np.linalg.eigvalsh(s[:, None] * Ad * s[None, :]),
}
for nombre, ev in casos.items():
    dentro = np.mean(np.abs(ev / np.median(ev) - 1) < 0.25)
    print(f"{nombre:22s} λmin = {ev[0]:.4g}  λmax = {ev[-1]:.4g}  κ = {ev[-1] / ev[0]:9.1f}  "
          f"fracción a ±25 % de la mediana: {dentro:.2f}")

IC(0) reduces κ\kappa from 252.6 to 23.2 and, more importantly, clusters most eigenvalues around 1: the fraction within 25 % of the median rises from a minority to nearly all. Jacobi changes nothing for Poisson (it divides the spectrum by 4, and CG is invariant to that scaling). For poorly scaled SAS\mat{S}\mat{A}\mat{S} instead, with unknown scales between 0.10.1 and 1010, κ\kappa rises near 1.5⋅1051.5\cdot 10^5, and Jacobi exactly restores the spectrum of A/4\mat{A}/4: if DS=diag⁡(SAS)=4S2\mat{D}_S = \operatorname{diag}(\mat{S}\mat{A}\mat{S}) = 4\mat{S}^2, then DS−1/2SASDS−1/2=A/4\mat{D}_S^{-1/2}\mat{S}\mat{A}\mat{S}\mat{D}_S^{-1/2} = \mat{A}/4. IC(0) is also immune to this scaling: incomplete Cholesky of SAS\mat{S}\mat{A}\mat{S} is SL\mat{S}\mat{L}, and (SL)−1SAS(SL)−⊤=L−1AL−⊤(\mat{S}\mat{L})\inv\mat{S}\mat{A}\mat{S}(\mat{S}\mat{L})^{-\top} = \mat{L}\inv\mat{A}\mat{L}^{-\top}.

A literature-backed nuance: IC(0) improves the constant but not the order. For the model problem, κ(M−1A)\kappa(\mat{M}\inv\mat{A}) still grows like h−2h^{-2}; the modified MIC version, adding discarded entries to the diagonal, reduces it to O(h−1)\bigO(h^{-1}) (Gustafsson, 1978), and only multigrid keeps it bounded.

Now the full lab: CG and PCG with IC(0) from scratch versus SciPy as the grid grows.

[ ]A preconditioned CG Poisson solverBrowser
import time
import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spla

def pcg(A, b, M_inv=None, tol=1e-8, maxiter=10_000):
    x = np.zeros_like(b)
    r = b.copy()
    z = r if M_inv is None else M_inv(r)
    p = z.copy()
    rz = r @ z
    nb = np.linalg.norm(b)
    for k in range(1, maxiter + 1):
        Ap = A @ p
        alpha = rz / (p @ Ap)
        x += alpha * p
        r -= alpha * Ap
        if np.linalg.norm(r) <= tol * nb:
            return x, k
        z = r if M_inv is None else M_inv(r)
        rz, rz_viejo = r @ z, rz
        p = z + (rz / rz_viejo) * p
    return x, maxiter

print("   m       n    CG   PCG-IC(0)   t CG    t PCG (+IC0)   t spsolve   err vs spsolve")
for m in [32, 64, 128]:
    A = poisson2d(m)
    b = np.ones(m * m)
    t = time.perf_counter(); x1, k1 = pcg(A, b); t1 = time.perf_counter() - t
    t = time.perf_counter()
    L = ic0(A)
    LU_L = spla.splu(L.tocsc(), permc_spec="NATURAL", diag_pivot_thresh=0.0)  # L es triangular: sin relleno
    M_inv = lambda r: LU_L.solve(LU_L.solve(r), trans="T")                      # z = L⁻ᵀ (L⁻¹ r)
    x2, k2 = pcg(A, b, M_inv)
    t2 = time.perf_counter() - t
    t = time.perf_counter(); xs = spla.spsolve(A.tocsc(), b); ts = time.perf_counter() - t
    err = max(np.linalg.norm(x1 - xs), np.linalg.norm(x2 - xs)) / np.linalg.norm(xs)
    print(f"{m:4d} {m*m:7d}  {k1:4d}   {k2:6d}     {t1*1e3:6.0f} ms   {t2*1e3:6.0f} ms     {ts*1e3:6.0f} ms     {err:.1e}")

# Jacobi sí ayuda cuando las incógnitas están mal escaladas
m = 32
A = poisson2d(m)
s = 10.0 ** np.random.default_rng(7).uniform(-1, 1, m * m)
B = sp.diags(s) @ A @ sp.diags(s)
b = np.ones(m * m)
_, k_sin = pcg(B.tocsr(), b, maxiter=20_000)
d = B.diagonal()
_, k_jac = pcg(B.tocsr(), b, lambda r: r / d)
print(f"\nS A S con m = 32: CG {k_sin} iteraciones, PCG-Jacobi {k_jac}")
[ ]The SciPy version: cg, spsolve and spiluBrowser
import time
import numpy as np
import scipy.sparse.linalg as spla

def contador():
    c = [0]
    return c, (lambda *_: c.__setitem__(0, c[0] + 1))

print("   m   cg (scipy)          spilu + gmres(30)        spsolve")
for m in [32, 64, 128]:
    A = poisson2d(m)
    b = np.ones(m * m)
    c, cb = contador()
    t = time.perf_counter(); x, info = spla.cg(A, b, rtol=1e-8, callback=cb); tc = time.perf_counter() - t
    t = time.perf_counter()
    ilu = spla.spilu(A.tocsc(), drop_tol=1e-2, fill_factor=2, drop_rule="basic")
    M = spla.LinearOperator(A.shape, ilu.solve)
    c2, cb2 = contador()
    x2, info2 = spla.gmres(A, b, rtol=1e-8, restart=30, M=M, callback=cb2, callback_type="pr_norm")
    ti = time.perf_counter() - t
    t = time.perf_counter(); xs = spla.spsolve(A.tocsc(), b); ts = time.perf_counter() - t
    print(f"{m:4d}   {c[0]:4d} it {tc*1e3:6.0f} ms      {c2[0]:4d} it {ti*1e3:6.0f} ms        {ts*1e3:6.0f} ms")

# spilu NO es simétrico: no es un precondicionador válido para CG
m = 64
A = poisson2d(m)
b = np.ones(m * m)
u, v = np.random.default_rng(1).normal(size=(2, m * m))
for nombre, ilu in [("spilu por defecto", spla.spilu(A.tocsc())),
                    ("spilu drop_rule='basic'", spla.spilu(A.tocsc(), drop_tol=1e-2, fill_factor=2, drop_rule="basic"))]:
    asim = abs(u @ ilu.solve(v) - v @ ilu.solve(u)) / abs(u @ ilu.solve(v))
    c, cb = contador()
    x, info = spla.cg(A, b, rtol=1e-8, maxiter=1000, M=spla.LinearOperator(A.shape, ilu.solve), callback=cb)
    print(f"{nombre:24s} asimetría {asim:.1e}: cg hace {c[0]} iteraciones, info = {info}, "
          f"residuo {np.linalg.norm(b - A @ x) / np.linalg.norm(b):.1e}")

# y en el problema no simétrico de antes, ILU sí es la herramienta
A = conveccion_difusion(64, 100)
it0, info0, r0 = iteraciones_gmres(A, b, 30)
ilu = spla.spilu(A.tocsc(), drop_tol=1e-2, fill_factor=2, drop_rule="basic")
it1, info1, r1 = iteraciones_gmres(A, b, 30, spla.LinearOperator(A.shape, ilu.solve))
print(f"\nconvección-difusión: GMRES(30) {it0} iteraciones; con ILU {it1} (residuo {r1:.1e})")

Read the tables together:

  • Iterations. For Poisson, CG’s double when mm doubles (59, 119, 239), and IC(0)-PCG reduces them by slightly over half (29, 52, 100) with the same linear growth in mm, as theory says: IC(0) improves the constant, not the order. The poorly scaled matrix differs: CG needs 2792 iterations and Jacobi-PCG 108, because Jacobi exactly reverses scaling.
  • Time. In your browser IC(0)-PCG takes longer than unpreconditioned CG because building IC(0) with Python loops dominates (the CSR loop issue again). Compiled IC(0) costs of order one matrix-vector product and changes the comparison; iteration counts do not depend on implementation. The cell prints your run’s times.
  • Direct versus iterative. spsolve is competitive at these sizes: a 2D problem with 16 38416\,384 unknowns is small for well-reordered sparse LU. Iterative methods win in 3D, when nn is so large the factor cannot fit in memory, or when only matrix-vector products are available.
  • ILU with CG, a real mistake. spilu is not symmetric. With default parameters cg does not converge in 1000 iterations even though A\mat{A} is perfect; with simpler threshold ILU (drop_rule="basic") it converges in 70, worse than GMRES’s 19 with the same preconditioner. Occasional success is dangerous: nothing guarantees it. GMRES does not require symmetry, so ILU is appropriate; for convection-diffusion it reduces GMRES(30) from 275 iterations to 9.

Matrix-free operators

Krylov methods access A\mat{A} only through v↦Av\vb{v} \mapsto \mat{A}\vb{v}. The matrix itself is unnecessary: a function computing the product suffices.

This greatly extends the methods’ reach:

  • Grid stencils. Applying a Laplacian with array shifts stores no indices. GPU PDE solvers commonly work this way.
  • Hessian-vector products. In optimization a loss Hessian with 10810^8 parameters cannot be formed, but ∇2L⋅v\hess\Loss\cdot\vb{v} costs about two gradients (the Hessian-vector product, computed with automatic differentiation in lesson 16). CG solves the Newton system without forming the Hessian: Newton-CG.
  • Structured kernels. Scalable Gaussian processes solve (K+σ2I)α=y(\mat{K} + \sigma^2\mat{I})\vb{\alpha} = \vb{y} with preconditioned CG and Kv\mat{K}\vb{v} products computed in GPU blocks, never storing all of K\mat{K}.
  • Compositions. A⊤A\mat{A}\T\mat{A}, AB\mat{A}\mat{B} or (A−σI)(\mat{A} - \sigma\mat{I}) apply as compositions of products without forming the product matrix (which can be dense even if factors are sparse).
[ ]Matrix-free Poisson and Newton-CGBrowser
import numpy as np
import scipy.sparse.linalg as spla

# 1. La plantilla de 5 puntos sin guardar la matriz
m = 64

def laplaciano(v):
    U = v.reshape(m, m)
    Y = 4 * U
    Y[1:, :] -= U[:-1, :]
    Y[:-1, :] -= U[1:, :]
    Y[:, 1:] -= U[:, :-1]
    Y[:, :-1] -= U[:, 1:]
    return Y.ravel()

op = spla.LinearOperator((m * m, m * m), matvec=laplaciano, rmatvec=laplaciano, dtype=float)
b = np.ones(m * m)
cuenta = [0]
x_mf, info = spla.cg(op, b, rtol=1e-8, callback=lambda xk: cuenta.__setitem__(0, cuenta[0] + 1))
x_sp = spla.spsolve(poisson2d(m).tocsc(), b)
print(f"sin matriz: {cuenta[0]} iteraciones, |x - x_spsolve| / |x| = {np.linalg.norm(x_mf - x_sp) / np.linalg.norm(x_sp):.1e}")

# 2. Un paso de Newton-CG para regresión logística con regularización L2
rng = np.random.default_rng(0)
N, d, lam = 2000, 300, 1e-3
X = rng.normal(size=(N, d))
w_true = 2 * rng.normal(size=d) / np.sqrt(d)
y = (rng.uniform(size=N) < 1 / (1 + np.exp(-X @ w_true))).astype(float)

def gradiente(w):
    p = 1 / (1 + np.exp(-X @ w))
    return X.T @ (p - y) / N + lam * w

def hess_vec(w, v):
    """H v = Xᵀ diag(p(1-p)) X v / N + lam v, sin formar H (d x d)."""
    p = 1 / (1 + np.exp(-X @ w))
    return X.T @ (p * (1 - p) * (X @ v)) / N + lam * v

w = np.zeros(d)
for it in range(7):
    g = gradiente(w)
    H = spla.LinearOperator((d, d), matvec=lambda v, w=w: hess_vec(w, v), dtype=float)
    pasos = [0]
    paso, _ = spla.cg(H, -g, rtol=1e-6, callback=lambda xk: pasos.__setitem__(0, pasos[0] + 1))
    w = w + paso
    print(f"Newton {it}: ||grad|| = {np.linalg.norm(g):.2e}, iteraciones de CG = {pasos[0]}")

The first block confirms the matrix-free operator and CSR matrix give the same solution. The second is miniature Newton-CG: each Newton step solves ∇2L Δw=−∇L\hess\Loss\,\Delta\vb{w} = -\grad\Loss with CG using only Hessian-vector products, and gradient norm falls quadratically in the final iterations. The Hessian is 300×300300\times 300 here, but code does not change with 10810^8 parameters.

Lanczos for estimating extreme eigenvalues

Another major matrix-free Krylov application is spectral: estimate λmax⁡\lambda_{\max} (to choose a stable learning step or gradient Lipschitz constant), λmin⁡\lambda_{\min}, or κ\kappa (to predict CG iterations). scipy.sparse.linalg.eigsh uses ARPACK, implementing Lanczos with implicit restarting: it maintains a small basis, periodically compresses it without losing good Ritz-value information, and controls orthogonality. The next lab builds Lanczos from scratch, compares it with eigsh and the exact Poisson formula, and provokes ghost eigenvalues.

[ ]Lanczos, ghost eigenvalues and eigshBrowser
import numpy as np
import scipy.sparse.linalg as spla

def lanczos(A_mv, q0, k, reortogonalizar=False):
    """k pasos de Lanczos. Devuelve la tridiagonal T_k y la base Q (n x k)."""
    n = len(q0)
    Q = np.zeros((n, k + 1))
    alfa, beta = np.zeros(k), np.zeros(k)
    Q[:, 0] = q0 / np.linalg.norm(q0)
    for j in range(k):
        w = A_mv(Q[:, j])
        if j > 0:
            w -= beta[j - 1] * Q[:, j - 1]
        alfa[j] = Q[:, j] @ w
        w -= alfa[j] * Q[:, j]
        if reortogonalizar:                        # Gram-Schmidt completo contra toda la base
            w -= Q[:, : j + 1] @ (Q[:, : j + 1].T @ w)
        beta[j] = np.linalg.norm(w)
        Q[:, j + 1] = w / beta[j]
    T = np.diag(alfa) + np.diag(beta[:-1], 1) + np.diag(beta[:-1], -1)
    return T, Q[:, :k]

# 1. Autovalores extremos de Poisson 2D (m = 64): Lanczos, eigsh y la fórmula exacta
m = 64
A = poisson2d(m)
s = lambda i: 4 * np.sin(i * np.pi / (2 * (m + 1))) ** 2
lmax_exacto, lmin_exacto = 2 * s(m), 2 * s(1)
q0 = np.random.default_rng(0).normal(size=m * m)
for k in [20, 60, 150]:
    T, _ = lanczos(lambda v: A @ v, q0, k)
    th = np.linalg.eigvalsh(T)
    print(f"k = {k:3d}: Ritz máx = {th[-1]:.8f} (error rel. {abs(th[-1] - lmax_exacto) / lmax_exacto:.0e})   "
          f"Ritz mín = {th[0]:.8f} (error rel. {abs(th[0] - lmin_exacto) / lmin_exacto:.0e})")
print(f"exactos:   λmax = {lmax_exacto:.8f}   λmin = {lmin_exacto:.8f}")
w_max = spla.eigsh(A, k=3, which="LA", return_eigenvectors=False)
w_min = spla.eigsh(A, k=1, sigma=0, which="LM", return_eigenvectors=False)   # desplazamiento e inversión
print("eigsh (ARPACK):", np.sort(w_max), w_min)

# 2. Autovalores fantasma: matriz de Strakoš (n = 100) con autovalores muy separados arriba
n = 100
i = np.arange(1, n + 1)
lam = 0.1 + (i - 1) / (n - 1) * (100 - 0.1) * 0.9 ** (n - i)
print("\nlos cinco mayores autovalores exactos:", np.round(lam[-5:], 4))
for k in [20, 40, 80]:
    for reort in [False, True]:
        T, Q = lanczos(lambda v: lam * v, np.ones(n), k, reort)
        th = np.linalg.eigvalsh(T)
        copias = np.sum(np.abs(th - lam[-1]) < 1e-6)
        print(f"k = {k:2d}, reortogonalizar = {reort!s:5}: copias de λ = 100: {copias}, "
              f"||QᵀQ - I|| = {np.linalg.norm(Q.T @ Q - np.eye(k)):.1e}, 3 mayores Ritz = {np.round(th[-3:], 4)}")

With 150 products (versus n=4096n = 4096), Lanczos finds both extremes to about seven correct digits (relative errors 2⋅10−82\cdot 10^{-8} and 10−710^{-7}). Not yet at 20 or 60 steps: Poisson’s spectrum is symmetric around 4 (λ\lambda and 8−λ8 - \lambda are both eigenvalues), its extremes cluster (the second largest, repeated, is 0.0070.007 from the first in a spectrum of width 8), and Lanczos converges quickly only to extremes well separated from the rest. Absolute accuracy is similar at both ends, but relative accuracy for the small one is much worse: at 60 steps 0.005570.00557 versus 0.004670.00467 is 19 % error. Hence eigsh uses shift-invert mode (sigma=0) for small eigenvalues, applying Lanczos to (A−σI)−1(\mat{A} - \sigma\mat{I})\inv whose dominant eigenvalues 1/(λ−σ)1/(\lambda - \sigma) are well separated, solving systems with sparse LU: inverse iteration extended to Krylov.

For Strakoš’s matrix without reorthogonalization, two, three and more copies of eigenvalue 100100 appear as kk grows, and basis orthogonality is lost entirely (∥Q⊤Q−I∥\norm{\mat{Q}\T\mat{Q} - \mat{I}} of order 1). Full reorthogonalization makes the basis orthonormal to machine precision and each eigenvalue appears once. This is exactly Paige’s phenomenon: orthogonality is lost in the direction of an already converged Ritz vector. Reorthogonalizing against the whole basis costs O(nk)\bigO(nk) per step, returning to Arnoldi’s cost; serious programs use selective reorthogonalization (only against converged Ritz vectors) or ARPACK implicit restarting.

The professional version

Needscipy.sparse.linalg functionNotes
Buildsp.coo_array, sp.diags, sp.kron, sp.lil_arraythen .tocsr() or .tocsc()
Direct, oncespsolve(A, b)SuperLU with COLAMD reordering by default
Direct, many right-hand sidessplu(A) and lu.solve(b)factor once
Symmetric positive definitecg(A, b, rtol, M=...)M symmetric positive definite
Symmetric indefiniteminres(A, b, M=...)
Nonsymmetricgmres(A, b, restart=..., M=...), bicgstab, lgmresgmres restarts every 20 steps by default
ILU preconditionerspilu(A) and LinearOperator(A.shape, ilu.solve)nonsymmetric: do not use with cg
Matrix-freeLinearOperator(shape, matvec=...)works for all above except direct methods
Extreme eigenvalueseigsh (symmetric, Lanczos), eigs (Arnoldi), svdssigma= for shift-invert

Four SciPy 1.18 interface details matter. Tolerance is relative to ∥b∥\norm{\vb{b}} by default (rtol=1e-5, atol=0), as it should be. Returned info is 0 on convergence and positive if iterations were exhausted: always check it. gmres preconditions on the left, minimizing preconditioned residual ∥M−1(b−Ax)∥\norm{\mat{M}\inv(\vb{b} - \mat{A}\vb{x})}, though final stopping checks b−Ax\vb{b} - \mat{A}\vb{x}. Its callback has a trap: default mode (legacy) calls it each inner iteration, but maxiter then counts inner iterations rather than restart cycles; with callback_type="pr_norm", as in the cells, maxiter counts cycles. Beyond SciPy, PETSc and Trilinos are scientific-computing reference environments; PyAMG provides algebraic multigrid in Python; CHOLMOD (via scikit-sparse) and PARDISO are fast direct solvers; on GPU, cupyx.scipy.sparse.linalg replicates SciPy’s interface and torch.sparse covers network products.

Common mistakes

Exercises

NumericPoisson matrix storage
The Poisson matrix for a 1000×10001000\times 1000 grid has n=106n = 10^6 rows and 4 996 0004\,996\,000 nonzeros. How many megabytes (of 10610^6 bytes) does CSR require with float64 values and int32 indices and pointers?
QuizDoes it converge?
Select the true statements.

More than one answer may be correct.

QuizChoosing the method
You have a large sparse nonsymmetric matrix A\mat{A}, an available ILU preconditioner, and memory for dozens of length-nn vectors. What do you choose?
NumericIterations guaranteed by the bound
Using bound 2((κ−1)/(κ+1))k2\big((\sqrt\kappa - 1)/(\sqrt\kappa + 1)\big)^k, how many CG iterations guarantee reducing AA-norm error by factor 10−810^{-8} when κ=104\kappa = 10^4? Give the smallest integer.
NumericHow long does Jacobi take?
On an m×mm\times m Poisson grid with m=99m = 99 (spacing h=1/100h = 1/100), how many Jacobi iterations are needed according to ρ(GJ)\rho(\mat{G}_J) to reduce error by factor 10−610^{-6}? Give the smallest integer kk with ρk≤10−6\rho^k \le 10^{-6}.
QuizWhat matters about the spectrum
A symmetric positive definite matrix of size 10510^5 has all eigenvalues in [1,1.1][1, 1.1] except five, equal to 10310^3, 10410^4, 10510^5, 10610^6 and 10710^7. What do you expect from CG at tolerance 10−810^{-8}?
QuizThe price of restarting
Let A\mat{A} be the size-nn cyclic permutation matrix (Aei=ei+1\mat{A}\vb{e}_i = \vb{e}_{i+1}, Aen=e1\mat{A}\vb{e}_n = \vb{e}_1), b=e1\vb{b} = \vb{e}_1 and x0=0\vb{x}_0 = \vb{0}. What does GMRES(rr) do with r<nr < n?
ProofOrthogonal residuals and conjugate directions
Prove: In conjugate gradient with symmetric positive definite A\mat{A}, while residuals are nonzero, for every kk: rk⊤rj=0\vb{r}_k\T\vb{r}_j = 0 and pk⊤Apj=0\vb{p}_k\T\mat{A}\vb{p}_j = 0 for every j<kj < k.
0
Use induction on kk and formulas αk=rk⊤rk/pk⊤Apk\alpha_k = \vb{r}_k\T\vb{r}_k/\vb{p}_k\T\mat{A}\vb{p}_k, rk+1=rk−αkApk\vb{r}_{k+1} = \vb{r}_k - \alpha_k\mat{A}\vb{p}_k, βk=rk+1⊤rk+1/rk⊤rk\beta_k = \vb{r}_{k+1}\T\vb{r}_{k+1}/\vb{r}_k\T\vb{r}_k and pk+1=rk+1+βkpk\vb{p}_{k+1} = \vb{r}_{k+1} + \beta_k\vb{p}_k. Inductive hypothesis: both properties hold through kk, for all index pairs j<i≤kj < i \le k.

Step 1 of 5. First, an auxiliary fact: what is pk⊤rk\vb{p}_k\T\vb{r}_k?

CodePreconditioned CG with functions
Implement pcg(A_mv, b, M_inv, tol=1e-8, maxiter=1000), where A_mv(v) returns Av\mat{A}\vb{v} and M_inv(r) returns M−1r\mat{M}\inv\vb{r} (both are functions; you do not have the matrix). Start at x0=0\vb{x}_0 = \vb{0} and stop as soon as ∥rk∥2≤tol ∥b∥2\norm{\vb{r}_k}_2 \le \text{tol}\,\norm{\vb{b}}_2. Return (x, k) with k the number of iterations performed (0 if b=0\vb{b} = \vb{0}). Each iteration must use one product with A\mat{A}.
import numpy as np

def pcg(A_mv, b, M_inv, tol=1e-8, maxiter=1000):
  """CG precondicionado: devuelve (x, k)."""
  b = np.asarray(b, dtype=float)
  x = np.zeros_like(b)
  # tu código: r, z = M_inv(r), p, y el bucle con alpha y beta
  return x, 0
Shift+Enter to run

Summary

Key idea
When a matrix is huge and almost empty, store only nonzeros and solve with matrix-vector products: Krylov methods choose the best iterate in the space generated by those products, their speed depends on spectral shape (not only κ\kappa), and preconditioning is the art of clustering that spectrum.
  • Formats. COO for building, CSR for Ax\mat{A}\vb{x} and rows, CSC for A⊤x\mat{A}\T\vb{x} and factorization. Sparse multiplication costs 2 nnz2\,\text{nnz} flops and is memory-bound. CSR insertion shifts later entries.
  • Sparse direct methods. Elimination ordering determines fill; minimum degree and nested dissection reduce it (on 2D grids, O(nlog⁡n)\bigO(n\log n) memory and O(n3/2)\bigO(n^{3/2}) flops). Symbolic factorization separates pattern from numbers. They are competitive in 2D, much less so in 3D.
  • Stationary methods. ek+1=Gek\vb{e}_{k+1} = \mat{G}\vb{e}_k, converging if and only if ρ(G)<1\rho(\mat{G}) < 1. For Poisson, ρ=cos⁡πh\rho = \cos\pi h and O(n)\bigO(n) iterations are needed, but short waves disappear quickly: they are smoothers, the basis of multigrid.
  • Krylov. xk∈x0+Kk\vb{x}_k \in \vb{x}_0 + \mathcal{K}_k, with orthonormal Arnoldi basis (or Lanczos, with a three-term recurrence, if A\mat{A} is symmetric).
  • CG minimizes AA-norm error, uses short recurrences, converges with bound 2((κ−1)/(κ+1))k2((\sqrt\kappa - 1)/(\sqrt\kappa + 1))^k and, better, in a few iterations per eigenvalue cluster. Only for symmetric positive definite matrices.
  • GMRES minimizes residual for any A\mat{A}, with cost and memory growing with kk; restart and precondition with ILU. MINRES handles symmetric indefinite matrices; BiCGSTAB helps when memory is tight.
  • Preconditioning (Jacobi for scales, IC(0) and ILU, multigrid) transforms the spectrum; PCG needs symmetric positive definite M\mat{M}.
  • Matrix-free. v↦Av\vb{v}\mapsto\mat{A}\vb{v} suffices: LinearOperator, Hessian-vector products, Newton-CG, Lanczos for extreme eigenvalues (with orthogonality loss and ghosts).

Connections. PDEs discretized with finite differences or finite elements produce exactly these systems, which you will solve with multigrid in numerical PDEs. CG also optimizes quadratics; its nonlinear version and Newton-CG appear in optimization. Scalable Gaussian processes solve their systems with preconditioned CG and kernel products. Large graph Laplacians such as the combinatorial Laplacian are stored in CSR and handled with Lanczos and CG.