Sparse Matrices
Matrices from PDEs, networks, finite elements and recommender systems are huge but almost entirely zero: a million unknowns, five nonzeros per row. Storing them densely would need terabytes. Sparse formats store only the nonzeros, and sparse algorithms only touch them. This lesson covers the formats, sparse matrix-vector products, and the main difficulty of sparse direct solvers: fill-in.
Storage formats
| Format | Stores | Good for |
|---|---|---|
| COO (coordinate) | arrays of (row, col, value) | building a matrix |
| CSR (compressed sparse row) | values, column indices, row pointers | fast , row slicing |
| CSC (compressed sparse column) | values, row indices, column pointers | column slicing, direct solvers |
| DIA, banded | diagonals | banded matrices |
import numpy as np
import scipy.sparse as sp
rows = np.array([0, 0, 1, 2, 2, 3])
cols = np.array([0, 2, 1, 0, 3, 3])
vals = np.array([4.0, -1, 3, -1, 2, 5])
A = sp.coo_matrix((vals, (rows, cols)), shape=(4, 4)).tocsr()
print("dense view:\n", A.toarray())
print("data :", A.data)
print("indices:", A.indices)
print("indptr :", A.indptr)dense view:
[[ 4. 0. -1. 0.]
[ 0. 3. 0. 0.]
[-1. 0. 0. 2.]
[ 0. 0. 0. 5.]]
data : [ 4. -1. 3. -1. 2. 5.]
indices: [0 2 1 0 3 3]
indptr : [0 2 3 5 6]
In CSR, row 's nonzeros are data[indptr[i]:indptr[i+1]] in the columns indices[indptr[i]:indptr[i+1]]. Memory is about bytes instead of .
Matrix-vector products
costs flops instead of . This is the operation iterative methods are built on (Conjugate Gradients).
import time
import numpy as np
import scipy.sparse as sp
n = 200_000
A = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(n, n), format="csr")
x = np.random.default_rng(101).normal(size=n)
y = A @ x
print(f"n = {n}, nonzeros = {A.nnz}, density = {A.nnz / n**2:.1e}")
print(f"dense storage would need {8 * n**2 / 1e9:.0f} GB; sparse needs about {(A.data.nbytes + A.indices.nbytes + A.indptr.nbytes) / 1e6:.1f} MB")
print(f"check y[1] = {y[1]:.6f} = {-x[0] + 2 * x[1] - x[2]:.6f}")n = 200000, nonzeros = 599998, density = 1.5e-05
dense storage would need 320 GB; sparse needs about 8.0 MB
check y[1] = -3.882400 = -3.882400
Fill-in
Gaussian elimination on a sparse matrix creates new nonzeros (fill-in) where zeros were. A matrix whose only nonzeros are the diagonal, first row and first column (an "arrowhead") fills in completely if eliminated from the top, but not at all if the dense row and column are ordered last:
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import splu
n = 200
A = sp.lil_matrix((n, n))
A.setdiag(4.0)
A[0, :] = 1.0; A[:, 0] = 1.0; A[0, 0] = n
A = A.tocsc()
for name, perm in (("arrow first (natural)", "NATURAL"), ("fill-reducing (COLAMD)", "COLAMD")):
lu = splu(A, permc_spec=perm)
print(f"{name:24s}: nnz(A) = {A.nnz}, nnz(L) + nnz(U) = {lu.L.nnz + lu.U.nnz}")arrow first (natural) : nnz(A) = 598, nnz(L) + nnz(U) = 40200
fill-reducing (COLAMD) : nnz(A) = 598, nnz(L) + nnz(U) = 798
Sparse direct solvers therefore first reorder rows and columns (minimum degree, nested dissection, COLAMD) to limit fill. For 2D grid problems nested dissection keeps the factors at nonzeros; in 3D the fill is much worse, which is why large 3D problems are solved iteratively.
Graph view
A symmetric sparse matrix is the adjacency structure of a graph: unknown is connected to when . Eliminating a variable connects all its neighbours to each other, which is exactly the fill-in. Graph partitioning tools (METIS) produce good orderings and also distribute matrices across parallel computers.
In software
scipy.sparse(csr_array,csc_array,diags,kron,random),scipy.sparse.linalg(spsolve,splu,cg,gmres,eigsh,svds).- Build matrices in COO or LIL format, then convert to CSR/CSC once; changing the sparsity of a CSR matrix entry by entry is slow.
- Large solvers: SuiteSparse (UMFPACK, CHOLMOD), MUMPS, PARDISO; PETSc and Trilinos for parallel iterative methods.
Exercises
Exercise 1: CSR by hand
Write the CSR arrays of .
Answer
data , indices , indptr .
Solution
Row 0 has entries in columns 0 and 2, row 1 in column 2, row 2 in columns 0 and 1; indptr marks where each row starts.
Exercise 2: Storage
A matrix with 7 nonzeros per row in CSR (8-byte values, 4-byte indices): how much memory?
Answer
About 88 MB.
Solution
bytes MB, plus the row pointer array (4 MB).
Exercise 3: Fill-in of the 2D Laplacian (code)
Factor the 5-point Laplacian for ( unknowns) with splu using NATURAL and COLAMD orderings and compare the nonzeros of .
Answer
The reordered factorization has noticeably fewer nonzeros.
Solution
import scipy.sparse as sp
from scipy.sparse.linalg import splu
N = 40
T = sp.diags([-1, 2, -1], [-1, 0, 1], shape=(N, N))
A = (sp.kron(sp.identity(N), T) + sp.kron(T, sp.identity(N))).tocsc()
for perm in ("NATURAL", "COLAMD"):
lu = splu(A, permc_spec=perm)
print(perm, A.nnz, lu.L.nnz + lu.U.nnz)NATURAL 7840 128078
COLAMD 7840 64902
With the natural (row-by-row) ordering the factors fill the whole band of width .
Test yourself
The cost of a sparse matrix-vector product is proportional to…
- the number of nonzeros
Fill-in means…
- storing zeros
- new nonzeros created during factorization
- padding a matrix
- a storage format
Which format is best for repeated matrix-vector products?
- COO
- CSR
- LIL
- dense