blob: f2a377b471a0554291f15252a759d830a1ef2cdb [file] [log] [blame]
Austin Schuh70cc9552019-01-21 19:46:48 -08001// Ceres Solver - A fast non-linear least squares minimizer
Austin Schuh3de38b02024-06-25 18:25:10 -07002// Copyright 2024 Google Inc. All rights reserved.
Austin Schuh70cc9552019-01-21 19:46:48 -08003// 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// Create CostFunctions as needed by the least squares framework with jacobians
33// computed via numeric (a.k.a. finite) differentiation. For more details see
34// http://en.wikipedia.org/wiki/Numerical_differentiation.
35//
36// To get an numerically differentiated cost function, you must define
37// a class with a operator() (a functor) that computes the residuals.
38//
39// The function must write the computed value in the last argument
40// (the only non-const one) and return true to indicate success.
41// Please see cost_function.h for details on how the return value
42// maybe used to impose simple constraints on the parameter block.
43//
44// For example, consider a scalar error e = k - x'y, where both x and y are
45// two-dimensional column vector parameters, the prime sign indicates
46// transposition, and k is a constant. The form of this error, which is the
47// difference between a constant and an expression, is a common pattern in least
48// squares problems. For example, the value x'y might be the model expectation
49// for a series of measurements, where there is an instance of the cost function
50// for each measurement k.
51//
52// The actual cost added to the total problem is e^2, or (k - x'k)^2; however,
53// the squaring is implicitly done by the optimization framework.
54//
55// To write an numerically-differentiable cost function for the above model,
56// first define the object
57//
58// class MyScalarCostFunctor {
59// explicit MyScalarCostFunctor(double k): k_(k) {}
60//
61// bool operator()(const double* const x,
62// const double* const y,
63// double* residuals) const {
64// residuals[0] = k_ - x[0] * y[0] - x[1] * y[1];
65// return true;
66// }
67//
68// private:
69// double k_;
70// };
71//
72// Note that in the declaration of operator() the input parameters x
73// and y come first, and are passed as const pointers to arrays of
74// doubles. If there were three input parameters, then the third input
75// parameter would come after y. The output is always the last
76// parameter, and is also a pointer to an array. In the example above,
77// the residual is a scalar, so only residuals[0] is set.
78//
79// Then given this class definition, the numerically differentiated
80// cost function with central differences used for computing the
81// derivative can be constructed as follows.
82//
83// CostFunction* cost_function
84// = new NumericDiffCostFunction<MyScalarCostFunctor, CENTRAL, 1, 2, 2>(
85// new MyScalarCostFunctor(1.0)); ^ ^ ^ ^
86// | | | |
87// Finite Differencing Scheme -+ | | |
88// Dimension of residual ------------+ | |
89// Dimension of x ----------------------+ |
90// Dimension of y -------------------------+
91//
92// In this example, there is usually an instance for each measurement of k.
93//
94// In the instantiation above, the template parameters following
95// "MyScalarCostFunctor", "1, 2, 2", describe the functor as computing
96// a 1-dimensional output from two arguments, both 2-dimensional.
97//
98// NumericDiffCostFunction also supports cost functions with a
99// runtime-determined number of residuals. For example:
100//
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800101// clang-format off
102//
Austin Schuh70cc9552019-01-21 19:46:48 -0800103// CostFunction* cost_function
104// = new NumericDiffCostFunction<MyScalarCostFunctor, CENTRAL, DYNAMIC, 2, 2>(
105// new CostFunctorWithDynamicNumResiduals(1.0), ^ ^ ^
106// TAKE_OWNERSHIP, | | |
107// runtime_number_of_residuals); <----+ | | |
108// | | | |
109// | | | |
110// Actual number of residuals ------+ | | |
111// Indicate dynamic number of residuals --------------------+ | |
112// Dimension of x ------------------------------------------------+ |
113// Dimension of y ---------------------------------------------------+
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800114// clang-format on
115//
Austin Schuh70cc9552019-01-21 19:46:48 -0800116//
117// The central difference method is considerably more accurate at the cost of
118// twice as many function evaluations than forward difference. Consider using
119// central differences begin with, and only after that works, trying forward
120// difference to improve performance.
121//
122// WARNING #1: A common beginner's error when first using
123// NumericDiffCostFunction is to get the sizing wrong. In particular,
124// there is a tendency to set the template parameters to (dimension of
125// residual, number of parameters) instead of passing a dimension
126// parameter for *every parameter*. In the example above, that would
127// be <MyScalarCostFunctor, 1, 2>, which is missing the last '2'
128// argument. Please be careful when setting the size parameters.
129//
130////////////////////////////////////////////////////////////////////////////
131////////////////////////////////////////////////////////////////////////////
132//
133// ALTERNATE INTERFACE
134//
135// For a variety of reasons, including compatibility with legacy code,
136// NumericDiffCostFunction can also take CostFunction objects as
137// input. The following describes how.
138//
139// To get a numerically differentiated cost function, define a
140// subclass of CostFunction such that the Evaluate() function ignores
141// the jacobian parameter. The numeric differentiation wrapper will
142// fill in the jacobian parameter if necessary by repeatedly calling
143// the Evaluate() function with small changes to the appropriate
144// parameters, and computing the slope. For performance, the numeric
145// differentiation wrapper class is templated on the concrete cost
146// function, even though it could be implemented only in terms of the
147// virtual CostFunction interface.
148//
149// The numerically differentiated version of a cost function for a cost function
150// can be constructed as follows:
151//
Austin Schuh3de38b02024-06-25 18:25:10 -0700152// auto* cost_function
153// = new NumericDiffCostFunction<MyCostFunction, CENTRAL, 1, 4, 8>();
Austin Schuh70cc9552019-01-21 19:46:48 -0800154//
155// where MyCostFunction has 1 residual and 2 parameter blocks with sizes 4 and 8
156// respectively. Look at the tests for a more detailed example.
157//
158// TODO(keir): Characterize accuracy; mention pitfalls; provide alternatives.
159
160#ifndef CERES_PUBLIC_NUMERIC_DIFF_COST_FUNCTION_H_
161#define CERES_PUBLIC_NUMERIC_DIFF_COST_FUNCTION_H_
162
163#include <array>
164#include <memory>
Austin Schuh3de38b02024-06-25 18:25:10 -0700165#include <type_traits>
Austin Schuh70cc9552019-01-21 19:46:48 -0800166
167#include "Eigen/Dense"
168#include "ceres/cost_function.h"
169#include "ceres/internal/numeric_diff.h"
170#include "ceres/internal/parameter_dims.h"
171#include "ceres/numeric_diff_options.h"
172#include "ceres/sized_cost_function.h"
173#include "ceres/types.h"
Austin Schuh70cc9552019-01-21 19:46:48 -0800174
175namespace ceres {
176
177template <typename CostFunctor,
Austin Schuh3de38b02024-06-25 18:25:10 -0700178 NumericDiffMethodType kMethod = CENTRAL,
Austin Schuh70cc9552019-01-21 19:46:48 -0800179 int kNumResiduals = 0, // Number of residuals, or ceres::DYNAMIC
180 int... Ns> // Parameters dimensions for each block.
Austin Schuh3de38b02024-06-25 18:25:10 -0700181class NumericDiffCostFunction final
182 : public SizedCostFunction<kNumResiduals, Ns...> {
Austin Schuh70cc9552019-01-21 19:46:48 -0800183 public:
Austin Schuh3de38b02024-06-25 18:25:10 -0700184 explicit NumericDiffCostFunction(
Austin Schuh70cc9552019-01-21 19:46:48 -0800185 CostFunctor* functor,
186 Ownership ownership = TAKE_OWNERSHIP,
187 int num_residuals = kNumResiduals,
188 const NumericDiffOptions& options = NumericDiffOptions())
Austin Schuh3de38b02024-06-25 18:25:10 -0700189 : NumericDiffCostFunction{std::unique_ptr<CostFunctor>{functor},
190 ownership,
191 num_residuals,
192 options} {}
Austin Schuh70cc9552019-01-21 19:46:48 -0800193
Austin Schuh3de38b02024-06-25 18:25:10 -0700194 explicit NumericDiffCostFunction(
195 std::unique_ptr<CostFunctor> functor,
196 int num_residuals = kNumResiduals,
197 const NumericDiffOptions& options = NumericDiffOptions())
198 : NumericDiffCostFunction{
199 std::move(functor), TAKE_OWNERSHIP, num_residuals, options} {}
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800200
Austin Schuh3de38b02024-06-25 18:25:10 -0700201 // Constructs the CostFunctor on the heap and takes the ownership.
202 // Invocable only if the number of residuals is known at compile-time.
203 template <class... Args,
204 bool kIsDynamic = kNumResiduals == DYNAMIC,
205 std::enable_if_t<!kIsDynamic &&
206 std::is_constructible_v<CostFunctor, Args&&...>>* =
207 nullptr>
208 explicit NumericDiffCostFunction(Args&&... args)
209 // NOTE We explicitly use direct initialization using parentheses instead
210 // of uniform initialization using braces to avoid narrowing conversion
211 // warnings.
212 : NumericDiffCostFunction{
213 std::make_unique<CostFunctor>(std::forward<Args>(args)...),
214 TAKE_OWNERSHIP} {}
215
216 NumericDiffCostFunction(NumericDiffCostFunction&& other) noexcept = default;
217 NumericDiffCostFunction& operator=(NumericDiffCostFunction&& other) noexcept =
218 default;
219 NumericDiffCostFunction(const NumericDiffCostFunction&) = delete;
220 NumericDiffCostFunction& operator=(const NumericDiffCostFunction&) = delete;
221
222 ~NumericDiffCostFunction() override {
Austin Schuh70cc9552019-01-21 19:46:48 -0800223 if (ownership_ != TAKE_OWNERSHIP) {
224 functor_.release();
225 }
226 }
227
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800228 bool Evaluate(double const* const* parameters,
229 double* residuals,
230 double** jacobians) const override {
Austin Schuh70cc9552019-01-21 19:46:48 -0800231 using internal::FixedArray;
232 using internal::NumericDiff;
233
234 using ParameterDims =
235 typename SizedCostFunction<kNumResiduals, Ns...>::ParameterDims;
Austin Schuh70cc9552019-01-21 19:46:48 -0800236
237 constexpr int kNumParameters = ParameterDims::kNumParameters;
238 constexpr int kNumParameterBlocks = ParameterDims::kNumParameterBlocks;
239
240 // Get the function value (residuals) at the the point to evaluate.
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800241 if (!internal::VariadicEvaluate<ParameterDims>(
242 *functor_, parameters, residuals)) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800243 return false;
244 }
245
Austin Schuh3de38b02024-06-25 18:25:10 -0700246 if (jacobians == nullptr) {
Austin Schuh70cc9552019-01-21 19:46:48 -0800247 return true;
248 }
249
250 // Create a copy of the parameters which will get mutated.
251 FixedArray<double> parameters_copy(kNumParameters);
252 std::array<double*, kNumParameterBlocks> parameters_reference_copy =
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800253 ParameterDims::GetUnpackedParameters(parameters_copy.data());
Austin Schuh70cc9552019-01-21 19:46:48 -0800254
255 for (int block = 0; block < kNumParameterBlocks; ++block) {
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800256 memcpy(parameters_reference_copy[block],
257 parameters[block],
Austin Schuh70cc9552019-01-21 19:46:48 -0800258 sizeof(double) * ParameterDims::GetDim(block));
259 }
260
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800261 internal::EvaluateJacobianForParameterBlocks<ParameterDims>::
Austin Schuh3de38b02024-06-25 18:25:10 -0700262 template Apply<kMethod, kNumResiduals>(
Austin Schuh1d1e6ea2020-12-23 21:56:30 -0800263 functor_.get(),
264 residuals,
265 options_,
266 SizedCostFunction<kNumResiduals, Ns...>::num_residuals(),
267 parameters_reference_copy.data(),
268 jacobians);
Austin Schuh70cc9552019-01-21 19:46:48 -0800269
270 return true;
271 }
272
Austin Schuh3de38b02024-06-25 18:25:10 -0700273 const CostFunctor& functor() const { return *functor_; }
274
Austin Schuh70cc9552019-01-21 19:46:48 -0800275 private:
Austin Schuh3de38b02024-06-25 18:25:10 -0700276 explicit NumericDiffCostFunction(std::unique_ptr<CostFunctor> functor,
277 Ownership ownership,
278 [[maybe_unused]] int num_residuals,
279 const NumericDiffOptions& options)
280 : functor_(std::move(functor)), ownership_(ownership), options_(options) {
281 if constexpr (kNumResiduals == DYNAMIC) {
282 SizedCostFunction<kNumResiduals, Ns...>::set_num_residuals(num_residuals);
283 }
284 }
285
Austin Schuh70cc9552019-01-21 19:46:48 -0800286 std::unique_ptr<CostFunctor> functor_;
287 Ownership ownership_;
288 NumericDiffOptions options_;
289};
290
291} // namespace ceres
292
293#endif // CERES_PUBLIC_NUMERIC_DIFF_COST_FUNCTION_H_