blob: b73274ca4074e22128ad8de8dbc41afd741c62e8 [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Ceres Solver - A fast non-linear least squares minimizer
Austin Schuh3de38b02024-06-25 18:25:10 -07002// Copyright 2023 Google Inc. All rights reserved.
Austin Schuh70cc9552019-01-21 19:46:48 -08003// 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
Austin Schuh70cc9552019-01-21 19:46:48 -080031#include "ceres/subset_preconditioner.h"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080032
33#include <memory>
Austin Schuh3de38b02024-06-25 18:25:10 -070034#include <random>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080035
Austin Schuh70cc9552019-01-21 19:46:48 -080036#include "Eigen/Dense"
37#include "Eigen/SparseCore"
38#include "ceres/block_sparse_matrix.h"
39#include "ceres/compressed_row_sparse_matrix.h"
40#include "ceres/inner_product_computer.h"
Austin Schuh3de38b02024-06-25 18:25:10 -070041#include "ceres/internal/config.h"
Austin Schuh70cc9552019-01-21 19:46:48 -080042#include "ceres/internal/eigen.h"
43#include "glog/logging.h"
44#include "gtest/gtest.h"
45
Austin Schuh3de38b02024-06-25 18:25:10 -070046namespace ceres::internal {
Austin Schuh70cc9552019-01-21 19:46:48 -080047
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080048namespace {
49
Austin Schuh70cc9552019-01-21 19:46:48 -080050// TODO(sameeragarwal): Refactor the following two functions out of
51// here and sparse_cholesky_test.cc into a more suitable place.
52template <int UpLoType>
53bool SolveLinearSystemUsingEigen(const Matrix& lhs,
54 const Vector rhs,
55 Vector* solution) {
56 Eigen::LLT<Matrix, UpLoType> llt = lhs.selfadjointView<UpLoType>().llt();
57 if (llt.info() != Eigen::Success) {
58 return false;
59 }
60 *solution = llt.solve(rhs);
61 return (llt.info() == Eigen::Success);
62}
63
64// Use Eigen's Dense Cholesky solver to compute the solution to a
65// sparse linear system.
66bool ComputeExpectedSolution(const CompressedRowSparseMatrix& lhs,
67 const Vector& rhs,
68 Vector* solution) {
69 Matrix dense_triangular_lhs;
70 lhs.ToDenseMatrix(&dense_triangular_lhs);
Austin Schuh3de38b02024-06-25 18:25:10 -070071 if (lhs.storage_type() ==
72 CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR) {
Austin Schuh70cc9552019-01-21 19:46:48 -080073 Matrix full_lhs = dense_triangular_lhs.selfadjointView<Eigen::Upper>();
74 return SolveLinearSystemUsingEigen<Eigen::Upper>(full_lhs, rhs, solution);
75 }
76 return SolveLinearSystemUsingEigen<Eigen::Lower>(
77 dense_triangular_lhs, rhs, solution);
78}
79
Austin Schuh3de38b02024-06-25 18:25:10 -070080using Param = ::testing::tuple<SparseLinearAlgebraLibraryType, bool>;
Austin Schuh70cc9552019-01-21 19:46:48 -080081
82std::string ParamInfoToString(testing::TestParamInfo<Param> info) {
83 Param param = info.param;
84 std::stringstream ss;
85 ss << SparseLinearAlgebraLibraryTypeToString(::testing::get<0>(param)) << "_"
86 << (::testing::get<1>(param) ? "Diagonal" : "NoDiagonal");
87 return ss.str();
88}
89
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080090} // namespace
91
Austin Schuh70cc9552019-01-21 19:46:48 -080092class SubsetPreconditionerTest : public ::testing::TestWithParam<Param> {
93 protected:
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080094 void SetUp() final {
Austin Schuh70cc9552019-01-21 19:46:48 -080095 BlockSparseMatrix::RandomMatrixOptions options;
96 options.num_col_blocks = 4;
97 options.min_col_block_size = 1;
98 options.max_col_block_size = 4;
99 options.num_row_blocks = 8;
100 options.min_row_block_size = 1;
101 options.max_row_block_size = 4;
102 options.block_density = 0.9;
103
Austin Schuh3de38b02024-06-25 18:25:10 -0700104 m_ = BlockSparseMatrix::CreateRandomMatrix(options, prng_);
Austin Schuh70cc9552019-01-21 19:46:48 -0800105 start_row_block_ = m_->block_structure()->rows.size();
106
107 // Ensure that the bottom part of the matrix has the same column
108 // block structure.
109 options.col_blocks = m_->block_structure()->cols;
Austin Schuh3de38b02024-06-25 18:25:10 -0700110 b_ = BlockSparseMatrix::CreateRandomMatrix(options, prng_);
Austin Schuh70cc9552019-01-21 19:46:48 -0800111 m_->AppendRows(*b_);
112
113 // Create a Identity block diagonal matrix with the same column
114 // block structure.
115 diagonal_ = Vector::Ones(m_->num_cols());
Austin Schuh3de38b02024-06-25 18:25:10 -0700116 block_diagonal_ = BlockSparseMatrix::CreateDiagonalMatrix(
117 diagonal_.data(), b_->block_structure()->cols);
Austin Schuh70cc9552019-01-21 19:46:48 -0800118
119 // Unconditionally add the block diagonal to the matrix b_,
120 // because either it is either part of b_ to make it full rank, or
121 // we pass the same diagonal matrix later as the parameter D. In
122 // either case the preconditioner matrix is b_' b + D'D.
123 b_->AppendRows(*block_diagonal_);
Austin Schuh3de38b02024-06-25 18:25:10 -0700124 inner_product_computer_ = InnerProductComputer::Create(
125 *b_, CompressedRowSparseMatrix::StorageType::UPPER_TRIANGULAR);
Austin Schuh70cc9552019-01-21 19:46:48 -0800126 inner_product_computer_->Compute();
127 }
128
129 std::unique_ptr<BlockSparseMatrix> m_;
130 std::unique_ptr<BlockSparseMatrix> b_;
131 std::unique_ptr<BlockSparseMatrix> block_diagonal_;
132 std::unique_ptr<InnerProductComputer> inner_product_computer_;
133 std::unique_ptr<Preconditioner> preconditioner_;
134 Vector diagonal_;
135 int start_row_block_;
Austin Schuh3de38b02024-06-25 18:25:10 -0700136 std::mt19937 prng_;
Austin Schuh70cc9552019-01-21 19:46:48 -0800137};
138
139TEST_P(SubsetPreconditionerTest, foo) {
140 Param param = GetParam();
141 Preconditioner::Options options;
142 options.subset_preconditioner_start_row_block = start_row_block_;
143 options.sparse_linear_algebra_library_type = ::testing::get<0>(param);
Austin Schuh3de38b02024-06-25 18:25:10 -0700144 preconditioner_ = std::make_unique<SubsetPreconditioner>(options, *m_);
Austin Schuh70cc9552019-01-21 19:46:48 -0800145
146 const bool with_diagonal = ::testing::get<1>(param);
147 if (!with_diagonal) {
148 m_->AppendRows(*block_diagonal_);
149 }
150
151 EXPECT_TRUE(
Austin Schuh3de38b02024-06-25 18:25:10 -0700152 preconditioner_->Update(*m_, with_diagonal ? diagonal_.data() : nullptr));
Austin Schuh70cc9552019-01-21 19:46:48 -0800153
154 // Repeatedly apply the preconditioner to random vectors and check
155 // that the preconditioned value is the same as one obtained by
156 // solving the linear system directly.
157 for (int i = 0; i < 5; ++i) {
158 CompressedRowSparseMatrix* lhs = inner_product_computer_->mutable_result();
159 Vector rhs = Vector::Random(lhs->num_rows());
160 Vector expected(lhs->num_rows());
161 EXPECT_TRUE(ComputeExpectedSolution(*lhs, rhs, &expected));
162
163 Vector actual(lhs->num_rows());
Austin Schuh3de38b02024-06-25 18:25:10 -0700164 preconditioner_->RightMultiplyAndAccumulate(rhs.data(), actual.data());
Austin Schuh70cc9552019-01-21 19:46:48 -0800165
166 Matrix eigen_lhs;
167 lhs->ToDenseMatrix(&eigen_lhs);
168 EXPECT_NEAR((actual - expected).norm() / actual.norm(),
169 0.0,
170 std::numeric_limits<double>::epsilon() * 10)
171 << "\n"
172 << eigen_lhs << "\n"
173 << expected.transpose() << "\n"
174 << actual.transpose();
175 }
176}
177
178#ifndef CERES_NO_SUITESPARSE
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800179INSTANTIATE_TEST_SUITE_P(SubsetPreconditionerWithSuiteSparse,
180 SubsetPreconditionerTest,
181 ::testing::Combine(::testing::Values(SUITE_SPARSE),
182 ::testing::Values(true, false)),
183 ParamInfoToString);
Austin Schuh70cc9552019-01-21 19:46:48 -0800184#endif
185
Austin Schuh70cc9552019-01-21 19:46:48 -0800186#ifndef CERES_NO_ACCELERATE_SPARSE
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800187INSTANTIATE_TEST_SUITE_P(
188 SubsetPreconditionerWithAccelerateSparse,
189 SubsetPreconditionerTest,
190 ::testing::Combine(::testing::Values(ACCELERATE_SPARSE),
191 ::testing::Values(true, false)),
192 ParamInfoToString);
Austin Schuh70cc9552019-01-21 19:46:48 -0800193#endif
194
195#ifdef CERES_USE_EIGEN_SPARSE
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800196INSTANTIATE_TEST_SUITE_P(SubsetPreconditionerWithEigenSparse,
197 SubsetPreconditionerTest,
198 ::testing::Combine(::testing::Values(EIGEN_SPARSE),
199 ::testing::Values(true, false)),
200 ParamInfoToString);
Austin Schuh70cc9552019-01-21 19:46:48 -0800201#endif
202
Austin Schuh3de38b02024-06-25 18:25:10 -0700203} // namespace ceres::internal