TExcelTAD
Home › Numerical Methods › Sparse Matrices

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 AxA\mathbf{x}, row slicing
CSC (compressed sparse column) values, row indices, column pointers column slicing, direct solvers
DIA, banded diagonals banded matrices
python · try it yourself
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 ii's nonzeros are data[indptr[i]:indptr[i+1]] in the columns indices[indptr[i]:indptr[i+1]]. Memory is about 12⋅nnz12\cdot\text{nnz} bytes instead of 8n28n^2.

Matrix-vector products

AxA\mathbf{x} costs 2⋅nnz2\cdot\text{nnz} flops instead of 2n22n^2. This is the operation iterative methods are built on (Conjugate Gradients).

python · try it yourself
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:

python · try it yourself
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 O(nlog⁡n)O(n\log n) 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 ii is connected to jj when aij≠0a_{ij} \ne 0. 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 (102003450)\begin{pmatrix} 1 & 0 & 2 \\ 0 & 0 & 3 \\ 4 & 5 & 0\end{pmatrix}.

Answer

data [1,2,3,4,5][1, 2, 3, 4, 5], indices [0,2,2,0,1][0, 2, 2, 0, 1], indptr [0,2,3,5][0, 2, 3, 5].

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 106×10610^6 \times 10^6 matrix with 7 nonzeros per row in CSR (8-byte values, 4-byte indices): how much memory?

Answer

About 88 MB.

Solution

7×106×(8+4)7 \times 10^6 \times (8 + 4) bytes =84= 84 MB, plus the row pointer array (4 MB).

Exercise 3: Fill-in of the 2D Laplacian (code)

Factor the 5-point Laplacian for N=40N = 40 (16001600 unknowns) with splu using NATURAL and COLAMD orderings and compare the nonzeros of L+UL + U.

Answer

The reordered factorization has noticeably fewer nonzeros.

Solution
python · try it yourself
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 NN.

Test yourself

The cost of a sparse matrix-vector product is proportional to…

  1. n2n^2
  2. the number of nonzeros
  3. n3n^3
  4. log⁡n\log n

Fill-in means…

  1. storing zeros
  2. new nonzeros created during factorization
  3. padding a matrix
  4. a storage format

Which format is best for repeated matrix-vector products?

  1. COO
  2. CSR
  3. LIL
  4. dense