Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Cholesky factorisation

ProblemFactor a symmetric (Hermitian) positive definite matrix as with lower triangular; solve systems with it; test positive definiteness
Devised byAndré-Louis Cholesky (about 1910, published posthumously by Ernest Benoît in 1924); Tadeusz Banachiewicz (1938), the row-oriented form; blocked algorithms: the LAPACK project (1992)
AccuracyBackward stable without any pivoting: the computed factor satisfies with
Cost flops, half of LU; per solve
Read firstGaussian elimination and LU factorisation
APICholesky, SolveTriangular, UPLO, Diag; reference: cholesky

Overview

A matrix is symmetric positive definite if and for every . Such matrices are everywhere: covariance matrices in statistics, stiffness matrices in structural mechanics and finite elements, the normal equations of least squares, Gram matrices of kernel methods, the Hessians of convex functions at a minimum. For them, Gaussian elimination simplifies into the Cholesky factorisation : half the work, half the storage, no pivoting, and guaranteed stability. It also answers a question in passing: the factorisation succeeds exactly when the matrix is positive definite, which makes it the cheapest test for that property.

Beyond solving systems, the Cholesky factor generates correlated random vectors ( has covariance when has independent standard normal entries), computes Mahalanobis distances and log-determinants (), and whitens data.

Where it is used

Cholesky is the fastest way to solve a symmetric positive definite system.

  • Least squares and statistics. The normal equations of regression, and the covariance matrices of multivariate normal distributions (which are sampled using their Cholesky factor).
  • Optimisation. Newton and interior-point methods solve a positive definite system at every step.
  • Finite elements and structures. Stiffness matrices are positive definite, and sparse Cholesky solves them.
  • Kalman filtering and Gaussian processes. Covariance updates and likelihoods use Cholesky factors for numerical stability.

History

André-Louis Cholesky, a French artillery officer and geodesist, devised the method around 1910 to solve the normal equations of geodetic surveys in Crete and North Africa. He was killed in the First World War in 1918, and his method was published by his colleague Ernest Benoît in 1924. Tadeusz Banachiewicz, a Polish astronomer, independently developed it in 1938 in his “Cracovian” matrix notation, in the row-by-row order that bears his name. Alan Turing and James Wilkinson analysed its stability in the 1940s and 1960s, showing that it needs no pivoting at all.

The idea

The factorisation

We look for a lower triangular matrix with . For a matrix, writing out the product shows how the entries of can be found one at a time:

The top left entry gives . The off-diagonal entry then gives , and the last gives . For this yields , and .

The same comparison of entries works for any size. Entry of is the dot product of rows and of , for . Setting it equal to and solving for the one entry not yet known gives

Working through the matrix row by row (or column by column), every entry on the right has already been computed when it is needed. The cost is about flops, half that of LU, because symmetry means only half the matrix has to be processed.

Three properties make this factorisation special.

  • It tests positive definiteness. The quantity under the square root is positive at every step if and only if is positive definite. (It equals the ratio of successive leading principal minors of , the determinants of its top left blocks, and a symmetric matrix is positive definite exactly when all of these are positive.) So the algorithm either succeeds, or meets a non-positive number under a square root and reports that is not positive definite.
  • It needs no pivoting. The diagonal entries of are , so every entry of row of satisfies . The entries of cannot grow beyond the size of those of . There is no growth factor to worry about, and the algorithm is backward stable as it stands.
  • It solves systems like LU. is solved by forward substitution with followed by back substitution with .

For complex Hermitian matrices the same formulas hold with the conjugate transpose and .

Table 7.4. Cholesky against LU on definite, indefinite and singular matrices.

matrixCholeskyLU
, positive definitesucceedssucceeds
, indefinite (eigenvalues 3, −1)fails: the matrix is not positive definite (pivot 1)succeeds
, semidefinite (singular)fails: the matrix is not positive definite (pivot 1)fails: the matrix is singular (zero pivot at step 1)
Hilbert matrix of order 12, positive definite with succeedssucceeds

