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

389 lines
15 KiB
C++
Raw Normal View History

2017-04-12 12:48:44 -07:00
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2017 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// 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)
#include "ceres/sparse_cholesky.h"
2018-03-30 16:16:59 -07:00
#include <memory>
2017-04-12 12:48:44 -07:00
#include <numeric>
#include <random>
2017-04-12 12:48:44 -07:00
#include <vector>
#include "Eigen/Dense"
#include "Eigen/SparseCore"
2017-06-13 00:12:00 -07:00
#include "ceres/block_sparse_matrix.h"
2017-04-12 12:48:44 -07:00
#include "ceres/compressed_row_sparse_matrix.h"
2017-06-13 00:12:00 -07:00
#include "ceres/inner_product_computer.h"
2022-03-12 15:22:19 -08:00
#include "ceres/internal/config.h"
2017-04-12 12:48:44 -07:00
#include "ceres/internal/eigen.h"
2018-04-09 16:21:18 -07:00
#include "ceres/iterative_refiner.h"
2017-04-12 12:48:44 -07:00
#include "glog/logging.h"
2018-04-09 16:21:18 -07:00
#include "gmock/gmock.h"
2017-04-12 12:48:44 -07:00
#include "gtest/gtest.h"
2022-04-21 17:41:10 -07:00
namespace ceres::internal {
2017-04-12 12:48:44 -07:00
namespace {
std::unique_ptr<BlockSparseMatrix> CreateRandomFullRankMatrix(
const int num_col_blocks,
const int min_col_block_size,
const int max_col_block_size,
const double block_density,
std::mt19937& prng) {
2017-04-12 12:48:44 -07:00
// Create a random matrix
2017-06-13 00:12:00 -07:00
BlockSparseMatrix::RandomMatrixOptions options;
2017-04-12 12:48:44 -07:00
options.num_col_blocks = num_col_blocks;
options.min_col_block_size = min_col_block_size;
options.max_col_block_size = max_col_block_size;
options.num_row_blocks = 2 * num_col_blocks;
options.min_row_block_size = 1;
options.max_row_block_size = max_col_block_size;
options.block_density = block_density;
auto random_matrix = BlockSparseMatrix::CreateRandomMatrix(options, prng);
2017-04-12 12:48:44 -07:00
// Add a diagonal block sparse matrix to make it full rank.
2017-06-13 00:12:00 -07:00
Vector diagonal = Vector::Ones(random_matrix->num_cols());
auto block_diagonal = BlockSparseMatrix::CreateDiagonalMatrix(
diagonal.data(), random_matrix->block_structure()->cols);
2017-06-13 00:12:00 -07:00
random_matrix->AppendRows(*block_diagonal);
return random_matrix;
2017-04-12 12:48:44 -07:00
}
2022-11-13 18:38:34 +01:00
bool ComputeExpectedSolution(const CompressedRowSparseMatrix& lhs,
const Vector& rhs,
Vector* solution) {
2017-04-12 12:48:44 -07:00
Matrix eigen_lhs;
lhs.ToDenseMatrix(&eigen_lhs);
2022-05-14 14:14:22 -07:00
if (lhs.storage_type() ==
CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR) {
2017-04-12 12:48:44 -07:00
Matrix full_lhs = eigen_lhs.selfadjointView<Eigen::Upper>();
Eigen::LLT<Matrix, Eigen::Upper> llt =
eigen_lhs.selfadjointView<Eigen::Upper>().llt();
if (llt.info() != Eigen::Success) {
return false;
}
*solution = llt.solve(rhs);
return (llt.info() == Eigen::Success);
}
Matrix full_lhs = eigen_lhs.selfadjointView<Eigen::Lower>();
Eigen::LLT<Matrix, Eigen::Lower> llt =
eigen_lhs.selfadjointView<Eigen::Lower>().llt();
if (llt.info() != Eigen::Success) {
return false;
}
*solution = llt.solve(rhs);
return (llt.info() == Eigen::Success);
}
void SparseCholeskySolverUnitTest(
const SparseLinearAlgebraLibraryType sparse_linear_algebra_library_type,
const OrderingType ordering_type,
const bool use_block_structure,
const int num_blocks,
const int min_block_size,
const int max_block_size,
const double block_density,
std::mt19937& prng) {
2018-04-06 08:39:16 -07:00
LinearSolver::Options sparse_cholesky_options;
sparse_cholesky_options.sparse_linear_algebra_library_type =
sparse_linear_algebra_library_type;
2022-05-19 00:47:24 -07:00
sparse_cholesky_options.ordering_type = ordering_type;
auto sparse_cholesky = SparseCholesky::Create(sparse_cholesky_options);
2017-04-12 12:48:44 -07:00
const CompressedRowSparseMatrix::StorageType storage_type =
sparse_cholesky->StorageType();
auto m = CreateRandomFullRankMatrix(
num_blocks, min_block_size, max_block_size, block_density, prng);
auto inner_product_computer = InnerProductComputer::Create(*m, storage_type);
2017-06-13 00:12:00 -07:00
inner_product_computer->Compute();
CompressedRowSparseMatrix* lhs = inner_product_computer->mutable_result();
2017-04-12 12:48:44 -07:00
if (!use_block_structure) {
lhs->mutable_row_blocks()->clear();
lhs->mutable_col_blocks()->clear();
}
Vector rhs = Vector::Random(lhs->num_rows());
Vector expected(lhs->num_rows());
Vector actual(lhs->num_rows());
EXPECT_TRUE(ComputeExpectedSolution(*lhs, rhs, &expected));
std::string message;
2019-03-02 22:42:20 -08:00
EXPECT_EQ(
sparse_cholesky->FactorAndSolve(lhs, rhs.data(), actual.data(), &message),
2022-05-14 14:14:22 -07:00
LinearSolverTerminationType::SUCCESS);
2017-04-12 12:48:44 -07:00
Matrix eigen_lhs;
lhs->ToDenseMatrix(&eigen_lhs);
EXPECT_NEAR((actual - expected).norm() / actual.norm(),
0.0,
std::numeric_limits<double>::epsilon() * 20)
2017-04-12 12:48:44 -07:00
<< "\n"
<< eigen_lhs;
}
2022-02-20 02:22:17 +01:00
using Param =
::testing::tuple<SparseLinearAlgebraLibraryType, OrderingType, bool>;
2017-04-12 12:48:44 -07:00
std::string ParamInfoToString(testing::TestParamInfo<Param> info) {
Param param = info.param;
std::stringstream ss;
ss << SparseLinearAlgebraLibraryTypeToString(::testing::get<0>(param)) << "_"
2022-05-19 00:47:24 -07:00
<< ::testing::get<1>(param) << "_"
<< (::testing::get<2>(param) ? "UseBlockStructure" : "NoBlockStructure");
2017-04-12 12:48:44 -07:00
return ss.str();
}
} // namespace
2017-04-12 12:48:44 -07:00
class SparseCholeskyTest : public ::testing::TestWithParam<Param> {};
TEST_P(SparseCholeskyTest, FactorAndSolve) {
2022-11-13 18:38:34 +01:00
constexpr int kMinNumBlocks = 1;
constexpr int kMaxNumBlocks = 10;
constexpr int kNumTrials = 10;
constexpr int kMinBlockSize = 1;
constexpr int kMaxBlockSize = 5;
Param param = GetParam();
std::mt19937 prng;
2022-08-08 20:16:51 -07:00
std::uniform_real_distribution<double> distribution(0.1, 1.0);
2017-04-12 12:48:44 -07:00
for (int num_blocks = kMinNumBlocks; num_blocks < kMaxNumBlocks;
++num_blocks) {
for (int trial = 0; trial < kNumTrials; ++trial) {
const double block_density = distribution(prng);
SparseCholeskySolverUnitTest(::testing::get<0>(param),
::testing::get<1>(param),
::testing::get<2>(param),
2017-04-12 12:48:44 -07:00
num_blocks,
kMinBlockSize,
kMaxBlockSize,
block_density,
prng);
2017-04-12 12:48:44 -07:00
}
}
}
namespace {
2017-04-12 12:48:44 -07:00
#ifndef CERES_NO_SUITESPARSE
2022-05-14 14:14:22 -07:00
INSTANTIATE_TEST_SUITE_P(
SuiteSparseCholesky,
SparseCholeskyTest,
::testing::Combine(::testing::Values(SUITE_SPARSE),
::testing::Values(OrderingType::AMD,
OrderingType::NATURAL),
2022-05-14 14:14:22 -07:00
::testing::Values(true, false)),
ParamInfoToString);
2017-04-12 12:48:44 -07:00
#endif
#if !defined(CERES_NO_SUITESPARSE) && !defined(CERES_NO_CHOLMOD_PARTITION)
INSTANTIATE_TEST_SUITE_P(
SuiteSparseCholeskyMETIS,
SparseCholeskyTest,
::testing::Combine(::testing::Values(SUITE_SPARSE),
::testing::Values(OrderingType::NESDIS),
::testing::Values(true, false)),
ParamInfoToString);
#endif // !defined(CERES_NO_SUITESPARSE) &&
// !defined(CERES_NO_CHOLMOD_PARTITION)
#ifndef CERES_NO_ACCELERATE_SPARSE
2019-03-02 22:42:20 -08:00
INSTANTIATE_TEST_SUITE_P(
AccelerateSparseCholesky,
SparseCholeskyTest,
::testing::Combine(::testing::Values(ACCELERATE_SPARSE),
2022-05-14 14:14:22 -07:00
::testing::Values(OrderingType::AMD,
OrderingType::NESDIS,
2022-05-14 14:14:22 -07:00
OrderingType::NATURAL),
2019-03-02 22:42:20 -08:00
::testing::Values(true, false)),
ParamInfoToString);
INSTANTIATE_TEST_SUITE_P(
AccelerateSparseCholeskySingle,
SparseCholeskyTest,
::testing::Combine(::testing::Values(ACCELERATE_SPARSE),
2022-05-14 14:14:22 -07:00
::testing::Values(OrderingType::AMD,
OrderingType::NESDIS,
2022-05-14 14:14:22 -07:00
OrderingType::NATURAL),
2019-03-02 22:42:20 -08:00
::testing::Values(true, false)),
ParamInfoToString);
#endif
2017-04-12 12:48:44 -07:00
#ifdef CERES_USE_EIGEN_SPARSE
2022-05-14 14:14:22 -07:00
INSTANTIATE_TEST_SUITE_P(
EigenSparseCholesky,
SparseCholeskyTest,
::testing::Combine(::testing::Values(EIGEN_SPARSE),
::testing::Values(OrderingType::AMD,
OrderingType::NATURAL),
::testing::Values(true, false)),
ParamInfoToString);
INSTANTIATE_TEST_SUITE_P(
EigenSparseCholeskySingle,
SparseCholeskyTest,
::testing::Combine(::testing::Values(EIGEN_SPARSE),
::testing::Values(OrderingType::AMD,
OrderingType::NATURAL),
::testing::Values(true, false)),
ParamInfoToString);
#endif // CERES_USE_EIGEN_SPARSE
#if defined(CERES_USE_EIGEN_SPARSE) && !defined(CERES_NO_EIGEN_METIS)
INSTANTIATE_TEST_SUITE_P(
EigenSparseCholeskyMETIS,
SparseCholeskyTest,
::testing::Combine(::testing::Values(EIGEN_SPARSE),
::testing::Values(OrderingType::NESDIS),
::testing::Values(true, false)),
ParamInfoToString);
INSTANTIATE_TEST_SUITE_P(
EigenSparseCholeskySingleMETIS,
SparseCholeskyTest,
::testing::Combine(::testing::Values(EIGEN_SPARSE),
::testing::Values(OrderingType::NESDIS),
::testing::Values(true, false)),
ParamInfoToString);
#endif // defined(CERES_USE_EIGEN_SPARSE) && !defined(CERES_NO_EIGEN_METIS)
2017-04-12 12:48:44 -07:00
2018-04-09 16:21:18 -07:00
class MockSparseCholesky : public SparseCholesky {
public:
MOCK_CONST_METHOD0(StorageType, CompressedRowSparseMatrix::StorageType());
MOCK_METHOD2(Factorize,
LinearSolverTerminationType(CompressedRowSparseMatrix* lhs,
std::string* message));
MOCK_METHOD3(Solve,
LinearSolverTerminationType(const double* rhs,
double* solution,
std::string* message));
};
class MockSparseIterativeRefiner : public SparseIterativeRefiner {
2018-04-09 16:21:18 -07:00
public:
MockSparseIterativeRefiner() : SparseIterativeRefiner(1) {}
2018-04-09 16:21:18 -07:00
MOCK_METHOD4(Refine,
2019-03-02 22:42:20 -08:00
void(const SparseMatrix& lhs,
const double* rhs,
SparseCholesky* sparse_cholesky,
double* solution));
2018-04-09 16:21:18 -07:00
};
using testing::_;
using testing::Return;
TEST(RefinedSparseCholesky, StorageType) {
2022-11-13 18:38:34 +01:00
auto sparse_cholesky = std::make_unique<MockSparseCholesky>();
auto iterative_refiner = std::make_unique<MockSparseIterativeRefiner>();
EXPECT_CALL(*sparse_cholesky, StorageType())
2018-04-09 16:21:18 -07:00
.Times(1)
2022-05-14 14:14:22 -07:00
.WillRepeatedly(
Return(CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR));
2022-11-13 18:38:34 +01:00
EXPECT_CALL(*iterative_refiner, Refine(_, _, _, _)).Times(0);
2018-04-09 16:21:18 -07:00
RefinedSparseCholesky refined_sparse_cholesky(std::move(sparse_cholesky),
std::move(iterative_refiner));
EXPECT_EQ(refined_sparse_cholesky.StorageType(),
2022-05-14 14:14:22 -07:00
CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR);
2018-04-09 16:21:18 -07:00
};
TEST(RefinedSparseCholesky, Factorize) {
2022-02-20 02:22:17 +01:00
auto* mock_sparse_cholesky = new MockSparseCholesky;
auto* mock_iterative_refiner = new MockSparseIterativeRefiner;
2018-04-09 16:21:18 -07:00
EXPECT_CALL(*mock_sparse_cholesky, Factorize(_, _))
.Times(1)
2022-05-14 14:14:22 -07:00
.WillRepeatedly(Return(LinearSolverTerminationType::SUCCESS));
2019-03-02 22:42:20 -08:00
EXPECT_CALL(*mock_iterative_refiner, Refine(_, _, _, _)).Times(0);
2018-04-09 16:21:18 -07:00
std::unique_ptr<SparseCholesky> sparse_cholesky(mock_sparse_cholesky);
std::unique_ptr<SparseIterativeRefiner> iterative_refiner(
mock_iterative_refiner);
2018-04-09 16:21:18 -07:00
RefinedSparseCholesky refined_sparse_cholesky(std::move(sparse_cholesky),
std::move(iterative_refiner));
CompressedRowSparseMatrix m(1, 1, 1);
std::string message;
EXPECT_EQ(refined_sparse_cholesky.Factorize(&m, &message),
2022-05-14 14:14:22 -07:00
LinearSolverTerminationType::SUCCESS);
2018-04-09 16:21:18 -07:00
};
TEST(RefinedSparseCholesky, FactorAndSolveWithUnsuccessfulFactorization) {
2022-02-20 02:22:17 +01:00
auto* mock_sparse_cholesky = new MockSparseCholesky;
auto* mock_iterative_refiner = new MockSparseIterativeRefiner;
2018-04-09 16:21:18 -07:00
EXPECT_CALL(*mock_sparse_cholesky, Factorize(_, _))
.Times(1)
2022-05-14 14:14:22 -07:00
.WillRepeatedly(Return(LinearSolverTerminationType::FAILURE));
2019-03-02 22:42:20 -08:00
EXPECT_CALL(*mock_sparse_cholesky, Solve(_, _, _)).Times(0);
EXPECT_CALL(*mock_iterative_refiner, Refine(_, _, _, _)).Times(0);
2018-04-09 16:21:18 -07:00
std::unique_ptr<SparseCholesky> sparse_cholesky(mock_sparse_cholesky);
std::unique_ptr<SparseIterativeRefiner> iterative_refiner(
mock_iterative_refiner);
2018-04-09 16:21:18 -07:00
RefinedSparseCholesky refined_sparse_cholesky(std::move(sparse_cholesky),
std::move(iterative_refiner));
CompressedRowSparseMatrix m(1, 1, 1);
std::string message;
double rhs;
double solution;
2019-03-02 22:42:20 -08:00
EXPECT_EQ(
refined_sparse_cholesky.FactorAndSolve(&m, &rhs, &solution, &message),
2022-05-14 14:14:22 -07:00
LinearSolverTerminationType::FAILURE);
2018-04-09 16:21:18 -07:00
};
TEST(RefinedSparseCholesky, FactorAndSolveWithSuccess) {
2022-02-20 02:22:17 +01:00
auto* mock_sparse_cholesky = new MockSparseCholesky;
std::unique_ptr<MockSparseIterativeRefiner> mock_iterative_refiner(
new MockSparseIterativeRefiner);
2018-04-09 16:21:18 -07:00
EXPECT_CALL(*mock_sparse_cholesky, Factorize(_, _))
.Times(1)
2022-05-14 14:14:22 -07:00
.WillRepeatedly(Return(LinearSolverTerminationType::SUCCESS));
2018-04-09 16:21:18 -07:00
EXPECT_CALL(*mock_sparse_cholesky, Solve(_, _, _))
.Times(1)
2022-05-14 14:14:22 -07:00
.WillRepeatedly(Return(LinearSolverTerminationType::SUCCESS));
2019-03-02 22:42:20 -08:00
EXPECT_CALL(*mock_iterative_refiner, Refine(_, _, _, _)).Times(1);
2018-04-09 16:21:18 -07:00
std::unique_ptr<SparseCholesky> sparse_cholesky(mock_sparse_cholesky);
std::unique_ptr<SparseIterativeRefiner> iterative_refiner(
2019-03-02 22:42:20 -08:00
std::move(mock_iterative_refiner));
2018-04-09 16:21:18 -07:00
RefinedSparseCholesky refined_sparse_cholesky(std::move(sparse_cholesky),
std::move(iterative_refiner));
CompressedRowSparseMatrix m(1, 1, 1);
std::string message;
double rhs;
double solution;
2019-03-02 22:42:20 -08:00
EXPECT_EQ(
refined_sparse_cholesky.FactorAndSolve(&m, &rhs, &solution, &message),
2022-05-14 14:14:22 -07:00
LinearSolverTerminationType::SUCCESS);
2018-04-09 16:21:18 -07:00
};
} // namespace
2022-04-21 17:41:10 -07:00
} // namespace ceres::internal