Pivoting, norms and conditioning

Part 3 — Linear systems

Numerical analysis for biologists

About this lecture

In Gaussian elimination as LU we solved A\mathbf x = \mathbf b by elimination and assumed every step was fine. Today: two different ways the answer can still be wrong.

  • The algorithm’s fault. Elimination divides by the pivot. A tiny pivot destroys the answer; partial pivoting (swapping rows) fixes it.
  • The problem’s fault. Some systems amplify errors in \mathbf b whatever the algorithm. To measure this we need sizes of vectors and matrices: norms (1, 2, \infty).
  • The condition number \kappa(A): lose about \log_{10}\kappa digits.
  • Residual vs error: a small residual does not mean a small error.
  • Biology: spectral unmixing in flow cytometry. Dyes with overlapping spectra give an ill-conditioned matrix, and detector noise is amplified.

Where we left off: two dyes

At the end of Error, conditioning and stability:

A <- matrix(c(1,    0.95,
              0.95, 1   ), nrow = 2, byrow = TRUE)
solve(A, c(1.95, 1.95))
# [1] 1 1
solve(A, c(1.96, 1.94))             # b off by 0.5 %
# [1] 1.2 0.8
kappa(A, exact = TRUE)
# [1] 39
  • A 0.5 % change in the detector readings moves the dye amounts by 20 %.
  • Today: why 39, what \kappa measures, and what to do about it.

Spectral unmixing is A\mathbf x = \mathbf b

  • Each dye emits over a range of wavelengths. Each detector sees light from several dyes.
  • A_{ij} = signal in detector i per unit of dye j (measured from single-stained controls).
  • \mathbf b = detector readings for one cell; \mathbf x = dye amounts.
  • Solve A\mathbf x = \mathbf b for every cell: millions of times.

Two dyes, detectors at the two peaks: A = \begin{pmatrix}1 & c\\ c & 1\end{pmatrix}, overlap c. Close peaks give c = 0.95, our matrix.

Recap: elimination as LU

Row 2 minus m = a_{21}/a_{11} times row 1 (the pivot is a_{11}):

\begin{pmatrix}1 & 0.95\\ 0.95 & 1\end{pmatrix} \;\xrightarrow{\;m = 0.95\;}\; \begin{pmatrix}1 & 0.95\\ 0 & 1 - 0.95^2\end{pmatrix} = \begin{pmatrix}1 & 0.95\\ 0 & 0.0975\end{pmatrix} = U, \qquad L = \begin{pmatrix}1 & 0\\ 0.95 & 1\end{pmatrix}

  • A = LU. Solve L\mathbf y = \mathbf b (forward), then U\mathbf x = \mathbf y (back).
  • Each step divides by a pivot u_{kk}. Nothing so far checks its size.
  • Cost \tfrac23 n^3 for the factorisation, 2n^2 per right-hand side (from Gaussian elimination as LU).

A zero pivot, a tiny pivot

solve_nopivot <- function(A, b) {
  n <- nrow(A)
  for (k in 1:(n - 1)) for (i in (k + 1):n) {
    m <- A[i, k] / A[k, k]                 # multiplier
    A[i, ] <- A[i, ] - m * A[k, ];  b[i] <- b[i] - m * b[k]
  }
  backsolve(A, b)                          # back substitution
}
solve_nopivot(matrix(c(0, 1, 1, 0.3), 2, byrow = TRUE), c(1, 1.3))
# Error in backsolve(A, b) : singular matrix in 'backsolve'. First zero in diagonal [1]
A1 <- matrix(c(1e-20, 1, 1, 1), 2, byrow = TRUE)
solve_nopivot(A1, c(1, 2))
# [1] 0 1
solve(A1, c(1, 2))
# [1] 1 1
  • Zero pivot: dye 1 gives no signal in detector 1 (the order of detectors is arbitrary). The multiplier is 1/0; the method stops.
  • Tiny pivot: no warning, and x_1 = 0 instead of 1.

What went wrong

With \delta = 10^{-20}: multiplier m = 1/\delta = 10^{20}.

\begin{pmatrix}\delta & 1 & \mid & 1\\ 1 & 1 & \mid & 2\end{pmatrix} \;\to\; \begin{pmatrix}\delta & 1 & \mid & 1\\ 0 & 1 - 10^{20} & \mid & 2 - 10^{20}\end{pmatrix} \;\approx\; \begin{pmatrix}\delta & 1 & \mid & 1\\ 0 & -10^{20} & \mid & -10^{20}\end{pmatrix}

  • 1 - 10^{20} rounds to -10^{20}: the 1 and the 2 of row 2 are lost (they are below the gap between doubles near 10^{20}).
  • x_2 = 1 (fine), then x_1 = (1 - x_2)/\delta = 0/\delta = 0: catastrophic cancellation, divided by a tiny number.
  • The computed L and U belong to a different matrix: LU has 0 where A has 1 in position (2,2).

