Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Sparse matrices and iterative solvers

ProblemStore, multiply and solve with large matrices that are mostly zeros, and find a few of their eigenvalues or singular values
Devised byMagnus Hestenes and Eduard Stiefel (1952), conjugate gradients; Cornelius Lanczos (1950), the Lanczos process; Walter Arnoldi (1951), the Arnoldi process; Danny Sorensen (1992) and G. W. Stewart (2001), restarted Arnoldi; Elizabeth Cuthill and James McKee (1969), bandwidth reduction; Christopher Paige and Michael Saunders (1975, 1982), MINRES and LSQR; Youcef Saad and Martin Schultz (1986), GMRES; Allison Baker, Elizabeth Jessup and Thomas Manteuffel (2005), LGMRES; Henk van der Vorst (1992), BiCGSTAB; John Gilbert and Tim Peierls (1988), sparse LU in time proportional to the arithmetic; William Tinney and John Walker (1967), minimum degree; Alan George (1973), nested dissection; Timothy Davis, John Gilbert, Stefan Larimore and Esmond Ng (2004), COLAMD; Koos Meijerink and Henk van der Vorst (1977), Thomas Manteuffel (1980) and Yousef Saad (1994), incomplete LU and Cholesky; Awad Al-Mohy and Nicholas Higham (2011), the action of the matrix exponential
AccuracyDirect solves agree with SciPy to ; iterative solves reach the requested residual and take the same number of iterations as SciPy within a few; eigenvalues and singular values agree to
CostStorage and a product with : . Iterative solvers: one or two products per iteration, plus (CG, MINRES, BiCGSTAB) or at inner step (GMRES). Sparse LU: proportional to the arithmetic on the fill
Read firstGaussian elimination and LU factorisation, Eigenvalue algorithms, The singular value decomposition
APIsparse: CsrMatrix, spsolve, SparseLu, cg, minres, gmres, lgmres, LgmresSolver, bicgstab, lsqr, eigsh, svds, eigsh_shift_invert, eigs, eigs_shift_invert, reverse_cuthill_mckee, minimum_degree, colamd, nested_dissection, Ilu, IncompleteCholesky, expm_multiply

Overview

Discretised differential equations, networks and least-squares problems with local couplings produce matrices with millions of rows but only a few non-zero entries in each. Such a matrix, with , takes 8 TB as a dense array but a few tens of megabytes in sparse storage. Dense factorisations are then impossible: the operations take hours and the factors fill memory. Two families of methods work instead:

  • Direct sparse methods factorise while keeping the factors sparse. Their cost depends on the fill-in, the new non-zeros created by elimination, which depends strongly on the order of the rows and columns.
  • Iterative (Krylov) methods use only through products . They build the solution from the Krylov subspace and need only a few vectors of memory. The same subspaces give the extreme eigenvalues by the Lanczos process.

The module follows scipy.sparse and scipy.sparse.linalg:

  • COO, CSR and CSC storage;
  • spsolve and a sparse LU with minimum-degree or reverse Cuthill-McKee ordering;
  • cg, minres, gmres, lgmres, bicgstab and lsqr, with Jacobi and incomplete-LU preconditioners;
  • eigsh (with a shift-invert mode) and svds;
  • expm_multiply;
  • reverse_cuthill_mckee from scipy.sparse.csgraph. Every solver takes a LinearOperator, so a matrix that is never stored, only applied, works as well.

Where it is used

Large problems are almost always sparse, and everything depends on exploiting it.

  • Engineering simulation. Finite-element and finite-difference models of structures, fluids and electromagnetics have millions of unknowns and a few non-zeros per row.
  • Networks and the web. Adjacency matrices of graphs; PageRank is an eigenproblem on a sparse matrix.
  • Circuit simulation. The nodal matrix of an integrated circuit has non-zeros only where components connect.
  • Optimisation and machine learning. Sparse linear algebra underlies interior-point solvers and large regression problems.
  • Iterative solvers. Conjugate gradients, GMRES and preconditioning make solutions possible when direct factorisation would run out of memory.

History

Magnus Hestenes and Eduard Stiefel published conjugate gradients in 1952, as a direct method that terminates in steps. In floating point it did not, and the method was set aside until John Reid (1971) showed that it converges in far fewer than steps on large sparse systems. Cornelius Lanczos (1950) had proposed the tridiagonalisation behind it, also discarded for its loss of orthogonality until Christopher Paige’s thesis (1971) explained the loss and how to live with it.

For symmetric indefinite systems, Paige and Michael Saunders built MINRES (1975) from the same Lanczos recurrence, and in 1982 LSQR for least squares from the Golub-Kahan bidiagonalisation (1965). For nonsymmetric systems, Youcef Saad and Martin Schultz’s GMRES (1986) minimises the residual over the Krylov subspace using Arnoldi’s process (1951). Henk van der Vorst’s BiCGSTAB (1992) instead uses short recurrences, with no optimality, and became the most used alternative.

On the direct side, Elizabeth Cuthill and James McKee (1969) reordered structural engineering matrices to reduce their bandwidth, and Alan George (1971) noticed that reversing their order reduces fill further. John Gilbert and Tim Peierls (1988) showed how to compute a sparse LU with partial pivoting in time proportional to the arithmetic. Their left-looking algorithm is the core of later solvers such as SuperLU (used by SciPy) and KLU.

For eigenvalues of nonsymmetric matrices, Arnoldi’s process needs a growing basis, and a practical method needs restarts that keep what has been learnt. Yousef Saad (1980) restarted it explicitly from a combination of Ritz vectors. Danny Sorensen’s implicitly restarted Arnoldi (1992) applies the restart as shifted QR steps on the small Hessenberg matrix, and became ARPACK (Lehoucq, Sorensen and Yang, 1998), which SciPy’s eigs and eigsh call. G. W. Stewart’s Krylov-Schur method (2001) achieves the same by truncating a Schur form, which is simpler and more robust, and is the default in SLEPc.

The idea

Storage

A sparse matrix is assembled as a list of triplets (the COO format), where repeated positions add up. That is how finite-element matrices are built. For computation it is converted to compressed sparse rows (CSR). The column indices and values are stored row after row, with indptr[i] marking where row starts:

A product walks each row once, in operations. Compressed sparse columns (CSC) is the same layout for , natural for column-oriented elimination. Converting between them is a counting sort.

Krylov subspaces and conjugate gradients

For symmetric positive definite , solving is minimising , whose gradient is . Steepest descent zig-zags. Conjugate gradients chooses each search direction to be -conjugate to the previous ones, . Then each step minimises over all the directions so far, and minimises the -norm of the error over :

Each step costs one product with and a few vector operations. The error after steps is bounded through the condition number of :

The number of iterations grows like . For the 2-D Laplacian on an grid, , so about iterations are needed for each factor of in accuracy.

Preconditioning solves with cheap to apply, which lowers the effective condition number. The simplest choice is Jacobi, . It helps when the diagonal varies widely (Figure 7.15). Incomplete factorisations, below, go much further.

Incomplete LU preconditioning

An exact LU factorisation is the perfect preconditioner, with , but its fill makes it expensive. An incomplete factorisation keeps the factors sparse by discarding fill, and is applied by two sparse triangular solves:

  • ILU(0) (Meijerink and van der Vorst, 1977) performs Gaussian elimination row by row but discards every update outside the sparsity pattern of , so has exactly the pattern of .
  • ILUT(τ, p) (Saad, 1994) allows fill but drops each multiplier and each entry of the new row below . It then keeps only the largest entries in each of the and parts of the row. Smaller and larger give a more accurate and more expensive factorisation; with and it is the exact LU without pivoting.

SciPy’s spilu uses SuperLU’s threshold ILU, which also pivots and orders the columns, so the two are compared by their effect (Table 7.26) rather than entry by entry.

Incomplete Cholesky preconditioning

For a symmetric positive definite an incomplete factor needs half the storage of ILU and keeps the preconditioner symmetric positive definite, as conjugate gradients require. The factors are the same two kinds:

  • IC(0) keeps the pattern of the lower triangle of . It is the Cholesky recurrences , , evaluated only at entries inside the pattern.
  • IC(k) (IncompleteCholesky::ic_k(A, k, modified)) keeps the entries whose level of fill is at most : entries of have level 0, and an entry created by eliminating column from entries of levels and has level . is IC(0), and a large the exact factor. With modified, each update that falls outside the pattern is subtracted from the two diagonal entries it would have changed (MIC, Gustafsson 1978), so that has the row sums of . For the Laplacian this lowers the condition number of the preconditioned system from to . It needs a right-looking elimination, since the compensation changes diagonals that are not yet used.
  • IncompleteCholesky::ordered(A, IcOrdering::{Natural, ReverseCuthillMcKee, MinimumDegree}, |m| factor(m)) factors for the chosen ordering and applies the permutation in solve, so the result is used like any other factor. A matrix numbered at random loses the structure that IC(k) and ICT rely on; the ordering restores it.
  • SparseLu::refactor(&new_matrix) redoes only the numerical part of a factorisation for a matrix with the same sparsity pattern: the column order, the pivot rows and the structure of and are kept, so there is no search for the reach of each column. It refuses (and the caller factors afresh) when a pivot falls below a tenth of the largest candidate of its column or an update would leave the stored structure. The ODE solvers use it for their Newton matrices.
  • ICT(τ, p) allows fill, but drops each entry of row below and keeps only the largest. With and it is the exact Cholesky factor.

Unlike the complete factorisation, an incomplete one can break down on a positive definite matrix: the dropped terms leave a pivot that is zero or negative, and the square root fails. Manteuffel’s shift (1980) factorises instead. As grows the matrix becomes diagonally dominant, for which the incomplete factorisation always exists. The library tries , then , doubling after each failure, and reports the value used.

Other Krylov methods

  • MINRES minimises over the same subspace, for any symmetric , indefinite included. The Lanczos process gives with tridiagonal (). The residual minimisation becomes a small least-squares problem with , updated by one Givens rotation per step.
  • GMRES does the same for nonsymmetric , with Arnoldi’s process: with upper Hessenberg. Each step orthogonalises against every previous basis vector, so the work and storage grow with . Restarting after steps, written GMRES(), bounds them, but it can slow convergence or stall it.
  • LGMRES (Baker, Jessup and Manteuffel, 2005) recovers some of what a restart discards. Each correction found by a cycle approximates the error, and the last few of them (outer_k, default 3) are appended to the next cycle’s Krylov basis. The cycle then minimises the residual over both. Restarted GMRES tends to alternate between similar search spaces from one cycle to the next, and the augmentation vectors damp this. SciPy’s newton_krylov uses LGMRES by default, and keeps the augmentation vectors from one Newton step to the next.
  • BiCGSTAB uses short recurrences for nonsymmetric , with two products per step and constant storage. It has no minimisation property, and its residual can jump, as in Figure 7.14.
  • LSQR solves for rectangular . It is mathematically CG on the normal equations , but it is built from the Golub-Kahan bidiagonalisation and never squares the condition number.

The Lanczos process for eigenvalues

The Lanczos vectors of a symmetric give tridiagonal. The eigenvalues of , the Ritz values, approximate the extreme eigenvalues of after far fewer than steps. The eigenvector of gives the Ritz vector , whose residual norm is known without forming it:

eigsh runs Lanczos with full reorthogonalisation, which keeps orthonormal in floating point at a cost of . It doubles until the wanted residuals are below the tolerance. svds does the same with Golub-Kahan bidiagonalisation, , whose bidiagonal has the singular values as Ritz values.

A single Krylov subspace contains only one direction from each eigenspace, so a repeated eigenvalue appears only once. On the square grid, , so most eigenvalues of the Laplacian are double. Both functions therefore deflate. After a run they lock the converged vectors, run again in their orthogonal complement, and keep the best of the union, until a run finds nothing better. Two details matter. The locked vectors and the Lanczos basis must be projected out together in each Gram-Schmidt pass: projecting against one set after the other reintroduces the first, amplified by the Lanczos coefficients at every step. And the start vector of each run must be orthogonal to the locked vectors.

Shift-invert. Lanczos finds the extreme eigenvalues quickly and interior ones slowly. The eigenvalues of nearest a shift are the largest in magnitude of , . So eigsh_shift_invert factorises once by sparse LU, and runs Lanczos on the operator that solves with it. Each product costs a pair of sparse triangular solves, and convergence takes a few dozen steps.

The Arnoldi process and Krylov-Schur restarts

For a nonsymmetric , the Gram-Schmidt process on the Krylov vectors no longer stops after two terms. Each new vector is orthogonalised against all the previous ones, and the coefficients fill an upper Hessenberg matrix :

The eigenvalues of are the Ritz values, now complex in general. As for Lanczos, the Ritz vector has residual norm , where is the unit eigenvector of .

Arnoldi’s basis costs memory and work, so must stay small, and the subspace has to be restarted. A good restart keeps the wanted part of the subspace and discards the rest. The Krylov-Schur method does this with the Schur form , which the library computes in complex arithmetic:

  1. Reorder by plane rotations that swap adjacent diagonal entries, until the wanted Ritz values come first.
  2. The leading Schur vectors span an invariant subspace of , . Then : a factorisation of size , with a full row in place of .
  3. Continue the Arnoldi process from back to vectors. The small matrix is now Hessenberg apart from its row , which does not matter: its eigenvalues are still the Ritz values, and the residual formula still holds.

A real matrix has eigenvalues in conjugate pairs. When the kept set contains both members of every pair, the span of is the complexification of a real subspace, and has rank exactly . Its leading left singular vectors give a real orthonormal basis . So the restart, and all the work on long vectors, stays in real arithmetic.

Each restart acts as a polynomial filter. In exact arithmetic it is the same as Sorensen’s implicit restart with the discarded Ritz values as shifts: their components are removed from the start vector, and the wanted ones grow. Shift-invert applies to eigs as it does to eigsh: the eigenvalues nearest become the largest in magnitude of .

The action of the matrix exponential

The solution of is . For a large sparse , the matrix is dense, but its action on one vector can be computed from products with alone (Al-Mohy and Higham, 2011). Shift by the mean of its eigenvalues, , to reduce its norm. Then

and each factor is applied as the truncated Taylor series . The degree and the number of steps minimise the work subject to a backward-error bound. The bound says that terms suffice when , for tabulated (). For large norms, the bound uses instead. For non-normal matrices this can be much smaller than . SciPy estimates these norms; the library computes them exactly from sparse matrix powers. Each Taylor sum stops early once two consecutive terms are negligible.

