Skip to main content

lib_jsl_linalg_reference/
lu.rs

1//! The LU factorisation `P A = L U` (Doolittle form, unit lower triangular `L`).
2//!
3//! Gaussian elimination secretly computes `L` (the multipliers) and `U` (the reduced matrix).
4//! Keeping them lets you solve `A x = b` for any number of right-hand sides at `O(n²)` each after
5//! one `O(n³)` factorisation, and gives the determinant as the product of the pivots.
6//!
7//! See the book entry [Gaussian elimination and LU factorisation](https://jwkunz.github.io/lib_jsl/book/linear_algebra/lu.html#lu-factorisation).
8
9use crate::Error;
10use ndarray::{Array1, Array2};
11
12/// `P A = L U` with the permutation stored as a row order.
13#[derive(Debug, Clone)]
14pub struct Lu {
15    /// Unit lower triangular factor.
16    pub l: Array2<f64>,
17    /// Upper triangular factor.
18    pub u: Array2<f64>,
19    /// Row `i` of `P A` is row `rows[i]` of `A`.
20    pub rows: Vec<usize>,
21    /// The number of row swaps (for the determinant's sign).
22    pub swaps: usize,
23}
24
25// ANCHOR: doolittle
26/// Factorises a square matrix with partial pivoting.
27pub fn lu(a: &Array2<f64>) -> Result<Lu, Error> {
28    let n = a.nrows();
29    let mut u = a.clone();
30    let mut l = crate::identity(n);
31    let mut rows: Vec<usize> = (0..n).collect();
32    let mut swaps = 0;
33    for k in 0..n {
34        let p = (k..n).max_by(|&i, &j| u[[i, k]].abs().total_cmp(&u[[j, k]].abs())).ok_or("empty matrix")?;
35        if u[[p, k]] == 0.0 {
36            return Err("the matrix is singular");
37        }
38        if p != k {
39            for j in 0..n {
40                u.swap([k, j], [p, j]);
41            }
42            // Multipliers already computed move with their rows.
43            for j in 0..k {
44                l.swap([k, j], [p, j]);
45            }
46            rows.swap(k, p);
47            swaps += 1;
48        }
49        for i in k + 1..n {
50            l[[i, k]] = u[[i, k]] / u[[k, k]];
51            for j in k..n {
52                u[[i, j]] -= l[[i, k]] * u[[k, j]];
53            }
54        }
55    }
56    Ok(Lu { l, u, rows, swaps })
57}
58// ANCHOR_END: doolittle
59
60impl Lu {
61    /// Solves `A x = b`: permute, then `L y = P b` forward and `U x = y` backward.
62    pub fn solve(&self, b: &Array1<f64>) -> Result<Array1<f64>, Error> {
63        let n = self.l.nrows();
64        let mut y = Array1::zeros(n);
65        for i in 0..n {
66            y[i] = b[self.rows[i]] - (0..i).map(|j| self.l[[i, j]] * y[j]).sum::<f64>();
67        }
68        crate::gaussian_elimination::back_substitute(&self.u, &y)
69    }
70
71    /// `det A = (−1)^{swaps} Π u_ii`.
72    pub fn determinant(&self) -> f64 {
73        let sign = if self.swaps.is_multiple_of(2) { 1.0 } else { -1.0 };
74        sign * (0..self.u.nrows()).map(|i| self.u[[i, i]]).product::<f64>()
75    }
76
77    /// The inverse, one column `A x = e_j` at a time.
78    pub fn inverse(&self) -> Result<Array2<f64>, Error> {
79        let n = self.l.nrows();
80        let mut inv = Array2::zeros((n, n));
81        for j in 0..n {
82            let e = Array1::from_shape_fn(n, |i| if i == j { 1.0 } else { 0.0 });
83            inv.column_mut(j).assign(&self.solve(&e)?);
84        }
85        Ok(inv)
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use crate::random_matrix;
93    use ndarray::array;
94
95    #[test]
96    fn factors_reconstruct_and_solve() {
97        let a = random_matrix(12, 12, 2);
98        let f = lu(&a).unwrap();
99        let pa = Array2::from_shape_fn((12, 12), |(i, j)| a[[f.rows[i], j]]);
100        assert!((f.l.dot(&f.u) - pa).iter().all(|v| v.abs() < 1e-12));
101        let b = Array1::from_iter((0..12).map(|i| (i as f64).sin()));
102        assert!((a.dot(&f.solve(&b).unwrap()) - &b).iter().all(|v| v.abs() < 1e-10));
103        assert!((a.dot(&f.inverse().unwrap()) - crate::identity(12)).iter().all(|v| v.abs() < 1e-10));
104        assert!((lu(&array![[2.0, 1.0], [7.0, 4.0]]).unwrap().determinant() - 1.0).abs() < 1e-14);
105        assert!((lu(&array![[0.0, 1.0], [1.0, 0.0]]).unwrap().determinant() + 1.0).abs() < 1e-15);
106    }
107}