blob: ae96d77c41e9987836648d7f87a1035183b4df13 [file] [log] [blame]
Gael Guennebaud86a19262009-01-16 17:20:12 +00001namespace Eigen {
2
Jitse Niesen90735b62009-08-22 20:12:47 +01003/** \page TutorialSparse Tutorial 4/4 - Getting started with the sparse module
Gael Guennebaud86a19262009-01-16 17:20:12 +00004 \ingroup Tutorial
5
6<div class="eimainmenu">\ref index "Overview"
7 | \ref TutorialCore "Core features"
8 | \ref TutorialGeometry "Geometry"
9 | \ref TutorialAdvancedLinearAlgebra "Advanced linear algebra"
10 | \b Sparse \b matrix
11</div>
12
13\b Table \b of \b contents \n
14 - \ref TutorialSparseIntro
15 - \ref TutorialSparseFilling
16 - \ref TutorialSparseFeatureSet
17 - \ref TutorialSparseDirectSolvers
18<hr>
19
Gael Guennebaud25f16582009-01-21 17:44:58 +000020\section TutorialSparseIntro Sparse matrix representations
Gael Guennebaud86a19262009-01-16 17:20:12 +000021
22In many applications (e.g., finite element methods) it is common to deal with very large matrices where only a few coefficients are different than zero. Both in term of memory consumption and performance, it is fundamental to use an adequate representation storing only nonzero coefficients. Such a matrix is called a sparse matrix.
23
Gael Guennebaud25f16582009-01-21 17:44:58 +000024\b Declaring \b sparse \b matrices \b and \b vectors \n
25The SparseMatrix class is the main sparse matrix representation of the Eigen's sparse module which offers high performance, low memory usage, and compatibility with most of sparse linear algebra packages. Because of its limited flexibility, we also provide a DynamicSparseMatrix variante taillored for low-level sparse matrix assembly. Both of them can be either row major or column major:
26
27\code
28#include <Eigen/Sparse>
29SparseMatrix<std::complex<float> > m1(1000,2000); // declare a 1000x2000 col-major compressed sparse matrix of complex<float>
30SparseMatrix<double,RowMajor> m2(1000,2000); // declare a 1000x2000 row-major compressed sparse matrix of double
31DynamicSparseMatrix<std::complex<float> > m1(1000,2000); // declare a 1000x2000 col-major dynamic sparse matrix of complex<float>
32DynamicSparseMatrix<double,RowMajor> m2(1000,2000); // declare a 1000x2000 row-major dynamic sparse matrix of double
33\endcode
34
35Although a sparse matrix could also be used to represent a sparse vector, for that purpose it is better to use the specialized SparseVector class:
36\code
37SparseVector<std::complex<float> > v1(1000); // declare a column sparse vector of complex<float> of size 1000
38SparseVector<double,RowMajor> v2(1000); // declare a row sparse vector of double of size 1000
39\endcode
40Note that here the size of a vector denotes its dimension and not the number of nonzero coefficients which is initially zero (like sparse matrices).
41
42
43\b Overview \b of \b the \b internal \b sparse \b storage \n
44In order to get the best of the Eigen's sparse objects, it is important to have a rough idea of the way they are internally stored. The SparseMatrix class implements the common and generic Compressed Column/Row Storage scheme. It consists of three compact arrays storing the values with their respective inner coordinates, and pointer indices to the begining of each outer vector. For instance, let \c m be a column-major sparse matrix. Then its nonzero coefficients are sequentially stored in memory in a column-major order (\em values). A second array of integer stores the respective row index of each coefficient (\em inner \em indices). Finally, a third array of integer, having the same length than the number of columns, stores the index in the previous arrays of the first element of each column (\em outer \em indices).
Gael Guennebaud86a19262009-01-16 17:20:12 +000045
46Here is an example, with the matrix:
47<table>
48<tr><td>0</td><td>3</td><td>0</td><td>0</td><td>0</td></tr>
49<tr><td>22</td><td>0</td><td>0</td><td>0</td><td>17</td></tr>
50<tr><td>7</td><td>5</td><td>0</td><td>1</td><td>0</td></tr>
51<tr><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td></tr>
52<tr><td>0</td><td>0</td><td>14</td><td>0</td><td>8</td></tr>
53</table>
54
55and its internal representation using the Compressed Column Storage format:
56<table>
57<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>
58<tr><td>Inner indices:</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>
59</table>
60Outer indices:<table><tr><td>0</td><td>2</td><td>4</td><td>5</td><td>6</td><td>\em 7 </td></tr></table>
61
Gael Guennebaud25f16582009-01-21 17:44:58 +000062As you can guess, here the storage order is even more important than with dense matrix. We will therefore often make a clear difference between the \em inner and \em outer dimensions. For instance, it is easy to loop over the coefficients of an \em inner \em vector (e.g., a column of a column-major matrix), but completely inefficient to do the same for an \em outer \em vector (e.g., a row of a col-major matrix).
Gael Guennebaud86a19262009-01-16 17:20:12 +000063
Gael Guennebaud25f16582009-01-21 17:44:58 +000064The SparseVector class implements the same compressed storage scheme but, of course, without any outer index buffer.
Gael Guennebaud86a19262009-01-16 17:20:12 +000065
Gael Guennebaud25f16582009-01-21 17:44:58 +000066Since all nonzero coefficients of such a matrix are sequentially stored in memory, random insertion of new nonzeros can be extremely costly. To overcome this limitation, Eigen's sparse module provides a DynamicSparseMatrix class which is basically implemented as an array of SparseVector. In other words, a DynamicSparseMatrix is a SparseMatrix where the values and inner-indices arrays have been splitted into multiple small and resizable arrays. Assuming the number of nonzeros per inner vector is relatively low, this slight modification allow for very fast random insertion at the cost of a slight memory overhead and a lost of compatibility with other sparse libraries used by some of our highlevel solvers. Note that the major memory overhead comes from the extra memory preallocated by each inner vector to avoid an expensive memory reallocation at every insertion.
Gael Guennebaud86a19262009-01-16 17:20:12 +000067
Gael Guennebaud25f16582009-01-21 17:44:58 +000068To summarize, it is recommanded to use a SparseMatrix whenever this is possible, and reserve the use of DynamicSparseMatrix for matrix assembly purpose when a SparseMatrix is not flexible enough. The respective pro/cons of both representations are summarized in the following table:
69
70<table>
71<tr><td></td> <td>SparseMatrix</td><td>DynamicSparseMatrix</td></tr>
72<tr><td>memory usage</td><td>***</td><td>**</td></tr>
73<tr><td>sorted insertion</td><td>***</td><td>***</td></tr>
74<tr><td>random insertion \n in sorted inner vector</td><td>**</td><td>**</td></tr>
75<tr><td>sorted insertion \n in random inner vector</td><td>-</td><td>***</td></tr>
76<tr><td>random insertion</td><td>-</td><td>**</td></tr>
77<tr><td>coeff wise unary operators</td><td>***</td><td>***</td></tr>
78<tr><td>coeff wise binary operators</td><td>***</td><td>***</td></tr>
79<tr><td>matrix products</td><td>***</td><td>**(*)</td></tr>
80<tr><td>transpose</td><td>**</td><td>***</td></tr>
81<tr><td>redux</td><td>***</td><td>**</td></tr>
82<tr><td>*= scalar</td><td>***</td><td>**</td></tr>
83<tr><td>Compatibility with highlevel solvers \n (TAUCS, Cholmod, SuperLU, UmfPack)</td><td>***</td><td>-</td></tr>
84</table>
85
Gael Guennebaud86a19262009-01-16 17:20:12 +000086
87\b Matrix \b and \b vector \b properties \n
88
Gael Guennebaud25f16582009-01-21 17:44:58 +000089Here mat and vec represents any sparse-matrix and sparse-vector types respectively.
90
Gael Guennebaud86a19262009-01-16 17:20:12 +000091<table>
92<tr><td>Standard \n dimensions</td><td>\code
93mat.rows()
94mat.cols()\endcode</td>
95<td>\code
96vec.size() \endcode</td>
97</tr>
98<tr><td>Sizes along the \n inner/outer dimensions</td><td>\code
99mat.innerSize()
100mat.outerSize()\endcode</td>
101<td></td>
102</tr>
103<tr><td>Number of non \n zero coefficiens</td><td>\code
104mat.nonZeros() \endcode</td>
105<td>\code
106vec.nonZeros() \endcode</td></tr>
107</table>
108
Gael Guennebaud25f16582009-01-21 17:44:58 +0000109
Gael Guennebaud86a19262009-01-16 17:20:12 +0000110\b Iterating \b over \b the \b nonzero \b coefficients \n
111
112Iterating over the coefficients of a sparse matrix can be done only in the same order than the storage order. Here is an example:
113<table>
114<tr><td>
115\code
Gael Guennebaud25f16582009-01-21 17:44:58 +0000116SparseMatrixType mat(rows,cols);
117for (int k=0; k\<m1.outerSize(); ++k)
118 for (SparseMatrixType::InnerIterator it(mat,k); it; ++it)
Gael Guennebaud86a19262009-01-16 17:20:12 +0000119 {
120 it.value();
121 it.row(); // row index
122 it.col(); // col index (here it is equal to k)
123 it.index(); // inner index, here it is equal to it.row()
124 }
125\endcode
126</td><td>
127\code
Gael Guennebaud25f16582009-01-21 17:44:58 +0000128SparseVector<double> vec(size);
129for (SparseVector<double>::InnerIterator it(vec); it; ++it)
Gael Guennebaud86a19262009-01-16 17:20:12 +0000130{
Gael Guennebaud25f16582009-01-21 17:44:58 +0000131 it.value(); // == vec[ it.index() ]
Gael Guennebaudc532f422009-09-25 16:30:44 +0200132 it.index();
Gael Guennebaud86a19262009-01-16 17:20:12 +0000133}
134\endcode
135</td></tr>
136</table>
137
138
139\section TutorialSparseFilling Filling a sparse matrix
140
Gael Guennebaudc532f422009-09-25 16:30:44 +0200141Owing to the special storage scheme of a SparseMatrix, it is obvious that for performance reasons a sparse matrix cannot be filled as easily as a dense matrix. For instance the cost of a purely random insertion into a SparseMatrix is in O(nnz) where nnz is the current number of non zeros. In order to cover all uses cases with best efficiency, Eigen provides various mechanisms, from the easiest but slowest, to the fastest but restrictive one.
142
143If you don't have any prior knowledge about the order your matrix will be filled, then the best choice is to use a DynamicSparseMatrix. With a DynamicSparseMatrix, you can add or modify any coefficients at any time using the coeffRef(row,col) method. Here is an example:
Gael Guennebaud25f16582009-01-21 17:44:58 +0000144\code
145DynamicSparseMatrix<float> aux(1000,1000);
Gael Guennebaudc532f422009-09-25 16:30:44 +0200146aux.reserve(estimated_number_of_non_zero); // optional
Gael Guennebaud25f16582009-01-21 17:44:58 +0000147for (...)
Gael Guennebaudc532f422009-09-25 16:30:44 +0200148 for each j // the j can be random
149 for each i interacting with j // the i can be random
150 aux.coeffRef(i,j) += foo(i,j);
151\endcode
152Then the DynamicSparseMatrix object can be converted to a compact SparseMatrix to be used, e.g., by one of our supported solver:
153\code
154SparseMatrix<float> mat(aux);
Gael Guennebaud25f16582009-01-21 17:44:58 +0000155\endcode
156
Gael Guennebaudc532f422009-09-25 16:30:44 +0200157In order to optimize this process, instead of the generic coeffRef(i,j) method one can also use:
158 - \code m.insert(i,j) = value; \endcode which assumes the coefficient of coordinate (row,col) does not already exist (otherwise this is a programming error and your program will stop).
159 - \code m.insertBack(i,j) = value; \endcode which, in addition to the requirements of insert(), also assumes that the coefficient of coordinate (row,col) will be inserted at the end of the target inner-vector. More precisely, if the matrix m is column major, then the row index of the last non zero coefficient of the j-th column must be smaller than i.
Gael Guennebaud25f16582009-01-21 17:44:58 +0000160
Gael Guennebaud25f16582009-01-21 17:44:58 +0000161
Gael Guennebaudc532f422009-09-25 16:30:44 +0200162Actually, the SparseMatrix class also supports random insertion via the insert() method. However, its uses should be reserved in cases where the inserted non zero is nearly the last one of the compact storage array. In practice, this means it should be used only to perform random (or sorted) insertion into the current inner-vector while filling the inner-vectors in an increasing order. Moreover, with a SparseMatrix an insertion session must be closed by a call to finalize() before any use of the matrix. Here is an example for a column major matrix:
Gael Guennebaud25f16582009-01-21 17:44:58 +0000163
Gael Guennebaud86a19262009-01-16 17:20:12 +0000164\code
Gael Guennebaudc532f422009-09-25 16:30:44 +0200165SparseMatrix<float> mat(1000,1000);
166mat.reserve(estimated_number_of_non_zero); // optional
167for each j // should be in increasing order for performance reasons
168 for each i interacting with j // the i can be random
169 mat.insert(i,j) = foo(i,j); // optional for a DynamicSparseMatrix
170mat.finalize();
Gael Guennebaud86a19262009-01-16 17:20:12 +0000171\endcode
172
Gael Guennebaudc532f422009-09-25 16:30:44 +0200173Finally, the fastest way to fill a SparseMatrix object is to insert the elements in a purely coherence order (increasing inner index per increasing outer index). To this end, Eigen provides a very low but optimal API and illustrated below:
Gael Guennebaud86a19262009-01-16 17:20:12 +0000174
Gael Guennebaud86a19262009-01-16 17:20:12 +0000175\code
Gael Guennebaudc532f422009-09-25 16:30:44 +0200176SparseMatrix<float> mat(1000,1000);
177mat.reserve(estimated_number_of_non_zero); // optional
178for(int j=0; j<1000; ++j)
Gael Guennebaud86a19262009-01-16 17:20:12 +0000179{
Gael Guennebaudc532f422009-09-25 16:30:44 +0200180 mat.startVec(j); // optional for a DynamicSparseMatrix
181 for each i interacting with j // with increasing i
182 mat.insertBack(i,j) = foo(i,j);
Gael Guennebaud86a19262009-01-16 17:20:12 +0000183}
Gael Guennebaudc532f422009-09-25 16:30:44 +0200184mat.finalize(); // optional for a DynamicSparseMatrix
Gael Guennebaud86a19262009-01-16 17:20:12 +0000185\endcode
Gael Guennebaud86a19262009-01-16 17:20:12 +0000186
187
188\section TutorialSparseFeatureSet Supported operators and functions
189
190In the following \em sm denote a sparse matrix, \em sv a sparse vector, \em dm a dense matrix, and \em dv a dense vector.
191In Eigen's sparse module we chose to expose only the subset of the dense matrix API which can be efficiently implemented. Moreover, all combinations are not always possible. For instance, it is not possible to add two sparse matrices having two different storage order. On the other hand it is perfectly fine to evaluate a sparse matrix/expression to a matrix having a different storage order:
192\code
193SparseMatrixType sm1, sm2, sm3;
194sm3 = sm1.transpose() + sm2; // invalid
195sm3 = SparseMatrixType(sm1.transpose()) + sm2; // correct
196\endcode
197
198Here are some examples of the supported operations:
199\code
200s_1 *= 0.5;
201sm4 = sm1 + sm2 + sm3; // only if s_1, s_2 and s_3 have the same storage order
202sm3 = sm1 * sm2;
203dv3 = sm1 * dv2;
204dm3 = sm1 * dm2;
205dm3 = dm2 * sm1;
206sm3 = sm1.cwise() * sm2; // only if s_1 and s_2 have the same storage order
207dv2 = sm1.marked<UpperTriangular>().solveTriangular(dv2);
208\endcode
209
210The product of a sparse matrix A time a dense matrix/vector dv with A symmetric can be optimized by telling that to Eigen:
211\code
212res = A.marked<SeflAdjoint>() * dv; // if all coefficients of A are stored
213res = A.marked<SeflAdjoint|UpperTriangular>() * dv; // if only the upper part of A is stored
214res = A.marked<SeflAdjoint|LowerTriangular>() * dv; // if only the lower part of A is stored
215\endcode
216
217
218\section TutorialSparseDirectSolvers Using the direct solvers
219
220TODO
221
222\subsection TutorialSparseDirectSolvers_LLT LLT
223Cholmod, Taucs.
224
225\subsection TutorialSparseDirectSolvers_LDLT LDLT
226
227
228\subsection TutorialSparseDirectSolvers_LU LU
229SuperLU, UmfPack.
230
231*/
232
233}