Skip to main content

caroli_dense/
field.rs

1//! The scalar of the elimination kernels: complex f64, or complex f32 for reduced precision.
2
3use crate::{Lu, Op, matmul};
4use faer::{Accum, Conj, Mat, MatRef, c32, c64};
5
6/// A complex scalar the elimination kernels run in: [`c64`], or [`c32`] for reduced precision.
7/// Through Accelerate on Apple silicon, the Schur step of a front of 128 to 2048 variables runs
8/// 2.7–3.7× faster in `c32`.
9pub trait Field:
10    faer::traits::ComplexField
11    + Copy
12    + Send
13    + Sync
14    + PartialEq
15    + std::fmt::Debug
16    + 'static
17    + std::ops::Add<Output = Self>
18    + std::ops::Sub<Output = Self>
19    + std::ops::Mul<Output = Self>
20    + std::ops::Div<Output = Self>
21    + std::ops::AddAssign
22    + std::ops::SubAssign
23    + std::ops::MulAssign
24{
25    /// The scalar `0`.
26    const ZERO: Self;
27    /// The scalar `1`.
28    const ONE: Self;
29    /// The pivot test of [`Field::schur`]: a pivot below this fraction of the largest entry of
30    /// the block counts as zero. About 10⁵ times the rounding error of `c64`; for `c32`, about
31    /// 100 times its rounding error. A stricter `c32` test would refuse more ill-conditioned
32    /// blocks, which nested dissection then delays to larger fronts: more accurate, but up to
33    /// 3× slower than `c64` (`ARCHITECTURE.md`, item 12).
34    const PIVOT_TOL: f64;
35
36    /// `z` in this precision: rounded to `c32`, unchanged for `c64`.
37    fn from_c64(z: c64) -> Self;
38    /// The scalar in complex f64 (exact).
39    fn to_c64(self) -> c64;
40    /// `|z|`, in f64.
41    fn modulus(self) -> f64;
42    /// The matrix in complex f64 (a move for `c64`).
43    fn into_c64(m: Mat<Self>) -> Mat<c64>;
44
45    /// Schur complement of the leading `ne × ne` block `f11` of the square matrix `f`:
46    /// `(S, X)` with `X = f11⁻¹ f12` and `S = f22 − f21 X`, or `None` if a pivot of the LU of
47    /// `f11` falls below [`Field::PIVOT_TOL`] times its largest entry (numerically singular).
48    fn schur(f: MatRef<'_, Self>, ne: usize) -> Option<(Mat<Self>, Mat<Self>)>;
49}
50
51/// Largest modulus of the entries of `a`.
52fn largest<T: Field>(a: MatRef<'_, T>) -> f64 {
53    let mut m = 0.0f64;
54    for j in 0..a.ncols() {
55        for i in 0..a.nrows() {
56            m = m.max(a[(i, j)].modulus());
57        }
58    }
59    m
60}
61
62impl Field for c64 {
63    const ZERO: Self = c64::new(0.0, 0.0);
64    const ONE: Self = c64::new(1.0, 0.0);
65    const PIVOT_TOL: f64 = 1e-11;
66
67    fn from_c64(z: c64) -> Self {
68        z
69    }
70
71    fn to_c64(self) -> c64 {
72        self
73    }
74
75    fn modulus(self) -> f64 {
76        self.norm()
77    }
78
79    fn into_c64(m: Mat<Self>) -> Mat<c64> {
80        m
81    }
82
83    fn schur(f: MatRef<'_, Self>, ne: usize) -> Option<(Mat<Self>, Mat<Self>)> {
84        let n = f.nrows();
85        let f11 = f.submatrix(0, 0, ne, ne);
86        let scale = f11.norm_max();
87        let lu = Lu::new(f11);
88        let (small, _) = lu.pivot_range();
89        let stable = small > Self::PIVOT_TOL * scale; // false for NaN
90        if !stable {
91            return None;
92        }
93        let nb = n - ne;
94        if nb == 0 {
95            return Some((Mat::zeros(0, 0), Mat::zeros(ne, 0)));
96        }
97        let x = lu.solve(f.submatrix(0, ne, ne, nb));
98        let mut s = f.submatrix(ne, ne, nb, nb).to_owned();
99        matmul(
100            s.as_mut(),
101            Accum::Add,
102            f.submatrix(ne, 0, nb, ne),
103            Op::Plain,
104            x.as_ref(),
105            Op::Plain,
106            -Self::ONE,
107        );
108        Some((s, x))
109    }
110}
111
112impl Field for c32 {
113    const ZERO: Self = c32::new(0.0, 0.0);
114    const ONE: Self = c32::new(1.0, 0.0);
115    const PIVOT_TOL: f64 = 1e-5;
116
117    fn from_c64(z: c64) -> Self {
118        c32::new(z.re as f32, z.im as f32)
119    }
120
121    fn to_c64(self) -> c64 {
122        c64::new(self.re as f64, self.im as f64)
123    }
124
125    fn modulus(self) -> f64 {
126        (self.re as f64).hypot(self.im as f64)
127    }
128
129    fn into_c64(m: Mat<Self>) -> Mat<c64> {
130        Mat::from_fn(m.nrows(), m.ncols(), |i, j| m[(i, j)].to_c64())
131    }
132
133    fn schur(f: MatRef<'_, Self>, ne: usize) -> Option<(Mat<Self>, Mat<Self>)> {
134        #[cfg(all(target_os = "macos", feature = "accelerate"))]
135        if crate::use_accelerate()
136            && let Some(result) = crate::accelerate::schur_c32(f, ne, Self::PIVOT_TOL)
137        {
138            return result;
139        }
140        faer_schur(f, ne)
141    }
142}
143
144/// [`Field::schur`] with faer's LU and product.
145fn faer_schur<T: Field>(f: MatRef<'_, T>, ne: usize) -> Option<(Mat<T>, Mat<T>)> {
146    use faer::linalg::solvers::SolveCore;
147    let n = f.nrows();
148    let f11 = f.submatrix(0, 0, ne, ne);
149    let scale = largest(f11);
150    let lu = f11.partial_piv_lu();
151    let u = lu.U();
152    let small = (0..ne).map(|i| u[(i, i)].modulus()).fold(f64::INFINITY, f64::min);
153    let stable = small > T::PIVOT_TOL * scale; // false for NaN
154    if !stable {
155        return None;
156    }
157    let nb = n - ne;
158    if nb == 0 {
159        return Some((Mat::zeros(0, 0), Mat::zeros(ne, 0)));
160    }
161    let mut x = f.submatrix(0, ne, ne, nb).to_owned();
162    lu.solve_in_place_with_conj(Conj::No, x.as_mut());
163    let mut s = f.submatrix(ne, ne, nb, nb).to_owned();
164    let minus_one = T::from_c64(c64::new(-1.0, 0.0));
165    faer::linalg::matmul::matmul(
166        s.as_mut(),
167        Accum::Add,
168        f.submatrix(ne, 0, nb, ne),
169        x.as_ref(),
170        minus_one,
171        faer::get_global_parallelism(),
172    );
173    Some((s, x))
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179
180    fn front(n: usize) -> Mat<c64> {
181        Mat::from_fn(n, n, |i, j| {
182            let v = ((i * 7 + j * 13) % 17) as f64 / 17.0 - 0.5;
183            c64::new(v + if i == j { 3.0 } else { 0.0 }, ((i + 2 * j) % 5) as f64 / 10.0)
184        })
185    }
186
187    #[test]
188    fn single_schur_follows_double() {
189        for (n, ne) in [(12, 5), (90, 40)] {
190            let f = front(n);
191            let (s64, x64) = c64::schur(f.as_ref(), ne).unwrap();
192            let f32m = Mat::from_fn(n, n, |i, j| c32::from_c64(f[(i, j)]));
193            let (s32, x32) = c32::schur(f32m.as_ref(), ne).unwrap();
194            let (s32, x32) = (c32::into_c64(s32), c32::into_c64(x32));
195            let err = |a: &Mat<c64>, b: &Mat<c64>| (a - b).norm_max() / b.norm_max();
196            assert!(err(&s32, &s64) < 1e-5 && err(&x32, &x64) < 1e-5, "n = {n}");
197            // The faer path gives the same.
198            let (s, _) = faer_schur(f32m.as_ref(), ne).unwrap();
199            assert!(err(&c32::into_c64(s), &s64) < 1e-5);
200        }
201    }
202
203    #[test]
204    fn singular_block_is_refused() {
205        let mut f = front(10);
206        for j in 0..10 {
207            f[(1, j)] = f[(0, j)]; // two equal rows in the leading block
208        }
209        assert!(c64::schur(f.as_ref(), 4).is_none());
210        let f32m = Mat::from_fn(10, 10, |i, j| c32::from_c64(f[(i, j)]));
211        assert!(c32::schur(f32m.as_ref(), 4).is_none());
212    }
213}