Error grows like \varepsilon/\delta

  • Without pivoting the error is about \varepsilon/\delta: every factor 10 smaller pivot costs one digit. Below \delta \approx 10^{-16}: all lost.
  • With pivoting: full accuracy for every \delta. The problem was never hard.

Partial pivoting

Before eliminating column k, swap rows so the entry of largest absolute value in that column (on or below the diagonal) becomes the pivot.

\begin{pmatrix}\delta & 1 & \mid & 1\\ 1 & 1 & \mid & 2\end{pmatrix} \;\xrightarrow{\text{swap}}\; \begin{pmatrix}1 & 1 & \mid & 2\\ \delta & 1 & \mid & 1\end{pmatrix} \;\xrightarrow{m = \delta}\; \begin{pmatrix}1 & 1 & \mid & 2\\ 0 & 1 - \delta & \mid & 1 - 2\delta\end{pmatrix}

  • Now x_2 = (1-2\delta)/(1-\delta) \approx 1, x_1 = 2 - x_2 \approx 1. Correct.
  • Every multiplier satisfies |m| \le 1, so no row is scaled up and swamps another.
  • Swapping rows = reordering the equations (detectors). The solution does not change.

Partial pivoting in code

solve_pivot <- function(A, b) {
  n <- nrow(A)
  for (k in 1:(n - 1)) {
    p <- which.max(abs(A[k:n, k])) + k - 1   # largest entry in column k
    A[c(k, p), ] <- A[c(p, k), ];  b[c(k, p)] <- b[c(p, k)]   # swap rows
    for (i in (k + 1):n) {
      m <- A[i, k] / A[k, k]                 # now |m| <= 1
      A[i, ] <- A[i, ] - m * A[k, ];  b[i] <- b[i] - m * b[k]
    }
  }
  backsolve(A, b)
}
solve_pivot(A1, c(1, 2))
# [1] 1 1
  • Three extra lines. solve() calls LAPACK (dgesv), which does exactly this, in optimised code.

PA = LU

The row swaps are recorded in a permutation matrix P (the identity with its rows reordered):

PA = LU, \qquad A\mathbf x = \mathbf b \;\Longleftrightarrow\; L U\mathbf x = P\mathbf b.

  • Factor once (\tfrac23 n^3), then for each cell: permute \mathbf b, forward and back substitute (2n^2).
  • Partial pivoting is backward stable in practice: the computed \mathbf x is the exact solution of (A + \Delta A)\mathbf x = \mathbf b with \|\Delta A\| \approx \varepsilon \|A\|. (Rare matrices defeat it; they almost never occur in applications.)
  • So after pivoting, any remaining error is the problem’s. To measure it we need the size of a vector and of a matrix.

Pivoting does not rescue the two dyes

solve_pivot(A, c(1.96, 1.94))     # A = [1 0.95; 0.95 1]
# [1] 1.2 0.8
  • Same answer as solve(): it is the exact solution of the perturbed system.
  • The algorithm is innocent. The problem amplifies the 0.5 % change in \mathbf b to 20 % in \mathbf x.
  • To say “0.5 %” and “20 %” for vectors, we need a size: a norm.

Vector norms

A norm \|\mathbf v\| is a length. Three common ones, for \mathbf v = (3, -4, 12):

name formula value
1-norm \|\mathbf v\|_1 = \sum_i \lvert v_i\rvert 3 + 4 + 12 = 19
2-norm (Euclidean) \|\mathbf v\|_2 = \sqrt{\sum_i v_i^2} \sqrt{9 + 16 + 144} = 13
\infty-norm (max) \|\mathbf v\|_\infty = \max_i \lvert v_i\rvert 12
v <- c(3, -4, 12)
c(sum(abs(v)), sqrt(sum(v^2)), max(abs(v)))
# [1] 19 13 12
  • Always \|\mathbf v\|_\infty \le \|\mathbf v\|_2 \le \|\mathbf v\|_1, and they differ by at most a factor n. For error sizes, any of them will do.
  • Relative error of a vector: \|\hat{\mathbf x} - \mathbf x\| / \|\mathbf x\|.

Unit balls

