Skip to main content

lib_jsl_linalg/sparse/
mod.rs

1//! Sparse matrices and solvers for large systems, following `scipy.sparse` and
2//! `scipy.sparse.linalg`: COO, CSR and CSC storage; a sparse LU factorisation with a
3//! fill-reducing column ordering (minimum degree, COLAMD, nested dissection or reverse
4//! Cuthill-McKee; `spsolve`, `SparseLu`); Krylov
5//! solvers (CG, MINRES, GMRES, LGMRES, BiCGSTAB, LSQR) for any [`LinearOperator`], with Jacobi,
6//! incomplete-LU and incomplete-Cholesky preconditioners; a few eigenvalues or singular values by
7//! Lanczos methods (`eigsh`, its shift-invert mode, `svds`) and of nonsymmetric matrices by Arnoldi's
8//! (`eigs`, `eigs_shift_invert`); and `expm_multiply`. These are real (`f64`); complex matrices have their own storage, LU and
9//! Krylov solvers (`ComplexCsrMatrix`, `ComplexSparseLu`, `cg_complex`, `gmres_complex`,
10//! `bicgstab_complex`).
11//!
12//! See the book entry [Sparse matrices and iterative solvers](https://jwkunz.github.io/lib_jsl/book/linear_algebra/sparse.html).
13
14mod amd;
15mod arnoldi;
16mod colamd;
17mod complex;
18mod direct;
19mod dissection;
20mod eigen;
21mod expm;
22mod formats;
23mod ichol;
24mod ilu;
25mod iterative;
26mod lgmres;
27
28pub use arnoldi::{EigsOptions, EigsResult, EigsWhich, eigs, eigs_shift_invert};
29pub use colamd::{colamd, symamd};
30pub use complex::{ComplexCooMatrix, ComplexCsrMatrix, ComplexIterativeOptions, ComplexIterativeResult, ComplexJacobi, ComplexLinearOperator, ComplexSparseLu, bicgstab_complex, cg_complex, gmres_complex, spsolve_complex, spsolve_complex_colamd};
31pub use dissection::nested_dissection;
32pub use amd::minimum_degree;
33pub use direct::{Ordering, SparseLu, bandwidth, minimum_degree_exact, reverse_cuthill_mckee, spsolve};
34pub use eigen::{EigenPairs, Which, eigsh, eigsh_shift_invert, svds};
35pub use expm::expm_multiply;
36pub use ichol::{IcOrdering, IncompleteCholesky};
37pub use ilu::Ilu;
38pub use formats::{CooMatrix, CscMatrix, CsrMatrix};
39pub use lgmres::{LgmresSolver, lgmres};
40pub use iterative::{FnOperator, IterativeOptions, IterativeResult, Jacobi, LinearOperator, LsmrOptions, LsmrResult, bicgstab, cg, gmres, lsmr, lsqr, minres};
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45
46    /// The 5-point Laplacian on an `m × m` grid (SPD, n = m²).
47    fn poisson(m: usize) -> CsrMatrix {
48        let mut coo = CooMatrix::new(m * m, m * m);
49        for i in 0..m {
50            for j in 0..m {
51                let k = i * m + j;
52                coo.push(k, k, 4.0);
53                if i > 0 {
54                    coo.push(k, k - m, -1.0);
55                }
56                if i + 1 < m {
57                    coo.push(k, k + m, -1.0);
58                }
59                if j > 0 {
60                    coo.push(k, k - 1, -1.0);
61                }
62                if j + 1 < m {
63                    coo.push(k, k + 1, -1.0);
64                }
65            }
66        }
67        coo.to_csr().unwrap()
68    }
69
70    fn residual(a: &CsrMatrix, x: &[f64], b: &[f64]) -> f64 {
71        a.matvec(x).iter().zip(b).map(|(p, q)| (p - q).powi(2)).sum::<f64>().sqrt()
72    }
73
74    #[test]
75    fn formats_round_trip_and_multiply() {
76        let a = CsrMatrix::from_triplets(3, 4, &[0, 2, 1, 0, 2], &[1, 3, 0, 1, 0], &[1.0, 2.0, 3.0, 4.0, 5.0]).unwrap();
77        assert_eq!(a.get(0, 1), 5.0);
78        assert_eq!(a.nnz(), 4);
79        assert_eq!(a.to_csc().to_csr(), a);
80        let d = a.to_dense();
81        let p = a.matmul(&a.transpose()).unwrap().to_dense();
82        assert!((p - d.dot(&d.t())).iter().all(|v| v.abs() < 1e-14));
83    }
84
85    #[test]
86    fn direct_and_iterative_solvers_agree() {
87        let a = poisson(12);
88        let n = a.nrows;
89        let b: Vec<f64> = (0..n).map(|i| ((i * 7) % 11) as f64 - 5.0).collect();
90        let x = spsolve(&a, &b).unwrap();
91        assert!(residual(&a, &x, &b) < 1e-11);
92        let o = IterativeOptions { rtol: 1e-10, ..Default::default() };
93        for r in [cg(&a, &b, None, None, o).unwrap(), bicgstab(&a, &b, None, None, o).unwrap(), gmres(&a, &b, None, None, 30, o).unwrap(), minres(&a, &b, None, o).unwrap()] {
94            assert!(r.converged, "{} iterations", r.iterations);
95            assert!(x.iter().zip(&r.x).all(|(p, q)| (p - q).abs() < 1e-8));
96        }
97        let pre = Jacobi::new(&a).unwrap();
98        assert!(cg(&a, &b, None, Some(&pre), o).unwrap().converged);
99    }
100
101    #[test]
102    fn lanczos_finds_the_extreme_eigenvalues_of_the_laplacian() {
103        let m = 10;
104        let a = poisson(m);
105        let (vals, vecs) = eigsh(&a, 3, Which::LargestAlgebraic, 0.0).unwrap();
106        // Eigenvalues 4 − 2cos(iπ/(m+1)) − 2cos(jπ/(m+1)).
107        let mut exact: Vec<f64> = (1..=m).flat_map(|i| (1..=m).map(move |j| 4.0 - 2.0 * (i as f64 * std::f64::consts::PI / (m + 1) as f64).cos() - 2.0 * (j as f64 * std::f64::consts::PI / (m + 1) as f64).cos())).collect();
108        exact.sort_by(f64::total_cmp);
109        let top = &exact[exact.len() - 3..];
110        for (v, e) in vals.iter().zip(top) {
111            assert!((v - e).abs() < 1e-8, "{vals:?} vs {top:?}");
112        }
113        let av = a.matvec(&vecs.column(2).to_vec());
114        assert!(av.iter().zip(vecs.column(2)).all(|(p, q)| (p - vals[2] * q).abs() < 1e-6));
115        let (s, _, _) = svds(&a, 2, 0.0).unwrap();
116        assert!((s[0] - top[2]).abs() < 1e-8);
117    }
118
119    #[test]
120    fn deflation_finds_both_copies_of_a_repeated_eigenvalue() {
121        // On a square grid λ(i, j) = λ(j, i): the second and third largest eigenvalues coincide.
122        let m = 30;
123        let (vals, vecs) = eigsh(&poisson(m), 4, Which::LargestAlgebraic, 0.0).unwrap();
124        let h = std::f64::consts::PI / (m + 1) as f64;
125        let lam = |i: usize, j: usize| 4.0 - 2.0 * (i as f64 * h).cos() - 2.0 * (j as f64 * h).cos();
126        let mut exact: Vec<f64> = (1..=m).flat_map(|i| (1..=m).map(move |j| (i, j))).map(|(i, j)| lam(i, j)).collect();
127        exact.sort_by(f64::total_cmp);
128        let top = &exact[exact.len() - 4..];
129        for (v, e) in vals.iter().zip(top) {
130            assert!((v - e).abs() < 1e-10, "{vals:?} vs {top:?}");
131        }
132        let gram = vecs.t().dot(&vecs);
133        assert!(gram.indexed_iter().all(|((i, j), g)| (g - if i == j { 1.0 } else { 0.0 }).abs() < 1e-10));
134    }
135
136    #[test]
137    fn lsmr_solves_damped_least_squares() {
138        let mut coo = CooMatrix::new(30, 8);
139        for i in 0..30 {
140            coo.push(i, i % 8, 1.0 + 0.1 * i as f64);
141            coo.push(i, (3 * i + 1) % 8, -0.5 + 0.03 * i as f64);
142        }
143        let a = coo.to_csr().unwrap();
144        let b: Vec<f64> = (0..30).map(|i| (0.3 * i as f64).sin()).collect();
145        for damp in [0.0, 0.7] {
146            let r = lsmr(&a, &b, LsmrOptions { atol: 1e-14, btol: 1e-14, max_iterations: Some(100), ..LsmrOptions::with_damp(damp) }).unwrap();
147            assert!((1..=2).contains(&r.istop) || r.istop == 4 || r.istop == 5, "{}", r.istop);
148            // Aᵀ(b − A x) − λ² x = 0.
149            let res: Vec<f64> = a.matvec(&r.x).iter().zip(&b).map(|(p, q)| q - p).collect();
150            let g: Vec<f64> = a.rmatvec(&res).iter().zip(&r.x).map(|(p, x)| p - damp * damp * x).collect();
151            assert!(g.iter().all(|v| v.abs() < 1e-10), "{g:?}");
152            assert!((r.normar - g.iter().map(|v| v * v).sum::<f64>().sqrt()).abs() < 1e-8);
153        }
154    }
155
156    #[test]
157    fn lsqr_matches_the_normal_equations() {
158        // A 30 × 8 matrix with a few entries per row.
159        let mut coo = CooMatrix::new(30, 8);
160        for i in 0..30 {
161            coo.push(i, i % 8, 1.0 + 0.1 * i as f64);
162            coo.push(i, (3 * i + 1) % 8, -0.5 + 0.03 * i as f64);
163        }
164        let a = coo.to_csr().unwrap();
165        let b: Vec<f64> = (0..30).map(|i| (0.3 * i as f64).sin()).collect();
166        let r = lsqr(&a, &b, IterativeOptions { rtol: 1e-12, ..Default::default() }).unwrap();
167        assert!(r.converged);
168        // Aᵀ(b − A x) = 0 at the least-squares solution.
169        let res: Vec<f64> = a.matvec(&r.x).iter().zip(&b).map(|(p, q)| q - p).collect();
170        assert!(a.rmatvec(&res).iter().all(|g| g.abs() < 1e-9));
171        let (s, u, v) = svds(&a, 3, 0.0).unwrap();
172        let dense = a.to_dense();
173        for c in 0..3 {
174            let av = dense.dot(&v.column(c));
175            assert!(av.iter().zip(u.column(c)).all(|(p, q)| (p - s[c] * q).abs() < 1e-9));
176        }
177    }
178
179    #[test]
180    fn minimum_degree_reduces_fill_and_ilu_preconditions() {
181        let a = poisson(20);
182        let natural = SparseLu::factor(&a, Ordering::Natural).unwrap().nnz();
183        let md = SparseLu::factor(&a, Ordering::MinimumDegree).unwrap().nnz();
184        let rcm = SparseLu::factor(&a, Ordering::ReverseCuthillMcKee).unwrap().nnz();
185        assert!(md < rcm && rcm <= natural, "md {md} rcm {rcm} natural {natural}");
186        let mut perm = minimum_degree(&a);
187        perm.sort_unstable();
188        assert_eq!(perm, (0..a.nrows).collect::<Vec<_>>());
189        let b: Vec<f64> = (0..a.nrows).map(|i| (i as f64).cos()).collect();
190        let o = IterativeOptions { rtol: 1e-10, ..Default::default() };
191        let plain = cg(&a, &b, None, None, o).unwrap().iterations;
192        let ilu0 = Ilu::ilu0(&a).unwrap();
193        assert_eq!(ilu0.nnz(), a.nnz());
194        let with = gmres(&a, &b, None, Some(&ilu0), 50, o).unwrap();
195        assert!(with.converged && with.iterations < plain / 2, "{} vs {plain}", with.iterations);
196        let ilut = Ilu::ilut(&a, 1e-12, 1000).unwrap();
197        // With no dropping ILUT is the exact LU, so one iteration suffices.
198        assert!(gmres(&a, &b, None, Some(&ilut), 50, o).unwrap().iterations <= 2);
199    }
200
201    #[test]
202    fn shift_invert_finds_interior_eigenvalues() {
203        let m = 12;
204        let a = poisson(m);
205        let h = std::f64::consts::PI / (m + 1) as f64;
206        let mut exact: Vec<f64> = (1..=m).flat_map(|i| (1..=m).map(move |j| 4.0 - 2.0 * (i as f64 * h).cos() - 2.0 * (j as f64 * h).cos())).collect();
207        exact.sort_by(f64::total_cmp);
208        let sigma = 3.3;
209        let mut near: Vec<f64> = exact.clone();
210        near.sort_by(|x, y| (x - sigma).abs().total_cmp(&(y - sigma).abs()));
211        let mut want: Vec<f64> = near[..5].to_vec();
212        want.sort_by(f64::total_cmp);
213        let (vals, _) = eigsh_shift_invert(&a, 5, sigma, 0.0).unwrap();
214        for (v, w) in vals.iter().zip(&want) {
215            assert!((v - w).abs() < 1e-10, "{vals:?} vs {want:?}");
216        }
217    }
218
219    /// A random sparse unsymmetric matrix with a dominant diagonal.
220    fn random_unsymmetric(n: usize, per_row: usize, seed: u64) -> CsrMatrix {
221        let mut state = seed;
222        let mut next = || {
223            state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
224            (state >> 33) as usize
225        };
226        let mut coo = CooMatrix::new(n, n);
227        for i in 0..n {
228            coo.push(i, i, 4.0 + (next() % 7) as f64);
229            for _ in 0..per_row {
230                coo.push(i, next() % n, (next() % 9) as f64 / 4.0 - 1.0);
231            }
232        }
233        coo.to_csr().unwrap()
234    }
235
236    fn is_permutation(q: &[usize], n: usize) -> bool {
237        let mut seen = vec![false; n];
238        q.len() == n && q.iter().all(|&c| c < n && !std::mem::replace(&mut seen[c], true))
239    }
240
241    #[test]
242    fn colamd_and_nested_dissection_give_permutations_and_solve() {
243        for a in [poisson(25), random_unsymmetric(400, 3, 7)] {
244            let n = a.nrows;
245            let b: Vec<f64> = (0..n).map(|i| ((i * 5) % 13) as f64 - 6.0).collect();
246            for q in [colamd(&a), nested_dissection(&a)] {
247                assert!(is_permutation(&q, n));
248                let x = SparseLu::factor_with_order(&a, &q).unwrap().solve(&b).unwrap();
249                assert!(residual(&a, &x, &b) < 1e-9);
250            }
251        }
252        assert!(SparseLu::factor_with_order(&poisson(3), &[0, 1, 2]).is_err());
253    }
254
255    #[test]
256    fn symamd_orders_symmetric_matrices_like_minimum_degree() {
257        let a = poisson(40);
258        let fill = |q: Vec<usize>| SparseLu::factor_with_order(&a, &q).unwrap().nnz();
259        let q = symamd(&a);
260        assert!(is_permutation(&q, a.nrows));
261        let (sy, co, md) = (fill(q), fill(colamd(&a)), fill(minimum_degree(&a)));
262        assert!(sy < co, "symmetric {sy} against column ordering {co}");
263        assert!((sy as f64) < 1.3 * md as f64, "{sy} against {md}");
264    }
265
266    #[test]
267    fn colamd_handles_rectangular_dense_and_empty_columns() {
268        // 150 x 170: column 3 is dense and columns 140..170 are empty.
269        let mut coo = CooMatrix::new(150, 170);
270        for i in 0..150 {
271            coo.push(i, 3, 1.0);
272            coo.push(i, i % 140, 2.0);
273            coo.push(i, (i + 7) % 140, 1.0);
274        }
275        let a = coo.to_csr().unwrap();
276        let q = colamd(&a);
277        assert!(is_permutation(&q, 170));
278        assert_eq!(q[139], 3, "the dense column comes after the others and before the empty ones");
279        assert!(q[140..].iter().all(|&c| c >= 140));
280    }
281
282    #[test]
283    fn minimum_degree_orderings_are_close_to_the_exact_one() {
284        let a = poisson(60);
285        let fill = |q: Vec<usize>| SparseLu::factor_with_order(&a, &q).unwrap().nnz();
286        let (amd, exact, nd, nat) = (fill(minimum_degree(&a)), fill(minimum_degree_exact(&a)), fill(nested_dissection(&a)), fill((0..a.nrows).collect()));
287        assert!(amd < nat / 3 && nd < nat / 3, "{amd} {nd} against natural {nat}");
288        assert!((amd as f64) < 1.1 * exact as f64, "approximate {amd} against exact {exact}");
289        assert!((nd as f64) < 1.3 * amd as f64, "nested dissection {nd} against {amd}");
290    }
291
292    #[test]
293    fn minimum_degree_handles_disconnected_and_dense_patterns() {
294        // Two components and an isolated vertex.
295        let mut coo = CooMatrix::new(7, 7);
296        for (i, j) in [(0, 1), (1, 2), (2, 0), (3, 4), (4, 5)] {
297            coo.push(i, j, 1.0);
298            coo.push(j, i, 1.0);
299        }
300        for i in 0..7 {
301            coo.push(i, i, 4.0);
302        }
303        let a = coo.to_csr().unwrap();
304        assert!(is_permutation(&minimum_degree(&a), 7));
305        // A dense matrix and an arrowhead.
306        let mut d = CooMatrix::new(30, 30);
307        for i in 0..30 {
308            for j in 0..30 {
309                d.push(i, j, if i == j { 40.0 } else { 1.0 });
310            }
311        }
312        let q = minimum_degree(&d.to_csr().unwrap());
313        assert!(is_permutation(&q, 30));
314        let mut arrow = CooMatrix::new(40, 40);
315        for i in 0..40 {
316            arrow.push(i, i, 4.0);
317            arrow.push(0, i, 1.0);
318            arrow.push(i, 0, 1.0);
319        }
320        let arrow = arrow.to_csr().unwrap();
321        let q = minimum_degree(&arrow);
322        let nnz = |q: &[usize]| SparseLu::factor_with_order(&arrow, q).unwrap().nnz();
323        let natural: Vec<usize> = (0..40).collect();
324        assert_eq!(nnz(&q), nnz(&minimum_degree_exact(&arrow)), "no fill beyond the arrowhead");
325        assert!(nnz(&q) * 5 < nnz(&natural), "the hub first (natural order) fills the matrix");
326    }
327
328    #[test]
329    fn incomplete_cholesky_preconditions_cg() {
330        let a = poisson(30);
331        let b: Vec<f64> = (0..a.nrows).map(|i| (i as f64 * 0.3).sin()).collect();
332        let o = IterativeOptions { rtol: 1e-10, ..Default::default() };
333        let plain = cg(&a, &b, None, None, o).unwrap().iterations;
334        let ic0 = IncompleteCholesky::ic0(&a).unwrap();
335        assert_eq!(ic0.nnz(), (a.nnz() + a.nrows) / 2);
336        let with0 = cg(&a, &b, None, Some(&ic0), o).unwrap();
337        assert!(with0.converged && with0.iterations * 2 < plain, "{} vs {plain}", with0.iterations);
338        // ICT with no dropping is the exact factor: one iteration.
339        let exact = IncompleteCholesky::ict(&a, 0.0, usize::MAX).unwrap();
340        assert!(cg(&a, &b, None, Some(&exact), o).unwrap().iterations <= 2);
341        let ict = IncompleteCholesky::ict(&a, 1e-2, 12).unwrap();
342        assert!(cg(&a, &b, None, Some(&ict), o).unwrap().iterations < with0.iterations);
343    }
344
345    #[test]
346    fn refactoring_with_new_values_matches_a_fresh_factorisation() {
347        let a = poisson(12);
348        let n = a.nrows;
349        let lu = SparseLu::factor(&a, Ordering::MinimumDegree).unwrap();
350        // The same pattern, new values: a Newton matrix `I h − J` with another step size.
351        let shifted = a.add(1.0, &CsrMatrix::identity(n), 3.7).unwrap();
352        let b: Vec<f64> = (0..n).map(|i| (i as f64 * 0.7).cos()).collect();
353        let re = lu.refactor(&shifted).unwrap();
354        let fresh = SparseLu::factor_with_order(&shifted, &minimum_degree(&a)).unwrap();
355        let (x1, x2) = (re.solve(&b).unwrap(), fresh.solve(&b).unwrap());
356        assert!(x1.iter().zip(&x2).all(|(p, q)| (p - q).abs() < 1e-12), "{:?}", &x1[..3]);
357        let r = shifted.matvec(&x1);
358        assert!(r.iter().zip(&b).all(|(p, q)| (p - q).abs() < 1e-10));
359        assert_eq!(re.nnz(), lu.nnz());
360        // A different pattern is refused, and so is a matrix that the pivot sequence does not suit.
361        let mut off = CooMatrix::new(n, n);
362        for i in 0..n {
363            for p in a.indptr[i]..a.indptr[i + 1] {
364                off.push(i, a.indices[p], a.data[p]);
365            }
366        }
367        off.push(0, n - 1, 0.5); // an entry outside the pattern
368        assert!(lu.refactor(&off.to_csr().unwrap()).is_err());
369        let mut coo = CooMatrix::new(n, n);
370        for i in 0..n {
371            for p in a.indptr[i]..a.indptr[i + 1] {
372                // Make the diagonal tiny and the off-diagonals large: the old pivots are poor.
373                coo.push(i, a.indices[p], if a.indices[p] == i { 1e-9 } else { 1.0 });
374            }
375        }
376        assert!(lu.refactor(&coo.to_csr().unwrap()).is_err());
377    }
378
379    #[test]
380    fn incomplete_cholesky_of_level_k_and_modified() {
381        let a = poisson(30);
382        let b: Vec<f64> = (0..a.nrows).map(|i| (i as f64 * 0.3).sin()).collect();
383        let o = IterativeOptions { rtol: 1e-10, ..Default::default() };
384        let iters = |m: &IncompleteCholesky| cg(&a, &b, None, Some(m), o).unwrap().iterations;
385        // Level 0 is IC(0): the same factor, and the same iteration count.
386        let ic0 = IncompleteCholesky::ic0(&a).unwrap();
387        let l0 = IncompleteCholesky::ic_k(&a, 0, false).unwrap();
388        assert_eq!(l0.nnz(), ic0.nnz());
389        assert_eq!(iters(&l0), iters(&ic0));
390        // More levels: more fill, fewer iterations; enough levels give the exact factor.
391        let (l1, l2) = (IncompleteCholesky::ic_k(&a, 1, false).unwrap(), IncompleteCholesky::ic_k(&a, 2, false).unwrap());
392        assert!(l0.nnz() < l1.nnz() && l1.nnz() < l2.nnz());
393        assert!(iters(&l1) < iters(&l0) && iters(&l2) < iters(&l1), "{} {} {}", iters(&l0), iters(&l1), iters(&l2));
394        let full = IncompleteCholesky::ic_k(&a, 1000, false).unwrap();
395        assert!(iters(&full) <= 2);
396        // MIC(0): L Lᵀ has the row sums of A (the Poisson matrix needs no shift), and takes fewer
397        // iterations than IC(0) (36 → 26 here; the gap widens with the grid).
398        let mic = IncompleteCholesky::ic_k(&a, 0, true).unwrap();
399        assert_eq!(mic.shift(), 0.0);
400        let ones = vec![1.0; a.nrows];
401        let back = mic.solve(&a.matvec(&ones));
402        assert!(back.iter().all(|v| (v - 1.0).abs() < 1e-9), "{:?}", &back[..3]);
403        assert!(iters(&mic) < iters(&l0), "{} vs {}", iters(&mic), iters(&l0));
404    }
405
406    #[test]
407    fn ordered_incomplete_cholesky_preconditions_the_original_system() {
408        // A Laplacian numbered in a scrambled order: the same matrix up to a permutation.
409        let m = 25;
410        let a0 = poisson(m);
411        let n = a0.nrows;
412        let scramble: Vec<usize> = (0..n).map(|i| (i * 211) % n).collect(); // 211 is coprime with 625
413        let (mut r, mut c, mut v) = (Vec::new(), Vec::new(), Vec::new());
414        for i in 0..n {
415            for p in a0.indptr[i]..a0.indptr[i + 1] {
416                r.push(scramble[i]);
417                c.push(scramble[a0.indices[p]]);
418                v.push(a0.data[p]);
419            }
420        }
421        let a = CsrMatrix::from_triplets(n, n, &r, &c, &v).unwrap();
422        let b: Vec<f64> = (0..n).map(|i| (i as f64 * 0.3).sin()).collect();
423        let o = IterativeOptions { rtol: 1e-10, ..Default::default() };
424        let iters = |ic: &IncompleteCholesky| cg(&a, &b, None, Some(ic), o).unwrap().iterations;
425        let natural = IncompleteCholesky::ordered(&a, IcOrdering::Natural, |m| IncompleteCholesky::ic_k(m, 1, false)).unwrap();
426        let rcm = IncompleteCholesky::ordered(&a, IcOrdering::ReverseCuthillMcKee, |m| IncompleteCholesky::ic_k(m, 1, false)).unwrap();
427        let amd = IncompleteCholesky::ordered(&a, IcOrdering::MinimumDegree, |m| IncompleteCholesky::ic_k(m, 1, false)).unwrap();
428        // The exact factor, in any order, solves in one or two iterations: the permutation is applied right.
429        let exact = IncompleteCholesky::ordered(&a, IcOrdering::MinimumDegree, |m| IncompleteCholesky::ic_k(m, 1000, false)).unwrap();
430        assert!(iters(&exact) <= 2, "{}", iters(&exact));
431        // Ordering restores the structure that the scrambled numbering hid.
432        assert!(iters(&rcm) < iters(&natural), "{} vs {}", iters(&rcm), iters(&natural));
433        assert!(iters(&amd) > 0 && cg(&a, &b, None, Some(&amd), o).unwrap().converged);
434    }
435
436    #[test]
437    fn incomplete_cholesky_shifts_on_breakdown() {
438        // An SPD matrix whose IC(0) breaks down without a shift: a diagonally weak M-matrix variant.
439        let n = 40;
440        let mut coo = CooMatrix::new(n, n);
441        for i in 0..n {
442            coo.push(i, i, 1.0);
443            for d in [1usize, 2, 3] {
444                if i + d < n {
445                    coo.push(i, i + d, 0.3);
446                    coo.push(i + d, i, 0.3);
447                }
448            }
449        }
450        let a = coo.to_csr().unwrap();
451        let ic = IncompleteCholesky::ic0(&a).unwrap();
452        assert!(ic.shift() >= 0.0);
453        let b = vec![1.0; n];
454        let o = IterativeOptions { rtol: 1e-9, ..Default::default() };
455        assert!(cg(&a, &b, None, Some(&ic), o).unwrap().converged);
456        assert!(IncompleteCholesky::ic0_shifted(&poisson(3).add(1.0, &CsrMatrix::identity(9), -5.0).unwrap(), 0.0).is_err());
457    }
458
459    use num_complex::Complex;
460
461    /// A complex symmetric (not Hermitian) matrix: the 5-point Laplacian plus `shift + i damping`.
462    fn helmholtz(m: usize, shift: f64, damping: f64) -> ComplexCsrMatrix {
463        let real = poisson(m);
464        let n = m * m;
465        let mut coo = ComplexCooMatrix::new(n, n);
466        for i in 0..n {
467            for p in real.indptr[i]..real.indptr[i + 1] {
468                coo.push(i, real.indices[p], Complex::new(real.data[p], 0.0));
469            }
470            coo.push(i, i, Complex::new(shift, damping));
471        }
472        coo.to_csr().unwrap()
473    }
474
475    fn crhs(n: usize) -> Vec<Complex<f64>> {
476        (0..n).map(|i| Complex::new(((i * 7) % 11) as f64 - 5.0, ((i * 3) % 5) as f64 - 2.0)).collect()
477    }
478
479    fn cresidual(a: &ComplexCsrMatrix, x: &[Complex<f64>], b: &[Complex<f64>]) -> f64 {
480        a.matvec(x).iter().zip(b).map(|(p, q)| (p - q).norm_sqr()).sum::<f64>().sqrt()
481    }
482
483    #[test]
484    fn complex_matrices_products_and_conversions() {
485        let a = helmholtz(5, 1.0, 0.7);
486        let d = a.to_dense();
487        // Round trip through dense, and the products against dense ones.
488        assert_eq!(ComplexCsrMatrix::from_dense(&d, 0.0), a);
489        let at = a.adjoint();
490        let dense_adj = d.t().mapv(|v| v.conj());
491        assert!((at.to_dense() - &dense_adj).iter().all(|v| v.norm() < 1e-15));
492        let p = a.matmul(&at).unwrap().to_dense();
493        assert!((p - d.dot(&dense_adj)).iter().all(|v| v.norm() < 1e-13));
494        let x = crhs(25);
495        let dense_ax: Vec<Complex<f64>> = (0..25).map(|i| (0..25).map(|j| d[(i, j)] * x[j]).sum()).collect();
496        assert!(a.matvec(&x).iter().zip(&dense_ax).all(|(p, q)| (p - q).norm() < 1e-13));
497        assert!(a.rmatvec(&x).iter().zip(at.matvec(&x)).all(|(p, q)| (p - q).norm() < 1e-13));
498        // From real and imaginary parts, and the sum.
499        let re = poisson(5);
500        let im = CsrMatrix::identity(25);
501        let z = ComplexCsrMatrix::from_real_imag(&re, &im).unwrap();
502        assert_eq!(z.diagonal()[3], Complex::new(4.0, 1.0));
503        let s = z.add(Complex::new(2.0, 0.0), &z.conj(), Complex::new(0.0, 0.0)).unwrap();
504        assert_eq!(s.diagonal()[0], Complex::new(8.0, 2.0));
505    }
506
507    #[test]
508    fn complex_direct_and_krylov_solvers_agree() {
509        let a = helmholtz(12, 1.5, 0.8);
510        let n = a.nrows;
511        let b = crhs(n);
512        for ordering in [Ordering::Natural, Ordering::ReverseCuthillMcKee, Ordering::MinimumDegree] {
513            let x = ComplexSparseLu::factor(&a, ordering).unwrap().solve(&b).unwrap();
514            assert!(cresidual(&a, &x, &b) < 1e-10, "{ordering:?}");
515        }
516        assert!(cresidual(&a, &spsolve_complex(&a, &b).unwrap(), &b) < 1e-10);
517        assert!(cresidual(&a, &spsolve_complex_colamd(&a, &b).unwrap(), &b) < 1e-10);
518        let o = IterativeOptions { rtol: 1e-10, ..Default::default() };
519        let jac = ComplexJacobi::new(&a).unwrap();
520        for r in [gmres_complex(&a, &b, None, None, 30, o).unwrap(), gmres_complex(&a, &b, None, Some(&jac), 30, o).unwrap(), bicgstab_complex(&a, &b, None, None, o).unwrap(), bicgstab_complex(&a, &b, None, Some(&jac), o).unwrap()] {
521            assert!(r.converged && cresidual(&a, &r.x, &b) < 1e-8 * norm2c(&b), "{} iterations", r.iterations);
522        }
523        // A singular matrix is refused.
524        let mut z = ComplexCooMatrix::new(2, 2);
525        z.push(0, 0, Complex::new(1.0, 0.0));
526        z.push(1, 0, Complex::new(2.0, 0.0));
527        assert!(ComplexSparseLu::factor(&z.to_csr().unwrap(), Ordering::Natural).is_err());
528    }
529
530    fn norm2c(v: &[Complex<f64>]) -> f64 {
531        v.iter().map(|z| z.norm_sqr()).sum::<f64>().sqrt()
532    }
533
534    #[test]
535    fn complex_cg_on_a_hermitian_positive_definite_matrix() {
536        // H = Bᴴ B + I with a complex banded B.
537        let n = 60;
538        let mut coo = ComplexCooMatrix::new(n, n);
539        for i in 0..n {
540            coo.push(i, i, Complex::new(2.0, 0.0));
541            if i + 1 < n {
542                coo.push(i, i + 1, Complex::new(-0.5, 0.7));
543                coo.push(i + 1, i, Complex::new(0.3, -0.2));
544            }
545        }
546        let bm = coo.to_csr().unwrap();
547        let h = bm.adjoint().matmul(&bm).unwrap().add(Complex::new(1.0, 0.0), &ComplexCsrMatrix::from_dense(&ndarray::Array2::from_shape_fn((n, n), |(i, j)| if i == j { Complex::new(1.0, 0.0) } else { Complex::new(0.0, 0.0) }), 0.0), Complex::new(1.0, 0.0)).unwrap();
548        let b = crhs(n);
549        let o = IterativeOptions { rtol: 1e-12, ..Default::default() };
550        let r = cg_complex(&h, &b, None, None, o).unwrap();
551        assert!(r.converged && cresidual(&h, &r.x, &b) < 1e-9, "{}", r.iterations);
552        let x = spsolve_complex(&h, &b).unwrap();
553        assert!(r.x.iter().zip(&x).all(|(p, q)| (p - q).norm() < 1e-8));
554        let jac = ComplexJacobi::new(&h).unwrap();
555        assert!(cg_complex(&h, &b, None, Some(&jac), o).unwrap().converged);
556    }
557}