Ordering and fill-in

Eliminating a variable couples all its neighbours, which creates fill. For a banded matrix of half-bandwidth , LU without pivoting stays inside the band, at a cost of operations. Reverse Cuthill-McKee reduces the bandwidth by a breadth-first search on the graph of . It starts from a vertex of low degree, visits neighbours in order of increasing degree, and reverses the order at the end. Each breadth-first level becomes a block of consecutive indices. The 2-D Laplacian with its unknowns shuffled has bandwidth 135. After RCM it has bandwidth 12, the grid side:

Figure 7.12. The non-zeros of the 5-point Laplacian on a 12 × 12 grid, with its unknowns in random order (left) and after reverse Cuthill-McKee (right).

Bandwidth is a crude measure. The minimum-degree heuristic (Tinney and Walker, 1967) reduces fill more directly. Eliminating a vertex of the elimination graph joins all its neighbours into a clique, so it chooses at every step a vertex of least degree, the one that creates the least fill locally. minimum_degree_exact does this literally, on an explicit elimination graph with a priority queue of degrees. minimum_degree follows the approximate minimum degree algorithm (AMD; Amestoy, Davis and Duff, 1996), which never forms the cliques. Eliminating a vertex turns it into an element, standing for the clique of its neighbours. The degree of a remaining vertex is bounded using the sizes of the elements it belongs to, so one elimination costs work proportional to the size of the new element and not to its square. Three devices keep the bound sharp and the work small:

  • Absorption. An element contained in a new element is deleted, and a vertex’s neighbours that the new element covers are dropped from its list.
  • Supervariables. Vertices left with the same neighbours and elements are indistinguishable. They are merged into one weighted vertex and eliminated together.
  • Mass elimination. A vertex whose only neighbour is the new element is eliminated with it.

On a 2-D grid, the fill grows like for any banded order but close to for minimum degree (Figure 7.16). Nested dissection achieves provably.

COLAMD (Davis, Gilbert, Larimore and Ng, 2004) orders the columns of an unsymmetric, even rectangular, matrix for LU with partial pivoting. Whatever rows the pivoting chooses, the fill of and lies within the pattern of the Cholesky factor of , so a good ordering of the columns is a minimum-degree ordering of the graph of . That graph is never formed, since can be far denser than . Instead each row of is an element, a clique of the columns it touches, as in the quotient-graph form of minimum degree. Eliminating a column merges the elements that contain it into one new element. The degree of any other column is bounded using only the sizes of its elements, so it is never computed exactly. Three devices keep this cheap and accurate:

  • Absorption. An element contained in a new element is deleted, which keeps the element lists short.
  • Supercolumns. Columns left with identical element lists are indistinguishable. They are merged into one weighted column and eliminated together.
  • Dense rows and columns. Rows with more than entries are ignored, since each would join almost every column into a clique. Dense columns, and empty ones, are placed last.

SciPy uses COLAMD as the default ordering of splu, so on unsymmetric matrices it is the one to compare with. On a symmetric matrix, a minimum-degree ordering of does better, because it uses the symmetry that COLAMD must assume away.

Nested dissection (George, 1973) is divide and conquer on the graph. A small set of vertices, a separator, splits the rest into two parts and with no edge between them. Numbering , then , then last confines the fill: no elimination in can touch , and what remains is a dense block on . Applying the same idea inside and gives the ordering. On an grid the separator is one line of points, the parts have points each, and the fill satisfies , which solves to for unknowns. The arithmetic is , against for banded orders. In three dimensions the separators are planes, giving fill and arithmetic.

Finding a small balanced separator is itself hard, and the practical methods are multilevel, as in METIS (Karypis and Kumar, 1998). nested_dissection follows that scheme:

  1. Coarsen. Match each vertex with the neighbour across its heaviest edge, in random order, and merge the pairs into one vertex whose weight is the sum. Repeat until the graph has about 40 vertices.
  2. Partition the small graph. Grow a region from each of a dozen seed vertices, adding vertices breadth first until it holds half the weight, and keep the partition with the smallest cut.
  3. Uncoarsen and refine. Project the partition onto the finer graph, and improve it there with passes of Fiduccia-Mattheyses: move the boundary vertex that most reduces the number of cut edges (even to a worse state, to climb over bumps) while keeping the parts balanced, and return to the best state seen.
  4. From edges to vertices. The cut edges form a bipartite graph between the two boundaries. The smallest set of vertices that touches every cut edge is a minimum vertex cover of that graph, and König’s theorem finds it from a maximum matching. It is the separator.

Pieces with at most 800 vertices, and every separator, are ordered by minimum degree, with the vertices that come later (the separators above) frozen as a halo: they take part in the degrees but are not eliminated. Disconnected pieces are handled one component at a time.

Algorithm

Conjugate gradients cg(A, b, x₀, M):

  1. , , , .
  2. While :
    1. , ;
    2. , ;
    3. , , , .

Sparse LU (Gilbert-Peierls), for each column of :

  1. Find the rows that the column’s non-zeros reach in the graph of the found so far, by depth-first search. These are exactly the rows that can be non-zero after the triangular solve, and the search returns them in a valid order.
  2. Solve with the columns of for those rows only.
  3. Entries in already-pivoted rows go to column of . Of the others, the largest in magnitude becomes the pivot, and the rest, divided by it, form column of .

COLAMD colamd(A): put every row of in the element list of each of its columns, and score each column by a bound on its degree in the graph of : the sum, over the rows it meets, of the row length minus one. Then repeat:

  1. Take the column of least score. Its new element is the union of the elements containing , which are removed. and the columns merged into it come next in the order.
  2. For every column and every other element containing , find . If it is zero, absorb .
  3. Set the score of to the least of , the old score plus , and .
  4. Merge columns of with identical element lists into supercolumns.

Approximate minimum degree minimum_degree(A), on the graph of . Start with the neighbour lists as the degrees, and no elements. Then repeat:

  1. Take a vertex of least approximate degree. Its new element is the union of its neighbours and of the elements that contain it, which are deleted.
  2. For every vertex : drop from its neighbour list the vertices that covers, drop deleted elements from its element list, and add to it.
  3. For every element that meets find , and delete if it is zero.
  4. Set the degree of to the least of the number of vertices left, its old degree plus , and .
  5. Eliminate with any left with no neighbour but , and merge vertices with identical lists.

Nested dissection nested_dissection(A), on the graph of :

  1. If the graph is disconnected, order each component separately. If it has at most 800 vertices, order it by halo minimum degree.
  2. Bisect it by the multilevel scheme and take the vertex separator from the cut edges.
  3. Order the two parts recursively, then by halo minimum degree.

IC(0) IncompleteCholesky::ic0(A), for each row in turn: let be the entries of row of left of the diagonal. For each non-zero in increasing , set , and subtract from for each entry of column of already computed, if is in the pattern. Then . ICT is the same with the pattern test replaced by dropping.

Complex matrices. The algorithms are those of the real case with complex arithmetic: the sparse LU pivots by modulus, so the stored multipliers are complex, and fill depends only on the pattern. The Krylov solvers use the inner product . CG needs a Hermitian positive definite , where is real. GMRES uses unitary Givens rotations with a real cosine, , , , , to triangularise the Hessenberg matrix; BiCGSTAB conjugates its first argument in each inner product.

eigsh(A, k): Lanczos with full reorthogonalisation for steps; the eigenvalues of ; if the wanted Ritz residuals exceed , double and repeat; then deflate as above.

eigs(A, k), with and :

  1. Extend the Arnoldi factorisation to vectors, orthogonalising each new vector twice by classical Gram-Schmidt.
  2. Compute the complex Schur form of , and reorder it so that the Ritz values come in order of preference, with each conjugate pair kept together.
  3. If the wanted Ritz residuals are below , return the Ritz pairs.
  4. Otherwise keep values (one more or one fewer if would split a pair), take the real basis of their Schur vectors, set , and , and go to step 1.

Implementation

