blob: b91b0ed784366447bb1ec6ac94720a858177f45e [file] [log] [blame]
Keir Mierle8ebb0732012-04-30 23:09:08 -07001// Ceres Solver - A fast non-linear least squares minimizer
2// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.
3// http://code.google.com/p/ceres-solver/
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
38#include "ceres/corrector.h"
39#include "ceres/parameter_block.h"
40#include "ceres/residual_block_utils.h"
41#include "ceres/cost_function.h"
42#include "ceres/internal/eigen.h"
43#include "ceres/internal/fixed_array.h"
44#include "ceres/local_parameterization.h"
45#include "ceres/loss_function.h"
46
47namespace ceres {
48namespace internal {
49
50ResidualBlock::ResidualBlock(const CostFunction* cost_function,
51 const LossFunction* loss_function,
Keir Mierle04938ef2013-02-17 12:37:55 -080052 const vector<ParameterBlock*>& parameter_blocks,
53 int index)
Keir Mierle8ebb0732012-04-30 23:09:08 -070054 : cost_function_(cost_function),
55 loss_function_(loss_function),
56 parameter_blocks_(
57 new ParameterBlock* [
Keir Mierle04938ef2013-02-17 12:37:55 -080058 cost_function->parameter_block_sizes().size()]),
59 index_(index) {
Keir Mierle8ebb0732012-04-30 23:09:08 -070060 std::copy(parameter_blocks.begin(),
61 parameter_blocks.end(),
62 parameter_blocks_.get());
63}
64
Sameer Agarwal039ff072013-02-26 09:15:39 -080065bool ResidualBlock::Evaluate(const bool apply_loss_function,
66 double* cost,
Keir Mierle8ebb0732012-04-30 23:09:08 -070067 double* residuals,
68 double** jacobians,
69 double* scratch) const {
70 const int num_parameter_blocks = NumParameterBlocks();
71 const int num_residuals = cost_function_->num_residuals();
72
73 // Collect the parameters from their blocks. This will rarely allocate, since
74 // residuals taking more than 8 parameter block arguments are rare.
75 FixedArray<const double*, 8> parameters(num_parameter_blocks);
76 for (int i = 0; i < num_parameter_blocks; ++i) {
77 parameters[i] = parameter_blocks_[i]->state();
78 }
79
80 // Put pointers into the scratch space into global_jacobians as appropriate.
81 FixedArray<double*, 8> global_jacobians(num_parameter_blocks);
82 if (jacobians != NULL) {
83 for (int i = 0; i < num_parameter_blocks; ++i) {
84 const ParameterBlock* parameter_block = parameter_blocks_[i];
85 if (jacobians[i] != NULL &&
86 parameter_block->LocalParameterizationJacobian() != NULL) {
87 global_jacobians[i] = scratch;
88 scratch += num_residuals * parameter_block->Size();
89 } else {
90 global_jacobians[i] = jacobians[i];
91 }
92 }
93 }
94
95 // If the caller didn't request residuals, use the scratch space for them.
96 bool outputting_residuals = (residuals != NULL);
97 if (!outputting_residuals) {
98 residuals = scratch;
99 }
100
101 // Invalidate the evaluation buffers so that we can check them after
102 // the CostFunction::Evaluate call, to see if all the return values
103 // that were required were written to and that they are finite.
104 double** eval_jacobians = (jacobians != NULL) ? global_jacobians.get() : NULL;
105
106 InvalidateEvaluation(*this, cost, residuals, eval_jacobians);
107
Sameer Agarwal552f9f82012-08-31 07:27:22 -0700108 if (!cost_function_->Evaluate(parameters.get(), residuals, eval_jacobians)) {
109 return false;
110 }
111
112 if (!IsEvaluationValid(*this,
Keir Mierle8ebb0732012-04-30 23:09:08 -0700113 parameters.get(),
114 cost,
115 residuals,
116 eval_jacobians)) {
117 string message =
118 "\n\n"
119 "Error in evaluating the ResidualBlock.\n\n"
120 "There are two possible reasons. Either the CostFunction did not evaluate and fill all \n" // NOLINT
121 "residual and jacobians that were requested or there was a non-finite value (nan/infinite)\n" // NOLINT
122 "generated during the or jacobian computation. \n\n" +
123 EvaluationToString(*this,
124 parameters.get(),
125 cost,
126 residuals,
127 eval_jacobians);
128 LOG(WARNING) << message;
129 return false;
130 }
131
132 double squared_norm = VectorRef(residuals, num_residuals).squaredNorm();
133
134 // Update the jacobians with the local parameterizations.
135 if (jacobians != NULL) {
136 for (int i = 0; i < num_parameter_blocks; ++i) {
137 if (jacobians[i] != NULL) {
138 const ParameterBlock* parameter_block = parameter_blocks_[i];
139
140 // Apply local reparameterization to the jacobians.
141 if (parameter_block->LocalParameterizationJacobian() != NULL) {
142 ConstMatrixRef local_to_global(
143 parameter_block->LocalParameterizationJacobian(),
144 parameter_block->Size(),
145 parameter_block->LocalSize());
146 MatrixRef global_jacobian(global_jacobians[i],
147 num_residuals,
148 parameter_block->Size());
149 MatrixRef local_jacobian(jacobians[i],
150 num_residuals,
151 parameter_block->LocalSize());
152 local_jacobian.noalias() = global_jacobian * local_to_global;
153 }
154 }
155 }
156 }
157
Sameer Agarwal039ff072013-02-26 09:15:39 -0800158 if (loss_function_ == NULL || !apply_loss_function) {
Keir Mierle8ebb0732012-04-30 23:09:08 -0700159 *cost = 0.5 * squared_norm;
160 return true;
161 }
162
163 double rho[3];
164 loss_function_->Evaluate(squared_norm, rho);
165 *cost = 0.5 * rho[0];
166
167 // No jacobians and not outputting residuals? All done. Doing an early exit
168 // here avoids constructing the "Corrector" object below in a common case.
169 if (jacobians == NULL && !outputting_residuals) {
170 return true;
171 }
172
173 // Correct for the effects of the loss function. The jacobians need to be
174 // corrected before the residuals, since they use the uncorrected residuals.
175 Corrector correct(squared_norm, rho);
176 if (jacobians != NULL) {
177 for (int i = 0; i < num_parameter_blocks; ++i) {
178 if (jacobians[i] != NULL) {
179 const ParameterBlock* parameter_block = parameter_blocks_[i];
180
181 // Correct the jacobians for the loss function.
182 correct.CorrectJacobian(num_residuals,
183 parameter_block->LocalSize(),
184 residuals,
185 jacobians[i]);
186 }
187 }
188 }
189
190 // Correct the residuals with the loss function.
191 if (outputting_residuals) {
192 correct.CorrectResiduals(num_residuals, residuals);
193 }
194 return true;
195}
196
197int ResidualBlock::NumScratchDoublesForEvaluate() const {
198 // Compute the amount of scratch space needed to store the full-sized
199 // jacobians. For parameters that have no local parameterization no storage
200 // is needed and the passed-in jacobian array is used directly. Also include
201 // space to store the residuals, which is needed for cost-only evaluations.
202 // This is slightly pessimistic, since both won't be needed all the time, but
203 // the amount of excess should not cause problems for the caller.
204 int num_parameters = NumParameterBlocks();
205 int scratch_doubles = 1;
206 for (int i = 0; i < num_parameters; ++i) {
207 const ParameterBlock* parameter_block = parameter_blocks_[i];
208 if (!parameter_block->IsConstant() &&
209 parameter_block->LocalParameterizationJacobian() != NULL) {
210 scratch_doubles += parameter_block->Size();
211 }
212 }
213 scratch_doubles *= NumResiduals();
214 return scratch_doubles;
215}
216
217} // namespace internal
218} // namespace ceres