The Hilbert matrix of order 12, with condition number near , is still factorised: positive definiteness is decided by the rounded arithmetic, and a matrix closer to singularity may be reported as indefinite even though it is not.

The blocked algorithm

As with LU, the formulas update one entry at a time, and run at the speed of memory. The right-looking blocked algorithm processes a block of columns at a time: factor the diagonal block by the unblocked method; solve for the panel below it; and update the trailing matrix, , a symmetric rank- update done by the matrix-multiply kernel, on the lower triangle only. The update holds almost all the arithmetic.

The library’s block size is 16. In the speed figure the blocked Cholesky reaches about 7 GFLOP/s, a third of the rate of the recursive LU. It is still faster in time, since it does half the work, but it trails OpenBLAS by up to 1.8 times for small matrices.

Algorithm

Cholesky-Banachiewicz (the reference crate). Input: a symmetric (or Hermitian) matrix , of which only the lower triangle is read. For each row :

  1. for , compute , a dot product of the parts of rows and already computed;
  2. compute ; if , stop and report that is not positive definite; otherwise .

The cost is flops.

Blocked Cholesky (the production crate). Copy the given triangle into , and process the columns in blocks of 16. For each block, with the diagonal block, the panel below it and the trailing matrix:

  1. factor the diagonal block, , by the unblocked method, failing if a diagonal quantity is not positive;
  2. solve for the panel (a triangular solve for each row);
  3. update the lower triangle of the trailing matrix, , with the matrix-multiply kernel.

Solving with the factor: forward substitution for , then back substitution for , flops in all.

Implementation

The textbook algorithm:

/// The lower Cholesky factor `L`.
pub fn cholesky(a: &Array2<f64>) -> Result<Array2<f64>, Error> {
    let n = a.nrows();
    let mut l = Array2::zeros((n, n));
    for i in 0..n {
        for j in 0..=i {
            let sum: f64 = (0..j).map(|k| l[[i, k]] * l[[j, k]]).sum();
            if i == j {
                let d = a[[i, i]] - sum;
                if d <= 0.0 {
                    return Err("the matrix is not positive definite");
                }
                l[[i, i]] = d.sqrt();
            } else {
                l[[i, j]] = (a[[i, j]] - sum) / l[[j, j]];
            }
        }
    }
    Ok(l)
}

The production loop over blocks:

    for k in (blocked_from..n).step_by(BLOCK) {
        let kb = BLOCK.min(n - k);
        factor_diagonal_block(&mut l, k, kb)?;
        let rest = n - k - kb;
        if rest == 0 {
            break;
        }
        // Panel: each row r of A₂₁ becomes x with x L₁₁ᴴ = r, by forward substitution.
        let (head, tail) = l.data.split_at_mut((k + kb) * n);
        for i in 0..rest {
            let row = &mut tail[i * n + k..i * n + k + kb];
            for j in 0..kb {
                let ljj = &head[(k + j) * n + k..(k + j) * n + k + j + 1];
                let s = row[j] - dot_conj(&row[..j], &ljj[..j]);
                row[j] = s.scale(1.0 / ljj[j].re());
            }
        }
        // Trailing update A₂₂ ← A₂₂ − L₂₁ L₂₁ᴴ, block row by block row, lower part only.
        // L₂₁ᴴ is copied out explicitly (the complex kernel cannot conjugate on the fly).
        panel_adjoint.clear();
        panel_adjoint.resize(kb * rest, T::zero());
        for i in 0..rest {
            for j in 0..kb {
                panel_adjoint[j * rest + i] = tail[i * n + k + j].conj();
            }
        }
        for i0 in (0..rest).step_by(BLOCK) {
            let ib = BLOCK.min(rest - i0);
            let ptr = tail.as_mut_ptr();
            // SAFETY: C (columns ≥ k + kb) is disjoint from A (columns k..k + kb) and from B,
            // which lives in a separate buffer; all three lie inside `tail` / `panel_adjoint`.
            unsafe {
                sub_matmul(
                    ib,
                    kb,
                    i0 + ib,
                    ptr.add(i0 * n + k),
                    n,
                    panel_adjoint.as_ptr(),
                    rest,
                    ptr.add(i0 * n + k + kb),
                    n,
                );
            }
        }
    }
  • cholesky(UPLO::Lower) reads the lower triangle and returns ; UPLO::Upper reads the upper triangle and returns . The other triangle of the input is ignored.
  • solve_triangular(uplo, diag, b) solves with a triangular matrix and a vector or matrix right-hand side; Diag::Unit assumes a unit diagonal.
  • A non-positive pivot is reported as NotPositiveDefinite with its index.

