Skip to main content

lib_jsl_linalg/
factorizations.rs

1//! Further matrix decompositions with SciPy's conventions: QR with optional column pivoting,
2//! RQ, the Hessenberg and real Schur forms, the Bunch-Kaufman `LDLᵀ` (or `LDLᴴ`) factorisation,
3//! the polar decomposition, principal angles between subspaces, and general matrix functions by
4//! the Schur-Parlett method. The Householder reflectors follow LAPACK's `larfg` sign convention,
5//! so the factors agree with SciPy's entry by entry, not merely up to signs.
6//!
7//! See the book entry [Further factorisations](https://jwkunz.github.io/lib_jsl/book/linear_algebra/factorizations.html).
8
9use crate::dense::Mat;
10use crate::error::{LinalgError, Result};
11use crate::scalar::Scalar;
12use crate::{SVD, orth, schur_complex};
13use ndarray::{Array1, Array2, ArrayBase, Data, Ix2, s};
14use num_complex::Complex;
15
16type C = Complex<f64>;
17
18fn zeros<T: Scalar>(rows: usize, cols: usize) -> Array2<T> {
19    Array2::from_elem((rows, cols), T::zero())
20}
21
22fn eye<T: Scalar>(n: usize) -> Array2<T> {
23    Array2::from_shape_fn((n, n), |(i, j)| if i == j { T::one() } else { T::zero() })
24}
25
26fn matmul<T: Scalar>(a: &Array2<T>, b: &Array2<T>) -> Array2<T> {
27    Array2::from_shape_fn((a.nrows(), b.ncols()), |(i, j)| (0..a.ncols()).fold(T::zero(), |acc, k| acc + a[(i, k)] * b[(k, j)]))
28}
29
30fn adjoint<T: Scalar>(a: &Array2<T>) -> Array2<T> {
31    Array2::from_shape_fn((a.ncols(), a.nrows()), |(i, j)| a[(j, i)].conj())
32}
33
34fn check_finite<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>) -> Result<Array2<T>> {
35    if a.iter().any(|v| !v.is_finite()) {
36        return Err(LinalgError::NonFinite);
37    }
38    Ok(a.to_owned())
39}
40
41// ANCHOR: larfg
42/// LAPACK's `larfg`: the reflector `H = I − τ v vᴴ`, `v = (1, x̂)`, with `Hᴴ (α, x) = (β, 0)` and
43/// `β = −sign(Re α) ‖(α, x)‖` real. Overwrites `x` with `x̂` and returns `(β, τ)`; `τ = 0` (no
44/// reflection) when `x = 0` and `α` is real.
45fn larfg<T: Scalar>(alpha: T, x: &mut [T]) -> (T, T) {
46    let xnorm = x.iter().map(|v| v.abs_sqr()).sum::<f64>().sqrt();
47    if xnorm == 0.0 && alpha.im() == 0.0 {
48        return (alpha, T::zero());
49    }
50    let norm = (alpha.abs_sqr() + xnorm * xnorm).sqrt();
51    let beta = T::from_real(if alpha.re() >= 0.0 { -norm } else { norm });
52    let tau = (beta - alpha) / beta;
53    let scale = T::one() / (alpha - beta);
54    x.iter_mut().for_each(|v| *v *= scale);
55    (beta, tau)
56}
57// ANCHOR_END: larfg
58
59/// `A[rows, cols] ← (I − τ v vᴴ) A[rows, cols]`, with `v` laid along `rows`.
60fn reflect_left<T: Scalar>(a: &mut Array2<T>, v: &[T], tau: T, row0: usize, cols: std::ops::Range<usize>) {
61    if tau == T::zero() {
62        return;
63    }
64    for j in cols {
65        let w = v.iter().enumerate().fold(T::zero(), |acc, (i, &vi)| acc + vi.conj() * a[(row0 + i, j)]);
66        let tw = tau * w;
67        for (i, &vi) in v.iter().enumerate() {
68            a[(row0 + i, j)] -= vi * tw;
69        }
70    }
71}
72
73/// `A[rows, cols] ← A[rows, cols] (I − τ v vᴴ)`, with `v` laid along `cols`.
74fn reflect_right<T: Scalar>(a: &mut Array2<T>, v: &[T], tau: T, rows: std::ops::Range<usize>, col0: usize) {
75    if tau == T::zero() {
76        return;
77    }
78    for i in rows {
79        let w = v.iter().enumerate().fold(T::zero(), |acc, (j, &vj)| acc + a[(i, col0 + j)] * vj);
80        let tw = tau * w;
81        for (j, &vj) in v.iter().enumerate() {
82            a[(i, col0 + j)] -= tw * vj.conj();
83        }
84    }
85}
86
87/// How much of a QR (or RQ) factorisation to return (SciPy's `mode`).
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
89#[non_exhaustive]
90pub enum QrMode {
91    /// `Q` square (`m × m` for QR, `n × n` for RQ).
92    Full,
93    /// `Q` with `min(m, n)` columns (QR) or rows (RQ), and `R` to match.
94    Economic,
95}
96
97/// A QR factorisation `A P = Q R` (`P` the identity without pivoting).
98#[derive(Clone, Debug)]
99#[non_exhaustive]
100pub struct QrFactors<T> {
101    pub q: Array2<T>,
102    pub r: Array2<T>,
103    /// The column permutation: column `j` of `A P` is column `permutation[j]` of `A`.
104    pub permutation: Vec<usize>,
105}
106
107/// The Householder QR of `a`, optionally with column pivoting, as LAPACK's `geqr2` and `laqp2`:
108/// returns the overwritten matrix (`R` above the diagonal, reflectors below), the `τ`s and the
109/// permutation.
110fn householder_qr<T: Scalar>(mut a: Array2<T>, pivoting: bool) -> (Array2<T>, Vec<T>, Vec<usize>) {
111    let (m, n) = a.dim();
112    let k = m.min(n);
113    let mut jpvt: Vec<usize> = (0..n).collect();
114    let col_norm = |a: &Array2<T>, j: usize, from: usize| (from..m).map(|i| a[(i, j)].abs_sqr()).sum::<f64>().sqrt();
115    let mut vn1: Vec<f64> = (0..n).map(|j| col_norm(&a, j, 0)).collect();
116    let mut vn2 = vn1.clone();
117    let tol3z = f64::EPSILON.sqrt();
118    let mut taus = Vec::with_capacity(k);
119    for i in 0..k {
120        if pivoting {
121            // The first column of largest remaining norm (LAPACK's idamax).
122            let mut pvt = i;
123            for j in i + 1..n {
124                if vn1[j] > vn1[pvt] {
125                    pvt = j;
126                }
127            }
128            if pvt != i {
129                for r in 0..m {
130                    a.swap((r, pvt), (r, i));
131                }
132                jpvt.swap(pvt, i);
133                vn1[pvt] = vn1[i];
134                vn2[pvt] = vn2[i];
135            }
136        }
137        let alpha = a[(i, i)];
138        let mut x: Vec<T> = (i + 1..m).map(|r| a[(r, i)]).collect();
139        let (beta, tau) = larfg(alpha, &mut x);
140        let mut v = vec![T::one()];
141        v.extend_from_slice(&x);
142        a[(i, i)] = beta;
143        for (r, &xv) in x.iter().enumerate() {
144            a[(i + 1 + r, i)] = xv;
145        }
146        // Apply Hᴴ from the left to the trailing columns.
147        reflect_left(&mut a, &v, tau.conj(), i, i + 1..n);
148        taus.push(tau);
149        if pivoting {
150            // Downdate the partial column norms, recomputing them when cancellation threatens.
151            for j in i + 1..n {
152                if vn1[j] != 0.0 {
153                    let t = (1.0 - (a[(i, j)].abs() / vn1[j]).powi(2)).max(0.0);
154                    let t2 = t * (vn1[j] / vn2[j]).powi(2);
155                    if t2 <= tol3z {
156                        if i + 1 < m {
157                            vn1[j] = col_norm(&a, j, i + 1);
158                            vn2[j] = vn1[j];
159                        } else {
160                            vn1[j] = 0.0;
161                            vn2[j] = 0.0;
162                        }
163                    } else {
164                        vn1[j] *= t.sqrt();
165                    }
166                }
167            }
168        }
169    }
170    (a, taus, jpvt)
171}
172
173// ANCHOR: qr
174/// The QR factorisation `A P = Q R` (SciPy's `qr`, with `pivoting` its `pivoting=True`): `Q` has
175/// orthonormal columns, `R` is upper triangular (trapezoidal), and with pivoting the columns are
176/// chosen in order of largest remaining norm, so that `|R₁₁| ≥ |R₂₂| ≥ …`, which reveals the rank.
177pub fn qr<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, mode: QrMode, pivoting: bool) -> Result<QrFactors<T>> {
178    let a = check_finite(a)?;
179    let (m, n) = a.dim();
180    let k = m.min(n);
181    let (f, taus, permutation) = householder_qr(a, pivoting);
182    let qcols = if mode == QrMode::Full { m } else { k };
183    // Q = H₁ H₂ ⋯ H_k applied to the first columns of the identity (LAPACK's orgqr).
184    let mut q = zeros::<T>(m, qcols);
185    for j in 0..qcols.min(m) {
186        q[(j, j)] = T::one();
187    }
188    for i in (0..k).rev() {
189        let mut v = vec![T::one()];
190        v.extend((i + 1..m).map(|r| f[(r, i)]));
191        reflect_left(&mut q, &v, taus[i], i, 0..qcols);
192    }
193    let rrows = if mode == QrMode::Full { m } else { k };
194    let r = Array2::from_shape_fn((rrows, n), |(i, j)| if j >= i { f[(i, j)] } else { T::zero() });
195    Ok(QrFactors { q, r, permutation })
196}
197// ANCHOR_END: qr
198
199// ANCHOR: rq
200/// The RQ factorisation `A = R Q` (SciPy's `rq`, LAPACK's `gerq2`): `R` upper triangular
201/// (trapezoidal, aligned to the right), `Q` with orthonormal rows. Each step reflects a row,
202/// from the last upwards, onto its own last allowed column. Returns `(R, Q)`.
203pub fn rq<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, mode: QrMode) -> Result<(Array2<T>, Array2<T>)> {
204    let mut a = check_finite(a)?;
205    let (m, n) = a.dim();
206    let k = m.min(n);
207    let mut reflectors: Vec<(Vec<T>, T)> = Vec::with_capacity(k);
208    for i in (0..k).rev() {
209        let (r, c) = (m - k + i, n - k + i);
210        // The conjugated row segment is reflected onto its last entry.
211        let alpha = a[(r, c)].conj();
212        let mut x: Vec<T> = (0..c).map(|j| a[(r, j)].conj()).collect();
213        let (beta, tau) = larfg(alpha, &mut x);
214        let mut v = x.clone();
215        v.push(T::one());
216        // A[0..r, 0..=c] ← A[0..r, 0..=c] H.
217        reflect_right(&mut a, &v, tau, 0..r, 0);
218        a[(r, c)] = beta;
219        for j in 0..c {
220            a[(r, j)] = T::zero();
221        }
222        reflectors.push((v, tau));
223    }
224    reflectors.reverse(); // reflectors[i] is H(i), acting on columns 0..=n−k+i
225    // Q = H(1)ᴴ H(2)ᴴ ⋯ H(k)ᴴ as an n × n matrix (LAPACK's orgrq).
226    let mut q = eye::<T>(n);
227    for (v, tau) in &reflectors {
228        reflect_right(&mut q, v, tau.conj(), 0..n, 0);
229    }
230    // R occupies the last min(m, n) "diagonals": R[i, j] = 0 for j < i + n − m.
231    let r_full = Array2::from_shape_fn((m, n), |(i, j)| if j as isize >= i as isize + n as isize - m as isize { a[(i, j)] } else { T::zero() });
232    if mode == QrMode::Economic && m <= n {
233        return Ok((r_full.slice(s![.., n - m..]).to_owned(), q.slice(s![n - m.., ..]).to_owned()));
234    }
235    Ok((r_full, q))
236}
237// ANCHOR_END: rq
238
239// ANCHOR: hessenberg
240/// The Hessenberg form `A = Q H Qᴴ` (SciPy's `hessenberg` with `calc_q=True`; LAPACK's `gehd2`
241/// and `orghr`): `H` is zero below its first subdiagonal, `Q` unitary. Reflector `i` zeros
242/// column `i` below row `i + 1` and is applied from both sides. Returns `(H, Q)`.
243pub fn hessenberg<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>) -> Result<(Array2<T>, Array2<T>)> {
244    let mut a = check_finite(a)?;
245    let n = a.nrows();
246    if a.ncols() != n {
247        return Err(LinalgError::NotSquare { rows: n, cols: a.ncols() });
248    }
249    let mut reflectors = Vec::new();
250    // As LAPACK, the last step has no entries to zero; for a complex matrix it still reflects,
251    // to make the last subdiagonal entry real.
252    for i in 0..n.saturating_sub(1) {
253        let alpha = a[(i + 1, i)];
254        let mut x: Vec<T> = (i + 2..n).map(|r| a[(r, i)]).collect();
255        let (beta, tau) = larfg(alpha, &mut x);
256        let mut v = vec![T::one()];
257        v.extend_from_slice(&x);
258        a[(i + 1, i)] = beta;
259        for r in i + 2..n {
260            a[(r, i)] = T::zero();
261        }
262        reflect_right(&mut a, &v, tau, 0..n, i + 1);
263        reflect_left(&mut a, &v, tau.conj(), i + 1, i + 1..n);
264        reflectors.push((i + 1, v, tau));
265    }
266    let mut q = eye::<T>(n);
267    for (row0, v, tau) in reflectors.iter().rev() {
268        reflect_left(&mut q, v, *tau, *row0, *row0..n);
269    }
270    Ok((a, q))
271}
272// ANCHOR_END: hessenberg
273
274// ANCHOR: lanv2
275/// LAPACK's `lanv2`: the rotation `[c −s; s c]` that brings a real 2 × 2 block to standard form,
276/// `[a b; c d] = R [a' b'; c' d'] Rᵀ`, where the new block is upper triangular when its eigenvalues
277/// are real, and otherwise has `a' = d'` and `b' c' < 0`. Returns `(a', b', c', d', cs, sn)`.
278fn lanv2(mut a: f64, mut b: f64, mut c: f64, mut d: f64) -> (f64, f64, f64, f64, f64, f64) {
279    let eps = f64::EPSILON;
280    let sign = |x: f64, y: f64| if y >= 0.0 { x.abs() } else { -x.abs() };
281    let (mut cs, mut sn);
282    if c == 0.0 {
283        cs = 1.0;
284        sn = 0.0;
285    } else if b == 0.0 {
286        cs = 0.0;
287        sn = 1.0;
288        std::mem::swap(&mut a, &mut d);
289        b = -c;
290        c = 0.0;
291    } else if a - d == 0.0 && b.signum() != c.signum() {
292        cs = 1.0;
293        sn = 0.0;
294    } else {
295        let temp = a - d;
296        let mut p = 0.5 * temp;
297        let bcmax = b.abs().max(c.abs());
298        let bcmis = b.abs().min(c.abs()) * b.signum() * c.signum();
299        let scale = p.abs().max(bcmax);
300        let mut z = p / scale * p + bcmax / scale * bcmis;
301        if z >= 4.0 * eps {
302            // Real eigenvalues: make the block upper triangular.
303            z = p + sign(scale.sqrt() * z.sqrt(), p);
304            a = d + z;
305            d -= bcmax / z * bcmis;
306            let tau = c.hypot(z);
307            cs = z / tau;
308            sn = c / tau;
309            b -= c;
310            c = 0.0;
311        } else {
312            // Complex or nearly equal real eigenvalues: equalise the diagonal.
313            let sigma = b + c;
314            let tau = sigma.hypot(temp);
315            cs = (0.5 * (1.0 + sigma.abs() / tau)).sqrt();
316            sn = -(p / (tau * cs)) * sign(1.0, sigma);
317            let (aa, bb, cc, dd) = (a * cs + b * sn, -a * sn + b * cs, c * cs + d * sn, -c * sn + d * cs);
318            a = aa * cs + cc * sn;
319            b = bb * cs + dd * sn;
320            c = -aa * sn + cc * cs;
321            d = -bb * sn + dd * cs;
322            let temp = 0.5 * (a + d);
323            a = temp;
324            d = temp;
325            if c != 0.0 {
326                if b != 0.0 {
327                    if b.signum() == c.signum() {
328                        // Real eigenvalues after all: triangularise.
329                        let sab = b.abs().sqrt();
330                        let sac = c.abs().sqrt();
331                        p = sign(sab * sac, c);
332                        let tau = 1.0 / (b + c).abs().sqrt();
333                        a = temp + p;
334                        d = temp - p;
335                        b -= c;
336                        c = 0.0;
337                        let (cs1, sn1) = (sab * tau, sac * tau);
338                        let t = cs * cs1 - sn * sn1;
339                        sn = cs * sn1 + sn * cs1;
340                        cs = t;
341                    }
342                } else {
343                    b = -c;
344                    c = 0.0;
345                    let t = cs;
346                    cs = -sn;
347                    sn = t;
348                }
349            }
350        }
351    }
352    (a, b, c, d, cs, sn)
353}
354// ANCHOR_END: lanv2
355
356/// [`lanv2`] for the reordering module.
357pub(crate) fn lanv2_pub(a: f64, b: f64, c: f64, d: f64) -> (f64, f64, f64, f64, f64, f64) {
358    lanv2(a, b, c, d)
359}
360
361// ANCHOR: schur_real
362/// The real Schur form `A = Z T Zᵀ` of a real matrix (SciPy's `schur(a, output='real')`): `Z`
363/// orthogonal and `T` quasi upper triangular, with 1 × 1 blocks for real eigenvalues and 2 × 2
364/// blocks `[a b; c a]`, `b c < 0`, for each complex conjugate pair `a ± i√(−bc)`. Returns `(T, Z)`.
365pub fn schur_real<S: Data<Elem = f64>>(a: &ArrayBase<S, Ix2>) -> Result<(Array2<f64>, Array2<f64>)> {
366    let (mut t, mut z, pair) = crate::eig::real_schur_unbalanced(&Mat::from_array(a)?)?;
367    let n = t.rows;
368    let rot = |x: f64, y: f64, cs: f64, sn: f64| (cs * x + sn * y, cs * y - sn * x);
369    for k in (0..n).filter(|&k| pair[k]) {
370        let (a0, b0, c0, d0, cs, sn) = lanv2(t.at(k, k), t.at(k, k + 1), t.at(k + 1, k), t.at(k + 1, k + 1));
371        *t.at_mut(k, k) = a0;
372        *t.at_mut(k, k + 1) = b0;
373        *t.at_mut(k + 1, k) = c0;
374        *t.at_mut(k + 1, k + 1) = d0;
375        for j in k + 2..n {
376            let (x, y) = rot(t.at(k, j), t.at(k + 1, j), cs, sn);
377            *t.at_mut(k, j) = x;
378            *t.at_mut(k + 1, j) = y;
379        }
380        for i in 0..k {
381            let (x, y) = rot(t.at(i, k), t.at(i, k + 1), cs, sn);
382            *t.at_mut(i, k) = x;
383            *t.at_mut(i, k + 1) = y;
384        }
385        for i in 0..n {
386            let (x, y) = rot(z.at(i, k), z.at(i, k + 1), cs, sn);
387            *z.at_mut(i, k) = x;
388            *z.at_mut(i, k + 1) = y;
389        }
390    }
391    Ok((t.into_array(), z.into_array()))
392}
393// ANCHOR_END: schur_real
394
395/// An `LDLᵀ` (or `LDLᴴ`) factorisation `A = L D Lᴴ` with symmetric pivoting.
396#[derive(Clone, Debug)]
397#[non_exhaustive]
398pub struct LdlFactors<T> {
399    /// The triangular factor, with its rows permuted: `L[perm, :]` is unit triangular.
400    pub l: Array2<T>,
401    /// Block diagonal, with 1 × 1 and 2 × 2 blocks.
402    pub d: Array2<T>,
403    /// The row order that makes `l` triangular.
404    pub perm: Vec<usize>,
405}
406
407/// `|x|` as LAPACK compares complex entries when choosing pivots, `|Re x| + |Im x|`.
408fn cabs1<T: Scalar>(x: T) -> f64 {
409    if T::IS_COMPLEX { x.re().abs() + x.im().abs() } else { x.abs() }
410}
411
412// ANCHOR: ldl
413/// The Bunch-Kaufman factorisation of a symmetric or Hermitian matrix (SciPy's `ldl`, LAPACK's
414/// `sytf2`/`hetf2`): `A = L D Lᴴ` (or `U D Uᴴ` with `lower = false`), `D` block diagonal with 1 × 1
415/// and 2 × 2 blocks, and `L` a row permutation of a unit triangular matrix. A 2 × 2 pivot is
416/// taken when no diagonal entry is large enough relative to its column, `α = (1 + √17)/8`,
417/// which bounds the growth of the entries for indefinite matrices. Only the `lower` (or upper)
418/// triangle is read; `hermitian = false` factorises a complex symmetric matrix, `A = L D Lᵀ`.
419pub fn ldl<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, lower: bool, hermitian: bool) -> Result<LdlFactors<T>> {
420    let mut a = check_finite(a)?;
421    let n = a.nrows();
422    if a.ncols() != n {
423        return Err(LinalgError::NotSquare { rows: n, cols: a.ncols() });
424    }
425    let herm = hermitian && T::IS_COMPLEX;
426    let cj = |x: T| if herm { x.conj() } else { x };
427    let re = |x: T| if herm { T::from_real(x.re()) } else { x };
428    let dabs = |x: T| if herm { x.re().abs() } else { cabs1(x) };
429    let alpha = (1.0 + 17f64.sqrt()) / 8.0;
430    // Work on the lower triangle; the upper case reads the transpose (conjugated if Hermitian),
431    // which is the lower triangle of the same matrix, and mirrors the indices.
432    let mut ipiv = vec![0isize; n];
433    if lower {
434        let mut k = 0;
435        while k < n {
436            let mut kstep = 1;
437            let absakk = dabs(a[(k, k)]);
438            let (imax, colmax) = if k + 1 < n {
439                let mut im = k + 1;
440                for i in k + 2..n {
441                    if cabs1(a[(i, k)]) > cabs1(a[(im, k)]) {
442                        im = i;
443                    }
444                }
445                (im, cabs1(a[(im, k)]))
446            } else {
447                (k, 0.0)
448            };
449            let kp;
450            if absakk.max(colmax) == 0.0 || absakk >= alpha * colmax {
451                kp = k;
452            } else {
453                let mut rowmax = 0.0f64;
454                for j in k..imax {
455                    rowmax = rowmax.max(cabs1(a[(imax, j)]));
456                }
457                for j in imax + 1..n {
458                    rowmax = rowmax.max(cabs1(a[(j, imax)]));
459                }
460                if absakk >= alpha * colmax * (colmax / rowmax) {
461                    kp = k;
462                } else if dabs(a[(imax, imax)]) >= alpha * rowmax {
463                    kp = imax;
464                } else {
465                    kp = imax;
466                    kstep = 2;
467                }
468            }
469            let kk = k + kstep - 1;
470            if kp != kk {
471                for i in kp + 1..n {
472                    a.swap((i, kk), (i, kp));
473                }
474                for j in kk + 1..kp {
475                    let t = cj(a[(j, kk)]);
476                    a[(j, kk)] = cj(a[(kp, j)]);
477                    a[(kp, j)] = t;
478                }
479                if herm {
480                    a[(kp, kk)] = a[(kp, kk)].conj();
481                }
482                let t = re(a[(kk, kk)]);
483                a[(kk, kk)] = re(a[(kp, kp)]);
484                a[(kp, kp)] = t;
485                if kstep == 2 {
486                    if herm {
487                        a[(k, k)] = re(a[(k, k)]);
488                    }
489                    a.swap((k + 1, k), (kp, k));
490                }
491            } else if herm {
492                a[(k, k)] = re(a[(k, k)]);
493                if kstep == 2 {
494                    a[(k + 1, k + 1)] = re(a[(k + 1, k + 1)]);
495                }
496            }
497            if kstep == 1 {
498                if k + 1 < n {
499                    let d11 = T::one() / re(a[(k, k)]);
500                    for j in k + 1..n {
501                        let ajk = a[(j, k)];
502                        for i in j..n {
503                            let aik = a[(i, k)];
504                            a[(i, j)] -= d11 * aik * cj(ajk);
505                        }
506                        if herm {
507                            a[(j, j)] = re(a[(j, j)]);
508                        }
509                    }
510                    for i in k + 1..n {
511                        a[(i, k)] *= d11;
512                    }
513                }
514                ipiv[k] = kp as isize + 1;
515            } else {
516                if k + 2 < n {
517                    if herm {
518                        let d = a[(k + 1, k)].abs();
519                        let d11 = a[(k + 1, k + 1)].re() / d;
520                        let d22 = a[(k, k)].re() / d;
521                        let tt = 1.0 / (d11 * d22 - 1.0);
522                        let d21 = a[(k + 1, k)].scale(1.0 / d);
523                        let dd = tt / d;
524                        for j in k + 2..n {
525                            let wk = (a[(j, k)].scale(d11) - d21 * a[(j, k + 1)]).scale(dd);
526                            let wkp1 = (a[(j, k + 1)].scale(d22) - d21.conj() * a[(j, k)]).scale(dd);
527                            for i in j..n {
528                                let (aik, aik1) = (a[(i, k)], a[(i, k + 1)]);
529                                a[(i, j)] -= aik * wk.conj() + aik1 * wkp1.conj();
530                            }
531                            a[(j, k)] = wk;
532                            a[(j, k + 1)] = wkp1;
533                            a[(j, j)] = re(a[(j, j)]);
534                        }
535                    } else {
536                        let mut d21 = a[(k + 1, k)];
537                        let d11 = a[(k + 1, k + 1)] / d21;
538                        let d22 = a[(k, k)] / d21;
539                        let t = T::one() / (d11 * d22 - T::one());
540                        d21 = t / d21;
541                        for j in k + 2..n {
542                            let wk = d21 * (d11 * a[(j, k)] - a[(j, k + 1)]);
543                            let wkp1 = d21 * (d22 * a[(j, k + 1)] - a[(j, k)]);
544                            for i in j..n {
545                                let (aik, aik1) = (a[(i, k)], a[(i, k + 1)]);
546                                a[(i, j)] -= aik * wk + aik1 * wkp1;
547                            }
548                            a[(j, k)] = wk;
549                            a[(j, k + 1)] = wkp1;
550                        }
551                    }
552                }
553                ipiv[k] = -(kp as isize + 1);
554                ipiv[k + 1] = -(kp as isize + 1);
555            }
556            k += kstep;
557        }
558    } else {
559        let mut k = n;
560        while k > 0 {
561            let kc = k - 1; // the current column, 0-based
562            let mut kstep = 1;
563            let absakk = dabs(a[(kc, kc)]);
564            let (imax, colmax) = if kc > 0 {
565                let mut im = 0;
566                for i in 1..kc {
567                    if cabs1(a[(i, kc)]) > cabs1(a[(im, kc)]) {
568                        im = i;
569                    }
570                }
571                (im, cabs1(a[(im, kc)]))
572            } else {
573                (kc, 0.0)
574            };
575            let kp;
576            if absakk.max(colmax) == 0.0 || absakk >= alpha * colmax {
577                kp = kc;
578            } else {
579                let mut rowmax = 0.0f64;
580                for j in imax + 1..=kc {
581                    rowmax = rowmax.max(cabs1(a[(imax, j)]));
582                }
583                for i in 0..imax {
584                    rowmax = rowmax.max(cabs1(a[(i, imax)]));
585                }
586                if absakk >= alpha * colmax * (colmax / rowmax) {
587                    kp = kc;
588                } else if dabs(a[(imax, imax)]) >= alpha * rowmax {
589                    kp = imax;
590                } else {
591                    kp = imax;
592                    kstep = 2;
593                }
594            }
595            let kk = kc + 1 - kstep;
596            if kp != kk {
597                for i in 0..kp {
598                    a.swap((i, kk), (i, kp));
599                }
600                for j in kp + 1..kk {
601                    let t = cj(a[(j, kk)]);
602                    a[(j, kk)] = cj(a[(kp, j)]);
603                    a[(kp, j)] = t;
604                }
605                if herm {
606                    a[(kp, kk)] = a[(kp, kk)].conj();
607                }
608                let t = re(a[(kk, kk)]);
609                a[(kk, kk)] = re(a[(kp, kp)]);
610                a[(kp, kp)] = t;
611                if kstep == 2 {
612                    if herm {
613                        a[(kc, kc)] = re(a[(kc, kc)]);
614                    }
615                    a.swap((kc - 1, kc), (kp, kc));
616                }
617            } else if herm {
618                a[(kc, kc)] = re(a[(kc, kc)]);
619                if kstep == 2 {
620                    a[(kc - 1, kc - 1)] = re(a[(kc - 1, kc - 1)]);
621                }
622            }
623            if kstep == 1 {
624                let r1 = T::one() / re(a[(kc, kc)]);
625                for j in (0..kc).rev() {
626                    let ajk = a[(j, kc)];
627                    for i in 0..=j {
628                        let aik = a[(i, kc)];
629                        a[(i, j)] -= r1 * aik * cj(ajk);
630                    }
631                    if herm {
632                        a[(j, j)] = re(a[(j, j)]);
633                    }
634                }
635                for i in 0..kc {
636                    a[(i, kc)] *= r1;
637                }
638                ipiv[kc] = kp as isize + 1;
639            } else {
640                if kc > 1 {
641                    if herm {
642                        let d = a[(kc - 1, kc)].abs();
643                        let d22 = a[(kc - 1, kc - 1)].re() / d;
644                        let d11 = a[(kc, kc)].re() / d;
645                        let tt = 1.0 / (d11 * d22 - 1.0);
646                        let d12 = a[(kc - 1, kc)].scale(1.0 / d);
647                        let dd = tt / d;
648                        for j in (0..kc - 1).rev() {
649                            let wkm1 = (a[(j, kc - 1)].scale(d11) - d12.conj() * a[(j, kc)]).scale(dd);
650                            let wk = (a[(j, kc)].scale(d22) - d12 * a[(j, kc - 1)]).scale(dd);
651                            for i in (0..=j).rev() {
652                                let (aik, aikm1) = (a[(i, kc)], a[(i, kc - 1)]);
653                                a[(i, j)] -= aik * wk.conj() + aikm1 * wkm1.conj();
654                            }
655                            a[(j, kc)] = wk;
656                            a[(j, kc - 1)] = wkm1;
657                            a[(j, j)] = re(a[(j, j)]);
658                        }
659                    } else {
660                        let mut d12 = a[(kc - 1, kc)];
661                        let d22 = a[(kc - 1, kc - 1)] / d12;
662                        let d11 = a[(kc, kc)] / d12;
663                        let t = T::one() / (d11 * d22 - T::one());
664                        d12 = t / d12;
665                        for j in (0..kc - 1).rev() {
666                            let wkm1 = d12 * (d11 * a[(j, kc - 1)] - a[(j, kc)]);
667                            let wk = d12 * (d22 * a[(j, kc)] - a[(j, kc - 1)]);
668                            for i in (0..=j).rev() {
669                                let (aik, aikm1) = (a[(i, kc)], a[(i, kc - 1)]);
670                                a[(i, j)] -= aik * wk + aikm1 * wkm1;
671                            }
672                            a[(j, kc)] = wk;
673                            a[(j, kc - 1)] = wkm1;
674                        }
675                    }
676                }
677                ipiv[kc] = -(kp as isize + 1);
678                ipiv[kc - 1] = -(kp as isize + 1);
679            }
680            k -= kstep;
681        }
682    }
683    Ok(ldl_assemble(a, &ipiv, lower, herm))
684}
685// ANCHOR_END: ldl
686
687/// SciPy's post-processing of `sytrf`/`hetrf` (`_ldl_sanitize_ipiv`, `_ldl_get_d_and_l`,
688/// `_ldl_construct_tri_factor`): the swap list and block sizes from the pivot indices, `D` and the
689/// unit triangle from the packed factor, and the row interchanges applied to the triangle.
690fn ldl_assemble<T: Scalar>(ldu: Array2<T>, ipiv: &[isize], lower: bool, herm: bool) -> LdlFactors<T> {
691    let n = ldu.nrows();
692    let mut swap: Vec<usize> = (0..n).collect();
693    let mut pivots = vec![0usize; n];
694    let indices: Vec<usize> = if lower { (0..n).collect() } else { (0..n).rev().collect() };
695    let (x, y): (isize, isize) = if lower { (1, 0) } else { (-1, -1) };
696    let mut skip = false;
697    for &ind in &indices {
698        if skip {
699            skip = false;
700            continue;
701        }
702        let cur = ipiv[ind];
703        if cur > 0 {
704            if cur as usize != ind + 1 {
705                swap[ind] = swap[cur as usize - 1];
706            }
707            pivots[ind] = 1;
708        } else {
709            let other = (ind as isize + x) as usize;
710            // As SciPy: record the interchange unless −ipiv = ind + 2 (1-based ind + 1).
711            if (-cur) as usize != ind + 2 {
712                swap[other] = swap[(-cur) as usize - 1];
713            }
714            pivots[(ind as isize + y) as usize] = 2;
715            skip = true;
716        }
717    }
718    let mut d = zeros::<T>(n, n);
719    for i in 0..n {
720        d[(i, i)] = ldu[(i, i)];
721    }
722    let mut lu = Array2::from_shape_fn((n, n), |(i, j)| if (lower && i > j) || (!lower && i < j) { ldu[(i, j)] } else if i == j { T::one() } else { T::zero() });
723    let (bx, by) = if lower { (1usize, 0usize) } else { (0, 1) };
724    let mut blk = 0;
725    for &p in pivots.iter().filter(|&&p| p != 0) {
726        if p == 2 {
727            let v = ldu[(blk + bx, blk + by)];
728            d[(blk + bx, blk + by)] = v;
729            d[(blk + by, blk + bx)] = if herm { v.conj() } else { v };
730            lu[(blk + bx, blk + by)] = T::zero();
731        }
732        blk += p;
733    }
734    let mut perm: Vec<usize> = (0..n).collect();
735    let order: Vec<usize> = if lower { (0..n).rev().collect() } else { (0..n).collect() };
736    for ind in order {
737        let s_ind = swap[ind];
738        if s_ind != ind {
739            let (mut col_s, mut col_e) = if lower { (ind, n) } else { (0, ind + 1) };
740            if pivots[ind] == if lower { 0 } else { 2 } {
741                if lower {
742                    col_s -= 1;
743                } else {
744                    col_e += 1;
745                }
746            }
747            for c in col_s..col_e {
748                let t = lu[(s_ind, c)];
749                lu[(s_ind, c)] = lu[(ind, c)];
750                lu[(ind, c)] = t;
751            }
752            perm.swap(s_ind, ind);
753        }
754    }
755    // perm ← argsort(perm).
756    let mut inverse = vec![0; n];
757    for (i, &p) in perm.iter().enumerate() {
758        inverse[p] = i;
759    }
760    LdlFactors { l: lu, d, perm: inverse }
761}
762
763// ANCHOR: polar
764/// The polar decomposition `A = U P` (`side = right`) or `A = P U` (left) (SciPy's `polar`): `U`
765/// with orthonormal columns (or rows) and `P` Hermitian positive semi-definite, from the SVD
766/// `A = W Σ Vᴴ`: `U = W Vᴴ`, and `P = V Σ Vᴴ` or `W Σ Wᴴ`. Returns `(U, P)`.
767pub fn polar<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, right: bool) -> Result<(Array2<T>, Array2<T>)> {
768    let (m, n) = a.dim();
769    let k = m.min(n);
770    let (w, sv, vh) = a.svd(true, true)?;
771    let (w, vh) = (w.expect("requested"), vh.expect("requested"));
772    let w = w.slice(s![.., ..k]).to_owned();
773    let vh = vh.slice(s![..k, ..]).to_owned();
774    let u = matmul(&w, &vh);
775    let p = if right {
776        Array2::from_shape_fn((n, n), |(i, j)| (0..k).fold(T::zero(), |acc, l| acc + vh[(l, i)].conj().scale(sv[l]) * vh[(l, j)]))
777    } else {
778        Array2::from_shape_fn((m, m), |(i, j)| (0..k).fold(T::zero(), |acc, l| acc + w[(i, l)].scale(sv[l]) * w[(j, l)].conj()))
779    };
780    Ok((u, p))
781}
782// ANCHOR_END: polar
783
784// ANCHOR: subspace_angles
785/// The principal angles between the column spaces of `A` and `B` (SciPy's `subspace_angles`),
786/// largest first. With orthonormal bases `Q_A`, `Q_B`, the cosines are the singular values of
787/// `Q_Aᴴ Q_B`; angles whose cosine exceeds `1/√2` are taken instead from the sines, the singular
788/// values of `Q_B − Q_A Q_Aᴴ Q_B`, which keeps small angles accurate (Knyazev and Argentati, 2002).
789pub fn subspace_angles<T: Scalar, S: Data<Elem = T>, S2: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, b: &ArrayBase<S2, Ix2>) -> Result<Array1<f64>> {
790    if a.nrows() != b.nrows() {
791        return Err(LinalgError::Shape(format!("A and B must have the same number of rows, got {} and {}", a.nrows(), b.nrows())));
792    }
793    let qa = orth(a, None)?;
794    let qb = orth(b, None)?;
795    let qa_h_qb = matmul(&adjoint(&qa), &qb);
796    let (_, sigma, _) = qa_h_qb.svd(false, false)?;
797    let residual = if qa.ncols() >= qb.ncols() {
798        let p = matmul(&qa, &qa_h_qb);
799        Array2::from_shape_fn(qb.dim(), |(i, j)| qb[(i, j)] - p[(i, j)])
800    } else {
801        let p = matmul(&qb, &adjoint(&qa_h_qb));
802        Array2::from_shape_fn(qa.dim(), |(i, j)| qa[(i, j)] - p[(i, j)])
803    };
804    let use_sines = sigma.iter().any(|s| s * s >= 0.5);
805    let mu_arcsin: Vec<f64> = if use_sines {
806        let (_, sv, _) = residual.svd(false, false)?;
807        sv.iter().map(|v| v.clamp(-1.0, 1.0).asin()).collect()
808    } else {
809        Vec::new()
810    };
811    let len = sigma.len();
812    Ok(Array1::from_shape_fn(len, |i| {
813        if sigma[i] * sigma[i] >= 0.5 { mu_arcsin.get(i).copied().unwrap_or(0.0) } else { sigma[len - 1 - i].clamp(-1.0, 1.0).acos() }
814    }))
815}
816// ANCHOR_END: subspace_angles
817
818// ANCHOR: funm
819/// `f(A)` for a scalar function `f` (SciPy's `funm`), by the Schur-Parlett method: with the complex
820/// Schur form `A = Z T Zᴴ`, `F = f(T)` is upper triangular with `F_ii = f(T_ii)`, and the
821/// commutation `T F = F T` determines the rest, superdiagonal by superdiagonal:
822/// `F_ij = (T_ij (F_jj − F_ii) + Σ_{i<k<j} (T_ik F_kj − F_ik T_kj)) / (T_jj − T_ii)`.
823/// Returns `(Z F Zᴴ, error estimate)`; the estimate is large when eigenvalues nearly coincide,
824/// where this recurrence divides by small differences.
825pub fn funm<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, f: impl Fn(C) -> C) -> Result<(Array2<C>, f64)> {
826    let (t, z) = schur_complex(a)?;
827    let n = t.nrows();
828    let mut fm = Array2::<C>::zeros((n, n));
829    for i in 0..n {
830        fm[(i, i)] = f(t[(i, i)]);
831    }
832    let mut minden = if n > 0 { t[(0, 0)].norm() } else { 0.0 };
833    for p in 1..n {
834        for i in 0..n - p {
835            let j = i + p;
836            let mut s = t[(i, j)] * (fm[(j, j)] - fm[(i, i)]);
837            for k in i + 1..j {
838                s += t[(i, k)] * fm[(k, j)] - fm[(i, k)] * t[(k, j)];
839            }
840            let den = t[(j, j)] - t[(i, i)];
841            if den != C::new(0.0, 0.0) {
842                s /= den;
843            }
844            fm[(i, j)] = s;
845            minden = minden.min(den.norm());
846        }
847    }
848    let zh = z.t().mapv(|v| v.conj());
849    let result = z.dot(&fm).dot(&zh);
850    let tol = f64::EPSILON;
851    let minden = if minden == 0.0 { tol } else { minden };
852    // ‖triu(T, 1)‖₁, the largest column sum of the strictly upper part.
853    let upper_norm = (0..n).map(|j| (0..j).map(|i| t[(i, j)].norm()).sum::<f64>()).fold(0.0, f64::max);
854    let mut err = 1f64.min(tol.max(tol / minden * upper_norm));
855    if result.iter().any(|v| !v.re.is_finite() || !v.im.is_finite()) {
856        err = f64::INFINITY;
857    }
858    Ok((result, err))
859}
860// ANCHOR_END: funm
861
862#[cfg(test)]
863mod tests {
864    use super::*;
865    use crate::expm;
866
867    fn max_diff<T: Scalar>(a: &Array2<T>, b: &Array2<T>) -> f64 {
868        a.iter().zip(b.iter()).fold(0.0f64, |m, (x, y)| m.max((*x - *y).abs()))
869    }
870
871    fn test_matrix(m: usize, n: usize, seed: f64) -> Array2<f64> {
872        Array2::from_shape_fn((m, n), |(i, j)| (seed + 1.3 * i as f64 + 0.7 * (j * j) as f64 + 0.37 * (i * j) as f64).sin() + if i == j { 2.0 } else { 0.0 })
873    }
874
875    fn complex_matrix(m: usize, n: usize, seed: f64) -> Array2<C> {
876        let r = test_matrix(m, n, seed);
877        Array2::from_shape_fn((m, n), |(i, j)| C::new(r[(i, j)], (seed + 0.4 * (i * i) as f64 - 0.9 * j as f64).cos()))
878    }
879
880    #[test]
881    fn qr_and_rq_reconstruct_and_are_orthogonal() {
882        for (m, n) in [(6, 6), (7, 4), (4, 7)] {
883            let a = complex_matrix(m, n, 1.0);
884            for mode in [QrMode::Full, QrMode::Economic] {
885                for pivoting in [false, true] {
886                    let f = qr(&a, mode, pivoting).unwrap();
887                    let ap = Array2::from_shape_fn((m, n), |(i, j)| a[(i, f.permutation[j])]);
888                    assert!(max_diff(&matmul(&f.q, &f.r), &ap) < 1e-13);
889                    let qhq = matmul(&adjoint(&f.q), &f.q);
890                    assert!(max_diff(&qhq, &eye(f.q.ncols())) < 1e-13);
891                    assert!((0..f.r.nrows()).all(|i| (0..i.min(n)).all(|j| f.r[(i, j)] == C::new(0.0, 0.0))));
892                    if pivoting {
893                        let d: Vec<f64> = (0..m.min(n)).map(|i| f.r[(i, i)].norm()).collect();
894                        assert!(d.windows(2).all(|w| w[0] >= w[1] - 1e-12), "{d:?}");
895                    }
896                }
897                let (r, q) = rq(&a, mode).unwrap();
898                assert!(max_diff(&matmul(&r, &q), &a) < 1e-13);
899                assert!(max_diff(&matmul(&q, &adjoint(&q)), &eye(q.nrows())) < 1e-13);
900            }
901        }
902    }
903
904    #[test]
905    fn hessenberg_and_real_schur_forms() {
906        let a = test_matrix(9, 9, 2.0);
907        let (h, q) = hessenberg(&a).unwrap();
908        assert!((0..9usize).all(|i| (0..i.saturating_sub(1)).all(|j| h[(i, j)] == 0.0)));
909        assert!(max_diff(&matmul(&matmul(&q, &h), &adjoint(&q)), &a) < 1e-13);
910        let c = complex_matrix(6, 6, 3.0);
911        let (h, q) = hessenberg(&c).unwrap();
912        assert!((1..6).all(|i| h[(i, i - 1)].im == 0.0), "subdiagonal made real, as LAPACK");
913        assert!(max_diff(&matmul(&matmul(&q, &h), &adjoint(&q)), &c) < 1e-13);
914        // A rotation-like matrix has complex eigenvalues: 2 × 2 blocks in standard form.
915        let (t, z) = schur_real(&a).unwrap();
916        assert!(max_diff(&matmul(&matmul(&z, &t), &adjoint(&z)), &a) < 1e-12);
917        let mut blocks = 0;
918        for i in 1..9 {
919            if t[(i, i - 1)] != 0.0 {
920                blocks += 1;
921                assert!(t[(i, i)] == t[(i - 1, i - 1)] && t[(i, i - 1)] * t[(i - 1, i)] < 0.0);
922            }
923        }
924        assert!(blocks > 0);
925        assert!(hessenberg(&Array2::<f64>::zeros((2, 3))).is_err());
926    }
927
928    #[test]
929    fn ldl_reconstructs_with_two_by_two_pivots() {
930        // A zero diagonal forces 2 × 2 pivots.
931        let n = 6;
932        let s = Array2::from_shape_fn((n, n), |(i, j)| if i == j { 0.0 } else { (0.9 * (i + j) as f64 + 0.3 * (i * j) as f64).sin() * 2.0 });
933        for lower in [true, false] {
934            let f = ldl(&s, lower, true).unwrap();
935            let rec = matmul(&matmul(&f.l, &f.d), &adjoint(&f.l));
936            assert!(max_diff(&rec, &s) < 1e-13, "lower = {lower}");
937            assert!((0..n - 1).any(|i| f.d[(i + 1, i)] != 0.0));
938            // L[perm] is unit triangular.
939            for (r, &p) in f.perm.iter().enumerate() {
940                assert!((f.l[(p, r)] - 1.0).abs() < 1e-15);
941            }
942        }
943        let h = complex_matrix(5, 5, 4.0);
944        let herm = Array2::from_shape_fn((5, 5), |(i, j)| if i == j { C::new(h[(i, i)].re, 0.0) } else { (h[(i, j)] + h[(j, i)].conj()) / 2.0 });
945        let f = ldl(&herm, true, true).unwrap();
946        assert!(max_diff(&matmul(&matmul(&f.l, &f.d), &adjoint(&f.l)), &herm) < 1e-13);
947        let sym = Array2::from_shape_fn((5, 5), |(i, j)| h[(i.min(j), i.max(j))]);
948        let f = ldl(&sym, false, false).unwrap();
949        let lt = f.l.t().to_owned();
950        assert!(max_diff(&matmul(&matmul(&f.l, &f.d), &lt), &sym) < 1e-13);
951    }
952
953    #[test]
954    fn polar_angles_and_matrix_functions() {
955        let a = test_matrix(5, 3, 5.0);
956        let (u, p) = polar(&a, true).unwrap();
957        assert!(max_diff(&matmul(&u, &p), &a) < 1e-13 && max_diff(&matmul(&adjoint(&u), &u), &eye(3)) < 1e-13);
958        let (u, p) = polar(&a, false).unwrap();
959        assert!(max_diff(&matmul(&p, &u), &a) < 1e-13);
960        // The x axis and the line at 30° in the xy plane of ℝ³.
961        let x = Array2::from_shape_vec((3, 1), vec![1.0, 0.0, 0.0]).unwrap();
962        let l = Array2::from_shape_vec((3, 1), vec![3f64.sqrt() / 2.0, 0.5, 0.0]).unwrap();
963        let th = subspace_angles(&x, &l).unwrap();
964        assert!((th[0] - std::f64::consts::PI / 6.0).abs() < 1e-15);
965        let tiny = Array2::from_shape_vec((3, 1), vec![1.0, 1e-9, 0.0]).unwrap();
966        assert!((subspace_angles(&x, &tiny).unwrap()[0] - 1e-9).abs() < 1e-22, "small angles from sines");
967        let m = test_matrix(5, 5, 6.0) * 0.5;
968        let (f, err) = funm(&m, |z| z.exp()).unwrap();
969        let e = expm(&m).unwrap();
970        assert!(f.iter().zip(e.iter()).all(|(x, y)| (x.re - y).abs() < 1e-12 && x.im.abs() < 1e-12), "err {err:e}");
971        assert!(err < 1e-10);
972    }
973}