SciPy Sparse Linear Systems
Large simulations — heat flowing through a plate, stress in a bridge, the PageRank of a web graph — lead to systems of equations with thousands or millions of unknowns. Each unknown is connected only to a few neighbours, so the matrix is sparse. Dense solvers would need gigabytes of memory; scipy.sparse.linalg solves these systems while keeping the matrix sparse.
Direct solving with spsolve
spsolve(A, b) is the sparse counterpart of linalg.solve. It factorises the matrix while preserving as much sparsity as possible. Convert the matrix to CSC or CSR format first:
import numpy as np
from scipy import sparse
from scipy.sparse.linalg import spsolve
# Temperature along a 1-D rod with fixed ends: the classic tridiagonal system
n = 1000
A = sparse.diags_array([-1.0, 2.0, -1.0], offsets=[-1, 0, 1], shape=(n, n), format="csc")
b = np.full(n, 0.001) # a little heat added everywhere
T = spsolve(A, b)
print("unknowns :", n)
print("non-zeros :", A.nnz, f"({A.nnz / n**2:.2%} of the matrix)")
print("hottest point:", round(T.max(), 3), "at index", T.argmax())
print("residual :", f"{np.abs(A @ T - b).max():.1e}")unknowns : 1000
non-zeros : 2998 (0.30% of the matrix)
hottest point: 125.25 at index 500
residual : 3.8e-14
diags_array() builds a matrix from its diagonals — the natural way to create the banded matrices that come from simulations.
Iterative solvers
For really large problems even a sparse factorisation can be too expensive. Iterative solvers start from a guess and improve it step by step, using only matrix–vector products:
| Solver | Matrix requirements |
|---|---|
cg |
symmetric positive definite |
minres |
symmetric (possibly indefinite) |
gmres |
any square matrix |
bicgstab |
any square matrix |
lsqr, lsmr |
any shape — least squares |
Each returns (x, info), where info == 0 means it converged:
import numpy as np
from scipy import sparse
from scipy.sparse.linalg import cg, gmres
n = 200
A = sparse.diags_array([-1.0, 2.5, -1.0], offsets=[-1, 0, 1], shape=(n, n), format="csr")
b = np.ones(n)
iterations = []
x, info = cg(A, b, rtol=1e-10, callback=lambda xk: iterations.append(1))
print(f"cg : info={info}, iterations={len(iterations)}, "
f"residual={np.linalg.norm(A @ x - b):.1e}")
x2, info2 = gmres(A, b, rtol=1e-10)
print(f"gmres: info={info2}, same answer: {np.allclose(x, x2)}")cg : info=0, iterations=32, residual=9.7e-10
gmres: info=0, same answer: True
Eigenvalues of large sparse matrices
Often you only need a handful of eigenvalues — the lowest vibration frequencies, or the largest components. eigsh() (symmetric) and eigs() (general) compute just k of them:
import numpy as np
from scipy import sparse
from scipy.sparse.linalg import eigsh
n = 500
L = sparse.diags_array([-1.0, 2.0, -1.0], offsets=[-1, 0, 1], shape=(n, n), format="csc")
# The 3 smallest eigenvalues, using shift-invert around 0 for speed
vals = eigsh(L, k=3, sigma=0, return_eigenvectors=False)
print("smallest eigenvalues:", np.round(np.sort(vals), 8))
exact = 2 - 2 * np.cos(np.arange(1, 4) * np.pi / (n + 1))
print("exact formula :", np.round(exact, 8))smallest eigenvalues: [3.9320e-05 1.5728e-04 3.5388e-04]
exact formula : [3.9320e-05 1.5728e-04 3.5388e-04]
Matrices you never build: LinearOperator
Iterative solvers only need to know how to multiply by the matrix. A LinearOperator wraps a function that does the multiplication, so the matrix never has to exist in memory:
import numpy as np
from scipy.sparse.linalg import LinearOperator, cg
n = 5
def apply(v):
# Behaves like the matrix 3*I + (all-ones matrix), without storing it
v = np.ravel(v)
return 3 * v + v.sum()
A = LinearOperator((n, n), matvec=apply, dtype=float)
b = np.arange(1.0, n + 1)
x, info = cg(A, b)
print("converged:", info == 0)
print("x =", np.round(x, 4))
print("check:", np.round(apply(x), 4))converged: True
x = [-0.2917 0.0417 0.375 0.7083 1.0417]
check: [1. 2. 3. 4. 5.]
Tip: Iterative solvers converge faster with a good preconditioner — an easy-to-invert approximation of
Apassed asM=.spilu()builds an incomplete-LU preconditioner for general sparse matrices.
Test yourself
What does the info value returned by cg mean when it is 0?
- The solver failed
- The solver converged to the requested tolerance
- Zero iterations were done
- The matrix is singular
Which iterative solver requires a symmetric positive definite matrix?
- gmres
- bicgstab
- cg
- lsqr
What is a LinearOperator useful for?
- Converting dense matrices to sparse ones
- Describing a matrix only by how it multiplies a vector, without storing it
- Plotting matrices
- Sorting eigenvalues