All vectors of norm 1, in 2D:

  • \|\cdot\|_1: a diamond. \|\cdot\|_2: a circle. \|\cdot\|_\infty: a square.
  • Teaser: \Delta\mathbf b = (0.01, -0.01), \mathbf b = (1.95, 1.95). In the 2-norm \|\Delta\mathbf b\|_2/\|\mathbf b\|_2 = 0.01/1.95 = 0.51\,\%.
  • \Delta\mathbf x = (0.2, -0.2), \mathbf x = (1, 1): \|\Delta\mathbf x\|_2/\|\mathbf x\|_2 = 20\,\%.
  • Ratio: 0.2 / 0.005128 = 39.

Matrix norms

How much can A stretch a vector? \;\|A\| = \max_{\mathbf v \ne 0} \dfrac{\|A\mathbf v\|}{\|\mathbf v\|}

norm formula A = \begin{pmatrix}1 & 0.95\\0.95 & 1\end{pmatrix}
\|A\|_1 largest absolute column sum 1.95
\|A\|_\infty largest absolute row sum 1.95
\|A\|_2 largest stretch \sigma_{\max} 1.95
c(norm(A, "1"), norm(A, "I"), norm(A, "2"))
# [1] 1.95 1.95 1.95
svd(A)$d                           # singular values: all stretch factors
# [1] 1.95 0.05
  • \sigma_{\max}, \sigma_{\min}: the largest and smallest singular values. For a symmetric matrix they are the absolute eigenvalues (here 1.95 and 0.05).

A matrix turns a circle into an ellipse

  • Longest axis \sigma_{\max}, shortest \sigma_{\min}. With overlap 0.95, the direction (1, -1) (dye 1 minus dye 2) is squashed to 0.05.
  • Solving A\mathbf x = \mathbf b undoes this: it stretches that direction by 1/\sigma_{\min} = 20.

The condition number of a matrix

\kappa(A) = \|A\|\,\|A^{-1}\| \;\overset{\text{2-norm}}{=}\; \frac{\sigma_{\max}}{\sigma_{\min}}

If A\mathbf x = \mathbf b and A(\mathbf x + \Delta\mathbf x) = \mathbf b + \Delta\mathbf b, then

\frac{\|\Delta \mathbf x\|}{\|\mathbf x\|} \;\le\; \kappa(A)\,\frac{\|\Delta \mathbf b\|}{\|\mathbf b\|}.

  • Why: \Delta\mathbf x = A^{-1}\Delta\mathbf b, so \|\Delta\mathbf x\| \le \|A^{-1}\|\,\|\Delta\mathbf b\|; and \|\mathbf b\| \le \|A\|\,\|\mathbf x\|. Divide.
  • Same idea as \kappa = |x f'/f| in Error, conditioning and stability: amplification of relative errors.
  • \kappa \ge 1 always. \kappa = 1: no amplification. A singular: \kappa = \infty.

Two dyes by hand: \kappa = 39

A^{-1} = \frac{1}{1 - 0.95^2}\begin{pmatrix}1 & -0.95\\ -0.95 & 1\end{pmatrix} = \begin{pmatrix}10.26 & -9.74\\ -9.74 & 10.26\end{pmatrix}

  • \|A\|_\infty = 1.95, \|A^{-1}\|_\infty = 10.26 + 9.74 = 20, so \kappa_\infty = 1.95 \times 20 = 39.
  • 2-norm: \sigma_{\max}/\sigma_{\min} = 1.95/0.05 = 39. Overlap c: \kappa = \dfrac{1 + c}{1 - c}.
  • Worst case: \mathbf b \propto (1, 1) (both dyes, the stretched direction), \Delta\mathbf b \propto (1, -1) (anti-correlated detector errors). The teaser was exactly this: amplification 39.
  • Noise along (1, 1) is not amplified at all (factor 1).

Computing \kappa in R

kappa(A, exact = TRUE)          # 2-norm, from the singular values
# [1] 39
kappa(A)                        # default: a fast estimate
# [1] 39.95
1 / rcond(A)                    # 1-norm estimate, from the LU factors
# [1] 39
  • kappa() without exact = TRUE is an estimate, good to a small factor; enough for counting digits.
  • exact = TRUE costs an SVD (O(n^3), a few times dearer than solve()). rcond() costs only O(n^2) once the LU factors exist.
  • Python: np.linalg.cond(A); Rust (nalgebra): singular_values(), max / min.

Rule of thumb: lose \log_{10}\kappa digits

  • Six dyes, peaks moved closer: \kappa from 1.6 to 10^{10}. Blue: only rounding (\le \kappa\varepsilon). Orange: 1 % noise (\approx \kappa \times 0.01).
  • Rounding alone still leaves 10 of 16 digits at \kappa = 10^6; 2-digit data survive only \kappa \lesssim 10.

