Table of contents
Manipulating and solving sparse problems involves various modules which are summarized below:
Module | Header file | Contents |
---|---|---|
SparseCore | #include <Eigen/SparseCore>
| SparseMatrix and SparseVector classes, matrix assembly, basic sparse linear algebra (including sparse triangular solvers) |
SparseCholesky | #include <Eigen/SparseCholesky>
| Direct sparse LLT and LDLT Cholesky factorization to solve sparse self-adjoint positive definite problems |
IterativeLinearSolvers | #include <Eigen/IterativeLinearSolvers>
| Iterative solvers to solve large general linear square problems (including self-adjoint positive definite problems) |
#include <Eigen/Sparse>
| Includes all the above modules |
In many applications (e.g., finite element methods) it is common to deal with very large matrices where only a few coefficients are different from zero. In such cases, memory consumption can be reduced and performance increased by using a specialized representation storing only the nonzero coefficients. Such a matrix is called a sparse matrix.
The SparseMatrix class The class SparseMatrix is the main sparse matrix representation of Eigen's sparse module; it offers high performance and low memory usage. It implements a more versatile variant of the widely-used Compressed Column (or Row) Storage scheme. It consists of four compact arrays:
Values:
stores the coefficient values of the non-zeros.InnerIndices:
stores the row (resp. column) indices of the non-zeros.OuterIndexPtrs:
stores for each colmun (resp. row) the index of the first non zero in the previous arrays.InnerNNZs:
stores the number of non-zeros of each column (resp. row). The word inner
refers to an inner vector that is a column for a column-major matrix, or a row for a row-major matrix. The word outer
refers to the other direction.This storage scheme is better explained on an example. The following matrix
0 | 3 | 0 | 0 | 0 |
22 | 0 | 0 | 0 | 17 |
7 | 5 | 0 | 1 | 0 |
0 | 0 | 0 | 0 | 0 |
0 | 0 | 14 | 0 | 8 |
and one of its possible sparse, column major representation:
Values: | 22 | 7 | _ | 3 | 5 | 14 | _ | _ | 1 | _ | 17 | 8 |
InnerIndices: | 1 | 2 | _ | 0 | 2 | 4 | _ | _ | 2 | _ | 1 | 4 |
OuterIndexPtrs: | 0 | 3 | 5 | 8 | 10 | 12 |
InnerNNZs: | 2 | 2 | 1 | 1 | 2 |
Currently the elements of a given inner vector are guaranteed to be always sorted by increasing inner indices. The "_"
indicates available free space to quickly insert new elements. Assuming no reallocation is needed, the insertion of a random element is therefore in O(nnz_j) where nnz_j is the number of nonzeros of the respective inner vector. On the other hand, inserting elements with increasing inner indices in a given inner vector is much more efficient since this only requires to increase the respective InnerNNZs
entry that is a O(1) operation.
The case where no empty space is available is a special case, and is refered as the compressed mode. It corresponds to the widely used Compressed Column (or Row) Storage schemes (CCS or CRS). Any SparseMatrix can be turned to this form by calling the SparseMatrix::makeCompressed() function. In this case, one can remark that the InnerNNZs
array is redundant with OuterIndexPtrs
because we the equality: InnerNNZs
[j] = OuterIndexPtrs
[j+1]-OuterIndexPtrs
[j]. Therefore, in practice a call to SparseMatrix::makeCompressed() frees this buffer.
It is worth noting that most of our wrappers to external libraries requires compressed matrices as inputs.
The results of Eigen's operations always produces compressed sparse matrices. On the other hand, the insertion of a new element into a SparseMatrix converts this later to the uncompressed mode.
Here is the previous matrix represented in compressed mode:
Values: | 22 | 7 | 3 | 5 | 14 | 1 | 17 | 8 |
InnerIndices: | 1 | 2 | 0 | 2 | 4 | 2 | 1 | 4 |
OuterIndexPtrs: | 0 | 2 | 4 | 5 | 6 | 8 |
A SparseVector is a special case of a SparseMatrix where only the Values
and InnerIndices
arrays are stored. There is no notion of compressed/uncompressed mode for a SparseVector.
Matrix and vector properties
Here mat and vec represent any sparse-matrix and sparse-vector type, respectively.
Declarations:
Standard dimensions | vec.size()
| |
Sizes along the inner/outer dimensions | ||
Number of non zero coefficients | mat.nonZeros()
| vec.nonZeros()
|
Iterating over the nonzero coefficients
Iterating over the coefficients of a sparse matrix can be done only in the same order as the storage order. Here is an example:
SparseMatrixType mat(rows,cols);
for (SparseMatrixType::InnerIterator it(mat,k); it; ++it)
{
it.value();
it.row(); // row index
it.col(); // col index (here it is equal to k)
it.index(); // inner index, here it is equal to it.row()
}
| SparseVector<double> vec(size);
for (SparseVector<double>::InnerIterator it(vec); it; ++it)
{
it.value(); // == vec[ it.index() ]
it.index();
}
|
If the type of the sparse matrix or vector depends on a template parameter, then the typename
keyword is required to indicate that InnerIterator
denotes a type; see The template and typename keywords in C++ for details.
Because of the special storage scheme of a SparseMatrix, special care has to be taken when adding new nonzero entries. For instance, the cost of inserting nnz non zeros in a a single purely random insertion into a SparseMatrix is O(nnz), where nnz is the current number of nonzero coefficients.
The simplest way to create a sparse matrix while guarantying good performance is to first build a list of so called triplets, and then convert it to a SparseMatrix.
Here is a typical usage example:
The std::vector triplets might contain the elements in arbitrary order, and might even contain duplicated elements that will be summed up by setFromTriplets(). See the SparseMatrix::setFromTriplets() function and class Triplet for more details.
In some cases, however, slightly higher performance, and lower memory consumption can be reached by directly inserting the non zeros into the destination matrix. A typical scenario of this approach is illustrated bellow:
j-th
inner vector (e.g., via a VectorXi or std::vector<int>). If only a rought estimate of the number of nonzeros per inner-vector can be obtained, it is highly recommended to overestimate it rather than the opposite. If this line is omitted, then the first insertion of a new element will reserve room for 2 elements per inner vector.j-th
column is not full and contains non-zeros whose inner-indices are smaller than i
. In this case, this operation boils down to trivial O(1) operation.i
,j must not already exists, otherwise use the coeffRef(i,j) method that will allow to, e.g., accumulate values. This method first performs a binary search and finally calls insert(i,j) if the element does not already exist. It is more flexible than insert() but also more costly.In the following sm denotes a sparse matrix, sv a sparse vector, dm a dense matrix, and dv a dense vector. In Eigen's sparse module we chose to expose only the subset of the dense matrix API which can be efficiently implemented. Moreover, not every combination is allowed; for instance, it is not possible to add two sparse matrices having two different storage orders. On the other hand, it is perfectly fine to evaluate a sparse matrix or expression to a matrix having a different storage order:
Here are some examples of supported operations:
The product of a sparse symmetric matrix A with a dense matrix (or vector) d can be optimized by specifying the symmetry of A using selfadjointView:
Eigen currently provides a limited set of built-in solvers as well as wrappers to external solver libraries. They are summarized in the following table:
Class | Module | Solver kind | Matrix kind | Features related to performance | Dependencies,License |
Notes |
SimplicialLLt | SparseCholesky | Direct LLt factorization | SPD | Fill-in reducing | built-in, LGPL | SimplicialLDLt is often preferable |
SimplicialLDLt | SparseCholesky | Direct LDLt factorization | SPD | Fill-in reducing | built-in, LGPL | Recommended for very sparse and not too large problems (e.g., 2D Poisson eq.) |
ConjugateGradient | IterativeLinearSolvers | Classic iterative CG | SPD | Preconditionning | built-in, LGPL | Recommended for large symmetric problems (e.g., 3D Poisson eq.) |
BiCGSTAB | IterativeLinearSolvers | Iterative stabilized bi-conjugate gradient | Square | Preconditionning | built-in, LGPL | Might not always converge |
CholmodDecomposition | CholmodSupport | Direct LLT factorization | SPD | Fill-in reducing, Leverage fast dense algebra | Requires the SuiteSparse package, GPL | |
UmfPackLU | UmfPackSupport | Direct LU factorization | Square | Fill-in reducing, Leverage fast dense algebra | Requires the SuiteSparse package, GPL | |
SuperLU | SuperLUSupport | Direct LU factorization | Square | Fill-in reducing, Leverage fast dense algebra | Requires the SuperLU library, (BSD-like) |
Here SPD
means symmetric positive definite.
All these solvers follow the same general concept. Here is a typical and general example:
For SPD
solvers, a second optional template argument allows to specify which triangular part have to be used, e.g.:
In the above example, only the upper triangular part of the input matrix A is considered for solving. The opposite triangle might either be empty or contain arbitrary values.
In the case where multiple problems with the same sparcity pattern have to be solved, then the "compute" step can be decomposed as follow:
The compute() method is equivalent to calling both analyzePattern() and factorize().
Finally, each solver provides some specific features, such as determinant, access to the factors, controls of the iterations, and so on. More details are availble in the documentations of the respective classes.