blob: 3f90d5d53a1311f75e322e4059bbe8b39d468711 [file] [log] [blame]
Gael Guennebaud86a19262009-01-16 17:20:12 +00001namespace Eigen {
2
Gael Guennebaud41ea92d2010-07-04 10:14:47 +02003/** \page TutorialSparse Tutorial page 9 - Sparse Matrix
Gael Guennebaud86a19262009-01-16 17:20:12 +00004 \ingroup Tutorial
5
Gael Guennebaud41ea92d2010-07-04 10:14:47 +02006\li \b Previous: \ref TutorialGeometry
7\li \b Next: TODO
Gael Guennebaud86a19262009-01-16 17:20:12 +00008
9\b Table \b of \b contents \n
10 - \ref TutorialSparseIntro
11 - \ref TutorialSparseFilling
12 - \ref TutorialSparseFeatureSet
13 - \ref TutorialSparseDirectSolvers
14<hr>
15
Gael Guennebaud70206ab2011-11-24 17:32:30 +010016Manipulating and solving sparse problems involves various modules which are summarized below:
Gael Guennebaud86a19262009-01-16 17:20:12 +000017
Gael Guennebaudf66fe262010-10-19 11:40:49 +020018<table class="manual">
Gael Guennebaud70206ab2011-11-24 17:32:30 +010019<tr><th>Module</th><th>Header file</th><th>Contents</th></tr>
20<tr><td>\link Sparse_Module SparseCore \endlink</td><td>\code#include <Eigen/SparseCore>\endcode</td><td>SparseMatrix and SparseVector classes, matrix assembly, basic sparse linear algebra (including sparse triangular solvers)</td></tr>
21<tr><td>\link SparseCholesky_Module SparseCholesky \endlink</td><td>\code#include <Eigen/SparseCholesky>\endcode</td><td>Direct sparse LLT and LDLT Cholesky factorization to solve sparse self-adjoint positive definite problems</td></tr>
22<tr><td>\link IterativeLinearSolvers_Module IterativeLinearSolvers \endlink</td><td>\code#include <Eigen/IterativeLinearSolvers>\endcode</td><td>Iterative solvers to solve large general linear square problems (including self-adjoint positive definite problems)</td></tr>
23<tr><td></td><td>\code#include <Eigen/Sparse>\endcode</td><td>Includes all the above modules</td></tr>
Gael Guennebaud86a19262009-01-16 17:20:12 +000024</table>
25
Gael Guennebaud70206ab2011-11-24 17:32:30 +010026\section TutorialSparseIntro Representing sparse matrices
27
28In 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.
29
30\b The \b SparseMatrix \b class
31The class SparseMatrix is the main sparse matrix representation of Eigen's sparse module; it offers high performance and low memory usage.
32It implements a more versatile variant of the widely-used Compressed Column (or Row) Storage scheme.
33It consists of four compact arrays:
34 - \c Values: stores the coefficient values of the non-zeros.
35 - \c InnerIndices: stores the row (resp. column) indices of the non-zeros.
36 - \c OuterIndexPtrs: stores for each colmun (resp. row) the index of the first non zero in the previous arrays.
37 - \c InnerSizes: stores the number of non-zeros of each column (resp. row).
38The word \c inner refers to an \em inner \em vector that is a column for a column-major matrix, or a row for a row-major matrix.
39The word \c outer refers to the other direction.
40
41This storage scheme is better explained on an example. The following matrix
42<table class="manual">
43<tr><td> 0</td><td>3</td><td> 0</td><td>0</td><td> 0</td></tr>
44<tr><td>22</td><td>0</td><td> 0</td><td>0</td><td>17</td></tr>
45<tr><td> 7</td><td>5</td><td> 0</td><td>1</td><td> 0</td></tr>
46<tr><td> 0</td><td>0</td><td> 0</td><td>0</td><td> 0</td></tr>
47<tr><td> 0</td><td>0</td><td>14</td><td>0</td><td> 8</td></tr>
48</table>
49
50and its sparse, \b column \b major representation:
51<table class="manual">
52<tr><td>Values:</td> <td>22</td><td>7</td><td>_</td><td>3</td><td>5</td><td>14</td><td>_</td><td>_</td><td>1</td><td>_</td><td>17</td><td>8</td></tr>
53<tr><td>InnerIndices:</td> <td> 1</td><td>2</td><td>_</td><td>0</td><td>2</td><td> 4</td><td>_</td><td>_</td><td>2</td><td>_</td><td> 1</td><td>4</td></tr>
54</table>
55<table class="manual">
56<tr><td>OuterIndexPtrs:</td><td>0</td><td>3</td><td>5</td><td>8</td><td>10</td><td>\em 12 </td></tr>
57<tr><td>InnerSizes:</td> <td>2</td><td>2</td><td>1</td><td>1</td><td> 2</td><td></td></tr>
58</table>
59
60By default the elements of a given inner vector are always sorted by increasing inner indices.
61The \c _ indicates available free space to quickly insert new elements.
62Assuming no reallocation is needed, the insertion of a random element of coordinate is therefore in O(nnz) where nnz is the number of nonzeros of the respective inner vector.
63On the other hand, inserting elements with increasing inner indices in a given inner vector is much more efficient since this only requires to incresae the respective \c InnerSizes entry that is a O(1) operation.
64
65The case where no empty space is available is a special case, and is refered as the \em compressed mode and it corresponds to the widely used Compressed Column (or Row) Storage scheme.
66Any SparseMatrix can be turned in this form by calling the SparseMatrix::makeCompressed() function.
67In this case one can remark that the \c InnerSizes array is superfluous because \c InnerSizes[j] is simply equals to \c OuterIndexPtrs[j+1]-\c OuterIndexPtrs[j].
68Therefore, a call to SparseMatrix::makeCompressed() frees this buffer.
69
70Here is the previous matrix represented in compressed mode:
Gael Guennebaudf66fe262010-10-19 11:40:49 +020071<table class="manual">
Gael Guennebaud86a19262009-01-16 17:20:12 +000072<tr><td>Values:</td> <td>22</td><td>7</td><td>3</td><td>5</td><td>14</td><td>1</td><td>17</td><td>8</td></tr>
Gael Guennebaud70206ab2011-11-24 17:32:30 +010073<tr><td>InnerIndices:</td> <td> 1</td><td>2</td><td>0</td><td>2</td><td> 4</td><td>2</td><td> 1</td><td>4</td></tr>
Gael Guennebaud86a19262009-01-16 17:20:12 +000074</table>
Gael Guennebaudf66fe262010-10-19 11:40:49 +020075<table class="manual">
Gael Guennebaud70206ab2011-11-24 17:32:30 +010076<tr><td>OuterIndexPtrs:</td><td>0</td><td>2</td><td>4</td><td>5</td><td>6</td><td>\em 8 </td></tr>
Gael Guennebaud25f16582009-01-21 17:44:58 +000077</table>
Gael Guennebaud70206ab2011-11-24 17:32:30 +010078In this mode any insertion of new non zero elements would be extremely costly.
79
Gael Guennebaud25f16582009-01-21 17:44:58 +000080
Gael Guennebaud86a19262009-01-16 17:20:12 +000081
82\b Matrix \b and \b vector \b properties \n
83
Tim Holy16a2d892011-06-20 22:47:58 -050084Here mat and vec represent any sparse-matrix and sparse-vector type, respectively.
Gael Guennebaud25f16582009-01-21 17:44:58 +000085
Gael Guennebaud70206ab2011-11-24 17:32:30 +010086Declarations:
87\code
88SparseMatrix<std::complex<float> > mat(1000,2000); // declare a 1000x2000 col-major compressed sparse matrix of complex<float>
89SparseMatrix<double,RowMajor> mat(1000,2000); // declare a 1000x2000 row-major compressed sparse matrix of double
90SparseVector<std::complex<float> > vec(1000); // declare a column sparse vector of complex<float> of size 1000
91SparseVector<double,RowMajor> vec(1000); // declare a row sparse vector of double of size 1000
92\endcode
93
94Although a sparse matrix could also be used to represent a sparse vector, for that purpose it is better to use the specialized SparseVector class:
95\code
96
97\endcode
98
Gael Guennebaudf66fe262010-10-19 11:40:49 +020099<table class="manual">
Gael Guennebaud86a19262009-01-16 17:20:12 +0000100<tr><td>Standard \n dimensions</td><td>\code
101mat.rows()
102mat.cols()\endcode</td>
103<td>\code
104vec.size() \endcode</td>
105</tr>
106<tr><td>Sizes along the \n inner/outer dimensions</td><td>\code
107mat.innerSize()
108mat.outerSize()\endcode</td>
109<td></td>
110</tr>
Tim Holy16a2d892011-06-20 22:47:58 -0500111<tr><td>Number of non \n zero coefficients</td><td>\code
Gael Guennebaud86a19262009-01-16 17:20:12 +0000112mat.nonZeros() \endcode</td>
113<td>\code
114vec.nonZeros() \endcode</td></tr>
115</table>
116
Gael Guennebaud25f16582009-01-21 17:44:58 +0000117
Gael Guennebaud86a19262009-01-16 17:20:12 +0000118\b Iterating \b over \b the \b nonzero \b coefficients \n
119
Tim Holy16a2d892011-06-20 22:47:58 -0500120Iterating over the coefficients of a sparse matrix can be done only in the same order as the storage order. Here is an example:
Gael Guennebaudf66fe262010-10-19 11:40:49 +0200121<table class="manual">
Gael Guennebaud86a19262009-01-16 17:20:12 +0000122<tr><td>
123\code
Gael Guennebaud25f16582009-01-21 17:44:58 +0000124SparseMatrixType mat(rows,cols);
Jitse Niesen59b83c12011-09-10 09:18:18 +0100125for (int k=0; k<mat.outerSize(); ++k)
Gael Guennebaud25f16582009-01-21 17:44:58 +0000126 for (SparseMatrixType::InnerIterator it(mat,k); it; ++it)
Gael Guennebaud86a19262009-01-16 17:20:12 +0000127 {
128 it.value();
129 it.row(); // row index
130 it.col(); // col index (here it is equal to k)
131 it.index(); // inner index, here it is equal to it.row()
132 }
133\endcode
134</td><td>
135\code
Gael Guennebaud25f16582009-01-21 17:44:58 +0000136SparseVector<double> vec(size);
137for (SparseVector<double>::InnerIterator it(vec); it; ++it)
Gael Guennebaud86a19262009-01-16 17:20:12 +0000138{
Gael Guennebaud25f16582009-01-21 17:44:58 +0000139 it.value(); // == vec[ it.index() ]
Gael Guennebaudc532f422009-09-25 16:30:44 +0200140 it.index();
Gael Guennebaud86a19262009-01-16 17:20:12 +0000141}
142\endcode
143</td></tr>
144</table>
145
Jitse Niesen59b83c12011-09-10 09:18:18 +0100146If the type of the sparse matrix or vector depends on a template parameter, then the \c typename keyword is
147required to indicate that \c InnerIterator denotes a type; see \ref TopicTemplateKeyword for details.
148
Gael Guennebaud86a19262009-01-16 17:20:12 +0000149\section TutorialSparseFilling Filling a sparse matrix
150
Gael Guennebaud70206ab2011-11-24 17:32:30 +0100151Because of the special storage scheme of a SparseMatrix, special care has to be taken when adding new nonzero entries.
152For 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.
Gael Guennebaudc532f422009-09-25 16:30:44 +0200153
Gael Guennebaud70206ab2011-11-24 17:32:30 +0100154A typical scenario to insert nonzeros is illustrated bellow:
Gael Guennebaud25f16582009-01-21 17:44:58 +0000155\code
Gael Guennebaud70206ab2011-11-24 17:32:30 +01001561: SparseMatrix<double> m(rows,cols); // default is column major
1572: aux.reserve(VectorXi::Constant(rows,6));
1583: for each i,j such that v_ij != 0
1594: mat.insert(i,j) = v_ij;
1605: mat.makeCompressed(); // optional
Gael Guennebaud25f16582009-01-21 17:44:58 +0000161\endcode
162
Gael Guennebaud70206ab2011-11-24 17:32:30 +0100163- The key ingredient here is the line 2 where we reserve room for 6 non zeros per column. In many cases, the number of non zero per column or row can be easily known in advance. If it varies significantly for each inner vector, then it is possible to specify a reserve size for each inner vector by provifing a VectorXi or std::vector compatible object. 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.
164- The line 4 performs a sorted insertion. In this example, the ideal case is when the 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.
165- The line 5 suppresses the left empty room and transform the matrix to a compressed column storage.
Gael Guennebaud25f16582009-01-21 17:44:58 +0000166
Gael Guennebaud25f16582009-01-21 17:44:58 +0000167
Gael Guennebaud86a19262009-01-16 17:20:12 +0000168\section TutorialSparseFeatureSet Supported operators and functions
169
Tim Holy16a2d892011-06-20 22:47:58 -0500170In the following \em sm denotes a sparse matrix, \em sv a sparse vector, \em dm a dense matrix, and \em dv a dense vector.
171In 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:
Gael Guennebaud86a19262009-01-16 17:20:12 +0000172\code
173SparseMatrixType sm1, sm2, sm3;
Tim Holy16a2d892011-06-20 22:47:58 -0500174sm3 = sm1.transpose() + sm2; // invalid, because transpose() changes the storage order
175sm3 = SparseMatrixType(sm1.transpose()) + sm2; // correct, because evaluation reformats as column-major
Gael Guennebaud86a19262009-01-16 17:20:12 +0000176\endcode
177
Tim Holy16a2d892011-06-20 22:47:58 -0500178Here are some examples of supported operations:
Gael Guennebaud86a19262009-01-16 17:20:12 +0000179\code
Tim Holy16a2d892011-06-20 22:47:58 -0500180sm1 *= 0.5;
181sm4 = sm1 + sm2 + sm3; // only if sm1, sm2 and sm3 have the same storage order
Gael Guennebaud86a19262009-01-16 17:20:12 +0000182sm3 = sm1 * sm2;
183dv3 = sm1 * dv2;
184dm3 = sm1 * dm2;
185dm3 = dm2 * sm1;
Tim Holy16a2d892011-06-20 22:47:58 -0500186sm3 = sm1.cwiseProduct(sm2); // only if sm1 and sm2 have the same storage order
Gael Guennebaud41ea92d2010-07-04 10:14:47 +0200187dv2 = sm1.triangularView<Upper>().solve(dv2);
Gael Guennebaud86a19262009-01-16 17:20:12 +0000188\endcode
189
Tim Holy16a2d892011-06-20 22:47:58 -0500190The product of a sparse \em symmetric matrix A with a dense matrix (or vector) d can be optimized by specifying the symmetry of A using selfadjointView:
Gael Guennebaud86a19262009-01-16 17:20:12 +0000191\code
Tim Holy16a2d892011-06-20 22:47:58 -0500192res = A.selfadjointView<>() * d; // if all coefficients of A are stored
193res = A.selfadjointView<Upper>() * d; // if only the upper part of A is stored
194res = A.selfadjointView<Lower>() * d; // if only the lower part of A is stored
Gael Guennebaud86a19262009-01-16 17:20:12 +0000195\endcode
196
197
Gael Guennebaud70206ab2011-11-24 17:32:30 +0100198\section TutorialSparseDirectSolvers Solving linear problems
Gael Guennebaud86a19262009-01-16 17:20:12 +0000199
Gael Guennebaud70206ab2011-11-24 17:32:30 +0100200Eigen currently provides a limited set of built-in solvers as well as wrappers to external solver libraries.
201They are summarized in the following table:
Gael Guennebaudab41c182010-08-18 15:33:58 +0200202
Gael Guennebaud70206ab2011-11-24 17:32:30 +0100203<table class="manual">
204<tr><td>Class </td><td>Module</td><td>Solver kind</td><td>Matrix kind</td><td>Features related to performance</td>
205 <td>Dependencies,License</td>
206 <td>Notes</td></tr>
Gael Guennebaudab41c182010-08-18 15:33:58 +0200207
Gael Guennebaud70206ab2011-11-24 17:32:30 +0100208<tr><td>SimplicialLLt </td><td>\link SparseCholesky_Module SparseCholesky \endlink</td><td>Direct LLt factorization</td><td>SPD</td><td>Fill-in reducing</td>
209 <td>built-in, LGPL</td>
210 <td>SimplicialLDLt is often preferable</td></tr>
211<tr><td>SimplicialLDLt </td><td>\link SparseCholesky_Module SparseCholesky \endlink</td><td>Direct LDLt factorization</td><td>SPD</td><td>Fill-in reducing</td>
212 <td>built-in, LGPL</td>
213 <td>Recommended for very sparse and not too large problems (e.g., 2D Poisson eq.)</td></tr>
214<tr><td>ConjugateGradient</td><td>\link IterativeLinearSolvers_Module IterativeLinearSolvers \endlink</td><td>Classic iterative CG</td><td>SPD</td><td>Preconditionning</td>
215 <td>built-in, LGPL</td>
216 <td>Recommended for large symmetric problems (e.g., 3D Poisson eq.)</td></tr>
217<tr><td>BiCGSTAB</td><td>\link IterativeLinearSolvers_Module IterativeLinearSolvers \endlink</td><td>Iterative stabilized bi-conjugate gradient</td><td>Square</td><td>Preconditionning</td>
218 <td>built-in, LGPL</td>
219 <td>Might not always converge</td></tr>
220
221
222
223<tr><td>CholmodDecomposition</td><td>\link CholmodSupport_Module CholmodSupport \endlink</td><td>Direct LLT factorization</td><td>SPD</td><td>Fill-in reducing, Leverage fast dense algebra</td>
224 <td>Requires the <a href="http://www.cise.ufl.edu/research/sparse/SuiteSparse/">SuiteSparse</a> package, \b GPL </td>
225 <td></td></tr>
226<tr><td>UmfPackLU</td><td>\link UmfPackSupport_Module UmfPackSupport \endlink</td><td>Direct LU factorization</td><td>Square</td><td>Fill-in reducing, Leverage fast dense algebra</td>
227 <td>Requires the <a href="http://www.cise.ufl.edu/research/sparse/SuiteSparse/">SuiteSparse</a> package, \b GPL </td>
228 <td></td></tr>
229<tr><td>SuperLU</td><td>\link SuperLUSupport_Module SuperLUSupport \endlink</td><td>Direct LU factorization</td><td>Square</td><td>Fill-in reducing, Leverage fast dense algebra</td>
230 <td>Requires the <a href="http://crd-legacy.lbl.gov/~xiaoye/SuperLU/">SuperLU</a> library, custom (BSD-like)</td>
231 <td></td></tr>
232</table>
233
234Here \c SPD means symmetric positive definite.
235
236All these solvers follow the same general concept.
237Here is a typical and general example:
Gael Guennebaudab41c182010-08-18 15:33:58 +0200238\code
Gael Guennebaud70206ab2011-11-24 17:32:30 +0100239#include <Eigen/RequiredModuleName>
Gael Guennebaudab41c182010-08-18 15:33:58 +0200240// ...
241SparseMatrix<double> A;
242// fill A
243VectorXd b, x;
244// fill b
Gael Guennebaud70206ab2011-11-24 17:32:30 +0100245// solve Ax = b
246SolverClassName<SparseMatrix<double> > solver;
247solver.compute(A);
248if(solver.info()!=Succeeded) {
Tim Holy16a2d892011-06-20 22:47:58 -0500249 // decomposition failed
Gael Guennebaudab41c182010-08-18 15:33:58 +0200250 return;
251}
Gael Guennebaud70206ab2011-11-24 17:32:30 +0100252x = solver.solve(b);
253if(solver.info()!=Succeeded) {
Gael Guennebaudab41c182010-08-18 15:33:58 +0200254 // solving failed
255 return;
256}
Gael Guennebaud70206ab2011-11-24 17:32:30 +0100257// solve for another right hand side:
258x1 = solver.solve(b1);
Gael Guennebaudab41c182010-08-18 15:33:58 +0200259\endcode
260
Gael Guennebaud70206ab2011-11-24 17:32:30 +0100261For \c SPD solvers, a second optional template argument allows to specify which triangular part have to be used, e.g.:
262
263\code
264#include <Eigen/IterativeLinearSolvers>
265
266ConjugateGradient<SparseMatrix<double>, Eigen::Upper> solver;
267x = solver.compute(A).solve(b);
268\endcode
269In 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.
270
271In the case where multiple problems with the same sparcity pattern have to be solved, then the "compute" step can be decomposed as follow:
272\code
273SolverClassName<SparseMatrix<double> > solver;
274solver.analyzePattern(A); // for this step the numerical values of A are not used
275solver.factorize(A);
276x1 = solver.solve(b1);
277x2 = solver.solve(b2);
278...
279A = ...; // modify the values of the nonzeros of A, the nonzeros pattern must stay unchanged
280solver.factorize(A);
281x1 = solver.solve(b1);
282x2 = solver.solve(b2);
283...
284\endcode
285The compute() methode is equivalent to calling both analyzePattern() and factorize().
286
287Finally, each solver provides some specific features, such as determinant, access to the factors, controls of the iterations, etc.
288More details are availble on the documentation of the respective classes.
Gael Guennebaud86a19262009-01-16 17:20:12 +0000289
Gael Guennebaud41ea92d2010-07-04 10:14:47 +0200290\li \b Next: TODO
Gael Guennebaud86a19262009-01-16 17:20:12 +0000291
292*/
293
294}