lib_jsl_linalg_reference/cholesky.rs
1//! The Cholesky factorisation `A = L Lᵀ` of a symmetric positive-definite matrix.
2//!
3//! Comparing entries of `A = L Lᵀ` row by row (the Cholesky-Banachiewicz order) gives each entry
4//! of `L` from those already known:
5//!
6//! `l_jj = √(a_jj − Σ_{k<j} l_jk²)`, `l_ij = (a_ij − Σ_{k<j} l_ik l_jk) / l_jj` for `i > j`.
7//!
8//! It costs half as much as LU, needs no pivoting (the diagonal of a positive-definite matrix
9//! dominates), and doubles as a test for positive definiteness: the square root fails exactly
10//! when `A` is not positive definite.
11//!
12//! See the book entry [Cholesky factorisation](https://jwkunz.github.io/lib_jsl/book/linear_algebra/cholesky.html).
13
14use crate::Error;
15use ndarray::Array2;
16
17// ANCHOR: banachiewicz
18/// The lower Cholesky factor `L`.
19pub fn cholesky(a: &Array2<f64>) -> Result<Array2<f64>, Error> {
20 let n = a.nrows();
21 let mut l = Array2::zeros((n, n));
22 for i in 0..n {
23 for j in 0..=i {
24 let sum: f64 = (0..j).map(|k| l[[i, k]] * l[[j, k]]).sum();
25 if i == j {
26 let d = a[[i, i]] - sum;
27 if d <= 0.0 {
28 return Err("the matrix is not positive definite");
29 }
30 l[[i, i]] = d.sqrt();
31 } else {
32 l[[i, j]] = (a[[i, j]] - sum) / l[[j, j]];
33 }
34 }
35 }
36 Ok(l)
37}
38// ANCHOR_END: banachiewicz
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43 use ndarray::array;
44
45 #[test]
46 fn reconstructs_and_detects_indefinite_matrices() {
47 let a = crate::random_positive_definite(15, 3);
48 let l = cholesky(&a).unwrap();
49 assert!((l.dot(&l.t()) - &a).iter().all(|v| v.abs() < 1e-10));
50 assert!(l.indexed_iter().all(|((i, j), v)| j <= i || *v == 0.0));
51 assert!(cholesky(&array![[1.0, 2.0], [2.0, 1.0]]).is_err());
52 }
53}