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, . Discretize it on a grid of interior points with spacing and the five-point stencil:
Numbering points by rows gives system with unknowns. With , . Each row of has at most five nonzero entries, with in total. The matrix is symmetric positive definite and almost empty: of its entries, only one in is nonzero.
Now compare solution costs:
- Dense LU or Cholesky (from lesson 4). Storing as a dense float64 matrix alone takes bytes TB. Cholesky factorization costs about 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, bytes plus one pointer per row: about 64 MB. Product costs 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 only through . 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 bytes versus COO’s .
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 in CSR (contiguous segments, one write per row) and CSC (scattered writes to ).CSR matrix-vector multiplication loops over rows, each a dot product of a contiguous segment of data with entries of pointed to by indices:
This takes flops, but each nonzero reads 12 matrix bytes plus an at an arbitrary position. Arithmetic intensity is below flop per byte: sparse multiplication is limited by memory bandwidth, not arithmetic (the roofline model quantifies this). Practical consequences:
| Operation | COO | CSR | CSC |
|---|---|---|---|
| Build by adding entries | cheap (append) | expensive (shift and index) | expensive |
| works, no row locality | best | scattered writes | |
| same | scattered writes | best | |
| Extract row | scan all | scan all | |
| Extract column | scan all | scan all | |
| Factor (sparse LU, Cholesky) | no | yes | usual (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.
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 , with , 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 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 : 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.
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 .
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 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:
- Reordering. Choose 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.
- Symbolic factorization. Compute the exact pattern of from the graph without arithmetic and reserve memory. The elimination tree organizes this: parent of column is the row of the first nonzero of below its diagonal. Columns in different branches can be factored in parallel.
- 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
cholandscikit-sparsein Python.
For a Poisson grid, natural order gives a band matrix with half-width : everything inside fills, entries and flops. George proved in 1973 that nested dissection on a grid of (that is, ) reduces storage to and operations to ; 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 memory and flops: iterative methods become essential.
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 measures Cholesky fill. Natural ordering fills the entire band; minimum degree on the graph of , 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 is a fixed point: . Subtraction gives error satisfying , so . Everything depends on powers of .
Proof
If , take an eigenvector (complex if needed) with and . If is real, gives . Otherwise its real or imaginary part is a real that does not converge, because does not tend to zero. Conversely, if , for every there is an induced norm with (constructed from Jordan form by scaling block ones), so by choosing . Equivalently, Gelfand’s formula gives .
∎Two easily checked sufficient conditions:
Proof
For (1) with Jacobi, has row containing numbers () and zero on the diagonal. Its infinity norm, maximum absolute row sum, is , and . 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, ), yet Jacobi converges. To find its speed calculate , which can be done by hand for the model problem.
Analyzing the model problem
Eigenvectors of of size are discrete sines , with eigenvalues , . Those of are products , with eigenvalues
Mode is one smooth hump; is a checkerboard. Since the diagonal is constant, and Jacobi matrix has the same eigenvectors, with eigenvalues
The largest magnitude is , reached at both extremes: the smoothest mode and checkerboard. Reducing error by factor takes about iterations: with , nearly three million. For row ordering, Gauss–Seidel satisfies (the matrix is consistently ordered in Young’s terminology), merely doubling speed. SOR with optimal , , achieves : iterations fall from to , but must be known and rarely is outside the model problem.
They smooth, but do not solve
approaching 1 does not mean all error decays slowly. Each mode has a different factor: modes with large or (short waves) have small and vanish in a few iterations; those with small (long waves) have and linger. There is a trap: with pure Jacobi the checkerboard has and also remains, merely changing sign each iteration. Hence weighted Jacobi, , with factors . For high-frequency modes (those with ), , and with factors lie in : each iteration reduces short waves by at least a third. Long waves with still have factor .
The curves tell the whole story. All three stationary methods fall quickly at first as they remove noise, then crawl with slope (on a logarithmic iteration axis the straight line looks like a late drop): with the initial seed, Gauss–Seidel falls below 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.
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 , Gauss–Seidel needs half as many as Jacobi, and the ratio of Jacobi iterations to stabilizes: cost grows as iterations, each costing . We need to do better.
Krylov subspaces
Consider the space containing a Jacobi iterate. With and , is a combination of , with coefficients fixed in advance by the method. The same holds for any method using only through products. Naturally, since the iterate belongs to that space, why not choose its best element?
The spaces grow with until they stabilize; at that point the solution is guaranteed to lie inside.
Proof
If , then , and by induction . Since is invertible, restricted to is injective and thus bijective, so for some ; that is . For the bound, write as the sum of components in eigenspaces of the distinct eigenvalues present. Polynomial of degree annihilates each component, so : is a combination of lower powers and .
∎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 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:
- .
- For : ; for : and . Then and .
After steps, is an orthonormal basis of and coefficients form Hessenberg matrix (zeros below the first subdiagonal) with
Step costs one product with and dot products: cost and memory grow with .
If is symmetric, so is , and a symmetric Hessenberg matrix is tridiagonal. Almost all vanish by construction and an Arnoldi step reduces to a three-term recurrence: Lanczos iteration (1950),
with . The basis need not be stored to continue: constant cost and memory per step. Eigenvalues of , the Ritz values, approximate extreme eigenvalues of long before , 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: 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 , solving is equivalent to minimizing the quadratic form
because is strictly convex and its only critical point is . Some algebra gives , where is the energy norm. Minimizing minimizes error in norm.
Steepest descent and its zigzag
The obvious idea is to move along the residual, , with a step minimizing on that line: . With this exact step the new residual is orthogonal to the previous one (): each step turns relative to the last. Kantorovich proved the bound
where is the condition number of . With , each step guarantees only factor .
The figure’s transformation captures the idea. In coordinates the function is , with circular contours; for a circular problem, move in orthogonal directions and take the exact step in each: steps finish it. Returning to , orthogonality in means : directions conjugate with respect to .
Derivation
Seek minimizing over the whole Krylov space. Given a basis of that is -conjugate ( for ), write :
Cross terms vanish: the problem decouples into one-variable minimizations, , and already computed do not change when adding a direction. Thus the minimum over follows from the minimum over in one step, . The minimum condition also says the residual is orthogonal to the entire space: (the Galerkin condition).
Directions still need to be constructed cheaply. Hestenes and Stiefel conjugate the new residual against the previous direction: , choosing so . Remarkably this suffices: is conjugate to all previous directions. For , and , so , and by induction. Symmetry of permits forgetting the past; the same phenomenon turns Arnoldi into Lanczos.
The formulas for and simplify and 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 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 steps when is large and sparse.
Convergence: polynomials, and spectral shape
Since , error is , with a polynomial of degree and . CG optimality says it chooses the best:
The inequality follows by writing in the orthonormal eigenvector basis: . CG convergence is a polynomial approximation problem: find a degree- polynomial equal to 1 at the origin and small at all eigenvalues. Two immediate consequences:
- Few distinct eigenvalues. If has distinct eigenvalues, has degree , equals 1 at 0 and vanishes on the whole spectrum: CG finishes in steps.
- Clustered eigenvalues. If the spectrum lies in 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 , the best polynomial for the whole interval is a rescaled Chebyshev polynomial, with . On the interval its numerator lies between and , so the maximum is . For , , and with :
This gives the classical bound:
Compare steepest descent: instead of . To reduce error by factor , descent needs about iterations and CG about . For Poisson, , so CG needs iterations versus Jacobi’s . But the bound only uses spectral extremes, which limits it.
The figure shows three distinct regimes:
- Spectrum filling the interval. With 500 eigenvalues at Chebyshev nodes of , the bound is nearly exact (with , 297 iterations versus 302): eigenvalues are everywhere and the Chebyshev polynomial is almost optimal.
- Clustered spectrum. CG eventually places roots on each cluster, and iteration count depends on relative cluster width, not . Zero width (three distinct values) takes 3 iterations; with , 25 versus the bound’s 310.
- A few outliers. With 200 eigenvalues in , CG needs 11 iterations; adding outliers at , , and sends 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:
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).
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 (column “iter/(m+1)” is nearly constant), as predicts, and remain below the bound due to superlinear convergence. With , unknowns are solved in a few hundred matrix-vector products; Jacobi would need order . The final line shows floating-point effects: Strakoš’s matrix has eigenvalues tightly clustered near and widely separated near , and CG needs more iterations than its dimension, impossible in exact arithmetic.
GMRES and methods for nonsymmetric matrices
If is nonsymmetric, no longer makes sense (its gradient would be ), and norm does not exist. The natural criterion becomes the residual.
is Hessenberg, so its QR is updated at each step with one Givens rotation, and residual norm comes for free without forming . GMRES residual never grows and in exact arithmetic it terminates in at most steps. Cost is the problem: Arnoldi step costs and stores vectors of length . With and the basis occupies 4 GB.
The practical solution is restart: GMRES() takes steps, computes , uses it as new 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 steps, it never will (the classic example is a cyclic permutation matrix with ). Choosing 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 with 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 ), avoids products with and smooths BiCG’s irregular convergence with a local minimum-residual step. It uses two products with per iteration, minimizes nothing globally and can break down, but is cheap when it works.
GMRES convergence can also be written with polynomials: , and if is diagonalizable,
For normal matrices, 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.
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 (), but the basis is not orthonormal to that precision: . 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. Ignoringinforisks 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() iteration is cheaper for smaller .
Preconditioning
With convergence tied to the spectrum, the idea is to replace the system with an equivalent one having a better spectrum. If and solving with is cheap, has the same solution, and if its spectrum clusters near 1.
The extremes clarify the tradeoff: is free and does not help; solves in one iteration, but applying it solves the original problem. Useful preconditioners lie between.
For CG there is a subtlety: is not symmetric. If is symmetric positive definite with , CG on (symmetric, similar to ) can be rewritten in original variables, and disappears. The result is preconditioned CG (PCG): like CG, with instead of in two places,
Its convergence is that of CG with and the spectrum of . 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: . 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 has the lower-triangular pattern of and agrees with 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 ; ILUT drops entries below a relative threshold and limits fill per row.
scipy.sparse.linalg.spilucalls SuperLU’s threshold ILU. - Beyond these: SSOR, sparse approximate inverses, algebraic multigrid (giving iteration counts independent of for elliptic problems), and problem-specific preconditioners.
Remember the criterion. A good preconditioner is not the one closest to in norm, but the one that clusters the spectrum of : if most eigenvalues lie near 1 and only a few are isolated, CG benefits even if remains large. In the spectrum figure, “2D Poisson” uses exact eigenvalues of the matrix for grid and the preconditioned ones computed in the next cell.
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 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 instead, with unknown scales between and , rises near , and Jacobi exactly restores the spectrum of : if , then . IC(0) is also immune to this scaling: incomplete Cholesky of is , and .
A literature-backed nuance: IC(0) improves the constant but not the order. For the model problem, still grows like ; the modified MIC version, adding discarded entries to the diagonal, reduces it to (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.
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}")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 doubles (59, 119, 239), and IC(0)-PCG reduces them by slightly over half (29, 52, 100) with the same linear growth in , 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.
spsolveis competitive at these sizes: a 2D problem with unknowns is small for well-reordered sparse LU. Iterative methods win in 3D, when is so large the factor cannot fit in memory, or when only matrix-vector products are available. - ILU with CG, a real mistake.
spiluis not symmetric. With default parameterscgdoes not converge in 1000 iterations even though 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 only through . 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 parameters cannot be formed, but 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 with preconditioned CG and products computed in GPU blocks, never storing all of .
- Compositions. , or apply as compositions of products without forming the product matrix (which can be dense even if factors are sparse).
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 with CG using only Hessian-vector products, and gradient norm falls quadratically in the final iterations. The Hessian is here, but code does not change with parameters.
Lanczos for estimating extreme eigenvalues
Another major matrix-free Krylov application is spectral: estimate (to choose a stable learning step or gradient Lipschitz constant), , or (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.
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 ), Lanczos finds both extremes to about seven correct digits (relative errors and ). Not yet at 20 or 60 steps: Poisson’s spectrum is symmetric around 4 ( and are both eigenvalues), its extremes cluster (the second largest, repeated, is 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 versus is 19 % error. Hence eigsh uses shift-invert mode (sigma=0) for small eigenvalues, applying Lanczos to whose dominant eigenvalues 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 appear as grows, and basis orthogonality is lost entirely ( 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 per step, returning to Arnoldi’s cost; serious programs use selective reorthogonalization (only against converged Ritz vectors) or ARPACK implicit restarting.
The professional version
| Need | scipy.sparse.linalg function | Notes |
|---|---|---|
| Build | sp.coo_array, sp.diags, sp.kron, sp.lil_array | then .tocsr() or .tocsc() |
| Direct, once | spsolve(A, b) | SuperLU with COLAMD reordering by default |
| Direct, many right-hand sides | splu(A) and lu.solve(b) | factor once |
| Symmetric positive definite | cg(A, b, rtol, M=...) | M symmetric positive definite |
| Symmetric indefinite | minres(A, b, M=...) | |
| Nonsymmetric | gmres(A, b, restart=..., M=...), bicgstab, lgmres | gmres restarts every 20 steps by default |
| ILU preconditioner | spilu(A) and LinearOperator(A.shape, ilu.solve) | nonsymmetric: do not use with cg |
| Matrix-free | LinearOperator(shape, matvec=...) | works for all above except direct methods |
| Extreme eigenvalues | eigsh (symmetric, Lanczos), eigs (Arnoldi), svds | sigma= for shift-invert |
Four SciPy 1.18 interface details matter. Tolerance is relative to 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 , though final stopping checks . 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
More than one answer may be correct.
Step 1 of 5. First, an auxiliary fact: what is ?
pcg(A_mv, b, M_inv, tol=1e-8, maxiter=1000), where A_mv(v) returns and M_inv(r) returns (both are functions; you do not have the matrix). Start at and stop as soon as . Return (x, k) with k the number of iterations performed (0 if ). Each iteration must use one product with .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, 0Summary
- Formats. COO for building, CSR for and rows, CSC for and factorization. Sparse multiplication costs 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, memory and flops). Symbolic factorization separates pattern from numbers. They are competitive in 2D, much less so in 3D.
- Stationary methods. , converging if and only if . For Poisson, and iterations are needed, but short waves disappear quickly: they are smoothers, the basis of multigrid.
- Krylov. , with orthonormal Arnoldi basis (or Lanczos, with a three-term recurrence, if is symmetric).
- CG minimizes -norm error, uses short recurrences, converges with bound and, better, in a few iterations per eigenvalue cluster. Only for symmetric positive definite matrices.
- GMRES minimizes residual for any , with cost and memory growing with ; 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 .
- Matrix-free. 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.