Gaussian elimination as LU

Part 3 — Linear systems

Numerical analysis for biologists

About this lecture

Part 2 ended with Newton for systems of equations: one linear solve J\,\Delta\mathbf x = -\mathbf f per step. This part opens the black box behind solve().

  • Recap: Gaussian elimination, as in a first linear algebra course.
  • The new view: elimination is a factorisation A = LU, lower triangular times upper triangular.
  • With L and U in hand, A\mathbf x = \mathbf b is two cheap triangular solves: forward and back substitution.
  • Cost: factorising is O(n^3), each solve with the factors only O(n^2). So: factor once, solve many.
  • Never solve(A) %*% b: slower and less accurate.
  • Failure: a zero pivot stops elimination even when the system has a perfectly good answer (the fix, pivoting, is the next unit).
  • Biology: isotope mixing models: what fraction of an animal’s diet came from each source, for one animal or for thousands.

A biology problem: what did they eat?

Stable isotope ratios in bone collagen record diet. Each source has a signature (\delta^{13}C, \delta^{15}N, corrected for trophic enrichment); a consumer is a mixture.

  • Three sources, unknown diet fractions f_1, f_2, f_3.
  • Two isotopes give two equations; the fractions summing to 1 gives the third.
  • 3 equations, 3 unknowns: a linear system.
  • Consumer #4 lies outside the triangle; we come back to it.

As a matrix equation

Mass balance for each isotope, plus “fractions sum to 1”:

