blob: dadaaa0873454b4e561c1bf7a8b9698806d6b4fa [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Ceres Solver - A fast non-linear least squares minimizer
2// Copyright 2016 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// Authors: wjr@google.com (William Rucklidge),
30// keir@google.com (Keir Mierle),
31// dgossow@google.com (David Gossow)
32
33#include "ceres/gradient_checker.h"
34
35#include <algorithm>
36#include <cmath>
37#include <cstdint>
38#include <numeric>
39#include <string>
40#include <vector>
41
42#include "ceres/is_close.h"
43#include "ceres/stringprintf.h"
44#include "ceres/types.h"
45
46namespace ceres {
47
48using internal::IsClose;
49using internal::StringAppendF;
50using internal::StringPrintf;
51using std::string;
52using std::vector;
53
54namespace {
55// Evaluate the cost function and transform the returned Jacobians to
56// the local space of the respective local parameterizations.
57bool EvaluateCostFunction(
58 const ceres::CostFunction* function,
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080059 double const* const* parameters,
Austin Schuh70cc9552019-01-21 19:46:48 -080060 const std::vector<const ceres::LocalParameterization*>&
61 local_parameterizations,
62 Vector* residuals,
63 std::vector<Matrix>* jacobians,
64 std::vector<Matrix>* local_jacobians) {
65 CHECK(residuals != nullptr);
66 CHECK(jacobians != nullptr);
67 CHECK(local_jacobians != nullptr);
68
69 const vector<int32_t>& block_sizes = function->parameter_block_sizes();
70 const int num_parameter_blocks = block_sizes.size();
71
72 // Allocate Jacobian matrices in local space.
73 local_jacobians->resize(num_parameter_blocks);
74 vector<double*> local_jacobian_data(num_parameter_blocks);
75 for (int i = 0; i < num_parameter_blocks; ++i) {
76 int block_size = block_sizes.at(i);
77 if (local_parameterizations.at(i) != NULL) {
78 block_size = local_parameterizations.at(i)->LocalSize();
79 }
80 local_jacobians->at(i).resize(function->num_residuals(), block_size);
81 local_jacobians->at(i).setZero();
82 local_jacobian_data.at(i) = local_jacobians->at(i).data();
83 }
84
85 // Allocate Jacobian matrices in global space.
86 jacobians->resize(num_parameter_blocks);
87 vector<double*> jacobian_data(num_parameter_blocks);
88 for (int i = 0; i < num_parameter_blocks; ++i) {
89 jacobians->at(i).resize(function->num_residuals(), block_sizes.at(i));
90 jacobians->at(i).setZero();
91 jacobian_data.at(i) = jacobians->at(i).data();
92 }
93
94 // Compute residuals & jacobians.
95 CHECK_NE(0, function->num_residuals());
96 residuals->resize(function->num_residuals());
97 residuals->setZero();
Austin Schuh1d1e6ea2020-12-23 21:56:30 -080098 if (!function->Evaluate(
99 parameters, residuals->data(), jacobian_data.data())) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800100 return false;
101 }
102
103 // Convert Jacobians from global to local space.
104 for (size_t i = 0; i < local_jacobians->size(); ++i) {
105 if (local_parameterizations.at(i) == NULL) {
106 local_jacobians->at(i) = jacobians->at(i);
107 } else {
108 int global_size = local_parameterizations.at(i)->GlobalSize();
109 int local_size = local_parameterizations.at(i)->LocalSize();
110 CHECK_EQ(jacobians->at(i).cols(), global_size);
111 Matrix global_J_local(global_size, local_size);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800112 local_parameterizations.at(i)->ComputeJacobian(parameters[i],
113 global_J_local.data());
Austin Schuh70cc9552019-01-21 19:46:48 -0800114 local_jacobians->at(i).noalias() = jacobians->at(i) * global_J_local;
115 }
116 }
117 return true;
118}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800119} // namespace
Austin Schuh70cc9552019-01-21 19:46:48 -0800120
121GradientChecker::GradientChecker(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800122 const CostFunction* function,
123 const vector<const LocalParameterization*>* local_parameterizations,
124 const NumericDiffOptions& options)
125 : function_(function) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800126 CHECK(function != nullptr);
127 if (local_parameterizations != NULL) {
128 local_parameterizations_ = *local_parameterizations;
129 } else {
130 local_parameterizations_.resize(function->parameter_block_sizes().size(),
131 NULL);
132 }
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800133 DynamicNumericDiffCostFunction<CostFunction, RIDDERS>*
Austin Schuh70cc9552019-01-21 19:46:48 -0800134 finite_diff_cost_function =
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800135 new DynamicNumericDiffCostFunction<CostFunction, RIDDERS>(
136 function, DO_NOT_TAKE_OWNERSHIP, options);
Austin Schuh70cc9552019-01-21 19:46:48 -0800137 finite_diff_cost_function_.reset(finite_diff_cost_function);
138
139 const vector<int32_t>& parameter_block_sizes =
140 function->parameter_block_sizes();
141 const int num_parameter_blocks = parameter_block_sizes.size();
142 for (int i = 0; i < num_parameter_blocks; ++i) {
143 finite_diff_cost_function->AddParameterBlock(parameter_block_sizes[i]);
144 }
145 finite_diff_cost_function->SetNumResiduals(function->num_residuals());
146}
147
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800148bool GradientChecker::Probe(double const* const* parameters,
Austin Schuh70cc9552019-01-21 19:46:48 -0800149 double relative_precision,
150 ProbeResults* results_param) const {
151 int num_residuals = function_->num_residuals();
152
153 // Make sure that we have a place to store results, no matter if the user has
154 // provided an output argument.
155 ProbeResults* results;
156 ProbeResults results_local;
157 if (results_param != NULL) {
158 results = results_param;
159 results->residuals.resize(0);
160 results->jacobians.clear();
161 results->numeric_jacobians.clear();
162 results->local_jacobians.clear();
163 results->local_numeric_jacobians.clear();
164 results->error_log.clear();
165 } else {
166 results = &results_local;
167 }
168 results->maximum_relative_error = 0.0;
169 results->return_value = true;
170
171 // Evaluate the derivative using the user supplied code.
172 vector<Matrix>& jacobians = results->jacobians;
173 vector<Matrix>& local_jacobians = results->local_jacobians;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800174 if (!EvaluateCostFunction(function_,
175 parameters,
176 local_parameterizations_,
177 &results->residuals,
178 &jacobians,
179 &local_jacobians)) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800180 results->error_log = "Function evaluation with Jacobians failed.";
181 results->return_value = false;
182 }
183
184 // Evaluate the derivative using numeric derivatives.
185 vector<Matrix>& numeric_jacobians = results->numeric_jacobians;
186 vector<Matrix>& local_numeric_jacobians = results->local_numeric_jacobians;
187 Vector finite_diff_residuals;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800188 if (!EvaluateCostFunction(finite_diff_cost_function_.get(),
189 parameters,
190 local_parameterizations_,
191 &finite_diff_residuals,
192 &numeric_jacobians,
193 &local_numeric_jacobians)) {
194 results->error_log +=
195 "\nFunction evaluation with numerical "
Austin Schuh70cc9552019-01-21 19:46:48 -0800196 "differentiation failed.";
197 results->return_value = false;
198 }
199
200 if (!results->return_value) {
201 return false;
202 }
203
204 for (int i = 0; i < num_residuals; ++i) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800205 if (!IsClose(results->residuals[i],
206 finite_diff_residuals[i],
207 relative_precision,
208 NULL,
209 NULL)) {
210 results->error_log =
211 "Function evaluation with and without Jacobians "
Austin Schuh70cc9552019-01-21 19:46:48 -0800212 "resulted in different residuals.";
213 LOG(INFO) << results->residuals.transpose();
214 LOG(INFO) << finite_diff_residuals.transpose();
215 return false;
216 }
217 }
218
219 // See if any elements have relative error larger than the threshold.
220 int num_bad_jacobian_components = 0;
221 double& worst_relative_error = results->maximum_relative_error;
222 worst_relative_error = 0;
223
224 // Accumulate the error message for all the jacobians, since it won't get
225 // output if there are no bad jacobian components.
226 string error_log;
227 for (int k = 0; k < function_->parameter_block_sizes().size(); k++) {
228 StringAppendF(&error_log,
229 "========== "
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800230 "Jacobian for block %d: (%ld by %ld)) "
Austin Schuh70cc9552019-01-21 19:46:48 -0800231 "==========\n",
232 k,
233 static_cast<long>(local_jacobians[k].rows()),
234 static_cast<long>(local_jacobians[k].cols()));
235 // The funny spacing creates appropriately aligned column headers.
236 error_log +=
237 " block row col user dx/dy num diff dx/dy "
238 "abs error relative error parameter residual\n";
239
240 for (int i = 0; i < local_jacobians[k].rows(); i++) {
241 for (int j = 0; j < local_jacobians[k].cols(); j++) {
242 double term_jacobian = local_jacobians[k](i, j);
243 double finite_jacobian = local_numeric_jacobians[k](i, j);
244 double relative_error, absolute_error;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800245 bool bad_jacobian_entry = !IsClose(term_jacobian,
246 finite_jacobian,
247 relative_precision,
248 &relative_error,
249 &absolute_error);
Austin Schuh70cc9552019-01-21 19:46:48 -0800250 worst_relative_error = std::max(worst_relative_error, relative_error);
251
252 StringAppendF(&error_log,
253 "%6d %4d %4d %17g %17g %17g %17g %17g %17g",
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800254 k,
255 i,
256 j,
257 term_jacobian,
258 finite_jacobian,
259 absolute_error,
260 relative_error,
Austin Schuh70cc9552019-01-21 19:46:48 -0800261 parameters[k][j],
262 results->residuals[i]);
263
264 if (bad_jacobian_entry) {
265 num_bad_jacobian_components++;
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800266 StringAppendF(&error_log,
267 " ------ (%d,%d,%d) Relative error worse than %g",
268 k,
269 i,
270 j,
271 relative_precision);
Austin Schuh70cc9552019-01-21 19:46:48 -0800272 }
273 error_log += "\n";
274 }
275 }
276 }
277
278 // Since there were some bad errors, dump comprehensive debug info.
279 if (num_bad_jacobian_components) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800280 string header = StringPrintf(
281 "\nDetected %d bad Jacobian component(s). "
Austin Schuh70cc9552019-01-21 19:46:48 -0800282 "Worst relative error was %g.\n",
283 num_bad_jacobian_components,
284 worst_relative_error);
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800285 results->error_log = header + "\n" + error_log;
Austin Schuh70cc9552019-01-21 19:46:48 -0800286 return false;
287 }
288 return true;
289}
290
291} // namespace ceres