blob: 067c9efe83d17a770f3c688f5798dfbf0080f0e8 [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Ceres Solver - A fast non-linear least squares minimizer
2// Copyright 2015 Google Inc. All rights reserved.
3// 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"
42#include "ceres/local_parameterization.h"
43#include "ceres/loss_function.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
50namespace ceres {
51namespace internal {
52
53ResidualBlock::ResidualBlock(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080054 const CostFunction* cost_function,
55 const LossFunction* loss_function,
56 const std::vector<ParameterBlock*>& parameter_blocks,
57 int index)
Austin Schuh70cc9552019-01-21 19:46:48 -080058 : cost_function_(cost_function),
59 loss_function_(loss_function),
60 parameter_blocks_(
61 new ParameterBlock*[cost_function->parameter_block_sizes().size()]),
62 index_(index) {
63 CHECK(cost_function_ != nullptr);
64 std::copy(parameter_blocks.begin(),
65 parameter_blocks.end(),
66 parameter_blocks_.get());
67}
68
69bool ResidualBlock::Evaluate(const bool apply_loss_function,
70 double* cost,
71 double* residuals,
72 double** jacobians,
73 double* scratch) const {
74 const int num_parameter_blocks = NumParameterBlocks();
75 const int num_residuals = cost_function_->num_residuals();
76
77 // Collect the parameters from their blocks. This will rarely allocate, since
78 // residuals taking more than 8 parameter block arguments are rare.
79 FixedArray<const double*, 8> parameters(num_parameter_blocks);
80 for (int i = 0; i < num_parameter_blocks; ++i) {
81 parameters[i] = parameter_blocks_[i]->state();
82 }
83
84 // Put pointers into the scratch space into global_jacobians as appropriate.
85 FixedArray<double*, 8> global_jacobians(num_parameter_blocks);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080086 if (jacobians != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080087 for (int i = 0; i < num_parameter_blocks; ++i) {
88 const ParameterBlock* parameter_block = parameter_blocks_[i];
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080089 if (jacobians[i] != nullptr &&
90 parameter_block->LocalParameterizationJacobian() != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -080091 global_jacobians[i] = scratch;
92 scratch += num_residuals * parameter_block->Size();
93 } else {
94 global_jacobians[i] = jacobians[i];
95 }
96 }
97 }
98
99 // If the caller didn't request residuals, use the scratch space for them.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800100 bool outputting_residuals = (residuals != nullptr);
Austin Schuh70cc9552019-01-21 19:46:48 -0800101 if (!outputting_residuals) {
102 residuals = scratch;
103 }
104
105 // Invalidate the evaluation buffers so that we can check them after
106 // the CostFunction::Evaluate call, to see if all the return values
107 // that were required were written to and that they are finite.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800108 double** eval_jacobians =
109 (jacobians != nullptr) ? global_jacobians.data() : nullptr;
Austin Schuh70cc9552019-01-21 19:46:48 -0800110
111 InvalidateEvaluation(*this, cost, residuals, eval_jacobians);
112
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800113 if (!cost_function_->Evaluate(parameters.data(), residuals, eval_jacobians)) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800114 return false;
115 }
116
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800117 if (!IsEvaluationValid(
118 *this, parameters.data(), cost, residuals, eval_jacobians)) {
119 // clang-format off
Austin Schuh70cc9552019-01-21 19:46:48 -0800120 std::string message =
121 "\n\n"
122 "Error in evaluating the ResidualBlock.\n\n"
123 "There are two possible reasons. Either the CostFunction did not evaluate and fill all \n" // NOLINT
124 "residual and jacobians that were requested or there was a non-finite value (nan/infinite)\n" // NOLINT
125 "generated during the or jacobian computation. \n\n" +
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800126 EvaluationToString(
127 *this, parameters.data(), cost, residuals, eval_jacobians);
128 // clang-format on
Austin Schuh70cc9552019-01-21 19:46:48 -0800129 LOG(WARNING) << message;
130 return false;
131 }
132
133 double squared_norm = VectorRef(residuals, num_residuals).squaredNorm();
134
135 // Update the jacobians with the local parameterizations.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800136 if (jacobians != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800137 for (int i = 0; i < num_parameter_blocks; ++i) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800138 if (jacobians[i] != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800139 const ParameterBlock* parameter_block = parameter_blocks_[i];
140
141 // Apply local reparameterization to the jacobians.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800142 if (parameter_block->LocalParameterizationJacobian() != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800143 // jacobians[i] = global_jacobians[i] * global_to_local_jacobian.
144 MatrixMatrixMultiply<Dynamic, Dynamic, Dynamic, Dynamic, 0>(
145 global_jacobians[i],
146 num_residuals,
147 parameter_block->Size(),
148 parameter_block->LocalParameterizationJacobian(),
149 parameter_block->Size(),
150 parameter_block->LocalSize(),
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800151 jacobians[i],
152 0,
153 0,
154 num_residuals,
155 parameter_block->LocalSize());
Austin Schuh70cc9552019-01-21 19:46:48 -0800156 }
157 }
158 }
159 }
160
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800161 if (loss_function_ == nullptr || !apply_loss_function) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800162 *cost = 0.5 * squared_norm;
163 return true;
164 }
165
166 double rho[3];
167 loss_function_->Evaluate(squared_norm, rho);
168 *cost = 0.5 * rho[0];
169
170 // No jacobians and not outputting residuals? All done. Doing an early exit
171 // here avoids constructing the "Corrector" object below in a common case.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800172 if (jacobians == nullptr && !outputting_residuals) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800173 return true;
174 }
175
176 // Correct for the effects of the loss function. The jacobians need to be
177 // corrected before the residuals, since they use the uncorrected residuals.
178 Corrector correct(squared_norm, rho);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800179 if (jacobians != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800180 for (int i = 0; i < num_parameter_blocks; ++i) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800181 if (jacobians[i] != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800182 const ParameterBlock* parameter_block = parameter_blocks_[i];
183
184 // Correct the jacobians for the loss function.
185 correct.CorrectJacobian(num_residuals,
186 parameter_block->LocalSize(),
187 residuals,
188 jacobians[i]);
189 }
190 }
191 }
192
193 // Correct the residuals with the loss function.
194 if (outputting_residuals) {
195 correct.CorrectResiduals(num_residuals, residuals);
196 }
197 return true;
198}
199
200int ResidualBlock::NumScratchDoublesForEvaluate() const {
201 // Compute the amount of scratch space needed to store the full-sized
202 // jacobians. For parameters that have no local parameterization no storage
203 // is needed and the passed-in jacobian array is used directly. Also include
204 // space to store the residuals, which is needed for cost-only evaluations.
205 // This is slightly pessimistic, since both won't be needed all the time, but
206 // the amount of excess should not cause problems for the caller.
207 int num_parameters = NumParameterBlocks();
208 int scratch_doubles = 1;
209 for (int i = 0; i < num_parameters; ++i) {
210 const ParameterBlock* parameter_block = parameter_blocks_[i];
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800211 if (parameter_block->LocalParameterizationJacobian() != nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800212 scratch_doubles += parameter_block->Size();
213 }
214 }
215 scratch_doubles *= NumResiduals();
216 return scratch_doubles;
217}
218
219} // namespace internal
220} // namespace ceres