\underbrace{\begin{pmatrix} 1 & 1 & 1 \\ -26 & -10 & -18 \\ 2 & 6 & 14 \end{pmatrix}}_{A:\ \text{columns = sources}} \begin{pmatrix} f_1 \\ f_2 \\ f_3 \end{pmatrix} = \underbrace{\begin{pmatrix} 1 \\ -19.6 \\ 5.6 \end{pmatrix}}_{\mathbf b:\ \text{consumer \#1}}

A <- rbind(c(  1,   1,   1),      # fractions sum to 1
           c(-26, -10, -18),      # d13C of C3 plants, maize, fish
           c(  2,   6,  14))      # d15N
b <- c(1, -19.6, 5.6)             # consumer #1
solve(A, b)
# [1] 0.5 0.3 0.2

Half C3 plants, 30 % maize, 20 % fish. What did solve() do?

Many consumers, one matrix

A study has hundreds of animals (or an isotope image has 10^5 pixels), all against the same sources:

B <- cbind(c(1, -19.6,  5.6),     # one column per consumer
           c(1, -14.8,  6.8),
           c(1, -17.2, 11.2),
           c(1, -24.0,  9.0))
X <- solve(A, B)                  # one column of fractions per consumer
X
#      [,1] [,2] [,3]  [,4]
# [1,]  0.5  0.2  0.1  0.55
# [2,]  0.3  0.6  0.2 -0.20
# [3,]  0.2  0.2  0.7  0.65
  • Same A, many right-hand sides \mathbf b. Can the work on A be done once?
  • Consumer #4: a negative fraction. The numerics are fine; the consumer lies outside the mixing triangle (a missing source, or wrong source values).

Recap: Gaussian elimination

Subtract multiples of row 1 to make zeros below the pivot a_{11} = 1:

\begin{pmatrix} 1 & 1 & 1 \\ -26 & -10 & -18 \\ 2 & 6 & 14 \end{pmatrix} \xrightarrow[\ R_3 \,-\, 2\,R_1\ ]{\ R_2 \,-\, (-26)\,R_1\ } \begin{pmatrix} 1 & 1 & 1 \\ 0 & 16 & 8 \\ 0 & 4 & 12 \end{pmatrix} \xrightarrow{\ R_3 \,-\, \tfrac14 R_2\ } \begin{pmatrix} 1 & 1 & 1 \\ 0 & 16 & 8 \\ 0 & 0 & 10 \end{pmatrix} = U

  • The multiplier for row i at step k: \ell_{ik} = a_{ik}/a_{kk} (entry to be zeroed / pivot).
  • Here \ell_{21} = -26/1 = -26, \ell_{31} = 2/1 = 2, \ell_{32} = 4/16 = \tfrac14.
  • The result U is upper triangular.

In a first course you did the same row operations on \mathbf b at the same time (the augmented matrix). Now we keep \mathbf b out of it.

Keep the multipliers: L

Put each multiplier where it made its zero, with 1 on the diagonal:

L = \begin{pmatrix} 1 & 0 & 0 \\ \ell_{21} & 1 & 0 \\ \ell_{31} & \ell_{32} & 1 \end{pmatrix} = \begin{pmatrix} 1 & 0 & 0 \\ -26 & 1 & 0 \\ 2 & \tfrac14 & 1 \end{pmatrix}, \qquad U = \begin{pmatrix} 1 & 1 & 1 \\ 0 & 16 & 8 \\ 0 & 0 & 10 \end{pmatrix}

Then A = LU. Check row 3: 2\cdot(1, 1, 1) + \tfrac14 \cdot (0, 16, 8) + 1\cdot(0, 0, 10) = (2, 6, 14). ✓

  • Row i of A = (row i of U) + (the multiples of earlier U rows that elimination subtracted). L records exactly those multiples.
  • L is unit lower triangular, U is upper triangular. This is the LU factorisation.

Why triangular is good

A\mathbf x = \mathbf b becomes L(U\mathbf x) = \mathbf b. Call \mathbf y = U\mathbf x and solve two triangular systems:

1. Forward substitution L\mathbf y = \mathbf b, top to bottom:

\begin{aligned} y_1 &= 1 \\ y_2 &= -19.6 + 26\,y_1 = 6.4 \\ y_3 &= 5.6 - 2\,y_1 - \tfrac14 y_2 = 2.0 \end{aligned}

2. Back substitution U\mathbf x = \mathbf y, bottom to top:

\begin{aligned} x_3 &= 2.0 / 10 = 0.2 \\ x_2 &= (6.4 - 8\,x_3)/16 = 0.3 \\ x_1 &= 1 - x_2 - x_3 = 0.5 \end{aligned}

  • Forward substitution replays on \mathbf b the row operations that elimination did on A (\mathbf y is the right-hand column of the augmented matrix after elimination).
  • Next consumer: new \mathbf b, same L and U, only these 6 lines again.

Try it: factor once, solve many samples

Elimination in R, written out

lu_nopivot <- function(A) {
  n <- nrow(A); L <- diag(n); U <- A
  for (k in 1:(n - 1)) {                         # pivot column k
    for (i in (k + 1):n) {                       # rows below the pivot
      L[i, k] <- U[i, k] / U[k, k]               # multiplier l_ik
      U[i, k:n] <- U[i, k:n] - L[i, k] * U[k, k:n]   # row i - l_ik * row k
    }
  }
  list(L = L, U = U)
}
F <- lu_nopivot(A)
F$L %*% F$U                                      # gives back A exactly
  • Three nested loops (the third is the vector operation on k:n): that is where n^3 will come from.
  • diag(n) is the n \times n identity matrix; %*% is the matrix product.

Forward and back substitution in R

forward_sub <- function(L, b) {          # solve L y = b, top to bottom
  n <- length(b); y <- numeric(n)
  for (i in 1:n) {
    j <- seq_len(i - 1)                  # columns 1..i-1
    y[i] <- (b[i] - sum(L[i, j] * y[j])) / L[i, i]
  }
  y
}
back_sub <- function(U, y) {             # solve U x = y, bottom to top
  n <- length(y); x <- numeric(n)
  for (i in n:1) {
    j <- seq_len(n - i) + i              # columns i+1..n
    x[i] <- (y[i] - sum(U[i, j] * x[j])) / U[i, i]
  }
  x
}

back_sub(F$U, forward_sub(F$L, b)) gives [1] 0.5 0.3 0.2; the intermediate y is 1.0 6.4 2.0, as on the board.

What libraries do: Matrix::lu

library(Matrix)
Fm <- lu(A)                     # LAPACK's LU, stored compactly
e  <- expand2(Fm)               # A = P1. %*% L %*% U
e$L
#             [,1]        [,2]        [,3]
# [1,]  1.00000000           .           .
# [2,] -0.07692308  1.00000000           .
# [3,] -0.03846154  0.11764706  1.00000000
solve(Fm, b)                    # forward + back substitution only
# [1] 0.5 0.3 0.2
  • lu() gives different L and U from ours: it reorders the rows first (pivot -26, the largest in column 1). The permutation matrix P records the swaps: A = PLU.
  • Same answer. Why it reorders is the next unit, Pivoting, norms and conditioning.

Counting the cost

Factorising. At step k there are n-k rows below the pivot; each needs 1 division and n-k multiply–subtract pairs:

\sum_{k=1}^{n-1} 2(n-k)^2 \;\approx\; 2\sum_{j=1}^{n} j^2 \;\approx\; \tfrac23 n^3 \text{ operations}

Substitution. Row i of forward substitution needs i-1 pairs: \sum_i 2(i-1) \approx n^2. Back substitution the same. Total \approx 2n^2.

n factorise \tfrac23 n^3 substitute 2n^2 ratio
3 18 18 1
100 6.7\times10^5 2\times10^4 33
1000 6.7\times10^8 2\times10^6 333
10 000 6.7\times10^{11} 2\times10^8 3 333

Measured: slopes on a log–log plot

  • Substitution: slope ≈ 2. Factorising: slope ≈ 2.6, doubling ratio 5.5 → 6.3 → 6.5 (towards 8).
  • The gap grows with n: at n = 8000, one factorisation (6.4 s) = 145 solves (0.044 s).

Factor once, solve many

Right-hand sides that arrive one at a time (a new sample, the next time step, the next Newton step with a frozen Jacobian):

set.seed(1)                    # times: our server, one thread; yours differ
n <- 1000; A <- matrix(rnorm(n * n), n)
Bm <- matrix(rnorm(n * 200), n)                    # 200 right-hand sides
system.time(for (j in 1:200) x <- solve(A, Bm[, j]))["elapsed"]
#  6.618                                           # factorises 200 times
system.time({ F <- lu(A); for (j in 1:200) x <- solve(F, Bm[, j]) })["elapsed"]
#  0.12                                            # factorises once
system.time(X <- solve(A, Bm))["elapsed"]
#  0.035                                           # all at once
  • 55 times faster by keeping the factors. If all \mathbf b are known in advance, put them as columns of a matrix: solve(A, B) factorises once.

How the total cost grows with m

  • Refactorising: m \cdot \tfrac23 n^3. Factor once: \tfrac23 n^3 + m \cdot 2n^2. For m = 10\,000 samples: 4 min vs 4 s.
  • The orange dashed line (inverse once) runs parallel to the blue one, but higher. Next slide.

Never solve(A) %*% b (1): cost

solve(A) with one argument returns A^{-1}. It computes it by solving A\,\mathbf x_j = \mathbf e_j for each column \mathbf e_j of the identity:

  • LU of A: \tfrac23 n^3, plus n right-hand sides: about \tfrac43 n^3 more. Total \approx 2n^3, 3 times one factorisation.
  • Then A^{-1}\mathbf b costs 2n^2, the same as forward + back substitution.
system.time(solve(A))["elapsed"]       # n = 1000, one thread, our server
#  0.068
system.time(lu(A))["elapsed"]
#  0.018

So for one \mathbf b, the inverse is 3–4 times slower, and for many \mathbf b it gains nothing over keeping L and U.

Never solve(A) %*% b (2): accuracy

Four sources, three isotopes; sources 1 and 2 differ by only 0.01–0.02 ‰:

A4 <- rbind(1,
            c(-26, -25.99, -10, -18),   # d13C
            c(  2,   2.01,   6,  14),   # d15N
            c(  4,   4.02,   3,  19))   # d34S
f <- c(0.3, 0.2, 0.4, 0.1); b <- A4 %*% f
x_lu  <- solve(A4, b)
x_inv <- solve(A4) %*% b
c(max(abs(b - A4 %*% x_lu)), max(abs(b - A4 %*% x_inv)))   # residuals
# [1] 0.000000e+00 4.657608e-12
c(max(abs(x_lu - f)),        max(abs(x_inv - f)))          # errors
# [1] 2.060296e-13 4.786171e-13
  • The residual \mathbf b - A\mathbf x of solve(A, b) is at rounding level (here exactly 0); the inverse’s is about 10^3 times rounding level. The error is also larger.

The residual check, on many matrices

  • Random 50 \times 50 matrices with condition number \kappa from 10 to 10^{15}. Residual relative to \max|A|\cdot\max|\mathbf x|.
  • solve(A, b): about \varepsilon, whatever \kappa. Inverse: grows like \kappa\,\varepsilon.

When elimination breaks: a zero pivot

Two sources with the same \delta^{13}C (C3 plants and freshwater fish, both -26 ‰), told apart by \delta^{15}N:

A0 <- rbind(c(  1,   1,   1),
            c(-26, -26, -10),       # d13C: C3 plants, freshwater fish, maize
            c(  2,  10,   6))       # d15N
lu_nopivot(A0)$U
#      [,1] [,2] [,3]
# [1,]    1    1    1
# [2,]    0    0   16             # pivot U[2, 2] = 0
# [3,]    0  NaN -Inf
solve(A0, c(1, -20, 6.5))
# [1] 0.250 0.375 0.375
  • After step 1 the pivot is 0: division by zero gives Inf and NaN, no error message.
  • The system is fine (solve answers): swapping rows 2 and 3 fixes it.

Worse: a tiny pivot gives a wrong answer silently

\begin{pmatrix} 10^{-20} & 1 \\ 1 & 1 \end{pmatrix}\mathbf x = \begin{pmatrix} 1 \\ 2 \end{pmatrix}, \qquad \mathbf x \approx (1, 1)

As <- rbind(c(1e-20, 1), c(1, 1))
Fs <- lu_nopivot(As)                  # l21 = 1e20, u22 = 1 - 1e20
back_sub(Fs$U, forward_sub(Fs$L, c(1, 2)))
# [1] 0 1                               # x1 is 100 % wrong
solve(As, c(1, 2))
# [1] 1 1
  • 1 - 10^{20} rounds to -10^{20}: the “1” in a_{22} is lost, and with it x_1.
  • No NaN, no warning. Check: the residual, b - A %*% x, here (0, 1).
  • The cure is partial pivoting: Pivoting, norms and conditioning.

Checks to run on a linear solve

  1. Residual: max(abs(b - A %*% x)) should be near \varepsilon \cdot \max|A| \cdot \max|\mathbf x|. If not, the algorithm failed (no pivoting, inverse).
  2. Factors: max(abs(L %*% U - A)) for your own LU; is.finite() on the factors catches a zero pivot.
  3. Use the library: solve(A, b), solve(A, B), or F <- lu(A) then solve(F, b). They pivot.
  4. No inverses in code: solve(A) %*% b → solve(A, b).
  5. Plausibility: diet fractions between 0 and 1. A negative fraction = consumer outside the source polygon, a model problem, not a numerical one.

A small residual does not prove a small error (A4 above): that depends on the condition number. Next unit.

Summary

  • Gaussian elimination = LU factorisation. Keep the multipliers \ell_{ik} = a_{ik}/a_{kk} in a unit lower triangular L; the eliminated matrix is the upper triangular U; A = LU.
  • Solve A\mathbf x = \mathbf b as L\mathbf y = \mathbf b (forward substitution), then U\mathbf x = \mathbf y (back substitution).
  • Cost: factorising \approx \tfrac23 n^3, each solve with the factors \approx 2n^2. Factor once, solve many: F <- lu(A); solve(F, b), or solve(A, B) for many columns at once.
  • Never solve(A) %*% b: about 3 times the work, and a residual that grows with \kappa.
  • Libraries reorder rows (A = PLU). Without that, a zero pivot gives NaN, a tiny pivot a silently wrong answer. Check the residual.
  • Biology: isotope mixing models for many consumers against the same sources; negative fractions flag a consumer outside the source polygon.

Next: Pivoting, norms and conditioning: why libraries pivot, and how much a matrix amplifies noise.