Banded and Positive Definite Matrices
The matrices that come out of applications are rarely arbitrary. Discretized differential equations give banded matrices with nonzeros only near the diagonal; least squares, statistics and energy methods give symmetric positive definite (SPD) matrices. Exploiting this structure cuts the cost of a solve from to as little as , and removes the need for pivoting.
Banded matrices
has bandwidth (lower) and (upper) if whenever or . LU without pivoting keeps the band: has lower bandwidth and upper bandwidth , and the cost is . A tridiagonal matrix () is solved in by the Thomas algorithm:
import numpy as np
from scipy.linalg import solve_banded
def thomas(a, d, c, b):
"""Solve a tridiagonal system: sub-diagonal a, diagonal d, super-diagonal c."""
n = len(d)
d = d.astype(float).copy(); b = b.astype(float).copy()
for i in range(1, n):
m = a[i - 1] / d[i - 1]
d[i] -= m * c[i - 1]
b[i] -= m * b[i - 1]
x = np.zeros(n)
x[-1] = b[-1] / d[-1]
for i in range(n - 2, -1, -1):
x[i] = (b[i] - c[i] * x[i + 1]) / d[i]
return x
n = 8
a = -np.ones(n - 1); c = -np.ones(n - 1); d = 2.0 * np.ones(n) # the 1D Laplacian
b = np.ones(n)
x = thomas(a, d, c, b)
ab = np.vstack([np.r_[0, c], d, np.r_[a, 0]]) # LAPACK banded storage
print("Thomas :", np.round(x, 6))
print("solve_banded:", np.round(solve_banded((1, 1), ab, b), 6))Thomas : [ 4. 7. 9. 10. 10. 9. 7. 4.]
solve_banded: [ 4. 7. 9. 10. 10. 9. 7. 4.]
The matrix appears in Finite Differences for BVPs and the heat equation.
Symmetric positive definite matrices
is SPD if and for all . Equivalent tests: all eigenvalues are positive; all pivots of elimination are positive. Examples: covariance matrices, with of full column rank, stiffness matrices, Hessians at a strict minimum.
Cholesky factorization
Every SPD matrix factors as
with upper triangular with positive diagonal (equivalently ). It costs flops, half of LU, needs no pivoting, and is unconditionally backward stable. Failure of Cholesky (a non-positive value under a square root) is the standard numerical test for positive definiteness.
import numpy as np
def cholesky(A):
n = A.shape[0]
R = np.zeros_like(A, dtype=float)
for k in range(n):
s = A[k, k] - R[:k, k] @ R[:k, k]
if s <= 0:
raise np.linalg.LinAlgError("matrix is not positive definite")
R[k, k] = np.sqrt(s)
R[k, k + 1:] = (A[k, k + 1:] - R[:k, k] @ R[:k, k + 1:]) / R[k, k]
return R
A = np.array([[4.0, 2, -2], [2, 10, 4], [-2, 4, 9]])
R = cholesky(A)
print("R =\n", R)
print("R^T R == A:", np.allclose(R.T @ R, A), "| NumPy L == R^T:", np.allclose(np.linalg.cholesky(A), R.T))
try:
cholesky(np.array([[1.0, 2], [2, 1]]))
except np.linalg.LinAlgError as e:
print("[[1, 2], [2, 1]]:", e)R =
[[ 2. 1. -1. ]
[ 0. 3. 1.66666667]
[ 0. 0. 2.2852182 ]]
R^T R == A: True | NumPy L == R^T: True
[[1, 2], [2, 1]]: matrix is not positive definite
Sampling with Cholesky
If has independent standard normal entries and , then has covariance . This is how multivariate normal samples are generated:
import numpy as np
Sigma = np.array([[1.0, 0.8], [0.8, 2.0]])
L = np.linalg.cholesky(Sigma)
rng = np.random.default_rng(12)
Z = rng.standard_normal((2, 200_000))
X = L @ Z
print("sample covariance:\n", np.round(np.cov(X), 3))sample covariance:
[[1. 0.794]
[0.794 1.993]]
In software
scipy.linalg.cho_factor/cho_solvefor SPD systems;scipy.linalg.solve(A, b, assume_a="pos")picks Cholesky;solve_bandedandsolveh_bandedfor banded matrices.- Gaussian processes, Kalman filters and Newton's method for convex problems all run on Cholesky factorizations.
Exercises
Exercise 1: Tridiagonal cost
How many flops does the Thomas algorithm take, to leading order?
Answer
About .
Solution
Elimination: 1 division, 2 multiplications and 2 subtractions per row (); back substitution: about . That is , compared with for dense LU.
Exercise 2: Is it SPD?
Is positive definite?
Answer
No.
Solution
Elimination gives pivots and (equivalently ).
Exercise 3: Cholesky versus LU (code)
For a random SPD matrix with , compare the solutions of cho_solve and np.linalg.solve and confirm they agree.
Answer
They agree to a relative difference of a few times , consistent with .
Solution
import numpy as np
from scipy.linalg import cho_factor, cho_solve
rng = np.random.default_rng(9)
B = rng.normal(size=(300, 300)); A = B.T @ B + np.eye(300); b = rng.normal(size=300)
x1 = cho_solve(cho_factor(A), b); x2 = np.linalg.solve(A, b)
print(f"{np.linalg.norm(x1 - x2) / np.linalg.norm(x2):.1e}")3.4e-14
Test yourself
Cholesky factorization applies to…
- any square matrix
- symmetric positive definite matrices
- triangular matrices
- singular matrices
Solving a tridiagonal system costs…
Compared with LU, Cholesky costs about…
- twice as much
- the same
- half as much
- a tenth