blob: 35519fcdcb4265a88deefe16df9a8c73249f1c5f [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
31#include "ceres/implicit_schur_complement.h"
32
33#include <cstddef>
34#include <memory>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080035
Austin Schuh70cc9552019-01-21 19:46:48 -080036#include "Eigen/Dense"
37#include "ceres/block_random_access_dense_matrix.h"
38#include "ceres/block_sparse_matrix.h"
39#include "ceres/casts.h"
40#include "ceres/context_impl.h"
41#include "ceres/internal/eigen.h"
42#include "ceres/linear_least_squares_problems.h"
43#include "ceres/linear_solver.h"
44#include "ceres/schur_eliminator.h"
45#include "ceres/triplet_sparse_matrix.h"
46#include "ceres/types.h"
47#include "glog/logging.h"
48#include "gtest/gtest.h"
49
Austin Schuh3de38b02024-06-25 18:25:10 -070050namespace ceres::internal {
Austin Schuh70cc9552019-01-21 19:46:48 -080051
52using testing::AssertionResult;
53
54const double kEpsilon = 1e-14;
55
56class ImplicitSchurComplementTest : public ::testing::Test {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080057 protected:
58 void SetUp() final {
Austin Schuh3de38b02024-06-25 18:25:10 -070059 auto problem = CreateLinearLeastSquaresProblemFromId(2);
Austin Schuh70cc9552019-01-21 19:46:48 -080060
61 CHECK(problem != nullptr);
62 A_.reset(down_cast<BlockSparseMatrix*>(problem->A.release()));
Austin Schuh3de38b02024-06-25 18:25:10 -070063 b_ = std::move(problem->b);
64 D_ = std::move(problem->D);
Austin Schuh70cc9552019-01-21 19:46:48 -080065
66 num_cols_ = A_->num_cols();
67 num_rows_ = A_->num_rows();
68 num_eliminate_blocks_ = problem->num_eliminate_blocks;
69 }
70
71 void ReducedLinearSystemAndSolution(double* D,
72 Matrix* lhs,
73 Vector* rhs,
74 Vector* solution) {
75 const CompressedRowBlockStructure* bs = A_->block_structure();
76 const int num_col_blocks = bs->cols.size();
Austin Schuh3de38b02024-06-25 18:25:10 -070077 auto blocks = Tail(bs->cols, num_col_blocks - num_eliminate_blocks_);
78 BlockRandomAccessDenseMatrix blhs(blocks, &context_, 1);
Austin Schuh70cc9552019-01-21 19:46:48 -080079 const int num_schur_rows = blhs.num_rows();
80
81 LinearSolver::Options options;
82 options.elimination_groups.push_back(num_eliminate_blocks_);
83 options.type = DENSE_SCHUR;
84 ContextImpl context;
85 options.context = &context;
86
Austin Schuh3de38b02024-06-25 18:25:10 -070087 std::unique_ptr<SchurEliminatorBase> eliminator =
88 SchurEliminatorBase::Create(options);
Austin Schuh70cc9552019-01-21 19:46:48 -080089 CHECK(eliminator != nullptr);
90 const bool kFullRankETE = true;
91 eliminator->Init(num_eliminate_blocks_, kFullRankETE, bs);
92
93 lhs->resize(num_schur_rows, num_schur_rows);
94 rhs->resize(num_schur_rows);
95
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080096 eliminator->Eliminate(
97 BlockSparseMatrixData(*A_), b_.get(), D, &blhs, rhs->data());
Austin Schuh70cc9552019-01-21 19:46:48 -080098
99 MatrixRef lhs_ref(blhs.mutable_values(), num_schur_rows, num_schur_rows);
100
101 // lhs_ref is an upper triangular matrix. Construct a full version
102 // of lhs_ref in lhs by transposing lhs_ref, choosing the strictly
103 // lower triangular part of the matrix and adding it to lhs_ref.
104 *lhs = lhs_ref;
105 lhs->triangularView<Eigen::StrictlyLower>() =
106 lhs_ref.triangularView<Eigen::StrictlyUpper>().transpose();
107
108 solution->resize(num_cols_);
109 solution->setZero();
110 VectorRef schur_solution(solution->data() + num_cols_ - num_schur_rows,
111 num_schur_rows);
112 schur_solution = lhs->selfadjointView<Eigen::Upper>().llt().solve(*rhs);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800113 eliminator->BackSubstitute(BlockSparseMatrixData(*A_),
114 b_.get(),
115 D,
116 schur_solution.data(),
117 solution->data());
Austin Schuh70cc9552019-01-21 19:46:48 -0800118 }
119
120 AssertionResult TestImplicitSchurComplement(double* D) {
121 Matrix lhs;
122 Vector rhs;
123 Vector reference_solution;
124 ReducedLinearSystemAndSolution(D, &lhs, &rhs, &reference_solution);
125
126 LinearSolver::Options options;
127 options.elimination_groups.push_back(num_eliminate_blocks_);
128 options.preconditioner_type = JACOBI;
129 ContextImpl context;
130 options.context = &context;
131 ImplicitSchurComplement isc(options);
132 isc.Init(*A_, D, b_.get());
133
Austin Schuh3de38b02024-06-25 18:25:10 -0700134 const int num_f_cols = lhs.cols();
135 const int num_e_cols = num_cols_ - num_f_cols;
Austin Schuh70cc9552019-01-21 19:46:48 -0800136
Austin Schuh3de38b02024-06-25 18:25:10 -0700137 Matrix A_dense, E, F, DE, DF;
138 A_->ToDenseMatrix(&A_dense);
139 E = A_dense.leftCols(A_->num_cols() - num_f_cols);
140 F = A_dense.rightCols(num_f_cols);
141 if (D) {
142 DE = VectorRef(D, num_e_cols).asDiagonal();
143 DF = VectorRef(D + num_e_cols, num_f_cols).asDiagonal();
144 } else {
145 DE = Matrix::Zero(num_e_cols, num_e_cols);
146 DF = Matrix::Zero(num_f_cols, num_f_cols);
147 }
148
149 // Z = (block_diagonal(F'F))^-1 F'E (E'E)^-1 E'F
150 // Here, assuming that block_diagonal(F'F) == diagonal(F'F)
151 Matrix Z_reference =
152 (F.transpose() * F + DF).diagonal().asDiagonal().inverse() *
153 F.transpose() * E * (E.transpose() * E + DE).inverse() * E.transpose() *
154 F;
155
156 for (int i = 0; i < num_f_cols; ++i) {
157 Vector x(num_f_cols);
Austin Schuh70cc9552019-01-21 19:46:48 -0800158 x.setZero();
159 x(i) = 1.0;
160
Austin Schuh3de38b02024-06-25 18:25:10 -0700161 Vector y(num_f_cols);
Austin Schuh70cc9552019-01-21 19:46:48 -0800162 y = lhs * x;
163
Austin Schuh3de38b02024-06-25 18:25:10 -0700164 Vector z(num_f_cols);
165 isc.RightMultiplyAndAccumulate(x.data(), z.data());
Austin Schuh70cc9552019-01-21 19:46:48 -0800166
167 // The i^th column of the implicit schur complement is the same as
168 // the explicit schur complement.
169 if ((y - z).norm() > kEpsilon) {
170 return testing::AssertionFailure()
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800171 << "Explicit and Implicit SchurComplements differ in "
172 << "column " << i << ". explicit: " << y.transpose()
173 << " implicit: " << z.transpose();
Austin Schuh70cc9552019-01-21 19:46:48 -0800174 }
Austin Schuh3de38b02024-06-25 18:25:10 -0700175
176 y.setZero();
177 y = Z_reference * x;
178 z.setZero();
179 isc.InversePowerSeriesOperatorRightMultiplyAccumulate(x.data(), z.data());
180
181 // The i^th column of operator Z stored implicitly is the same as its
182 // explicit version.
183 if ((y - z).norm() > kEpsilon) {
184 return testing::AssertionFailure()
185 << "Explicit and Implicit operators used to approximate the "
186 "inversion of schur complement via power series expansion "
187 "differ in column "
188 << i << ". explicit: " << y.transpose()
189 << " implicit: " << z.transpose();
190 }
Austin Schuh70cc9552019-01-21 19:46:48 -0800191 }
192
193 // Compare the rhs of the reduced linear system
194 if ((isc.rhs() - rhs).norm() > kEpsilon) {
195 return testing::AssertionFailure()
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800196 << "Explicit and Implicit SchurComplements differ in "
197 << "rhs. explicit: " << rhs.transpose()
198 << " implicit: " << isc.rhs().transpose();
Austin Schuh70cc9552019-01-21 19:46:48 -0800199 }
200
201 // Reference solution to the f_block.
202 const Vector reference_f_sol =
203 lhs.selfadjointView<Eigen::Upper>().llt().solve(rhs);
204
205 // Backsubstituted solution from the implicit schur solver using the
206 // reference solution to the f_block.
207 Vector sol(num_cols_);
208 isc.BackSubstitute(reference_f_sol.data(), sol.data());
209 if ((sol - reference_solution).norm() > kEpsilon) {
210 return testing::AssertionFailure()
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800211 << "Explicit and Implicit SchurComplements solutions differ. "
212 << "explicit: " << reference_solution.transpose()
213 << " implicit: " << sol.transpose();
Austin Schuh70cc9552019-01-21 19:46:48 -0800214 }
215
216 return testing::AssertionSuccess();
217 }
218
Austin Schuh3de38b02024-06-25 18:25:10 -0700219 ContextImpl context_;
Austin Schuh70cc9552019-01-21 19:46:48 -0800220 int num_rows_;
221 int num_cols_;
222 int num_eliminate_blocks_;
223
224 std::unique_ptr<BlockSparseMatrix> A_;
225 std::unique_ptr<double[]> b_;
226 std::unique_ptr<double[]> D_;
227};
228
229// Verify that the Schur Complement matrix implied by the
230// ImplicitSchurComplement class matches the one explicitly computed
231// by the SchurComplement solver.
232//
233// We do this with and without regularization to check that the
234// support for the LM diagonal is correct.
235TEST_F(ImplicitSchurComplementTest, SchurMatrixValuesTest) {
Austin Schuh3de38b02024-06-25 18:25:10 -0700236 EXPECT_TRUE(TestImplicitSchurComplement(nullptr));
Austin Schuh70cc9552019-01-21 19:46:48 -0800237 EXPECT_TRUE(TestImplicitSchurComplement(D_.get()));
238}
239
Austin Schuh3de38b02024-06-25 18:25:10 -0700240} // namespace ceres::internal