Residual vs error

The residual \mathbf r = \mathbf b - A\hat{\mathbf x} is computable; the error \hat{\mathbf x} - \mathbf x is not (we do not know \mathbf x).

b <- c(1.95, 1.95); x <- c(1, 1)                   # true dye amounts
rel <- function(u, v) sqrt(sum((u - v)^2)) / sqrt(sum(v^2))
xa <- c(1.2, 0.8); xb <- c(1.01, 1.01)             # two candidate answers
c(resid = rel(A %*% xa, b), error = rel(xa, x))
#       resid       error
# 0.005128205 0.200000000
c(resid = rel(A %*% xb, b), error = rel(xb, x))
# resid error
#  0.01  0.01
  • xa has the smaller residual but a 20 times larger error.
  • Bound: \dfrac{\|\hat{\mathbf x} - \mathbf x\|}{\|\mathbf x\|} \le \kappa(A)\,\dfrac{\|\mathbf r\|}{\|\mathbf b\|}.

A stable solver always has a small residual

panel <- function(n, spacing, width = 30) {     # Gaussian spectra
  peak <- 500 + spacing * (0:(n - 1))           # dye peaks = detectors (nm)
  outer(peak, peak, function(d, p) exp(-(d - p)^2 / (2 * width^2)))
}
P <- panel(6, 6); xt <- c(5, 1, 3, 2, 4, 1)     # 6 dyes, peaks 6 nm apart
b6 <- drop(P %*% xt);  xh <- solve(P, b6)
c(kappa = kappa(P, exact = TRUE), resid = rel(P %*% xh, b6), error = rel(xh, xt))
#        kappa        resid        error
# 1.141239e+08 1.431645e-16 5.182116e-09
  • Residual at rounding level: solve() did its job (backward stable).
  • Error \approx 10^{8}\times larger: that is \kappa, the problem.
  • Check: residual tells you about the algorithm; \kappa tells you about the problem.

Detector noise in unmixed cells

  • 1000 cells, both dyes at 1 unit, 1 % detector noise. Overlap 0.95: spread \times 9.5, along dye 1 - dye 2.
  • Cytometrists call this spillover spreading: populations smear out after unmixing.

Try it: overlap, \kappa and spreading

What to do about an ill-conditioned unmixing

peak spacing (6 dyes, width 30 nm) 60 nm 30 nm 20 nm 10 nm 5 nm
\kappa 1.6 29 705 6.4\times10^5 7.2\times10^8
sapply(c(60, 30, 20, 10, 5), function(s) kappa(panel(6, s), exact = TRUE))
# [1] 1.644646e+00 2.876870e+01 7.053382e+02 6.373920e+05 7.210988e+08

Checklist: solving A\mathbf x = \mathbf b

  1. Use the library (solve, np.linalg.solve, nalgebra lu().solve): it pivots. Your own elimination without pivoting can fail silently.
  2. Compute \kappa (kappa(A), 1/rcond(A), np.linalg.cond). Expect to lose \log_{10}\kappa digits of your data’s accuracy.
  3. Residual small but answer odd? Then the problem is ill-conditioned; a small residual does not certify the answer.
  4. Perturb \mathbf b by its noise level and re-solve: the spread of \mathbf x is your real uncertainty.
  5. solve() error “computationally singular”: \kappa \gtrsim 10^{16}. Do not just switch to a different solver; rethink the model.

Summary

  • Elimination divides by pivots. Tiny pivot without pivoting: error \approx \varepsilon/\delta, silently. Partial pivoting (largest entry in the column, |m| \le 1) gives PA = LU and is backward stable in practice; solve() does it.
  • Vector norms: \|\cdot\|_1 (sum), \|\cdot\|_2 (length), \|\cdot\|_\infty (max). Matrix norm: largest stretch; column sums, row sums, \sigma_{\max}.
  • Condition number \kappa(A) = \|A\|\|A^{-1}\| = \sigma_{\max}/\sigma_{\min}: relative error in \mathbf x \le \kappa \times relative error in \mathbf b. Lose about \log_{10}\kappa digits.
  • Residual vs error: a stable solver gives a tiny residual; the error can still be \kappa times larger.
  • Two dyes with overlap c: \kappa = (1+c)/(1-c); c = 0.95 gives 39 and a tenfold spread of unmixed cells. Cure the experiment, not the algorithm.
  • Next, Structure: symmetric, banded, sparse: faster solves when A has structure.