impl CsrMatrix {
    /// Builds a CSR matrix from triplets, summing duplicates and sorting the column indices of
    /// each row: a counting sort by row, then by column within each row.
    pub fn from_triplets(nrows: usize, ncols: usize, rows: &[usize], cols: &[usize], values: &[f64]) -> Result<Self> {
        if rows.len() != cols.len() || rows.len() != values.len() {
            return Err(LinalgError::Shape("triplet arrays of different lengths".into()));
        }
        if rows.iter().any(|&r| r >= nrows) || cols.iter().any(|&c| c >= ncols) {
            return Err(LinalgError::Shape("an index lies outside the matrix".into()));
        }
        let mut count = vec![0usize; nrows + 1];
        for &r in rows {
            count[r + 1] += 1;
        }
        for i in 0..nrows {
            count[i + 1] += count[i];
        }
        let mut next = count.clone();
        let mut cols_sorted = vec![0usize; rows.len()];
        let mut vals_sorted = vec![0.0; rows.len()];
        for k in 0..rows.len() {
            let p = next[rows[k]];
            cols_sorted[p] = cols[k];
            vals_sorted[p] = values[k];
            next[rows[k]] += 1;
        }
        let mut indptr = vec![0usize; nrows + 1];
        let mut indices = Vec::with_capacity(rows.len());
        let mut data = Vec::with_capacity(rows.len());
        for i in 0..nrows {
            let mut entries: Vec<(usize, f64)> = (count[i]..count[i + 1]).map(|p| (cols_sorted[p], vals_sorted[p])).collect();
            entries.sort_by_key(|e| e.0);
            for (c, v) in entries {
                if indices.len() > indptr[i] && *indices.last().expect("non-empty") == c {
                    *data.last_mut().expect("non-empty") += v;
                } else {
                    indices.push(c);
                    data.push(v);
                }
            }
            indptr[i + 1] = indices.len();
        }
        Ok(CsrMatrix { nrows, ncols, indptr, indices, data })
    }
/// Conjugate gradients for symmetric positive definite `A` (SciPy's `cg`): each step minimises
/// the `A`-norm of the error over a growing Krylov subspace, with search directions that are
/// `A`-conjugate. With `M`, the preconditioned residual `z = M r` replaces `r` in the recurrences.
pub fn cg(a: &dyn LinearOperator, b: &[f64], x0: Option<&[f64]>, m: Option<&dyn LinearOperator>, options: IterativeOptions) -> Result<IterativeResult> {
    let mut x = setup(a, b, x0)?;
    let tol = (options.rtol * norm(b)).max(options.atol);
    let max_it = options.max_iterations.unwrap_or(10 * b.len());
    let mut r = residual(a, b, &x);
    let mut history = vec![norm(&r)];
    let mut z = precondition(m, &r);
    let mut p = z.clone();
    let mut rz = dot(&r, &z);
    let mut it = 0;
    while history[history.len() - 1] > tol && it < max_it {
        let ap = a.matvec(&p);
        let alpha = rz / dot(&p, &ap);
        axpy(&mut x, alpha, &p);
        axpy(&mut r, -alpha, &ap);
        it += 1;
        history.push(norm(&r));
        z = precondition(m, &r);
        let rz_new = dot(&r, &z);
        let beta = rz_new / rz;
        rz = rz_new;
        p = z.iter().zip(&p).map(|(zi, pi)| zi + beta * pi).collect();
    }
    let converged = history[history.len() - 1] <= tol;
    Ok(IterativeResult { x, iterations: it, converged, residual_history: history })
}
/// Restarted GMRES(`restart`) for general square `A` (SciPy's `gmres`, default restart 20): the
/// Arnoldi process builds an orthonormal Krylov basis, and Givens rotations keep the small least-
/// squares problem for the residual-minimising combination triangular, which gives the residual
/// norm at every step without forming `x`. Right preconditioning, `A M y = b`, `x = M y`.
pub fn gmres(a: &dyn LinearOperator, b: &[f64], x0: Option<&[f64]>, m: Option<&dyn LinearOperator>, restart: usize, options: IterativeOptions) -> Result<IterativeResult> {
    let mut x = setup(a, b, x0)?;
    let n = b.len();
    let restart = restart.clamp(1, n.max(1));
    let tol = (options.rtol * norm(b)).max(options.atol);
    let max_it = options.max_iterations.unwrap_or(10 * n);
    let mut r = residual(a, b, &x);
    let mut history = vec![norm(&r)];
    let mut it = 0;
    while history[history.len() - 1] > tol && it < max_it {
        let beta = norm(&r);
        let mut basis: Vec<Vec<f64>> = vec![r.iter().map(|v| v / beta).collect()];
        let mut h = vec![vec![0.0; restart]; restart + 1];
        let (mut cs, mut sn) = (vec![0.0; restart], vec![0.0; restart]);
        let mut g = vec![0.0; restart + 1];
        g[0] = beta;
        let mut k_done = 0;
        for k in 0..restart {
            let mut w = a.matvec(&precondition(m, &basis[k]));
            // Modified Gram-Schmidt.
            for (j, vj) in basis.iter().enumerate() {
                h[j][k] = dot(&w, vj);
                axpy(&mut w, -h[j][k], vj);
            }
            h[k + 1][k] = norm(&w);
            // Apply the previous rotations to the new column, then a new rotation.
            for j in 0..k {
                let t = cs[j] * h[j][k] + sn[j] * h[j + 1][k];
                h[j + 1][k] = -sn[j] * h[j][k] + cs[j] * h[j + 1][k];
                h[j][k] = t;
            }
            let denom = h[k][k].hypot(h[k + 1][k]);
            cs[k] = h[k][k] / denom;
            sn[k] = h[k + 1][k] / denom;
            h[k][k] = denom;
            h[k + 1][k] = 0.0;
            g[k + 1] = -sn[k] * g[k];
            g[k] *= cs[k];
            it += 1;
            k_done = k + 1;
            history.push(g[k + 1].abs());
            if g[k + 1].abs() <= tol || it >= max_it {
                break;
            }
            let hk1 = h_norm(&w);
            if hk1 == 0.0 {
                break;
            }
            basis.push(w.iter().map(|v| v / hk1).collect());
        }
        // Back-substitution for y, then x += M V y.
        let mut y = vec![0.0; k_done];
        for i in (0..k_done).rev() {
            let s: f64 = (i + 1..k_done).map(|j| h[i][j] * y[j]).sum();
            y[i] = (g[i] - s) / h[i][i];
        }
        let mut update = vec![0.0; n];
        for (j, yj) in y.iter().enumerate() {
            axpy(&mut update, *yj, &basis[j]);
        }
        let dx = precondition(m, &update);
        axpy(&mut x, 1.0, &dx);
        r = residual(a, b, &x);
        let true_norm = norm(&r);
        let last = history.len() - 1;
        history[last] = true_norm;
    }
    let converged = history[history.len() - 1] <= tol;
    Ok(IterativeResult { x, iterations: it, converged, residual_history: history })
}
    /// Solves `A x = b`, with an optional left preconditioner `M ≈ A⁻¹`. Each cycle runs flexible
    /// GMRES on `M A` from the preconditioned residual over `inner_m` Krylov vectors plus the
    /// kept error approximations `z` (with `M A z`), and the correction it finds becomes a new
    /// augmentation vector. A cycle stops early at a relative residual `ptol`, which adapts: it
    /// tightens when a cycle reaches it, and relaxes when one does not.
    /// `options.max_iterations` is the number of cycles (SciPy's `maxiter`, default 1000).
    pub fn solve(&mut self, a: &dyn LinearOperator, b: &[f64], x0: Option<&[f64]>, m: Option<&dyn LinearOperator>, options: IterativeOptions) -> Result<IterativeResult> {
        let (rows, cols) = a.shape();
        if rows != cols || b.len() != rows {
            return Err(LinalgError::Shape(format!("operator {rows} × {cols} with right-hand side of length {}", b.len())));
        }
        let n = b.len();
        let psolve = |v: &[f64]| m.map_or_else(|| v.to_vec(), |m| m.matvec(v));
        let mut x = x0.map_or(vec![0.0; n], |v| v.to_vec());
        let b_norm = norm(b);
        let tol = options.atol.max(options.rtol * b_norm);
        let mut matvecs = 0;
        let mut history = Vec::new();
        if b_norm == 0.0 {
            return Ok(IterativeResult { x: vec![0.0; n], iterations: 0, converged: true, residual_history: vec![0.0] });
        }
        let mut ptol_max_factor: f64 = 1.0;
        let max_cycles = options.max_iterations.unwrap_or(1000);
        let mut converged = false;
        for _ in 0..max_cycles {
            let ax = a.matvec(&x);
            matvecs += 1;
            let r: Vec<f64> = ax.iter().zip(b).map(|(p, q)| p - q).collect();
            let r_norm = norm(&r);
            history.push(r_norm);
            if r_norm <= tol {
                converged = true;
                break;
            }
            let mut v0: Vec<f64> = psolve(&r).iter().map(|v| -v).collect();
            let inner_res_0 = norm(&v0);
            if inner_res_0 == 0.0 {
                return Err(LinalgError::Shape("lgmres: the preconditioner returned a zero vector".into()));
            }
            v0.iter_mut().for_each(|v| *v /= inner_res_0);
            let ptol = ptol_max_factor.min(tol / r_norm);
            // Flexible GMRES over [Krylov vectors, augmentation vectors].
            let total = self.inner_m + self.outer.len();
            let mut vs: Vec<Vec<f64>> = vec![v0.clone()];
            let mut zs: Vec<Vec<f64>> = Vec::new();
            let mut h: Vec<Vec<f64>> = Vec::new(); // columns of the Hessenberg matrix
            let (mut cs, mut sn): (Vec<f64>, Vec<f64>) = (Vec::new(), Vec::new());
            let mut g = vec![1.0];
            let mut pres = f64::NAN;
            let k_outer = self.outer.len();
            for j in 0..total {
                let (z, stored) = if self.prepend_outer_v && j < k_outer {
                    (self.outer[j].0.clone(), self.outer[j].1.clone())
                } else if self.prepend_outer_v && j == k_outer {
                    (v0.clone(), None)
                } else if !self.prepend_outer_v && j >= total - k_outer {
                    let o = &self.outer[j - (total - k_outer)];
                    (o.0.clone(), o.1.clone())
                } else {
                    (vs[vs.len() - 1].clone(), None)
                };
                let mut w = match stored {
                    Some(w) => w,
                    None => {
                        matvecs += 1;
                        psolve(&a.matvec(&z))
                    }
                };
                let w_norm = norm(&w);
                // Modified Gram-Schmidt against the basis.
                let mut col = vec![0.0; j + 2];
                for (i, v) in vs.iter().enumerate() {
                    col[i] = dot(v, &w);
                    w.iter_mut().zip(v).for_each(|(wi, vi)| *wi -= col[i] * vi);
                }
                col[j + 1] = norm(&w);
                // Written to treat a NaN norm as a breakdown, as SciPy does.
                let breakdown = col[j + 1].partial_cmp(&(f64::EPSILON * w_norm)) != Some(std::cmp::Ordering::Greater);
                if col[j + 1].is_finite() && col[j + 1] != 0.0 {
                    let s = col[j + 1];
                    w.iter_mut().for_each(|wi| *wi /= s);
                }
                vs.push(w);
                zs.push(z);
                // Givens rotations keep the least-squares problem triangular.
                for i in 0..j {
                    let t = cs[i] * col[i] + sn[i] * col[i + 1];
                    col[i + 1] = -sn[i] * col[i] + cs[i] * col[i + 1];
                    col[i] = t;
                }
                let denom = col[j].hypot(col[j + 1]);
                let (c, s) = if denom == 0.0 { (1.0, 0.0) } else { (col[j] / denom, col[j + 1] / denom) };
                cs.push(c);
                sn.push(s);
                col[j] = denom;
                col[j + 1] = 0.0;
                g.push(-s * g[j]);
                g[j] *= c;
                h.push(col);
                pres = g[j + 1].abs();
                if pres < ptol || breakdown {
                    break;
                }
            }
            let k = h.len();
            let mut y = vec![0.0; k];
            for i in (0..k).rev() {
                let s: f64 = (i + 1..k).map(|c| h[c][i] * y[c]).sum();
                y[i] = (g[i] - s) / h[i][i];
            }
            if y.iter().any(|v| !v.is_finite()) {
                return Ok(IterativeResult { x, iterations: matvecs, converged: false, residual_history: history });
            }
            y.iter_mut().for_each(|v| *v *= inner_res_0);
            ptol_max_factor = if pres > ptol { (1.5 * ptol_max_factor).min(1.0) } else { (0.25 * ptol_max_factor).max(1e-16) };
            let mut dx = vec![0.0; n];
            for (z, yc) in zs.iter().zip(&y) {
                dx.iter_mut().zip(z).for_each(|(d, zi)| *d += yc * zi);
            }
            let nx = norm(&dx);
            if nx > 0.0 {
                let w = self.store_outer_av.then(|| {
                    // M A dx = V_{k+1} H y, without a product. The columns hold R = G H after
                    // the rotations G, so H y = Gᵀ (R y), undoing the rotations in reverse.
                    let mut q = vec![0.0; k + 1];
                    for (i, qi) in q.iter_mut().enumerate().take(k) {
                        *qi = (i..k).map(|c| h[c][i] * y[c]).sum();
                    }
                    for i in (0..k).rev() {
                        let (a0, a1) = (q[i], q[i + 1]);
                        q[i] = cs[i] * a0 - sn[i] * a1;
                        q[i + 1] = sn[i] * a0 + cs[i] * a1;
                    }
                    let mut ax = vec![0.0; n];
                    for (v, qc) in vs.iter().zip(&q) {
                        ax.iter_mut().zip(v).for_each(|(s, vi)| *s += qc * vi);
                    }
                    ax.iter().map(|v| v / nx).collect::<Vec<f64>>()
                });
                self.outer.push((dx.iter().map(|v| v / nx).collect(), w));
            }
            while self.outer.len() > self.outer_k {
                self.outer.remove(0);
            }
            x.iter_mut().zip(&dx).for_each(|(xi, d)| *xi += d);
        }
        Ok(IterativeResult { x, iterations: matvecs, converged, residual_history: history })
    }
/// The reverse Cuthill-McKee ordering of the symmetric pattern of `A + Aᵀ` (SciPy's
/// `reverse_cuthill_mckee`): a breadth-first search from a vertex of low degree in each
/// connected component, visiting neighbours by increasing degree, then reversed. It concentrates
/// the entries near the diagonal (reduces the bandwidth), which limits fill-in during elimination.
pub fn reverse_cuthill_mckee(a: &CsrMatrix) -> Vec<usize> {
    let n = a.nrows.max(a.ncols);
    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
    for i in 0..a.nrows {
        for p in a.indptr[i]..a.indptr[i + 1] {
            let j = a.indices[p];
            if i != j {
                adj[i].push(j);
                adj[j].push(i);
            }
        }
    }
    for list in adj.iter_mut() {
        list.sort_unstable();
        list.dedup();
    }
    let degree: Vec<usize> = adj.iter().map(|l| l.len()).collect();
    let mut visited = vec![false; n];
    let mut order = Vec::with_capacity(n);
    let mut by_degree: Vec<usize> = (0..n).collect();
    by_degree.sort_by_key(|&v| degree[v]);
    for &start in &by_degree {
        if visited[start] {
            continue;
        }
        visited[start] = true;
        let mut queue = VecDeque::from([start]);
        while let Some(v) = queue.pop_front() {
            order.push(v);
            let mut next: Vec<usize> = adj[v].iter().copied().filter(|&w| !visited[w]).collect();
            next.sort_by_key(|&w| degree[w]);
            for w in next {
                visited[w] = true;
                queue.push_back(w);
            }
        }
    }
    order.reverse();
    order
}
/// `k` eigenvalues and eigenvectors of a symmetric operator (SciPy's `eigsh`). The Lanczos
/// process builds an orthonormal basis `Q` of the Krylov subspace in which `A` is tridiagonal,
/// `QᵀAQ = T`; the eigenvalues of `T` (Ritz values) approximate the extreme eigenvalues of `A`,
/// with residual norms `|β_m s_{m,i}|` known without forming the vectors. Full
/// reorthogonalisation keeps `Q` orthonormal in floating point; if the wanted Ritz values have not
/// converged to `tol` relative accuracy, the subspace is doubled.
pub fn eigsh(a: &dyn LinearOperator, k: usize, which: Which, tol: f64) -> Result<EigenPairs> {
    let (n, n2) = a.shape();
    if n != n2 || k == 0 || k > n {
        return Err(LinalgError::Shape(format!("need a square operator and 1 ≤ k ≤ n, got {n} × {n2}, k = {k}")));
    }
    let tol = if tol > 0.0 { tol } else { f64::EPSILON.sqrt() * 1e-2 };
    let mut pairs = with_deflation(k, n, |p: &(f64, Vec<f64>)| preference(which, p.0), |f| f.len(), |found| {
        let locked: Vec<Vec<f64>> = found.iter().map(|p| p.1.clone()).collect();
        lanczos(a, k, which, tol, &locked)
    })?;
    pairs.sort_by(|x, y| x.0.total_cmp(&y.0));
    let values = pairs.iter().map(|p| p.0).collect();
    let vectors = Array2::from_shape_fn((n, pairs.len()), |(r, c)| pairs[c].1[r]);
    Ok((values, vectors))
}

/// One Lanczos run in the orthogonal complement of `locked`: the `k` wanted Ritz pairs, the
/// subspace doubled until their residuals `|β_m s_{m,i}|` are below `tol` times the largest Ritz
/// value.
fn lanczos(a: &dyn LinearOperator, k: usize, which: Which, tol: f64, locked: &[Vec<f64>]) -> Result<Vec<(f64, Vec<f64>)>> {
    let n = a.shape().0;
    let room = n - locked.len();
    if room == 0 {
        return Ok(Vec::new());
    }
    let mut m = (2 * k + 1).max(20).min(room);
    loop {
        let mut q = vec![start_vector(n, locked)];
        let (mut alpha, mut beta) = (Vec::with_capacity(m), Vec::with_capacity(m));
        let mut last_beta = 0.0;
        for j in 0..m {
            let mut w = a.matvec(&q[j]);
            let aj = dot(&w, &q[j]);
            alpha.push(aj);
            reorthogonalise(&mut w, locked, &q);
            let b = norm(&w);
            let breakdown = b <= f64::EPSILON * aj.abs().max(1.0);
            last_beta = if breakdown { 0.0 } else { b };
            if j + 1 == m || breakdown {
                break;
            }
            beta.push(b);
            q.push(w.iter().map(|t| t / b).collect());
        }
        let size = alpha.len();
        let t = Array2::from_shape_fn((size, size), |(i, j)| if i == j { alpha[i] } else if i + 1 == j || j + 1 == i { beta[i.min(j)] } else { 0.0 });
        let (theta, s) = t.eigh(UPLO::Lower)?;
        let mut idx: Vec<usize> = (0..size).collect();
        idx.sort_by(|&x, &y| preference(which, theta[y]).total_cmp(&preference(which, theta[x])));
        let wanted: Vec<usize> = idx.into_iter().take(k).collect();
        let scale = theta.iter().fold(0.0f64, |acc, v| acc.max(v.abs())).max(f64::MIN_POSITIVE);
        let converged = wanted.iter().all(|&i| (last_beta * s[(size - 1, i)]).abs() <= tol * scale);
        if converged || size == room || size < m {
            return Ok(wanted
                .iter()
                .map(|&i| {
                    let mut v = vec![0.0; n];
                    for (j, qj) in q.iter().enumerate() {
                        let c = s[(j, i)];
                        v.iter_mut().zip(qj).for_each(|(vi, qi)| *vi += c * qi);
                    }
                    (theta[i], v)
                })
                .collect());
        }
        m = (2 * m).min(room);
    }
}
/// `k` eigenvalues and eigenvectors of a square operator (SciPy's `eigs`), by the Krylov-Schur
/// method. The Arnoldi process builds an orthonormal basis `V` of a Krylov subspace with
/// `A V = V H + f eₘᵀ`; the eigenvalues of the small `H` (Ritz values) approximate those of `A`,
/// with residuals `‖f‖ |eₘᵀ y|` known without forming the vectors. When the subspace reaches
/// `ncv` vectors, the Schur form of `H` is reordered to put the wanted Ritz values first, and
/// the factorisation is cut back to their invariant subspace: a real orthonormal basis of it, so
/// that the work stays in real arithmetic. The Arnoldi process then extends it again.
pub fn eigs(a: &dyn LinearOperator, k: usize, which: EigsWhich, options: &EigsOptions) -> Result<EigsResult> {
    let (n, n2) = a.shape();
    if n != n2 || k == 0 || k > n {
        return Err(LinalgError::Shape(format!("need a square operator and 1 ≤ k ≤ n, got {n} × {n2}, k = {k}")));
    }
    let m = options.ncv.unwrap_or((2 * k + 1).max(30)).clamp((k + 1).min(n), n);
    // Residual estimates of converged pairs settle at a few ε|θ|, which may lie just above ε|θ|.
    let tol = options.tol.max(8.0 * f64::EPSILON);
    let max_restarts = options.max_restarts.unwrap_or(10 * n);
    let mut v0 = match &options.v0 {
        Some(v) if v.len() == n && v.iter().any(|x| *x != 0.0) => v.clone(),
        Some(_) => return Err(LinalgError::Shape(format!("v0 must be a non-zero vector of length {n}"))),
        None => start_vector(n, &[]),
    };
    let nv = dot(&v0, &v0).sqrt();
    v0.iter_mut().for_each(|x| *x /= nv);
    let mut basis: Vec<Vec<f64>> = vec![v0];
    // H̄ is (m + 1) × m: A V[:, :j] = V[:, :j+1] H̄[:j+1, :j] for the columns built so far.
    let mut hbar = Array2::<f64>::zeros((m + 1, m));
    let (mut kept, mut restarts, mut matvecs) = (0, 0, 0);
    loop {
        // Extend the Arnoldi factorisation from `kept` to `m` columns.
        for j in kept..m {
            let mut w = a.matvec(&basis[j]);
            matvecs += 1;
            let wnorm = dot(&w, &w).sqrt();
            // Classical Gram-Schmidt, twice (the second pass restores orthogonality).
            for _ in 0..2 {
                let c: Vec<f64> = basis.iter().map(|v| dot(&w, v)).collect();
                for (v, ci) in basis.iter().zip(&c) {
                    w.iter_mut().zip(v).for_each(|(wi, vi)| *wi -= ci * vi);
                }
                for (i, ci) in c.iter().enumerate() {
                    hbar[(i, j)] += ci;
                }
            }
            let beta = dot(&w, &w).sqrt();
            if beta > 1e3 * f64::EPSILON * wnorm.max(f64::MIN_POSITIVE) {
                hbar[(j + 1, j)] = beta;
                basis.push(w.iter().map(|x| x / beta).collect());
            } else {
                // An invariant subspace: continue with a new direction, or a zero vector if
                // the basis already spans the whole space.
                hbar[(j + 1, j)] = 0.0;
                basis.push(if basis.len() < n { start_vector(n, &basis) } else { vec![0.0; n] });
            }
        }
        let beta_m = hbar[(m, m - 1)];
        let h = hbar.slice(s![..m, ..]).to_owned();
        let (mut t, mut z) = schur_complex(&h)?;
        let group = reorder(&mut t, &mut z, which);
        let hnorm = h.iter().map(|v| v * v).sum::<f64>().sqrt().max(f64::MIN_POSITIVE);
        let eps23 = f64::EPSILON.powf(2.0 / 3.0) * hnorm;
        let wanted = k.min(m);
        let ritz: Vec<Vec<C>> = (0..wanted).map(|i| {
            let s = triangular_eigenvector(&t, i);
            (0..m).map(|r| (0..=i).map(|c| z[(r, c)] * s[c]).sum()).collect()
        }).collect();
        let nconv = (0..wanted)
            .filter(|&i| {
                let y = &ritz[i];
                let ynorm = y.iter().map(|v| v.norm_sqr()).sum::<f64>().sqrt();
                beta_m * y[m - 1].norm() / ynorm <= tol * t[(i, i)].norm().max(eps23)
            })
            .count();
        if nconv >= wanted || restarts >= max_restarts || m == n {
            return Ok(finish(&basis, &t, &group, &ritz, n, m, nconv, wanted, restarts, matvecs));
        }
        restarts += 1;
        // Keep the wanted values and half of the rest, without splitting a conjugate pair.
        let mut p = (k + (m - k) / 2).min(m - 1);
        if p < m && p > 0 && group[p] == group[p - 1] {
            if p + 1 < m { p += 1 } else { p -= 1 }
        }
        // A real orthonormal basis of the invariant subspace spanned by the leading p Schur
        // vectors: it is closed under conjugation, so [Re Z_p, Im Z_p] has rank p.
        let w = Array2::from_shape_fn((m, 2 * p), |(r, c)| if c < p { z[(r, c)].re } else { z[(r, c - p)].im });
        let (u, _, _) = w.svd(true, false)?;
        let u = u.expect("requested").slice(s![.., ..p]).to_owned();
        let small = u.t().dot(&h).dot(&u);
        let mut new_basis: Vec<Vec<f64>> = (0..p).map(|c| {
            let mut v = vec![0.0; n];
            for (j, bj) in basis.iter().take(m).enumerate() {
                let coef = u[(j, c)];
                v.iter_mut().zip(bj).for_each(|(vi, b)| *vi += coef * b);
            }
            v
        }).collect();
        new_basis.push(basis[m].clone());
        basis = new_basis;
        hbar.fill(0.0);
        hbar.slice_mut(s![..p, ..p]).assign(&small);
        for c in 0..p {
            hbar[(p, c)] = beta_m * u[(m - 1, c)];
        }
        kept = p;
    }
}

The reordering swaps two adjacent eigenvalues of the triangular factor with one rotation:

/// Swaps the adjacent diagonal entries `k`, `k + 1` of the upper triangular `T` in
/// `H = Z T Zᴴ` by a plane rotation (LAPACK's `ztrexc`): the rotation that maps the eigenvector
/// `(t₁₂, t₂₂ − t₁₁)` of the 2 × 2 block onto the first axis makes the second eigenvalue lead.
fn swap(t: &mut Array2<C>, z: &mut Array2<C>, k: usize) {
    let m = t.nrows();
    let (t11, t22) = (t[(k, k)], t[(k + 1, k + 1)]);
    let (c, s) = rotation(t[(k, k + 1)], t22 - t11);
    for j in k + 2..m {
        let (x, y) = (t[(k, j)], t[(k + 1, j)]);
        t[(k, j)] = x * c + s * y;
        t[(k + 1, j)] = y * c - s.conj() * x;
    }
    for i in 0..k {
        let (x, y) = (t[(i, k)], t[(i, k + 1)]);
        t[(i, k)] = x * c + s.conj() * y;
        t[(i, k + 1)] = y * c - s * x;
    }
    t[(k, k)] = t22;
    t[(k + 1, k + 1)] = t11;
    for i in 0..m {
        let (x, y) = (z[(i, k)], z[(i, k + 1)]);
        z[(i, k)] = x * c + s.conj() * y;
        z[(i, k + 1)] = y * c - s * x;
    }
}
/// A minimum-degree ordering of the symmetric pattern of `A + Aᵀ` (SciPy's `MMD_AT_PLUS_A` is the
/// same idea): repeatedly eliminate a vertex of least degree in the elimination graph.
///
/// The graph is never formed. Eliminating a vertex turns it into an *element*, standing for the
/// clique of its neighbours, and a vertex's degree is bounded using the sizes of the elements it
/// belongs to (Amestoy, Davis and Duff's *approximate* degree), so one elimination costs work
/// proportional to the size of the new element and not to the square of it. Elements contained in
/// a new one are absorbed, vertices left with the same neighbours are merged into one weighted
/// *supervariable* and eliminated together, and a vertex whose only neighbour is the new element
/// is eliminated with it. Ties go to the lowest index.
///
/// Returns `q` with `q[k]` the vertex eliminated `k`-th.
pub fn minimum_degree(a: &CsrMatrix) -> Vec<usize> {
    let n = a.nrows.max(a.ncols);
    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
    for i in 0..a.nrows {
        for p in a.indptr[i]..a.indptr[i + 1] {
            let j = a.indices[p];
            if i != j {
                adj[i].push(j);
                adj[j].push(i);
            }
        }
    }
    for l in adj.iter_mut() {
        l.sort_unstable();
        l.dedup();
    }
    amd_graph(&adj, &vec![false; n])
}
/// The textbook minimum-degree ordering of the symmetric pattern of `A + Aᵀ`: repeatedly eliminate a vertex of least degree in the elimination graph, where
/// eliminating a vertex joins all its neighbours into a clique (the fill it would create). Ties go
/// to the lowest index. This is the textbook algorithm on an explicit graph with a lazily updated
/// priority queue; AMD and MMD reach similar orderings faster with quotient graphs,
/// supervariables and approximate degrees.
pub fn minimum_degree_exact(a: &CsrMatrix) -> Vec<usize> {
    let n = a.nrows.max(a.ncols);
    let mut adj: Vec<HashSet<usize>> = vec![HashSet::new(); n];
    for i in 0..a.nrows {
        for p in a.indptr[i]..a.indptr[i + 1] {
            let j = a.indices[p];
            if i != j {
                adj[i].insert(j);
                adj[j].insert(i);
            }
        }
    }
    minimum_degree_graph(adj)
}

/// Minimum degree on an explicit undirected graph given by adjacency sets.
pub(super) fn minimum_degree_graph(mut adj: Vec<HashSet<usize>>) -> Vec<usize> {
    let n = adj.len();
    let mut heap: BinaryHeap<Reverse<(usize, usize)>> = (0..n).map(|v| Reverse((adj[v].len(), v))).collect();
    let mut eliminated = vec![false; n];
    let mut order = Vec::with_capacity(n);
    while let Some(Reverse((d, v))) = heap.pop() {
        if eliminated[v] || adj[v].len() != d {
            continue; // a stale entry
        }
        eliminated[v] = true;
        order.push(v);
        let mut nbrs: Vec<usize> = adj[v].drain().collect();
        nbrs.sort_unstable();
        for &u in &nbrs {
            adj[u].remove(&v);
        }
        for (x, &u) in nbrs.iter().enumerate() {
            for &w in &nbrs[x + 1..] {
                adj[u].insert(w);
                adj[w].insert(u);
            }
        }
        for &u in &nbrs {
            heap.push(Reverse((adj[u].len(), u)));
        }
    }
    order
}
    /// Saad's ILUT(τ, p): eliminate row by row with fill allowed, but drop every multiplier and
    /// every entry of the new row smaller than `τ ‖aᵢ‖₂`, and keep only the `p` largest entries of
    /// each of the `L` and `U` parts of the row (the diagonal is always kept).
    pub fn ilut(a: &CsrMatrix, drop_tol: f64, max_fill: usize) -> Result<Ilu> {
        let n = check_square(a)?;
        let mut l: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
        let mut u: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
        for i in 0..n {
            let mut w: BTreeMap<usize, f64> = BTreeMap::new();
            for p in a.indptr[i]..a.indptr[i + 1] {
                *w.entry(a.indices[p]).or_insert(0.0) += a.data[p];
            }
            let norm = w.values().map(|v| v * v).sum::<f64>().sqrt();
            let tau = drop_tol * norm;
            // Eliminate the entries left of the diagonal in increasing column order; fill created
            // by an update is always to the right of the column being eliminated.
            let mut next = 0;
            while let Some((&k, &wk)) = w.range(next..i).next() {
                next = k + 1;
                let lik = wk / u[k][0].1;
                if lik.abs() < tau {
                    w.remove(&k);
                    continue;
                }
                w.insert(k, lik);
                for &(j, ukj) in &u[k][1..] {
                    *w.entry(j).or_insert(0.0) -= lik * ukj;
                }
            }
            let diag = w.remove(&i).unwrap_or(0.0);
            let keep = |entries: Vec<(usize, f64)>| -> Vec<(usize, f64)> {
                let mut e: Vec<(usize, f64)> = entries.into_iter().filter(|(_, v)| v.abs() >= tau && *v != 0.0).collect();
                if e.len() > max_fill {
                    e.sort_by(|x, y| y.1.abs().total_cmp(&x.1.abs()));
                    e.truncate(max_fill);
                }
                e.sort_by_key(|x| x.0);
                e
            };
            let li = keep(w.range(..i).map(|(&j, &v)| (j, v)).collect());
            let mut ui = vec![(i, safe_pivot(diag, norm))];
            ui.extend(keep(w.range(i + 1..).map(|(&j, &v)| (j, v)).collect()));
            l.push(li);
            u.push(ui);
        }
        Ok(Ilu { n, l, u })
    }
/// A sparse LU factorisation `P A Q = L U` of a complex matrix: Gilbert and Peierls' left-looking
/// algorithm with partial pivoting by modulus, as [`SparseLu`](super::SparseLu), with the column
/// order `Q` from the pattern of `A`.
#[derive(Clone, Debug)]
pub struct ComplexSparseLu {
    n: usize,
    l: Vec<Vec<(usize, C)>>,
    u: Vec<Vec<(usize, C)>>,
    pivot_row: Vec<usize>,
    q: Vec<usize>,
}

impl ComplexSparseLu {
    /// Factorises with one of the real code's column orderings (applied to the pattern of `A`).
    pub fn factor(a: &ComplexCsrMatrix, ordering: Ordering) -> Result<ComplexSparseLu> {
        let n = a.nrows;
        if a.ncols != n {
            return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
        }
        let q = match ordering {
            Ordering::Natural => (0..n).collect(),
            Ordering::ReverseCuthillMcKee => reverse_cuthill_mckee(&a.pattern()),
            Ordering::MinimumDegree => minimum_degree(&a.pattern()),
        };
        Self::factor_with_order(a, &q)
    }

