blob: 9847bfd866c93d0684c79d58ea12b286a6d0c6c2 [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Ceres Solver - A fast non-linear least squares minimizer
2// Copyright 2017 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#include "ceres/eigensparse.h"
32
33#ifdef CERES_USE_EIGEN_SPARSE
34
35#include <sstream>
36#include "Eigen/SparseCholesky"
37#include "Eigen/SparseCore"
38#include "ceres/compressed_row_sparse_matrix.h"
39#include "ceres/linear_solver.h"
40
41namespace ceres {
42namespace internal {
43
44// TODO(sameeragarwal): Use enable_if to clean up the implementations
45// for when Scalar == double.
46template <typename Solver>
47class EigenSparseCholeskyTemplate : public SparseCholesky {
48 public:
49 EigenSparseCholeskyTemplate() : analyzed_(false) {}
50 virtual ~EigenSparseCholeskyTemplate() {}
51 virtual CompressedRowSparseMatrix::StorageType StorageType() const {
52 return CompressedRowSparseMatrix::LOWER_TRIANGULAR;
53 }
54
55 virtual LinearSolverTerminationType Factorize(
56 const Eigen::SparseMatrix<typename Solver::Scalar>& lhs,
57 std::string* message) {
58 if (!analyzed_) {
59 solver_.analyzePattern(lhs);
60
61 if (VLOG_IS_ON(2)) {
62 std::stringstream ss;
63 solver_.dumpMemory(ss);
64 VLOG(2) << "Symbolic Analysis\n" << ss.str();
65 }
66
67 if (solver_.info() != Eigen::Success) {
68 *message = "Eigen failure. Unable to find symbolic factorization.";
69 return LINEAR_SOLVER_FATAL_ERROR;
70 }
71
72 analyzed_ = true;
73 }
74
75 solver_.factorize(lhs);
76 if (solver_.info() != Eigen::Success) {
77 *message = "Eigen failure. Unable to find numeric factorization.";
78 return LINEAR_SOLVER_FAILURE;
79 }
80 return LINEAR_SOLVER_SUCCESS;
81 }
82
83 LinearSolverTerminationType Solve(const double* rhs_ptr,
84 double* solution_ptr,
85 std::string* message) {
86 CHECK(analyzed_) << "Solve called without a call to Factorize first.";
87
88 scalar_rhs_ = ConstVectorRef(rhs_ptr, solver_.cols())
89 .template cast<typename Solver::Scalar>();
90
91 // The two casts are needed if the Scalar in this class is not
92 // double. For code simplicity we are going to assume that Eigen
93 // is smart enough to figure out that casting a double Vector to a
94 // double Vector is a straight copy. If this turns into a
95 // performance bottleneck (unlikely), we can revisit this.
96 scalar_solution_ = solver_.solve(scalar_rhs_);
97 VectorRef(solution_ptr, solver_.cols()) =
98 scalar_solution_.template cast<double>();
99
100 if (solver_.info() != Eigen::Success) {
101 *message = "Eigen failure. Unable to do triangular solve.";
102 return LINEAR_SOLVER_FAILURE;
103 }
104 return LINEAR_SOLVER_SUCCESS;
105 }
106
107 virtual LinearSolverTerminationType Factorize(CompressedRowSparseMatrix* lhs,
108 std::string* message) {
109 CHECK_EQ(lhs->storage_type(), StorageType());
110
111 typename Solver::Scalar* values_ptr = NULL;
112 if (std::is_same<typename Solver::Scalar, double>::value) {
113 values_ptr =
114 reinterpret_cast<typename Solver::Scalar*>(lhs->mutable_values());
115 } else {
116 // In the case where the scalar used in this class is not
117 // double. In that case, make a copy of the values array in the
118 // CompressedRowSparseMatrix and cast it to Scalar along the way.
119 values_ = ConstVectorRef(lhs->values(), lhs->num_nonzeros())
120 .cast<typename Solver::Scalar>();
121 values_ptr = values_.data();
122 }
123
124 Eigen::MappedSparseMatrix<typename Solver::Scalar, Eigen::ColMajor>
125 eigen_lhs(lhs->num_rows(),
126 lhs->num_rows(),
127 lhs->num_nonzeros(),
128 lhs->mutable_rows(),
129 lhs->mutable_cols(),
130 values_ptr);
131 return Factorize(eigen_lhs, message);
132 }
133
134 private:
135 Eigen::Matrix<typename Solver::Scalar, Eigen::Dynamic, 1> values_,
136 scalar_rhs_, scalar_solution_;
137 bool analyzed_;
138 Solver solver_;
139};
140
141std::unique_ptr<SparseCholesky> EigenSparseCholesky::Create(
142 const OrderingType ordering_type) {
143 std::unique_ptr<SparseCholesky> sparse_cholesky;
144
145 // The preprocessor gymnastics here are dealing with the fact that
146 // before version 3.2.2, Eigen did not support a third template
147 // parameter to specify the ordering and it always defaults to AMD.
148#if EIGEN_VERSION_AT_LEAST(3, 2, 2)
149 typedef Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>,
150 Eigen::Upper,
151 Eigen::AMDOrdering<int>>
152 WithAMDOrdering;
153 typedef Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>,
154 Eigen::Upper,
155 Eigen::NaturalOrdering<int>>
156 WithNaturalOrdering;
157 if (ordering_type == AMD) {
158 sparse_cholesky.reset(new EigenSparseCholeskyTemplate<WithAMDOrdering>());
159 } else {
160 sparse_cholesky.reset(
161 new EigenSparseCholeskyTemplate<WithNaturalOrdering>());
162 }
163#else
164 typedef Eigen::SimplicialLDLT<Eigen::SparseMatrix<double>, Eigen::Upper>
165 WithAMDOrdering;
166 sparse_cholesky.reset(new EigenSparseCholeskyTemplate<WithAMDOrdering>());
167#endif
168 return sparse_cholesky;
169}
170
171EigenSparseCholesky::~EigenSparseCholesky() {}
172
173std::unique_ptr<SparseCholesky> FloatEigenSparseCholesky::Create(
174 const OrderingType ordering_type) {
175 std::unique_ptr<SparseCholesky> sparse_cholesky;
176 // The preprocessor gymnastics here are dealing with the fact that
177 // before version 3.2.2, Eigen did not support a third template
178 // parameter to specify the ordering and it always defaults to AMD.
179#if EIGEN_VERSION_AT_LEAST(3, 2, 2)
180 typedef Eigen::SimplicialLDLT<Eigen::SparseMatrix<float>,
181 Eigen::Upper,
182 Eigen::AMDOrdering<int>>
183 WithAMDOrdering;
184 typedef Eigen::SimplicialLDLT<Eigen::SparseMatrix<float>,
185 Eigen::Upper,
186 Eigen::NaturalOrdering<int>>
187 WithNaturalOrdering;
188 if (ordering_type == AMD) {
189 sparse_cholesky.reset(new EigenSparseCholeskyTemplate<WithAMDOrdering>());
190 } else {
191 sparse_cholesky.reset(
192 new EigenSparseCholeskyTemplate<WithNaturalOrdering>());
193 }
194#else
195 typedef Eigen::SimplicialLDLT<Eigen::SparseMatrix<float>, Eigen::Upper>
196 WithAMDOrdering;
197 sparse_cholesky.reset(new EigenSparseCholeskyTemplate<WithAMDOrdering>());
198#endif
199 return sparse_cholesky;
200}
201
202FloatEigenSparseCholesky::~FloatEigenSparseCholesky() {}
203
204} // namespace internal
205} // namespace ceres
206
207#endif // CERES_USE_EIGEN_SPARSE