blob: 1d5338f4b66ea182e03a10da80553c6032c9033b [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// Abstract interface for objects solving linear systems of various
32// kinds.
33
34#ifndef CERES_INTERNAL_LINEAR_SOLVER_H_
35#define CERES_INTERNAL_LINEAR_SOLVER_H_
36
37#include <cstddef>
38#include <map>
Austin Schuh3de38b02024-06-25 18:25:10 -070039#include <memory>
Austin Schuh70cc9552019-01-21 19:46:48 -080040#include <string>
41#include <vector>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080042
Austin Schuh70cc9552019-01-21 19:46:48 -080043#include "ceres/block_sparse_matrix.h"
44#include "ceres/casts.h"
45#include "ceres/compressed_row_sparse_matrix.h"
46#include "ceres/context_impl.h"
47#include "ceres/dense_sparse_matrix.h"
48#include "ceres/execution_summary.h"
Austin Schuh3de38b02024-06-25 18:25:10 -070049#include "ceres/internal/disable_warnings.h"
50#include "ceres/internal/export.h"
Austin Schuh70cc9552019-01-21 19:46:48 -080051#include "ceres/triplet_sparse_matrix.h"
52#include "ceres/types.h"
53#include "glog/logging.h"
54
Austin Schuh3de38b02024-06-25 18:25:10 -070055namespace ceres::internal {
Austin Schuh70cc9552019-01-21 19:46:48 -080056
Austin Schuh3de38b02024-06-25 18:25:10 -070057enum class LinearSolverTerminationType {
Austin Schuh70cc9552019-01-21 19:46:48 -080058 // Termination criterion was met.
Austin Schuh3de38b02024-06-25 18:25:10 -070059 SUCCESS,
Austin Schuh70cc9552019-01-21 19:46:48 -080060
61 // Solver ran for max_num_iterations and terminated before the
62 // termination tolerance could be satisfied.
Austin Schuh3de38b02024-06-25 18:25:10 -070063 NO_CONVERGENCE,
Austin Schuh70cc9552019-01-21 19:46:48 -080064
65 // Solver was terminated due to numerical problems, generally due to
66 // the linear system being poorly conditioned.
Austin Schuh3de38b02024-06-25 18:25:10 -070067 FAILURE,
Austin Schuh70cc9552019-01-21 19:46:48 -080068
69 // Solver failed with a fatal error that cannot be recovered from,
70 // e.g. CHOLMOD ran out of memory when computing the symbolic or
71 // numeric factorization or an underlying library was called with
72 // the wrong arguments.
Austin Schuh3de38b02024-06-25 18:25:10 -070073 FATAL_ERROR
Austin Schuh70cc9552019-01-21 19:46:48 -080074};
75
Austin Schuh3de38b02024-06-25 18:25:10 -070076inline std::ostream& operator<<(std::ostream& s,
77 LinearSolverTerminationType type) {
78 switch (type) {
79 case LinearSolverTerminationType::SUCCESS:
80 s << "LINEAR_SOLVER_SUCCESS";
81 break;
82 case LinearSolverTerminationType::NO_CONVERGENCE:
83 s << "LINEAR_SOLVER_NO_CONVERGENCE";
84 break;
85 case LinearSolverTerminationType::FAILURE:
86 s << "LINEAR_SOLVER_FAILURE";
87 break;
88 case LinearSolverTerminationType::FATAL_ERROR:
89 s << "LINEAR_SOLVER_FATAL_ERROR";
90 break;
91 default:
92 s << "UNKNOWN LinearSolverTerminationType";
93 }
94 return s;
95}
96
Austin Schuh70cc9552019-01-21 19:46:48 -080097// This enum controls the fill-reducing ordering a sparse linear
98// algebra library should use before computing a sparse factorization
99// (usually Cholesky).
Austin Schuh3de38b02024-06-25 18:25:10 -0700100//
101// TODO(sameeragarwal): Add support for nested dissection
102enum class OrderingType {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800103 NATURAL, // Do not re-order the matrix. This is useful when the
104 // matrix has been ordered using a fill-reducing ordering
105 // already.
Austin Schuh3de38b02024-06-25 18:25:10 -0700106
107 AMD, // Use the Approximate Minimum Degree algorithm to re-order
108 // the matrix.
109
110 NESDIS, // Use the Nested Dissection algorithm to re-order the matrix.
Austin Schuh70cc9552019-01-21 19:46:48 -0800111};
112
Austin Schuh3de38b02024-06-25 18:25:10 -0700113inline std::ostream& operator<<(std::ostream& s, OrderingType type) {
114 switch (type) {
115 case OrderingType::NATURAL:
116 s << "NATURAL";
117 break;
118 case OrderingType::AMD:
119 s << "AMD";
120 break;
121 case OrderingType::NESDIS:
122 s << "NESDIS";
123 break;
124 default:
125 s << "UNKNOWN OrderingType";
126 }
127 return s;
128}
129
Austin Schuh70cc9552019-01-21 19:46:48 -0800130class LinearOperator;
131
132// Abstract base class for objects that implement algorithms for
133// solving linear systems
134//
135// Ax = b
136//
137// It is expected that a single instance of a LinearSolver object
138// maybe used multiple times for solving multiple linear systems with
139// the same sparsity structure. This allows them to cache and reuse
140// information across solves. This means that calling Solve on the
141// same LinearSolver instance with two different linear systems will
142// result in undefined behaviour.
143//
144// Subclasses of LinearSolver use two structs to configure themselves.
145// The Options struct configures the LinearSolver object for its
146// lifetime. The PerSolveOptions struct is used to specify options for
147// a particular Solve call.
Austin Schuh3de38b02024-06-25 18:25:10 -0700148class CERES_NO_EXPORT LinearSolver {
Austin Schuh70cc9552019-01-21 19:46:48 -0800149 public:
150 struct Options {
151 LinearSolverType type = SPARSE_NORMAL_CHOLESKY;
152 PreconditionerType preconditioner_type = JACOBI;
153 VisibilityClusteringType visibility_clustering_type = CANONICAL_VIEWS;
154 DenseLinearAlgebraLibraryType dense_linear_algebra_library_type = EIGEN;
155 SparseLinearAlgebraLibraryType sparse_linear_algebra_library_type =
156 SUITE_SPARSE;
Austin Schuh3de38b02024-06-25 18:25:10 -0700157 OrderingType ordering_type = OrderingType::NATURAL;
Austin Schuh70cc9552019-01-21 19:46:48 -0800158
159 // See solver.h for information about these flags.
Austin Schuh70cc9552019-01-21 19:46:48 -0800160 bool dynamic_sparsity = false;
161 bool use_explicit_schur_complement = false;
162
163 // Number of internal iterations that the solver uses. This
164 // parameter only makes sense for iterative solvers like CG.
165 int min_num_iterations = 1;
166 int max_num_iterations = 1;
167
Austin Schuh3de38b02024-06-25 18:25:10 -0700168 // Maximum number of iterations performed by SCHUR_POWER_SERIES_EXPANSION.
169 // This value controls the maximum number of iterations whether it is used
170 // as a preconditioner or just to initialize the solution for
171 // ITERATIVE_SCHUR.
172 int max_num_spse_iterations = 5;
173
174 // Use SCHUR_POWER_SERIES_EXPANSION to initialize the solution for
175 // ITERATIVE_SCHUR. This option can be set true regardless of what
176 // preconditioner is being used.
177 bool use_spse_initialization = false;
178
179 // When use_spse_initialization is true, this parameter along with
180 // max_num_spse_iterations controls the number of
181 // SCHUR_POWER_SERIES_EXPANSION iterations performed for initialization. It
182 // is not used to control the preconditioner.
183 double spse_tolerance = 0.1;
184
Austin Schuh70cc9552019-01-21 19:46:48 -0800185 // If possible, how many threads can the solver use.
186 int num_threads = 1;
187
188 // Hints about the order in which the parameter blocks should be
189 // eliminated by the linear solver.
190 //
191 // For example if elimination_groups is a vector of size k, then
192 // the linear solver is informed that it should eliminate the
193 // parameter blocks 0 ... elimination_groups[0] - 1 first, and
194 // then elimination_groups[0] ... elimination_groups[1] - 1 and so
195 // on. Within each elimination group, the linear solver is free to
196 // choose how the parameter blocks are ordered. Different linear
197 // solvers have differing requirements on elimination_groups.
198 //
199 // The most common use is for Schur type solvers, where there
200 // should be at least two elimination groups and the first
201 // elimination group must form an independent set in the normal
202 // equations. The first elimination group corresponds to the
203 // num_eliminate_blocks in the Schur type solvers.
204 std::vector<int> elimination_groups;
205
206 // Iterative solvers, e.g. Preconditioned Conjugate Gradients
207 // maintain a cheap estimate of the residual which may become
208 // inaccurate over time. Thus for non-zero values of this
209 // parameter, the solver can be told to recalculate the value of
210 // the residual using a |b - Ax| evaluation.
211 int residual_reset_period = 10;
212
213 // If the block sizes in a BlockSparseMatrix are fixed, then in
214 // some cases the Schur complement based solvers can detect and
215 // specialize on them.
216 //
217 // It is expected that these parameters are set programmatically
218 // rather than manually.
219 //
220 // Please see schur_complement_solver.h and schur_eliminator.h for
221 // more details.
222 int row_block_size = Eigen::Dynamic;
223 int e_block_size = Eigen::Dynamic;
224 int f_block_size = Eigen::Dynamic;
225
226 bool use_mixed_precision_solves = false;
227 int max_num_refinement_iterations = 0;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800228 int subset_preconditioner_start_row_block = -1;
Austin Schuh70cc9552019-01-21 19:46:48 -0800229 ContextImpl* context = nullptr;
230 };
231
232 // Options for the Solve method.
233 struct PerSolveOptions {
234 // This option only makes sense for unsymmetric linear solvers
235 // that can solve rectangular linear systems.
236 //
237 // Given a matrix A, an optional diagonal matrix D as a vector,
238 // and a vector b, the linear solver will solve for
239 //
240 // | A | x = | b |
241 // | D | | 0 |
242 //
243 // If D is null, then it is treated as zero, and the solver returns
244 // the solution to
245 //
246 // A x = b
247 //
248 // In either case, x is the vector that solves the following
249 // optimization problem.
250 //
251 // arg min_x ||Ax - b||^2 + ||Dx||^2
252 //
253 // Here A is a matrix of size m x n, with full column rank. If A
254 // does not have full column rank, the results returned by the
255 // solver cannot be relied on. D, if it is not null is an array of
256 // size n. b is an array of size m and x is an array of size n.
257 double* D = nullptr;
258
259 // This option only makes sense for iterative solvers.
260 //
261 // In general the performance of an iterative linear solver
262 // depends on the condition number of the matrix A. For example
263 // the convergence rate of the conjugate gradients algorithm
264 // is proportional to the square root of the condition number.
265 //
266 // One particularly useful technique for improving the
267 // conditioning of a linear system is to precondition it. In its
268 // simplest form a preconditioner is a matrix M such that instead
269 // of solving Ax = b, we solve the linear system AM^{-1} y = b
270 // instead, where M is such that the condition number k(AM^{-1})
271 // is smaller than the conditioner k(A). Given the solution to
272 // this system, x = M^{-1} y. The iterative solver takes care of
273 // the mechanics of solving the preconditioned system and
274 // returning the corrected solution x. The user only needs to
275 // supply a linear operator.
276 //
277 // A null preconditioner is equivalent to an identity matrix being
278 // used a preconditioner.
279 LinearOperator* preconditioner = nullptr;
280
Austin Schuh70cc9552019-01-21 19:46:48 -0800281 // The following tolerance related options only makes sense for
282 // iterative solvers. Direct solvers ignore them.
283
284 // Solver terminates when
285 //
286 // |Ax - b| <= r_tolerance * |b|.
287 //
288 // This is the most commonly used termination criterion for
289 // iterative solvers.
290 double r_tolerance = 0.0;
291
292 // For PSD matrices A, let
293 //
294 // Q(x) = x'Ax - 2b'x
295 //
296 // be the cost of the quadratic function defined by A and b. Then,
297 // the solver terminates at iteration i if
298 //
299 // i * (Q(x_i) - Q(x_i-1)) / Q(x_i) < q_tolerance.
300 //
301 // This termination criterion is more useful when using CG to
302 // solve the Newton step. This particular convergence test comes
303 // from Stephen Nash's work on truncated Newton
304 // methods. References:
305 //
306 // 1. Stephen G. Nash & Ariela Sofer, Assessing A Search
307 // Direction Within A Truncated Newton Method, Operation
308 // Research Letters 9(1990) 219-221.
309 //
310 // 2. Stephen G. Nash, A Survey of Truncated Newton Methods,
311 // Journal of Computational and Applied Mathematics,
312 // 124(1-2), 45-59, 2000.
313 //
314 double q_tolerance = 0.0;
315 };
316
317 // Summary of a call to the Solve method. We should move away from
318 // the true/false method for determining solver success. We should
319 // let the summary object do the talking.
320 struct Summary {
321 double residual_norm = -1.0;
322 int num_iterations = -1;
Austin Schuh3de38b02024-06-25 18:25:10 -0700323 LinearSolverTerminationType termination_type =
324 LinearSolverTerminationType::FAILURE;
Austin Schuh70cc9552019-01-21 19:46:48 -0800325 std::string message;
326 };
327
328 // If the optimization problem is such that there are no remaining
329 // e-blocks, a Schur type linear solver cannot be used. If the
330 // linear solver is of Schur type, this function implements a policy
331 // to select an alternate nearest linear solver to the one selected
332 // by the user. The input linear_solver_type is returned otherwise.
333 static LinearSolverType LinearSolverForZeroEBlocks(
334 LinearSolverType linear_solver_type);
335
336 virtual ~LinearSolver();
337
338 // Solve Ax = b.
339 virtual Summary Solve(LinearOperator* A,
340 const double* b,
341 const PerSolveOptions& per_solve_options,
342 double* x) = 0;
343
344 // This method returns copies instead of references so that the base
345 // class implementation does not have to worry about life time
346 // issues. Further, this calls are not expected to be frequent or
347 // performance sensitive.
348 virtual std::map<std::string, CallStatistics> Statistics() const {
Austin Schuh3de38b02024-06-25 18:25:10 -0700349 return {};
Austin Schuh70cc9552019-01-21 19:46:48 -0800350 }
351
352 // Factory
Austin Schuh3de38b02024-06-25 18:25:10 -0700353 static std::unique_ptr<LinearSolver> Create(const Options& options);
Austin Schuh70cc9552019-01-21 19:46:48 -0800354};
355
356// This templated subclass of LinearSolver serves as a base class for
357// other linear solvers that depend on the particular matrix layout of
358// the underlying linear operator. For example some linear solvers
359// need low level access to the TripletSparseMatrix implementing the
360// LinearOperator interface. This class hides those implementation
361// details behind a private virtual method, and has the Solve method
362// perform the necessary upcasting.
363template <typename MatrixType>
364class TypedLinearSolver : public LinearSolver {
365 public:
Austin Schuh3de38b02024-06-25 18:25:10 -0700366 LinearSolver::Summary Solve(
Austin Schuh70cc9552019-01-21 19:46:48 -0800367 LinearOperator* A,
368 const double* b,
369 const LinearSolver::PerSolveOptions& per_solve_options,
Austin Schuh3de38b02024-06-25 18:25:10 -0700370 double* x) override {
Austin Schuh70cc9552019-01-21 19:46:48 -0800371 ScopedExecutionTimer total_time("LinearSolver::Solve", &execution_summary_);
372 CHECK(A != nullptr);
373 CHECK(b != nullptr);
374 CHECK(x != nullptr);
375 return SolveImpl(down_cast<MatrixType*>(A), b, per_solve_options, x);
376 }
377
Austin Schuh3de38b02024-06-25 18:25:10 -0700378 std::map<std::string, CallStatistics> Statistics() const override {
Austin Schuh70cc9552019-01-21 19:46:48 -0800379 return execution_summary_.statistics();
380 }
381
382 private:
383 virtual LinearSolver::Summary SolveImpl(
384 MatrixType* A,
385 const double* b,
386 const LinearSolver::PerSolveOptions& per_solve_options,
387 double* x) = 0;
388
389 ExecutionSummary execution_summary_;
390};
391
Austin Schuh3de38b02024-06-25 18:25:10 -0700392// Linear solvers that depend on access to the low level structure of
Austin Schuh70cc9552019-01-21 19:46:48 -0800393// a SparseMatrix.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800394// clang-format off
Austin Schuh3de38b02024-06-25 18:25:10 -0700395using BlockSparseMatrixSolver = TypedLinearSolver<BlockSparseMatrix>; // NOLINT
396using CompressedRowSparseMatrixSolver = TypedLinearSolver<CompressedRowSparseMatrix>; // NOLINT
397using DenseSparseMatrixSolver = TypedLinearSolver<DenseSparseMatrix>; // NOLINT
398using TripletSparseMatrixSolver = TypedLinearSolver<TripletSparseMatrix>; // NOLINT
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800399// clang-format on
Austin Schuh70cc9552019-01-21 19:46:48 -0800400
Austin Schuh3de38b02024-06-25 18:25:10 -0700401} // namespace ceres::internal
402
403#include "ceres/internal/reenable_warnings.h"
Austin Schuh70cc9552019-01-21 19:46:48 -0800404
405#endif // CERES_INTERNAL_LINEAR_SOLVER_H_