    /// Factorises with an explicit column order (for example the output of `colamd`).
    pub fn factor_with_order(a: &ComplexCsrMatrix, q: &[usize]) -> Result<ComplexSparseLu> {
        let n = a.nrows;
        if a.ncols != n {
            return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
        }
        let mut seen = vec![false; n];
        if q.len() != n || q.iter().any(|&c| c >= n || std::mem::replace(&mut seen[c], true)) {
            return Err(LinalgError::Shape(format!("the column order must be a permutation of 0..{n}")));
        }
        // Compressed columns.
        let t = a.transpose();
        let scale = a.data.iter().fold(0.0f64, |m, v| m.max(v.norm())).max(f64::MIN_POSITIVE);
        let mut l: Vec<Vec<(usize, C)>> = Vec::with_capacity(n);
        let mut u: Vec<Vec<(usize, C)>> = Vec::with_capacity(n);
        let mut pinv: Vec<Option<usize>> = vec![None; n];
        let mut pivot_row = Vec::with_capacity(n);
        let mut x = vec![C::new(0.0, 0.0); n];
        let mut mark = vec![usize::MAX; n];
        for (k, &col) in q.iter().enumerate() {
            // Column `col` of A is row `col` of Aᵀ.
            let (lo, hi) = (t.indptr[col], t.indptr[col + 1]);
            let mut topo: Vec<usize> = Vec::new();
            let mut stack: Vec<(usize, usize)> = Vec::new();
            for p in lo..hi {
                let r = t.indices[p];
                if mark[r] == k {
                    continue;
                }
                mark[r] = k;
                stack.push((r, 0));
                while let Some((v, child)) = stack.pop() {
                    let children = pinv[v].map(|j| &l[j][1..]);
                    match children.and_then(|c| c.get(child)) {
                        Some(&(w, _)) => {
                            stack.push((v, child + 1));
                            if mark[w] != k {
                                mark[w] = k;
                                stack.push((w, 0));
                            }
                        }
                        None => topo.push(v),
                    }
                }
            }
            for p in lo..hi {
                x[t.indices[p]] = t.data[p];
            }
            for &r in topo.iter().rev() {
                if let Some(j) = pinv[r] {
                    let ujk = x[r];
                    for &(i, lij) in &l[j][1..] {
                        x[i] -= lij * ujk;
                    }
                }
            }
            let mut ucol = Vec::new();
            let mut best: Option<(usize, C)> = None;
            for &r in &topo {
                match pinv[r] {
                    Some(j) => {
                        if x[r] != C::new(0.0, 0.0) {
                            ucol.push((j, x[r]));
                        }
                    }
                    None => {
                        if best.is_none_or(|(_, v)| x[r].norm() > v.norm()) {
                            best = Some((r, x[r]));
                        }
                    }
                }
            }
            let Some((piv, d)) = best.filter(|(_, v)| v.norm() > f64::EPSILON * scale * 1e-3) else {
                return Err(LinalgError::Singular(k));
            };
            ucol.sort_by_key(|e| e.0);
            ucol.push((k, d));
            let mut lcol = vec![(piv, C::new(1.0, 0.0))];
            for &r in &topo {
                if pinv[r].is_none() && r != piv && x[r] != C::new(0.0, 0.0) {
                    lcol.push((r, x[r] / d));
                }
            }
            for &r in &topo {
                x[r] = C::new(0.0, 0.0);
            }
            pinv[piv] = Some(k);
            pivot_row.push(piv);
            l.push(lcol);
            u.push(ucol);
        }
        Ok(ComplexSparseLu { n, l, u, pivot_row, q: q.to_vec() })
    }

