suitesparse.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. // Ceres Solver - A fast non-linear least squares minimizer
  2. // Copyright 2023 Google Inc. All rights reserved.
  3. // http://ceres-solver.org/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are met:
  7. //
  8. // * Redistributions of source code must retain the above copyright notice,
  9. // this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above copyright notice,
  11. // this list of conditions and the following disclaimer in the documentation
  12. // and/or other materials provided with the distribution.
  13. // * Neither the name of Google Inc. nor the names of its contributors may be
  14. // used to endorse or promote products derived from this software without
  15. // specific prior written permission.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  21. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  24. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  25. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  27. // POSSIBILITY OF SUCH DAMAGE.
  28. //
  29. // Author: sameeragarwal@google.com (Sameer Agarwal)
  30. //
  31. // A simple C++ interface to the SuiteSparse and CHOLMOD libraries.
  32. #ifndef CERES_INTERNAL_SUITESPARSE_H_
  33. #define CERES_INTERNAL_SUITESPARSE_H_
  34. // This include must come before any #ifndef check on Ceres compile options.
  35. #include "ceres/internal/config.h"
  36. #ifndef CERES_NO_SUITESPARSE
  37. #include <cstring>
  38. #include <memory>
  39. #include <string>
  40. #include <vector>
  41. #include "SuiteSparseQR.hpp"
  42. #include "ceres/block_structure.h"
  43. #include "ceres/internal/disable_warnings.h"
  44. #include "ceres/linear_solver.h"
  45. #include "ceres/sparse_cholesky.h"
  46. #include "cholmod.h"
  47. #include "glog/logging.h"
  48. namespace ceres::internal {
  49. class CompressedRowSparseMatrix;
  50. class TripletSparseMatrix;
  51. // The raw CHOLMOD and SuiteSparseQR libraries have a slightly
  52. // cumbersome c like calling format. This object abstracts it away and
  53. // provides the user with a simpler interface. The methods here cannot
  54. // be static as a cholmod_common object serves as a global variable
  55. // for all cholmod function calls.
  56. class CERES_NO_EXPORT SuiteSparse {
  57. public:
  58. SuiteSparse();
  59. ~SuiteSparse();
  60. // Functions for building cholmod_sparse objects from sparse
  61. // matrices stored in triplet form. The matrix A is not
  62. // modified. Called owns the result.
  63. cholmod_sparse* CreateSparseMatrix(TripletSparseMatrix* A);
  64. // This function works like CreateSparseMatrix, except that the
  65. // return value corresponds to A' rather than A.
  66. cholmod_sparse* CreateSparseMatrixTranspose(TripletSparseMatrix* A);
  67. // Create a cholmod_sparse wrapper around the contents of A. This is
  68. // a shallow object, which refers to the contents of A and does not
  69. // use the SuiteSparse machinery to allocate memory.
  70. cholmod_sparse CreateSparseMatrixTransposeView(CompressedRowSparseMatrix* A);
  71. // Create a cholmod_dense vector around the contents of the array x.
  72. // This is a shallow object, which refers to the contents of x and
  73. // does not use the SuiteSparse machinery to allocate memory.
  74. cholmod_dense CreateDenseVectorView(const double* x, int size);
  75. // Given a vector x, build a cholmod_dense vector of size out_size
  76. // with the first in_size entries copied from x. If x is nullptr, then
  77. // an all zeros vector is returned. Caller owns the result.
  78. cholmod_dense* CreateDenseVector(const double* x, int in_size, int out_size);
  79. // The matrix A is scaled using the matrix whose diagonal is the
  80. // vector scale. mode describes how scaling is applied. Possible
  81. // values are CHOLMOD_ROW for row scaling - diag(scale) * A,
  82. // CHOLMOD_COL for column scaling - A * diag(scale) and CHOLMOD_SYM
  83. // for symmetric scaling which scales both the rows and the columns
  84. // - diag(scale) * A * diag(scale).
  85. void Scale(cholmod_dense* scale, int mode, cholmod_sparse* A) {
  86. cholmod_scale(scale, mode, A, &cc_);
  87. }
  88. // Create and return a matrix m = A * A'. Caller owns the
  89. // result. The matrix A is not modified.
  90. cholmod_sparse* AATranspose(cholmod_sparse* A) {
  91. cholmod_sparse* m = cholmod_aat(A, nullptr, A->nrow, 1, &cc_);
  92. m->stype = 1; // Pay attention to the upper triangular part.
  93. return m;
  94. }
  95. // y = alpha * A * x + beta * y. Only y is modified.
  96. void SparseDenseMultiply(cholmod_sparse* A,
  97. double alpha,
  98. double beta,
  99. cholmod_dense* x,
  100. cholmod_dense* y) {
  101. double alpha_[2] = {alpha, 0};
  102. double beta_[2] = {beta, 0};
  103. cholmod_sdmult(A, 0, alpha_, beta_, x, y, &cc_);
  104. }
  105. // Compute a symbolic factorization for A or AA' (if A is
  106. // unsymmetric). If ordering_type is NATURAL, then no fill reducing
  107. // ordering is computed, otherwise depending on the value of
  108. // ordering_type AMD or Nested Dissection is used to compute a fill
  109. // reducing ordering before the symbolic factorization is computed.
  110. //
  111. // A is not modified, only the pattern of non-zeros of A is used,
  112. // the actual numerical values in A are of no consequence.
  113. //
  114. // message contains an explanation of the failures if any.
  115. //
  116. // Caller owns the result.
  117. cholmod_factor* AnalyzeCholesky(cholmod_sparse* A,
  118. OrderingType ordering_type,
  119. std::string* message);
  120. // Block oriented version of AnalyzeCholesky.
  121. cholmod_factor* BlockAnalyzeCholesky(cholmod_sparse* A,
  122. OrderingType ordering_type,
  123. const std::vector<Block>& row_blocks,
  124. const std::vector<Block>& col_blocks,
  125. std::string* message);
  126. // If A is symmetric, then compute the symbolic Cholesky
  127. // factorization of A(ordering, ordering). If A is unsymmetric, then
  128. // compute the symbolic factorization of
  129. // A(ordering,:) A(ordering,:)'.
  130. //
  131. // A is not modified, only the pattern of non-zeros of A is used,
  132. // the actual numerical values in A are of no consequence.
  133. //
  134. // message contains an explanation of the failures if any.
  135. //
  136. // Caller owns the result.
  137. cholmod_factor* AnalyzeCholeskyWithGivenOrdering(
  138. cholmod_sparse* A,
  139. const std::vector<int>& ordering,
  140. std::string* message);
  141. // Use the symbolic factorization in L, to find the numerical
  142. // factorization for the matrix A or AA^T. Return true if
  143. // successful, false otherwise. L contains the numeric factorization
  144. // on return.
  145. //
  146. // message contains an explanation of the failures if any.
  147. LinearSolverTerminationType Cholesky(cholmod_sparse* A,
  148. cholmod_factor* L,
  149. std::string* message);
  150. // Given a Cholesky factorization of a matrix A = LL^T, solve the
  151. // linear system Ax = b, and return the result. If the Solve fails
  152. // nullptr is returned. Caller owns the result.
  153. //
  154. // message contains an explanation of the failures if any.
  155. cholmod_dense* Solve(cholmod_factor* L,
  156. cholmod_dense* b,
  157. std::string* message);
  158. // Find a fill reducing ordering. ordering is expected to be large
  159. // enough to hold the ordering. ordering_type must be AMD or NESDIS.
  160. bool Ordering(cholmod_sparse* matrix,
  161. OrderingType ordering_type,
  162. int* ordering);
  163. // Find the block oriented fill reducing ordering of a matrix A,
  164. // whose row and column blocks are given by row_blocks, and
  165. // col_blocks respectively. The matrix may or may not be
  166. // symmetric. The entries of col_blocks do not need to sum to the
  167. // number of columns in A. If this is the case, only the first
  168. // sum(col_blocks) are used to compute the ordering.
  169. //
  170. // By virtue of the modeling layer in Ceres being block oriented,
  171. // all the matrices used by Ceres are also block oriented. When
  172. // doing sparse direct factorization of these matrices the
  173. // fill-reducing ordering algorithms can either be run on the block
  174. // or the scalar form of these matrices. But since the underlying
  175. // matrices are block oriented, it is worth running the fill
  176. // reducing ordering on just the block structure of these matrices
  177. // and then lifting these block orderings to a full scalar
  178. // ordering. This preserves the block structure of the permuted
  179. // matrix, and exposes more of the super-nodal structure of the
  180. // matrix to the numerical factorization routines.
  181. bool BlockOrdering(const cholmod_sparse* A,
  182. OrderingType ordering_type,
  183. const std::vector<Block>& row_blocks,
  184. const std::vector<Block>& col_blocks,
  185. std::vector<int>* ordering);
  186. // Nested dissection is only available if SuiteSparse is compiled
  187. // with Metis support.
  188. static bool IsNestedDissectionAvailable();
  189. // Find a fill reducing approximate minimum degree
  190. // ordering. constraints is an array which associates with each
  191. // column of the matrix an elimination group. i.e., all columns in
  192. // group 0 are eliminated first, all columns in group 1 are
  193. // eliminated next etc. This function finds a fill reducing ordering
  194. // that obeys these constraints.
  195. //
  196. // Calling ApproximateMinimumDegreeOrdering is equivalent to calling
  197. // ConstrainedApproximateMinimumDegreeOrdering with a constraint
  198. // array that puts all columns in the same elimination group.
  199. bool ConstrainedApproximateMinimumDegreeOrdering(cholmod_sparse* matrix,
  200. int* constraints,
  201. int* ordering);
  202. void Free(cholmod_sparse* m) { cholmod_free_sparse(&m, &cc_); }
  203. void Free(cholmod_dense* m) { cholmod_free_dense(&m, &cc_); }
  204. void Free(cholmod_factor* m) { cholmod_free_factor(&m, &cc_); }
  205. void Print(cholmod_sparse* m, const std::string& name) {
  206. cholmod_print_sparse(m, const_cast<char*>(name.c_str()), &cc_);
  207. }
  208. void Print(cholmod_dense* m, const std::string& name) {
  209. cholmod_print_dense(m, const_cast<char*>(name.c_str()), &cc_);
  210. }
  211. void Print(cholmod_triplet* m, const std::string& name) {
  212. cholmod_print_triplet(m, const_cast<char*>(name.c_str()), &cc_);
  213. }
  214. cholmod_common* mutable_cc() { return &cc_; }
  215. private:
  216. cholmod_common cc_;
  217. };
  218. class CERES_NO_EXPORT SuiteSparseCholesky final : public SparseCholesky {
  219. public:
  220. static std::unique_ptr<SparseCholesky> Create(OrderingType ordering_type);
  221. // SparseCholesky interface.
  222. ~SuiteSparseCholesky() override;
  223. CompressedRowSparseMatrix::StorageType StorageType() const final;
  224. LinearSolverTerminationType Factorize(CompressedRowSparseMatrix* lhs,
  225. std::string* message) final;
  226. LinearSolverTerminationType Solve(const double* rhs,
  227. double* solution,
  228. std::string* message) final;
  229. private:
  230. explicit SuiteSparseCholesky(const OrderingType ordering_type);
  231. const OrderingType ordering_type_;
  232. SuiteSparse ss_;
  233. cholmod_factor* factor_;
  234. };
  235. } // namespace ceres::internal
  236. #include "ceres/internal/reenable_warnings.h"
  237. #else // CERES_NO_SUITESPARSE
  238. using cholmod_factor = void;
  239. #include "ceres/internal/disable_warnings.h"
  240. namespace ceres {
  241. namespace internal {
  242. class CERES_NO_EXPORT SuiteSparse {
  243. public:
  244. // Nested dissection is only available if SuiteSparse is compiled
  245. // with Metis support.
  246. static bool IsNestedDissectionAvailable() { return false; }
  247. void Free(void* /*arg*/) {}
  248. };
  249. } // namespace internal
  250. } // namespace ceres
  251. #include "ceres/internal/reenable_warnings.h"
  252. #endif // CERES_NO_SUITESPARSE
  253. #endif // CERES_INTERNAL_SUITESPARSE_H_