Skip to main content

lib_jsl_linalg/
lu.rs

1//! LU factorisation with partial pivoting: `P A = L U`.
2//!
3//! See the book entry [Gaussian elimination and LU factorisation](https://jwkunz.github.io/lib_jsl/book/linear_algebra/lu.html#blocked-and-recursive-factorisation).
4
5use crate::dense::{Mat, axpy_sub, require_square, sub_matmul};
6use crate::error::{LinalgError, Result};
7use crate::scalar::Scalar;
8
9/// A factorised square matrix, reusable for many right-hand sides.
10#[derive(Debug, Clone)]
11pub struct LuFactorization<T> {
12    /// `L` (unit lower, below the diagonal) and `U` (on and above) packed together.
13    pub(crate) lu: Mat<T>,
14    /// Row `i` of `P A` is row `pivots[i]` of `A`.
15    pub(crate) pivots: Vec<usize>,
16}
17
18impl<T: Scalar> LuFactorization<T> {
19    /// Recursive LU (Toledo's algorithm, LAPACK's `getrf2`): factor the left half of the columns,
20    /// solve for the top-right block, update the bottom-right block with one matrix multiply,
21    /// and recurse on it. Nearly all the arithmetic lands in the matrix-multiply kernel, at every
22    /// level of the cache hierarchy.
23    pub(crate) fn new(mut a: Mat<T>) -> Result<Self> {
24        require_square(a.rows, a.cols)?;
25        let n = a.rows;
26        let mut pivots: Vec<usize> = (0..n).collect();
27        let scale = a.data.iter().fold(0.0f64, |m, v| m.max(v.abs())).max(f64::MIN_POSITIVE);
28        recursive_lu(&mut a, &mut pivots, 0, n, f64::EPSILON * scale * 1e-3)?;
29        Ok(LuFactorization { lu: a, pivots })
30    }
31
32    pub fn dimension(&self) -> usize {
33        self.lu.rows
34    }
35
36    /// Solves `A x = b` in place.
37    pub(crate) fn solve_vec(&self, b: &[T]) -> Vec<T> {
38        let n = self.lu.rows;
39        let mut x: Vec<T> = self.pivots.iter().map(|&p| b[p]).collect();
40        for i in 0..n {
41            let row = &self.lu.data[i * n..i * n + i];
42            let s = row.iter().zip(&x[..i]).fold(T::zero(), |acc, (&l, &v)| acc + l * v);
43            x[i] -= s;
44        }
45        for i in (0..n).rev() {
46            let row = &self.lu.data[i * n + i + 1..(i + 1) * n];
47            let s = row.iter().zip(&x[i + 1..]).fold(T::zero(), |acc, (&u, &v)| acc + u * v);
48            x[i] = (x[i] - s) / self.lu.at(i, i);
49        }
50        x
51    }
52
53    /// `X ← L⁻¹ X`, recursively on halves of the rows: the first half is solved, its contribution
54    /// to the second half is subtracted with one matrix multiply, and the second half is solved.
55    /// Only triangles of order [`SOLVE_LEAF`] are done row by row. With `lower_rhs`, `X` is known
56    /// to be lower triangular (as when inverting), and the columns that are still zero are skipped.
57    fn forward(&self, x: &mut Mat<T>, lower_rhs: bool) {
58        self.forward_range(x, 0, self.lu.rows, lower_rhs);
59    }
60
61    fn forward_range(&self, x: &mut Mat<T>, lo: usize, hi: usize, lower_rhs: bool) {
62        let (n, m) = (self.lu.rows, x.cols);
63        let lu = &self.lu.data;
64        if hi - lo <= SOLVE_LEAF {
65            let cols = if lower_rhs { hi } else { m };
66            for i in lo + 1..hi {
67                let (done, rest) = x.data.split_at_mut(i * m);
68                let row = &mut rest[..cols];
69                for k in lo..i {
70                    let l = lu[i * n + k];
71                    if l != T::zero() {
72                        axpy_sub(row, l, &done[k * m..k * m + cols]);
73                    }
74                }
75            }
76            return;
77        }
78        let mid = lo + (hi - lo) / 2;
79        self.forward_range(x, lo, mid, lower_rhs);
80        let cols = if lower_rhs { mid } else { m };
81        let ptr = x.data.as_mut_ptr();
82        // SAFETY: rows lo..mid and rows mid..hi of X are disjoint; L lives in another buffer.
83        unsafe { sub_matmul(hi - mid, mid - lo, cols, lu.as_ptr().add(mid * n + lo), n, ptr.add(lo * m), m, ptr.add(mid * m), m) };
84        self.forward_range(x, mid, hi, lower_rhs);
85    }
86
87    /// `X ← U⁻¹ X`, recursively like [`Self::forward`].
88    fn backward(&self, x: &mut Mat<T>) {
89        self.backward_range(x, 0, self.lu.rows);
90    }
91
92    fn backward_range(&self, x: &mut Mat<T>, lo: usize, hi: usize) {
93        let (n, m) = (self.lu.rows, x.cols);
94        let lu = &self.lu.data;
95        if hi - lo <= SOLVE_LEAF {
96            for i in (lo..hi).rev() {
97                let (head, tail) = x.data.split_at_mut((i + 1) * m);
98                let row = &mut head[i * m..];
99                for k in i + 1..hi {
100                    let u = lu[i * n + k];
101                    if u != T::zero() {
102                        axpy_sub(row, u, &tail[(k - i - 1) * m..(k - i) * m]);
103                    }
104                }
105                let d = T::one() / lu[i * n + i];
106                row.iter_mut().for_each(|r| *r *= d);
107            }
108            return;
109        }
110        let mid = lo + (hi - lo) / 2;
111        self.backward_range(x, mid, hi);
112        let ptr = x.data.as_mut_ptr();
113        // SAFETY: rows lo..mid and rows mid..hi of X are disjoint; U lives in another buffer.
114        unsafe { sub_matmul(mid - lo, hi - mid, m, lu.as_ptr().add(lo * n + mid), n, ptr.add(mid * m), m, ptr.add(lo * m), m) };
115        self.backward_range(x, lo, mid);
116    }
117
118    /// The inverse `A⁻¹ = U⁻¹ L⁻¹ P`: `L⁻¹` costs `n³/3` because it stays lower triangular, then
119    /// one full back substitution and a column permutation (`2n³` with the factorisation, as in
120    /// LAPACK's `getri`).
121    pub(crate) fn inverse(&self) -> Mat<T> {
122        let n = self.lu.rows;
123        let mut x = Mat::identity(n);
124        self.forward(&mut x, true);
125        self.backward(&mut x);
126        // (M P)[:, pivots[i]] = M[:, i].
127        let mut inv = Mat::zeros(n, n);
128        for (row_in, row_out) in x.data.chunks_exact(n.max(1)).zip(inv.data.chunks_exact_mut(n.max(1))) {
129            for (i, &p) in self.pivots.iter().enumerate() {
130                row_out[p] = row_in[i];
131            }
132        }
133        inv
134    }
135
136    /// The determinant.
137    pub fn determinant(&self) -> T {
138        let n = self.lu.rows;
139        // The sign of the permutation from its cycle structure.
140        let mut seen = vec![false; n];
141        let mut sign = 1.0;
142        for i in 0..n {
143            if seen[i] {
144                continue;
145            }
146            let (mut j, mut length) = (i, 0);
147            while !seen[j] {
148                seen[j] = true;
149                j = self.pivots[j];
150                length += 1;
151            }
152            if length % 2 == 0 {
153                sign = -sign;
154            }
155        }
156        (0..n).fold(T::from_real(sign), |acc, i| acc * self.lu.at(i, i))
157    }
158}
159
160/// Panels up to this width are factorised in column-major order.
161const LEAF: usize = 32;
162
163/// Triangular blocks up to this order are solved row by row.
164const SOLVE_LEAF: usize = 16;
165
166// ANCHOR: recursive_lu
167/// Factorises the panel of columns `k..k + w` (rows `k..n`) of the square buffer in place,
168/// swapping whole rows so that every column sees the same permutation.
169fn recursive_lu<T: Scalar>(a: &mut Mat<T>, pivots: &mut [usize], k: usize, w: usize, threshold: f64) -> Result<()> {
170    let n = a.cols;
171    if w <= LEAF {
172        return unblocked_panel(a, pivots, k, w, threshold);
173    }
174    let w1 = w / 2;
175    recursive_lu(a, pivots, k, w1, threshold)?;
176    // A₁₂ ← L₁₁⁻¹ A₁₂ (rows k..k+w1, columns k+w1..k+w).
177    unit_lower_solve(a, k, w1, k + w1, w - w1);
178    // A₂₂ ← A₂₂ − A₂₁ A₁₂ (rows k+w1..n, columns k+w1..k+w).
179    let ptr = a.data.as_mut_ptr();
180    // SAFETY: A₂₁ (columns k..k+w1, rows ≥ k+w1), A₁₂ (rows k..k+w1) and A₂₂ are disjoint.
181    unsafe { sub_matmul(n - k - w1, w1, w - w1, ptr.add((k + w1) * n + k), n, ptr.add(k * n + k + w1), n, ptr.add((k + w1) * n + k + w1), n) };
182    recursive_lu(a, pivots, k + w1, w - w1, threshold)
183}
184// ANCHOR_END: recursive_lu
185
186/// Factorises the panel of columns `k..k + w` (rows `k..n`). The narrow panel is copied to
187/// column-major order, where pivot searches and eliminations run along long contiguous columns,
188/// and factorised there recursively; the row interchanges are then applied to the rest of the
189/// matrix.
190fn unblocked_panel<T: Scalar>(a: &mut Mat<T>, pivots: &mut [usize], k: usize, w: usize, threshold: f64) -> Result<()> {
191    let n = a.cols;
192    let m = n - k;
193    let mut panel = vec![T::zero(); w * m];
194    for i in 0..m {
195        for j in 0..w {
196            panel[j * m + i] = a.data[(k + i) * n + k + j];
197        }
198    }
199    let mut local = vec![0usize; w];
200    column_major_lu(&mut panel, m, w, 0, w, &mut local, threshold).map_err(|c| LinalgError::Singular(k + c))?;
201    for (c, &r) in local.iter().enumerate() {
202        if r != c {
203            let (top, bottom) = a.data.split_at_mut((k + r) * n);
204            let (upper, lower) = (&mut top[(k + c) * n..(k + c + 1) * n], &mut bottom[..n]);
205            upper[..k].swap_with_slice(&mut lower[..k]);
206            upper[k + w..].swap_with_slice(&mut lower[k + w..]);
207            pivots.swap(k + c, k + r);
208        }
209    }
210    for i in 0..m {
211        for j in 0..w {
212            a.data[(k + i) * n + k + j] = panel[j * m + i];
213        }
214    }
215    Ok(())
216}
217
218/// Recursive LU of columns `c0..c0 + w` (rows `c0..m`) of an `m × total` column-major panel,
219/// recording in `local[c]` the row swapped with row `c`. Swaps act on all `total` columns.
220/// Returns the failing column if a pivot is negligible.
221fn column_major_lu<T: Scalar>(p: &mut [T], m: usize, total: usize, c0: usize, w: usize, local: &mut [usize], threshold: f64) -> std::result::Result<(), usize> {
222    if w <= 8 {
223        for c in c0..c0 + w {
224            let column = &p[c * m..(c + 1) * m];
225            let (piv, big) = (c..m).map(|i| (i, column[i].abs())).fold((c, -1.0), |best, x| if x.1 > best.1 { x } else { best });
226            if big <= threshold || big == 0.0 {
227                return Err(c);
228            }
229            local[c] = piv;
230            if piv != c {
231                for j in 0..total {
232                    p.swap(j * m + c, j * m + piv);
233                }
234            }
235            let (left, right) = p.split_at_mut((c + 1) * m);
236            let column = &mut left[c * m..];
237            let inverse_pivot = T::one() / column[c];
238            column[c + 1..].iter_mut().for_each(|x| *x *= inverse_pivot);
239            let multipliers = &column[c + 1..];
240            for later in right.chunks_exact_mut(m).take(c0 + w - c - 1) {
241                let f = later[c];
242                if f != T::zero() {
243                    axpy_sub(&mut later[c + 1..], f, multipliers);
244                }
245            }
246        }
247        return Ok(());
248    }
249    let w1 = w / 2;
250    let (mid, end) = (c0 + w1, c0 + w);
251    column_major_lu(p, m, total, c0, w1, local, threshold)?;
252    // A₁₂ ← L₁₁⁻¹ A₁₂, column by column.
253    for j in mid..end {
254        let (left, right) = p.split_at_mut(j * m);
255        let x = &mut right[c0..mid];
256        for q in c0..mid {
257            let f = x[q - c0];
258            if f != T::zero() {
259                axpy_sub(&mut x[q - c0 + 1..], f, &left[q * m + q + 1..q * m + mid]);
260            }
261        }
262    }
263    // A₂₂ ← A₂₂ − A₂₁ A₁₂ with column-major strides (row stride 1, column stride m).
264    let ptr = p.as_mut_ptr();
265    let ms = m as isize;
266    // SAFETY: A₂₁ (columns c0..mid), A₁₂ (rows c0..mid of columns mid..end) and A₂₂ (rows ≥ mid of
267    // columns mid..end) are disjoint parts of the panel.
268    unsafe { T::gemm_sub(m - mid, w1, w - w1, ptr.add(c0 * m + mid), 1, ms, ptr.add(mid * m + c0), 1, ms, ptr.add(mid * m + mid), 1, ms) };
269    column_major_lu(p, m, total, mid, w - w1, local, threshold)
270}
271
272/// `X ← L⁻¹ X` for the unit lower triangle `L` of order `w` at `(k, k)` and the block `X` in
273/// rows `k..k + w`, columns `c..c + nc`, recursively so that most of the work is a multiply.
274fn unit_lower_solve<T: Scalar>(a: &mut Mat<T>, k: usize, w: usize, c: usize, nc: usize) {
275    let n = a.cols;
276    if w <= SOLVE_LEAF {
277        for r in k + 1..k + w {
278            let (top, bottom) = a.data.split_at_mut(r * n);
279            // Row r holds its multipliers (columns k..r) to the left of its block of X (c ≥ k + w).
280            let (multipliers, right) = bottom.split_at_mut(c);
281            let row = &mut right[..nc];
282            for p in k..r {
283                let l = multipliers[p];
284                if l != T::zero() {
285                    axpy_sub(row, l, &top[p * n + c..p * n + c + nc]);
286                }
287            }
288        }
289        return;
290    }
291    let h = w / 2;
292    unit_lower_solve(a, k, h, c, nc);
293    let ptr = a.data.as_mut_ptr();
294    // SAFETY: L₂₁ (rows k+h..k+w, columns k..k+h), X₁ (rows k..k+h, columns c..) and
295    // X₂ (rows k+h..k+w, columns c..) are disjoint because c ≥ k + w.
296    unsafe { sub_matmul(w - h, h, nc, ptr.add((k + h) * n + k), n, ptr.add(k * n + c), n, ptr.add((k + h) * n + c), n) };
297    unit_lower_solve(a, k + h, w - h, c, nc);
298}