Skip to main content

caroli_dense/
lib.rs

1//! Dense complex kernels for caroli: the Schur decomposition, its reordering, LU solves, QR and
2//! SVD, and matrix products. They dominate the lead modes and the nested-dissection fronts.
3//!
4//! On macOS, with the `accelerate` feature (on by default), they can call Apple's Accelerate
5//! framework (LAPACK and BLAS, which run on the matrix units of Apple silicon); elsewhere, or
6//! with the feature off, they use faer and an in-house QR algorithm. The reordering is in-house
7//! everywhere: adjacent swaps (LAPACK ztrexc) made in small windows, whose rotations reach the
8//! rest of the matrix as products.
9//!
10//! [`set_backend`] chooses the library at run time (see [`Backend`]); the environment variable
11//! `CAROLI_DENSE_BACKEND` (`accelerate`, `faer`) sets the initial choice.
12
13// The calls into Accelerate's LAPACK and BLAS (C functions) are the crate's only unsafe code,
14// every block with its `SAFETY` reason.
15#[cfg(all(target_os = "macos", feature = "accelerate"))]
16#[allow(unsafe_code)]
17mod accelerate;
18mod field;
19mod schur;
20
21pub use faer::{Accum, Mat, MatMut, MatRef, c32, c64};
22pub use field::Field;
23pub use schur::{partition, reorder};
24use std::sync::atomic::{AtomicUsize, Ordering};
25
26/// Errors of the dense kernels.
27#[derive(Debug, thiserror::Error)]
28pub enum DenseError {
29    /// [`schur()`] or [`schur_of_real`]: the QR iterations did not converge, or an entry of the
30    /// matrix is not finite.
31    #[error("the Schur decomposition did not converge")]
32    Schur,
33    /// [`svd`] or [`svd_of_real`]: the decomposition did not converge.
34    #[error("the singular value decomposition did not converge")]
35    Svd,
36    /// [`hermitian_eigen`]: the eigensolver did not converge.
37    #[error("the Hermitian eigensolver did not converge")]
38    Eigen,
39}
40
41/// Libraries this build can use: `"accelerate"` (with faer) on macOS with the feature, else
42/// `"faer"`.
43pub const BACKEND: &str =
44    if cfg!(all(target_os = "macos", feature = "accelerate")) { "accelerate" } else { "faer" };
45
46/// Which library runs the dense kernels. Without Accelerate in the build, both choices run faer.
47///
48/// Accelerate is the default: its kernels run on the matrix units of Apple silicon, several
49/// times faster than faer's on the vector units, and it stays ahead on every core at once
50/// (`benchmarks/README.md`, multi-core throughput).
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum Backend {
53    /// Accelerate for every call.
54    Accelerate,
55    /// faer (and the in-house Schur decomposition) for every call.
56    Faer,
57}
58
59/// `0`: not set yet; `1`: Accelerate; `2`: faer.
60static POLICY: AtomicUsize = AtomicUsize::new(0);
61
62fn encode(b: Backend) -> usize {
63    match b {
64        Backend::Accelerate => 1,
65        Backend::Faer => 2,
66    }
67}
68
69/// Chooses the library of the dense kernels for the whole process.
70pub fn set_backend(b: Backend) {
71    POLICY.store(encode(b), Ordering::Relaxed);
72}
73
74/// The current choice (from `CAROLI_DENSE_BACKEND` at the first call, Accelerate by default).
75pub fn backend() -> Backend {
76    let mut code = POLICY.load(Ordering::Relaxed);
77    if code == 0 {
78        let chosen = std::env::var("CAROLI_DENSE_BACKEND").ok().and_then(|v| match v.as_str() {
79            "accelerate" => Some(Backend::Accelerate),
80            "faer" => Some(Backend::Faer),
81            _ => None,
82        });
83        code = encode(chosen.unwrap_or(Backend::Accelerate));
84        // Keep a choice made meanwhile by set_backend.
85        code = match POLICY.compare_exchange(0, code, Ordering::Relaxed, Ordering::Relaxed) {
86            Ok(_) => code,
87            Err(current) => current,
88        };
89    }
90    if code == 2 { Backend::Faer } else { Backend::Accelerate }
91}
92
93/// Whether Accelerate runs the next call.
94#[cfg_attr(not(all(target_os = "macos", feature = "accelerate")), allow(dead_code))]
95fn use_accelerate() -> bool {
96    cfg!(all(target_os = "macos", feature = "accelerate")) && backend() == Backend::Accelerate
97}
98
99/// Complex Schur decomposition `a = q t q†`: `q` unitary, `t` upper triangular with exact zeros
100/// below the diagonal. Returns `(q, t)`.
101pub fn schur(a: MatRef<'_, c64>) -> Result<(Mat<c64>, Mat<c64>), DenseError> {
102    assert_eq!(a.nrows(), a.ncols(), "schur: square matrix expected");
103    #[cfg(all(target_os = "macos", feature = "accelerate"))]
104    if use_accelerate() {
105        return accelerate::schur(a);
106    }
107    schur::schur(a)
108}
109
110/// Complex Schur decomposition `a = q t q†` of a real matrix (given with zero imaginary parts):
111/// the real Schur form (a quarter of the arithmetic of the complex one), whose 2 × 2 blocks of
112/// complex pairs are then split by complex rotations (`rsf2csf`). Same output as [`schur`].
113pub fn schur_of_real(a: MatRef<'_, c64>) -> Result<(Mat<c64>, Mat<c64>), DenseError> {
114    let n = a.nrows();
115    assert_eq!(n, a.ncols(), "schur_of_real: square matrix expected");
116    #[cfg(all(target_os = "macos", feature = "accelerate"))]
117    if use_accelerate() {
118        let mut t: Vec<f64> = (0..n * n).map(|k| a[(k % n, k / n)].re).collect();
119        if !t.iter().all(|x| x.is_finite()) {
120            return Err(DenseError::Schur);
121        }
122        let mut q = vec![0.0; n * n];
123        accelerate::real_schur(&mut t, &mut q, n)?;
124        let mut tc = Mat::<c64>::from_fn(n, n, |i, j| c64::new(t[i + j * n], 0.0));
125        let mut qc = Mat::<c64>::from_fn(n, n, |i, j| c64::new(q[i + j * n], 0.0));
126        split_pairs(&mut tc, &mut qc);
127        return Ok((qc, tc));
128    }
129    schur(a)
130}
131
132/// Turns a real quasi-triangular Schur form into a complex triangular one (as MATLAB's
133/// `rsf2csf`): each 2 × 2 block of a complex pair is triangularised by a complex rotation applied
134/// to its two rows, its two columns and the Schur vectors.
135#[cfg_attr(not(all(target_os = "macos", feature = "accelerate")), allow(dead_code))]
136fn split_pairs(t: &mut Mat<c64>, q: &mut Mat<c64>) {
137    let n = t.nrows();
138    let zero = c64::new(0.0, 0.0);
139    for m in (1..n).rev() {
140        let sub = t[(m, m - 1)];
141        if sub == zero {
142            continue;
143        }
144        // An eigenvalue of the block [[a, b], [c, d]], relative to d. The block is first scaled
145        // by a power of two (exactly): the blocks of clusters of tiny eigenvalues (such as the
146        // zero eigenvalues of a low-rank matrix) would otherwise underflow in the squares, and the
147        // rotation would not be unitary.
148        let (a, b, c, d) = (t[(m - 1, m - 1)], t[(m - 1, m)], sub, t[(m, m)]);
149        let big = [a, b, c, d].iter().fold(0.0f64, |x, z| x.max(z.re.abs()).max(z.im.abs()));
150        let scale = 2f64.powi(-(big.log2().floor() as i32).clamp(-1000, 1000));
151        let (a, b, c, d) = (a * scale, b * scale, c * scale, d * scale);
152        let half = (a - d) * 0.5;
153        let mu = half + (half * half + b * c).sqrt(); // eigenvalue − d
154        let r = mu.norm().hypot(c.norm());
155        if r == 0.0 {
156            continue;
157        }
158        let (cs, sn) = (mu / r, c / r);
159        // G = [[cs*, sn*], [−sn, cs]] on rows m−1, m (columns m−1..n), G† on columns m−1, m.
160        for j in m - 1..n {
161            let (x, y) = (t[(m - 1, j)], t[(m, j)]);
162            t[(m - 1, j)] = cs.conj() * x + sn.conj() * y;
163            t[(m, j)] = -sn * x + cs * y;
164        }
165        for i in 0..=m {
166            let (x, y) = (t[(i, m - 1)], t[(i, m)]);
167            t[(i, m - 1)] = x * cs + y * sn;
168            t[(i, m)] = -x * sn.conj() + y * cs.conj();
169        }
170        for i in 0..n {
171            let (x, y) = (q[(i, m - 1)], q[(i, m)]);
172            q[(i, m - 1)] = x * cs + y * sn;
173            q[(i, m)] = -x * sn.conj() + y * cs.conj();
174        }
175        t[(m, m - 1)] = zero;
176    }
177}
178
179/// LU factorisation with partial pivoting of a square matrix.
180#[derive(Clone, Debug)]
181pub struct Lu {
182    inner: LuInner,
183}
184
185#[derive(Clone, Debug)]
186enum LuInner {
187    #[cfg(all(target_os = "macos", feature = "accelerate"))]
188    Accelerate(accelerate::Lu),
189    Faer(faer::linalg::solvers::PartialPivLu<c64>),
190}
191
192impl Lu {
193    /// LU factorisation of the square matrix `a` (panics otherwise). A singular matrix is
194    /// factorised all the same: its zero pivots show in [`Self::pivot_range`].
195    pub fn new(a: MatRef<'_, c64>) -> Self {
196        assert_eq!(a.nrows(), a.ncols(), "lu: square matrix expected");
197        #[cfg(all(target_os = "macos", feature = "accelerate"))]
198        if use_accelerate() {
199            return Self { inner: LuInner::Accelerate(accelerate::Lu::new(a)) };
200        }
201        Self { inner: LuInner::Faer(a.partial_piv_lu()) }
202    }
203
204    /// Smallest and largest modulus of the pivots (the diagonal of `U`); `(∞, 0)` for an empty
205    /// matrix.
206    pub fn pivot_range(&self) -> (f64, f64) {
207        let diagonal: Vec<c64> = match &self.inner {
208            #[cfg(all(target_os = "macos", feature = "accelerate"))]
209            LuInner::Accelerate(lu) => lu.diagonal().collect(),
210            LuInner::Faer(lu) => {
211                let u = lu.U();
212                (0..u.nrows()).map(|i| u[(i, i)]).collect()
213            }
214        };
215        diagonal.iter().fold((f64::INFINITY, 0.0f64), |(lo, hi), d| (lo.min(d.norm()), hi.max(d.norm())))
216    }
217
218    /// `b ← a⁻¹ b`.
219    pub fn solve_in_place(&self, b: MatMut<'_, c64>) {
220        self.solve_with(b, false);
221    }
222
223    /// `b ← a⁻† b`.
224    pub fn solve_adjoint_in_place(&self, b: MatMut<'_, c64>) {
225        self.solve_with(b, true);
226    }
227
228    fn solve_with(&self, b: MatMut<'_, c64>, adjoint: bool) {
229        match &self.inner {
230            #[cfg(all(target_os = "macos", feature = "accelerate"))]
231            LuInner::Accelerate(lu) => {
232                if let Err(mut b) = lu.solve_in_place(b, adjoint) {
233                    // A stride LAPACK cannot take: solve a column-major copy.
234                    let mut copy = b.to_owned();
235                    let _ = lu.solve_in_place(copy.as_mut(), adjoint);
236                    b.copy_from(&copy);
237                }
238            }
239            LuInner::Faer(lu) => {
240                use faer::linalg::solvers::SolveCore;
241                if adjoint {
242                    lu.solve_transpose_in_place_with_conj(faer::Conj::Yes, b);
243                } else {
244                    lu.solve_in_place_with_conj(faer::Conj::No, b);
245                }
246            }
247        }
248    }
249
250    /// Estimate of the reciprocal condition number `1 / (‖a‖₁ ‖a⁻¹‖₁)`, given `‖a‖₁`: 0 for a
251    /// singular matrix. As LAPACK zgecon, `‖a⁻¹‖₁` comes from a few solves with `a` and `a†`
252    /// (Hager's method with Higham's refinements, zlacn2). The 2-norm ratio `σ_min / σ_max` is
253    /// within a factor n of it.
254    pub fn inverse_condition_1(&self, norm_1: f64) -> f64 {
255        let n = self.pivots_len();
256        if n == 0 {
257            return 1.0;
258        }
259        let (lo, _) = self.pivot_range();
260        let invertible = lo > 0.0 && norm_1 > 0.0; // false for NaN
261        if !invertible {
262            return 0.0;
263        }
264        let estimate = self.inverse_norm_1();
265        if estimate.is_finite() && estimate > 0.0 { 1.0 / (norm_1 * estimate) } else { 0.0 }
266    }
267
268    fn pivots_len(&self) -> usize {
269        match &self.inner {
270            #[cfg(all(target_os = "macos", feature = "accelerate"))]
271            LuInner::Accelerate(lu) => lu.diagonal().count(),
272            LuInner::Faer(lu) => lu.U().nrows(),
273        }
274    }
275    /// Lower estimate of `‖a⁻¹‖₁` (LAPACK zlacn2, at most 5 iterations).
276    fn inverse_norm_1(&self) -> f64 {
277        let n = self.pivots_len();
278        let one = c64::new(1.0, 0.0);
279        let apply = |x: Mat<c64>, adjoint: bool| {
280            let mut y = x;
281            self.solve_with(y.as_mut(), adjoint);
282            y
283        };
284        let norm = |y: &Mat<c64>| (0..n).map(|i| y[(i, 0)].norm()).sum::<f64>();
285        let sign = |y: &Mat<c64>| {
286            Mat::from_fn(n, 1, |i, _| {
287                let a = y[(i, 0)].norm();
288                if a > f64::MIN_POSITIVE { y[(i, 0)] / a } else { one }
289            })
290        };
291        let argmax =
292            |z: &Mat<c64>| (0..n).max_by(|&a, &b| z[(a, 0)].norm().total_cmp(&z[(b, 0)].norm())).unwrap_or(0);
293        let y = apply(Mat::from_fn(n, 1, |_, _| c64::new(1.0 / n as f64, 0.0)), false);
294        if n == 1 {
295            return y[(0, 0)].norm();
296        }
297        let mut estimate = norm(&y);
298        let z = apply(sign(&y), true);
299        let mut j = argmax(&z);
300        for _ in 2..=5 {
301            let y = apply(Mat::from_fn(n, 1, |i, _| if i == j { one } else { c64::new(0.0, 0.0) }), false);
302            let previous = estimate;
303            estimate = estimate.max(norm(&y));
304            if estimate <= previous {
305                break;
306            }
307            let z = apply(sign(&y), true);
308            let last = j;
309            j = argmax(&z);
310            if z[(last, 0)].norm() == z[(j, 0)].norm() {
311                break;
312            }
313        }
314        // Alternative estimate from x_i = ±(1 + i/(n − 1)).
315        let x = Mat::from_fn(n, 1, |i, _| {
316            let sign = if i % 2 == 0 { 1.0 } else { -1.0 };
317            c64::new(sign * (1.0 + i as f64 / (n - 1) as f64), 0.0)
318        });
319        estimate.max(2.0 * norm(&apply(x, false)) / (3.0 * n as f64))
320    }
321
322    /// `a⁻¹ b`.
323    pub fn solve(&self, b: MatRef<'_, c64>) -> Mat<c64> {
324        let mut x = b.to_owned();
325        self.solve_in_place(x.as_mut());
326        x
327    }
328}
329
330/// `‖a‖₁`, the largest column sum of moduli.
331pub fn norm_1(a: MatRef<'_, c64>) -> f64 {
332    (0..a.ncols()).map(|j| (0..a.nrows()).map(|i| a[(i, j)].norm()).sum::<f64>()).fold(0.0, f64::max)
333}
334
335/// Orthonormal basis of the columns of a full-rank `m × n` matrix, `m ≥ n`: the thin `Q` of its
336/// QR factorisation.
337pub fn orthonormal_columns(a: MatRef<'_, c64>) -> Mat<c64> {
338    assert!(a.nrows() >= a.ncols(), "orthonormal_columns: more columns than rows");
339    #[cfg(all(target_os = "macos", feature = "accelerate"))]
340    if use_accelerate() {
341        return accelerate::orthonormal_columns(a);
342    }
343    a.qr().compute_thin_Q()
344}
345
346/// Thin singular value decomposition `a = u diag(s) v†`.
347#[derive(Clone, Debug)]
348pub struct Svd {
349    /// Left singular vectors in columns (`m × k` for an `m × n` matrix, `k = min(m, n)`).
350    pub u: Mat<c64>,
351    /// Singular values, in decreasing order.
352    pub s: Vec<f64>,
353    /// Right singular vectors in columns (`n × k`).
354    pub v: Mat<c64>,
355}
356
357/// Thin singular value decomposition of `a`.
358pub fn svd(a: MatRef<'_, c64>) -> Result<Svd, DenseError> {
359    #[cfg(all(target_os = "macos", feature = "accelerate"))]
360    if use_accelerate() {
361        return accelerate::svd(a);
362    }
363    let svd = a.thin_svd().map_err(|_| DenseError::Svd)?;
364    let s = (0..a.nrows().min(a.ncols())).map(|k| svd.S()[k].re).collect();
365    Ok(Svd { u: svd.U().to_owned(), s, v: svd.V().to_owned() })
366}
367
368/// Eigen-decomposition `a = v diag(w) v†` of a Hermitian matrix, from its lower triangle:
369/// eigenvalues in increasing order, orthonormal eigenvectors in columns.
370pub fn hermitian_eigen(a: MatRef<'_, c64>) -> Result<(Vec<f64>, Mat<c64>), DenseError> {
371    assert_eq!(a.nrows(), a.ncols(), "hermitian_eigen: square matrix expected");
372    #[cfg(all(target_os = "macos", feature = "accelerate"))]
373    if use_accelerate() {
374        return accelerate::hermitian_eigen(a);
375    }
376    let evd = a.self_adjoint_eigen(faer::Side::Lower).map_err(|_| DenseError::Eigen)?;
377    Ok(((0..a.nrows()).map(|k| evd.S()[k].re).collect(), evd.U().to_owned()))
378}
379
380/// Whether a matrix has no imaginary part at all.
381pub fn is_real(a: MatRef<'_, c64>) -> bool {
382    (0..a.ncols()).all(|j| (0..a.nrows()).all(|i| a[(i, j)].im == 0.0))
383}
384
385/// Thin singular value decomposition of a real matrix (given with zero imaginary parts), with
386/// real singular vectors (a complex decomposition may mix degenerate ones with phases). Without
387/// Accelerate, [`svd`].
388pub fn svd_of_real(a: MatRef<'_, c64>) -> Result<Svd, DenseError> {
389    #[cfg(all(target_os = "macos", feature = "accelerate"))]
390    if use_accelerate() {
391        let (m, n) = (a.nrows(), a.ncols());
392        let k = m.min(n);
393        let mut re: Vec<f64> = (0..m * n).map(|x| a[(x % m, x / m)].re).collect();
394        let (u, s, vt) = accelerate::real_svd(&mut re, m, n)?;
395        return Ok(Svd {
396            u: Mat::from_fn(m, k, |i, j| c64::new(u[i + j * m], 0.0)),
397            s,
398            v: Mat::from_fn(n, k, |i, j| c64::new(vt[j + i * k], 0.0)),
399        });
400    }
401    svd(a)
402}
403
404/// How a factor enters a product.
405#[derive(Clone, Copy, Debug, PartialEq, Eq)]
406pub enum Op {
407    /// The factor as it is, `a`.
408    Plain,
409    /// Its transpose, `aᵀ`.
410    Transpose,
411    /// Its conjugate transpose, `a†`.
412    Adjoint,
413}
414
415/// `dst = α op(a) op(b)` (`Accum::Replace`) or `dst += α op(a) op(b)` (`Accum::Add`).
416pub fn matmul(
417    dst: MatMut<'_, c64>,
418    accum: Accum,
419    a: MatRef<'_, c64>,
420    op_a: Op,
421    b: MatRef<'_, c64>,
422    op_b: Op,
423    alpha: c64,
424) {
425    let shape = |m: MatRef<'_, c64>, op: Op| {
426        if op == Op::Plain { (m.nrows(), m.ncols()) } else { (m.ncols(), m.nrows()) }
427    };
428    let ((ra, ka), (kb, cb)) = (shape(a, op_a), shape(b, op_b));
429    assert!(ra == dst.nrows() && cb == dst.ncols() && ka == kb, "matmul: dimension mismatch");
430    #[cfg(all(target_os = "macos", feature = "accelerate"))]
431    let dst = if use_accelerate() {
432        match accelerate::matmul(dst, accum, a, op_a, b, op_b, alpha) {
433            Ok(()) => return,
434            Err(dst) => dst, // strides BLAS cannot take
435        }
436    } else {
437        dst
438    };
439    faer_matmul(dst, accum, a, op_a, b, op_b, alpha);
440}
441
442fn faer_matmul(
443    dst: MatMut<'_, c64>,
444    accum: Accum,
445    a: MatRef<'_, c64>,
446    op_a: Op,
447    b: MatRef<'_, c64>,
448    op_b: Op,
449    alpha: c64,
450) {
451    use faer::linalg::matmul::matmul as mm;
452    let par = faer::get_global_parallelism();
453    match (op_a, op_b) {
454        (Op::Plain, Op::Plain) => mm(dst, accum, a, b, alpha, par),
455        (Op::Plain, Op::Transpose) => mm(dst, accum, a, b.transpose(), alpha, par),
456        (Op::Plain, Op::Adjoint) => mm(dst, accum, a, b.adjoint(), alpha, par),
457        (Op::Transpose, Op::Plain) => mm(dst, accum, a.transpose(), b, alpha, par),
458        (Op::Transpose, Op::Transpose) => mm(dst, accum, a.transpose(), b.transpose(), alpha, par),
459        (Op::Transpose, Op::Adjoint) => mm(dst, accum, a.transpose(), b.adjoint(), alpha, par),
460        (Op::Adjoint, Op::Plain) => mm(dst, accum, a.adjoint(), b, alpha, par),
461        (Op::Adjoint, Op::Transpose) => mm(dst, accum, a.adjoint(), b.transpose(), alpha, par),
462        (Op::Adjoint, Op::Adjoint) => mm(dst, accum, a.adjoint(), b.adjoint(), alpha, par),
463    }
464}
465
466/// `op(a) op(b)` as a new matrix.
467pub fn product(a: MatRef<'_, c64>, op_a: Op, b: MatRef<'_, c64>, op_b: Op) -> Mat<c64> {
468    let rows = if op_a == Op::Plain { a.nrows() } else { a.ncols() };
469    let cols = if op_b == Op::Plain { b.ncols() } else { b.nrows() };
470    let mut c = Mat::zeros(rows, cols);
471    matmul(c.as_mut(), Accum::Replace, a, op_a, b, op_b, c64::new(1.0, 0.0));
472    c
473}
474
475#[cfg(test)]
476mod tests {
477    use super::*;
478
479    fn test_matrix(m: usize, n: usize, seed: usize) -> Mat<c64> {
480        Mat::from_fn(m, n, |i, j| {
481            c64::new(
482                ((i * 7 + j * 13 + seed) % 17) as f64 / 17.0 - 0.5,
483                ((i * 3 + j * 5 + 2 * seed) % 11) as f64 / 11.0 - 0.5,
484            )
485        })
486    }
487
488    /// Held by the tests that depend on the backend: [`backends_agree`] changes it for the whole
489    /// process while the other tests run.
490    static BACKEND: std::sync::Mutex<()> = std::sync::Mutex::new(());
491
492    /// Every backend gives the same results.
493    #[test]
494    fn backends_agree() {
495        let _lock = BACKEND.lock().unwrap_or_else(|e| e.into_inner());
496        let a = test_matrix(60, 60, 3) + Mat::<c64>::identity(60, 60) * faer::Scale(c64::new(1.5, 0.2));
497        let b = test_matrix(60, 4, 4);
498        let run =
499            || {
500                let x = Lu::new(a.as_ref()).solve(b.as_ref());
501                let p = product(a.as_ref(), Op::Adjoint, b.as_ref(), Op::Plain);
502                let s = svd(a.as_ref()).unwrap().s;
503                let h = &a + a.adjoint();
504                let (w, v) = hermitian_eigen(h.as_ref()).unwrap();
505                let d = Mat::<c64>::from_fn(60, 60, |i, j| {
506                    if i == j { c64::new(w[i], 0.0) } else { c64::new(0.0, 0.0) }
507                });
508                assert!((&v * d * v.adjoint() - &h).norm_max() < 1e-11);
509                assert!(w.windows(2).all(|p| p[0] <= p[1]));
510                (x, p, s, w)
511            };
512        let saved = backend();
513        let reference = run();
514        for choice in [Backend::Accelerate, Backend::Faer] {
515            set_backend(choice);
516            assert_eq!(backend(), choice);
517            let (x, p, s, w) = run();
518            assert!(
519                (&x - &reference.0).norm_max() < 1e-11 && (&p - &reference.1).norm_max() < 1e-11,
520                "{choice:?}"
521            );
522            assert!(s.iter().zip(&reference.2).all(|(u, v)| (u - v).abs() < 1e-11), "{choice:?}");
523            assert!(w.iter().zip(&reference.3).all(|(u, v)| (u - v).abs() < 1e-11), "{choice:?}");
524        }
525        set_backend(saved);
526    }
527
528    /// The Schur form of a real matrix through its real Schur form, against the complex one.
529    #[test]
530    fn schur_of_real_matrices() {
531        let _lock = BACKEND.lock().unwrap_or_else(|e| e.into_inner());
532        for n in [1usize, 2, 7, 60, 257] {
533            let a = Mat::<c64>::from_fn(n, n, |i, j| c64::new(test_matrix(n, n, 5)[(i, j)].re, 0.0));
534            let start = std::time::Instant::now();
535            let (q, t) = schur_of_real(a.as_ref()).unwrap_or_else(|e| panic!("n {n}: {e:?}"));
536            let (residual, unitarity) = (
537                (&q * &t * q.adjoint() - &a).norm_max(),
538                (q.adjoint() * &q - Mat::<c64>::identity(n, n)).norm_max(),
539            );
540            let report = format!(
541                "n {n} ({:?}, {:.1?}): q t q† − a {residual:e}, q†q − 1 {unitarity:e}",
542                backend(),
543                start.elapsed()
544            );
545            assert!(residual < 1e-12 * n as f64 && unitarity < 1e-12 * n as f64, "{report}");
546            assert!((0..n).all(|j| (j + 1..n).all(|i| t[(i, j)] == c64::new(0.0, 0.0))), "n {n}: triangular");
547            let (_, tc) = schur(a.as_ref()).unwrap();
548            // Each eigenvalue matches one of the complex decomposition.
549            let mut theirs: Vec<c64> = (0..n).map(|k| tc[(k, k)]).collect();
550            for k in 0..n {
551                let mine = t[(k, k)];
552                let (best, d) = theirs
553                    .iter()
554                    .enumerate()
555                    .map(|(i, x)| (i, (x - mine).norm()))
556                    .min_by(|x, y| x.1.total_cmp(&y.1))
557                    .unwrap();
558                assert!(d < 1e-9, "n {n}: eigenvalue {mine}");
559                theirs.swap_remove(best);
560            }
561        }
562    }
563
564    /// The real SVD reconstructs the matrix with real factors.
565    #[test]
566    fn svd_of_real_matrices() {
567        for (m, n) in [(7usize, 3usize), (40, 40), (30, 50)] {
568            let a = Mat::<c64>::from_fn(m, n, |i, j| c64::new(test_matrix(m, n, 9)[(i, j)].re, 0.0));
569            let Svd { u, s, v } = svd_of_real(a.as_ref()).unwrap();
570            let k = m.min(n);
571            let sigma =
572                Mat::<c64>::from_fn(
573                    k,
574                    k,
575                    |i, j| if i == j { c64::new(s[i], 0.0) } else { c64::new(0.0, 0.0) },
576                );
577            assert!((&u * sigma * v.adjoint() - &a).norm_max() < 1e-12, "{m}x{n}");
578            assert!(is_real(u.as_ref()) && is_real(v.as_ref()));
579        }
580    }
581
582    /// Time of the real path against the complex one (`cargo test --release -- --ignored`).
583    #[test]
584    #[ignore]
585    fn schur_of_real_timing() {
586        for n in [256usize, 512, 1024] {
587            let a = Mat::<c64>::from_fn(n, n, |i, j| {
588                c64::new(((i * 7919 + j * 104729) % 1009) as f64 / 1009.0 - 0.5, 0.0)
589            });
590            let t0 = std::time::Instant::now();
591            let _ = schur(a.as_ref()).unwrap();
592            let complex = t0.elapsed();
593            let t0 = std::time::Instant::now();
594            let _ = schur_of_real(a.as_ref()).unwrap();
595            println!("n {n}: complex {complex:.2?}, real {:.2?}", t0.elapsed());
596        }
597    }
598
599    /// LU solves against faer, with a strided right-hand side, and the pivots of a singular matrix.
600    #[test]
601    fn lu_solves() {
602        for n in [1usize, 4, 37, 120] {
603            let a = test_matrix(n, n, 7) + Mat::<c64>::identity(n, n) * faer::Scale(c64::new(2.0, 0.5));
604            let b = test_matrix(n, 5, 8);
605            let lu = Lu::new(a.as_ref());
606            let x = lu.solve(b.as_ref());
607            assert!((&a * &x - &b).norm_max() < 1e-12, "n {n}");
608            let mut big = test_matrix(n + 2, 9, 9);
609            big.as_mut().submatrix_mut(1, 2, n, 5).copy_from(&b);
610            lu.solve_in_place(big.as_mut().submatrix_mut(1, 2, n, 5));
611            assert!((big.as_ref().submatrix(1, 2, n, 5).to_owned() - &x).norm_max() < 1e-12);
612            let (lo, hi) = lu.pivot_range();
613            assert!(lo > 0.0 && hi >= lo);
614        }
615        let mut s = test_matrix(6, 6, 1);
616        for i in 0..6 {
617            s[(i, 5)] = s[(i, 0)] * 2.0; // dependent columns
618        }
619        let (lo, hi) = Lu::new(s.as_ref()).pivot_range();
620        assert!(lo < 1e-14 * hi, "singular: {lo:e} / {hi:e}");
621    }
622
623    /// The condition estimate against the singular values, and solves with the adjoint.
624    #[test]
625    fn condition_estimate() {
626        for n in [1usize, 5, 40, 150] {
627            let mut a = test_matrix(n, n, 3);
628            for i in 0..n {
629                a[(i, i)] += c64::new(0.05 * i as f64, 0.0);
630            }
631            let lu = Lu::new(a.as_ref());
632            let b = test_matrix(n, 3, 4);
633            let mut x = b.clone();
634            lu.solve_adjoint_in_place(x.as_mut());
635            assert!((a.adjoint() * &x - &b).norm_max() < 1e-9 * (1.0 + x.norm_max()), "n {n}: adjoint solve");
636            let s = a.singular_values().unwrap();
637            let ratio =
638                s.iter().cloned().fold(f64::INFINITY, f64::min) / s.iter().cloned().fold(0.0, f64::max);
639            let rcond = lu.inverse_condition_1(norm_1(a.as_ref()));
640            assert!(
641                rcond <= n as f64 * ratio * (1.0 + 1e-9) && rcond >= ratio / (n as f64 * n as f64),
642                "n {n}: {rcond:e} vs {ratio:e}"
643            );
644        }
645        let mut s = test_matrix(6, 6, 1);
646        for i in 0..6 {
647            s[(i, 5)] = s[(i, 0)] * 2.0;
648        }
649        assert!(Lu::new(s.as_ref()).inverse_condition_1(norm_1(s.as_ref())) < 1e-14);
650    }
651
652    #[test]
653    fn qr_and_svd() {
654        for (m, n) in [(7usize, 3usize), (60, 60), (90, 40)] {
655            let a = test_matrix(m, n, 5)
656                + Mat::<c64>::from_fn(
657                    m,
658                    n,
659                    |i, j| if i == j { c64::new(1.0, 0.0) } else { c64::new(0.0, 0.0) },
660                );
661            let q = orthonormal_columns(a.as_ref());
662            assert!((q.adjoint() * &q - Mat::<c64>::identity(n, n)).norm_max() < 1e-13);
663            // Same column space: a = q (q† a).
664            assert!((&q * (q.adjoint() * &a) - &a).norm_max() < 1e-12);
665            let Svd { u, s, v } = svd(a.as_ref()).unwrap();
666            let k = m.min(n);
667            let sigma =
668                Mat::<c64>::from_fn(
669                    k,
670                    k,
671                    |i, j| if i == j { c64::new(s[i], 0.0) } else { c64::new(0.0, 0.0) },
672                );
673            assert!((&u * sigma * v.adjoint() - &a).norm_max() < 1e-12, "{m}x{n}");
674            assert!(s.windows(2).all(|w| w[0] >= w[1]));
675        }
676    }
677
678    /// Every combination of operations, both accumulation modes, and strided views.
679    #[test]
680    fn products_match_faer() {
681        let ops = [Op::Plain, Op::Transpose, Op::Adjoint];
682        let alpha = c64::new(0.7, -0.4);
683        for (m, n, k) in [(5, 7, 3), (40, 33, 65), (1, 9, 4), (6, 1, 1), (3, 4, 0)] {
684            for &op_a in &ops {
685                for &op_b in &ops {
686                    let a = if op_a == Op::Plain { test_matrix(m, k, 1) } else { test_matrix(k, m, 1) };
687                    let b = if op_b == Op::Plain { test_matrix(k, n, 2) } else { test_matrix(n, k, 2) };
688                    let opm = |x: &Mat<c64>, op: Op| match op {
689                        Op::Plain => x.clone(),
690                        Op::Transpose => x.transpose().to_owned(),
691                        Op::Adjoint => x.adjoint().to_owned(),
692                    };
693                    let reference = (opm(&a, op_a) * opm(&b, op_b)) * faer::Scale(alpha);
694                    // Replace, into a view of a larger matrix (column stride above the row count).
695                    let mut big = test_matrix(m + 3, n + 2, 3);
696                    matmul(
697                        big.as_mut().submatrix_mut(1, 2, m, n),
698                        Accum::Replace,
699                        a.as_ref(),
700                        op_a,
701                        b.as_ref(),
702                        op_b,
703                        alpha,
704                    );
705                    let got = big.as_ref().submatrix(1, 2, m, n).to_owned();
706                    assert!((&got - &reference).norm_max() < 1e-13, "replace {op_a:?} {op_b:?} {m}x{n}x{k}");
707                    // Add.
708                    let mut c = test_matrix(m, n, 4);
709                    let expected = &c + &reference;
710                    matmul(c.as_mut(), Accum::Add, a.as_ref(), op_a, b.as_ref(), op_b, alpha);
711                    assert!((&c - &expected).norm_max() < 1e-13, "add {op_a:?} {op_b:?} {m}x{n}x{k}");
712                }
713            }
714        }
715        // A row-major view goes through the fallback.
716        let a = test_matrix(6, 5, 5);
717        let b = test_matrix(6, 4, 6);
718        let at = a.transpose(); // row stride ≠ 1
719        let mut c = Mat::zeros(5, 4);
720        matmul(c.as_mut(), Accum::Replace, at, Op::Plain, b.as_ref(), Op::Plain, c64::new(1.0, 0.0));
721        assert!((&c - a.transpose() * &b).norm_max() < 1e-13);
722    }
723}