    /// Solves `A x = b`.
    pub fn solve(&self, b: &[C]) -> Result<Vec<C>> {
        if b.len() != self.n {
            return Err(LinalgError::Shape(format!("right-hand side of length {}, expected {}", b.len(), self.n)));
        }
        let mut w = b.to_vec();
        let mut y = vec![C::new(0.0, 0.0); self.n];
        for j in 0..self.n {
            let yj = w[self.pivot_row[j]];
            y[j] = yj;
            for &(i, lij) in &self.l[j][1..] {
                w[i] -= lij * yj;
            }
        }
        for j in (0..self.n).rev() {
            let (_, ujj) = *self.u[j].last().expect("diagonal");
            let zj = y[j] / ujj;
            y[j] = zj;
            for &(i, uij) in &self.u[j][..self.u[j].len() - 1] {
                y[i] -= uij * zj;
            }
        }
        let mut x = vec![C::new(0.0, 0.0); self.n];
        for (k, &col) in self.q.iter().enumerate() {
            x[col] = y[k];
        }
        Ok(x)
    }

    /// The number of stored entries of `L` and `U` together.
    pub fn nnz(&self) -> usize {
        self.l.iter().map(|c| c.len()).sum::<usize>() + self.u.iter().map(|c| c.len()).sum::<usize>()
    }
}

/// Solves the complex sparse system `A x = b` (SciPy's `spsolve`) by a sparse LU factorisation
/// with the minimum-degree column ordering.
pub fn spsolve_complex(a: &ComplexCsrMatrix, b: &[C]) -> Result<Vec<C>> {
    ComplexSparseLu::factor(a, Ordering::MinimumDegree)?.solve(b)
}

/// A complex sparse LU factorisation with the COLAMD column ordering, which does not assume a
/// symmetric pattern.
pub fn spsolve_complex_colamd(a: &ComplexCsrMatrix, b: &[C]) -> Result<Vec<C>> {
    ComplexSparseLu::factor_with_order(a, &colamd(&a.pattern()))?.solve(b)
}
/// Conjugate gradients for Hermitian positive definite `A` (SciPy's `cg` on complex data), with
/// the inner product `⟨x, y⟩ = xᴴ y`.
pub fn cg_complex(a: &dyn ComplexLinearOperator, b: &[C], x0: Option<&[C]>, m: Option<&dyn ComplexLinearOperator>, options: ComplexIterativeOptions) -> Result<ComplexIterativeResult> {
    let mut x = check(a, b, x0)?;
    let tol = (options.rtol * norm2(b)).max(options.atol);
    let max_it = options.max_iterations.unwrap_or(10 * b.len());
    let mut r = residual(a, b, &x);
    let mut history = vec![norm2(&r)];
    let mut z = apply(m, &r);
    let mut p = z.clone();
    let mut rz = dotc(&r, &z);
    let mut it = 0;
    while history[history.len() - 1] > tol && it < max_it {
        let ap = a.matvec(&p);
        let alpha = rz / dotc(&p, &ap);
        axpy(&mut x, alpha, &p);
        axpy(&mut r, -alpha, &ap);
        z = apply(m, &r);
        let rz_new = dotc(&r, &z);
        let beta = rz_new / rz;
        rz = rz_new;
        p.iter_mut().zip(&z).for_each(|(pi, zi)| *pi = zi + beta * *pi);
        it += 1;
        history.push(norm2(&r));
    }
    let converged = history[history.len() - 1] <= tol;
    Ok(ComplexIterativeResult { x, iterations: it, converged, residual_history: history })
}

/// Restarted GMRES (SciPy's `gmres` on complex data): Arnoldi with modified Gram-Schmidt, complex
/// Givens rotations on the Hessenberg matrix, and right preconditioning.
pub fn gmres_complex(a: &dyn ComplexLinearOperator, b: &[C], x0: Option<&[C]>, m: Option<&dyn ComplexLinearOperator>, restart: usize, options: ComplexIterativeOptions) -> Result<ComplexIterativeResult> {
    let mut x = check(a, b, x0)?;
    let n = b.len();
    let restart = restart.clamp(1, n.max(1));
    let tol = (options.rtol * norm2(b)).max(options.atol);
    let max_it = options.max_iterations.unwrap_or(10 * n);
    let mut r = residual(a, b, &x);
    let mut history = vec![norm2(&r)];
    let mut it = 0;
    let zero = C::new(0.0, 0.0);
    while history[history.len() - 1] > tol && it < max_it {
        let beta = norm2(&r);
        let mut basis: Vec<Vec<C>> = vec![r.iter().map(|v| v / beta).collect()];
        let mut h = vec![vec![zero; restart]; restart + 1];
        let (mut cs, mut sn) = (vec![0.0f64; restart], vec![zero; restart]);
        let mut g = vec![zero; restart + 1];
        g[0] = C::new(beta, 0.0);
        let mut k_done = 0;
        for k in 0..restart {
            let mut w = a.matvec(&apply(m, &basis[k]));
            for (j, vj) in basis.iter().enumerate() {
                h[j][k] = dotc(vj, &w);
                let hjk = h[j][k];
                axpy(&mut w, -hjk, vj);
            }
            let hk1 = norm2(&w);
            h[k + 1][k] = C::new(hk1, 0.0);
            // Previous rotations on the new column: [c s; −s̄ c] with real c.
            for j in 0..k {
                let t = h[j][k] * cs[j] + sn[j] * h[j + 1][k];
                h[j + 1][k] = -sn[j].conj() * h[j][k] + h[j + 1][k] * cs[j];
                h[j][k] = t;
            }
            let (f, gg) = (h[k][k], h[k + 1][k]);
            let denom = (f.norm_sqr() + gg.norm_sqr()).sqrt();
            if f.norm() == 0.0 {
                cs[k] = 0.0;
                sn[k] = gg.conj() / gg.norm().max(f64::MIN_POSITIVE);
                h[k][k] = C::new(gg.norm(), 0.0);
            } else {
                let phase = f / f.norm();
                cs[k] = f.norm() / denom;
                sn[k] = phase * gg.conj() / denom;
                h[k][k] = phase * denom;
            }
            h[k + 1][k] = zero;
            g[k + 1] = -sn[k].conj() * g[k];
            g[k] *= cs[k];
            it += 1;
            k_done = k + 1;
            history.push(g[k + 1].norm());
            if g[k + 1].norm() <= tol || it >= max_it {
                break;
            }
            if hk1 == 0.0 {
                break;
            }
            basis.push(w.iter().map(|v| v / hk1).collect());
        }
        let mut y = vec![zero; k_done];
        for i in (0..k_done).rev() {
            let s: C = (i + 1..k_done).map(|j| h[i][j] * y[j]).sum();
            y[i] = (g[i] - s) / h[i][i];
        }
        let mut update = vec![zero; n];
        for (j, yj) in y.iter().enumerate() {
            axpy(&mut update, *yj, &basis[j]);
        }
        let dx = apply(m, &update);
        axpy(&mut x, C::new(1.0, 0.0), &dx);
        r = residual(a, b, &x);
        let last = history.len() - 1;
        history[last] = norm2(&r);
    }
    let converged = history[history.len() - 1] <= tol;
    Ok(ComplexIterativeResult { x, iterations: it, converged, residual_history: history })
}

/// BiCGSTAB (SciPy's `bicgstab` on complex data), left-preconditioned as SciPy's.
pub fn bicgstab_complex(a: &dyn ComplexLinearOperator, b: &[C], x0: Option<&[C]>, m: Option<&dyn ComplexLinearOperator>, options: ComplexIterativeOptions) -> Result<ComplexIterativeResult> {
    let mut x = check(a, b, x0)?;
    let tol = (options.rtol * norm2(b)).max(options.atol);
    let max_it = options.max_iterations.unwrap_or(10 * b.len());
    let mut r = residual(a, b, &x);
    let r_hat = r.clone();
    let mut history = vec![norm2(&r)];
    let one = C::new(1.0, 0.0);
    let zero = C::new(0.0, 0.0);
    let (mut rho, mut alpha, mut omega) = (one, one, one);
    let (mut v, mut p) = (vec![zero; b.len()], vec![zero; b.len()]);
    let mut it = 0;
    while history[history.len() - 1] > tol && it < max_it {
        let rho_new = dotc(&r_hat, &r);
        if rho_new.norm() == 0.0 {
            break;
        }
        let beta = (rho_new / rho) * (alpha / omega);
        rho = rho_new;
        p.iter_mut().zip(r.iter().zip(&v)).for_each(|(pi, (ri, vi))| *pi = ri + beta * (*pi - omega * vi));
        let p_hat = apply(m, &p);
        v = a.matvec(&p_hat);
        alpha = rho / dotc(&r_hat, &v);
        let s: Vec<C> = r.iter().zip(&v).map(|(ri, vi)| ri - alpha * vi).collect();
        it += 1;
        if norm2(&s) <= tol {
            axpy(&mut x, alpha, &p_hat);
            r = s;
            history.push(norm2(&r));
            break;
        }
        let s_hat = apply(m, &s);
        let t = a.matvec(&s_hat);
        omega = dotc(&t, &s) / dotc(&t, &t);
        axpy(&mut x, alpha, &p_hat);
        axpy(&mut x, omega, &s_hat);
        r = s.iter().zip(&t).map(|(si, ti)| si - omega * ti).collect();
        history.push(norm2(&r));
        if omega.norm() == 0.0 {
            break;
        }
    }
    let converged = history[history.len() - 1] <= tol;
    Ok(ComplexIterativeResult { x, iterations: it, converged, residual_history: history })
}
/// A column ordering of `A` that approximately minimises the fill of the Cholesky factor of
/// `AᵀA`, and so bounds the fill of the LU factors of `A Q` under any row pivoting (SciPy's
/// `COLAMD`).
///
/// The rows of `A` start as *elements*, the cliques they create in the graph of `AᵀA`. Eliminating
/// a column merges the elements that contain it into one new element; the degree of a column is
/// then bounded by the sizes of the elements it belongs to, without forming any clique. Elements
/// contained in a new element are absorbed, and columns with identical patterns are merged into one
/// weighted *supercolumn* and eliminated together. Rows and columns with more than
/// `max(16, 10 √n)` entries are ignored (dense columns are placed last), as in the reference
/// implementation.
///
/// Returns `q` with `q[k]` the original column placed at position `k`; `q` has length `ncols`.
pub fn colamd(a: &CsrMatrix) -> Vec<usize> {
    let (m, n) = (a.nrows, a.ncols);
    let dense_row = ((10.0 * (n as f64).sqrt()) as usize).max(16);
    let dense_col = ((10.0 * (m.min(n) as f64).sqrt()) as usize).max(16);

    // Patterns: rows are the initial elements.
    let mut row_cols: Vec<Vec<usize>> = Vec::with_capacity(m + n);
    let mut alive_row: Vec<bool> = Vec::with_capacity(m + n);
    for i in 0..m {
        let mut c: Vec<usize> = a.indices[a.indptr[i]..a.indptr[i + 1]].to_vec();
        c.sort_unstable();
        c.dedup();
        alive_row.push(!c.is_empty() && c.len() <= dense_row);
        if c.len() > dense_row {
            c.clear();
        }
        row_cols.push(c);
    }
    let mut count = vec![0usize; n];
    for c in row_cols.iter().flatten() {
        count[*c] += 1;
    }
    let mut col_alive = vec![true; n];
    // Dense columns (the sparser first) and then empty ones go last.
    let mut tail: Vec<usize> = (0..n).filter(|&j| count[j] == 0 || count[j] > dense_col).collect();
    tail.sort_by_key(|&j| (count[j] == 0, count[j], j));
    for &j in &tail {
        col_alive[j] = false;
    }

    let mut col_rows: Vec<Vec<usize>> = vec![Vec::new(); n];
    for (i, cols) in row_cols.iter().enumerate() {
        if !alive_row[i] {
            continue;
        }
        for &j in cols {
            if col_alive[j] {
                col_rows[j].push(i);
            }
        }
    }
    for r in 0..m {
        row_cols[r].retain(|&j| col_alive[j]);
    }
    let mut weight = vec![1usize; n];
    let mut members: Vec<Vec<usize>> = vec![Vec::new(); n];
    let mut remaining = col_alive.iter().filter(|&&x| x).count();
    let mut score = vec![0usize; n];
    let mut heap: BinaryHeap<Reverse<(usize, usize)>> = BinaryHeap::new();
    for j in 0..n {
        if col_alive[j] {
            score[j] = col_rows[j].iter().map(|&r| row_cols[r].len() - 1).sum::<usize>().min(remaining.saturating_sub(1));
            heap.push(Reverse((score[j], j)));
        }
    }

    let mut elem_cols: Vec<Vec<usize>> = Vec::new(); // the columns eliminated with each element
    let mut parent: Vec<usize> = Vec::new(); // the element that absorbed it, or MAX
    let mut tag = vec![usize::MAX; n];
    let mut wstamp: Vec<usize> = vec![usize::MAX; m + n];
    let mut w: Vec<usize> = vec![0; m + n];
    let mut step = 0usize;
    while let Some(Reverse((s, p))) = heap.pop() {
        if !col_alive[p] || score[p] != s {
            continue; // a stale entry
        }
        step += 1;
        let t = elem_cols.len();
        let mut cols_of_t = vec![p];
        cols_of_t.extend(members[p].iter().copied());
        elem_cols.push(cols_of_t);
        parent.push(usize::MAX);
        // The new element Lp: the union of the elements containing the pivot column.
        let rows_p: Vec<usize> = col_rows[p].iter().copied().filter(|&r| alive_row[r]).collect();
        let mut lp: Vec<usize> = Vec::new();
        tag[p] = step;
        for &r in &rows_p {
            for &c in &row_cols[r] {
                if col_alive[c] && tag[c] != step {
                    tag[c] = step;
                    lp.push(c);
                }
            }
            alive_row[r] = false;
            row_cols[r] = Vec::new();
            if r >= m {
                parent[r - m] = t;
            }
        }
        col_alive[p] = false;
        remaining -= weight[p];
        lp.sort_unstable();
        let e = row_cols.len();
        let lp_weight: usize = lp.iter().map(|&j| weight[j]).sum();
        row_cols.push(lp.clone());
        alive_row.push(true);
        for &j in &lp {
            col_rows[j].retain(|&r| alive_row[r]);
            col_rows[j].push(e);
        }
        // |Le \ Lp|, weighted, for every other element that meets Lp.
        for &j in &lp {
            for &r in &col_rows[j] {
                if r == e {
                    continue;
                }
                if wstamp[r] != step {
                    wstamp[r] = step;
                    row_cols[r].retain(|&c| col_alive[c]);
                    w[r] = row_cols[r].iter().map(|&c| weight[c]).sum();
                }
                w[r] -= weight[j];
            }
        }
        // Aggressive absorption, and the approximate degrees.
        for &j in &lp {
            let mut sum = 0usize;
            let mut kept = Vec::with_capacity(col_rows[j].len());
            for &r in &col_rows[j] {
                if r == e {
                    kept.push(r);
                } else if w[r] == 0 {
                    alive_row[r] = false; // Le is contained in Lp
                    if r >= m {
                        parent[r - m] = t;
                    }
                } else {
                    sum += w[r];
                    kept.push(r);
                }
            }
            col_rows[j] = kept;
            let others = lp_weight - weight[j];
            score[j] = (remaining - weight[j]).min(score[j] + others).min(sum + others);
        }
        // Columns with identical patterns become one supercolumn.
        let mut buckets: BTreeMap<(usize, usize), Vec<usize>> = BTreeMap::new();
        for &j in &lp {
            col_rows[j].sort_unstable();
            let hash = col_rows[j].iter().fold(0usize, |h, &r| h.wrapping_add(r.wrapping_mul(2654435761)));
            buckets.entry((col_rows[j].len(), hash)).or_default().push(j);
        }
        for group in buckets.values().filter(|g| g.len() > 1) {
            for (x, &i) in group.iter().enumerate() {
                if !col_alive[i] {
                    continue;
                }
                for &k in &group[x + 1..] {
                    if col_alive[k] && col_rows[i] == col_rows[k] {
                        weight[i] += weight[k];
                        let moved = std::mem::take(&mut members[k]);
                        members[i].push(k);
                        members[i].extend(moved);
                        col_alive[k] = false;
                        score[i] = score[i].saturating_sub(weight[k]);
                    }
                }
            }
        }
        for &j in &lp {
            if col_alive[j] {
                heap.push(Reverse((score[j], j)));
            }
        }
    }
    // Postorder the assembly tree: every element after the elements it absorbed, each subtree
    // contiguous. The fill is the same; the order is the one a supernodal factorisation wants.
    let count = elem_cols.len();
    let mut children: Vec<Vec<usize>> = vec![Vec::new(); count];
    let mut roots = Vec::new();
    for t in 0..count {
        if parent[t] == usize::MAX {
            roots.push(t);
        } else {
            children[parent[t]].push(t);
        }
    }
    let mut order: Vec<usize> = Vec::with_capacity(n);
    for &root in &roots {
        let mut stack = vec![(root, 0usize)];
        while let Some((t, next)) = stack.pop() {
            if next < children[t].len() {
                stack.push((t, next + 1));
                stack.push((children[t][next], 0));
            } else {
                order.extend(elem_cols[t].iter().copied());
            }
        }
    }
    order.extend(tail);
    debug_assert_eq!(order.len(), n);
    order
}

/// A column ordering for a symmetric matrix (SYMAMD): `colamd` applied to a matrix with one row,
/// holding the two columns `i` and `j`, for each off-diagonal pair `a_ij ≠ 0`, whose `AᵀA` has the
/// pattern of `A + Aᵀ`. It is a minimum-degree ordering of the symmetric graph, found by the
/// COLAMD machinery, with its handling of dense vertices.
pub fn symamd(a: &CsrMatrix) -> Vec<usize> {
    let n = a.nrows.max(a.ncols);
    let mut pairs: Vec<(usize, usize)> = Vec::new();
    for i in 0..a.nrows {
        for p in a.indptr[i]..a.indptr[i + 1] {
            let j = a.indices[p];
            if i != j {
                pairs.push((i.min(j), i.max(j)));
            }
        }
    }
    pairs.sort_unstable();
    pairs.dedup();
    let (mut rows, mut cols) = (Vec::with_capacity(2 * pairs.len()), Vec::with_capacity(2 * pairs.len()));
    for (k, &(i, j)) in pairs.iter().enumerate() {
        rows.extend([k, k]);
        cols.extend([i, j]);
    }
    let edges = CsrMatrix::from_triplets(pairs.len(), n, &rows, &cols, &vec![1.0; rows.len()]).expect("a valid pattern");
    colamd(&edges)
}
/// A nested dissection ordering of the symmetric pattern of `A + Aᵀ`: a small vertex *separator*
/// splits the graph into two parts that no longer touch, each part is ordered recursively, and the
/// separator is numbered last. Eliminating the parts independently confines the fill to each part
/// and to the separator; on an `n × n` grid the fill is `O(N log N)` for `N = n²` unknowns, against
/// `O(N^1.5)` for banded and minimum-degree orderings. Pieces of at most 800 vertices, and the
/// separators, are ordered by approximate minimum degree, with the vertices still to come as a
/// frozen halo.
///
/// The separators come from a multilevel bisection: the graph is coarsened by matching heavy edges,
/// bisected by growing a region from a vertex until it holds half the weight, and refined at each
/// level by Fiduccia-Mattheyses moves. The edge cut is turned into a vertex separator by a minimum
/// vertex cover of the cut edges (König's theorem). Returns `q` with `q[k]` the vertex numbered
/// `k`-th.
pub fn nested_dissection(a: &CsrMatrix) -> Vec<usize> {
    let n = a.nrows.max(a.ncols);
    let mut gadj: Vec<Vec<usize>> = vec![Vec::new(); n];
    for i in 0..a.nrows {
        for p in a.indptr[i]..a.indptr[i + 1] {
            let j = a.indices[p];
            if i != j {
                gadj[i].push(j);
                gadj[j].push(i);
            }
        }
    }
    for l in gadj.iter_mut() {
        l.sort_unstable();
        l.dedup();
    }
    let graph = Graph { adj: gadj.iter().map(|l| l.iter().map(|&w| (w, 1)).collect()).collect(), vw: vec![1; n] };
    let ids: Vec<usize> = (0..n).collect();
    let mut order = Vec::with_capacity(n);
    let mut done = vec![false; n];
    dissect(&graph, &ids, &gadj, &mut done, &mut order);
    order
}
/// The up-looking factorisation: row `i` of `L` solves `L₀ ℓᵢ = aᵢ` against the rows computed so
/// far. Working left to right, each entry `ℓᵢⱼ = wⱼ / ℓⱼⱼ` is final once the contributions of the
/// earlier entries have been subtracted, and then updates the entries to its right through column
/// `j` of `L`.
fn factor(a: &CsrMatrix, mode: Mode, shift: f64) -> Result<IncompleteCholesky> {
    let n = a.nrows;
    if a.ncols != n {
        return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
    }
    let mut rows: Vec<Vec<(usize, f64)>> = Vec::with_capacity(n);
    let mut diag: Vec<f64> = Vec::with_capacity(n);
    // Column j of L below the diagonal, for the rows finished so far: (row, value).
    let mut cols: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
    for i in 0..n {
        let mut w: BTreeMap<usize, f64> = BTreeMap::new();
        let mut aii = 0.0;
        let mut norm = 0.0;
        for p in a.indptr[i]..a.indptr[i + 1] {
            let (j, v) = (a.indices[p], a.data[p]);
            norm += v * v;
            if j < i {
                *w.entry(j).or_insert(0.0) += v;
            } else if j == i {
                aii += v;
            }
        }
        let (tau, max_fill) = match mode {
            Mode::Pattern => (0.0, usize::MAX),
            Mode::Threshold { drop_tol, max_fill } => (drop_tol * norm.sqrt(), max_fill),
        };
        let mut sum_sq = 0.0;
        let mut kept: Vec<(usize, f64)> = Vec::new();
        let mut next = 0;
        while let Some((&j, &wj)) = w.range(next..i).next() {
            next = j + 1;
            let lij = wj / diag[j];
            if matches!(mode, Mode::Threshold { .. }) && lij.abs() < tau {
                w.remove(&j);
                continue;
            }
            w.insert(j, lij);
            for &(m, lmj) in &cols[j] {
                match mode {
                    Mode::Pattern => {
                        if let Some(x) = w.get_mut(&m) {
                            *x -= lij * lmj;
                        }
                    }
                    Mode::Threshold { .. } => *w.entry(m).or_insert(0.0) -= lij * lmj,
                }
            }
        }
        let mut entries: Vec<(usize, f64)> = w.into_iter().filter(|&(_, v)| v != 0.0).collect();
        if entries.len() > max_fill {
            entries.sort_by(|x, y| y.1.abs().total_cmp(&x.1.abs()));
            entries.truncate(max_fill);
            entries.sort_by_key(|e| e.0);
        }
        for &(j, v) in &entries {
            sum_sq += v * v;
            kept.push((j, v));
        }
        let d = aii * (1.0 + shift) - sum_sq;
        if d <= 1e-14 * aii.abs() || d <= 0.0 || !d.is_finite() {
            return Err(LinalgError::NotPositiveDefinite(i));
        }
        let dii = d.sqrt();
        for &(j, v) in &kept {
            cols[j].push((i, v));
        }
        rows.push(kept);
        diag.push(dii);
    }
    Ok(IncompleteCholesky { n, rows, diag, shift, order: None })
}
/// `e^{tA} b` (SciPy's `expm_multiply` at one time point). With `μ = trace(A)/n` and `B = A − μI`,
/// `e^{tA} b = e^{tμ} (e^{tB/s})^s b`, and each factor is applied by the Taylor series
/// `Σ_{j≤m} (tB/s)^j b / j!`, stopping early once two consecutive terms are negligible.
pub fn expm_multiply(a: &CsrMatrix, b: &[f64], t: f64) -> Result<Vec<f64>> {
    let n = a.nrows;
    if a.ncols != n || b.len() != n {
        return Err(LinalgError::Shape(format!("{} × {} operator with a vector of length {}", a.nrows, a.ncols, b.len())));
    }
    let mu = a.diagonal().iter().sum::<f64>() / n as f64;
    let shifted = a.add(1.0, &CsrMatrix::identity(n), -mu)?;
    let norm = t.abs() * one_norm(&shifted);
    let (m, s) = if norm == 0.0 { (0, 1) } else { parameters(&shifted, t, norm) };
    let tol = 2f64.powi(-53);
    let eta = (t * mu / s as f64).exp();
    let mut f = b.to_vec();
    let mut v = b.to_vec();
    for _ in 0..s {
        let mut c1 = inf_norm(&v);
        for j in 0..m {
            let coeff = t / (s * (j + 1)) as f64;
            v = shifted.matvec(&v).into_iter().map(|x| coeff * x).collect();
            let c2 = inf_norm(&v);
            f.iter_mut().zip(&v).for_each(|(fi, vi)| *fi += vi);
            if c1 + c2 <= tol * inf_norm(&f) {
                break;
            }
            c1 = c2;
        }
        f.iter_mut().for_each(|x| *x *= eta);
        v = f.clone();
    }
    Ok(f)
}
  • The real solvers and eigensolvers work on f64 matrices. Complex matrices have their own types and solvers (ComplexCsrMatrix, ComplexSparseLu, cg_complex, gmres_complex, bicgstab_complex), written out for Complex<f64>: the real code is not generic. The complex LU takes the real code’s orderings, applied to the pattern of . Complex eigenvalue solvers (eigs, eigsh) and the other Krylov methods (MINRES, LSQR, LGMRES), ILU and incomplete Cholesky are not provided.
  • Every solver counts iterations as SciPy’s callbacks do, and returns the residual history. GMRES records one entry per inner iteration.
  • The stopping rule of cg, minres, gmres and bicgstab is . SciPy’s minres uses a looser test relative to , so it stops earlier (Table 7.18).
  • spsolve orders the columns by minimum degree. SparseLu::factor also accepts the natural order or reverse Cuthill-McKee, and SparseLu::factor_with_order takes any column order, such as the output of colamd or nested_dissection. SparseLu::flops counts the arithmetic of a factorisation, which is what an ordering is for.
  • colamd returns an order for the columns of any matrix, and treats rows and columns of as SuperLU’s does. It does not post-order the elimination tree, which changes the order but not the fill.
  • nested_dissection is deterministic: its pseudo-random choices use fixed seeds.
  • IncompleteCholesky implements LinearOperator as . ic0_shifted takes a fixed shift and reports a breakdown instead of retrying.
  • Ilu implements LinearOperator as , so it is passed to any solver as the preconditioner. A zero pivot is replaced by times the row norm.
  • expm_multiply takes one time point and one vector; SciPy’s version also accepts several columns and a grid of times.
  • eigsh, svds and eigs use a deterministic start vector, so results are reproducible. eigs also accepts one, v0, as SciPy does.
  • eigs returns the eigenvalues in order of preference, a real eigenvalue with an exactly zero imaginary part. Each eigenvector is scaled so that its largest component is real and positive, which makes the vectors of a conjugate pair exact conjugates.
  • A residual estimate of a converged pair settles at a few times , and can stay just above . So the default tolerance is rather than ARPACK’s .
  • eigs’s default subspace is vectors, against SciPy’s . Keeping half of a 20-vector subspace, the library needed 17,654 products on one case of Table 7.28, where SciPy needs 3,449. With 30 vectors it needs 750. Keeping fewer vectors at each restart, as ARPACK does, made that case faster but missed one of the six wanted values.

In practice

The references come from SciPy 1.17.1 (book/generator/data/make_sparse_refs.py). The test systems have : the 5-point Laplacian on a grid, a convection-diffusion operator from central differences with cell Péclet numbers 0.3 and 0.1 (nonsymmetric), and a Laplacian plus a diagonal varying from 0 to 47. The right-hand side is .

Table 7.17. Direct solves, least squares, eigenvalues and singular values against SciPy.

computation (n = 900 unless stated)largest difference from SciPy (relative)
spsolve, 2-D Laplacian7e-15
spsolve, convection-diffusion4e-15
spsolve, varying diagonal8e-16
lsqr, random 200 × 80 (5 % filled), 46 / 46 iterations, against SciPy8e-12
lsqr, the same, against the dense least-squares solution1e-9
eigsh, the 4 largest eigenvalues of the 2-D Laplacian9e-15
eigsh, the 4 smallest eigenvalues of the 2-D Laplacian7e-14
eigsh, the 4 largest in magnitude eigenvalues of the 2-D Laplacian3e-15
svds, the 4 largest singular values of the 200 × 80 matrix2e-15

The iterative solvers stop at slightly different points. Instead of comparing the two iterates, both are compared with the direct solution:

Table 7.18. Iterative solvers with rtol = 10⁻⁸: iterations and error, library and SciPy.

solver, n = 900, rtol = 10⁻⁸iterations (library / SciPy)error against the direct solution (library / SciPy)
cg, 2-D Laplacian87 / 876e-10 / 6e-10
minres, 2-D Laplacian86 / 531e-9 / 8e-6
cg, varying diagonal31 / 315e-8 / 5e-8
minres, varying diagonal30 / 269e-8 / 4e-7
cg with Jacobi preconditioning, varying diagonal10 / 109e-9 / —
bicgstab, 2-D Laplacian63 / 611e-9 / 5e-9
gmres (restart 30), 2-D Laplacian118 / 1181e-8 / 1e-8
bicgstab, convection-diffusion57 / 566e-9 / 6e-9
gmres (restart 30), convection-diffusion210 / 2106e-9 / 6e-9

CG, GMRES and the Jacobi-preconditioned CG take exactly SciPy’s number of iterations. BiCGSTAB differs by one or two, because its rounding differs and its residual is not monotone. MINRES takes as many iterations as CG on the Laplacian. That is the expected count for the strict stopping rule, and it gives an error 8000 times smaller than SciPy’s.

Figure 7.13. Convergence on the 2-D Laplacian. MINRES and full GMRES lie on top of each other: for symmetric , both minimise the residual over the same subspace. CG minimises the -norm of the error instead, so its residual is not monotone. Restarting GMRES every 30 steps discards the subspace, and convergence slows.

Figure 7.14. A nonsymmetric system. Full GMRES converges in the fewest iterations (86) but stores every basis vector. Restarting costs iterations, and not monotonically: GMRES(10) needs 114 and GMRES(30) needs 210, as in SciPy. Short and long restarts discard different parts of the subspace, and which is better depends on the problem (Embree, 2003). BiCGSTAB's residual is erratic, but it converges in 57 iterations of two products each.

LGMRES, compared with SciPy’s lgmres on two convection-diffusion systems with rtol . Like SciPy’s, the library’s LGMRES preconditions on the left, adapts the tolerance of each cycle, and counts the residual computed at the start of each cycle among the products:

Table 7.19. LGMRES against SciPy.

convection-diffusion, n = 900augmentation vectorsproducts with A (library / SciPy)final relative residual (library / SciPy)solution, relative difference from SciPy
γ = 0.53205 / 2058.8e-9 / 8.8e-94e-16
γ = 0.93163 / 1639.4e-9 / 9.4e-92e-16
γ = 0.50 (restarted GMRES(30))155 / 1559.4e-9 / 9.4e-93e-16
γ = 0.90 (restarted GMRES(30))113 / 1139.7e-9 / 9.7e-94e-16

The two take the same steps, product for product. On these systems the augmentation does not pay: restarted GMRES(30) needs 24–31 % fewer products. LGMRES helps most when restarts stagnate. Its larger gains come inside Newton iterations, where the augmentation vectors carry information from one linear system to the next.

Figure 7.15. Jacobi preconditioning on a matrix whose diagonal varies from 4 to 51 cuts CG from 31 iterations to 10. The large diagonal already makes this matrix better conditioned than the plain Laplacian (grey).

Ordering decides the cost of a direct solve. The table repeats the experiment of Figure 7.12 on the grid, with SciPy’s SuperLU for comparison:

Table 7.20. Bandwidth and fill of the LU factors of a shuffled 900 × 900 Laplacian under several orderings.

orderingbandwidth (library / SciPy)nnz(L) + nnz(U), librarynnz(L) + nnz(U), SciPy’s SuperLU
the shuffled matrix, as given890 / 890123840123840
reverse Cuthill-McKee30 / 303863038630
COLAMD (SciPy’s default for splu)——29360
minimum degree on AᵀA + A (SciPy’s MMD_AT_PLUS_A)——21000

The library’s sparse LU produces exactly SuperLU’s fill for the same ordering. Reverse Cuthill-McKee cuts the fill by a factor of 3, and minimum degree saves another 40–60 %. On larger and nonsymmetric matrices the library’s minimum degree comes within 2–4 % of SuperLU’s MMD and does much better than SuperLU’s default, COLAMD, which orders for unsymmetric pivoting. The library’s own COLAMD agrees with SuperLU’s within 4 %:

Table 7.21. Fill (nnz(L) + nnz(U)) under the library's orderings and SuperLU's.

matrixnaturalRCMCOLAMDminimum degreeSuperLU naturalSuperLU COLAMDSuperLU MMD on A + Aᵀ
shuffled 2-D Laplacian, n = 9001252543863030830218181252542976221366
shuffled 2-D Laplacian, n = 360020740722986601858881224942074072186426117924
convection-diffusion, n = 16001280789004065644412921280786490239942

Figure 7.16. Fill of the LU factors of the Laplacian on grids from 10 × 10 to 80 × 80. The banded orders grow like (the natural order exactly as ); minimum degree grows roughly like .

COLAMD and nested dissection, added in 2.22, against SuperLU on matrices whose patterns the library reproduces exactly (the random matrices come from a 64-bit linear congruential generator, book/generator/data/make_dir222_refs.py):

Table 7.22. Fill (nnz(L) + nnz(U)) under COLAMD, minimum degree and nested dissection.

MatrixNatural: library / SciPyCOLAMD: library / SciPyMinimum degree on A + Aᵀ: library / SciPy’s MMDSYMAMD: libraryNested dissection: library
2-D Laplacian, 40 × 40 grid (n = 1,600)128078 / 12807865644 / 6490241292 / 399424129242672
3-D Laplacian, 14³ grid (n = 2,744)1009426 / 1009426664270 / 670942311872 / 343042311872353206
random unsymmetric, n = 3,000, 4 entries per row1966440 / 19664401173471 / 1320422993103 / 10149239931751167816
random unsymmetric, n = 3,000, 7 entries per row4495849 / 44958493558012 / 36825542769399 / 270837027693743917598

The natural-order fill is identical to SuperLU’s, which shows that the factorisations agree. COLAMD is within about 1 % of SuperLU’s on the grids, 11 % lower on the sparser random matrix and 3 % lower on the denser one. On the symmetric grids it is 60–110 % above minimum degree, as expected, since it cannot use the symmetry, and on the random matrices 18–29 % above. symamd, the same machinery applied to the graph of , matches minimum degree to within 0.01 %. The library’s minimum degree is 3 % above SuperLU’s MMD on the 2-D grid, 9 % below it on the 3-D grid, and 2 % below and 2 % above on the two random matrices. Those random graphs have no small separators, and nested dissection does no better than COLAMD on the sparser one and worse on the denser. It needs a graph that can be cut. On the 3-D grid the separators are planes, and at this size minimum degree is still ahead.

The value of nested dissection appears with size. The table gives the fill and the arithmetic on larger and larger grids, with the time to find each ordering:

Table 7.23. Fill, arithmetic and ordering time on grids of growing size.

GridUnknownsFill, SuperLU’s MMDFill, minimum_degree (ordering time)Fill, minimum_degree_exact (ordering time)Fill, nested_dissection (ordering time)Flops, minimum_degreeFlops, nested_dissection
50 × 5025007188670540 (0.00 s)76538 (0.01 s)76254 (0.01 s)1.92e62.30e6
100 × 10010000371346389624 (0.01 s)442064 (0.13 s)435652 (0.03 s)2.18e72.68e7
200 × 2004000019524342061484 (0.05 s)2444572 (1.70 s)2308562 (0.18 s)2.20e82.58e8
400 × 400160000969619810511976 (0.27 s)—11627334 (0.99 s)2.15e92.33e9
800 × 8006400004716556252808018 (1.61 s)—56786916 (5.74 s)2.08e102.07e10

Figure 7.17. Fill per unknown against the number of unknowns for SuperLU's MMD, minimum degree and nested dissection.

The quotient-graph minimum degree is the strongest of the three here. Its fill is within 2 % of SuperLU’s MMD below 100 × 100 and within 12 % up to 800 × 800 (640,000 unknowns), and it orders the 400 × 400 grid in 0.45 s, against 74 s for the explicit-graph algorithm of the earlier release (0.24 s against 0.02 s at 100 × 100, and 3.8 s against 0.08 s at 200 × 200). Nested dissection has 8–12 % more fill at every size. Its arithmetic is 17–23 % higher up to 200 × 200, 8 % higher at 400 × 400, and the same at 800 × 800: operations against . That is the asymptotics at work, but only beyond half a million unknowns. Nested dissection is also the ordering that parallelises, since its two halves are independent. Its own ordering time is four to five times that of minimum degree. One attempt to narrow the gap did not work: running the bisection with several coarsenings (different matching orders; three trials above 1000 vertices and six above 3000) and keeping the smallest separator left the arithmetic where it was ( on 100 × 100, on 200 × 200), so the separators are not the limit. Multiple elimination for minimum degree and Ashcraft-Liu refinement of the separators were not tried.

Figure 7.18. Position of each point of a 33 × 33 grid in the nested dissection elimination order.

The picture shows the recursion: the parts are eliminated first, the separators last, with the longest at the end. Each level’s separators are straight lines on the grid, and the multilevel partitioner finds them.

Incomplete Cholesky as a preconditioner for CG, with rtol :

Table 7.24. CG with IC(0), MIC(0), IC(2) and ICT preconditioning: iterations (and stored entries of the factor).

MatrixCG, no preconditioner: library / SciPyCG + Jacobi: library / SciPyCG + IC(0) (stored entries)CG + MIC(0)CG + IC(2)CG + ICT(10⁻², 15)CG + ICT(10⁻³, 30)
2-D Laplacian, 60 × 60200 / 200200 / 20067 (3.0n)41 (3.0n)34 (4.9n)34 (4.9n)16 (11.0n)
2-D Laplacian, 100 × 100296 / 296296 / 29690 (3.0n)51 (3.0n)48 (4.9n)48 (4.9n)22 (11.4n)
anisotropic 2-D (coupling ratio 100), 80 × 80458 / 458458 / 45839 (3.0n)39 (3.0n)31 (4.9n)44 (2.0n)20 (11.0n)
3-D Laplacian, 20³91 / 9191 / 9134 (3.9n)30 (3.9n)19 (10.8n)23 (6.6n)16 (14.8n)

The unpreconditioned and Jacobi counts equal SciPy’s. Jacobi changes nothing, since the diagonals are constant. IC(0), which stores just the lower triangle of , cuts the iterations by a factor of 3 on the Laplacians and by 12 on the anisotropic problem. MIC(0), with the same storage, takes 41 and 51 iterations against IC(0)’s 67 and 90 on the Laplacians, a gap that widens with the grid as the condition numbers predict, but no fewer on the anisotropic problem. IC(2), at 5 entries per row, is as good as ICT(10⁻², 15) on the Laplacians and better on the anisotropic and 3-D problems. ICT(10⁻², 15) roughly halves the count again on the Laplacians, at 5–7 entries per row, and ICT(10⁻³, 30) reaches 16 to 22 iterations at 11–15 entries per row. More fill is not always better, though: on the anisotropic problem the cheap ICT needs 44 iterations against IC(0)’s 39, because it drops entries along the strong direction that IC(0) keeps. For scale, the complete Cholesky factor of the 100 × 100 Laplacian has about 19 entries per row (half the 371,346 entries of SuperLU’s LU, plus the diagonal), and solves in one iteration.

The check against the textbook recurrences is exact to rounding:

IncompleteCholesky::ic0 on the 20 × 20 Laplacian: the solve (L Lᵀ)⁻¹ b agrees with a dense NumPy implementation of the same recurrences to a relative 5e-16; both factors hold 1160 entries (1160 / 1160) with shift 0.

Complex sparse matrices, against SciPy’s complex solvers: a complex symmetric matrix, the 5-point Laplacian on a grid plus (as arises in damped wave problems), and a Hermitian positive definite one, for a banded complex . The iterative solves stop at and of the right-hand side:

Table 7.25. Complex sparse matrices and solvers against SciPy.

MatrixOperationIterations or entries, library / SciPyLargest relative difference from SciPy’s result
complex symmetric, n = 900spsolve (sparse LU)—4e-16
gmres (restart 30)20 / 209e-9
bicgstab12 / 122e-8
Hermitian positive definite, n = 200spsolve (sparse LU)—1e-16
cg21 / 217e-11
product B Bᴴ, 200 × 200matmul, adjoint994 / 994 entries1e-14

The sparse LU agrees with SciPy’s SuperLU to rounding, and the iterative solvers take exactly SciPy’s number of iterations, as the real ones do. The differences of the iterative solutions are the size of their stopping tolerances.

Incomplete LU preconditioning on two nonsymmetric problems with 1600 unknowns, against SciPy’s spilu. Jacobi does nothing here, because the diagonal is constant:

Table 7.26. GMRES(30) with incomplete-LU preconditioners, rtol = 10⁻⁸.

matrix (n = 1600)preconditionerGMRES(30) iterationsnnz of the factorsfinal relative residual
convection-diffusion (Péclet 0.3, 0.1)none265—1e-8
convection-diffusion (Péclet 0.3, 0.1)Jacobi26516001e-8
convection-diffusion (Péclet 0.3, 0.1)ILU(0)3178408e-9
convection-diffusion (Péclet 0.3, 0.1)ILUT(τ = 1e-2, p = 10)17137707e-9
convection-diffusion (Péclet 0.3, 0.1)ILUT(τ = 1e-4, p = 30)5632095e-10
convection-diffusion (Péclet 0.3, 0.1)SciPy, none265—1e-8
convection-diffusion (Péclet 0.3, 0.1)SciPy spilu(drop_tol = 1e-2)9324763e-9
convection-diffusion (Péclet 0.3, 0.1)SciPy spilu(drop_tol = 1e-4)8533582e-9
convection-dominated (Péclet 1.4, 0.9)none190—9e-9
convection-dominated (Péclet 1.4, 0.9)Jacobi19016009e-9
convection-dominated (Péclet 1.4, 0.9)ILU(0)1278406e-9
convection-dominated (Péclet 1.4, 0.9)ILUT(τ = 1e-2, p = 10)1294005e-9
convection-dominated (Péclet 1.4, 0.9)ILUT(τ = 1e-4, p = 30)4300002e-9
convection-dominated (Péclet 1.4, 0.9)SciPy, none190—9e-9
convection-dominated (Péclet 1.4, 0.9)SciPy spilu(drop_tol = 1e-2)5284361e-8
convection-dominated (Péclet 1.4, 0.9)SciPy spilu(drop_tol = 1e-4)3390901e-11

ILU(0), with no more storage than , cuts the iterations by a factor of 8 to 16. ILUT with needs 4–5 iterations. SuperLU’s threshold ILU, which also pivots and reorders, reaches 3–9 iterations with a similar amount of fill. Finally, expm_multiply and shift-invert eigsh:

Table 7.27. The action of the matrix exponential and interior eigenvalues against SciPy.

computation (SciPy reference), n = 900largest difference (relative)
expm_multiply, heat equation e^(−tA) b, t = 0.011e-16
expm_multiply, heat equation e^(−tA) b, t = 1 (dense expm times b: 6e-15)0
expm_multiply, heat equation e^(−tA) b, t = 102e-15
expm_multiply, heat equation e^(−tA) b, t = 406e-15
expm_multiply, convection-diffusion, t = 0.50
expm_multiply, convection-diffusion, t = 36e-16
eigsh shift-invert, the 6 eigenvalues nearest σ = 2 (three double pairs)1e-16
eigsh shift-invert, the 6 eigenvalues nearest σ = 5.5 (three double pairs)0

At the norm is beyond the simple bound, so the parameters come from the norms of powers. These are estimated in SciPy and exact here, and both reach the same result.

eigs on three nonsymmetric matrices, with the error measured against the exact spectrum. That spectrum comes from dense numpy.linalg.eigvals for the first two matrices, and in closed form, , for the convection-diffusion operator. Both programs start from the vector of ones, with and each program’s default tolerance:

Table 7.28. `eigs` against SciPy's ARPACK.

matrixsix eigenvalues witherror, libraryerror, SciPyproducts with A (library / SciPy)
pseudo-random, n = 300largest |λ|9e-151e-14329 / 546
pseudo-random, n = 300largest Re λ9e-151e-14430 / 1043
pseudo-random, n = 300smallest Re λ9e-151e-14252 / 493
pseudo-random, n = 300largest |Im λ|2e-141e-14750 / 3449
ramp plus skew-symmetric, n = 400largest |λ|1e-132e-14294 / 453
ramp plus skew-symmetric, n = 400largest Re λ4e-143e-14330 / 477
ramp plus skew-symmetric, n = 400largest |Im λ|2e-147e-15450 / 553
convection-diffusion, γ = 0.2, n = 900largest |λ|4e-131e-13326 / 420
convection-diffusion, γ = 0.2, n = 900smallest Re λ2e-142e-15337 / 487
pseudo-random, n = 300nearest σ = 0.32e-151e-1552 solves
convection-diffusion, γ = 0.2, n = 900nearest σ = 18e-143e-1554 solves

Every run finds the right six eigenvalues, to between and of the spectral radius, and the library needs fewer products than ARPACK in each case. Part of that comes from its larger default subspace. The largest errors are on the convection-diffusion operator. It is far from normal: its eigenvector matrix has a condition number of about , and although the nearest eigenvalue is from the shift. Rounding errors of order move its eigenvalues by up to times as much. ARPACK’s results are more accurate on this operator, and we have not established why.

Figure 7.19. The eigenvalues `eigs` returns for each choice of `which`, on the pseudo-random matrix of Table 7.24. Extreme eigenvalues (largest or smallest real part, largest imaginary part) converge in a few hundred products. The six nearest , in the interior of the spectrum, need shift-invert: 52 solves with the LU factors of .

Strengths

