Austin Schuh | 70cc955 | 2019-01-21 19:46:48 -0800 | [diff] [blame^] | 1 | // Ceres Solver - A fast non-linear least squares minimizer |
| 2 | // Copyright 2015 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 | // This include must come before any #ifndef check on Ceres compile options. |
| 32 | #include "ceres/internal/port.h" |
| 33 | |
| 34 | #ifndef CERES_NO_SUITESPARSE |
| 35 | #include "ceres/suitesparse.h" |
| 36 | |
| 37 | #include <vector> |
| 38 | |
| 39 | #include "ceres/compressed_col_sparse_matrix_utils.h" |
| 40 | #include "ceres/compressed_row_sparse_matrix.h" |
| 41 | #include "ceres/linear_solver.h" |
| 42 | #include "ceres/triplet_sparse_matrix.h" |
| 43 | #include "cholmod.h" |
| 44 | |
| 45 | namespace ceres { |
| 46 | namespace internal { |
| 47 | |
| 48 | using std::string; |
| 49 | using std::vector; |
| 50 | |
| 51 | SuiteSparse::SuiteSparse() { cholmod_start(&cc_); } |
| 52 | |
| 53 | SuiteSparse::~SuiteSparse() { cholmod_finish(&cc_); } |
| 54 | |
| 55 | cholmod_sparse* SuiteSparse::CreateSparseMatrix(TripletSparseMatrix* A) { |
| 56 | cholmod_triplet triplet; |
| 57 | |
| 58 | triplet.nrow = A->num_rows(); |
| 59 | triplet.ncol = A->num_cols(); |
| 60 | triplet.nzmax = A->max_num_nonzeros(); |
| 61 | triplet.nnz = A->num_nonzeros(); |
| 62 | triplet.i = reinterpret_cast<void*>(A->mutable_rows()); |
| 63 | triplet.j = reinterpret_cast<void*>(A->mutable_cols()); |
| 64 | triplet.x = reinterpret_cast<void*>(A->mutable_values()); |
| 65 | triplet.stype = 0; // Matrix is not symmetric. |
| 66 | triplet.itype = CHOLMOD_INT; |
| 67 | triplet.xtype = CHOLMOD_REAL; |
| 68 | triplet.dtype = CHOLMOD_DOUBLE; |
| 69 | |
| 70 | return cholmod_triplet_to_sparse(&triplet, triplet.nnz, &cc_); |
| 71 | } |
| 72 | |
| 73 | cholmod_sparse* SuiteSparse::CreateSparseMatrixTranspose( |
| 74 | TripletSparseMatrix* A) { |
| 75 | cholmod_triplet triplet; |
| 76 | |
| 77 | triplet.ncol = A->num_rows(); // swap row and columns |
| 78 | triplet.nrow = A->num_cols(); |
| 79 | triplet.nzmax = A->max_num_nonzeros(); |
| 80 | triplet.nnz = A->num_nonzeros(); |
| 81 | |
| 82 | // swap rows and columns |
| 83 | triplet.j = reinterpret_cast<void*>(A->mutable_rows()); |
| 84 | triplet.i = reinterpret_cast<void*>(A->mutable_cols()); |
| 85 | triplet.x = reinterpret_cast<void*>(A->mutable_values()); |
| 86 | triplet.stype = 0; // Matrix is not symmetric. |
| 87 | triplet.itype = CHOLMOD_INT; |
| 88 | triplet.xtype = CHOLMOD_REAL; |
| 89 | triplet.dtype = CHOLMOD_DOUBLE; |
| 90 | |
| 91 | return cholmod_triplet_to_sparse(&triplet, triplet.nnz, &cc_); |
| 92 | } |
| 93 | |
| 94 | cholmod_sparse SuiteSparse::CreateSparseMatrixTransposeView( |
| 95 | CompressedRowSparseMatrix* A) { |
| 96 | cholmod_sparse m; |
| 97 | m.nrow = A->num_cols(); |
| 98 | m.ncol = A->num_rows(); |
| 99 | m.nzmax = A->num_nonzeros(); |
| 100 | m.nz = nullptr; |
| 101 | m.p = reinterpret_cast<void*>(A->mutable_rows()); |
| 102 | m.i = reinterpret_cast<void*>(A->mutable_cols()); |
| 103 | m.x = reinterpret_cast<void*>(A->mutable_values()); |
| 104 | m.z = nullptr; |
| 105 | |
| 106 | if (A->storage_type() == CompressedRowSparseMatrix::LOWER_TRIANGULAR) { |
| 107 | m.stype = 1; |
| 108 | } else if (A->storage_type() == CompressedRowSparseMatrix::UPPER_TRIANGULAR) { |
| 109 | m.stype = -1; |
| 110 | } else { |
| 111 | m.stype = 0; |
| 112 | } |
| 113 | |
| 114 | m.itype = CHOLMOD_INT; |
| 115 | m.xtype = CHOLMOD_REAL; |
| 116 | m.dtype = CHOLMOD_DOUBLE; |
| 117 | m.sorted = 1; |
| 118 | m.packed = 1; |
| 119 | |
| 120 | return m; |
| 121 | } |
| 122 | |
| 123 | cholmod_dense SuiteSparse::CreateDenseVectorView(const double* x, int size) { |
| 124 | cholmod_dense v; |
| 125 | v.nrow = size; |
| 126 | v.ncol = 1; |
| 127 | v.nzmax = size; |
| 128 | v.d = size; |
| 129 | v.x = const_cast<void*>(reinterpret_cast<const void*>(x)); |
| 130 | v.xtype = CHOLMOD_REAL; |
| 131 | v.dtype = CHOLMOD_DOUBLE; |
| 132 | return v; |
| 133 | } |
| 134 | |
| 135 | cholmod_dense* SuiteSparse::CreateDenseVector(const double* x, |
| 136 | int in_size, |
| 137 | int out_size) { |
| 138 | CHECK_LE(in_size, out_size); |
| 139 | cholmod_dense* v = cholmod_zeros(out_size, 1, CHOLMOD_REAL, &cc_); |
| 140 | if (x != nullptr) { |
| 141 | memcpy(v->x, x, in_size * sizeof(*x)); |
| 142 | } |
| 143 | return v; |
| 144 | } |
| 145 | |
| 146 | cholmod_factor* SuiteSparse::AnalyzeCholesky(cholmod_sparse* A, |
| 147 | string* message) { |
| 148 | // Cholmod can try multiple re-ordering strategies to find a fill |
| 149 | // reducing ordering. Here we just tell it use AMD with automatic |
| 150 | // matrix dependence choice of supernodal versus simplicial |
| 151 | // factorization. |
| 152 | cc_.nmethods = 1; |
| 153 | cc_.method[0].ordering = CHOLMOD_AMD; |
| 154 | cc_.supernodal = CHOLMOD_AUTO; |
| 155 | |
| 156 | cholmod_factor* factor = cholmod_analyze(A, &cc_); |
| 157 | if (VLOG_IS_ON(2)) { |
| 158 | cholmod_print_common(const_cast<char*>("Symbolic Analysis"), &cc_); |
| 159 | } |
| 160 | |
| 161 | if (cc_.status != CHOLMOD_OK) { |
| 162 | *message = |
| 163 | StringPrintf("cholmod_analyze failed. error code: %d", cc_.status); |
| 164 | return nullptr; |
| 165 | } |
| 166 | |
| 167 | CHECK(factor != nullptr); |
| 168 | return factor; |
| 169 | } |
| 170 | |
| 171 | cholmod_factor* SuiteSparse::BlockAnalyzeCholesky(cholmod_sparse* A, |
| 172 | const vector<int>& row_blocks, |
| 173 | const vector<int>& col_blocks, |
| 174 | string* message) { |
| 175 | vector<int> ordering; |
| 176 | if (!BlockAMDOrdering(A, row_blocks, col_blocks, &ordering)) { |
| 177 | return nullptr; |
| 178 | } |
| 179 | return AnalyzeCholeskyWithUserOrdering(A, ordering, message); |
| 180 | } |
| 181 | |
| 182 | cholmod_factor* SuiteSparse::AnalyzeCholeskyWithUserOrdering( |
| 183 | cholmod_sparse* A, const vector<int>& ordering, string* message) { |
| 184 | CHECK_EQ(ordering.size(), A->nrow); |
| 185 | |
| 186 | cc_.nmethods = 1; |
| 187 | cc_.method[0].ordering = CHOLMOD_GIVEN; |
| 188 | |
| 189 | cholmod_factor* factor = |
| 190 | cholmod_analyze_p(A, const_cast<int*>(&ordering[0]), nullptr, 0, &cc_); |
| 191 | if (VLOG_IS_ON(2)) { |
| 192 | cholmod_print_common(const_cast<char*>("Symbolic Analysis"), &cc_); |
| 193 | } |
| 194 | if (cc_.status != CHOLMOD_OK) { |
| 195 | *message = |
| 196 | StringPrintf("cholmod_analyze failed. error code: %d", cc_.status); |
| 197 | return nullptr; |
| 198 | } |
| 199 | |
| 200 | CHECK(factor != nullptr); |
| 201 | return factor; |
| 202 | } |
| 203 | |
| 204 | cholmod_factor* SuiteSparse::AnalyzeCholeskyWithNaturalOrdering( |
| 205 | cholmod_sparse* A, string* message) { |
| 206 | cc_.nmethods = 1; |
| 207 | cc_.method[0].ordering = CHOLMOD_NATURAL; |
| 208 | cc_.postorder = 0; |
| 209 | |
| 210 | cholmod_factor* factor = cholmod_analyze(A, &cc_); |
| 211 | if (VLOG_IS_ON(2)) { |
| 212 | cholmod_print_common(const_cast<char*>("Symbolic Analysis"), &cc_); |
| 213 | } |
| 214 | if (cc_.status != CHOLMOD_OK) { |
| 215 | *message = |
| 216 | StringPrintf("cholmod_analyze failed. error code: %d", cc_.status); |
| 217 | return nullptr; |
| 218 | } |
| 219 | |
| 220 | CHECK(factor != nullptr); |
| 221 | return factor; |
| 222 | } |
| 223 | |
| 224 | bool SuiteSparse::BlockAMDOrdering(const cholmod_sparse* A, |
| 225 | const vector<int>& row_blocks, |
| 226 | const vector<int>& col_blocks, |
| 227 | vector<int>* ordering) { |
| 228 | const int num_row_blocks = row_blocks.size(); |
| 229 | const int num_col_blocks = col_blocks.size(); |
| 230 | |
| 231 | // Arrays storing the compressed column structure of the matrix |
| 232 | // incoding the block sparsity of A. |
| 233 | vector<int> block_cols; |
| 234 | vector<int> block_rows; |
| 235 | |
| 236 | CompressedColumnScalarMatrixToBlockMatrix(reinterpret_cast<const int*>(A->i), |
| 237 | reinterpret_cast<const int*>(A->p), |
| 238 | row_blocks, |
| 239 | col_blocks, |
| 240 | &block_rows, |
| 241 | &block_cols); |
| 242 | cholmod_sparse_struct block_matrix; |
| 243 | block_matrix.nrow = num_row_blocks; |
| 244 | block_matrix.ncol = num_col_blocks; |
| 245 | block_matrix.nzmax = block_rows.size(); |
| 246 | block_matrix.p = reinterpret_cast<void*>(&block_cols[0]); |
| 247 | block_matrix.i = reinterpret_cast<void*>(&block_rows[0]); |
| 248 | block_matrix.x = nullptr; |
| 249 | block_matrix.stype = A->stype; |
| 250 | block_matrix.itype = CHOLMOD_INT; |
| 251 | block_matrix.xtype = CHOLMOD_PATTERN; |
| 252 | block_matrix.dtype = CHOLMOD_DOUBLE; |
| 253 | block_matrix.sorted = 1; |
| 254 | block_matrix.packed = 1; |
| 255 | |
| 256 | vector<int> block_ordering(num_row_blocks); |
| 257 | if (!cholmod_amd(&block_matrix, nullptr, 0, &block_ordering[0], &cc_)) { |
| 258 | return false; |
| 259 | } |
| 260 | |
| 261 | BlockOrderingToScalarOrdering(row_blocks, block_ordering, ordering); |
| 262 | return true; |
| 263 | } |
| 264 | |
| 265 | LinearSolverTerminationType SuiteSparse::Cholesky(cholmod_sparse* A, |
| 266 | cholmod_factor* L, |
| 267 | string* message) { |
| 268 | CHECK(A != nullptr); |
| 269 | CHECK(L != nullptr); |
| 270 | |
| 271 | // Save the current print level and silence CHOLMOD, otherwise |
| 272 | // CHOLMOD is prone to dumping stuff to stderr, which can be |
| 273 | // distracting when the error (matrix is indefinite) is not a fatal |
| 274 | // failure. |
| 275 | const int old_print_level = cc_.print; |
| 276 | cc_.print = 0; |
| 277 | |
| 278 | cc_.quick_return_if_not_posdef = 1; |
| 279 | int cholmod_status = cholmod_factorize(A, L, &cc_); |
| 280 | cc_.print = old_print_level; |
| 281 | |
| 282 | switch (cc_.status) { |
| 283 | case CHOLMOD_NOT_INSTALLED: |
| 284 | *message = "CHOLMOD failure: Method not installed."; |
| 285 | return LINEAR_SOLVER_FATAL_ERROR; |
| 286 | case CHOLMOD_OUT_OF_MEMORY: |
| 287 | *message = "CHOLMOD failure: Out of memory."; |
| 288 | return LINEAR_SOLVER_FATAL_ERROR; |
| 289 | case CHOLMOD_TOO_LARGE: |
| 290 | *message = "CHOLMOD failure: Integer overflow occurred."; |
| 291 | return LINEAR_SOLVER_FATAL_ERROR; |
| 292 | case CHOLMOD_INVALID: |
| 293 | *message = "CHOLMOD failure: Invalid input."; |
| 294 | return LINEAR_SOLVER_FATAL_ERROR; |
| 295 | case CHOLMOD_NOT_POSDEF: |
| 296 | *message = "CHOLMOD warning: Matrix not positive definite."; |
| 297 | return LINEAR_SOLVER_FAILURE; |
| 298 | case CHOLMOD_DSMALL: |
| 299 | *message = |
| 300 | "CHOLMOD warning: D for LDL' or diag(L) or " |
| 301 | "LL' has tiny absolute value."; |
| 302 | return LINEAR_SOLVER_FAILURE; |
| 303 | case CHOLMOD_OK: |
| 304 | if (cholmod_status != 0) { |
| 305 | return LINEAR_SOLVER_SUCCESS; |
| 306 | } |
| 307 | |
| 308 | *message = |
| 309 | "CHOLMOD failure: cholmod_factorize returned false " |
| 310 | "but cholmod_common::status is CHOLMOD_OK." |
| 311 | "Please report this to ceres-solver@googlegroups.com."; |
| 312 | return LINEAR_SOLVER_FATAL_ERROR; |
| 313 | default: |
| 314 | *message = StringPrintf( |
| 315 | "Unknown cholmod return code: %d. " |
| 316 | "Please report this to ceres-solver@googlegroups.com.", |
| 317 | cc_.status); |
| 318 | return LINEAR_SOLVER_FATAL_ERROR; |
| 319 | } |
| 320 | |
| 321 | return LINEAR_SOLVER_FATAL_ERROR; |
| 322 | } |
| 323 | |
| 324 | cholmod_dense* SuiteSparse::Solve(cholmod_factor* L, |
| 325 | cholmod_dense* b, |
| 326 | string* message) { |
| 327 | if (cc_.status != CHOLMOD_OK) { |
| 328 | *message = "cholmod_solve failed. CHOLMOD status is not CHOLMOD_OK"; |
| 329 | return nullptr; |
| 330 | } |
| 331 | |
| 332 | return cholmod_solve(CHOLMOD_A, L, b, &cc_); |
| 333 | } |
| 334 | |
| 335 | bool SuiteSparse::ApproximateMinimumDegreeOrdering(cholmod_sparse* matrix, |
| 336 | int* ordering) { |
| 337 | return cholmod_amd(matrix, nullptr, 0, ordering, &cc_); |
| 338 | } |
| 339 | |
| 340 | bool SuiteSparse::ConstrainedApproximateMinimumDegreeOrdering( |
| 341 | cholmod_sparse* matrix, int* constraints, int* ordering) { |
| 342 | #ifndef CERES_NO_CAMD |
| 343 | return cholmod_camd(matrix, nullptr, 0, constraints, ordering, &cc_); |
| 344 | #else |
| 345 | LOG(FATAL) << "Congratulations you have found a bug in Ceres." |
| 346 | << "Ceres Solver was compiled with SuiteSparse " |
| 347 | << "version 4.1.0 or less. Calling this function " |
| 348 | << "in that case is a bug. Please contact the" |
| 349 | << "the Ceres Solver developers."; |
| 350 | return false; |
| 351 | #endif |
| 352 | } |
| 353 | |
| 354 | std::unique_ptr<SparseCholesky> SuiteSparseCholesky::Create( |
| 355 | const OrderingType ordering_type) { |
| 356 | return std::unique_ptr<SparseCholesky>(new SuiteSparseCholesky(ordering_type)); |
| 357 | } |
| 358 | |
| 359 | SuiteSparseCholesky::SuiteSparseCholesky(const OrderingType ordering_type) |
| 360 | : ordering_type_(ordering_type), factor_(nullptr) {} |
| 361 | |
| 362 | SuiteSparseCholesky::~SuiteSparseCholesky() { |
| 363 | if (factor_ != nullptr) { |
| 364 | ss_.Free(factor_); |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | LinearSolverTerminationType SuiteSparseCholesky::Factorize( |
| 369 | CompressedRowSparseMatrix* lhs, string* message) { |
| 370 | if (lhs == nullptr) { |
| 371 | *message = "Failure: Input lhs is NULL."; |
| 372 | return LINEAR_SOLVER_FATAL_ERROR; |
| 373 | } |
| 374 | |
| 375 | cholmod_sparse cholmod_lhs = ss_.CreateSparseMatrixTransposeView(lhs); |
| 376 | |
| 377 | if (factor_ == nullptr) { |
| 378 | if (ordering_type_ == NATURAL) { |
| 379 | factor_ = ss_.AnalyzeCholeskyWithNaturalOrdering(&cholmod_lhs, message); |
| 380 | } else { |
| 381 | if (!lhs->col_blocks().empty() && !(lhs->row_blocks().empty())) { |
| 382 | factor_ = ss_.BlockAnalyzeCholesky( |
| 383 | &cholmod_lhs, lhs->col_blocks(), lhs->row_blocks(), message); |
| 384 | } else { |
| 385 | factor_ = ss_.AnalyzeCholesky(&cholmod_lhs, message); |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | if (factor_ == nullptr) { |
| 390 | return LINEAR_SOLVER_FATAL_ERROR; |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | return ss_.Cholesky(&cholmod_lhs, factor_, message); |
| 395 | } |
| 396 | |
| 397 | CompressedRowSparseMatrix::StorageType SuiteSparseCholesky::StorageType() |
| 398 | const { |
| 399 | return ((ordering_type_ == NATURAL) |
| 400 | ? CompressedRowSparseMatrix::UPPER_TRIANGULAR |
| 401 | : CompressedRowSparseMatrix::LOWER_TRIANGULAR); |
| 402 | } |
| 403 | |
| 404 | LinearSolverTerminationType SuiteSparseCholesky::Solve(const double* rhs, |
| 405 | double* solution, |
| 406 | string* message) { |
| 407 | // Error checking |
| 408 | if (factor_ == nullptr) { |
| 409 | *message = "Solve called without a call to Factorize first."; |
| 410 | return LINEAR_SOLVER_FATAL_ERROR; |
| 411 | } |
| 412 | |
| 413 | const int num_cols = factor_->n; |
| 414 | cholmod_dense cholmod_rhs = ss_.CreateDenseVectorView(rhs, num_cols); |
| 415 | cholmod_dense* cholmod_dense_solution = |
| 416 | ss_.Solve(factor_, &cholmod_rhs, message); |
| 417 | |
| 418 | if (cholmod_dense_solution == nullptr) { |
| 419 | return LINEAR_SOLVER_FAILURE; |
| 420 | } |
| 421 | |
| 422 | memcpy(solution, cholmod_dense_solution->x, num_cols * sizeof(*solution)); |
| 423 | ss_.Free(cholmod_dense_solution); |
| 424 | return LINEAR_SOLVER_SUCCESS; |
| 425 | } |
| 426 | |
| 427 | } // namespace internal |
| 428 | } // namespace ceres |
| 429 | |
| 430 | #endif // CERES_NO_SUITESPARSE |