Files
ceres-solver/internal/ceres/suitesparse.cc
T

417 lines
14 KiB
C++
Raw Normal View History

2012-04-30 23:09:08 -07:00
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2015 Google Inc. All rights reserved.
// http://ceres-solver.org/
2012-04-30 23:09:08 -07:00
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: sameeragarwal@google.com (Sameer Agarwal)
// This include must come before any #ifndef check on Ceres compile options.
#include "ceres/internal/port.h"
2012-04-30 23:09:08 -07:00
#ifndef CERES_NO_SUITESPARSE
#include "ceres/suitesparse.h"
2012-06-05 23:10:59 -07:00
#include <vector>
2017-04-12 12:48:44 -07:00
#include "ceres/compressed_col_sparse_matrix_utils.h"
2012-04-30 23:09:08 -07:00
#include "ceres/compressed_row_sparse_matrix.h"
#include "ceres/linear_solver.h"
2012-04-30 23:09:08 -07:00
#include "ceres/triplet_sparse_matrix.h"
2017-04-12 12:48:44 -07:00
#include "cholmod.h"
2013-04-01 09:11:07 -07:00
2012-04-30 23:09:08 -07:00
namespace ceres {
namespace internal {
2013-04-01 09:11:07 -07:00
2015-01-07 15:10:46 -08:00
using std::string;
2014-12-17 07:35:09 -08:00
using std::vector;
2017-04-12 12:48:44 -07:00
SuiteSparse::SuiteSparse() { cholmod_start(&cc_); }
2013-04-01 09:11:07 -07:00
2017-04-12 12:48:44 -07:00
SuiteSparse::~SuiteSparse() { cholmod_finish(&cc_); }
2013-04-01 09:11:07 -07:00
2012-04-30 23:09:08 -07:00
cholmod_sparse* SuiteSparse::CreateSparseMatrix(TripletSparseMatrix* A) {
cholmod_triplet triplet;
triplet.nrow = A->num_rows();
triplet.ncol = A->num_cols();
triplet.nzmax = A->max_num_nonzeros();
triplet.nnz = A->num_nonzeros();
triplet.i = reinterpret_cast<void*>(A->mutable_rows());
triplet.j = reinterpret_cast<void*>(A->mutable_cols());
triplet.x = reinterpret_cast<void*>(A->mutable_values());
triplet.stype = 0; // Matrix is not symmetric.
triplet.itype = CHOLMOD_INT;
triplet.xtype = CHOLMOD_REAL;
triplet.dtype = CHOLMOD_DOUBLE;
return cholmod_triplet_to_sparse(&triplet, triplet.nnz, &cc_);
}
cholmod_sparse* SuiteSparse::CreateSparseMatrixTranspose(
TripletSparseMatrix* A) {
cholmod_triplet triplet;
triplet.ncol = A->num_rows(); // swap row and columns
triplet.nrow = A->num_cols();
triplet.nzmax = A->max_num_nonzeros();
triplet.nnz = A->num_nonzeros();
// swap rows and columns
triplet.j = reinterpret_cast<void*>(A->mutable_rows());
triplet.i = reinterpret_cast<void*>(A->mutable_cols());
triplet.x = reinterpret_cast<void*>(A->mutable_values());
triplet.stype = 0; // Matrix is not symmetric.
triplet.itype = CHOLMOD_INT;
triplet.xtype = CHOLMOD_REAL;
triplet.dtype = CHOLMOD_DOUBLE;
return cholmod_triplet_to_sparse(&triplet, triplet.nnz, &cc_);
}
2013-04-19 08:19:11 -07:00
cholmod_sparse SuiteSparse::CreateSparseMatrixTransposeView(
CompressedRowSparseMatrix* A) {
2013-04-19 08:19:11 -07:00
cholmod_sparse m;
m.nrow = A->num_cols();
m.ncol = A->num_rows();
m.nzmax = A->num_nonzeros();
m.nz = NULL;
m.p = reinterpret_cast<void*>(A->mutable_rows());
m.i = reinterpret_cast<void*>(A->mutable_cols());
m.x = reinterpret_cast<void*>(A->mutable_values());
m.z = NULL;
if (A->storage_type() == CompressedRowSparseMatrix::LOWER_TRIANGULAR) {
m.stype = 1;
} else if (A->storage_type() == CompressedRowSparseMatrix::UPPER_TRIANGULAR) {
m.stype = -1;
} else {
m.stype = 0;
}
2013-04-19 08:19:11 -07:00
m.itype = CHOLMOD_INT;
m.xtype = CHOLMOD_REAL;
m.dtype = CHOLMOD_DOUBLE;
m.sorted = 1;
m.packed = 1;
2012-04-30 23:09:08 -07:00
return m;
}
cholmod_dense* SuiteSparse::CreateDenseVector(const double* x,
int in_size,
int out_size) {
2017-04-12 12:48:44 -07:00
CHECK_LE(in_size, out_size);
cholmod_dense* v = cholmod_zeros(out_size, 1, CHOLMOD_REAL, &cc_);
if (x != NULL) {
memcpy(v->x, x, in_size * sizeof(*x));
}
return v;
2012-04-30 23:09:08 -07:00
}
cholmod_factor* SuiteSparse::AnalyzeCholesky(cholmod_sparse* A,
2013-11-28 06:50:43 -08:00
string* message) {
2012-06-05 23:10:59 -07:00
// Cholmod can try multiple re-ordering strategies to find a fill
// reducing ordering. Here we just tell it use AMD with automatic
// matrix dependence choice of supernodal versus simplicial
// factorization.
cc_.nmethods = 1;
cc_.method[0].ordering = CHOLMOD_AMD;
cc_.supernodal = CHOLMOD_AUTO;
2013-04-01 09:11:07 -07:00
2012-04-30 23:09:08 -07:00
cholmod_factor* factor = cholmod_analyze(A, &cc_);
2013-04-01 09:11:07 -07:00
if (VLOG_IS_ON(2)) {
cholmod_print_common(const_cast<char*>("Symbolic Analysis"), &cc_);
}
if (cc_.status != CHOLMOD_OK) {
2017-04-12 12:48:44 -07:00
*message =
StringPrintf("cholmod_analyze failed. error code: %d", cc_.status);
return NULL;
}
return CHECK_NOTNULL(factor);
2012-04-30 23:09:08 -07:00
}
2017-04-12 12:48:44 -07:00
cholmod_factor* SuiteSparse::BlockAnalyzeCholesky(cholmod_sparse* A,
const vector<int>& row_blocks,
const vector<int>& col_blocks,
string* message) {
2012-06-05 23:10:59 -07:00
vector<int> ordering;
if (!BlockAMDOrdering(A, row_blocks, col_blocks, &ordering)) {
return NULL;
}
2013-11-28 06:50:43 -08:00
return AnalyzeCholeskyWithUserOrdering(A, ordering, message);
2012-06-05 23:10:59 -07:00
}
2013-02-20 01:39:03 -08:00
cholmod_factor* SuiteSparse::AnalyzeCholeskyWithUserOrdering(
2017-04-12 12:48:44 -07:00
cholmod_sparse* A, const vector<int>& ordering, string* message) {
2012-06-05 23:10:59 -07:00
CHECK_EQ(ordering.size(), A->nrow);
2013-04-01 09:11:07 -07:00
2013-02-20 01:39:03 -08:00
cc_.nmethods = 1;
2012-06-05 23:10:59 -07:00
cc_.method[0].ordering = CHOLMOD_GIVEN;
2013-04-01 09:11:07 -07:00
2017-04-12 12:48:44 -07:00
cholmod_factor* factor =
2012-06-05 23:10:59 -07:00
cholmod_analyze_p(A, const_cast<int*>(&ordering[0]), NULL, 0, &cc_);
2013-04-01 09:11:07 -07:00
if (VLOG_IS_ON(2)) {
cholmod_print_common(const_cast<char*>("Symbolic Analysis"), &cc_);
}
if (cc_.status != CHOLMOD_OK) {
2017-04-12 12:48:44 -07:00
*message =
StringPrintf("cholmod_analyze failed. error code: %d", cc_.status);
return NULL;
}
2013-04-01 09:11:07 -07:00
return CHECK_NOTNULL(factor);
2012-06-05 23:10:59 -07:00
}
2013-04-22 10:18:18 -07:00
cholmod_factor* SuiteSparse::AnalyzeCholeskyWithNaturalOrdering(
2017-04-12 12:48:44 -07:00
cholmod_sparse* A, string* message) {
2013-04-19 08:19:11 -07:00
cc_.nmethods = 1;
cc_.method[0].ordering = CHOLMOD_NATURAL;
cc_.postorder = 0;
2017-04-12 12:48:44 -07:00
cholmod_factor* factor = cholmod_analyze(A, &cc_);
2013-04-19 08:19:11 -07:00
if (VLOG_IS_ON(2)) {
cholmod_print_common(const_cast<char*>("Symbolic Analysis"), &cc_);
}
if (cc_.status != CHOLMOD_OK) {
2017-04-12 12:48:44 -07:00
*message =
StringPrintf("cholmod_analyze failed. error code: %d", cc_.status);
return NULL;
}
2013-04-19 08:19:11 -07:00
return CHECK_NOTNULL(factor);
2013-04-19 08:19:11 -07:00
}
2012-06-05 23:10:59 -07:00
bool SuiteSparse::BlockAMDOrdering(const cholmod_sparse* A,
const vector<int>& row_blocks,
const vector<int>& col_blocks,
vector<int>* ordering) {
const int num_row_blocks = row_blocks.size();
const int num_col_blocks = col_blocks.size();
// Arrays storing the compressed column structure of the matrix
// incoding the block sparsity of A.
vector<int> block_cols;
vector<int> block_rows;
CompressedColumnScalarMatrixToBlockMatrix(reinterpret_cast<const int*>(A->i),
reinterpret_cast<const int*>(A->p),
row_blocks,
col_blocks,
&block_rows,
&block_cols);
2012-06-05 23:10:59 -07:00
cholmod_sparse_struct block_matrix;
block_matrix.nrow = num_row_blocks;
block_matrix.ncol = num_col_blocks;
block_matrix.nzmax = block_rows.size();
block_matrix.p = reinterpret_cast<void*>(&block_cols[0]);
block_matrix.i = reinterpret_cast<void*>(&block_rows[0]);
block_matrix.x = NULL;
block_matrix.stype = A->stype;
block_matrix.itype = CHOLMOD_INT;
block_matrix.xtype = CHOLMOD_PATTERN;
block_matrix.dtype = CHOLMOD_DOUBLE;
block_matrix.sorted = 1;
block_matrix.packed = 1;
vector<int> block_ordering(num_row_blocks);
if (!cholmod_amd(&block_matrix, NULL, 0, &block_ordering[0], &cc_)) {
return false;
}
BlockOrderingToScalarOrdering(row_blocks, block_ordering, ordering);
return true;
}
LinearSolverTerminationType SuiteSparse::Cholesky(cholmod_sparse* A,
cholmod_factor* L,
2013-11-28 06:50:43 -08:00
string* message) {
2012-04-30 23:09:08 -07:00
CHECK_NOTNULL(A);
CHECK_NOTNULL(L);
2013-04-01 09:11:07 -07:00
// Save the current print level and silence CHOLMOD, otherwise
// CHOLMOD is prone to dumping stuff to stderr, which can be
// distracting when the error (matrix is indefinite) is not a fatal
// failure.
const int old_print_level = cc_.print;
cc_.print = 0;
2012-04-30 23:09:08 -07:00
cc_.quick_return_if_not_posdef = 1;
int cholmod_status = cholmod_factorize(A, L, &cc_);
2013-04-01 09:11:07 -07:00
cc_.print = old_print_level;
2012-04-30 23:09:08 -07:00
switch (cc_.status) {
case CHOLMOD_NOT_INSTALLED:
2013-11-28 06:50:43 -08:00
*message = "CHOLMOD failure: Method not installed.";
2013-11-27 10:24:03 -08:00
return LINEAR_SOLVER_FATAL_ERROR;
2012-04-30 23:09:08 -07:00
case CHOLMOD_OUT_OF_MEMORY:
2013-11-28 06:50:43 -08:00
*message = "CHOLMOD failure: Out of memory.";
2013-11-27 10:24:03 -08:00
return LINEAR_SOLVER_FATAL_ERROR;
2012-04-30 23:09:08 -07:00
case CHOLMOD_TOO_LARGE:
2016-10-19 04:45:23 -07:00
*message = "CHOLMOD failure: Integer overflow occurred.";
2013-11-27 10:24:03 -08:00
return LINEAR_SOLVER_FATAL_ERROR;
2012-04-30 23:09:08 -07:00
case CHOLMOD_INVALID:
2013-11-28 06:50:43 -08:00
*message = "CHOLMOD failure: Invalid input.";
2013-11-27 10:24:03 -08:00
return LINEAR_SOLVER_FATAL_ERROR;
2012-04-30 23:09:08 -07:00
case CHOLMOD_NOT_POSDEF:
2013-11-28 06:50:43 -08:00
*message = "CHOLMOD warning: Matrix not positive definite.";
2013-11-27 10:24:03 -08:00
return LINEAR_SOLVER_FAILURE;
2012-04-30 23:09:08 -07:00
case CHOLMOD_DSMALL:
2017-04-12 12:48:44 -07:00
*message =
"CHOLMOD warning: D for LDL' or diag(L) or "
"LL' has tiny absolute value.";
2013-11-27 10:24:03 -08:00
return LINEAR_SOLVER_FAILURE;
2012-04-30 23:09:08 -07:00
case CHOLMOD_OK:
2013-11-28 07:13:26 -08:00
if (cholmod_status != 0) {
2013-11-27 10:24:03 -08:00
return LINEAR_SOLVER_SUCCESS;
2012-04-30 23:09:08 -07:00
}
2017-04-12 12:48:44 -07:00
*message =
"CHOLMOD failure: cholmod_factorize returned false "
2013-12-02 12:02:03 -08:00
"but cholmod_common::status is CHOLMOD_OK."
"Please report this to ceres-solver@googlegroups.com.";
2013-11-27 10:24:03 -08:00
return LINEAR_SOLVER_FATAL_ERROR;
2012-04-30 23:09:08 -07:00
default:
2017-04-12 12:48:44 -07:00
*message = StringPrintf(
"Unknown cholmod return code: %d. "
"Please report this to ceres-solver@googlegroups.com.",
cc_.status);
2013-11-27 10:24:03 -08:00
return LINEAR_SOLVER_FATAL_ERROR;
2012-04-30 23:09:08 -07:00
}
2013-11-27 10:24:03 -08:00
return LINEAR_SOLVER_FATAL_ERROR;
2012-04-30 23:09:08 -07:00
}
cholmod_dense* SuiteSparse::Solve(cholmod_factor* L,
cholmod_dense* b,
2013-11-28 06:50:43 -08:00
string* message) {
2012-04-30 23:09:08 -07:00
if (cc_.status != CHOLMOD_OK) {
2013-11-28 06:50:43 -08:00
*message = "cholmod_solve failed. CHOLMOD status is not CHOLMOD_OK";
2012-04-30 23:09:08 -07:00
return NULL;
}
return cholmod_solve(CHOLMOD_A, L, b, &cc_);
}
bool SuiteSparse::ApproximateMinimumDegreeOrdering(cholmod_sparse* matrix,
int* ordering) {
return cholmod_amd(matrix, NULL, 0, ordering, &cc_);
}
bool SuiteSparse::ConstrainedApproximateMinimumDegreeOrdering(
2017-04-12 12:48:44 -07:00
cholmod_sparse* matrix, int* constraints, int* ordering) {
2013-04-26 21:17:49 -07:00
#ifndef CERES_NO_CAMD
return cholmod_camd(matrix, NULL, 0, constraints, ordering, &cc_);
2013-04-26 21:17:49 -07:00
#else
LOG(FATAL) << "Congratulations you have found a bug in Ceres."
<< "Ceres Solver was compiled with SuiteSparse "
<< "version 4.1.0 or less. Calling this function "
<< "in that case is a bug. Please contact the"
2013-04-29 17:27:26 -07:00
<< "the Ceres Solver developers.";
return false;
2013-04-26 21:17:49 -07:00
#endif
}
2017-04-12 12:48:44 -07:00
SuiteSparseCholesky* SuiteSparseCholesky::Create(
const OrderingType ordering_type) {
return new SuiteSparseCholesky(ordering_type);
}
SuiteSparseCholesky::SuiteSparseCholesky(const OrderingType ordering_type)
: ordering_type_(ordering_type), factor_(NULL) {}
SuiteSparseCholesky::~SuiteSparseCholesky() {
if (factor_ != NULL) {
ss_.Free(factor_);
}
}
LinearSolverTerminationType SuiteSparseCholesky::Factorize(
CompressedRowSparseMatrix* lhs, string* message) {
if (lhs == NULL) {
*message = "Failure: Input lhs is NULL.";
return LINEAR_SOLVER_FATAL_ERROR;
}
cholmod_sparse cholmod_lhs = ss_.CreateSparseMatrixTransposeView(lhs);
if (factor_ == NULL) {
if (ordering_type_ == NATURAL) {
factor_ = ss_.AnalyzeCholeskyWithNaturalOrdering(&cholmod_lhs, message);
} else {
if (!lhs->col_blocks().empty() && !(lhs->row_blocks().empty())) {
factor_ = ss_.BlockAnalyzeCholesky(
&cholmod_lhs, lhs->col_blocks(), lhs->row_blocks(), message);
} else {
factor_ = ss_.AnalyzeCholesky(&cholmod_lhs, message);
}
}
if (factor_ == NULL) {
return LINEAR_SOLVER_FATAL_ERROR;
}
}
return ss_.Cholesky(&cholmod_lhs, factor_, message);
}
CompressedRowSparseMatrix::StorageType SuiteSparseCholesky::StorageType()
const {
return ((ordering_type_ == NATURAL)
? CompressedRowSparseMatrix::UPPER_TRIANGULAR
: CompressedRowSparseMatrix::LOWER_TRIANGULAR);
}
LinearSolverTerminationType SuiteSparseCholesky::Solve(const double* rhs,
double* solution,
string* message) {
// Error checking
if (factor_ == NULL) {
*message = "Solve called without a call to Factorize first.";
return LINEAR_SOLVER_FATAL_ERROR;
}
const int num_cols = factor_->n;
cholmod_dense* cholmod_dense_rhs =
ss_.CreateDenseVector(rhs, num_cols, num_cols);
cholmod_dense* cholmod_dense_solution =
ss_.Solve(factor_, cholmod_dense_rhs, message);
ss_.Free(cholmod_dense_rhs);
if (cholmod_dense_solution == NULL) {
return LINEAR_SOLVER_FAILURE;
}
memcpy(solution, cholmod_dense_solution->x, num_cols * sizeof(*solution));
2017-05-24 01:17:03 -07:00
ss_.Free(cholmod_dense_solution);
2017-04-12 12:48:44 -07:00
return LINEAR_SOLVER_SUCCESS;
}
2012-04-30 23:09:08 -07:00
} // namespace internal
} // namespace ceres
#endif // CERES_NO_SUITESPARSE