You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

338 lines
18 KiB

  1. namespace StormEigen {
  2. /** \eigenManualPage TutorialSparse Sparse matrix manipulations
  3. \eigenAutoToc
  4. Manipulating and solving sparse problems involves various modules which are summarized below:
  5. <table class="manual">
  6. <tr><th>Module</th><th>Header file</th><th>Contents</th></tr>
  7. <tr><td>\link SparseCore_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>
  8. <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>
  9. <tr><td>\link SparseLU_Module SparseLU \endlink</td><td>\code #include<Eigen/SparseLU> \endcode</td>
  10. <td>%Sparse LU factorization to solve general square sparse systems</td></tr>
  11. <tr><td>\link SparseQR_Module SparseQR \endlink</td><td>\code #include<Eigen/SparseQR>\endcode </td><td>%Sparse QR factorization for solving sparse linear least-squares problems</td></tr>
  12. <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>
  13. <tr><td>\link Sparse_Module Sparse \endlink</td><td>\code#include <Eigen/Sparse>\endcode</td><td>Includes all the above modules</td></tr>
  14. </table>
  15. \section TutorialSparseIntro Sparse matrix format
  16. 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.
  17. \b The \b %SparseMatrix \b class
  18. The class SparseMatrix is the main sparse matrix representation of Eigen's sparse module; it offers high performance and low memory usage.
  19. It implements a more versatile variant of the widely-used Compressed Column (or Row) Storage scheme.
  20. It consists of four compact arrays:
  21. - \c Values: stores the coefficient values of the non-zeros.
  22. - \c InnerIndices: stores the row (resp. column) indices of the non-zeros.
  23. - \c OuterStarts: stores for each column (resp. row) the index of the first non-zero in the previous two arrays.
  24. - \c InnerNNZs: stores the number of non-zeros of each column (resp. row).
  25. The 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.
  26. The word \c outer refers to the other direction.
  27. This storage scheme is better explained on an example. The following matrix
  28. <table class="manual">
  29. <tr><td> 0</td><td>3</td><td> 0</td><td>0</td><td> 0</td></tr>
  30. <tr><td>22</td><td>0</td><td> 0</td><td>0</td><td>17</td></tr>
  31. <tr><td> 7</td><td>5</td><td> 0</td><td>1</td><td> 0</td></tr>
  32. <tr><td> 0</td><td>0</td><td> 0</td><td>0</td><td> 0</td></tr>
  33. <tr><td> 0</td><td>0</td><td>14</td><td>0</td><td> 8</td></tr>
  34. </table>
  35. and one of its possible sparse, \b column \b major representation:
  36. <table class="manual">
  37. <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>
  38. <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>
  39. </table>
  40. <table class="manual">
  41. <tr><td>OuterStarts:</td><td>0</td><td>3</td><td>5</td><td>8</td><td>10</td><td>\em 12 </td></tr>
  42. <tr><td>InnerNNZs:</td> <td>2</td><td>2</td><td>1</td><td>1</td><td> 2</td><td></td></tr>
  43. </table>
  44. Currently the elements of a given inner vector are guaranteed to be always sorted by increasing inner indices.
  45. The \c "_" indicates available free space to quickly insert new elements.
  46. 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.
  47. 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 \c InnerNNZs entry that is a O(1) operation.
  48. The case where no empty space is available is a special case, and is refered as the \em compressed mode.
  49. It corresponds to the widely used Compressed Column (or Row) Storage schemes (CCS or CRS).
  50. Any SparseMatrix can be turned to this form by calling the SparseMatrix::makeCompressed() function.
  51. In this case, one can remark that the \c InnerNNZs array is redundant with \c OuterStarts because we the equality: \c InnerNNZs[j] = \c OuterStarts[j+1]-\c OuterStarts[j].
  52. Therefore, in practice a call to SparseMatrix::makeCompressed() frees this buffer.
  53. It is worth noting that most of our wrappers to external libraries requires compressed matrices as inputs.
  54. The results of %Eigen's operations always produces \b compressed sparse matrices.
  55. On the other hand, the insertion of a new element into a SparseMatrix converts this later to the \b uncompressed mode.
  56. Here is the previous matrix represented in compressed mode:
  57. <table class="manual">
  58. <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>
  59. <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>
  60. </table>
  61. <table class="manual">
  62. <tr><td>OuterStarts:</td><td>0</td><td>2</td><td>4</td><td>5</td><td>6</td><td>\em 8 </td></tr>
  63. </table>
  64. A SparseVector is a special case of a SparseMatrix where only the \c Values and \c InnerIndices arrays are stored.
  65. There is no notion of compressed/uncompressed mode for a SparseVector.
  66. \section TutorialSparseExample First example
  67. Before describing each individual class, let's start with the following typical example: solving the Laplace equation \f$ \Delta u = 0 \f$ on a regular 2D grid using a finite difference scheme and Dirichlet boundary conditions.
  68. Such problem can be mathematically expressed as a linear problem of the form \f$ Ax=b \f$ where \f$ x \f$ is the vector of \c m unknowns (in our case, the values of the pixels), \f$ b \f$ is the right hand side vector resulting from the boundary conditions, and \f$ A \f$ is an \f$ m \times m \f$ matrix containing only a few non-zero elements resulting from the discretization of the Laplacian operator.
  69. <table class="manual">
  70. <tr><td>
  71. \include Tutorial_sparse_example.cpp
  72. </td>
  73. <td>
  74. \image html Tutorial_sparse_example.jpeg
  75. </td></tr></table>
  76. In this example, we start by defining a column-major sparse matrix type of double \c SparseMatrix<double>, and a triplet list of the same scalar type \c Triplet<double>. A triplet is a simple object representing a non-zero entry as the triplet: \c row index, \c column index, \c value.
  77. In the main function, we declare a list \c coefficients of triplets (as a std vector) and the right hand side vector \f$ b \f$ which are filled by the \a buildProblem function.
  78. The raw and flat list of non-zero entries is then converted to a true SparseMatrix object \c A.
  79. Note that the elements of the list do not have to be sorted, and possible duplicate entries will be summed up.
  80. The last step consists of effectively solving the assembled problem.
  81. Since the resulting matrix \c A is symmetric by construction, we can perform a direct Cholesky factorization via the SimplicialLDLT class which behaves like its LDLT counterpart for dense objects.
  82. The resulting vector \c x contains the pixel values as a 1D array which is saved to a jpeg file shown on the right of the code above.
  83. Describing the \a buildProblem and \a save functions is out of the scope of this tutorial. They are given \ref TutorialSparse_example_details "here" for the curious and reproducibility purpose.
  84. \section TutorialSparseSparseMatrix The SparseMatrix class
  85. \b %Matrix \b and \b vector \b properties \n
  86. The SparseMatrix and SparseVector classes take three template arguments:
  87. * the scalar type (e.g., double)
  88. * the storage order (ColMajor or RowMajor, the default is ColMajor)
  89. * the inner index type (default is \c int).
  90. As for dense Matrix objects, constructors takes the size of the object.
  91. Here are some examples:
  92. \code
  93. SparseMatrix<std::complex<float> > mat(1000,2000); // declares a 1000x2000 column-major compressed sparse matrix of complex<float>
  94. SparseMatrix<double,RowMajor> mat(1000,2000); // declares a 1000x2000 row-major compressed sparse matrix of double
  95. SparseVector<std::complex<float> > vec(1000); // declares a column sparse vector of complex<float> of size 1000
  96. SparseVector<double,RowMajor> vec(1000); // declares a row sparse vector of double of size 1000
  97. \endcode
  98. In the rest of the tutorial, \c mat and \c vec represent any sparse-matrix and sparse-vector objects, respectively.
  99. The dimensions of a matrix can be queried using the following functions:
  100. <table class="manual">
  101. <tr><td>Standard \n dimensions</td><td>\code
  102. mat.rows()
  103. mat.cols()\endcode</td>
  104. <td>\code
  105. vec.size() \endcode</td>
  106. </tr>
  107. <tr><td>Sizes along the \n inner/outer dimensions</td><td>\code
  108. mat.innerSize()
  109. mat.outerSize()\endcode</td>
  110. <td></td>
  111. </tr>
  112. <tr><td>Number of non \n zero coefficients</td><td>\code
  113. mat.nonZeros() \endcode</td>
  114. <td>\code
  115. vec.nonZeros() \endcode</td></tr>
  116. </table>
  117. \b Iterating \b over \b the \b nonzero \b coefficients \n
  118. Random access to the elements of a sparse object can be done through the \c coeffRef(i,j) function.
  119. However, this function involves a quite expensive binary search.
  120. In most cases, one only wants to iterate over the non-zeros elements. This is achieved by a standard loop over the outer dimension, and then by iterating over the non-zeros of the current inner vector via an InnerIterator. Thus, the non-zero entries have to be visited in the same order than the storage order.
  121. Here is an example:
  122. <table class="manual">
  123. <tr><td>
  124. \code
  125. SparseMatrix<double> mat(rows,cols);
  126. for (int k=0; k<mat.outerSize(); ++k)
  127. for (SparseMatrix<double>::InnerIterator it(mat,k); it; ++it)
  128. {
  129. it.value();
  130. it.row(); // row index
  131. it.col(); // col index (here it is equal to k)
  132. it.index(); // inner index, here it is equal to it.row()
  133. }
  134. \endcode
  135. </td><td>
  136. \code
  137. SparseVector<double> vec(size);
  138. for (SparseVector<double>::InnerIterator it(vec); it; ++it)
  139. {
  140. it.value(); // == vec[ it.index() ]
  141. it.index();
  142. }
  143. \endcode
  144. </td></tr>
  145. </table>
  146. For a writable expression, the referenced value can be modified using the valueRef() function.
  147. If the type of the sparse matrix or vector depends on a template parameter, then the \c typename keyword is
  148. required to indicate that \c InnerIterator denotes a type; see \ref TopicTemplateKeyword for details.
  149. \section TutorialSparseFilling Filling a sparse matrix
  150. Because of the special storage scheme of a SparseMatrix, special care has to be taken when adding new nonzero entries.
  151. For instance, the cost of a single purely random insertion into a SparseMatrix is \c O(nnz), where \c nnz is the current number of non-zero coefficients.
  152. The simplest way to create a sparse matrix while guaranteeing good performance is thus to first build a list of so-called \em triplets, and then convert it to a SparseMatrix.
  153. Here is a typical usage example:
  154. \code
  155. typedef StormEigen::Triplet<double> T;
  156. std::vector<T> tripletList;
  157. tripletList.reserve(estimation_of_entries);
  158. for(...)
  159. {
  160. // ...
  161. tripletList.push_back(T(i,j,v_ij));
  162. }
  163. SparseMatrixType mat(rows,cols);
  164. mat.setFromTriplets(tripletList.begin(), tripletList.end());
  165. // mat is ready to go!
  166. \endcode
  167. The \c std::vector of triplets might contain the elements in arbitrary order, and might even contain duplicated elements that will be summed up by setFromTriplets().
  168. See the SparseMatrix::setFromTriplets() function and class Triplet for more details.
  169. In some cases, however, slightly higher performance, and lower memory consumption can be reached by directly inserting the non-zeros into the destination matrix.
  170. A typical scenario of this approach is illustrated bellow:
  171. \code
  172. 1: SparseMatrix<double> mat(rows,cols); // default is column major
  173. 2: mat.reserve(VectorXi::Constant(cols,6));
  174. 3: for each i,j such that v_ij != 0
  175. 4: mat.insert(i,j) = v_ij; // alternative: mat.coeffRef(i,j) += v_ij;
  176. 5: mat.makeCompressed(); // optional
  177. \endcode
  178. - 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-zeros per column or row can easily be 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 providing a vector object with an operator[](int j) returning the reserve size of the \c 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.
  179. - The line 4 performs a sorted insertion. In this example, the ideal case is when the \c j-th column is not full and contains non-zeros whose inner-indices are smaller than \c i. In this case, this operation boils down to trivial O(1) operation.
  180. - When calling insert(i,j) the element \c i \c ,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.
  181. - The line 5 suppresses the remaining empty space and transforms the matrix into a compressed column storage.
  182. \section TutorialSparseFeatureSet Supported operators and functions
  183. Because of their special storage format, sparse matrices cannot offer the same level of flexibility than dense matrices.
  184. In Eigen's sparse module we chose to expose only the subset of the dense matrix API which can be efficiently implemented.
  185. In the following \em sm denotes a sparse matrix, \em sv a sparse vector, \em dm a dense matrix, and \em dv a dense vector.
  186. \subsection TutorialSparse_BasicOps Basic operations
  187. %Sparse expressions support most of the unary and binary coefficient wise operations:
  188. \code
  189. sm1.real() sm1.imag() -sm1 0.5*sm1
  190. sm1+sm2 sm1-sm2 sm1.cwiseProduct(sm2)
  191. \endcode
  192. However, a strong restriction is that the storage orders must match. For instance, in the following example:
  193. \code
  194. sm4 = sm1 + sm2 + sm3;
  195. \endcode
  196. sm1, sm2, and sm3 must all be row-major or all column major.
  197. On the other hand, there is no restriction on the target matrix sm4.
  198. For instance, this means that for computing \f$ A^T + A \f$, the matrix \f$ A^T \f$ must be evaluated into a temporary matrix of compatible storage order:
  199. \code
  200. SparseMatrix<double> A, B;
  201. B = SparseMatrix<double>(A.transpose()) + A;
  202. \endcode
  203. Binary coefficient wise operators can also mix sparse and dense expressions:
  204. \code
  205. sm2 = sm1.cwiseProduct(dm1);
  206. dm2 = sm1 + dm1;
  207. \endcode
  208. %Sparse expressions also support transposition:
  209. \code
  210. sm1 = sm2.transpose();
  211. sm1 = sm2.adjoint();
  212. \endcode
  213. However, there is no transposeInPlace() method.
  214. \subsection TutorialSparse_Products Matrix products
  215. %Eigen supports various kind of sparse matrix products which are summarize below:
  216. - \b sparse-dense:
  217. \code
  218. dv2 = sm1 * dv1;
  219. dm2 = dm1 * sm1.adjoint();
  220. dm2 = 2. * sm1 * dm1;
  221. \endcode
  222. - \b symmetric \b sparse-dense. The product of a sparse symmetric matrix with a dense matrix (or vector) can also be optimized by specifying the symmetry with selfadjointView():
  223. \code
  224. dm2 = sm1.selfadjointView<>() * dm1; // if all coefficients of A are stored
  225. dm2 = A.selfadjointView<Upper>() * dm1; // if only the upper part of A is stored
  226. dm2 = A.selfadjointView<Lower>() * dm1; // if only the lower part of A is stored
  227. \endcode
  228. - \b sparse-sparse. For sparse-sparse products, two different algorithms are available. The default one is conservative and preserve the explicit zeros that might appear:
  229. \code
  230. sm3 = sm1 * sm2;
  231. sm3 = 4 * sm1.adjoint() * sm2;
  232. \endcode
  233. The second algorithm prunes on the fly the explicit zeros, or the values smaller than a given threshold. It is enabled and controlled through the prune() functions:
  234. \code
  235. sm3 = (sm1 * sm2).pruned(); // removes numerical zeros
  236. sm3 = (sm1 * sm2).pruned(ref); // removes elements much smaller than ref
  237. sm3 = (sm1 * sm2).pruned(ref,epsilon); // removes elements smaller than ref*epsilon
  238. \endcode
  239. - \b permutations. Finally, permutations can be applied to sparse matrices too:
  240. \code
  241. PermutationMatrix<Dynamic,Dynamic> P = ...;
  242. sm2 = P * sm1;
  243. sm2 = sm1 * P.inverse();
  244. sm2 = sm1.transpose() * P;
  245. \endcode
  246. \subsection TutorialSparse_TriangularSelfadjoint Triangular and selfadjoint views
  247. Just as with dense matrices, the triangularView() function can be used to address a triangular part of the matrix, and perform triangular solves with a dense right hand side:
  248. \code
  249. dm2 = sm1.triangularView<Lower>(dm1);
  250. dv2 = sm1.transpose().triangularView<Upper>(dv1);
  251. \endcode
  252. The selfadjointView() function permits various operations:
  253. - optimized sparse-dense matrix products:
  254. \code
  255. dm2 = sm1.selfadjointView<>() * dm1; // if all coefficients of A are stored
  256. dm2 = A.selfadjointView<Upper>() * dm1; // if only the upper part of A is stored
  257. dm2 = A.selfadjointView<Lower>() * dm1; // if only the lower part of A is stored
  258. \endcode
  259. - copy of triangular parts:
  260. \code
  261. sm2 = sm1.selfadjointView<Upper>(); // makes a full selfadjoint matrix from the upper triangular part
  262. sm2.selfadjointView<Lower>() = sm1.selfadjointView<Upper>(); // copies the upper triangular part to the lower triangular part
  263. \endcode
  264. - application of symmetric permutations:
  265. \code
  266. PermutationMatrix<Dynamic,Dynamic> P = ...;
  267. sm2 = A.selfadjointView<Upper>().twistedBy(P); // compute P S P' from the upper triangular part of A, and make it a full matrix
  268. sm2.selfadjointView<Lower>() = A.selfadjointView<Lower>().twistedBy(P); // compute P S P' from the lower triangular part of A, and then only compute the lower part
  269. \endcode
  270. Please, refer to the \link SparseQuickRefPage Quick Reference \endlink guide for the list of supported operations. The list of linear solvers available is \link TopicSparseSystems here. \endlink
  271. */
  272. }