blob: f5ad1256e80633d2534cf815c66b0ecbb4d42570 [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: keir@google.com (Keir Mierle)
30// sameeragarwal@google.com (Sameer Agarwal)
31
32#include "ceres/residual_block.h"
33
34#include <algorithm>
35#include <cstddef>
36#include <vector>
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080037
Austin Schuh70cc9552019-01-21 19:46:48 -080038#include "ceres/corrector.h"
Austin Schuh70cc9552019-01-21 19:46:48 -080039#include "ceres/cost_function.h"
40#include "ceres/internal/eigen.h"
41#include "ceres/internal/fixed_array.h"
Austin Schuh70cc9552019-01-21 19:46:48 -080042#include "ceres/loss_function.h"
Austin Schuh3de38b02024-06-25 18:25:10 -070043#include "ceres/manifold.h"
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080044#include "ceres/parameter_block.h"
45#include "ceres/residual_block_utils.h"
Austin Schuh70cc9552019-01-21 19:46:48 -080046#include "ceres/small_blas.h"
47
48using Eigen::Dynamic;
49
Austin Schuh3de38b02024-06-25 18:25:10 -070050namespace ceres::internal {
Austin Schuh70cc9552019-01-21 19:46:48 -080051
52ResidualBlock::ResidualBlock(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080053 const CostFunction* cost_function,
54 const LossFunction* loss_function,
55 const std::vector<ParameterBlock*>& parameter_blocks,
56 int index)
Austin Schuh70cc9552019-01-21 19:46:48 -080057 : cost_function_(cost_function),
58 loss_function_(loss_function),
59 parameter_blocks_(
60 new ParameterBlock*[cost_function->parameter_block_sizes().size()]),
61 index_(index) {
62 CHECK(cost_function_ != nullptr);
63 std::copy(parameter_blocks.begin(),
64 parameter_blocks.end(),
65 parameter_blocks_.get());
66}
67
68bool ResidualBlock::Evaluate(const bool apply_loss_function,
69 double* cost,
70 double* residuals,
71 double** jacobians,
72 double* scratch) const {
73 const int num_parameter_blocks = NumParameterBlocks();
74 const int num_residuals = cost_function_->num_residuals();
75
76 // Collect the parameters from their blocks. This will rarely allocate, since
77 // residuals taking more than 8 parameter block arguments are rare.
78 FixedArray<const double*, 8> parameters(num_parameter_blocks);
79 for (int i = 0; i < num_parameter_blocks; ++i) {
80 parameters[i] = parameter_blocks_[i]->state();
81 }
82
83 // Put pointers into the scratch space into global_jacobians as appropriate.
84 FixedArray<double*, 8> global_jacobians(num_parameter_blocks);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080085 if (jacobians != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080086 for (int i = 0; i < num_parameter_blocks; ++i) {
87 const ParameterBlock* parameter_block = parameter_blocks_[i];
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080088 if (jacobians[i] != nullptr &&
Austin Schuh3de38b02024-06-25 18:25:10 -070089 parameter_block->PlusJacobian() != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080090 global_jacobians[i] = scratch;
91 scratch += num_residuals * parameter_block->Size();
92 } else {
93 global_jacobians[i] = jacobians[i];
94 }
95 }
96 }
97
98 // If the caller didn't request residuals, use the scratch space for them.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080099 bool outputting_residuals = (residuals != nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -0800100 if (!outputting_residuals) {
101 residuals = scratch;
102 }
103
104 // Invalidate the evaluation buffers so that we can check them after
105 // the CostFunction::Evaluate call, to see if all the return values
106 // that were required were written to and that they are finite.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800107 double** eval_jacobians =
108 (jacobians != nullptr) ? global_jacobians.data() : nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -0800109
110 InvalidateEvaluation(*this, cost, residuals, eval_jacobians);
111
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800112 if (!cost_function_->Evaluate(parameters.data(), residuals, eval_jacobians)) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800113 return false;
114 }
115
Austin Schuh3de38b02024-06-25 18:25:10 -0700116 if (!IsEvaluationValid(*this, parameters.data(), residuals, eval_jacobians)) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800117 // clang-format off
Austin Schuh70cc9552019-01-21 19:46:48 -0800118 std::string message =
119 "\n\n"
120 "Error in evaluating the ResidualBlock.\n\n"
121 "There are two possible reasons. Either the CostFunction did not evaluate and fill all \n" // NOLINT
122 "residual and jacobians that were requested or there was a non-finite value (nan/infinite)\n" // NOLINT
123 "generated during the or jacobian computation. \n\n" +
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800124 EvaluationToString(
125 *this, parameters.data(), cost, residuals, eval_jacobians);
126 // clang-format on
Austin Schuh70cc9552019-01-21 19:46:48 -0800127 LOG(WARNING) << message;
128 return false;
129 }
130
131 double squared_norm = VectorRef(residuals, num_residuals).squaredNorm();
132
Austin Schuh3de38b02024-06-25 18:25:10 -0700133 // Update the plus_jacobian for the manifolds.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800134 if (jacobians != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800135 for (int i = 0; i < num_parameter_blocks; ++i) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800136 if (jacobians[i] != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800137 const ParameterBlock* parameter_block = parameter_blocks_[i];
138
Austin Schuh3de38b02024-06-25 18:25:10 -0700139 // Apply the Manifold::PlusJacobian to the ambient jacobians.
140 if (parameter_block->PlusJacobian() != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800141 // jacobians[i] = global_jacobians[i] * global_to_local_jacobian.
142 MatrixMatrixMultiply<Dynamic, Dynamic, Dynamic, Dynamic, 0>(
143 global_jacobians[i],
144 num_residuals,
145 parameter_block->Size(),
Austin Schuh3de38b02024-06-25 18:25:10 -0700146 parameter_block->PlusJacobian(),
Austin Schuh70cc9552019-01-21 19:46:48 -0800147 parameter_block->Size(),
Austin Schuh3de38b02024-06-25 18:25:10 -0700148 parameter_block->TangentSize(),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800149 jacobians[i],
150 0,
151 0,
152 num_residuals,
Austin Schuh3de38b02024-06-25 18:25:10 -0700153 parameter_block->TangentSize());
Austin Schuh70cc9552019-01-21 19:46:48 -0800154 }
155 }
156 }
157 }
158
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800159 if (loss_function_ == nullptr || !apply_loss_function) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800160 *cost = 0.5 * squared_norm;
161 return true;
162 }
163
164 double rho[3];
165 loss_function_->Evaluate(squared_norm, rho);
166 *cost = 0.5 * rho[0];
167
168 // No jacobians and not outputting residuals? All done. Doing an early exit
169 // here avoids constructing the "Corrector" object below in a common case.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800170 if (jacobians == nullptr && !outputting_residuals) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800171 return true;
172 }
173
174 // Correct for the effects of the loss function. The jacobians need to be
175 // corrected before the residuals, since they use the uncorrected residuals.
176 Corrector correct(squared_norm, rho);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800177 if (jacobians != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800178 for (int i = 0; i < num_parameter_blocks; ++i) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800179 if (jacobians[i] != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800180 const ParameterBlock* parameter_block = parameter_blocks_[i];
181
182 // Correct the jacobians for the loss function.
183 correct.CorrectJacobian(num_residuals,
Austin Schuh3de38b02024-06-25 18:25:10 -0700184 parameter_block->TangentSize(),
Austin Schuh70cc9552019-01-21 19:46:48 -0800185 residuals,
186 jacobians[i]);
187 }
188 }
189 }
190
191 // Correct the residuals with the loss function.
192 if (outputting_residuals) {
193 correct.CorrectResiduals(num_residuals, residuals);
194 }
195 return true;
196}
197
198int ResidualBlock::NumScratchDoublesForEvaluate() const {
199 // Compute the amount of scratch space needed to store the full-sized
Austin Schuh3de38b02024-06-25 18:25:10 -0700200 // jacobians. For parameters that have no manifold no storage is needed and
201 // the passed-in jacobian array is used directly. Also include space to store
202 // the residuals, which is needed for cost-only evaluations. This is slightly
203 // pessimistic, since both won't be needed all the time, but the amount of
204 // excess should not cause problems for the caller.
Austin Schuh70cc9552019-01-21 19:46:48 -0800205 int num_parameters = NumParameterBlocks();
206 int scratch_doubles = 1;
207 for (int i = 0; i < num_parameters; ++i) {
208 const ParameterBlock* parameter_block = parameter_blocks_[i];
Austin Schuh3de38b02024-06-25 18:25:10 -0700209 if (parameter_block->PlusJacobian() != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800210 scratch_doubles += parameter_block->Size();
211 }
212 }
213 scratch_doubles *= NumResiduals();
214 return scratch_doubles;
215}
216
Austin Schuh3de38b02024-06-25 18:25:10 -0700217} // namespace ceres::internal