blob: 2ef24e321caa4001a97326cb968dcb56e4fcce4d [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/sparse_cholesky.h"
32
33#include <memory>
34#include <numeric>
35#include <vector>
36
37#include "Eigen/Dense"
38#include "Eigen/SparseCore"
39#include "ceres/block_sparse_matrix.h"
40#include "ceres/compressed_row_sparse_matrix.h"
41#include "ceres/inner_product_computer.h"
42#include "ceres/internal/eigen.h"
43#include "ceres/iterative_refiner.h"
44#include "ceres/random.h"
45#include "glog/logging.h"
46#include "gmock/gmock.h"
47#include "gtest/gtest.h"
48
49namespace ceres {
50namespace internal {
51
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080052namespace {
53
Austin Schuh70cc9552019-01-21 19:46:48 -080054BlockSparseMatrix* CreateRandomFullRankMatrix(const int num_col_blocks,
55 const int min_col_block_size,
56 const int max_col_block_size,
57 const double block_density) {
58 // Create a random matrix
59 BlockSparseMatrix::RandomMatrixOptions options;
60 options.num_col_blocks = num_col_blocks;
61 options.min_col_block_size = min_col_block_size;
62 options.max_col_block_size = max_col_block_size;
63
64 options.num_row_blocks = 2 * num_col_blocks;
65 options.min_row_block_size = 1;
66 options.max_row_block_size = max_col_block_size;
67 options.block_density = block_density;
68 std::unique_ptr<BlockSparseMatrix> random_matrix(
69 BlockSparseMatrix::CreateRandomMatrix(options));
70
71 // Add a diagonal block sparse matrix to make it full rank.
72 Vector diagonal = Vector::Ones(random_matrix->num_cols());
73 std::unique_ptr<BlockSparseMatrix> block_diagonal(
74 BlockSparseMatrix::CreateDiagonalMatrix(
75 diagonal.data(), random_matrix->block_structure()->cols));
76 random_matrix->AppendRows(*block_diagonal);
77 return random_matrix.release();
78}
79
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080080static bool ComputeExpectedSolution(const CompressedRowSparseMatrix& lhs,
81 const Vector& rhs,
82 Vector* solution) {
Austin Schuh70cc9552019-01-21 19:46:48 -080083 Matrix eigen_lhs;
84 lhs.ToDenseMatrix(&eigen_lhs);
85 if (lhs.storage_type() == CompressedRowSparseMatrix::UPPER_TRIANGULAR) {
86 Matrix full_lhs = eigen_lhs.selfadjointView<Eigen::Upper>();
87 Eigen::LLT<Matrix, Eigen::Upper> llt =
88 eigen_lhs.selfadjointView<Eigen::Upper>().llt();
89 if (llt.info() != Eigen::Success) {
90 return false;
91 }
92 *solution = llt.solve(rhs);
93 return (llt.info() == Eigen::Success);
94 }
95
96 Matrix full_lhs = eigen_lhs.selfadjointView<Eigen::Lower>();
97 Eigen::LLT<Matrix, Eigen::Lower> llt =
98 eigen_lhs.selfadjointView<Eigen::Lower>().llt();
99 if (llt.info() != Eigen::Success) {
100 return false;
101 }
102 *solution = llt.solve(rhs);
103 return (llt.info() == Eigen::Success);
104}
105
106void SparseCholeskySolverUnitTest(
107 const SparseLinearAlgebraLibraryType sparse_linear_algebra_library_type,
108 const OrderingType ordering_type,
109 const bool use_block_structure,
110 const int num_blocks,
111 const int min_block_size,
112 const int max_block_size,
113 const double block_density) {
114 LinearSolver::Options sparse_cholesky_options;
115 sparse_cholesky_options.sparse_linear_algebra_library_type =
116 sparse_linear_algebra_library_type;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800117 sparse_cholesky_options.use_postordering = (ordering_type == AMD);
118 std::unique_ptr<SparseCholesky> sparse_cholesky =
119 SparseCholesky::Create(sparse_cholesky_options);
Austin Schuh70cc9552019-01-21 19:46:48 -0800120 const CompressedRowSparseMatrix::StorageType storage_type =
121 sparse_cholesky->StorageType();
122
123 std::unique_ptr<BlockSparseMatrix> m(CreateRandomFullRankMatrix(
124 num_blocks, min_block_size, max_block_size, block_density));
125 std::unique_ptr<InnerProductComputer> inner_product_computer(
126 InnerProductComputer::Create(*m, storage_type));
127 inner_product_computer->Compute();
128 CompressedRowSparseMatrix* lhs = inner_product_computer->mutable_result();
129
130 if (!use_block_structure) {
131 lhs->mutable_row_blocks()->clear();
132 lhs->mutable_col_blocks()->clear();
133 }
134
135 Vector rhs = Vector::Random(lhs->num_rows());
136 Vector expected(lhs->num_rows());
137 Vector actual(lhs->num_rows());
138
139 EXPECT_TRUE(ComputeExpectedSolution(*lhs, rhs, &expected));
140 std::string message;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800141 EXPECT_EQ(
142 sparse_cholesky->FactorAndSolve(lhs, rhs.data(), actual.data(), &message),
143 LINEAR_SOLVER_SUCCESS);
Austin Schuh70cc9552019-01-21 19:46:48 -0800144 Matrix eigen_lhs;
145 lhs->ToDenseMatrix(&eigen_lhs);
146 EXPECT_NEAR((actual - expected).norm() / actual.norm(),
147 0.0,
148 std::numeric_limits<double>::epsilon() * 20)
149 << "\n"
150 << eigen_lhs;
151}
152
153typedef ::testing::tuple<SparseLinearAlgebraLibraryType, OrderingType, bool>
154 Param;
155
156std::string ParamInfoToString(testing::TestParamInfo<Param> info) {
157 Param param = info.param;
158 std::stringstream ss;
159 ss << SparseLinearAlgebraLibraryTypeToString(::testing::get<0>(param)) << "_"
160 << (::testing::get<1>(param) == AMD ? "AMD" : "NATURAL") << "_"
161 << (::testing::get<2>(param) ? "UseBlockStructure" : "NoBlockStructure");
162 return ss.str();
163}
164
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800165} // namespace
166
Austin Schuh70cc9552019-01-21 19:46:48 -0800167class SparseCholeskyTest : public ::testing::TestWithParam<Param> {};
168
169TEST_P(SparseCholeskyTest, FactorAndSolve) {
170 SetRandomState(2982);
171 const int kMinNumBlocks = 1;
172 const int kMaxNumBlocks = 10;
173 const int kNumTrials = 10;
174 const int kMinBlockSize = 1;
175 const int kMaxBlockSize = 5;
176
177 for (int num_blocks = kMinNumBlocks; num_blocks < kMaxNumBlocks;
178 ++num_blocks) {
179 for (int trial = 0; trial < kNumTrials; ++trial) {
180 const double block_density = std::max(0.1, RandDouble());
181 Param param = GetParam();
182 SparseCholeskySolverUnitTest(::testing::get<0>(param),
183 ::testing::get<1>(param),
184 ::testing::get<2>(param),
185 num_blocks,
186 kMinBlockSize,
187 kMaxBlockSize,
188 block_density);
189 }
190 }
191}
192
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800193namespace {
194
Austin Schuh70cc9552019-01-21 19:46:48 -0800195#ifndef CERES_NO_SUITESPARSE
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800196INSTANTIATE_TEST_SUITE_P(SuiteSparseCholesky,
197 SparseCholeskyTest,
198 ::testing::Combine(::testing::Values(SUITE_SPARSE),
199 ::testing::Values(AMD, NATURAL),
200 ::testing::Values(true, false)),
201 ParamInfoToString);
Austin Schuh70cc9552019-01-21 19:46:48 -0800202#endif
203
204#ifndef CERES_NO_CXSPARSE
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800205INSTANTIATE_TEST_SUITE_P(CXSparseCholesky,
206 SparseCholeskyTest,
207 ::testing::Combine(::testing::Values(CX_SPARSE),
208 ::testing::Values(AMD, NATURAL),
209 ::testing::Values(true, false)),
210 ParamInfoToString);
Austin Schuh70cc9552019-01-21 19:46:48 -0800211#endif
212
213#ifndef CERES_NO_ACCELERATE_SPARSE
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800214INSTANTIATE_TEST_SUITE_P(
215 AccelerateSparseCholesky,
216 SparseCholeskyTest,
217 ::testing::Combine(::testing::Values(ACCELERATE_SPARSE),
218 ::testing::Values(AMD, NATURAL),
219 ::testing::Values(true, false)),
220 ParamInfoToString);
Austin Schuh70cc9552019-01-21 19:46:48 -0800221
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800222INSTANTIATE_TEST_SUITE_P(
223 AccelerateSparseCholeskySingle,
224 SparseCholeskyTest,
225 ::testing::Combine(::testing::Values(ACCELERATE_SPARSE),
226 ::testing::Values(AMD, NATURAL),
227 ::testing::Values(true, false)),
228 ParamInfoToString);
Austin Schuh70cc9552019-01-21 19:46:48 -0800229#endif
230
231#ifdef CERES_USE_EIGEN_SPARSE
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800232INSTANTIATE_TEST_SUITE_P(EigenSparseCholesky,
233 SparseCholeskyTest,
234 ::testing::Combine(::testing::Values(EIGEN_SPARSE),
235 ::testing::Values(AMD, NATURAL),
236 ::testing::Values(true, false)),
237 ParamInfoToString);
Austin Schuh70cc9552019-01-21 19:46:48 -0800238
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800239INSTANTIATE_TEST_SUITE_P(EigenSparseCholeskySingle,
240 SparseCholeskyTest,
241 ::testing::Combine(::testing::Values(EIGEN_SPARSE),
242 ::testing::Values(AMD, NATURAL),
243 ::testing::Values(true, false)),
244 ParamInfoToString);
Austin Schuh70cc9552019-01-21 19:46:48 -0800245#endif
246
247class MockSparseCholesky : public SparseCholesky {
248 public:
249 MOCK_CONST_METHOD0(StorageType, CompressedRowSparseMatrix::StorageType());
250 MOCK_METHOD2(Factorize,
251 LinearSolverTerminationType(CompressedRowSparseMatrix* lhs,
252 std::string* message));
253 MOCK_METHOD3(Solve,
254 LinearSolverTerminationType(const double* rhs,
255 double* solution,
256 std::string* message));
257};
258
259class MockIterativeRefiner : public IterativeRefiner {
260 public:
261 MockIterativeRefiner() : IterativeRefiner(1) {}
262 MOCK_METHOD4(Refine,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800263 void(const SparseMatrix& lhs,
264 const double* rhs,
265 SparseCholesky* sparse_cholesky,
266 double* solution));
Austin Schuh70cc9552019-01-21 19:46:48 -0800267};
268
Austin Schuh70cc9552019-01-21 19:46:48 -0800269using testing::_;
270using testing::Return;
271
272TEST(RefinedSparseCholesky, StorageType) {
273 MockSparseCholesky* mock_sparse_cholesky = new MockSparseCholesky;
274 MockIterativeRefiner* mock_iterative_refiner = new MockIterativeRefiner;
275 EXPECT_CALL(*mock_sparse_cholesky, StorageType())
276 .Times(1)
277 .WillRepeatedly(Return(CompressedRowSparseMatrix::UPPER_TRIANGULAR));
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800278 EXPECT_CALL(*mock_iterative_refiner, Refine(_, _, _, _)).Times(0);
Austin Schuh70cc9552019-01-21 19:46:48 -0800279 std::unique_ptr<SparseCholesky> sparse_cholesky(mock_sparse_cholesky);
280 std::unique_ptr<IterativeRefiner> iterative_refiner(mock_iterative_refiner);
281 RefinedSparseCholesky refined_sparse_cholesky(std::move(sparse_cholesky),
282 std::move(iterative_refiner));
283 EXPECT_EQ(refined_sparse_cholesky.StorageType(),
284 CompressedRowSparseMatrix::UPPER_TRIANGULAR);
285};
286
287TEST(RefinedSparseCholesky, Factorize) {
288 MockSparseCholesky* mock_sparse_cholesky = new MockSparseCholesky;
289 MockIterativeRefiner* mock_iterative_refiner = new MockIterativeRefiner;
290 EXPECT_CALL(*mock_sparse_cholesky, Factorize(_, _))
291 .Times(1)
292 .WillRepeatedly(Return(LINEAR_SOLVER_SUCCESS));
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800293 EXPECT_CALL(*mock_iterative_refiner, Refine(_, _, _, _)).Times(0);
Austin Schuh70cc9552019-01-21 19:46:48 -0800294 std::unique_ptr<SparseCholesky> sparse_cholesky(mock_sparse_cholesky);
295 std::unique_ptr<IterativeRefiner> iterative_refiner(mock_iterative_refiner);
296 RefinedSparseCholesky refined_sparse_cholesky(std::move(sparse_cholesky),
297 std::move(iterative_refiner));
298 CompressedRowSparseMatrix m(1, 1, 1);
299 std::string message;
300 EXPECT_EQ(refined_sparse_cholesky.Factorize(&m, &message),
301 LINEAR_SOLVER_SUCCESS);
302};
303
304TEST(RefinedSparseCholesky, FactorAndSolveWithUnsuccessfulFactorization) {
305 MockSparseCholesky* mock_sparse_cholesky = new MockSparseCholesky;
306 MockIterativeRefiner* mock_iterative_refiner = new MockIterativeRefiner;
307 EXPECT_CALL(*mock_sparse_cholesky, Factorize(_, _))
308 .Times(1)
309 .WillRepeatedly(Return(LINEAR_SOLVER_FAILURE));
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800310 EXPECT_CALL(*mock_sparse_cholesky, Solve(_, _, _)).Times(0);
311 EXPECT_CALL(*mock_iterative_refiner, Refine(_, _, _, _)).Times(0);
Austin Schuh70cc9552019-01-21 19:46:48 -0800312 std::unique_ptr<SparseCholesky> sparse_cholesky(mock_sparse_cholesky);
313 std::unique_ptr<IterativeRefiner> iterative_refiner(mock_iterative_refiner);
314 RefinedSparseCholesky refined_sparse_cholesky(std::move(sparse_cholesky),
315 std::move(iterative_refiner));
316 CompressedRowSparseMatrix m(1, 1, 1);
317 std::string message;
318 double rhs;
319 double solution;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800320 EXPECT_EQ(
321 refined_sparse_cholesky.FactorAndSolve(&m, &rhs, &solution, &message),
322 LINEAR_SOLVER_FAILURE);
Austin Schuh70cc9552019-01-21 19:46:48 -0800323};
324
325TEST(RefinedSparseCholesky, FactorAndSolveWithSuccess) {
326 MockSparseCholesky* mock_sparse_cholesky = new MockSparseCholesky;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800327 std::unique_ptr<MockIterativeRefiner> mock_iterative_refiner(
328 new MockIterativeRefiner);
Austin Schuh70cc9552019-01-21 19:46:48 -0800329 EXPECT_CALL(*mock_sparse_cholesky, Factorize(_, _))
330 .Times(1)
331 .WillRepeatedly(Return(LINEAR_SOLVER_SUCCESS));
332 EXPECT_CALL(*mock_sparse_cholesky, Solve(_, _, _))
333 .Times(1)
334 .WillRepeatedly(Return(LINEAR_SOLVER_SUCCESS));
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800335 EXPECT_CALL(*mock_iterative_refiner, Refine(_, _, _, _)).Times(1);
Austin Schuh70cc9552019-01-21 19:46:48 -0800336
337 std::unique_ptr<SparseCholesky> sparse_cholesky(mock_sparse_cholesky);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800338 std::unique_ptr<IterativeRefiner> iterative_refiner(
339 std::move(mock_iterative_refiner));
Austin Schuh70cc9552019-01-21 19:46:48 -0800340 RefinedSparseCholesky refined_sparse_cholesky(std::move(sparse_cholesky),
341 std::move(iterative_refiner));
342 CompressedRowSparseMatrix m(1, 1, 1);
343 std::string message;
344 double rhs;
345 double solution;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800346 EXPECT_EQ(
347 refined_sparse_cholesky.FactorAndSolve(&m, &rhs, &solution, &message),
348 LINEAR_SOLVER_SUCCESS);
Austin Schuh70cc9552019-01-21 19:46:48 -0800349};
350
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800351} // namespace
352
Austin Schuh70cc9552019-01-21 19:46:48 -0800353} // namespace internal
354} // namespace ceres