In practice

//! Cholesky factorisation of symmetric positive-definite matrices.
//!
//! Run with `cargo run -p lib_jsl_linalg_reference --example linalg_cholesky`.

use lib_jsl_linalg::{Cholesky, Diag, SolveTriangular, UPLO};
use lib_jsl_linalg_reference::cholesky::cholesky;
use ndarray::array;

fn main() {
    // A covariance matrix: symmetric and positive definite.
    let c = array![[4.0, 1.2, 0.8], [1.2, 2.0, 0.3], [0.8, 0.3, 1.0]];
    let l = c.cholesky(UPLO::Lower).unwrap();
    println!("L =\n{l:.6}");
    println!("reference factor agrees: {}", (&l - &cholesky(&c).unwrap()).iter().all(|v| v.abs() < 1e-14));

    // Solve C x = b with two triangular solves: L y = b, then Lᵀ x = y.
    let b = array![1.0, 2.0, 3.0];
    let y = l.solve_triangular(UPLO::Lower, Diag::NonUnit, &b).unwrap();
    let x = l.t().solve_triangular(UPLO::Upper, Diag::NonUnit, &y).unwrap();
    println!("x = {x:.6}, residual {:.1e}", (c.dot(&x) - &b).iter().fold(0.0f64, |m, v| m.max(v.abs())));

    // Correlated random samples: if z has independent standard normal entries, L z has covariance C.
    let z = array![0.3, -1.1, 0.7];
    println!("correlated sample L z = {:.6}", l.dot(&z));

    // Cholesky is also the cheapest test of positive definiteness.
    println!("indefinite matrix: {:?}", array![[1.0, 2.0], [2.0, 1.0]].cholesky(UPLO::Lower));
}

Strengths

  • Half the cost of LU, no pivoting, unconditionally stable.
  • A built-in test of positive definiteness.

Weaknesses

  • Only for Hermitian positive definite matrices; for symmetric indefinite matrices, the factorisation with Bunch-Kaufman pivoting (not provided) is the analogue.

Exercises

  1. Show that the diagonal quantity at step is the ratio of the -th and -th leading principal minors.
  2. Prove that , and deduce that the factorisation cannot suffer element growth.
  3. Generate 10 000 samples of with and check that their sample covariance approaches .
  4. Compute for a positive definite matrix from the Cholesky factor, and compare with the logarithm of det. Which overflows?
  5. Factor the matrix for and explain the results.
Hints and answers
  1. After steps the leading block of has been reduced to , and . The ratio of consecutive determinants is , the quantity under the square root, which is positive exactly when the leading minors are.
  2. Row of gives , so . Every entry of is bounded by the square root of a diagonal entry of , so there is no growth.
  3. . The sample covariance errors shrink like , about 1% of the entries’ scale.
  4. is a sum of moderate numbers. The determinant itself is a product of 500 factors and overflows double precision (about ) as soon as the typical eigenvalue exceeds about .
  5. has the factor in exact arithmetic. For the stored carries a relative error of in , so has about eight digits. For and , rounds to exactly (the rounding unit is ), the stored matrix is singular, and the factorisation reports that it is not positive definite.

Further reading

  • C. Brezinski, “The life and work of André Cholesky”, Numerical Algorithms 43 (2006) 279–288.
  • N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM, 2002, chapter 10.
  • G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed., Johns Hopkins University Press, 2013, §4.2.