  • One LinearOperator interface for every solver, so matrix-free operators and preconditioners plug in directly.
  • Iteration counts and solutions that match SciPy, and a strict, documented stopping rule.
  • A sparse LU with partial pivoting whose fill equals SuperLU’s under the same ordering, and the orderings to feed it: COLAMD, minimum degree and nested dissection.
  • Incomplete Cholesky, with automatic shifting, for conjugate gradients.
  • eigsh and svds that find repeated eigenvalues and singular values, by deflation.
  • eigs for nonsymmetric matrices, with real arithmetic throughout and fewer products than ARPACK on every test of Table 7.28.

Weaknesses

  • The library’s minimum degree has 4–12 % more fill than SuperLU’s MMD on the largest grids tested (400 × 400 and 800 × 800), and nested dissection has more fill than minimum degree up to 800 × 800. There are no supernodes or BLAS-3 kernels.
  • No algebraic multigrid or other advanced preconditioners, and the incomplete Cholesky factors have no ordering of their own (MIC may break down on matrices that are not M-matrices and then restarts with a shift, as IC(0) does): reorder first (reverse Cuthill-McKee, for example) if the iteration count matters.
  • eigsh’s full reorthogonalisation costs , where ARPACK’s implicit restarts keep the subspace small.
  • Complex sparse matrices have storage, products, LU, CG, GMRES and BiCGSTAB only (see above), and eigs_shift_invert accepts only a real shift.
  • eigs finds one copy of a repeated eigenvalue per Krylov subspace, like ARPACK; it has no deflation like eigsh’s.
  • Interior eigenvalues without a shift (SmallestMagnitude, or a small |Im λ| in the middle of the spectrum) converge very slowly, as with ARPACK.

Exercises

