Skip to main content

ruxla_kernels/
linalg.rs

1//! Linear algebra on batches of row-major matrices: Cholesky, triangular
2//! solves, LU, QR, symmetric eigendecomposition, and SVD.
3//!
4//! The results follow the conventions of the LAPACK routines that JAX calls
5//! on CPU, so that ruxla computes what JAX computes (up to rounding, since
6//! the algorithms differ in their order of operations):
7//!
8//! - [`cholesky`] (`potrf`): the lower factor in the lower triangle; the
9//!   strictly upper triangle of the input is left as it is; a matrix that
10//!   is not positive definite gives NaNs everywhere, as JAX returns;
11//! - [`triangular_solve`] (`trsm`): only the triangle given by `lower` is
12//!   read (and not the diagonal for a unit diagonal);
13//! - [`lu`] (`getrf`): partial pivoting choosing the first row with the
14//!   largest absolute value in the column, row swaps applied to whole rows,
15//!   and the multipliers scaled by the reciprocal of the pivot;
16//! - [`qr`] (`geqrf` and `orgqr`): Householder reflectors with LAPACK's
17//!   `larfg` convention (`beta = -sign(alpha) * norm`), so the signs of `Q`
18//!   and of the diagonal of `R` match LAPACK's;
19//! - [`eigh`] (`syevd`): eigenvalues in ascending order, only the triangle
20//!   given by `lower` read;
21//! - [`svd`] (`gesdd`): singular values in descending order.
22//!
23//! Eigenvectors and singular vectors are only defined up to sign (and up to
24//! a basis of each repeated eigenvalue), which LAPACK leaves to its
25//! algorithm. ruxla computes the eigendecomposition as LAPACK's `syev`
26//! does (the reduction to tridiagonal form and the implicit QL or QR
27//! algorithm, `steqr`), and the singular value decomposition as `gesvd`
28//! does (the reduction to bidiagonal form and `bdsqr`; one-sided Jacobi
29//! rotations on request), and then makes the component of largest magnitude of
30//! each eigenvector (of each left singular vector) positive, which is
31//! continuous in the input. Inputs with
32//! infinities or NaNs give NaNs for `eigh` and `svd` (where LAPACK reports
33//! an error, which JAX turns into NaNs).
34//!
35//! Complex matrices (`c64`, `c128`) follow the conventions of the complex
36//! LAPACK routines (`zpotrf`, `ztrsm`, `zgetrf`, `zgeqrf` and `zungqr`,
37//! `zheevd`, `zgesdd`): conjugate transposes in place of transposes, the
38//! pivots of `getrf` chosen by `|re| + |im|` (BLAS's `izamax`), Householder
39//! reflectors with `zlarfg`'s convention (a real `beta`), and real
40//! eigenvalues and singular values. Eigenvectors and singular vectors are
41//! defined up to a phase; ruxla makes the component of largest magnitude of
42//! each real and positive.
43
44use std::ops::{Add, Div, Mul, Neg, Sub};
45
46use crate::complex::Complex;
47use crate::dtype::Element;
48
49mod bidiagonal;
50mod eig;
51mod products;
52mod tridiagonal;
53pub use eig::{Cx, eig, hessenberg, schur};
54pub use products::{cholesky_update, symmetric_product};
55pub use tridiagonal::{tridiagonal, tridiagonal_solve};
56
57mod sealed {
58    pub trait Sealed {}
59    impl Sealed for f32 {}
60    impl Sealed for f64 {}
61    impl Sealed for super::Complex<f32> {}
62    impl Sealed for super::Complex<f64> {}
63}
64
65/// The real element types of linear algebra: `f32` and `f64`.
66pub trait LinalgFloat: LinalgScalar<LinalgReal = Self> + PartialOrd + sealed::Sealed {
67    /// The machine epsilon (`dlamch('E')` is half of it).
68    const EPSILON: Self;
69    /// The smallest positive normal number (`dlamch('S')`).
70    const MIN_POSITIVE: Self;
71    /// The square root.
72    fn sqrt(self) -> Self;
73    /// `sqrt(self^2 + other^2)` without undue overflow.
74    fn hypot(self, other: Self) -> Self;
75    /// `|self|` with the sign of `sign`.
76    fn copysign(self, sign: Self) -> Self;
77    /// Whether the value is NaN.
78    fn is_nan(self) -> bool;
79    /// The complex type of this real type (`c64` for `f32`).
80    type Complex: LinalgScalar<LinalgReal = Self>;
81}
82
83/// The element types of linear algebra: `f32`, `f64`, `c64`, and `c128`.
84pub trait LinalgScalar:
85    Element<Real = <Self as LinalgScalar>::LinalgReal>
86    + Add<Output = Self>
87    + Sub<Output = Self>
88    + Mul<Output = Self>
89    + Div<Output = Self>
90    + Neg<Output = Self>
91    + PartialEq
92    + sealed::Sealed
93{
94    /// The real type of the absolute values (`Self` for real types; the
95    /// element type's `Real`, whose `re`, `im`, and `from_parts` the
96    /// algorithms use).
97    type LinalgReal: LinalgFloat;
98    /// Whether the type is complex.
99    const IS_COMPLEX: bool;
100    /// Zero.
101    const ZERO: Self;
102    /// One.
103    const ONE: Self;
104    /// NaN (in both parts for complex types).
105    const NAN: Self;
106    /// The complex conjugate (the value itself for real types).
107    fn conj(self) -> Self;
108    /// The absolute value (the modulus for complex types).
109    fn abs(self) -> Self::LinalgReal;
110    /// `|re| + |im|`, by which BLAS's `izamax` compares complex values (the
111    /// absolute value for real types).
112    fn abs1(self) -> Self::LinalgReal;
113    /// `|x|^2`.
114    fn abs2(self) -> Self::LinalgReal;
115    /// `self * r` for a real `r`.
116    fn scale(self, r: Self::LinalgReal) -> Self;
117    /// Whether the value is finite (in both parts).
118    fn is_finite(self) -> bool;
119    /// The principal square root (NaN for negative real numbers).
120    fn csqrt(self) -> Self;
121    /// The value of a real number.
122    fn from_real(r: Self::LinalgReal) -> Self {
123        Self::from_parts(r, Self::LinalgReal::ZERO)
124    }
125}
126
127macro_rules! impl_linalg_float {
128    ($($t:ty)*) => {$(
129        impl LinalgScalar for $t {
130            type LinalgReal = $t;
131            const IS_COMPLEX: bool = false;
132            const ZERO: Self = 0.0;
133            const ONE: Self = 1.0;
134            const NAN: Self = <$t>::NAN;
135            #[inline]
136            fn conj(self) -> Self {
137                self
138            }
139            #[inline]
140            fn abs(self) -> Self {
141                <$t>::abs(self)
142            }
143            #[inline]
144            fn abs1(self) -> Self {
145                <$t>::abs(self)
146            }
147            #[inline]
148            fn abs2(self) -> Self {
149                self * self
150            }
151            #[inline]
152            fn scale(self, r: Self) -> Self {
153                self * r
154            }
155            #[inline]
156            fn is_finite(self) -> bool {
157                <$t>::is_finite(self)
158            }
159            #[inline]
160            fn csqrt(self) -> Self {
161                <$t>::sqrt(self)
162            }
163            #[inline]
164            fn from_real(r: Self) -> Self {
165                r
166            }
167        }
168
169        impl LinalgFloat for $t {
170            type Complex = Complex<$t>;
171            const EPSILON: Self = <$t>::EPSILON;
172            const MIN_POSITIVE: Self = <$t>::MIN_POSITIVE;
173            #[inline]
174            fn sqrt(self) -> Self {
175                <$t>::sqrt(self)
176            }
177            #[inline]
178            fn hypot(self, other: Self) -> Self {
179                <$t>::hypot(self, other)
180            }
181            #[inline]
182            fn copysign(self, sign: Self) -> Self {
183                <$t>::copysign(self, sign)
184            }
185            #[inline]
186            fn is_nan(self) -> bool {
187                <$t>::is_nan(self)
188            }
189        }
190
191        impl LinalgScalar for Complex<$t> {
192            type LinalgReal = $t;
193            const IS_COMPLEX: bool = true;
194            const ZERO: Self = Complex::new(0.0, 0.0);
195            const ONE: Self = Complex::new(1.0, 0.0);
196            const NAN: Self = Complex::new(<$t>::NAN, <$t>::NAN);
197            #[inline]
198            fn conj(self) -> Self {
199                Complex::new(self.re, -self.im)
200            }
201            #[inline]
202            fn abs(self) -> $t {
203                self.re.hypot(self.im)
204            }
205            #[inline]
206            fn abs1(self) -> $t {
207                self.re.abs() + self.im.abs()
208            }
209            #[inline]
210            fn abs2(self) -> $t {
211                self.re * self.re + self.im * self.im
212            }
213            #[inline]
214            fn scale(self, r: $t) -> Self {
215                Complex::new(self.re * r, self.im * r)
216            }
217            #[inline]
218            fn is_finite(self) -> bool {
219                self.re.is_finite() && self.im.is_finite()
220            }
221            #[inline]
222            fn csqrt(self) -> Self {
223                self.sqrt()
224            }
225        }
226    )*};
227}
228impl_linalg_float!(f32 f64);
229
230/// The Cholesky factorization `A = L L^H` of each `n x n` matrix of a batch
231/// of `batch` matrices, reading the lower triangle (LAPACK's `potrf` with
232/// `uplo = 'L'`; only the real part of the diagonal is read).
233///
234/// The result has `L` in the lower triangle and the strictly upper triangle
235/// of the input. A matrix that is not positive definite (or has NaNs) gives
236/// NaNs everywhere.
237///
238/// # Panics
239///
240/// Panics if `a` does not have `batch * n * n` elements.
241pub fn cholesky<T: LinalgScalar>(a: &[T], batch: usize, n: usize) -> Vec<T> {
242    assert_eq!(a.len(), batch * n * n, "cholesky: wrong number of elements");
243    let mut out = a.to_vec();
244    for m in out.chunks_exact_mut((n * n).max(1)).filter(|_| n > 0) {
245        if !cholesky_one(m, n) {
246            m.fill(T::NAN);
247        }
248    }
249    out
250}
251
252/// Factors one matrix in place (the lower triangle); returns `false` if it
253/// is not positive definite. Left-looking, as LAPACK's `potf2`.
254fn cholesky_one<T: LinalgScalar>(a: &mut [T], n: usize) -> bool {
255    for j in 0..n {
256        let mut ajj = a[j * n + j].re();
257        for k in 0..j {
258            ajj = ajj - a[j * n + k].abs2();
259        }
260        if ajj.is_nan() || ajj <= T::LinalgReal::ZERO {
261            return false;
262        }
263        let ajj = ajj.sqrt();
264        a[j * n + j] = T::from_real(ajj);
265        let r = T::LinalgReal::ONE / ajj;
266        for i in j + 1..n {
267            let mut v = a[i * n + j];
268            for k in 0..j {
269                v = v - a[i * n + k] * a[j * n + k].conj();
270            }
271            a[i * n + j] = v.scale(r);
272        }
273    }
274    true
275}
276
277/// The options of [`triangular_solve`], as in `lax.linalg.triangular_solve`.
278#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
279pub struct TriangularSolveOptions {
280    /// Solve `op(A) X = B` if true, `X op(A) = B` if false.
281    pub left_side: bool,
282    /// Use the lower triangle of `A` if true, the upper if false.
283    pub lower: bool,
284    /// `op(A) = A^T` if true, `A` if false.
285    pub transpose_a: bool,
286    /// Conjugate `A` in `op(A)` (no effect for real numbers).
287    pub conjugate_a: bool,
288    /// Assume that the diagonal of `A` is all ones (it is not read).
289    pub unit_diagonal: bool,
290}
291
292/// Solves `op(A) X = B` or `X op(A) = B` for each pair of a batch, where
293/// `A` is triangular (`k x k`, `k = m` on the left side and `n` on the
294/// right) and `B` is `m x n` (LAPACK's `trsm`).
295///
296/// # Panics
297///
298/// Panics if the slices do not have `batch` matrices of those sizes.
299pub fn triangular_solve<T: LinalgScalar>(
300    a: &[T],
301    b: &[T],
302    batch: usize,
303    m: usize,
304    n: usize,
305    options: TriangularSolveOptions,
306) -> Vec<T> {
307    let k = if options.left_side { m } else { n };
308    assert_eq!(a.len(), batch * k * k, "triangular_solve: wrong size of a");
309    assert_eq!(b.len(), batch * m * n, "triangular_solve: wrong size of b");
310    let mut out = b.to_vec();
311    if k == 0 || m * n == 0 {
312        return out;
313    }
314    let conjugate = options.conjugate_a && T::IS_COMPLEX;
315    for (a, x) in a.chunks_exact(k * k).zip(out.chunks_exact_mut(m * n)) {
316        let conj_a: Vec<T>;
317        let a = if conjugate {
318            conj_a = a.iter().map(|v| v.conj()).collect();
319            &conj_a[..]
320        } else {
321            a
322        };
323        if options.left_side {
324            // Each column of X solves op(A) x = b.
325            solve_vectors(
326                a,
327                k,
328                options.lower,
329                options.transpose_a,
330                options.unit_diagonal,
331                n,
332                |i, c| i * n + c,
333                x,
334            );
335        } else {
336            // Each row of X solves op(A)^T x = b.
337            solve_vectors(
338                a,
339                k,
340                options.lower,
341                !options.transpose_a,
342                options.unit_diagonal,
343                m,
344                |i, r| r * n + i,
345                x,
346            );
347        }
348    }
349    out
350}
351
352/// Solves `M x = b` in place for `count` vectors, where `M = A` or `A^T`
353/// (`transpose`) for the triangle of `A` given by `lower`, and element `i`
354/// of vector `v` is `x[index(i, v)]`.
355#[allow(clippy::too_many_arguments)] // The parameters of a BLAS routine.
356fn solve_vectors<T: LinalgScalar>(
357    a: &[T],
358    k: usize,
359    lower: bool,
360    transpose: bool,
361    unit_diagonal: bool,
362    count: usize,
363    index: impl Fn(usize, usize) -> usize,
364    x: &mut [T],
365) {
366    // M[i][j] for the stored triangle.
367    let at = |i: usize, j: usize| {
368        if transpose {
369            a[j * k + i]
370        } else {
371            a[i * k + j]
372        }
373    };
374    // M is lower triangular when A's lower triangle is used untransposed or
375    // its upper triangle transposed.
376    let forward = lower != transpose;
377    for v in 0..count {
378        let mut solve_row = |i: usize, js: &mut dyn Iterator<Item = usize>| {
379            let mut s = x[index(i, v)];
380            for j in js {
381                s = s - at(i, j) * x[index(j, v)];
382            }
383            if !unit_diagonal {
384                s = s / at(i, i);
385            }
386            x[index(i, v)] = s;
387        };
388        if forward {
389            for i in 0..k {
390                solve_row(i, &mut (0..i));
391            }
392        } else {
393            for i in (0..k).rev() {
394                solve_row(i, &mut (i + 1..k));
395            }
396        }
397    }
398}
399
400/// The LU factorization with partial pivoting `P A = L U` of each `m x n`
401/// matrix of a batch (LAPACK's `getrf`).
402///
403/// Returns the factors (`L` below the diagonal with an implicit unit
404/// diagonal, `U` on and above it), the pivots (`min(m, n)` row swaps per
405/// matrix, 0-based: row `i` was swapped with row `pivots[i]`), and the
406/// permutation (`m` per matrix: row `i` of `P A` is row `permutation[i]` of
407/// `A`).
408///
409/// # Panics
410///
411/// Panics if `a` does not have `batch * m * n` elements, or if `m` does not
412/// fit in an `i32`.
413pub fn lu<T: LinalgScalar>(
414    a: &[T],
415    batch: usize,
416    m: usize,
417    n: usize,
418) -> (Vec<T>, Vec<i32>, Vec<i32>) {
419    assert_eq!(a.len(), batch * m * n, "lu: wrong number of elements");
420    assert!(i32::try_from(m).is_ok(), "lu: too many rows for i32 pivots");
421    let k = m.min(n);
422    let mut out = a.to_vec();
423    let mut pivots = vec![0i32; batch * k];
424    for b in 0..batch {
425        let mat = &mut out[b * m * n..(b + 1) * m * n];
426        let piv = &mut pivots[b * k..(b + 1) * k];
427        lu_one(mat, m, n, piv);
428    }
429    let permutation = lu_pivots_to_permutation(&pivots, batch, k, m);
430    (out, pivots, permutation)
431}
432
433/// Factors one matrix in place, right-looking as LAPACK's `getf2`.
434fn lu_one<T: LinalgScalar>(a: &mut [T], m: usize, n: usize, pivots: &mut [i32]) {
435    for j in 0..m.min(n) {
436        // BLAS's `iamax`: the first index of the largest magnitude (`|re| +
437        // |im|` for complex values; NaNs compare false, so they are only
438        // chosen if they come first).
439        let mut p = j;
440        let mut max = a[j * n + j].abs1();
441        for i in j + 1..m {
442            let v = a[i * n + j].abs1();
443            if v > max {
444                max = v;
445                p = i;
446            }
447        }
448        pivots[j] = p as i32;
449        if a[p * n + j] != T::ZERO {
450            if p != j {
451                for c in 0..n {
452                    a.swap(j * n + c, p * n + c);
453                }
454            }
455            let pivot = a[j * n + j];
456            if pivot.abs() >= T::LinalgReal::MIN_POSITIVE {
457                let r = T::ONE / pivot;
458                for i in j + 1..m {
459                    a[i * n + j] = a[i * n + j] * r;
460                }
461            } else {
462                for i in j + 1..m {
463                    a[i * n + j] = a[i * n + j] / pivot;
464                }
465            }
466        }
467        // The rank-one update of the trailing matrix.
468        for i in j + 1..m {
469            let l = a[i * n + j];
470            for c in j + 1..n {
471                a[i * n + c] = a[i * n + c] - l * a[j * n + c];
472            }
473        }
474    }
475}
476
477/// Converts the pivots of [`lu`] (`k` row swaps per batch element) into
478/// permutations of `size` elements: starting from the identity, swaps
479/// element `i` with element `pivots[i]` for each `i` in order (as
480/// `lax.linalg.lu_pivots_to_permutation`). Pivots out of range leave the
481/// permutation unchanged at that step.
482///
483/// # Panics
484///
485/// Panics if `pivots` does not have `batch * k` elements.
486pub fn lu_pivots_to_permutation(pivots: &[i32], batch: usize, k: usize, size: usize) -> Vec<i32> {
487    assert_eq!(
488        pivots.len(),
489        batch * k,
490        "lu_pivots_to_permutation: wrong size"
491    );
492    let mut out = Vec::with_capacity(batch * size);
493    for b in 0..batch {
494        let start = out.len();
495        out.extend((0..size).map(|i| i as i32));
496        let perm = &mut out[start..];
497        for (i, &p) in pivots[b * k..(b + 1) * k].iter().enumerate() {
498            if i < size && p >= 0 && (p as usize) < size {
499                perm.swap(i, p as usize);
500            }
501        }
502    }
503    out
504}
505
506/// The 2-norm of a vector, scaled to avoid overflow and underflow (as BLAS's
507/// `nrm2`, over the real and imaginary parts for complex vectors).
508fn norm2<T: LinalgScalar>(x: impl Iterator<Item = T> + Clone) -> T::LinalgReal {
509    let parts = x.flat_map(|v| {
510        let im = T::IS_COMPLEX.then(|| v.im());
511        std::iter::once(v.re()).chain(im)
512    });
513    let zero = T::LinalgReal::ZERO;
514    let mut scale = zero;
515    for v in parts.clone() {
516        let a = v.abs();
517        if a > scale || a.is_nan() {
518            scale = a;
519        }
520    }
521    if scale == zero || !scale.is_finite() {
522        return scale;
523    }
524    let mut sum = zero;
525    for v in parts {
526        let s = v / scale;
527        sum = sum + s * s;
528    }
529    scale * sum.sqrt()
530}
531
532/// LAPACK's `larfg` (`zlarfg` for complex numbers): the Householder
533/// reflector `H = I - tau v v^H` with `v = [1, x']` such that `H^H [alpha,
534/// x] = [beta, 0]` with a real `beta`. Overwrites `x` with `x'` and returns
535/// `(beta, tau)`.
536fn larfg<T: LinalgScalar>(alpha: T, x: &mut [T]) -> (T, T) {
537    let xnorm = norm2(x.iter().copied());
538    let zero = T::LinalgReal::ZERO;
539    let one = T::LinalgReal::ONE;
540    if xnorm == zero && alpha.im() == zero {
541        return (alpha, T::ZERO);
542    }
543    // `dlapy3(re(alpha), im(alpha), xnorm)` (`hypot` for real numbers).
544    let lapy = |alpha: T, xnorm: T::LinalgReal| {
545        if T::IS_COMPLEX {
546            alpha.re().hypot(alpha.im()).hypot(xnorm)
547        } else {
548            alpha.re().hypot(xnorm)
549        }
550    };
551    let mut alpha = alpha;
552    let mut xnorm = xnorm;
553    let mut beta = -lapy(alpha, xnorm).copysign(alpha.re());
554    // Rescale tiny vectors, as `larfg` does, so that `tau` is accurate.
555    let safmin =
556        T::LinalgReal::MIN_POSITIVE / (T::LinalgReal::EPSILON * from_f64::<T::LinalgReal>(0.5));
557    let rsafmn = one / safmin;
558    let mut knt = 0;
559    if beta.abs() < safmin {
560        while beta.abs() < safmin && knt < 20 {
561            knt += 1;
562            for v in x.iter_mut() {
563                *v = v.scale(rsafmn);
564            }
565            beta = beta * rsafmn;
566            alpha = alpha.scale(rsafmn);
567        }
568        xnorm = norm2(x.iter().copied());
569        beta = -lapy(alpha, xnorm).copysign(alpha.re());
570    }
571    let tau = T::from_parts((beta - alpha.re()) / beta, -alpha.im() / beta);
572    let r = T::ONE / (alpha - T::from_real(beta));
573    for v in x.iter_mut() {
574        *v = *v * r;
575    }
576    for _ in 0..knt {
577        beta = beta * safmin;
578    }
579    (T::from_real(beta), tau)
580}
581
582fn from_f64<T: LinalgFloat>(v: f64) -> T {
583    crate::dtype::cast::<f64, T>(v)
584}
585
586/// Applies `H = I - tau v v^H` from the left to the columns `c0..c1` of
587/// the rows `r0..m` of the `? x n` matrix `a`, where `v[0] = 1` and
588/// `v[1..]` is stored in column `vc` below row `r0` (LAPACK's `larf`).
589#[allow(clippy::too_many_arguments)] // Matrix, reflector, and block bounds.
590fn apply_reflector<T: LinalgScalar>(
591    a: &mut [T],
592    n: usize,
593    m: usize,
594    r0: usize,
595    vc: usize,
596    tau: T,
597    c0: usize,
598    c1: usize,
599) {
600    if tau == T::ZERO || c0 >= c1 {
601        return;
602    }
603    let v: Vec<T> = (r0..m)
604        .map(|i| if i == r0 { T::ONE } else { a[i * n + vc] })
605        .collect();
606    // `w = v^H A`, then `A -= v (tau w)`, row by row (each sum still runs
607    // over the rows in order, so the rounding is that of the column-wise
608    // loops).
609    let mut w = vec![T::ZERO; c1 - c0];
610    for (i, vi) in (r0..m).zip(&v) {
611        let vi = vi.conj();
612        for (wc, x) in w.iter_mut().zip(&a[i * n + c0..i * n + c1]) {
613            *wc = *wc + vi * *x;
614        }
615    }
616    for wc in &mut w {
617        *wc = tau * *wc;
618    }
619    for (i, &vi) in (r0..m).zip(&v) {
620        for (x, &tw) in a[i * n + c0..i * n + c1].iter_mut().zip(&w) {
621            *x = *x - vi * tw;
622        }
623    }
624}
625
626/// The QR decomposition `A = Q R` of each `m x n` matrix of a batch, as
627/// `lax.linalg.qr` computes it with LAPACK's `geqrf` and `orgqr` (`ungqr`
628/// for complex numbers).
629///
630/// With `full_matrices`, `Q` is `m x m` and `R` is `m x n`; otherwise `Q` is
631/// `m x k` and `R` is `k x n`, where `k = min(m, n)`.
632///
633/// # Panics
634///
635/// Panics if `a` does not have `batch * m * n` elements.
636pub fn qr<T: LinalgScalar>(
637    a: &[T],
638    batch: usize,
639    m: usize,
640    n: usize,
641    full_matrices: bool,
642) -> (Vec<T>, Vec<T>) {
643    let (q, r, _) = qr_impl(a, batch, m, n, full_matrices, false);
644    (q, r)
645}
646
647/// The QR decomposition with column pivoting `A P = Q R` of each `m x n`
648/// matrix of a batch, as `lax.linalg.qr(pivoting=True)` computes it with
649/// LAPACK's `geqp3` (its unblocked `laqp2`): at each step, the column of
650/// largest remaining norm (the first one, if several) is moved forward,
651/// and the norms are downdated, or recomputed where the downdate loses
652/// accuracy.
653///
654/// Returns `Q` and `R` (as [`qr`]) and the permutations (`n` per matrix,
655/// 0-based: column `j` of `A P` is column `p[j]` of `A`; zeros for empty
656/// matrices, as JAX returns).
657///
658/// # Panics
659///
660/// Panics if `a` does not have `batch * m * n` elements, or if `n` does not
661/// fit in an `i32`.
662pub fn qr_pivoting<T: LinalgScalar>(
663    a: &[T],
664    batch: usize,
665    m: usize,
666    n: usize,
667    full_matrices: bool,
668) -> (Vec<T>, Vec<T>, Vec<i32>) {
669    assert!(
670        i32::try_from(n).is_ok(),
671        "qr: too many columns for i32 pivots"
672    );
673    qr_impl(a, batch, m, n, full_matrices, true)
674}
675
676fn qr_impl<T: LinalgScalar>(
677    a: &[T],
678    batch: usize,
679    m: usize,
680    n: usize,
681    full_matrices: bool,
682    pivoting: bool,
683) -> (Vec<T>, Vec<T>, Vec<i32>) {
684    assert_eq!(a.len(), batch * m * n, "qr: wrong number of elements");
685    let k = m.min(n);
686    let kq = if full_matrices { m } else { k };
687    let mut q_out = Vec::with_capacity(batch * m * kq);
688    let mut r_out = Vec::with_capacity(batch * kq * n);
689    let mut p_out = Vec::with_capacity(if pivoting { batch * n } else { 0 });
690    for mat in a.chunks_exact((m * n).max(1)).take(batch) {
691        let mut r = mat.to_vec();
692        let taus = if pivoting {
693            let (taus, jpvt) = geqp3_one(&mut r, m, n);
694            p_out.extend(jpvt);
695            taus
696        } else {
697            geqrf_one(&mut r, m, n)
698        };
699        // `orgqr` on the first `kq` columns of the reflectors (padded with
700        // zero columns if there are fewer).
701        let mut q = vec![T::ZERO; m * kq];
702        for i in 0..m {
703            for j in 0..kq.min(n) {
704                q[i * kq + j] = r[i * n + j];
705            }
706        }
707        orgqr_one(&mut q, m, kq, &taus);
708        q_out.extend_from_slice(&q);
709        for i in 0..kq {
710            for j in 0..n {
711                r_out.push(if j >= i && i < m {
712                    r[i * n + j]
713                } else {
714                    T::ZERO
715                });
716            }
717        }
718    }
719    // A batch of empty matrices still has `batch` (empty or identity) Qs,
720    // and zero permutations.
721    if m * n == 0 {
722        q_out.clear();
723        r_out.clear();
724        p_out.clear();
725        for _ in 0..batch {
726            let mut q = vec![T::ZERO; m * kq];
727            orgqr_one(&mut q, m, kq, &[]);
728            q_out.extend_from_slice(&q);
729            r_out.extend(std::iter::repeat_n(T::ZERO, kq * n));
730            if pivoting {
731                p_out.extend(std::iter::repeat_n(0, n));
732            }
733        }
734    }
735    (q_out, r_out, p_out)
736}
737
738/// LAPACK's `geqp3` (`laqp2`) on one matrix in place, with all columns
739/// free: `R` on and above the diagonal, the reflectors below it; returns
740/// the `min(m, n)` factors `tau` and the 0-based column permutation.
741fn geqp3_one<T: LinalgScalar>(a: &mut [T], m: usize, n: usize) -> (Vec<T>, Vec<i32>) {
742    let k = m.min(n);
743    let mut jpvt: Vec<i32> = (0..n as i32).collect();
744    let mut vn1: Vec<T::LinalgReal> = (0..n)
745        .map(|j| norm2((0..m).map(|r| a[r * n + j])))
746        .collect();
747    let mut vn2 = vn1.clone();
748    let zero = T::LinalgReal::ZERO;
749    let one = T::LinalgReal::ONE;
750    // `sqrt(dlamch('Epsilon'))`, LAPACK's epsilon being half the machine
751    // epsilon.
752    let tol3z = (T::LinalgReal::EPSILON * from_f64::<T::LinalgReal>(0.5)).sqrt();
753    let mut taus = Vec::with_capacity(k);
754    for i in 0..k {
755        // BLAS's `idamax` over the remaining norms.
756        let mut pvt = i;
757        let mut max = vn1[i];
758        for (j, &v) in vn1.iter().enumerate().skip(i + 1) {
759            if v > max {
760                max = v;
761                pvt = j;
762            }
763        }
764        if pvt != i {
765            for r in 0..m {
766                a.swap(r * n + pvt, r * n + i);
767            }
768            jpvt.swap(pvt, i);
769            vn1[pvt] = vn1[i];
770            vn2[pvt] = vn2[i];
771        }
772        let mut x: Vec<T> = (i + 1..m).map(|r| a[r * n + i]).collect();
773        let (beta, tau) = larfg(a[i * n + i], &mut x);
774        for (r, v) in (i + 1..m).zip(x) {
775            a[r * n + i] = v;
776        }
777        a[i * n + i] = beta;
778        apply_reflector(a, n, m, i, i, tau.conj(), i + 1, n);
779        taus.push(tau);
780        // Downdate the norms of the remaining columns.
781        for j in i + 1..n {
782            if vn1[j] == zero {
783                continue;
784            }
785            let ratio = a[i * n + j].abs() / vn1[j];
786            let temp = one - ratio * ratio;
787            let temp = if temp > zero { temp } else { zero };
788            let scale = vn1[j] / vn2[j];
789            let temp2 = temp * scale * scale;
790            if temp2 <= tol3z {
791                if i + 1 < m {
792                    vn1[j] = norm2((i + 1..m).map(|r| a[r * n + j]));
793                    vn2[j] = vn1[j];
794                } else {
795                    vn1[j] = zero;
796                    vn2[j] = zero;
797                }
798            } else {
799                vn1[j] = vn1[j] * temp.sqrt();
800            }
801        }
802    }
803    (taus, jpvt)
804}
805
806/// The first `n` columns of the product `Q = H_0 H_1 ... H_{k-1}` of the
807/// Householder reflectors stored below the diagonal of the first `k`
808/// columns of each `m x n` matrix of a batch (`m >= n >= k`), as LAPACK's
809/// `orgqr` (`ungqr`) and `lax.linalg.householder_product`.
810///
811/// # Panics
812///
813/// Panics if the slices do not have `batch` matrices and `batch` vectors of
814/// `k` factors, or if `m < n` or `n < k`.
815pub fn householder_product<T: LinalgScalar>(
816    a: &[T],
817    taus: &[T],
818    batch: usize,
819    m: usize,
820    n: usize,
821    k: usize,
822) -> Vec<T> {
823    assert!(m >= n && n >= k, "householder_product: needs m >= n >= k");
824    assert_eq!(
825        a.len(),
826        batch * m * n,
827        "householder_product: wrong size of a"
828    );
829    assert_eq!(
830        taus.len(),
831        batch * k,
832        "householder_product: wrong size of taus"
833    );
834    let mut out = a.to_vec();
835    for b in 0..batch {
836        orgqr_one(
837            &mut out[b * m * n..(b + 1) * m * n],
838            m,
839            n,
840            &taus[b * k..(b + 1) * k],
841        );
842    }
843    out
844}
845
846/// Multiplies each `rows x cols` matrix `c` of a batch by `Q` (`Q^H` with
847/// `transpose`) from the left (`left`) or the right, where `Q = H_0 ...
848/// H_{k-1}` is given by the reflectors below the diagonal of the first `k`
849/// columns of the `m x n` matrix `a` (`m` = `rows` from the left, `cols`
850/// from the right) and the factors `taus`, without forming `Q` (LAPACK's
851/// `ormqr`, `unmqr`, and `lax.linalg.ormqr`).
852///
853/// # Panics
854///
855/// Panics if the slices do not have the sizes of a batch of these.
856#[allow(clippy::too_many_arguments)] // The shapes and options of `ormqr`.
857pub fn ormqr<T: LinalgScalar>(
858    a: &[T],
859    taus: &[T],
860    c: &[T],
861    batch: usize,
862    (m, n, k): (usize, usize, usize),
863    (rows, cols): (usize, usize),
864    left: bool,
865    transpose: bool,
866) -> Vec<T> {
867    assert_eq!(a.len(), batch * m * n, "ormqr: wrong size of a");
868    assert_eq!(taus.len(), batch * k, "ormqr: wrong size of taus");
869    assert_eq!(c.len(), batch * rows * cols, "ormqr: wrong size of c");
870    assert_eq!(
871        if left { rows } else { cols },
872        m,
873        "ormqr: incompatible shapes"
874    );
875    let mut out = c.to_vec();
876    for b in 0..batch {
877        let a = &a[b * m * n..(b + 1) * m * n];
878        let taus = &taus[b * k..(b + 1) * k];
879        let c = &mut out[b * rows * cols..(b + 1) * rows * cols];
880        // `Q c` and `c Q^H` apply the reflectors in reverse order.
881        let reverse = left != transpose;
882        for step in 0..k {
883            let i = if reverse { k - 1 - step } else { step };
884            let tau = if transpose { taus[i].conj() } else { taus[i] };
885            if tau == T::ZERO {
886                continue;
887            }
888            // `v[r]` for `r >= i` (`v[i] = 1`).
889            let v = |r: usize| if r == i { T::ONE } else { a[r * n + i] };
890            if left {
891                // `c := c - tau v (v^H c)`.
892                for col in 0..cols {
893                    let mut w = T::ZERO;
894                    for r in i..m {
895                        w = w + v(r).conj() * c[r * cols + col];
896                    }
897                    let tw = tau * w;
898                    for r in i..m {
899                        c[r * cols + col] = c[r * cols + col] - v(r) * tw;
900                    }
901                }
902            } else {
903                // `c := c - tau (c v) v^H`.
904                for row in 0..rows {
905                    let mut w = T::ZERO;
906                    for r in i..m {
907                        w = w + c[row * cols + r] * v(r);
908                    }
909                    let tw = w * tau;
910                    for r in i..m {
911                        c[row * cols + r] = c[row * cols + r] - tw * v(r).conj();
912                    }
913                }
914            }
915        }
916    }
917    out
918}
919
920/// LAPACK's `geqr2` on one matrix in place: `R` on and above the diagonal,
921/// the reflectors below it; returns the `min(m, n)` factors `tau`.
922fn geqrf_one<T: LinalgScalar>(a: &mut [T], m: usize, n: usize) -> Vec<T> {
923    let k = m.min(n);
924    let mut taus = Vec::with_capacity(k);
925    for i in 0..k {
926        let mut x: Vec<T> = (i + 1..m).map(|r| a[r * n + i]).collect();
927        let (beta, tau) = larfg(a[i * n + i], &mut x);
928        for (r, v) in (i + 1..m).zip(x) {
929            a[r * n + i] = v;
930        }
931        a[i * n + i] = beta;
932        // `geqr2` applies `H^H` to the rest of the matrix.
933        apply_reflector(a, n, m, i, i, tau.conj(), i + 1, n);
934        taus.push(tau);
935    }
936    taus
937}
938
939/// LAPACK's `org2r` (`ung2r`) on one `m x nq` matrix in place: forms the
940/// first `nq` columns of `Q = H_0 H_1 ... H_{k-1}` from the reflectors
941/// stored below the diagonal of its first `k = taus.len()` columns.
942fn orgqr_one<T: LinalgScalar>(a: &mut [T], m: usize, nq: usize, taus: &[T]) {
943    let k = taus.len();
944    // Columns k..nq start as columns of the identity.
945    for j in k..nq {
946        for i in 0..m {
947            a[i * nq + j] = T::ZERO;
948        }
949        if j < m {
950            a[j * nq + j] = T::ONE;
951        }
952    }
953    for i in (0..k).rev() {
954        if i + 1 < nq {
955            a[i * nq + i] = T::ONE;
956            apply_reflector(a, nq, m, i, i, taus[i], i + 1, nq);
957        }
958        for r in i + 1..m {
959            a[r * nq + i] = -taus[i] * a[r * nq + i];
960        }
961        a[i * nq + i] = T::ONE - taus[i];
962        for r in 0..i {
963            a[r * nq + i] = T::ZERO;
964        }
965    }
966}
967
968/// Makes the component of largest magnitude of column `c` of the `rows x
969/// cols` matrix `v` real and positive (the first one, if several have it):
970/// negates the column for real numbers, multiplies it by a phase for
971/// complex ones. Returns the factor applied, if any.
972fn normalize_phase<T: LinalgScalar>(v: &mut [T], rows: usize, cols: usize, c: usize) -> Option<T> {
973    let mut best = 0;
974    let mut max = T::LinalgReal::ZERO;
975    for r in 0..rows {
976        let a = v[r * cols + c].abs();
977        if a > max {
978            max = a;
979            best = r;
980        }
981    }
982    if rows == 0 {
983        return None;
984    }
985    let z = v[best * cols + c];
986    if !T::IS_COMPLEX {
987        if z.re() < T::LinalgReal::ZERO {
988            for r in 0..rows {
989                v[r * cols + c] = -v[r * cols + c];
990            }
991            return Some(-T::ONE);
992        }
993        return None;
994    }
995    if z.im() == T::LinalgReal::ZERO && z.re() >= T::LinalgReal::ZERO {
996        return None;
997    }
998    // `conj(z) / |z|`; the component itself becomes exactly `|z|`.
999    let f = T::from_parts(z.re() / max, -z.im() / max);
1000    for r in 0..rows {
1001        v[r * cols + c] = v[r * cols + c] * f;
1002    }
1003    v[best * cols + c] = T::from_real(max);
1004    Some(f)
1005}
1006
1007/// The phase that makes the off-diagonal element `x` of a rotation real:
1008/// `(|x|, conj(x) / |x|)`; real numbers keep their sign (`(x, 1)`), so that
1009/// the rotations of real matrices are the plain Jacobi rotations.
1010fn rotation_phase<T: LinalgScalar>(x: T) -> (T::LinalgReal, Option<T>) {
1011    if T::IS_COMPLEX {
1012        let mag = x.abs();
1013        (mag, Some(T::from_parts(x.re() / mag, -x.im() / mag)))
1014    } else {
1015        (x.re(), None)
1016    }
1017}
1018
1019/// The maximum number of Jacobi sweeps; they converge quadratically, in
1020/// about ten sweeps for any size in practice.
1021const MAX_SWEEPS: usize = 60;
1022
1023/// The eigendecomposition `A = V diag(w) V^H` of each Hermitian (symmetric
1024/// for real numbers) `n x n` matrix of a batch, reading the triangle given
1025/// by `lower` (LAPACK's `syevd` and `heevd`; only the real part of the
1026/// diagonal is read), by the reduction to tridiagonal form and the QL or QR
1027/// algorithm (LAPACK's `syev`), or with `jacobi`, by cyclic Jacobi
1028/// rotations.
1029///
1030/// Returns the eigenvectors (`V`, one per column) and the real eigenvalues
1031/// (`w`, in ascending order, which `sort_eigenvalues = false` allows but
1032/// does not require changing). Matrices with infinities or NaNs in the
1033/// triangle give NaNs.
1034///
1035/// # Panics
1036///
1037/// Panics if `a` does not have `batch * n * n` elements.
1038pub fn eigh<T: LinalgScalar>(
1039    a: &[T],
1040    batch: usize,
1041    n: usize,
1042    lower: bool,
1043    jacobi: bool,
1044) -> (Vec<T>, Vec<T::LinalgReal>) {
1045    assert_eq!(a.len(), batch * n * n, "eigh: wrong number of elements");
1046    let mut vs = Vec::with_capacity(batch * n * n);
1047    let mut ws = Vec::with_capacity(batch * n);
1048    for b in 0..batch {
1049        let mat = &a[b * n * n..(b + 1) * n * n];
1050        let (v, w) = eigh_one(mat, n, lower, jacobi);
1051        vs.extend(v);
1052        ws.extend(w);
1053    }
1054    (vs, ws)
1055}
1056
1057fn eigh_one<T: LinalgScalar>(
1058    a: &[T],
1059    n: usize,
1060    lower: bool,
1061    jacobi: bool,
1062) -> (Vec<T>, Vec<T::LinalgReal>) {
1063    // The Hermitian matrix of the triangle.
1064    let mut s = vec![T::ZERO; n * n];
1065    let mut finite = true;
1066    for i in 0..n {
1067        for j in 0..=i {
1068            // Element (i, j) of the lower triangle.
1069            let v = if lower {
1070                a[i * n + j]
1071            } else {
1072                a[j * n + i].conj()
1073            };
1074            finite &= v.is_finite();
1075            if i == j {
1076                s[i * n + i] = T::from_real(v.re());
1077            } else {
1078                s[i * n + j] = v;
1079                s[j * n + i] = v.conj();
1080            }
1081        }
1082    }
1083    if !finite {
1084        return (vec![T::NAN; n * n], vec![T::LinalgReal::NAN; n]);
1085    }
1086    let solved = if jacobi {
1087        Some(eigh_jacobi(s, n))
1088    } else {
1089        tridiagonal::eigh_tridiagonal(&s, n)
1090    };
1091    let Some((mut sorted, w)) = solved else {
1092        return (vec![T::NAN; n * n], vec![T::LinalgReal::NAN; n]);
1093    };
1094    for c in 0..n {
1095        normalize_phase(&mut sorted, n, n, c);
1096    }
1097    (sorted, w)
1098}
1099
1100/// The eigendecomposition of the Hermitian `n x n` matrix `s` (both
1101/// triangles) by cyclic Jacobi rotations: the eigenvectors (columns) and
1102/// the eigenvalues in ascending order.
1103fn eigh_jacobi<T: LinalgScalar>(mut s: Vec<T>, n: usize) -> (Vec<T>, Vec<T::LinalgReal>) {
1104    let mut v = vec![T::ZERO; n * n];
1105    for i in 0..n {
1106        v[i * n + i] = T::ONE;
1107    }
1108    // Rotations below this size of the off-diagonal element change nothing
1109    // representable.
1110    let fro = norm2(s.iter().copied());
1111    let floor = fmax(
1112        T::LinalgReal::MIN_POSITIVE,
1113        fro * T::LinalgReal::EPSILON * T::LinalgReal::EPSILON,
1114    );
1115    let one = T::LinalgReal::ONE;
1116    for _ in 0..MAX_SWEEPS {
1117        let mut rotated = false;
1118        for p in 0..n {
1119            for q in p + 1..n {
1120                let apq = s[p * n + q];
1121                let (app, aqq) = (s[p * n + p].re(), s[q * n + q].re());
1122                // Skip elements negligible relative to the diagonal, which
1123                // gives eigenvalues with high relative accuracy.
1124                let mag = apq.abs();
1125                if mag <= floor || mag <= T::LinalgReal::EPSILON * (app.abs() * aqq.abs()).sqrt() {
1126                    continue;
1127                }
1128                rotated = true;
1129                // For complex matrices, column q is first multiplied by the
1130                // phase `u` that makes element (p, q) real.
1131                let (apq, u) = rotation_phase(apq);
1132                let phase = |x: T| u.map_or(x, |u| x * u);
1133                let theta = (aqq - app) / (apq + apq);
1134                let t = one.copysign(theta) / (theta.abs() + one.hypot(theta));
1135                let c = one / one.hypot(t);
1136                let sn = t * c;
1137                s[p * n + p] = T::from_real(app - t * apq);
1138                s[q * n + q] = T::from_real(aqq + t * apq);
1139                s[p * n + q] = T::ZERO;
1140                s[q * n + p] = T::ZERO;
1141                for r in 0..n {
1142                    if r != p && r != q {
1143                        let (arp, arq) = (s[r * n + p], phase(s[r * n + q]));
1144                        let np = arp.scale(c) - arq.scale(sn);
1145                        let nq = arp.scale(sn) + arq.scale(c);
1146                        s[r * n + p] = np;
1147                        s[p * n + r] = np.conj();
1148                        s[r * n + q] = nq;
1149                        s[q * n + r] = nq.conj();
1150                    }
1151                    let (vrp, vrq) = (v[r * n + p], phase(v[r * n + q]));
1152                    v[r * n + p] = vrp.scale(c) - vrq.scale(sn);
1153                    v[r * n + q] = vrp.scale(sn) + vrq.scale(c);
1154                }
1155            }
1156        }
1157        if !rotated {
1158            break;
1159        }
1160    }
1161    // Ascending eigenvalues; the sort is stable.
1162    let mut order: Vec<usize> = (0..n).collect();
1163    order.sort_by(|&i, &j| {
1164        s[i * n + i]
1165            .re()
1166            .partial_cmp(&s[j * n + j].re())
1167            .unwrap_or(std::cmp::Ordering::Equal)
1168    });
1169    let w: Vec<T::LinalgReal> = order.iter().map(|&i| s[i * n + i].re()).collect();
1170    let mut sorted = vec![T::ZERO; n * n];
1171    for (c, &i) in order.iter().enumerate() {
1172        for r in 0..n {
1173            sorted[r * n + c] = v[r * n + i];
1174        }
1175    }
1176    (sorted, w)
1177}
1178
1179/// The larger of two values (the first if either is NaN).
1180fn fmax<T: LinalgFloat>(a: T, b: T) -> T {
1181    if b > a { b } else { a }
1182}
1183
1184/// The singular value decomposition `A = U diag(s) V^H` of each `m x n`
1185/// matrix of a batch (what JAX computes with LAPACK's `gesdd`), by
1186/// bidiagonalization and the QR algorithm (LAPACK's `gesvd`), or with
1187/// `jacobi`, by one-sided Jacobi rotations.
1188///
1189/// Returns the real singular values (`min(m, n)` per matrix, in descending
1190/// order), and, with `compute_uv`, `U` and `V^H`: `m x m` and `n x n` with
1191/// `full_matrices`, `m x k` and `k x n` otherwise (`k = min(m, n)`).
1192/// Matrices with infinities or NaNs, and matrices on which the QR
1193/// algorithm does not converge, give NaNs.
1194///
1195/// # Panics
1196///
1197/// Panics if `a` does not have `batch * m * n` elements.
1198pub fn svd<T: LinalgScalar>(
1199    a: &[T],
1200    batch: usize,
1201    m: usize,
1202    n: usize,
1203    full_matrices: bool,
1204    compute_uv: bool,
1205    jacobi: bool,
1206) -> (Vec<T::LinalgReal>, Vec<T>, Vec<T>) {
1207    assert_eq!(a.len(), batch * m * n, "svd: wrong number of elements");
1208    let k = m.min(n);
1209    let (ucols, vrows) = if full_matrices { (m, n) } else { (k, k) };
1210    let mut s_out = Vec::with_capacity(batch * k);
1211    let mut u_out = Vec::new();
1212    let mut vt_out = Vec::new();
1213    for b in 0..batch {
1214        let mat = &a[b * m * n..(b + 1) * m * n];
1215        let (s, u, vt) = svd_one(mat, m, n, ucols, vrows, jacobi);
1216        s_out.extend(s);
1217        if compute_uv {
1218            u_out.extend(u);
1219            vt_out.extend(vt);
1220        }
1221    }
1222    (s_out, u_out, vt_out)
1223}
1224
1225/// The SVD of one matrix: `s`, `U` (`m x ucols`), and `V^H` (`vrows x n`),
1226/// by bidiagonalization (or one-sided Jacobi rotations with `jacobi`).
1227fn svd_one<T: LinalgScalar>(
1228    a: &[T],
1229    m: usize,
1230    n: usize,
1231    ucols: usize,
1232    vrows: usize,
1233    jacobi: bool,
1234) -> (Vec<T::LinalgReal>, Vec<T>, Vec<T>) {
1235    let k = m.min(n);
1236    if a.iter().any(|v| !v.is_finite()) {
1237        return (
1238            vec![T::LinalgReal::NAN; k],
1239            vec![T::NAN; m * ucols],
1240            vec![T::NAN; vrows * n],
1241        );
1242    }
1243    // One-sided Jacobi on the columns of the taller orientation: `g` is
1244    // `rows x cols` with `rows >= cols`, `g = A` or `A^H`, stored by columns
1245    // (`g[c * rows + r]`, so that the rotations read contiguous memory), and
1246    // so is the accumulated rotation `w`.
1247    let tall = m >= n;
1248    let (rows, cols) = if tall { (m, n) } else { (n, m) };
1249    let mut g = vec![T::ZERO; rows * cols];
1250    for i in 0..m {
1251        for j in 0..n {
1252            if tall {
1253                g[j * rows + i] = a[i * n + j];
1254            } else {
1255                g[i * rows + j] = a[i * n + j].conj();
1256            }
1257        }
1258    }
1259    let solved = if jacobi {
1260        Some(svd_jacobi(g, rows, cols))
1261    } else {
1262        let mut row_major = vec![T::ZERO; rows * cols];
1263        for c in 0..cols {
1264            for r in 0..rows {
1265                row_major[r * cols + c] = g[c * rows + r];
1266            }
1267        }
1268        bidiagonal::svd_bidiagonal(&row_major, rows, cols)
1269    };
1270    let Some((s, mut left, mut right)) = solved else {
1271        return (
1272            vec![T::LinalgReal::NAN; k],
1273            vec![T::NAN; m * ucols],
1274            vec![T::NAN; vrows * n],
1275        );
1276    };
1277    // Phases: the largest component of each left singular vector of A (the
1278    // columns of U) is real and positive; V follows for nonzero singular
1279    // values.
1280    let (u_full, v_full) = if tall {
1281        (&mut left, &mut right)
1282    } else {
1283        (&mut right, &mut left)
1284    };
1285    let (urows, vdim) = (m, n);
1286    for c in 0..urows {
1287        let factor = normalize_phase(u_full, urows, urows, c);
1288        if let Some(f) = factor
1289            && c < k
1290            && s[c] > T::LinalgReal::ZERO
1291        {
1292            for r in 0..vdim {
1293                v_full[r * vdim + c] = if T::IS_COMPLEX {
1294                    v_full[r * vdim + c] * f
1295                } else {
1296                    -v_full[r * vdim + c]
1297                };
1298            }
1299        }
1300    }
1301    for c in 0..vdim {
1302        let paired = s.get(c).is_some_and(|&sc| sc > T::LinalgReal::ZERO);
1303        if !paired {
1304            normalize_phase(v_full, vdim, vdim, c);
1305        }
1306    }
1307    let mut u = Vec::with_capacity(m * ucols);
1308    for r in 0..m {
1309        u.extend_from_slice(&u_full[r * m..r * m + ucols]);
1310    }
1311    let mut vt = Vec::with_capacity(vrows * n);
1312    for c in 0..vrows {
1313        for r in 0..n {
1314            vt.push(v_full[r * n + c].conj());
1315        }
1316    }
1317    (s, u, vt)
1318}
1319
1320/// The one-sided Jacobi SVD of `g` (`rows x cols`, `rows >= cols`, stored
1321/// by columns: `g[c * rows + r]`): the singular values in descending order,
1322/// the left singular vectors completed to an orthonormal basis (`rows x
1323/// rows`, row-major), and the right ones (`cols x cols`).
1324#[allow(clippy::type_complexity)] // the three factors
1325fn svd_jacobi<T: LinalgScalar>(
1326    mut g: Vec<T>,
1327    rows: usize,
1328    cols: usize,
1329) -> (Vec<T::LinalgReal>, Vec<T>, Vec<T>) {
1330    let mut w = vec![T::ZERO; cols * cols];
1331    for i in 0..cols {
1332        w[i * cols + i] = T::ONE;
1333    }
1334    // `g_i^H g_j`.
1335    let col_dot = |g: &[T], i: usize, j: usize| {
1336        let (gi, gj) = (&g[i * rows..(i + 1) * rows], &g[j * rows..(j + 1) * rows]);
1337        gi.iter()
1338            .zip(gj)
1339            .fold(T::ZERO, |s, (&x, &y)| s + x.conj() * y)
1340    };
1341    // Rotates the columns `i < j` of a matrix stored by columns of `len`.
1342    let rotate = |x: &mut [T], len: usize, i: usize, j: usize, c, s, phase: &dyn Fn(T) -> T| {
1343        let (head, tail) = x.split_at_mut(j * len);
1344        let (xi, xj) = (&mut head[i * len..(i + 1) * len], &mut tail[..len]);
1345        for (a, b) in xi.iter_mut().zip(xj.iter_mut()) {
1346            let (gi, gj) = (*a, phase(*b));
1347            *a = gi.scale(c) - gj.scale(s);
1348            *b = gi.scale(s) + gj.scale(c);
1349        }
1350    };
1351    let one = T::LinalgReal::ONE;
1352    let fro = norm2(g.iter().copied());
1353    let floor = fmax(
1354        T::LinalgReal::MIN_POSITIVE,
1355        fro * fro * T::LinalgReal::EPSILON * T::LinalgReal::EPSILON,
1356    );
1357    for _ in 0..MAX_SWEEPS {
1358        let mut rotated = false;
1359        for i in 0..cols {
1360            for j in i + 1..cols {
1361                let alpha = col_dot(&g, i, i).re();
1362                let beta = col_dot(&g, j, j).re();
1363                let gamma = col_dot(&g, i, j);
1364                let mag = gamma.abs();
1365                if mag <= floor || mag <= T::LinalgReal::EPSILON * (alpha * beta).sqrt() {
1366                    continue;
1367                }
1368                rotated = true;
1369                // For complex matrices, column j is first multiplied by the
1370                // phase that makes `g_i^H g_j` real.
1371                let (gamma, u) = rotation_phase(gamma);
1372                let phase = |x: T| u.map_or(x, |u| x * u);
1373                let zeta = (beta - alpha) / (gamma + gamma);
1374                let t = one.copysign(zeta) / (zeta.abs() + one.hypot(zeta));
1375                let c = one / one.hypot(t);
1376                let s = c * t;
1377                rotate(&mut g, rows, i, j, c, s, &phase);
1378                rotate(&mut w, cols, i, j, c, s, &phase);
1379            }
1380        }
1381        if !rotated {
1382            break;
1383        }
1384    }
1385    // Singular values are the norms of the columns, in descending order.
1386    let norms: Vec<T::LinalgReal> = (0..cols)
1387        .map(|c| norm2(g[c * rows..(c + 1) * rows].iter().copied()))
1388        .collect();
1389    let mut order: Vec<usize> = (0..cols).collect();
1390    order.sort_by(|&i, &j| {
1391        norms[j]
1392            .partial_cmp(&norms[i])
1393            .unwrap_or(std::cmp::Ordering::Equal)
1394    });
1395    let s: Vec<T::LinalgReal> = order.iter().map(|&i| norms[i]).collect();
1396    // `left` (`rows x rows`): the normalized columns, completed to an
1397    // orthonormal basis; `right` (`cols x cols`): the rotations.
1398    let mut left = vec![T::ZERO; rows * rows];
1399    let mut have = vec![false; rows];
1400    let mut right = vec![T::ZERO; cols * cols];
1401    for (c, &i) in order.iter().enumerate() {
1402        let norm = norms[i];
1403        if norm > T::LinalgReal::ZERO {
1404            let r = one / norm;
1405            for row in 0..rows {
1406                left[row * rows + c] = g[i * rows + row].scale(r);
1407            }
1408            have[c] = true;
1409        }
1410        for row in 0..cols {
1411            right[row * cols + c] = w[i * cols + row];
1412        }
1413    }
1414    complete_basis(&mut left, rows, &mut have);
1415    (s, left, right)
1416}
1417
1418/// Fills the columns of the `d x d` matrix `q` not marked in `have` so that
1419/// its columns are orthonormal, given that the marked ones are: each step
1420/// takes the standard basis vector with the largest component orthogonal to
1421/// the columns so far (orthogonalized twice).
1422fn complete_basis<T: LinalgScalar>(q: &mut [T], d: usize, have: &mut [bool]) {
1423    for c in 0..d {
1424        if have[c] {
1425            continue;
1426        }
1427        let mut best: Option<(T::LinalgReal, Vec<T>)> = None;
1428        for e in 0..d {
1429            let mut v = vec![T::ZERO; d];
1430            v[e] = T::ONE;
1431            for _ in 0..2 {
1432                for j in (0..d).filter(|&j| have[j]) {
1433                    let mut dot = T::ZERO;
1434                    for r in 0..d {
1435                        dot = dot + q[r * d + j].conj() * v[r];
1436                    }
1437                    for r in 0..d {
1438                        v[r] = v[r] - dot * q[r * d + j];
1439                    }
1440                }
1441            }
1442            let norm = norm2(v.iter().copied());
1443            if best.as_ref().is_none_or(|(b, _)| norm > *b) {
1444                best = Some((norm, v));
1445            }
1446        }
1447        let (norm, v) = best.expect("d > 0");
1448        let r = T::LinalgReal::ONE / norm;
1449        for row in 0..d {
1450            q[row * d + c] = v[row].scale(r);
1451        }
1452        have[c] = true;
1453    }
1454}
1455
1456#[cfg(test)]
1457mod tests {
1458    use super::*;
1459
1460    fn matmul(a: &[f64], b: &[f64], m: usize, k: usize, n: usize) -> Vec<f64> {
1461        let mut c = vec![0.0; m * n];
1462        for i in 0..m {
1463            for j in 0..n {
1464                c[i * n + j] = (0..k).map(|l| a[i * k + l] * b[l * n + j]).sum();
1465            }
1466        }
1467        c
1468    }
1469
1470    fn transpose(a: &[f64], m: usize, n: usize) -> Vec<f64> {
1471        let mut t = vec![0.0; m * n];
1472        for i in 0..m {
1473            for j in 0..n {
1474                t[j * m + i] = a[i * n + j];
1475            }
1476        }
1477        t
1478    }
1479
1480    fn assert_close(a: &[f64], b: &[f64], tol: f64) {
1481        assert_eq!(a.len(), b.len());
1482        for (i, (x, y)) in a.iter().zip(b).enumerate() {
1483            assert!(
1484                (x - y).abs() <= tol,
1485                "element {i}: {x} vs {y}\n{a:?}\n{b:?}"
1486            );
1487        }
1488    }
1489
1490    /// A deterministic pseudo-random matrix.
1491    fn matrix(m: usize, n: usize, seed: u64) -> Vec<f64> {
1492        let mut s = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
1493        (0..m * n)
1494            .map(|_| {
1495                s = s
1496                    .wrapping_mul(6364136223846793005)
1497                    .wrapping_add(1442695040888963407);
1498                ((s >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0
1499            })
1500            .collect()
1501    }
1502
1503    fn eye(n: usize) -> Vec<f64> {
1504        let mut e = vec![0.0; n * n];
1505        for i in 0..n {
1506            e[i * n + i] = 1.0;
1507        }
1508        e
1509    }
1510
1511    #[test]
1512    fn cholesky_of_a_textbook_matrix() {
1513        let a = [4.0, 12.0, -16.0, 12.0, 37.0, -43.0, -16.0, -43.0, 98.0];
1514        let l = cholesky(&a, 1, 3);
1515        // The upper triangle of the input is kept.
1516        assert_eq!(l, [2.0, 12.0, -16.0, 6.0, 1.0, -43.0, -8.0, 5.0, 3.0]);
1517        let bad = cholesky(&[1.0, 2.0, 2.0, 1.0], 1, 2);
1518        assert!(bad.iter().all(|v| v.is_nan()));
1519        assert!(cholesky::<f32>(&[], 0, 3).is_empty());
1520    }
1521
1522    #[test]
1523    fn triangular_solves_invert_products() {
1524        let n = 4;
1525        let a = matrix(n, n, 1);
1526        let b = matrix(n, 3, 2);
1527        let bt = matrix(3, n, 3);
1528        for lower in [false, true] {
1529            for transpose_a in [false, true] {
1530                for unit_diagonal in [false, true] {
1531                    // The triangular matrix the solve uses.
1532                    let mut t = vec![0.0; n * n];
1533                    for i in 0..n {
1534                        for j in 0..n {
1535                            let keep = if lower { j <= i } else { j >= i };
1536                            if keep {
1537                                t[i * n + j] = if i == j {
1538                                    if unit_diagonal {
1539                                        1.0
1540                                    } else {
1541                                        a[i * n + j] + 3.0
1542                                    }
1543                                } else {
1544                                    a[i * n + j]
1545                                };
1546                            }
1547                        }
1548                    }
1549                    let mut stored = a.clone();
1550                    for i in 0..n {
1551                        stored[i * n + i] = if unit_diagonal {
1552                            f64::NAN
1553                        } else {
1554                            a[i * n + i] + 3.0
1555                        };
1556                    }
1557                    let op = if transpose_a {
1558                        transpose(&t, n, n)
1559                    } else {
1560                        t.clone()
1561                    };
1562                    let options = TriangularSolveOptions {
1563                        left_side: true,
1564                        lower,
1565                        transpose_a,
1566                        conjugate_a: false,
1567                        unit_diagonal,
1568                    };
1569                    let x = triangular_solve(&stored, &b, 1, n, 3, options);
1570                    assert_close(&matmul(&op, &x, n, n, 3), &b, 1e-12);
1571                    let options = TriangularSolveOptions {
1572                        left_side: false,
1573                        ..options
1574                    };
1575                    let x = triangular_solve(&stored, &bt, 1, 3, n, options);
1576                    assert_close(&matmul(&x, &op, 3, n, n), &bt, 1e-12);
1577                }
1578            }
1579        }
1580    }
1581
1582    #[test]
1583    fn lu_pivots_by_the_largest_magnitude() {
1584        let a = [1.0, 2.0, -4.0, 3.0, 4.0, 1.0];
1585        // 3 x 2: the first column's largest magnitude is -4 (row 1).
1586        let (lu_, piv, perm) = lu(&a, 1, 3, 2);
1587        assert_eq!(piv, [1, 2]);
1588        assert_eq!(perm, [1, 2, 0]);
1589        // Rebuild P A = L U.
1590        let l = [1.0, 0.0, lu_[2], 1.0, lu_[4], lu_[5]];
1591        let u = [lu_[0], lu_[1], 0.0, lu_[3]];
1592        let pa: Vec<f64> = perm
1593            .iter()
1594            .flat_map(|&r| a[r as usize * 2..r as usize * 2 + 2].to_vec())
1595            .collect();
1596        assert_close(&matmul(&l, &u, 3, 2, 2), &pa, 1e-12);
1597        // Ties pick the first row; a zero column is not swapped.
1598        let (_, piv, _) = lu(&[0.0, 1.0, 0.0, 2.0], 1, 2, 2);
1599        assert_eq!(piv, [0, 1]);
1600        let (_, piv, _) = lu(&[-2.0, 1.0, 2.0, 1.0], 1, 2, 2);
1601        assert_eq!(piv, [0, 1]);
1602        assert_eq!(lu_pivots_to_permutation(&[2, 2, 2], 1, 3, 4), [2, 0, 1, 3]);
1603    }
1604
1605    #[test]
1606    fn qr_follows_lapack_signs() {
1607        for (m, n) in [(4, 3), (3, 4), (3, 3), (1, 1), (5, 2)] {
1608            let a = matrix(m, n, (m * 10 + n) as u64);
1609            for full in [false, true] {
1610                let (q, r) = qr(&a, 1, m, n, full);
1611                let kq = if full { m } else { m.min(n) };
1612                assert_close(&matmul(&q, &r, m, kq, n), &a, 1e-12);
1613                let qtq = matmul(&transpose(&q, m, kq), &q, kq, m, kq);
1614                assert_close(&qtq, &eye(kq), 1e-12);
1615                for i in 0..kq {
1616                    for j in 0..i.min(n) {
1617                        assert_eq!(r[i * n + j], 0.0);
1618                    }
1619                }
1620            }
1621        }
1622        // larfg's convention: beta = -sign(alpha) * norm.
1623        let (q, r) = qr(&[3.0, 4.0], 1, 2, 1, false);
1624        assert_close(&r, &[-5.0], 1e-15);
1625        assert_close(&q, &[-0.6, -0.8], 1e-15);
1626        // Empty matrices give identity Qs.
1627        let (q, r) = qr::<f64>(&[], 2, 2, 0, true);
1628        assert_eq!(q, [1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0]);
1629        assert!(r.is_empty());
1630    }
1631
1632    #[test]
1633    fn eigh_diagonalizes() {
1634        let n = 5;
1635        let b = matrix(n, n, 7);
1636        let a = matmul(&b, &transpose(&b, n, n), n, n, n);
1637        for (lower, jacobi) in [(true, false), (false, false), (true, true), (false, true)] {
1638            // Garbage in the unused triangle.
1639            let mut stored = a.clone();
1640            for i in 0..n {
1641                for j in 0..n {
1642                    if (lower && j > i) || (!lower && j < i) {
1643                        stored[i * n + j] = 1e3;
1644                    }
1645                }
1646            }
1647            let (v, w) = eigh(&stored, 1, n, lower, jacobi);
1648            assert!(w.windows(2).all(|p| p[0] <= p[1]));
1649            let mut vw = v.clone();
1650            for r in 0..n {
1651                for c in 0..n {
1652                    vw[r * n + c] *= w[c];
1653                }
1654            }
1655            assert_close(&matmul(&vw, &transpose(&v, n, n), n, n, n), &a, 1e-12);
1656            assert_close(&matmul(&transpose(&v, n, n), &v, n, n, n), &eye(n), 1e-12);
1657        }
1658        let (v, w) = eigh(&[f64::NAN, 0.0, 0.0, 1.0], 1, 2, true, false);
1659        assert!(v.iter().chain(&w).all(|x| x.is_nan()));
1660    }
1661
1662    #[test]
1663    fn svd_reconstructs() {
1664        for (m, n) in [(4, 3), (3, 4), (3, 3), (5, 1), (1, 4), (2, 0), (0, 3)] {
1665            let mut a = matrix(m, n, (m * 7 + n) as u64);
1666            if m == 4 && n == 3 {
1667                // Rank deficient: the last column repeats the first.
1668                for i in 0..m {
1669                    a[i * n + 2] = a[i * n];
1670                }
1671            }
1672            let k = m.min(n);
1673            for (full, jacobi) in [(false, false), (true, false), (false, true), (true, true)] {
1674                let (s, u, vt) = svd(&a, 1, m, n, full, true, jacobi);
1675                assert!(s.windows(2).all(|p| p[0] >= p[1]));
1676                let (uc, vr) = if full { (m, n) } else { (k, k) };
1677                let mut us = vec![0.0; m * vr];
1678                for i in 0..m {
1679                    for j in 0..k {
1680                        us[i * vr + j] = u[i * uc + j] * s[j];
1681                    }
1682                }
1683                assert_close(&matmul(&us, &vt, m, vr, n), &a, 1e-12);
1684                assert_close(
1685                    &matmul(&transpose(&u, m, uc), &u, uc, m, uc),
1686                    &eye(uc),
1687                    1e-12,
1688                );
1689                assert_close(
1690                    &matmul(&vt, &transpose(&vt, vr, n), vr, n, vr),
1691                    &eye(vr),
1692                    1e-12,
1693                );
1694                let (s2, u2, vt2) = svd(&a, 1, m, n, full, false, jacobi);
1695                assert_eq!(s2, s);
1696                assert!(u2.is_empty() && vt2.is_empty());
1697            }
1698        }
1699    }
1700
1701    type Z = Complex<f64>;
1702
1703    fn z(re: f64, im: f64) -> Z {
1704        Complex::new(re, im)
1705    }
1706
1707    fn cmatrix(m: usize, n: usize, seed: u64) -> Vec<Z> {
1708        let re = matrix(m, n, seed);
1709        let im = matrix(m, n, seed + 1000);
1710        re.into_iter().zip(im).map(|(a, b)| z(a, b)).collect()
1711    }
1712
1713    fn cmatmul(a: &[Z], b: &[Z], m: usize, k: usize, n: usize) -> Vec<Z> {
1714        let mut c = vec![Z::ZERO; m * n];
1715        for i in 0..m {
1716            for j in 0..n {
1717                let mut s = Z::ZERO;
1718                for l in 0..k {
1719                    s = s + a[i * k + l] * b[l * n + j];
1720                }
1721                c[i * n + j] = s;
1722            }
1723        }
1724        c
1725    }
1726
1727    /// The conjugate transpose.
1728    fn adjoint(a: &[Z], m: usize, n: usize) -> Vec<Z> {
1729        let mut t = vec![Z::ZERO; m * n];
1730        for i in 0..m {
1731            for j in 0..n {
1732                t[j * m + i] = a[i * n + j].conj();
1733            }
1734        }
1735        t
1736    }
1737
1738    fn ceye(n: usize) -> Vec<Z> {
1739        let mut e = vec![Z::ZERO; n * n];
1740        for i in 0..n {
1741            e[i * n + i] = Z::ONE;
1742        }
1743        e
1744    }
1745
1746    fn assert_cclose(a: &[Z], b: &[Z], tol: f64) {
1747        assert_eq!(a.len(), b.len());
1748        for (i, (x, y)) in a.iter().zip(b).enumerate() {
1749            assert!((*x - *y).abs() <= tol, "element {i}: {x:?} vs {y:?}");
1750        }
1751    }
1752
1753    /// A Hermitian positive definite matrix `B B^H + n I`.
1754    fn hpd(n: usize, seed: u64) -> Vec<Z> {
1755        let b = cmatrix(n, n, seed);
1756        let mut a = cmatmul(&b, &adjoint(&b, n, n), n, n, n);
1757        for i in 0..n {
1758            a[i * n + i] = a[i * n + i] + z(n as f64, 0.0);
1759        }
1760        a
1761    }
1762
1763    #[test]
1764    fn complex_cholesky_reconstructs() {
1765        let n = 4;
1766        let a = hpd(n, 1);
1767        let l = cholesky(&a, 1, n);
1768        let mut lower = vec![Z::ZERO; n * n];
1769        for i in 0..n {
1770            assert_eq!(l[i * n + i].im, 0.0);
1771            for j in 0..=i {
1772                lower[i * n + j] = l[i * n + j];
1773            }
1774            for j in i + 1..n {
1775                assert_eq!(l[i * n + j], a[i * n + j], "the upper triangle is kept");
1776            }
1777        }
1778        assert_cclose(&cmatmul(&lower, &adjoint(&lower, n, n), n, n, n), &a, 1e-12);
1779    }
1780
1781    #[test]
1782    fn complex_triangular_solves_conjugate() {
1783        let n = 3;
1784        let mut a = cmatrix(n, n, 5);
1785        for i in 0..n {
1786            a[i * n + i] = a[i * n + i] + z(3.0, 0.0);
1787        }
1788        let b = cmatrix(n, 2, 6);
1789        for transpose_a in [false, true] {
1790            for conjugate_a in [false, true] {
1791                let mut t = vec![Z::ZERO; n * n];
1792                for i in 0..n {
1793                    for j in 0..=i {
1794                        t[i * n + j] = a[i * n + j];
1795                    }
1796                }
1797                let mut op = if transpose_a {
1798                    adjoint(&adjoint(&adjoint(&t, n, n), n, n), n, n)
1799                        .iter()
1800                        .map(|v| v.conj())
1801                        .collect()
1802                } else {
1803                    t.clone()
1804                };
1805                if conjugate_a {
1806                    op = op.iter().map(|v| v.conj()).collect();
1807                }
1808                let options = TriangularSolveOptions {
1809                    left_side: true,
1810                    lower: true,
1811                    transpose_a,
1812                    conjugate_a,
1813                    unit_diagonal: false,
1814                };
1815                let x = triangular_solve(&a, &b, 1, n, 2, options);
1816                assert_cclose(&cmatmul(&op, &x, n, n, 2), &b, 1e-12);
1817            }
1818        }
1819    }
1820
1821    #[test]
1822    fn complex_lu_pivots_by_abs1() {
1823        // `izamax` compares |re| + |im|: 2.9 + 2.9i (5.8, modulus 4.1) is
1824        // chosen over 4.5 (4.5, modulus 4.5).
1825        let a = [z(4.5, 0.0), z(1.0, 0.0), z(2.9, 2.9), z(1.0, 1.0)];
1826        let (_, piv, _) = lu(&a, 1, 2, 2);
1827        assert_eq!(piv, [1, 1]);
1828        let (m, n) = (4, 3);
1829        let a = cmatrix(m, n, 9);
1830        let (f, _, perm) = lu(&a, 1, m, n);
1831        let mut l = vec![Z::ZERO; m * n];
1832        let mut u = vec![Z::ZERO; n * n];
1833        for i in 0..m {
1834            for j in 0..n {
1835                if j < i {
1836                    l[i * n + j] = f[i * n + j];
1837                } else {
1838                    if i == j {
1839                        l[i * n + j] = Z::ONE;
1840                    }
1841                    if i < n {
1842                        u[i * n + j] = f[i * n + j];
1843                    }
1844                }
1845            }
1846        }
1847        let pa: Vec<Z> = perm
1848            .iter()
1849            .flat_map(|&r| a[r as usize * n..(r as usize + 1) * n].to_vec())
1850            .collect();
1851        assert_cclose(&cmatmul(&l, &u, m, n, n), &pa, 1e-12);
1852    }
1853
1854    #[test]
1855    fn complex_qr_is_unitary() {
1856        for (m, n) in [(4, 3), (3, 4), (3, 3)] {
1857            let a = cmatrix(m, n, (m * 10 + n) as u64);
1858            for full in [false, true] {
1859                let (q, r) = qr(&a, 1, m, n, full);
1860                let kq = if full { m } else { m.min(n) };
1861                assert_cclose(&cmatmul(&q, &r, m, kq, n), &a, 1e-12);
1862                assert_cclose(
1863                    &cmatmul(&adjoint(&q, m, kq), &q, kq, m, kq),
1864                    &ceye(kq),
1865                    1e-12,
1866                );
1867                for i in 0..kq.min(n) {
1868                    // zlarfg's beta is real.
1869                    assert_eq!(r[i * n + i].im, 0.0);
1870                }
1871            }
1872        }
1873    }
1874
1875    #[test]
1876    fn complex_eigh_diagonalizes() {
1877        let n = 4;
1878        let a = hpd(n, 3);
1879        for (lower, jacobi) in [(true, false), (false, false), (true, true), (false, true)] {
1880            let (v, w) = eigh(&a, 1, n, lower, jacobi);
1881            assert!(w.windows(2).all(|p| p[0] <= p[1]));
1882            let mut vw = v.clone();
1883            for r in 0..n {
1884                for c in 0..n {
1885                    vw[r * n + c] = vw[r * n + c].scale(w[c]);
1886                }
1887            }
1888            assert_cclose(&cmatmul(&vw, &adjoint(&v, n, n), n, n, n), &a, 1e-10);
1889            assert_cclose(&cmatmul(&adjoint(&v, n, n), &v, n, n, n), &ceye(n), 1e-12);
1890            // The largest component of each eigenvector is real and positive.
1891            for c in 0..n {
1892                let best = (0..n)
1893                    .max_by(|&i, &j| v[i * n + c].abs().total_cmp(&v[j * n + c].abs()))
1894                    .unwrap();
1895                assert_eq!(v[best * n + c].im, 0.0);
1896                assert!(v[best * n + c].re > 0.0);
1897            }
1898        }
1899    }
1900
1901    #[test]
1902    fn complex_svd_reconstructs() {
1903        for (m, n) in [(4, 3), (3, 4), (3, 3)] {
1904            let a = cmatrix(m, n, (m * 7 + n) as u64);
1905            let k = m.min(n);
1906            for (full, jacobi) in [(false, false), (true, false), (false, true), (true, true)] {
1907                let (s, u, vt) = svd(&a, 1, m, n, full, true, jacobi);
1908                assert!(s.windows(2).all(|p| p[0] >= p[1]));
1909                let (uc, vr) = if full { (m, n) } else { (k, k) };
1910                let mut us = vec![Z::ZERO; m * vr];
1911                for i in 0..m {
1912                    for j in 0..k {
1913                        us[i * vr + j] = u[i * uc + j].scale(s[j]);
1914                    }
1915                }
1916                assert_cclose(&cmatmul(&us, &vt, m, vr, n), &a, 1e-12);
1917                assert_cclose(
1918                    &cmatmul(&adjoint(&u, m, uc), &u, uc, m, uc),
1919                    &ceye(uc),
1920                    1e-12,
1921                );
1922                assert_cclose(
1923                    &cmatmul(&vt, &adjoint(&vt, vr, n), vr, n, vr),
1924                    &ceye(vr),
1925                    1e-12,
1926                );
1927            }
1928        }
1929    }
1930
1931    #[test]
1932    fn qr_pivoting_moves_large_columns_forward() {
1933        // The third column has the largest norm, then the first.
1934        let a = [1.0, 0.0, 5.0, 2.0, 0.1, 0.0, 0.0, 0.0, 1.0];
1935        let (q, r, p) = qr_pivoting(&a, 1, 3, 3, false);
1936        assert_eq!(p, [2, 0, 1]);
1937        let mut ap = vec![0.0; 9];
1938        for i in 0..3 {
1939            for j in 0..3 {
1940                ap[i * 3 + j] = a[i * 3 + p[j] as usize];
1941            }
1942        }
1943        assert_close(&matmul(&q, &r, 3, 3, 3), &ap, 1e-12);
1944        // |diag(R)| does not increase.
1945        assert!(r[0].abs() >= r[4].abs() && r[4].abs() >= r[8].abs());
1946        for (m, n) in [(4, 3), (3, 5), (5, 5)] {
1947            let mut a = matrix(m, n, (m * 13 + n) as u64);
1948            // A repeated column: rank deficient.
1949            for i in 0..m {
1950                a[i * n + n - 1] = a[i * n];
1951            }
1952            for full in [false, true] {
1953                let (q, r, p) = qr_pivoting(&a, 1, m, n, full);
1954                let kq = if full { m } else { m.min(n) };
1955                let mut ap = vec![0.0; m * n];
1956                for i in 0..m {
1957                    for j in 0..n {
1958                        ap[i * n + j] = a[i * n + p[j] as usize];
1959                    }
1960                }
1961                assert_close(&matmul(&q, &r, m, kq, n), &ap, 1e-12);
1962                let mut sorted = p.clone();
1963                sorted.sort_unstable();
1964                assert_eq!(sorted, (0..n as i32).collect::<Vec<_>>());
1965            }
1966        }
1967        let (_, _, p) = qr_pivoting::<f64>(&[], 2, 0, 3, true);
1968        assert_eq!(p, [0; 6]);
1969    }
1970
1971    #[test]
1972    fn complex_qr_pivoting_reconstructs() {
1973        let (m, n) = (4, 3);
1974        let a = cmatrix(m, n, 21);
1975        let (q, r, p) = qr_pivoting(&a, 1, m, n, false);
1976        let mut ap = vec![Z::ZERO; m * n];
1977        for i in 0..m {
1978            for j in 0..n {
1979                ap[i * n + j] = a[i * n + p[j] as usize];
1980            }
1981        }
1982        assert_cclose(&cmatmul(&q, &r, m, n, n), &ap, 1e-12);
1983        assert_cclose(&cmatmul(&adjoint(&q, m, n), &q, n, m, n), &ceye(n), 1e-12);
1984    }
1985
1986    #[test]
1987    fn householder_product_and_ormqr_agree_with_qr() {
1988        let (m, n) = (5, 3);
1989        let a = matrix(m, n, 44);
1990        let mut r = a.clone();
1991        let taus = geqrf_one(&mut r, m, n);
1992        let q = householder_product(&r, &taus, 1, m, n, n);
1993        let (q_ref, _) = qr(&a, 1, m, n, false);
1994        assert_close(&q, &q_ref, 1e-14);
1995        // `Q^T Q c = c`, and `(Q c)^T = c^T Q^T` from the right.
1996        let c = matrix(m, 2, 45);
1997        let qc = ormqr(&r, &taus, &c, 1, (m, n, n), (m, 2), true, false);
1998        let back = ormqr(&r, &taus, &qc, 1, (m, n, n), (m, 2), true, true);
1999        assert_close(&back, &c, 1e-12);
2000        let ct = transpose(&c, m, 2);
2001        let cq = ormqr(&r, &taus, &ct, 1, (m, n, n), (2, m), false, true);
2002        assert_close(&transpose(&cq, 2, m), &qc, 1e-12);
2003    }
2004}