blob: 7582e92b2e34d7f44a4ca71e63c846166396e9ec [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>
37#include "ceres/corrector.h"
38#include "ceres/parameter_block.h"
39#include "ceres/residual_block_utils.h"
40#include "ceres/cost_function.h"
41#include "ceres/internal/eigen.h"
42#include "ceres/internal/fixed_array.h"
43#include "ceres/local_parameterization.h"
44#include "ceres/loss_function.h"
45#include "ceres/small_blas.h"
46
47using Eigen::Dynamic;
48
49namespace ceres {
50namespace internal {
51
52ResidualBlock::ResidualBlock(
53 const CostFunction* cost_function, const LossFunction* loss_function,
54 const std::vector<ParameterBlock*>& parameter_blocks, int index)
55 : cost_function_(cost_function),
56 loss_function_(loss_function),
57 parameter_blocks_(
58 new ParameterBlock*[cost_function->parameter_block_sizes().size()]),
59 index_(index) {
60 CHECK(cost_function_ != nullptr);
61 std::copy(parameter_blocks.begin(),
62 parameter_blocks.end(),
63 parameter_blocks_.get());
64}
65
66bool ResidualBlock::Evaluate(const bool apply_loss_function,
67 double* cost,
68 double* residuals,
69 double** jacobians,
70 double* scratch) const {
71 const int num_parameter_blocks = NumParameterBlocks();
72 const int num_residuals = cost_function_->num_residuals();
73
74 // Collect the parameters from their blocks. This will rarely allocate, since
75 // residuals taking more than 8 parameter block arguments are rare.
76 FixedArray<const double*, 8> parameters(num_parameter_blocks);
77 for (int i = 0; i < num_parameter_blocks; ++i) {
78 parameters[i] = parameter_blocks_[i]->state();
79 }
80
81 // Put pointers into the scratch space into global_jacobians as appropriate.
82 FixedArray<double*, 8> global_jacobians(num_parameter_blocks);
83 if (jacobians != NULL) {
84 for (int i = 0; i < num_parameter_blocks; ++i) {
85 const ParameterBlock* parameter_block = parameter_blocks_[i];
86 if (jacobians[i] != NULL &&
87 parameter_block->LocalParameterizationJacobian() != NULL) {
88 global_jacobians[i] = scratch;
89 scratch += num_residuals * parameter_block->Size();
90 } else {
91 global_jacobians[i] = jacobians[i];
92 }
93 }
94 }
95
96 // If the caller didn't request residuals, use the scratch space for them.
97 bool outputting_residuals = (residuals != NULL);
98 if (!outputting_residuals) {
99 residuals = scratch;
100 }
101
102 // Invalidate the evaluation buffers so that we can check them after
103 // the CostFunction::Evaluate call, to see if all the return values
104 // that were required were written to and that they are finite.
105 double** eval_jacobians = (jacobians != NULL) ? global_jacobians.get() : NULL;
106
107 InvalidateEvaluation(*this, cost, residuals, eval_jacobians);
108
109 if (!cost_function_->Evaluate(parameters.get(), residuals, eval_jacobians)) {
110 return false;
111 }
112
113 if (!IsEvaluationValid(*this,
114 parameters.get(),
115 cost,
116 residuals,
117 eval_jacobians)) {
118 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" +
124 EvaluationToString(*this,
125 parameters.get(),
126 cost,
127 residuals,
128 eval_jacobians);
129 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.
136 if (jacobians != NULL) {
137 for (int i = 0; i < num_parameter_blocks; ++i) {
138 if (jacobians[i] != NULL) {
139 const ParameterBlock* parameter_block = parameter_blocks_[i];
140
141 // Apply local reparameterization to the jacobians.
142 if (parameter_block->LocalParameterizationJacobian() != NULL) {
143 // 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(),
151 jacobians[i], 0, 0, num_residuals, parameter_block->LocalSize());
152 }
153 }
154 }
155 }
156
157 if (loss_function_ == NULL || !apply_loss_function) {
158 *cost = 0.5 * squared_norm;
159 return true;
160 }
161
162 double rho[3];
163 loss_function_->Evaluate(squared_norm, rho);
164 *cost = 0.5 * rho[0];
165
166 // No jacobians and not outputting residuals? All done. Doing an early exit
167 // here avoids constructing the "Corrector" object below in a common case.
168 if (jacobians == NULL && !outputting_residuals) {
169 return true;
170 }
171
172 // Correct for the effects of the loss function. The jacobians need to be
173 // corrected before the residuals, since they use the uncorrected residuals.
174 Corrector correct(squared_norm, rho);
175 if (jacobians != NULL) {
176 for (int i = 0; i < num_parameter_blocks; ++i) {
177 if (jacobians[i] != NULL) {
178 const ParameterBlock* parameter_block = parameter_blocks_[i];
179
180 // Correct the jacobians for the loss function.
181 correct.CorrectJacobian(num_residuals,
182 parameter_block->LocalSize(),
183 residuals,
184 jacobians[i]);
185 }
186 }
187 }
188
189 // Correct the residuals with the loss function.
190 if (outputting_residuals) {
191 correct.CorrectResiduals(num_residuals, residuals);
192 }
193 return true;
194}
195
196int ResidualBlock::NumScratchDoublesForEvaluate() const {
197 // Compute the amount of scratch space needed to store the full-sized
198 // jacobians. For parameters that have no local parameterization no storage
199 // is needed and the passed-in jacobian array is used directly. Also include
200 // space to store the residuals, which is needed for cost-only evaluations.
201 // This is slightly pessimistic, since both won't be needed all the time, but
202 // the amount of excess should not cause problems for the caller.
203 int num_parameters = NumParameterBlocks();
204 int scratch_doubles = 1;
205 for (int i = 0; i < num_parameters; ++i) {
206 const ParameterBlock* parameter_block = parameter_blocks_[i];
207 if (!parameter_block->IsConstant() &&
208 parameter_block->LocalParameterizationJacobian() != NULL) {
209 scratch_doubles += parameter_block->Size();
210 }
211 }
212 scratch_doubles *= NumResiduals();
213 return scratch_doubles;
214}
215
216} // namespace internal
217} // namespace ceres