  1. Write the CSR arrays of the tridiagonal matrix with 2 on the diagonal and −1 beside it, and count the operations of a product.
  2. Show that the CG residuals are mutually orthogonal and that the directions are -conjugate.
  3. Explain why CG terminates in at most steps in exact arithmetic when has distinct eigenvalues.
  4. For the Laplacian on an grid, estimate the CG iterations needed to reduce the error by , and compare with Table 7.18 for .
  5. Show that MINRES and full GMRES produce the same iterates for symmetric .
  6. Why can a Krylov subspace of a symmetric matrix contain only one vector from each eigenspace?
  7. Show that if and , then .
  8. Let be the first columns of a unitary , and suppose their span is closed under complex conjugation. Show that has rank and spans a real subspace invariant under the real matrix whenever is.
  9. Show that the fill of nested dissection on an grid is .
  10. Why can IC(0) of a symmetric positive definite matrix fail, when the exact Cholesky factorisation cannot? Why does adding with large enough always succeed?
  11. For an matrix with , bound the fill of in by that of the Cholesky factor of , and explain why COLAMD works for QR as well as LU.
Hints and answers
  1. indptr = [0, 2, 5, 8, 10], indices = [0, 1, 0, 1, 2, 1, 2, 3, 2, 3], data = [2, −1, −1, 2, −1, −1, 2, −1, −1, 2]. A product takes 10 multiplications and 6 additions, against 16 multiplications dense.

