blob: 03867891dba98bceef3467096597db1d20bce436 [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,
52 const vector<ParameterBlock*>& parameter_blocks)
53 : cost_function_(cost_function),
54 loss_function_(loss_function),
55 parameter_blocks_(
56 new ParameterBlock* [
57 cost_function->parameter_block_sizes().size()]) {
58 std::copy(parameter_blocks.begin(),
59 parameter_blocks.end(),
60 parameter_blocks_.get());
61}
62
63bool ResidualBlock::Evaluate(double* cost,
64 double* residuals,
65 double** jacobians,
66 double* scratch) const {
67 const int num_parameter_blocks = NumParameterBlocks();
68 const int num_residuals = cost_function_->num_residuals();
69
70 // Collect the parameters from their blocks. This will rarely allocate, since
71 // residuals taking more than 8 parameter block arguments are rare.
72 FixedArray<const double*, 8> parameters(num_parameter_blocks);
73 for (int i = 0; i < num_parameter_blocks; ++i) {
74 parameters[i] = parameter_blocks_[i]->state();
75 }
76
77 // Put pointers into the scratch space into global_jacobians as appropriate.
78 FixedArray<double*, 8> global_jacobians(num_parameter_blocks);
79 if (jacobians != NULL) {
80 for (int i = 0; i < num_parameter_blocks; ++i) {
81 const ParameterBlock* parameter_block = parameter_blocks_[i];
82 if (jacobians[i] != NULL &&
83 parameter_block->LocalParameterizationJacobian() != NULL) {
84 global_jacobians[i] = scratch;
85 scratch += num_residuals * parameter_block->Size();
86 } else {
87 global_jacobians[i] = jacobians[i];
88 }
89 }
90 }
91
92 // If the caller didn't request residuals, use the scratch space for them.
93 bool outputting_residuals = (residuals != NULL);
94 if (!outputting_residuals) {
95 residuals = scratch;
96 }
97
98 // Invalidate the evaluation buffers so that we can check them after
99 // the CostFunction::Evaluate call, to see if all the return values
100 // that were required were written to and that they are finite.
101 double** eval_jacobians = (jacobians != NULL) ? global_jacobians.get() : NULL;
102
103 InvalidateEvaluation(*this, cost, residuals, eval_jacobians);
104
105 if (!cost_function_->Evaluate(parameters.get(), residuals, eval_jacobians) ||
106 !IsEvaluationValid(*this,
107 parameters.get(),
108 cost,
109 residuals,
110 eval_jacobians)) {
111 string message =
112 "\n\n"
113 "Error in evaluating the ResidualBlock.\n\n"
114 "There are two possible reasons. Either the CostFunction did not evaluate and fill all \n" // NOLINT
115 "residual and jacobians that were requested or there was a non-finite value (nan/infinite)\n" // NOLINT
116 "generated during the or jacobian computation. \n\n" +
117 EvaluationToString(*this,
118 parameters.get(),
119 cost,
120 residuals,
121 eval_jacobians);
122 LOG(WARNING) << message;
123 return false;
124 }
125
126 double squared_norm = VectorRef(residuals, num_residuals).squaredNorm();
127
128 // Update the jacobians with the local parameterizations.
129 if (jacobians != NULL) {
130 for (int i = 0; i < num_parameter_blocks; ++i) {
131 if (jacobians[i] != NULL) {
132 const ParameterBlock* parameter_block = parameter_blocks_[i];
133
134 // Apply local reparameterization to the jacobians.
135 if (parameter_block->LocalParameterizationJacobian() != NULL) {
136 ConstMatrixRef local_to_global(
137 parameter_block->LocalParameterizationJacobian(),
138 parameter_block->Size(),
139 parameter_block->LocalSize());
140 MatrixRef global_jacobian(global_jacobians[i],
141 num_residuals,
142 parameter_block->Size());
143 MatrixRef local_jacobian(jacobians[i],
144 num_residuals,
145 parameter_block->LocalSize());
146 local_jacobian.noalias() = global_jacobian * local_to_global;
147 }
148 }
149 }
150 }
151
152 if (loss_function_ == NULL) {
153 *cost = 0.5 * squared_norm;
154 return true;
155 }
156
157 double rho[3];
158 loss_function_->Evaluate(squared_norm, rho);
159 *cost = 0.5 * rho[0];
160
161 // No jacobians and not outputting residuals? All done. Doing an early exit
162 // here avoids constructing the "Corrector" object below in a common case.
163 if (jacobians == NULL && !outputting_residuals) {
164 return true;
165 }
166
167 // Correct for the effects of the loss function. The jacobians need to be
168 // corrected before the residuals, since they use the uncorrected residuals.
169 Corrector correct(squared_norm, rho);
170 if (jacobians != NULL) {
171 for (int i = 0; i < num_parameter_blocks; ++i) {
172 if (jacobians[i] != NULL) {
173 const ParameterBlock* parameter_block = parameter_blocks_[i];
174
175 // Correct the jacobians for the loss function.
176 correct.CorrectJacobian(num_residuals,
177 parameter_block->LocalSize(),
178 residuals,
179 jacobians[i]);
180 }
181 }
182 }
183
184 // Correct the residuals with the loss function.
185 if (outputting_residuals) {
186 correct.CorrectResiduals(num_residuals, residuals);
187 }
188 return true;
189}
190
191int ResidualBlock::NumScratchDoublesForEvaluate() const {
192 // Compute the amount of scratch space needed to store the full-sized
193 // jacobians. For parameters that have no local parameterization no storage
194 // is needed and the passed-in jacobian array is used directly. Also include
195 // space to store the residuals, which is needed for cost-only evaluations.
196 // This is slightly pessimistic, since both won't be needed all the time, but
197 // the amount of excess should not cause problems for the caller.
198 int num_parameters = NumParameterBlocks();
199 int scratch_doubles = 1;
200 for (int i = 0; i < num_parameters; ++i) {
201 const ParameterBlock* parameter_block = parameter_blocks_[i];
202 if (!parameter_block->IsConstant() &&
203 parameter_block->LocalParameterizationJacobian() != NULL) {
204 scratch_doubles += parameter_block->Size();
205 }
206 }
207 scratch_doubles *= NumResiduals();
208 return scratch_doubles;
209}
210
211} // namespace internal
212} // namespace ceres