interfacing_with_autodiff.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. .. default-domain:: cpp
  2. .. cpp:namespace:: ceres
  3. .. _chapter-interfacing_with_automatic_differentiation:
  4. Interfacing with Automatic Differentiation
  5. ==========================================
  6. Automatic differentiation is straightforward to use in cases where an
  7. explicit expression for the cost function is available. But this is
  8. not always possible. Often one has to interface with external routines
  9. or data. In this chapter we will consider a number of different ways
  10. of doing so.
  11. To do this, we will consider the problem of finding parameters
  12. :math:`\theta` and :math:`t` that solve an optimization problem of the
  13. form:
  14. .. math::
  15. \min & \quad \sum_i \left \|y_i - f\left (\|q_{i}\|^2\right) q_i
  16. \right \|^2\\
  17. \text{such that} & \quad q_i = R(\theta) x_i + t
  18. Here, :math:`R` is a two dimensional rotation matrix parameterized
  19. using the angle :math:`\theta` and :math:`t` is a two dimensional
  20. vector. :math:`f` is an external distortion function.
  21. We begin by considering the case, where we have a templated function
  22. :code:`TemplatedComputeDistortion` that can compute the function
  23. :math:`f`. Then the implementation of the corresponding residual
  24. functor is straightforward and will look as follows:
  25. .. code-block:: c++
  26. :emphasize-lines: 21
  27. template <typename T> T TemplatedComputeDistortion(const T r2) {
  28. const double k1 = 0.0082;
  29. const double k2 = 0.000023;
  30. return 1.0 + k1 * r2 + k2 * r2 * r2;
  31. }
  32. struct Affine2DWithDistortion {
  33. Affine2DWithDistortion(const double x_in[2], const double y_in[2]) {
  34. x[0] = x_in[0];
  35. x[1] = x_in[1];
  36. y[0] = y_in[0];
  37. y[1] = y_in[1];
  38. }
  39. template <typename T>
  40. bool operator()(const T* theta,
  41. const T* t,
  42. T* residuals) const {
  43. const T q_0 = cos(theta[0]) * x[0] - sin(theta[0]) * x[1] + t[0];
  44. const T q_1 = sin(theta[0]) * x[0] + cos(theta[0]) * x[1] + t[1];
  45. const T f = TemplatedComputeDistortion(q_0 * q_0 + q_1 * q_1);
  46. residuals[0] = y[0] - f * q_0;
  47. residuals[1] = y[1] - f * q_1;
  48. return true;
  49. }
  50. double x[2];
  51. double y[2];
  52. };
  53. So far so good, but let us now consider three ways of defining
  54. :math:`f` which are not directly amenable to being used with automatic
  55. differentiation:
  56. #. A non-templated function that evaluates its value.
  57. #. A function that evaluates its value and derivative.
  58. #. A function that is defined as a table of values to be interpolated.
  59. We will consider them in turn below.
  60. A function that returns its value
  61. ----------------------------------
  62. Suppose we were given a function :code:`ComputeDistortionValue` with
  63. the following signature
  64. .. code-block:: c++
  65. double ComputeDistortionValue(double r2);
  66. that computes the value of :math:`f`. The actual implementation of the
  67. function does not matter. Interfacing this function with
  68. :code:`Affine2DWithDistortion` is a three step process:
  69. 1. Wrap :code:`ComputeDistortionValue` into a functor
  70. :code:`ComputeDistortionValueFunctor`.
  71. 2. Numerically differentiate :code:`ComputeDistortionValueFunctor`
  72. using :class:`NumericDiffCostFunction` to create a
  73. :class:`CostFunction`.
  74. 3. Wrap the resulting :class:`CostFunction` object using
  75. :class:`CostFunctionToFunctor`. The resulting object is a functor
  76. with a templated :code:`operator()` method, which pipes the
  77. Jacobian computed by :class:`NumericDiffCostFunction` into the
  78. appropriate :code:`Jet` objects.
  79. An implementation of the above three steps looks as follows:
  80. .. code-block:: c++
  81. :emphasize-lines: 15,16,17,18,19,20, 29
  82. struct ComputeDistortionValueFunctor {
  83. bool operator()(const double* r2, double* value) const {
  84. *value = ComputeDistortionValue(r2[0]);
  85. return true;
  86. }
  87. };
  88. struct Affine2DWithDistortion {
  89. Affine2DWithDistortion(const double x_in[2], const double y_in[2]) {
  90. x[0] = x_in[0];
  91. x[1] = x_in[1];
  92. y[0] = y_in[0];
  93. y[1] = y_in[1];
  94. compute_distortion.reset(new ceres::CostFunctionToFunctor<1, 1>(
  95. new ceres::NumericDiffCostFunction<ComputeDistortionValueFunctor,
  96. ceres::CENTRAL,
  97. 1,
  98. 1>(
  99. new ComputeDistortionValueFunctor)));
  100. }
  101. template <typename T>
  102. bool operator()(const T* theta, const T* t, T* residuals) const {
  103. const T q_0 = cos(theta[0]) * x[0] - sin(theta[0]) * x[1] + t[0];
  104. const T q_1 = sin(theta[0]) * x[0] + cos(theta[0]) * x[1] + t[1];
  105. const T r2 = q_0 * q_0 + q_1 * q_1;
  106. T f;
  107. (*compute_distortion)(&r2, &f);
  108. residuals[0] = y[0] - f * q_0;
  109. residuals[1] = y[1] - f * q_1;
  110. return true;
  111. }
  112. double x[2];
  113. double y[2];
  114. std::unique_ptr<ceres::CostFunctionToFunctor<1, 1> > compute_distortion;
  115. };
  116. A function that returns its value and derivative
  117. ------------------------------------------------
  118. Now suppose we are given a function :code:`ComputeDistortionValue`
  119. that is able to compute its value and optionally its Jacobian on demand
  120. and has the following signature:
  121. .. code-block:: c++
  122. void ComputeDistortionValueAndJacobian(double r2,
  123. double* value,
  124. double* jacobian);
  125. Again, the actual implementation of the function does not
  126. matter. Interfacing this function with :code:`Affine2DWithDistortion`
  127. is a two step process:
  128. 1. Wrap :code:`ComputeDistortionValueAndJacobian` into a
  129. :class:`CostFunction` object which we call
  130. :code:`ComputeDistortionFunction`.
  131. 2. Wrap the resulting :class:`ComputeDistortionFunction` object using
  132. :class:`CostFunctionToFunctor`. The resulting object is a functor
  133. with a templated :code:`operator()` method, which pipes the
  134. Jacobian computed by :class:`NumericDiffCostFunction` into the
  135. appropriate :code:`Jet` objects.
  136. The resulting code will look as follows:
  137. .. code-block:: c++
  138. :emphasize-lines: 21,22, 33
  139. class ComputeDistortionFunction : public ceres::SizedCostFunction<1, 1> {
  140. public:
  141. virtual bool Evaluate(double const* const* parameters,
  142. double* residuals,
  143. double** jacobians) const {
  144. if (!jacobians) {
  145. ComputeDistortionValueAndJacobian(parameters[0][0], residuals, nullptr);
  146. } else {
  147. ComputeDistortionValueAndJacobian(parameters[0][0], residuals, jacobians[0]);
  148. }
  149. return true;
  150. }
  151. };
  152. struct Affine2DWithDistortion {
  153. Affine2DWithDistortion(const double x_in[2], const double y_in[2]) {
  154. x[0] = x_in[0];
  155. x[1] = x_in[1];
  156. y[0] = y_in[0];
  157. y[1] = y_in[1];
  158. compute_distortion.reset(
  159. new ceres::CostFunctionToFunctor<1, 1>(new ComputeDistortionFunction));
  160. }
  161. template <typename T>
  162. bool operator()(const T* theta,
  163. const T* t,
  164. T* residuals) const {
  165. const T q_0 = cos(theta[0]) * x[0] - sin(theta[0]) * x[1] + t[0];
  166. const T q_1 = sin(theta[0]) * x[0] + cos(theta[0]) * x[1] + t[1];
  167. const T r2 = q_0 * q_0 + q_1 * q_1;
  168. T f;
  169. (*compute_distortion)(&r2, &f);
  170. residuals[0] = y[0] - f * q_0;
  171. residuals[1] = y[1] - f * q_1;
  172. return true;
  173. }
  174. double x[2];
  175. double y[2];
  176. std::unique_ptr<ceres::CostFunctionToFunctor<1, 1> > compute_distortion;
  177. };
  178. A function that is defined as a table of values
  179. -----------------------------------------------
  180. The third and final case we will consider is where the function
  181. :math:`f` is defined as a table of values on the interval :math:`[0,
  182. 100)`, with a value for each integer.
  183. .. code-block:: c++
  184. vector<double> distortion_values;
  185. There are many ways of interpolating a table of values. Perhaps the
  186. simplest and most common method is linear interpolation. But it is not
  187. a great idea to use linear interpolation because the interpolating
  188. function is not differentiable at the sample points.
  189. A simple (well behaved) differentiable interpolation is the `Cubic
  190. Hermite Spline
  191. <http://en.wikipedia.org/wiki/Cubic_Hermite_spline>`_. Ceres Solver
  192. ships with routines to perform Cubic & Bi-Cubic interpolation that is
  193. automatic differentiation friendly.
  194. Using Cubic interpolation requires first constructing a
  195. :class:`Grid1D` object to wrap the table of values and then
  196. constructing a :class:`CubicInterpolator` object using it.
  197. The resulting code will look as follows:
  198. .. code-block:: c++
  199. :emphasize-lines: 10,11,12,13, 24, 32,33
  200. struct Affine2DWithDistortion {
  201. Affine2DWithDistortion(const double x_in[2],
  202. const double y_in[2],
  203. const std::vector<double>& distortion_values) {
  204. x[0] = x_in[0];
  205. x[1] = x_in[1];
  206. y[0] = y_in[0];
  207. y[1] = y_in[1];
  208. grid.reset(new ceres::Grid1D<double, 1>(
  209. &distortion_values[0], 0, distortion_values.size()));
  210. compute_distortion.reset(
  211. new ceres::CubicInterpolator<ceres::Grid1D<double, 1> >(*grid));
  212. }
  213. template <typename T>
  214. bool operator()(const T* theta,
  215. const T* t,
  216. T* residuals) const {
  217. const T q_0 = cos(theta[0]) * x[0] - sin(theta[0]) * x[1] + t[0];
  218. const T q_1 = sin(theta[0]) * x[0] + cos(theta[0]) * x[1] + t[1];
  219. const T r2 = q_0 * q_0 + q_1 * q_1;
  220. T f;
  221. compute_distortion->Evaluate(r2, &f);
  222. residuals[0] = y[0] - f * q_0;
  223. residuals[1] = y[1] - f * q_1;
  224. return true;
  225. }
  226. double x[2];
  227. double y[2];
  228. std::unique_ptr<ceres::Grid1D<double, 1> > grid;
  229. std::unique_ptr<ceres::CubicInterpolator<ceres::Grid1D<double, 1> > > compute_distortion;
  230. };
  231. In the above example we used :class:`Grid1D` and
  232. :class:`CubicInterpolator` to interpolate a one dimensional table of
  233. values. :class:`Grid2D` combined with :class:`CubicInterpolator` lets
  234. the user to interpolate two dimensional tables of values. Note that
  235. neither :class:`Grid1D` or :class:`Grid2D` are limited to scalar
  236. valued functions, they also work with vector valued functions.