  2. By induction: with chosen so that , and so that is conjugate to . The short recurrence suffices because is symmetric.

  3. minimises over polynomials of degree with . The polynomial over the distinct eigenvalues vanishes on the spectrum.

  4. and . A factor needs steps by the bound. The actual count is 87: the bound is pessimistic.

  5. Both minimise over . For symmetric , the Arnoldi Hessenberg matrix is the Lanczos tridiagonal.

  6. Write , with the component in eigenspace . Then , so every Krylov vector lies in the span of the : one direction per eigenspace.

  7. .

  8. If , then , so and lie in . Hence the real vectors , span the real subspace , whose complex span is , so its real dimension is . Invariance: is real, so .

  9. At depth there are pieces, each cut by a separator of about vertices. Its dense block holds about entries, so a level holds entries in all, and there are levels. The coupling of each piece to the separators above it adds entries of the same order.

  10. In the exact factorisation every pivot is a diagonal entry of a Schur complement, which is positive definite. IC(0) discards updates outside the pattern, so what remains is no longer a Schur complement, and a pivot can reach zero. If is strictly diagonally dominant with positive diagonal, as it is for large, then every pivot of the incomplete factorisation stays positive (Manteuffel, 1980).

  11. , so is the Cholesky factor of and its pattern is the one COLAMD minimises. George and Ng showed that for any row pivoting the patterns of and lie inside those of and .

Further reading

  • Y. Saad, Iterative Methods for Sparse Linear Systems, 2nd ed., SIAM, 2003.
  • T. A. Davis, Direct Methods for Sparse Linear Systems, SIAM, 2006 (the Gilbert-Peierls algorithm, orderings and CSparse).
  • J. R. Shewchuk, “An introduction to the conjugate gradient method without the agonizing pain”, 1994.
  • C. C. Paige and M. A. Saunders, “Solution of sparse indefinite systems of linear equations”, SIAM Journal on Numerical Analysis 12 (1975) 617–629; “LSQR: an algorithm for sparse linear equations and sparse least squares”, ACM Transactions on Mathematical Software 8 (1982) 43–71.
  • A. H. Baker, E. R. Jessup and T. Manteuffel, “A technique for accelerating the convergence of restarted GMRES”, SIAM Journal on Matrix Analysis and Applications 26 (2005) 962–984.
  • Y. Saad and M. H. Schultz, “GMRES: a generalized minimal residual algorithm for solving nonsymmetric linear systems”, SIAM Journal on Scientific and Statistical Computing 7 (1986) 856–869.
  • H. A. van der Vorst, “Bi-CGSTAB: a fast and smoothly converging variant of Bi-CG for the solution of nonsymmetric linear systems”, SIAM Journal on Scientific and Statistical Computing 13 (1992) 631–644.
  • A. George, “Nested dissection of a regular finite element mesh”, SIAM Journal on Numerical Analysis 10 (1973) 345–363.
  • P. R. Amestoy, T. A. Davis and I. S. Duff, “An approximate minimum degree ordering algorithm”, SIAM Journal on Matrix Analysis and Applications 17 (1996) 886–905.
  • T. A. Davis, J. R. Gilbert, S. I. Larimore and E. G. Ng, “A column approximate minimum degree ordering algorithm”, ACM Transactions on Mathematical Software 30 (2004) 353–376.
  • G. Karypis and V. Kumar, “A fast and high quality multilevel scheme for partitioning irregular graphs”, SIAM Journal on Scientific Computing 20 (1998) 359–392.
  • C. M. Fiduccia and R. M. Mattheyses, “A linear-time heuristic for improving network partitions”, Proceedings of the 19th Design Automation Conference (1982) 175–181.
  • J. A. Meijerink and H. A. van der Vorst, “An iterative solution method for linear systems of which the coefficient matrix is a symmetric M-matrix”, Mathematics of Computation 31 (1977) 148–162.
  • T. A. Manteuffel, “An incomplete factorization technique for positive definite linear systems”, Mathematics of Computation 34 (1980) 473–497.
  • E. Cuthill and J. McKee, “Reducing the bandwidth of sparse symmetric matrices”, Proceedings of the 24th ACM National Conference (1969) 157–172.
  • J. R. Gilbert and T. Peierls, “Sparse partial pivoting in time proportional to arithmetic operations”, SIAM Journal on Scientific and Statistical Computing 9 (1988) 862–874.
  • M. Embree, “The tortoise and the hare restart GMRES”, SIAM Review 45 (2003) 259–266.
  • W. E. Arnoldi, “The principle of minimized iterations in the solution of the matrix eigenvalue problem”, Quarterly of Applied Mathematics 9 (1951) 17–29.
  • D. C. Sorensen, “Implicit application of polynomial filters in a -step Arnoldi method”, SIAM Journal on Matrix Analysis and Applications 13 (1992) 357–385.
  • R. B. Lehoucq, D. C. Sorensen and C. Yang, ARPACK Users’ Guide, SIAM, 1998.
  • G. W. Stewart, “A Krylov-Schur algorithm for large eigenproblems”, SIAM Journal on Matrix Analysis and Applications 23 (2001) 601–614.
  • B. N. Parlett, The Symmetric Eigenvalue Problem, SIAM, 1998, chapter 13 (Lanczos in practice).
  • W. F. Tinney and J. W. Walker, “Direct solutions of sparse network equations by optimally ordered triangular factorization”, Proceedings of the IEEE 55 (1967) 1801–1809.
  • Y. Saad, “ILUT: a dual threshold incomplete LU factorization”, Numerical Linear Algebra with Applications 1 (1994) 387–402.
  • A. H. Al-Mohy and N. J. Higham, “Computing the action of the matrix exponential, with an application to exponential integrators”, SIAM Journal on Scientific Computing 33 (2011) 488–511.