Squashed 'third_party/ceres/' changes from e51e9b46f..399cda773
399cda773 Update build documentation to reflect detection of Eigen via config mode
bb127272f Fix typos.
a0ec5c32a Update version history for 2.0.0RC2
3f6d27367 Unify symbol visibility configuration for all compilers
29c2912ee Unbreak the bazel build some more
bf47e1a36 Fix the Bazel build.
600e8c529 fix minor typos
bdcdcc78a update docs for changed cmake usage
3f69e5b36 Corrections from William Rucklidge
8bfdb02fb Rewrite uses of VLOG_IF and LOG_IF.
d1b35ffc1 Corrections from William Rucklidge
f34e80e91 Add dividers between licenses.
65c397dae Fix formatting
f63b1fea9 Add the MIT license text corresponding to the libmv derived files.
542613c13 minor formatting fix for trust_region_minimizer.cc
6d9e9843d Remove inclusion of ceres/eigen.h
eafeca5dc Fix a logging bug in TrustRegionMinimizer.
1fd0be916 Fix default initialisation of IterationCallback::cost
137bbe845 add info about clang-format to contributing docs
d3f66d77f fix formatting generated files (best effort)
a9c7361c8 minor formatting fix (wrongly updated in earlier commit)
7b8f675bf fix formatting for (non-generated) internal source files
921368ce3 Fix a number of typos in covariance.h
7b6b2491c fix formatting for examples
82275d8a4 some fixes for Linux and macOS install docs
9d762d74f fix formatting for public header files
c76478c48 gitignore *.pyc
4e69a475c Fix potential for mismatched release/debug TBB libraries
8e1d8e32a A number of small changes.
368a738e5 AutoDiffCostFunction: optional ownership
8cbd721c1 Add erf and erfc to jet.h, including tests in jet_test.cc
31366cff2 Benchmarks for dynamic autodiff.
29fb08aea Use CMAKE_PREFIX_PATH to pass Homebrew install location
242c703b5 Minor fixes to the documentation
79bbf9510 Add changelog for 2.0.0
41d05f13d Fix lint errors in evaluation_callback_test.cc
4b67903c1 Remove unused variables from problem_test.cc
10449fc36 Add Apache license to the LICENSE file for FixedArray
8c3ecec6d Fix some minor errors in IterationCallback docs
7d3ffcb42 Remove forced CONFIG from find_package(Eigen3)
a029fc0f9 Use latest FindTBB.cmake from VTK project
aa1abbc57 Replace use of GFLAGS_LIBRARIES with export gflags target
db2af1be8 Add Problem::EvaluateResidualBlockAssumingParametersUnchanged
ab4ed32cd Replace NULL with nullptr in the documentation.
ee280e27a Allow SubsetParameterization to accept an empty vector of constant parameters.
4b8c731d8 Fix a bug in DynamicAutoDiffCostFunction
5cb5b35a9 Fixed incorrect argument name in RotationMatrixToQuaternion()
e39d9ed1d Add a missing term and remove a superfluous word
27cab77b6 Reformulate some sentences
8ac6655ce Fix documentation formatting issues
7ef83e075 Update minimum required C++ version for Ceres to C++14
1d75e7568 Improve documentation for LocalParameterization
763398ca4 Update the section on Preconditioners
a614f788a Call EvaluationCallback before evaluating the fixed cost.
70308f7bb Simplify documentation generation.
e886d7e65 Reduce the number of minimizer iterations in evaluation_callback_test.cc
9483e6f2f Simplify DynamicCompressedRowJacobianWriter::Write
323cc55bb Update the version in package.xml to 2.0.0.
303b078b5 Fix few typos and alter a NULL to nullptr.
cca93fed6 Bypass Ceres' FindGlog.cmake in CeresConfig.cmake if possible
77fc1d0fc Use build_depend for private dependencies in Catkin package.xml
a09682f00 Fix MSVC version check to support use of clang-cl front-end
b70687fcc Add namespace qualified Ceres::ceres CMake target
99efa54bd Replace type aliases deprecated/removed in C++17/C++20 from FixedArray
adb973e4a NULL -> nullptr
27b717951 Respect FIND_QUIETLY flag in cmake config file
646959ef1 Do not export class template LineParameterization
1f128d070 Change the type of parameter index/offset to match their getter/setter
072c8f070 Initialize integer variables with integer instead of double
8c36bcc81 Use inline & -inlinehint-threshold in auto-diff benchmarks
57cf20aa5 static const -> static constexpr where we can.
40b27482a Add std::numeric_limit specialization for Jets
e751d6e4f Remove AutodiffCodegen
e9eb76f8e Remove AutodiffCodegen CMake integration
9435e08a7 More clang-tidy and wjr@ comment fixes
d93fac4b7 Remove AutodiffCodegen Tests
2281c6ed2 Fixes for comments from William Rucklidge
d797a87a4 Use Ridders' method in GradientChecker.
41675682d Fix a MSVC type deduction bug in ComputeHouseholderVector
947ec0c1f Remove AutodiffCodegen autodiff benchmarks
27183d661 Allow LocalParameterizations to have zero local size.
7ac7d79dc Remove HelloWorldCodegen example
8c8738bf8 Add photometric and relative-pose residuals to autodiff benchmarks
9f7fb66d6 Add a constant cost function to the autodiff benchmarks
ab0d373e4 Fix a comment in autodiff.h
27bb99714 Change SVD algorithm in covariance computation.
84fdac38e Add const to GetCovarianceMatrix*
6bde61d6b Add line local parameterization.
2c1c0932e Update documentation in autodiff.h
8904fa488 Inline Jet initialization in Autodiff
18a464d4e Remove an errant CR from local_parameterization.cc
5c85f2179 Use ArraySelector in Autodiff
80477ff07 Add class ArraySelector
e7a30359e Pass kNumResiduals to Autodiff
f339d71dd Refactor the automatic differentiation benchmarks.
d37b4cb15 Fix some include headers in codegen/test_utils.cc/h
550766e6d Add Autodiff Brdf Benchmark
8da9876e7 Add more autodiff benchmarks
6da364713 Fix Tukey loss function
cf4185c4e Add Codegen BA Benchmark
75dd30fae Simplify GenerateCodeForFunctor
9049688c6 Default Initialize ExpressionRef to Zero
bf1aff2f0 Fix 3+ nested Jet constructor
92d6541c7 Move Codegen files into codegen/ directory
8e962f37d Add Autodiff Codegen Tests
13c7a22ce Codegen Optimizer API
90799e29e Fix install and unnecessary string copy
032d5844c AutoDiff Code Generation - CMake Integration
d82de91b8 Add ExpressionGraph::Erase(ExpressionId)
c8e35e19f Add namespaces to generated functions and constants
75e575cae Fix use of incomplete type in defaulted Problem methods
8def19616 Remove ExpressionRef Move Constructor
f26f95410 Fix windows MSVC build.
fdf9cfd32 Add functions to find the matching ELSE, ENDIF expressions
678c05b28 Fix invert PSD matrix.
a384a7e96 Remove not used using declaration
a60136b7a Add COMMENT ExpressionType
f212c9295 Let Problem::SetParameterization be called more than once.
a3696835b use CMake function to create CeresConfigVersion
67fcff918 Make Problem movable.
19728e72d Add documentation for Problem::IsParameterBlockConstant
ba6e5fb4a Make the custom uninstall target optional
8547cbd55 Make EventLogger more efficient.
edb8322bd Update the minimum required version of Eigen to 3.3.
aa6ef417f Specify Eigen3_DIR in iOS and Android Travis CI builds
4655f2549 Use find_package() instead of find_dependency() in CeresConfig.cmake
a548766d1 Use glfags target
33dd469a5 Use Eigen3::Eigen target
47e784bb4 NULL-jacobians are handled correctly in generated autodiff code
edd54b83e Update Jet.h and rotation.h to use the new IF/ELSE macros
848c1f90c Update return type in code generator and add tests for logical functions
5010421bb Add the expression return type as a member to Expression
f4dc670ee Improve testing of the codegen system
572ec4a5a Rework Expression creation and insertion
c7337154e Disable the code generation module by default
7fa0f3db4 Explicitly state PUBLIC/PRIVATE when linking
4362a2169 Run clang-format on the public headers. Also update copyright year.
c56702aac Fix installation of codegen headers
0d03e74dc Fix the include in the autodiff codegen example
d16026440 Autodiff Codegen Part 4: Public API
d1703db45 Moved AutoDiffCodeGen macros to a separate (public) header
5ce6c063d Fix ExpressionRef copy constructor and add a move constructor
a90b5a12c Pass ExpressionRef by const reference instead of by value
ea057678c Remove MakeFunctionCall() and add test for Ternary
1084c5460 Quote all configure-expanded paths
3d756b07c Test Expressions with 'insert' instead of a macro
486d81812 Add ExpressionGraph::InsertExpression
3831a1dd3 Expression and ExpressionGraph comparison
9bb1dcb84 Remove definition of ExpressionRef::ExpressionRef(double&);
5be2e4883 Autodiff Codegen Part 3: CodeGenerator
6cd633043 Remove unused ExpressionTypes
7d0d69a4d Fix ExpressionRef
6ba8c57d2 Fix expression_test IsArithmetic
2b494cfb3 Update Travis CI to Bionic & Xcode 11.2
a3dde6877 Require Xcode >= 11.2 on macOS 10.15 (Catalina)
6fd4f072d Autodiff Codegen Part 2: Conditionals
52d6477a4 Detect and disable -fstack-check on macOS 10.15 with Xcode 11
46ca461b7 Fix `gradient_check_relative_precision` docs typo
4247d420f Autodiff Codegen Part 1: Expressions
ba62397d8 Run clang-format on jet.h
667062dcc Introduce BlockSparseMatrixData
17becf461 Remove a CHECK failure from covariance_impl.cc
d7f428e5c Add a missing cast in rotation.h
ea4d66e7e clang-tidy fixes.
be15b842a Integrate the SchurEliminatorForOneFBlock for the case <2,3,6>
087b28f1b Remove use of SetUsage as it creates compilation problems.
573046d7f Protect declarations of lapack functions under CERES_NO_LAPACK
71d638ef3 Add a specialized schur eliminator.
2ffddaccf Use override & final instead of just using virtual.
e4577dd6d Use override instead of virtual for subclasses.
3e5db5bc2 Fixing documentation typo.
82d325b73 Avoid memory allocations in Accelerate Sparse[Refactor/Solve]().
f66b51382 Fix some clang-tidy warnings.
0428e2dd0 Fix missing #include of <memory>
487c1aa51 Expose SubsetPreconditioner in the API
bf709ecac Move EvaluationCallback from Solver::Options to Problem::Options.
059bcb7f8 Drop ROS dependency on catkin
c4dbc927d Default to any other sparse libraries over Accelerate
db1f5b57a Allow some methods in Problem to use const double*.
a60c14525 Explicitly delete the copy constructor and copy assignment operator
084042c25 Lint changes from William Rucklidge
93d869020 Use selfAdjoingView<Upper> in InvertPSDMatrix.
a0cd0854a Speed up InvertPSDMatrix
7b53262b7 Allow Solver::Options::max_num_line_search_step_size_iterations = 0.
3e2cdca54 Make LineSearchMinizer work correctly with negative valued functions.
3ff12a878 Fix a clang-tidy warning in problem_test.cc
57441fe90 Fix two bugs.
1b852c57e Add Problem::EvaluateResidualBlock.
54ba6c27b Fix missing declaration warnings in Ceres code
fac46d50e Modernize ProductParameterization.
53dc6213f Add some missing string-to-enum-to-string convertors.
c0aa9a263 Add checks in rotation.h for inplace operations.
0f57fa82d Update Bazel WORKSPACE for newest Bazel
f8e5fba7b TripletSparseMatrix: guard against self-assignment
939253c20 Fix Eigen alignment issues.
bf67daf79 Add the missing <array> header to fixed_array.h
25e1cdbb6 Switch to FixedArray implementation from abseil.
d467a627b IdentityTransformation -> IdentityParameterization
eaec6a9d0 Fix more typos in CostFunctionToFunctor documentation.
99b5aa4aa Fix typos in CostFunctionToFunctor documentation.
ee7e2cb3c Set Homebrew paths via HINTS not CMAKE_PREFIX_PATH
4f8a01853 Revert "Fix custom Eigen on macos (EIGEN_INCLUDE_DIR_HINTS)"
e6c5c7226 Fix custom Eigen on macos (EIGEN_INCLUDE_DIR_HINTS)
5a56d522e Add the 3,3,3 template specialization.
df5c23116 Reorder initializer list to make -Wreorder happy
0fcfdb0b4 Fix the build breakage caused by the last commit.
9b9e9f0dc Reduce machoness of macro definition in cost_functor_to_function_test.cc
21d40daa0 Remove UTF-8 chars
9350e57a4 Enable optional use of sanitizers
0456edffb Update Travis CI Linux distro to 16.04 (Xenial)
bef0dfe35 Fix a typo in cubic_interpolation.h
056ba9bb1 Add AutoDiffFirstOrderFunction
6e527392d Update googletest/googlemock to db9b85e2.
1b2940749 Clarify documentation of BiCubicInterpolator::Evaluate for out-of-bounds values
Change-Id: Id61dd832e8fbe286deb0799aa1399d4017031dae
git-subtree-dir: third_party/ceres
git-subtree-split: 399cda773035d99eaf1f4a129a666b3c4df9d1b1
diff --git a/internal/ceres/autodiff_benchmarks/CMakeLists.txt b/internal/ceres/autodiff_benchmarks/CMakeLists.txt
new file mode 100644
index 0000000..610ebc3
--- /dev/null
+++ b/internal/ceres/autodiff_benchmarks/CMakeLists.txt
@@ -0,0 +1,17 @@
+# TODO: Add support for other compilers
+if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
+ # Increase the inlining threshold only for those functions marked with an
+ # inline hint. This is typically far more realistic to significantly increase
+ # in a large code-base than -inline-threshold as that has a larger scope.
+ list(APPEND CERES_BENCHMARK_FLAGS "-mllvm" "-inlinehint-threshold=1000000")
+endif()
+
+add_executable(autodiff_benchmarks autodiff_benchmarks.cc)
+add_dependencies_to_benchmark(autodiff_benchmarks)
+target_compile_options(autodiff_benchmarks PRIVATE ${CERES_BENCHMARK_FLAGS})
+
+# All other flags + fast-math
+list(APPEND CERES_BENCHMARK_FAST_MATH_FLAGS ${CERES_BENCHMARK_FLAGS} "-ffast-math")
+add_executable(autodiff_benchmarks_fast_math autodiff_benchmarks.cc)
+add_dependencies_to_benchmark(autodiff_benchmarks_fast_math)
+target_compile_options(autodiff_benchmarks_fast_math PRIVATE ${CERES_BENCHMARK_FAST_MATH_FLAGS})
diff --git a/internal/ceres/autodiff_benchmarks/autodiff_benchmarks.cc b/internal/ceres/autodiff_benchmarks/autodiff_benchmarks.cc
new file mode 100644
index 0000000..87e0067
--- /dev/null
+++ b/internal/ceres/autodiff_benchmarks/autodiff_benchmarks.cc
@@ -0,0 +1,430 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2020 Google Inc. All rights reserved.
+// http://ceres-solver.org/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// * Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: darius.rueckert@fau.de (Darius Rueckert)
+
+#include <memory>
+#include <random>
+#include <utility>
+
+#include "benchmark/benchmark.h"
+#include "ceres/autodiff_benchmarks/brdf_cost_function.h"
+#include "ceres/autodiff_benchmarks/constant_cost_function.h"
+#include "ceres/autodiff_benchmarks/linear_cost_functions.h"
+#include "ceres/autodiff_benchmarks/photometric_error.h"
+#include "ceres/autodiff_benchmarks/relative_pose_error.h"
+#include "ceres/autodiff_benchmarks/snavely_reprojection_error.h"
+#include "ceres/ceres.h"
+
+namespace ceres {
+
+enum Dynamic { kNotDynamic, kDynamic };
+
+// Transforms a static functor into a dynamic one.
+template <typename CostFunctionType, int kNumParameterBlocks>
+class ToDynamic {
+ public:
+ template <typename... _Args>
+ explicit ToDynamic(_Args&&... __args)
+ : cost_function_(std::forward<_Args>(__args)...) {}
+
+ template <typename T>
+ bool operator()(const T* const* parameters, T* residuals) const {
+ return Apply(
+ parameters, residuals, std::make_index_sequence<kNumParameterBlocks>());
+ }
+
+ private:
+ template <typename T, size_t... Indices>
+ bool Apply(const T* const* parameters,
+ T* residuals,
+ std::index_sequence<Indices...>) const {
+ return cost_function_(parameters[Indices]..., residuals);
+ }
+
+ CostFunctionType cost_function_;
+};
+
+template <int kParameterBlockSize>
+static void BM_ConstantAnalytic(benchmark::State& state) {
+ constexpr int num_residuals = 1;
+ std::array<double, kParameterBlockSize> parameters_values;
+ std::iota(parameters_values.begin(), parameters_values.end(), 0);
+ double* parameters[] = {parameters_values.data()};
+
+ std::array<double, num_residuals> residuals;
+
+ std::array<double, num_residuals * kParameterBlockSize> jacobian_values;
+ double* jacobians[] = {jacobian_values.data()};
+
+ std::unique_ptr<ceres::CostFunction> cost_function(
+ new AnalyticConstantCostFunction<kParameterBlockSize>());
+
+ for (auto _ : state) {
+ cost_function->Evaluate(parameters, residuals.data(), jacobians);
+ }
+}
+
+// Helpers for CostFunctionFactory.
+template <typename DynamicCostFunctionType>
+void AddParameterBlocks(DynamicCostFunctionType*) {}
+
+template <int HeadN, int... TailNs, typename DynamicCostFunctionType>
+void AddParameterBlocks(DynamicCostFunctionType* dynamic_function) {
+ dynamic_function->AddParameterBlock(HeadN);
+ AddParameterBlocks<TailNs...>(dynamic_function);
+}
+
+// Creates an autodiff cost function wrapping `CostFunctor`, with
+// `kNumResiduals` residuals and parameter blocks with sized `Ns..`.
+// Depending on `kIsDynamic`, either a static or dynamic cost function is
+// created.
+// `args` are forwarded to the `CostFunctor` constructor.
+template <Dynamic kIsDynamic>
+struct CostFunctionFactory {};
+
+template <>
+struct CostFunctionFactory<kNotDynamic> {
+ template <typename CostFunctor,
+ int kNumResiduals,
+ int... Ns,
+ typename... Args>
+ static std::unique_ptr<ceres::CostFunction> Create(Args&&... args) {
+ return std::make_unique<
+ ceres::AutoDiffCostFunction<CostFunctor, kNumResiduals, Ns...>>(
+ new CostFunctor(std::forward<Args>(args)...));
+ }
+};
+
+template <>
+struct CostFunctionFactory<kDynamic> {
+ template <typename CostFunctor,
+ int kNumResiduals,
+ int... Ns,
+ typename... Args>
+ static std::unique_ptr<ceres::CostFunction> Create(Args&&... args) {
+ constexpr const int kNumParameterBlocks = sizeof...(Ns);
+ auto dynamic_function = std::make_unique<ceres::DynamicAutoDiffCostFunction<
+ ToDynamic<CostFunctor, kNumParameterBlocks>>>(
+ new ToDynamic<CostFunctor, kNumParameterBlocks>(
+ std::forward<Args>(args)...));
+ dynamic_function->SetNumResiduals(kNumResiduals);
+ AddParameterBlocks<Ns...>(dynamic_function.get());
+ return dynamic_function;
+ }
+};
+
+template <int kParameterBlockSize, Dynamic kIsDynamic>
+static void BM_ConstantAutodiff(benchmark::State& state) {
+ constexpr int num_residuals = 1;
+ std::array<double, kParameterBlockSize> parameters_values;
+ std::iota(parameters_values.begin(), parameters_values.end(), 0);
+ double* parameters[] = {parameters_values.data()};
+
+ std::array<double, num_residuals> residuals;
+
+ std::array<double, num_residuals * kParameterBlockSize> jacobian_values;
+ double* jacobians[] = {jacobian_values.data()};
+
+ std::unique_ptr<ceres::CostFunction> cost_function =
+ CostFunctionFactory<kIsDynamic>::
+ template Create<ConstantCostFunction<kParameterBlockSize>, 1, 1>();
+
+ for (auto _ : state) {
+ cost_function->Evaluate(parameters, residuals.data(), jacobians);
+ }
+}
+
+BENCHMARK_TEMPLATE(BM_ConstantAnalytic, 1);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 1, kNotDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 1, kDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAnalytic, 10);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 10, kNotDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 10, kDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAnalytic, 20);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 20, kNotDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 20, kDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAnalytic, 30);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 30, kNotDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 30, kDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAnalytic, 40);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 40, kNotDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 40, kDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAnalytic, 50);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 50, kNotDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 50, kDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAnalytic, 60);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 60, kNotDynamic);
+BENCHMARK_TEMPLATE(BM_ConstantAutodiff, 60, kDynamic);
+
+template <Dynamic kIsDynamic>
+static void BM_Linear1AutoDiff(benchmark::State& state) {
+ double parameter_block1[] = {1.};
+ double* parameters[] = {parameter_block1};
+
+ double jacobian1[1];
+ double residuals[1];
+ double* jacobians[] = {jacobian1};
+
+ std::unique_ptr<ceres::CostFunction> cost_function = CostFunctionFactory<
+ kIsDynamic>::template Create<Linear1CostFunction, 1, 1>();
+
+ for (auto _ : state) {
+ cost_function->Evaluate(
+ parameters, residuals, state.range(0) ? jacobians : nullptr);
+ }
+}
+BENCHMARK_TEMPLATE(BM_Linear1AutoDiff, kNotDynamic)->Arg(0)->Arg(1);
+BENCHMARK_TEMPLATE(BM_Linear1AutoDiff, kDynamic)->Arg(0)->Arg(1);
+
+template <Dynamic kIsDynamic>
+static void BM_Linear10AutoDiff(benchmark::State& state) {
+ double parameter_block1[] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.};
+ double* parameters[] = {parameter_block1};
+
+ double jacobian1[10 * 10];
+ double residuals[10];
+ double* jacobians[] = {jacobian1};
+
+ std::unique_ptr<ceres::CostFunction> cost_function = CostFunctionFactory<
+ kIsDynamic>::template Create<Linear10CostFunction, 10, 10>();
+
+ for (auto _ : state) {
+ cost_function->Evaluate(
+ parameters, residuals, state.range(0) ? jacobians : nullptr);
+ }
+}
+BENCHMARK_TEMPLATE(BM_Linear10AutoDiff, kNotDynamic)->Arg(0)->Arg(1);
+BENCHMARK_TEMPLATE(BM_Linear10AutoDiff, kDynamic)->Arg(0)->Arg(1);
+
+// From the NIST problem collection.
+struct Rat43CostFunctor {
+ Rat43CostFunctor(const double x, const double y) : x_(x), y_(y) {}
+
+ template <typename T>
+ inline bool operator()(const T* parameters, T* residuals) const {
+ const T& b1 = parameters[0];
+ const T& b2 = parameters[1];
+ const T& b3 = parameters[2];
+ const T& b4 = parameters[3];
+ residuals[0] = b1 * pow(1.0 + exp(b2 - b3 * x_), -1.0 / b4) - y_;
+ return true;
+ }
+
+ static constexpr int kNumParameterBlocks = 1;
+
+ private:
+ const double x_;
+ const double y_;
+};
+
+template <Dynamic kIsDynamic>
+static void BM_Rat43AutoDiff(benchmark::State& state) {
+ double parameter_block1[] = {1., 2., 3., 4.};
+ double* parameters[] = {parameter_block1};
+
+ double jacobian1[] = {0.0, 0.0, 0.0, 0.0};
+ double residuals;
+ double* jacobians[] = {jacobian1};
+ const double x = 0.2;
+ const double y = 0.3;
+ std::unique_ptr<ceres::CostFunction> cost_function =
+ CostFunctionFactory<kIsDynamic>::template Create<Rat43CostFunctor, 1, 4>(
+ x, y);
+
+ for (auto _ : state) {
+ cost_function->Evaluate(
+ parameters, &residuals, state.range(0) ? jacobians : nullptr);
+ }
+}
+BENCHMARK_TEMPLATE(BM_Rat43AutoDiff, kNotDynamic)->Arg(0)->Arg(1);
+BENCHMARK_TEMPLATE(BM_Rat43AutoDiff, kDynamic)->Arg(0)->Arg(1);
+
+template <Dynamic kIsDynamic>
+static void BM_SnavelyReprojectionAutoDiff(benchmark::State& state) {
+ double parameter_block1[] = {1., 2., 3., 4., 5., 6., 7., 8., 9.};
+ double parameter_block2[] = {1., 2., 3.};
+ double* parameters[] = {parameter_block1, parameter_block2};
+
+ double jacobian1[2 * 9];
+ double jacobian2[2 * 3];
+ double residuals[2];
+ double* jacobians[] = {jacobian1, jacobian2};
+
+ const double x = 0.2;
+ const double y = 0.3;
+ std::unique_ptr<ceres::CostFunction> cost_function = CostFunctionFactory<
+ kIsDynamic>::template Create<SnavelyReprojectionError, 2, 9, 3>(x, y);
+
+ for (auto _ : state) {
+ cost_function->Evaluate(
+ parameters, residuals, state.range(0) ? jacobians : nullptr);
+ }
+}
+
+BENCHMARK_TEMPLATE(BM_SnavelyReprojectionAutoDiff, kNotDynamic)->Arg(0)->Arg(1);
+BENCHMARK_TEMPLATE(BM_SnavelyReprojectionAutoDiff, kDynamic)->Arg(0)->Arg(1);
+
+template <Dynamic kIsDynamic>
+static void BM_PhotometricAutoDiff(benchmark::State& state) {
+ constexpr int PATCH_SIZE = 8;
+
+ using FunctorType = PhotometricError<PATCH_SIZE>;
+ using ImageType = Eigen::Matrix<uint8_t, 128, 128, Eigen::RowMajor>;
+
+ // Prepare parameter / residual / jacobian blocks.
+ double parameter_block1[] = {1., 2., 3., 4., 5., 6., 7.};
+ double parameter_block2[] = {1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1};
+ double parameter_block3[] = {1.};
+ double* parameters[] = {parameter_block1, parameter_block2, parameter_block3};
+
+ Eigen::Map<Eigen::Quaterniond>(parameter_block1).normalize();
+ Eigen::Map<Eigen::Quaterniond>(parameter_block2).normalize();
+
+ double jacobian1[FunctorType::PATCH_SIZE * FunctorType::POSE_SIZE];
+ double jacobian2[FunctorType::PATCH_SIZE * FunctorType::POSE_SIZE];
+ double jacobian3[FunctorType::PATCH_SIZE * FunctorType::POINT_SIZE];
+ double residuals[FunctorType::PATCH_SIZE];
+ double* jacobians[] = {jacobian1, jacobian2, jacobian3};
+
+ // Prepare data (fixed seed for repeatability).
+ std::mt19937::result_type seed = 42;
+ std::mt19937 gen(seed);
+ std::uniform_real_distribution<double> uniform01(0.0, 1.0);
+ std::uniform_int_distribution<unsigned int> uniform0255(0, 255);
+
+ FunctorType::Patch<double> intensities_host =
+ FunctorType::Patch<double>::NullaryExpr(
+ [&]() { return uniform0255(gen); });
+
+ // Set bearing vector's z component to 1, i.e. pointing away from the camera,
+ // to ensure they are (likely) in the domain of the projection function (given
+ // a small rotation between host and target frame).
+ FunctorType::PatchVectors<double> bearings_host =
+ FunctorType::PatchVectors<double>::NullaryExpr(
+ [&]() { return uniform01(gen); });
+ bearings_host.row(2).array() = 1;
+ bearings_host.colwise().normalize();
+
+ ImageType image = ImageType::NullaryExpr(
+ [&]() { return static_cast<uint8_t>(uniform0255(gen)); });
+ FunctorType::Grid grid(image.data(), 0, image.rows(), 0, image.cols());
+ FunctorType::Interpolator image_target(grid);
+
+ FunctorType::Intrinsics intrinsics;
+ intrinsics << 128, 128, 1, -1, 0.5, 0.5;
+
+ std::unique_ptr<ceres::CostFunction> cost_function =
+ CostFunctionFactory<kIsDynamic>::template Create<FunctorType,
+ FunctorType::PATCH_SIZE,
+ FunctorType::POSE_SIZE,
+ FunctorType::POSE_SIZE,
+ FunctorType::POINT_SIZE>(
+ intensities_host, bearings_host, image_target, intrinsics);
+
+ for (auto _ : state) {
+ cost_function->Evaluate(
+ parameters, residuals, state.range(0) ? jacobians : nullptr);
+ }
+}
+
+BENCHMARK_TEMPLATE(BM_PhotometricAutoDiff, kNotDynamic)->Arg(0)->Arg(1);
+BENCHMARK_TEMPLATE(BM_PhotometricAutoDiff, kDynamic)->Arg(0)->Arg(1);
+
+template <Dynamic kIsDynamic>
+static void BM_RelativePoseAutoDiff(benchmark::State& state) {
+ using FunctorType = RelativePoseError;
+
+ double parameter_block1[] = {1., 2., 3., 4., 5., 6., 7.};
+ double parameter_block2[] = {1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1};
+ double* parameters[] = {parameter_block1, parameter_block2};
+
+ Eigen::Map<Eigen::Quaterniond>(parameter_block1).normalize();
+ Eigen::Map<Eigen::Quaterniond>(parameter_block2).normalize();
+
+ double jacobian1[6 * 7];
+ double jacobian2[6 * 7];
+ double residuals[6];
+ double* jacobians[] = {jacobian1, jacobian2};
+
+ Eigen::Quaterniond q_i_j = Eigen::Quaterniond(1, 2, 3, 4).normalized();
+ Eigen::Vector3d t_i_j(1, 2, 3);
+
+ std::unique_ptr<ceres::CostFunction> cost_function =
+ CostFunctionFactory<kIsDynamic>::template Create<FunctorType, 6, 7, 7>(
+ q_i_j, t_i_j);
+
+ for (auto _ : state) {
+ cost_function->Evaluate(
+ parameters, residuals, state.range(0) ? jacobians : nullptr);
+ }
+}
+
+BENCHMARK_TEMPLATE(BM_RelativePoseAutoDiff, kNotDynamic)->Arg(0)->Arg(1);
+BENCHMARK_TEMPLATE(BM_RelativePoseAutoDiff, kDynamic)->Arg(0)->Arg(1);
+
+template <Dynamic kIsDynamic>
+static void BM_BrdfAutoDiff(benchmark::State& state) {
+ using FunctorType = Brdf;
+
+ double material[] = {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.};
+ auto c = Eigen::Vector3d(0.1, 0.2, 0.3);
+ auto n = Eigen::Vector3d(-0.1, 0.5, 0.2).normalized();
+ auto v = Eigen::Vector3d(0.5, -0.2, 0.9).normalized();
+ auto l = Eigen::Vector3d(-0.3, 0.4, -0.3).normalized();
+ auto x = Eigen::Vector3d(0.5, 0.7, -0.1).normalized();
+ auto y = Eigen::Vector3d(0.2, -0.2, -0.2).normalized();
+
+ double* parameters[7] = {
+ material, c.data(), n.data(), v.data(), l.data(), x.data(), y.data()};
+
+ double jacobian[(10 + 6 * 3) * 3];
+ double residuals[3];
+ // clang-format off
+ double* jacobians[7] = {
+ jacobian + 0, jacobian + 10 * 3, jacobian + 13 * 3,
+ jacobian + 16 * 3, jacobian + 19 * 3, jacobian + 22 * 3,
+ jacobian + 25 * 3,
+ };
+ // clang-format on
+
+ std::unique_ptr<ceres::CostFunction> cost_function = CostFunctionFactory<
+ kIsDynamic>::template Create<FunctorType, 3, 10, 3, 3, 3, 3, 3, 3>();
+
+ for (auto _ : state) {
+ cost_function->Evaluate(
+ parameters, residuals, state.range(0) ? jacobians : nullptr);
+ }
+}
+
+BENCHMARK_TEMPLATE(BM_BrdfAutoDiff, kNotDynamic)->Arg(0)->Arg(1);
+BENCHMARK_TEMPLATE(BM_BrdfAutoDiff, kDynamic)->Arg(0)->Arg(1);
+
+} // namespace ceres
+
+BENCHMARK_MAIN();
diff --git a/internal/ceres/autodiff_benchmarks/brdf_cost_function.h b/internal/ceres/autodiff_benchmarks/brdf_cost_function.h
new file mode 100644
index 0000000..9d7c0cc
--- /dev/null
+++ b/internal/ceres/autodiff_benchmarks/brdf_cost_function.h
@@ -0,0 +1,223 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2020 Google Inc. All rights reserved.
+// http://ceres-solver.org/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// * Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: darius.rueckert@fau.de (Darius Rueckert)
+//
+//
+#ifndef CERES_INTERNAL_AUTODIFF_BENCHMARK_BRDF_COST_FUNCTION_H_
+#define CERES_INTERNAL_AUTODIFF_BENCHMARK_BRDF_COST_FUNCTION_H_
+
+#include <Eigen/Core>
+#include <cmath>
+
+namespace ceres {
+
+// The brdf is based on:
+// Burley, Brent, and Walt Disney Animation Studios. "Physically-based shading
+// at disney." ACM SIGGRAPH. Vol. 2012. 2012.
+//
+// The implementation is based on:
+// https://github.com/wdas/brdf/blob/master/src/brdfs/disney.brdf
+struct Brdf {
+ public:
+ Brdf() {}
+
+ template <typename T>
+ inline bool operator()(const T* const material,
+ const T* const c_ptr,
+ const T* const n_ptr,
+ const T* const v_ptr,
+ const T* const l_ptr,
+ const T* const x_ptr,
+ const T* const y_ptr,
+ T* residual) const {
+ using Vec3 = Eigen::Matrix<T, 3, 1>;
+
+ T metallic = material[0];
+ T subsurface = material[1];
+ T specular = material[2];
+ T roughness = material[3];
+ T specular_tint = material[4];
+ T anisotropic = material[5];
+ T sheen = material[6];
+ T sheen_tint = material[7];
+ T clearcoat = material[8];
+ T clearcoat_gloss = material[9];
+
+ Eigen::Map<const Vec3> c(c_ptr);
+ Eigen::Map<const Vec3> n(n_ptr);
+ Eigen::Map<const Vec3> v(v_ptr);
+ Eigen::Map<const Vec3> l(l_ptr);
+ Eigen::Map<const Vec3> x(x_ptr);
+ Eigen::Map<const Vec3> y(y_ptr);
+
+ const T n_dot_l = n.dot(l);
+ const T n_dot_v = n.dot(v);
+
+ const Vec3 l_p_v = l + v;
+ const Vec3 h = l_p_v / l_p_v.norm();
+
+ const T n_dot_h = n.dot(h);
+ const T l_dot_h = l.dot(h);
+
+ const T h_dot_x = h.dot(x);
+ const T h_dot_y = h.dot(y);
+
+ const T c_dlum = T(0.3) * c[0] + T(0.6) * c[1] + T(0.1) * c[2];
+
+ const Vec3 c_tint = c / c_dlum;
+
+ const Vec3 c_spec0 =
+ Lerp(specular * T(0.08) *
+ Lerp(Vec3(T(1), T(1), T(1)), c_tint, specular_tint),
+ c,
+ metallic);
+ const Vec3 c_sheen = Lerp(Vec3(T(1), T(1), T(1)), c_tint, sheen_tint);
+
+ // Diffuse fresnel - go from 1 at normal incidence to .5 at grazing
+ // and mix in diffuse retro-reflection based on roughness
+ const T fl = SchlickFresnel(n_dot_l);
+ const T fv = SchlickFresnel(n_dot_v);
+ const T fd_90 = T(0.5) + T(2) * l_dot_h * l_dot_h * roughness;
+ const T fd = Lerp(T(1), fd_90, fl) * Lerp(T(1), fd_90, fv);
+
+ // Based on Hanrahan-Krueger brdf approximation of isotropic bssrdf
+ // 1.25 scale is used to (roughly) preserve albedo
+ // Fss90 used to "flatten" retroreflection based on roughness
+ const T fss_90 = l_dot_h * l_dot_h * roughness;
+ const T fss = Lerp(T(1), fss_90, fl) * Lerp(T(1), fss_90, fv);
+ const T ss =
+ T(1.25) * (fss * (T(1) / (n_dot_l + n_dot_v) - T(0.5)) + T(0.5));
+
+ // specular
+ const T eps = T(0.001);
+ const T aspct = Aspect(anisotropic);
+ const T ax_temp = Square(roughness) / aspct;
+ const T ay_temp = Square(roughness) * aspct;
+ const T ax = (ax_temp < eps ? eps : ax_temp);
+ const T ay = (ay_temp < eps ? eps : ay_temp);
+ const T ds = GTR2Aniso(n_dot_h, h_dot_x, h_dot_y, ax, ay);
+ const T fh = SchlickFresnel(l_dot_h);
+ const Vec3 fs = Lerp(c_spec0, Vec3(T(1), T(1), T(1)), fh);
+ const T roughg = Square(roughness * T(0.5) + T(0.5));
+ const T ggxn_dot_l = SmithG_GGX(n_dot_l, roughg);
+ const T ggxn_dot_v = SmithG_GGX(n_dot_v, roughg);
+ const T gs = ggxn_dot_l * ggxn_dot_v;
+
+ // sheen
+ const Vec3 f_sheen = fh * sheen * c_sheen;
+
+ // clearcoat (ior = 1.5 -> F0 = 0.04)
+ const T a = Lerp(T(0.1), T(0.001), clearcoat_gloss);
+ const T dr = GTR1(n_dot_h, a);
+ const T fr = Lerp(T(0.04), T(1), fh);
+ const T cggxn_dot_l = SmithG_GGX(n_dot_l, T(0.25));
+ const T cggxn_dot_v = SmithG_GGX(n_dot_v, T(0.25));
+ const T gr = cggxn_dot_l * cggxn_dot_v;
+
+ const Vec3 result_no_cosine =
+ (T(1.0 / M_PI) * Lerp(fd, ss, subsurface) * c + f_sheen) *
+ (T(1) - metallic) +
+ gs * fs * ds +
+ Vec3(T(0.25), T(0.25), T(0.25)) * clearcoat * gr * fr * dr;
+ const Vec3 result = n_dot_l * result_no_cosine;
+ residual[0] = result(0);
+ residual[1] = result(1);
+ residual[2] = result(2);
+
+ return true;
+ }
+
+ template <typename T>
+ inline T SchlickFresnel(const T& u) const {
+ T m = T(1) - u;
+ const T m2 = m * m;
+ return m2 * m2 * m; // (1-u)^5
+ }
+
+ template <typename T>
+ inline T Aspect(const T& anisotropic) const {
+ return T(sqrt(T(1) - anisotropic * T(0.9)));
+ }
+
+ template <typename T>
+ inline T SmithG_GGX(const T& n_dot_v, const T& alpha_g) const {
+ const T a = alpha_g * alpha_g;
+ const T b = n_dot_v * n_dot_v;
+ return T(1) / (n_dot_v + T(sqrt(a + b - a * b)));
+ }
+
+ // Generalized-Trowbridge-Reitz (GTR) Microfacet Distribution
+ // See paper, Appendix B
+ template <typename T>
+ inline T GTR1(const T& n_dot_h, const T& a) const {
+ T result = T(0);
+
+ if (a >= T(1)) {
+ result = T(1 / M_PI);
+ } else {
+ const T a2 = a * a;
+ const T t = T(1) + (a2 - T(1)) * n_dot_h * n_dot_h;
+ result = (a2 - T(1)) / (T(M_PI) * T(log(a2) * t));
+ }
+ return result;
+ }
+
+ template <typename T>
+ inline T GTR2Aniso(const T& n_dot_h,
+ const T& h_dot_x,
+ const T& h_dot_y,
+ const T& ax,
+ const T& ay) const {
+ return T(1) / (T(M_PI) * ax * ay *
+ Square(Square(h_dot_x / ax) + Square(h_dot_y / ay) +
+ n_dot_h * n_dot_h));
+ }
+
+ template <typename T>
+ inline T Lerp(const T& a, const T& b, const T& u) const {
+ return a + u * (b - a);
+ }
+
+ template <typename Derived1, typename Derived2>
+ inline typename Derived1::PlainObject Lerp(
+ const Eigen::MatrixBase<Derived1>& a,
+ const Eigen::MatrixBase<Derived2>& b,
+ typename Derived1::Scalar alpha) const {
+ return (typename Derived1::Scalar(1) - alpha) * a + alpha * b;
+ }
+
+ template <typename T>
+ inline T Square(const T& x) const {
+ return x * x;
+ }
+};
+
+} // namespace ceres
+
+#endif // CERES_INTERNAL_AUTODIFF_BENCHMARK_BRDF_COST_FUNCTION_H_
diff --git a/internal/ceres/autodiff_benchmarks/constant_cost_function.h b/internal/ceres/autodiff_benchmarks/constant_cost_function.h
new file mode 100644
index 0000000..2bbe4cb
--- /dev/null
+++ b/internal/ceres/autodiff_benchmarks/constant_cost_function.h
@@ -0,0 +1,66 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2020 Google Inc. All rights reserved.
+// http://ceres-solver.org/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// * Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: darius.rueckert@fau.de (Darius Rueckert)
+//
+//
+#ifndef CERES_INTERNAL_AUTODIFF_BENCHMARKS_CONSTANT_COST_FUNCTIONS_H_
+#define CERES_INTERNAL_AUTODIFF_BENCHMARKS_CONSTANT_COST_FUNCTIONS_H_
+
+#include "ceres/sized_cost_function.h"
+
+namespace ceres {
+
+template <int kParameterBlockSize>
+struct ConstantCostFunction {
+ template <typename T>
+ inline bool operator()(const T* const x, T* residuals) const {
+ residuals[0] = T(5);
+ return true;
+ }
+};
+
+template <int kParameterBlockSize>
+struct AnalyticConstantCostFunction
+ : public ceres::SizedCostFunction<1, kParameterBlockSize> {
+ virtual bool Evaluate(double const* const* parameters,
+ double* residuals,
+ double** jacobians) const {
+ residuals[0] = 5.0;
+ if (jacobians) {
+ if (jacobians[0]) {
+ memset(jacobians[0], 0, sizeof(double) * kParameterBlockSize);
+ }
+ }
+ return true;
+ }
+};
+
+} // namespace ceres
+
+#endif // CERES_INTERNAL_AUTODIFF_BENCHMARKS_CONSTANT_COST_FUNCTIONS_H_
diff --git a/internal/ceres/autodiff_benchmarks/linear_cost_functions.h b/internal/ceres/autodiff_benchmarks/linear_cost_functions.h
new file mode 100644
index 0000000..2f2552f
--- /dev/null
+++ b/internal/ceres/autodiff_benchmarks/linear_cost_functions.h
@@ -0,0 +1,58 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2020 Google Inc. All rights reserved.
+// http://ceres-solver.org/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// * Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: darius.rueckert@fau.de (Darius Rueckert)
+//
+//
+#ifndef CERES_INTERNAL_AUTODIFF_BENCHMARKS_LINEAR_COST_FUNCTIONS_H_
+#define CERES_INTERNAL_AUTODIFF_BENCHMARKS_LINEAR_COST_FUNCTIONS_H_
+
+#include "ceres/rotation.h"
+
+namespace ceres {
+
+struct Linear1CostFunction {
+ template <typename T>
+ inline bool operator()(const T* const x, T* residuals) const {
+ residuals[0] = x[0] + T(10);
+ return true;
+ }
+};
+
+struct Linear10CostFunction {
+ template <typename T>
+ inline bool operator()(const T* const x, T* residuals) const {
+ for (int i = 0; i < 10; ++i) {
+ residuals[i] = x[i] + T(i);
+ }
+ return true;
+ }
+};
+} // namespace ceres
+
+#endif // CERES_INTERNAL_AUTODIFF_BENCHMARKS_LINEAR_COST_FUNCTIONS_H_
diff --git a/internal/ceres/autodiff_benchmarks/photometric_error.h b/internal/ceres/autodiff_benchmarks/photometric_error.h
new file mode 100644
index 0000000..8ed278d
--- /dev/null
+++ b/internal/ceres/autodiff_benchmarks/photometric_error.h
@@ -0,0 +1,191 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2020 Google Inc. All rights reserved.
+// http://ceres-solver.org/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// * Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: nikolaus@nikolaus-demmel.de (Nikolaus Demmel)
+//
+//
+#ifndef CERES_INTERNAL_AUTODIFF_BENCHMARK_PHOTOMETRIC_ERROR_H_
+#define CERES_INTERNAL_AUTODIFF_BENCHMARK_PHOTOMETRIC_ERROR_H_
+
+#include <Eigen/Dense>
+
+#include "ceres/cubic_interpolation.h"
+
+namespace ceres {
+
+// Photometric residual that computes the intensity difference for a patch
+// between host and target frame. The point is parameterized with inverse
+// distance relative to the host frame. The relative pose between host and
+// target frame is computed from their respective absolute poses.
+//
+// The residual is similar to the one defined by Engel et al. [1]. Differences
+// include:
+//
+// 1. Use of a camera model based on spherical projection, namely the enhanced
+// unified camera model [2][3]. This is intended to bring some variability to
+// the benchmark compared to the SnavelyReprojection that uses a
+// polynomial-based distortion model.
+//
+// 2. To match the camera model, inverse distance parameterization is used for
+// points instead of inverse depth [4].
+//
+// 3. For simplicity, camera intrinsics are assumed constant, and thus host
+// frame points are passed as (unprojected) bearing vectors, which avoids the
+// need for an 'unproject' function.
+//
+// 4. Some details of the residual in [1] are omitted for simplicity: The
+// brightness transform parameters [a,b], the constant pre-weight w, and the
+// per-pixel robust norm.
+//
+// [1] J. Engel, V. Koltun and D. Cremers, "Direct Sparse Odometry," in IEEE
+// Transactions on Pattern Analysis and Machine Intelligence, vol. 40, no. 3,
+// pp. 611-625, 1 March 2018.
+//
+// [2] B. Khomutenko, G. Garcia and P. Martinet, "An Enhanced Unified Camera
+// Model," in IEEE Robotics and Automation Letters, vol. 1, no. 1, pp. 137-144,
+// Jan. 2016.
+//
+// [3] V. Usenko, N. Demmel and D. Cremers, "The Double Sphere Camera Model,"
+// 2018 International Conference on 3D Vision (3DV), Verona, 2018, pp. 552-560.
+//
+// [4] H. Matsuki, L. von Stumberg, V. Usenko, J. Stückler and D. Cremers,
+// "Omnidirectional DSO: Direct Sparse Odometry With Fisheye Cameras," in IEEE
+// Robotics and Automation Letters, vol. 3, no. 4, pp. 3693-3700, Oct. 2018.
+template <int PATCH_SIZE_ = 8>
+struct PhotometricError {
+ static constexpr int PATCH_SIZE = PATCH_SIZE_;
+ static constexpr int POSE_SIZE = 7;
+ static constexpr int POINT_SIZE = 1;
+
+ using Grid = Grid2D<uint8_t, 1>;
+ using Interpolator = BiCubicInterpolator<Grid>;
+ using Intrinsics = Eigen::Array<double, 6, 1>;
+
+ template <typename T>
+ using Patch = Eigen::Array<T, PATCH_SIZE, 1>;
+
+ template <typename T>
+ using PatchVectors = Eigen::Matrix<T, 3, PATCH_SIZE>;
+
+ PhotometricError(const Patch<double>& intensities_host,
+ const PatchVectors<double>& bearings_host,
+ const Interpolator& image_target,
+ const Intrinsics& intrinsics)
+ : intensities_host_(intensities_host),
+ bearings_host_(bearings_host),
+ image_target_(image_target),
+ intrinsics_(intrinsics) {}
+
+ template <typename T>
+ inline bool Project(Eigen::Matrix<T, 2, 1>& proj,
+ const Eigen::Matrix<T, 3, 1>& p) const {
+ const double& fx = intrinsics_[0];
+ const double& fy = intrinsics_[1];
+ const double& cx = intrinsics_[2];
+ const double& cy = intrinsics_[3];
+ const double& alpha = intrinsics_[4];
+ const double& beta = intrinsics_[5];
+
+ const T rho2 = beta * (p.x() * p.x() + p.y() * p.y()) + p.z() * p.z();
+ const T rho = sqrt(rho2);
+
+ // Check if 3D point is in domain of projection function.
+ // See (8) and (17) in [3].
+ constexpr double NUMERIC_EPSILON = 1e-10;
+ const double w =
+ alpha > 0.5 ? (1.0 - alpha) / alpha : alpha / (1.0 - alpha);
+ if (p.z() <= -w * rho + NUMERIC_EPSILON) {
+ return false;
+ }
+
+ const T norm = alpha * rho + (1.0 - alpha) * p.z();
+ const T norm_inv = 1.0 / norm;
+
+ const T mx = p.x() * norm_inv;
+ const T my = p.y() * norm_inv;
+
+ proj[0] = fx * mx + cx;
+ proj[1] = fy * my + cy;
+
+ return true;
+ }
+
+ template <typename T>
+ inline bool operator()(const T* const pose_host_ptr,
+ const T* const pose_target_ptr,
+ const T* const idist_ptr,
+ T* residuals_ptr) const {
+ Eigen::Map<const Eigen::Quaternion<T>> q_w_h(pose_host_ptr);
+ Eigen::Map<const Eigen::Matrix<T, 3, 1>> t_w_h(pose_host_ptr + 4);
+ Eigen::Map<const Eigen::Quaternion<T>> q_w_t(pose_target_ptr);
+ Eigen::Map<const Eigen::Matrix<T, 3, 1>> t_w_t(pose_target_ptr + 4);
+ const T& idist = *idist_ptr;
+ Eigen::Map<Patch<T>> residuals(residuals_ptr);
+
+ // Compute relative pose from host to target frame.
+ const Eigen::Quaternion<T> q_t_h = q_w_t.conjugate() * q_w_h;
+ const Eigen::Matrix<T, 3, 3> R_t_h = q_t_h.toRotationMatrix();
+ const Eigen::Matrix<T, 3, 1> t_t_h = q_w_t.conjugate() * (t_w_h - t_w_t);
+
+ // Transform points from host to target frame. 3D point in target frame is
+ // scaled by idist for numerical stability when idist is close to 0
+ // (projection is invariant to scaling).
+ PatchVectors<T> p_target_scaled =
+ (R_t_h * bearings_host_).colwise() + idist * t_t_h;
+
+ // Project points and interpolate image.
+ Patch<T> intensities_target;
+ for (int i = 0; i < p_target_scaled.cols(); ++i) {
+ Eigen::Matrix<T, 2, 1> uv;
+ if (!Project(uv, Eigen::Matrix<T, 3, 1>(p_target_scaled.col(i)))) {
+ // If any point of the patch is outside the domain of the projection
+ // function, the residual cannot be evaluated. For the benchmark we want
+ // to avoid this case and thus throw an exception to indicate
+ // immediately if it does actually happen after possible future changes.
+ throw std::runtime_error("Benchmark data leads to invalid projection.");
+ }
+
+ // Mind the order of u and v: Evaluate takes (row, column), but u is
+ // left-to-right and v top-to-bottom image axis.
+ image_target_.Evaluate(uv[1], uv[0], &intensities_target[i]);
+ }
+
+ // Residual is intensity difference between host and target frame.
+ residuals = intensities_target - intensities_host_;
+
+ return true;
+ }
+
+ private:
+ const Patch<double>& intensities_host_;
+ const PatchVectors<double>& bearings_host_;
+ const Interpolator& image_target_;
+ const Intrinsics& intrinsics_;
+};
+} // namespace ceres
+#endif // CERES_INTERNAL_AUTODIFF_BENCHMARK_PHOTOMETRIC_ERROR_H_
diff --git a/internal/ceres/autodiff_benchmarks/relative_pose_error.h b/internal/ceres/autodiff_benchmarks/relative_pose_error.h
new file mode 100644
index 0000000..b5c1a93
--- /dev/null
+++ b/internal/ceres/autodiff_benchmarks/relative_pose_error.h
@@ -0,0 +1,87 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2020 Google Inc. All rights reserved.
+// http://ceres-solver.org/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// * Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: nikolaus@nikolaus-demmel.de (Nikolaus Demmel)
+//
+//
+#ifndef CERES_INTERNAL_AUTODIFF_BENCHMARK_RELATIVE_POSE_ERROR_H_
+#define CERES_INTERNAL_AUTODIFF_BENCHMARK_RELATIVE_POSE_ERROR_H_
+
+#include <Eigen/Dense>
+
+#include "ceres/rotation.h"
+
+namespace ceres {
+
+// Relative pose error as one might use in SE(3) pose graph optimization.
+// The measurement is a relative pose T_i_j, and the parameters are absolute
+// poses T_w_i and T_w_j. For the residual we use the log of the the residual
+// pose, in split representation SO(3) x R^3.
+struct RelativePoseError {
+ RelativePoseError(const Eigen::Quaterniond& q_i_j,
+ const Eigen::Vector3d& t_i_j)
+ : meas_q_i_j_(q_i_j), meas_t_i_j_(t_i_j) {}
+
+ template <typename T>
+ inline bool operator()(const T* const pose_i_ptr,
+ const T* const pose_j_ptr,
+ T* residuals_ptr) const {
+ Eigen::Map<const Eigen::Quaternion<T>> q_w_i(pose_i_ptr);
+ Eigen::Map<const Eigen::Matrix<T, 3, 1>> t_w_i(pose_i_ptr + 4);
+ Eigen::Map<const Eigen::Quaternion<T>> q_w_j(pose_j_ptr);
+ Eigen::Map<const Eigen::Matrix<T, 3, 1>> t_w_j(pose_j_ptr + 4);
+ Eigen::Map<Eigen::Matrix<T, 6, 1>> residuals(residuals_ptr);
+
+ // Compute estimate of relative pose from i to j.
+ const Eigen::Quaternion<T> est_q_j_i = q_w_j.conjugate() * q_w_i;
+ const Eigen::Matrix<T, 3, 1> est_t_j_i =
+ q_w_j.conjugate() * (t_w_i - t_w_j);
+
+ // Compute residual pose.
+ const Eigen::Quaternion<T> res_q = meas_q_i_j_.cast<T>() * est_q_j_i;
+ const Eigen::Matrix<T, 3, 1> res_t =
+ meas_q_i_j_.cast<T>() * est_t_j_i + meas_t_i_j_;
+
+ // Convert quaternion to ceres convention (Eigen stores xyzw, Ceres wxyz).
+ Eigen::Matrix<T, 4, 1> res_q_ceres;
+ res_q_ceres << res_q.w(), res_q.vec();
+
+ // Residual is log of pose. Use split representation SO(3) x R^3.
+ QuaternionToAngleAxis(res_q_ceres.data(), residuals.data());
+ residuals.template bottomRows<3>() = res_t;
+
+ return true;
+ }
+
+ private:
+ // Measurement of relative pose from j to i.
+ Eigen::Quaterniond meas_q_i_j_;
+ Eigen::Vector3d meas_t_i_j_;
+};
+} // namespace ceres
+#endif // CERES_INTERNAL_AUTODIFF_BENCHMARK_RELATIVE_POSE_ERROR_H_
diff --git a/internal/ceres/autodiff_benchmarks/snavely_reprojection_error.h b/internal/ceres/autodiff_benchmarks/snavely_reprojection_error.h
new file mode 100644
index 0000000..795342f
--- /dev/null
+++ b/internal/ceres/autodiff_benchmarks/snavely_reprojection_error.h
@@ -0,0 +1,87 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2020 Google Inc. All rights reserved.
+// http://ceres-solver.org/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// * Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following disclaimer in the documentation
+// and/or other materials provided with the distribution.
+// * Neither the name of Google Inc. nor the names of its contributors may be
+// used to endorse or promote products derived from this software without
+// specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+//
+// Author: darius.rueckert@fau.de (Darius Rueckert)
+//
+//
+#ifndef CERES_INTERNAL_AUTODIFF_BENCHMARK_SNAVELY_REPROJECTION_ERROR_H_
+#define CERES_INTERNAL_AUTODIFF_BENCHMARK_SNAVELY_REPROJECTION_ERROR_H_
+
+#include "ceres/rotation.h"
+
+namespace ceres {
+
+struct SnavelyReprojectionError {
+ SnavelyReprojectionError(double observed_x, double observed_y)
+ : observed_x(observed_x), observed_y(observed_y) {}
+
+ SnavelyReprojectionError() = default;
+ template <typename T>
+ inline bool operator()(const T* const camera,
+ const T* const point,
+ T* residuals) const {
+ T ox = T(observed_x);
+ T oy = T(observed_y);
+
+ // camera[0,1,2] are the angle-axis rotation.
+ T p[3];
+ ceres::AngleAxisRotatePoint(camera, point, p);
+
+ // camera[3,4,5] are the translation.
+ p[0] += camera[3];
+ p[1] += camera[4];
+ p[2] += camera[5];
+
+ // Compute the center of distortion. The sign change comes from
+ // the camera model that Noah Snavely's Bundler assumes, whereby
+ // the camera coordinate system has a negative z axis.
+ const T xp = -p[0] / p[2];
+ const T yp = -p[1] / p[2];
+
+ // Apply second and fourth order radial distortion.
+ const T& l1 = camera[7];
+ const T& l2 = camera[8];
+ const T r2 = xp * xp + yp * yp;
+ const T distortion = T(1.0) + r2 * (l1 + l2 * r2);
+
+ // Compute final projected point position.
+ const T& focal = camera[6];
+ const T predicted_x = focal * distortion * xp;
+ const T predicted_y = focal * distortion * yp;
+
+ // The error is the difference between the predicted and observed position.
+ residuals[0] = predicted_x - ox;
+ residuals[1] = predicted_y - oy;
+
+ return true;
+ }
+ double observed_x;
+ double observed_y;
+};
+} // namespace ceres
+#endif // CERES_INTERNAL_AUTODIFF_BENCHMARK_SNAVELY_REPROJECTION_ERROR_H_