nnls_modeling.rst 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722
  1. .. highlight:: c++
  2. .. default-domain:: cpp
  3. .. cpp:namespace:: ceres
  4. .. _`chapter-nnls_modeling`:
  5. =================================
  6. Modeling Non-linear Least Squares
  7. =================================
  8. Introduction
  9. ============
  10. Ceres solver consists of two distinct parts. A modeling API which
  11. provides a rich set of tools to construct an optimization problem one
  12. term at a time and a solver API that controls the minimization
  13. algorithm. This chapter is devoted to the task of modeling
  14. optimization problems using Ceres. :ref:`chapter-nnls_solving` discusses
  15. the various ways in which an optimization problem can be solved using
  16. Ceres.
  17. Ceres solves robustified bounds constrained non-linear least squares
  18. problems of the form:
  19. .. math:: :label: ceresproblem_modeling
  20. \min_{\mathbf{x}} &\quad \frac{1}{2}\sum_{i}
  21. \rho_i\left(\left\|f_i\left(x_{i_1},
  22. ... ,x_{i_k}\right)\right\|^2\right) \\
  23. \text{s.t.} &\quad l_j \le x_j \le u_j
  24. In Ceres parlance, the expression
  25. :math:`\rho_i\left(\left\|f_i\left(x_{i_1},...,x_{i_k}\right)\right\|^2\right)`
  26. is known as a **residual block**, where :math:`f_i(\cdot)` is a
  27. :class:`CostFunction` that depends on the **parameter blocks**
  28. :math:`\left\{x_{i_1},... , x_{i_k}\right\}`.
  29. In most optimization problems small groups of scalars occur
  30. together. For example the three components of a translation vector and
  31. the four components of the quaternion that define the pose of a
  32. camera. We refer to such a group of scalars as a **parameter block**. Of
  33. course a parameter block can be just a single scalar too.
  34. :math:`\rho_i` is a :class:`LossFunction`. A :class:`LossFunction` is
  35. a scalar valued function that is used to reduce the influence of
  36. outliers on the solution of non-linear least squares problems.
  37. :math:`l_j` and :math:`u_j` are lower and upper bounds on the
  38. parameter block :math:`x_j`.
  39. As a special case, when :math:`\rho_i(x) = x`, i.e., the identity
  40. function, and :math:`l_j = -\infty` and :math:`u_j = \infty` we get
  41. the usual unconstrained `non-linear least squares problem
  42. <http://en.wikipedia.org/wiki/Non-linear_least_squares>`_.
  43. .. math:: :label: ceresproblemunconstrained
  44. \frac{1}{2}\sum_{i} \left\|f_i\left(x_{i_1}, ... ,x_{i_k}\right)\right\|^2.
  45. :class:`CostFunction`
  46. =====================
  47. For each term in the objective function, a :class:`CostFunction` is
  48. responsible for computing a vector of residuals and Jacobian
  49. matrices. Concretely, consider a function
  50. :math:`f\left(x_{1},...,x_{k}\right)` that depends on parameter blocks
  51. :math:`\left[x_{1}, ... , x_{k}\right]`.
  52. Then, given :math:`\left[x_{1}, ... , x_{k}\right]`,
  53. :class:`CostFunction` is responsible for computing the vector
  54. :math:`f\left(x_{1},...,x_{k}\right)` and the Jacobian matrices
  55. .. math:: J_i = D_i f(x_1, ..., x_k) \quad \forall i \in \{1, \ldots, k\}
  56. .. class:: CostFunction
  57. .. code-block:: c++
  58. class CostFunction {
  59. public:
  60. virtual bool Evaluate(double const* const* parameters,
  61. double* residuals,
  62. double** jacobians) const = 0;
  63. const std::vector<int32>& parameter_block_sizes();
  64. int num_residuals() const;
  65. protected:
  66. std::vector<int32>* mutable_parameter_block_sizes();
  67. void set_num_residuals(int num_residuals);
  68. };
  69. The signature of the :class:`CostFunction` (number and sizes of input
  70. parameter blocks and number of outputs) is stored in
  71. :member:`CostFunction::parameter_block_sizes_` and
  72. :member:`CostFunction::num_residuals_` respectively. User code
  73. inheriting from this class is expected to set these two members with
  74. the corresponding accessors. This information will be verified by the
  75. :class:`Problem` when added with :func:`Problem::AddResidualBlock`.
  76. .. function:: bool CostFunction::Evaluate(double const* const* parameters, double* residuals, double** jacobians) const
  77. Compute the residual vector and the Jacobian matrices.
  78. ``parameters`` is an array of arrays of size
  79. ``CostFunction::parameter_block_sizes_.size()`` and
  80. ``parameters[i]`` is an array of size ``parameter_block_sizes_[i]``
  81. that contains the :math:`i^{\text{th}}` parameter block that the
  82. ``CostFunction`` depends on.
  83. ``parameters`` is never ``nullptr``.
  84. ``residuals`` is an array of size ``num_residuals_``.
  85. ``residuals`` is never ``nullptr``.
  86. ``jacobians`` is an array of arrays of size
  87. ``CostFunction::parameter_block_sizes_.size()``.
  88. If ``jacobians`` is ``nullptr``, the user is only expected to compute
  89. the residuals.
  90. ``jacobians[i]`` is a row-major array of size ``num_residuals x
  91. parameter_block_sizes_[i]``.
  92. If ``jacobians[i]`` is **not** ``nullptr``, the user is required to
  93. compute the Jacobian of the residual vector with respect to
  94. ``parameters[i]`` and store it in this array, i.e.
  95. ``jacobians[i][r * parameter_block_sizes_[i] + c]`` =
  96. :math:`\frac{\displaystyle \partial \text{residual}[r]}{\displaystyle \partial \text{parameters}[i][c]}`
  97. If ``jacobians[i]`` is ``nullptr``, then this computation can be
  98. skipped. This is the case when the corresponding parameter block is
  99. marked constant.
  100. The return value indicates whether the computation of the residuals
  101. and/or jacobians was successful or not. This can be used to
  102. communicate numerical failures in Jacobian computations for
  103. instance.
  104. :class:`SizedCostFunction`
  105. ==========================
  106. .. class:: SizedCostFunction
  107. If the size of the parameter blocks and the size of the residual
  108. vector is known at compile time (this is the common case),
  109. :class:`SizeCostFunction` can be used where these values can be
  110. specified as template parameters and the user only needs to
  111. implement :func:`CostFunction::Evaluate`.
  112. .. code-block:: c++
  113. template<int kNumResiduals, int... Ns>
  114. class SizedCostFunction : public CostFunction {
  115. public:
  116. virtual bool Evaluate(double const* const* parameters,
  117. double* residuals,
  118. double** jacobians) const = 0;
  119. };
  120. :class:`AutoDiffCostFunction`
  121. =============================
  122. .. class:: AutoDiffCostFunction
  123. Defining a :class:`CostFunction` or a :class:`SizedCostFunction`
  124. can be a tedious and error prone especially when computing
  125. derivatives. To this end Ceres provides `automatic differentiation
  126. <http://en.wikipedia.org/wiki/Automatic_differentiation>`_.
  127. .. code-block:: c++
  128. template <typename CostFunctor,
  129. int kNumResiduals, // Number of residuals, or ceres::DYNAMIC.
  130. int... Ns> // Size of each parameter block
  131. class AutoDiffCostFunction : public
  132. SizedCostFunction<kNumResiduals, Ns> {
  133. public:
  134. AutoDiffCostFunction(CostFunctor* functor, ownership = TAKE_OWNERSHIP);
  135. // Ignore the template parameter kNumResiduals and use
  136. // num_residuals instead.
  137. AutoDiffCostFunction(CostFunctor* functor,
  138. int num_residuals,
  139. ownership = TAKE_OWNERSHIP);
  140. };
  141. To get an auto differentiated cost function, you must define a
  142. class with a templated ``operator()`` (a functor) that computes the
  143. cost function in terms of the template parameter ``T``. The
  144. autodiff framework substitutes appropriate ``Jet`` objects for
  145. ``T`` in order to compute the derivative when necessary, but this
  146. is hidden, and you should write the function as if ``T`` were a
  147. scalar type (e.g. a double-precision floating point number).
  148. The function must write the computed value in the last argument
  149. (the only non-``const`` one) and return true to indicate success.
  150. For example, consider a scalar error :math:`e = k - x^\top y`,
  151. where both :math:`x` and :math:`y` are two-dimensional vector
  152. parameters and :math:`k` is a constant. The form of this error,
  153. which is the difference between a constant and an expression, is a
  154. common pattern in least squares problems. For example, the value
  155. :math:`x^\top y` might be the model expectation for a series of
  156. measurements, where there is an instance of the cost function for
  157. each measurement :math:`k`.
  158. The actual cost added to the total problem is :math:`e^2`, or
  159. :math:`(k - x^\top y)^2`; however, the squaring is implicitly done
  160. by the optimization framework.
  161. To write an auto-differentiable cost function for the above model,
  162. first define the object
  163. .. code-block:: c++
  164. class MyScalarCostFunctor {
  165. MyScalarCostFunctor(double k): k_(k) {}
  166. template <typename T>
  167. bool operator()(const T* const x , const T* const y, T* e) const {
  168. e[0] = k_ - x[0] * y[0] - x[1] * y[1];
  169. return true;
  170. }
  171. private:
  172. double k_;
  173. };
  174. Note that in the declaration of ``operator()`` the input parameters
  175. ``x`` and ``y`` come first, and are passed as const pointers to arrays
  176. of ``T``. If there were three input parameters, then the third input
  177. parameter would come after ``y``. The output is always the last
  178. parameter, and is also a pointer to an array. In the example above,
  179. ``e`` is a scalar, so only ``e[0]`` is set.
  180. Then given this class definition, the auto differentiated cost
  181. function for it can be constructed as follows.
  182. .. code-block:: c++
  183. CostFunction* cost_function
  184. = new AutoDiffCostFunction<MyScalarCostFunctor, 1, 2, 2>(
  185. new MyScalarCostFunctor(1.0)); ^ ^ ^
  186. | | |
  187. Dimension of residual ------+ | |
  188. Dimension of x ----------------+ |
  189. Dimension of y -------------------+
  190. In this example, there is usually an instance for each measurement
  191. of ``k``.
  192. In the instantiation above, the template parameters following
  193. ``MyScalarCostFunction``, ``<1, 2, 2>`` describe the functor as
  194. computing a 1-dimensional output from two arguments, both
  195. 2-dimensional.
  196. By default :class:`AutoDiffCostFunction` will take ownership of the cost
  197. functor pointer passed to it, ie. will call `delete` on the cost functor
  198. when the :class:`AutoDiffCostFunction` itself is deleted. However, this may
  199. be undesirable in certain cases, therefore it is also possible to specify
  200. :class:`DO_NOT_TAKE_OWNERSHIP` as a second argument in the constructor,
  201. while passing a pointer to a cost functor which does not need to be deleted
  202. by the AutoDiffCostFunction. For example:
  203. .. code-block:: c++
  204. MyScalarCostFunctor functor(1.0)
  205. CostFunction* cost_function
  206. = new AutoDiffCostFunction<MyScalarCostFunctor, 1, 2, 2>(
  207. &functor, DO_NOT_TAKE_OWNERSHIP);
  208. :class:`AutoDiffCostFunction` also supports cost functions with a
  209. runtime-determined number of residuals. For example:
  210. .. code-block:: c++
  211. CostFunction* cost_function
  212. = new AutoDiffCostFunction<MyScalarCostFunctor, DYNAMIC, 2, 2>(
  213. new CostFunctorWithDynamicNumResiduals(1.0), ^ ^ ^
  214. runtime_number_of_residuals); <----+ | | |
  215. | | | |
  216. | | | |
  217. Actual number of residuals ------+ | | |
  218. Indicate dynamic number of residuals --------+ | |
  219. Dimension of x ------------------------------------+ |
  220. Dimension of y ---------------------------------------+
  221. .. warning::
  222. A common beginner's error when first using :class:`AutoDiffCostFunction`
  223. is to get the sizing wrong. In particular, there is a tendency to set the
  224. template parameters to (dimension of residual, number of parameters)
  225. instead of passing a dimension parameter for *every parameter block*. In
  226. the example above, that would be ``<MyScalarCostFunction, 1, 2>``, which
  227. is missing the 2 as the last template argument.
  228. :class:`DynamicAutoDiffCostFunction`
  229. ====================================
  230. .. class:: DynamicAutoDiffCostFunction
  231. :class:`AutoDiffCostFunction` requires that the number of parameter
  232. blocks and their sizes be known at compile time. In a number of
  233. applications, this is not enough e.g., Bezier curve fitting, Neural
  234. Network training etc.
  235. .. code-block:: c++
  236. template <typename CostFunctor, int Stride = 4>
  237. class DynamicAutoDiffCostFunction : public CostFunction {
  238. };
  239. In such cases :class:`DynamicAutoDiffCostFunction` can be
  240. used. Like :class:`AutoDiffCostFunction` the user must define a
  241. templated functor, but the signature of the functor differs
  242. slightly. The expected interface for the cost functors is:
  243. .. code-block:: c++
  244. struct MyCostFunctor {
  245. template<typename T>
  246. bool operator()(T const* const* parameters, T* residuals) const {
  247. }
  248. }
  249. Since the sizing of the parameters is done at runtime, you must
  250. also specify the sizes after creating the dynamic autodiff cost
  251. function. For example:
  252. .. code-block:: c++
  253. DynamicAutoDiffCostFunction<MyCostFunctor, 4>* cost_function =
  254. new DynamicAutoDiffCostFunction<MyCostFunctor, 4>(
  255. new MyCostFunctor());
  256. cost_function->AddParameterBlock(5);
  257. cost_function->AddParameterBlock(10);
  258. cost_function->SetNumResiduals(21);
  259. Under the hood, the implementation evaluates the cost function
  260. multiple times, computing a small set of the derivatives (four by
  261. default, controlled by the ``Stride`` template parameter) with each
  262. pass. There is a performance tradeoff with the size of the passes;
  263. Smaller sizes are more cache efficient but result in larger number
  264. of passes, and larger stride lengths can destroy cache-locality
  265. while reducing the number of passes over the cost function. The
  266. optimal value depends on the number and sizes of the various
  267. parameter blocks.
  268. As a rule of thumb, try using :class:`AutoDiffCostFunction` before
  269. you use :class:`DynamicAutoDiffCostFunction`.
  270. :class:`NumericDiffCostFunction`
  271. ================================
  272. .. class:: NumericDiffCostFunction
  273. In some cases, its not possible to define a templated cost functor,
  274. for example when the evaluation of the residual involves a call to a
  275. library function that you do not have control over. In such a
  276. situation, `numerical differentiation
  277. <http://en.wikipedia.org/wiki/Numerical_differentiation>`_ can be
  278. used.
  279. .. NOTE ::
  280. TODO(sameeragarwal): Add documentation for the constructor and for
  281. NumericDiffOptions. Update DynamicNumericDiffOptions in a similar
  282. manner.
  283. .. code-block:: c++
  284. template <typename CostFunctor,
  285. NumericDiffMethodType method = CENTRAL,
  286. int kNumResiduals, // Number of residuals, or ceres::DYNAMIC.
  287. int... Ns> // Size of each parameter block.
  288. class NumericDiffCostFunction : public
  289. SizedCostFunction<kNumResiduals, Ns> {
  290. };
  291. To get a numerically differentiated :class:`CostFunction`, you must
  292. define a class with a ``operator()`` (a functor) that computes the
  293. residuals. The functor must write the computed value in the last
  294. argument (the only non-``const`` one) and return ``true`` to
  295. indicate success. Please see :class:`CostFunction` for details on
  296. how the return value may be used to impose simple constraints on the
  297. parameter block. e.g., an object of the form
  298. .. code-block:: c++
  299. struct ScalarFunctor {
  300. public:
  301. bool operator()(const double* const x1,
  302. const double* const x2,
  303. double* residuals) const;
  304. }
  305. For example, consider a scalar error :math:`e = k - x'y`, where both
  306. :math:`x` and :math:`y` are two-dimensional column vector
  307. parameters, the prime sign indicates transposition, and :math:`k` is
  308. a constant. The form of this error, which is the difference between
  309. a constant and an expression, is a common pattern in least squares
  310. problems. For example, the value :math:`x'y` might be the model
  311. expectation for a series of measurements, where there is an instance
  312. of the cost function for each measurement :math:`k`.
  313. To write an numerically-differentiable class:`CostFunction` for the
  314. above model, first define the object
  315. .. code-block:: c++
  316. class MyScalarCostFunctor {
  317. MyScalarCostFunctor(double k): k_(k) {}
  318. bool operator()(const double* const x,
  319. const double* const y,
  320. double* residuals) const {
  321. residuals[0] = k_ - x[0] * y[0] + x[1] * y[1];
  322. return true;
  323. }
  324. private:
  325. double k_;
  326. };
  327. Note that in the declaration of ``operator()`` the input parameters
  328. ``x`` and ``y`` come first, and are passed as const pointers to
  329. arrays of ``double`` s. If there were three input parameters, then
  330. the third input parameter would come after ``y``. The output is
  331. always the last parameter, and is also a pointer to an array. In the
  332. example above, the residual is a scalar, so only ``residuals[0]`` is
  333. set.
  334. Then given this class definition, the numerically differentiated
  335. :class:`CostFunction` with central differences used for computing
  336. the derivative can be constructed as follows.
  337. .. code-block:: c++
  338. CostFunction* cost_function
  339. = new NumericDiffCostFunction<MyScalarCostFunctor, CENTRAL, 1, 2, 2>(
  340. new MyScalarCostFunctor(1.0)); ^ ^ ^ ^
  341. | | | |
  342. Finite Differencing Scheme -+ | | |
  343. Dimension of residual ------------+ | |
  344. Dimension of x ----------------------+ |
  345. Dimension of y -------------------------+
  346. In this example, there is usually an instance for each measurement
  347. of `k`.
  348. In the instantiation above, the template parameters following
  349. ``MyScalarCostFunctor``, ``1, 2, 2``, describe the functor as
  350. computing a 1-dimensional output from two arguments, both
  351. 2-dimensional.
  352. NumericDiffCostFunction also supports cost functions with a
  353. runtime-determined number of residuals. For example:
  354. .. code-block:: c++
  355. CostFunction* cost_function
  356. = new NumericDiffCostFunction<MyScalarCostFunctor, CENTRAL, DYNAMIC, 2, 2>(
  357. new CostFunctorWithDynamicNumResiduals(1.0), ^ ^ ^
  358. TAKE_OWNERSHIP, | | |
  359. runtime_number_of_residuals); <----+ | | |
  360. | | | |
  361. | | | |
  362. Actual number of residuals ------+ | | |
  363. Indicate dynamic number of residuals --------------------+ | |
  364. Dimension of x ------------------------------------------------+ |
  365. Dimension of y ---------------------------------------------------+
  366. There are three available numeric differentiation schemes in ceres-solver:
  367. The ``FORWARD`` difference method, which approximates :math:`f'(x)`
  368. by computing :math:`\frac{f(x+h)-f(x)}{h}`, computes the cost
  369. function one additional time at :math:`x+h`. It is the fastest but
  370. least accurate method.
  371. The ``CENTRAL`` difference method is more accurate at the cost of
  372. twice as many function evaluations than forward difference,
  373. estimating :math:`f'(x)` by computing
  374. :math:`\frac{f(x+h)-f(x-h)}{2h}`.
  375. The ``RIDDERS`` difference method[Ridders]_ is an adaptive scheme
  376. that estimates derivatives by performing multiple central
  377. differences at varying scales. Specifically, the algorithm starts at
  378. a certain :math:`h` and as the derivative is estimated, this step
  379. size decreases. To conserve function evaluations and estimate the
  380. derivative error, the method performs Richardson extrapolations
  381. between the tested step sizes. The algorithm exhibits considerably
  382. higher accuracy, but does so by additional evaluations of the cost
  383. function.
  384. Consider using ``CENTRAL`` differences to begin with. Based on the
  385. results, either try forward difference to improve performance or
  386. Ridders' method to improve accuracy.
  387. .. warning::
  388. A common beginner's error when first using
  389. :class:`NumericDiffCostFunction` is to get the sizing wrong. In
  390. particular, there is a tendency to set the template parameters to
  391. (dimension of residual, number of parameters) instead of passing a
  392. dimension parameter for *every parameter*. In the example above, that
  393. would be ``<MyScalarCostFunctor, 1, 2>``, which is missing the last ``2``
  394. argument. Please be careful when setting the size parameters.
  395. Numeric Differentiation & Manifolds
  396. -----------------------------------
  397. If your cost function depends on a parameter block that must lie on
  398. a manifold and the functor cannot be evaluated for values of that
  399. parameter block not on the manifold then you may have problems
  400. numerically differentiating such functors.
  401. This is because numeric differentiation in Ceres is performed by
  402. perturbing the individual coordinates of the parameter blocks that
  403. a cost functor depends on. This perturbation assumes that the
  404. parameter block lives on a Euclidean Manifold rather than the
  405. actual manifold associated with the parameter block. As a result
  406. some of the perturbed points may not lie on the manifold anymore.
  407. For example consider a four dimensional parameter block that is
  408. interpreted as a unit Quaternion. Perturbing the coordinates of
  409. this parameter block will violate the unit norm property of the
  410. parameter block.
  411. Fixing this problem requires that :class:`NumericDiffCostFunction`
  412. be aware of the :class:`Manifold` associated with each
  413. parameter block and only generate perturbations in the local
  414. tangent space of each parameter block.
  415. For now this is not considered to be a serious enough problem to
  416. warrant changing the :class:`NumericDiffCostFunction` API. Further,
  417. in most cases it is relatively straightforward to project a point
  418. off the manifold back onto the manifold before using it in the
  419. functor. For example in case of the Quaternion, normalizing the
  420. 4-vector before using it does the trick.
  421. **Alternate Interface**
  422. For a variety of reasons, including compatibility with legacy code,
  423. :class:`NumericDiffCostFunction` can also take
  424. :class:`CostFunction` objects as input. The following describes
  425. how.
  426. To get a numerically differentiated cost function, define a
  427. subclass of :class:`CostFunction` such that the
  428. :func:`CostFunction::Evaluate` function ignores the ``jacobians``
  429. parameter. The numeric differentiation wrapper will fill in the
  430. jacobian parameter if necessary by repeatedly calling the
  431. :func:`CostFunction::Evaluate` with small changes to the
  432. appropriate parameters, and computing the slope. For performance,
  433. the numeric differentiation wrapper class is templated on the
  434. concrete cost function, even though it could be implemented only in
  435. terms of the :class:`CostFunction` interface.
  436. The numerically differentiated version of a cost function for a
  437. cost function can be constructed as follows:
  438. .. code-block:: c++
  439. CostFunction* cost_function
  440. = new NumericDiffCostFunction<MyCostFunction, CENTRAL, 1, 4, 8>(
  441. new MyCostFunction(...), TAKE_OWNERSHIP);
  442. where ``MyCostFunction`` has 1 residual and 2 parameter blocks with
  443. sizes 4 and 8 respectively. Look at the tests for a more detailed
  444. example.
  445. :class:`DynamicNumericDiffCostFunction`
  446. =======================================
  447. .. class:: DynamicNumericDiffCostFunction
  448. Like :class:`AutoDiffCostFunction` :class:`NumericDiffCostFunction`
  449. requires that the number of parameter blocks and their sizes be
  450. known at compile time. In a number of applications, this is not enough.
  451. .. code-block:: c++
  452. template <typename CostFunctor, NumericDiffMethodType method = CENTRAL>
  453. class DynamicNumericDiffCostFunction : public CostFunction {
  454. };
  455. In such cases when numeric differentiation is desired,
  456. :class:`DynamicNumericDiffCostFunction` can be used.
  457. Like :class:`NumericDiffCostFunction` the user must define a
  458. functor, but the signature of the functor differs slightly. The
  459. expected interface for the cost functors is:
  460. .. code-block:: c++
  461. struct MyCostFunctor {
  462. bool operator()(double const* const* parameters, double* residuals) const {
  463. }
  464. }
  465. Since the sizing of the parameters is done at runtime, you must
  466. also specify the sizes after creating the dynamic numeric diff cost
  467. function. For example:
  468. .. code-block:: c++
  469. DynamicNumericDiffCostFunction<MyCostFunctor>* cost_function =
  470. new DynamicNumericDiffCostFunction<MyCostFunctor>(new MyCostFunctor);
  471. cost_function->AddParameterBlock(5);
  472. cost_function->AddParameterBlock(10);
  473. cost_function->SetNumResiduals(21);
  474. As a rule of thumb, try using :class:`NumericDiffCostFunction` before
  475. you use :class:`DynamicNumericDiffCostFunction`.
  476. .. warning::
  477. The same caution about mixing manifolds with numeric differentiation
  478. applies as is the case with :class:`NumericDiffCostFunction`.
  479. :class:`CostFunctionToFunctor`
  480. ==============================
  481. .. class:: CostFunctionToFunctor
  482. :class:`CostFunctionToFunctor` is an adapter class that allows
  483. users to use :class:`CostFunction` objects in templated functors
  484. which are to be used for automatic differentiation. This allows
  485. the user to seamlessly mix analytic, numeric and automatic
  486. differentiation.
  487. For example, let us assume that
  488. .. code-block:: c++
  489. class IntrinsicProjection : public SizedCostFunction<2, 5, 3> {
  490. public:
  491. IntrinsicProjection(const double* observation);
  492. virtual bool Evaluate(double const* const* parameters,
  493. double* residuals,
  494. double** jacobians) const;
  495. };
  496. is a :class:`CostFunction` that implements the projection of a
  497. point in its local coordinate system onto its image plane and
  498. subtracts it from the observed point projection. It can compute its
  499. residual and either via analytic or numerical differentiation can
  500. compute its jacobians.
  501. Now we would like to compose the action of this
  502. :class:`CostFunction` with the action of camera extrinsics, i.e.,
  503. rotation and translation. Say we have a templated function
  504. .. code-block:: c++
  505. template<typename T>
  506. void RotateAndTranslatePoint(const T* rotation,
  507. const T* translation,
  508. const T* point,
  509. T* result);
  510. Then we can now do the following,
  511. .. code-block:: c++
  512. struct CameraProjection {
  513. CameraProjection(double* observation)
  514. : intrinsic_projection_(new IntrinsicProjection(observation)) {
  515. }
  516. template <typename T>
  517. bool operator()(const T* rotation,
  518. const T* translation,
  519. const T* intrinsics,
  520. const T* point,
  521. T* residual) const {
  522. T transformed_point[3];
  523. RotateAndTranslatePoint(rotation, translation, point, transformed_point);
  524. // Note that we call intrinsic_projection_, just like it was
  525. // any other templated functor.
  526. return intrinsic_projection_(intrinsics, transformed_point, residual);
  527. }
  528. private:
  529. CostFunctionToFunctor<2,5,3> intrinsic_projection_;
  530. };
  531. Note that :class:`CostFunctionToFunctor` takes ownership of the
  532. :class:`CostFunction` that was passed in to the constructor.
  533. In the above example, we assumed that ``IntrinsicProjection`` is a
  534. ``CostFunction`` capable of evaluating its value and its
  535. derivatives. Suppose, if that were not the case and
  536. ``IntrinsicProjection`` was defined as follows:
  537. .. code-block:: c++
  538. struct IntrinsicProjection {
  539. IntrinsicProjection(const double* observation) {
  540. observation_[0] = observation[0];
  541. observation_[1] = observation[1];
  542. }
  543. bool operator()(const double* calibration,
  544. const double* point,
  545. double* residuals) const {
  546. double projection[2];
  547. ThirdPartyProjectionFunction(calibration, point, projection);
  548. residuals[0] = observation_[0] - projection[0];
  549. residuals[1] = observation_[1] - projection[1];
  550. return true;
  551. }
  552. double observation_[2];
  553. };
  554. Here ``ThirdPartyProjectionFunction`` is some third party library
  555. function that we have no control over. So this function can compute
  556. its value and we would like to use numeric differentiation to
  557. compute its derivatives. In this case we can use a combination of
  558. ``NumericDiffCostFunction`` and ``CostFunctionToFunctor`` to get the
  559. job done.
  560. .. code-block:: c++
  561. struct CameraProjection {
  562. CameraProjection(double* observation)
  563. : intrinsic_projection_(
  564. new NumericDiffCostFunction<IntrinsicProjection, CENTRAL, 2, 5, 3>(
  565. new IntrinsicProjection(observation))) {}
  566. template <typename T>
  567. bool operator()(const T* rotation,
  568. const T* translation,
  569. const T* intrinsics,
  570. const T* point,
  571. T* residuals) const {
  572. T transformed_point[3];
  573. RotateAndTranslatePoint(rotation, translation, point, transformed_point);
  574. return intrinsic_projection_(intrinsics, transformed_point, residuals);
  575. }
  576. private:
  577. CostFunctionToFunctor<2, 5, 3> intrinsic_projection_;
  578. };
  579. :class:`DynamicCostFunctionToFunctor`
  580. =====================================
  581. .. class:: DynamicCostFunctionToFunctor
  582. :class:`DynamicCostFunctionToFunctor` provides the same functionality as
  583. :class:`CostFunctionToFunctor` for cases where the number and size of the
  584. parameter vectors and residuals are not known at compile-time. The API
  585. provided by :class:`DynamicCostFunctionToFunctor` matches what would be
  586. expected by :class:`DynamicAutoDiffCostFunction`, i.e. it provides a
  587. templated functor of this form:
  588. .. code-block:: c++
  589. template<typename T>
  590. bool operator()(T const* const* parameters, T* residuals) const;
  591. Similar to the example given for :class:`CostFunctionToFunctor`, let us
  592. assume that
  593. .. code-block:: c++
  594. class IntrinsicProjection : public CostFunction {
  595. public:
  596. IntrinsicProjection(const double* observation);
  597. virtual bool Evaluate(double const* const* parameters,
  598. double* residuals,
  599. double** jacobians) const;
  600. };
  601. is a :class:`CostFunction` that projects a point in its local coordinate
  602. system onto its image plane and subtracts it from the observed point
  603. projection.
  604. Using this :class:`CostFunction` in a templated functor would then look like
  605. this:
  606. .. code-block:: c++
  607. struct CameraProjection {
  608. CameraProjection(double* observation)
  609. : intrinsic_projection_(new IntrinsicProjection(observation)) {
  610. }
  611. template <typename T>
  612. bool operator()(T const* const* parameters,
  613. T* residual) const {
  614. const T* rotation = parameters[0];
  615. const T* translation = parameters[1];
  616. const T* intrinsics = parameters[2];
  617. const T* point = parameters[3];
  618. T transformed_point[3];
  619. RotateAndTranslatePoint(rotation, translation, point, transformed_point);
  620. const T* projection_parameters[2];
  621. projection_parameters[0] = intrinsics;
  622. projection_parameters[1] = transformed_point;
  623. return intrinsic_projection_(projection_parameters, residual);
  624. }
  625. private:
  626. DynamicCostFunctionToFunctor intrinsic_projection_;
  627. };
  628. Like :class:`CostFunctionToFunctor`, :class:`DynamicCostFunctionToFunctor`
  629. takes ownership of the :class:`CostFunction` that was passed in to the
  630. constructor.
  631. :class:`ConditionedCostFunction`
  632. ================================
  633. .. class:: ConditionedCostFunction
  634. This class allows you to apply different conditioning to the residual
  635. values of a wrapped cost function. An example where this is useful is
  636. where you have an existing cost function that produces N values, but you
  637. want the total cost to be something other than just the sum of these
  638. squared values - maybe you want to apply a different scaling to some
  639. values, to change their contribution to the cost.
  640. Usage:
  641. .. code-block:: c++
  642. // my_cost_function produces N residuals
  643. CostFunction* my_cost_function = ...
  644. CHECK_EQ(N, my_cost_function->num_residuals());
  645. std::vector<CostFunction*> conditioners;
  646. // Make N 1x1 cost functions (1 parameter, 1 residual)
  647. CostFunction* f_1 = ...
  648. conditioners.push_back(f_1);
  649. CostFunction* f_N = ...
  650. conditioners.push_back(f_N);
  651. ConditionedCostFunction* ccf =
  652. new ConditionedCostFunction(my_cost_function, conditioners);
  653. Now ``ccf`` 's ``residual[i]`` (i=0..N-1) will be passed though the
  654. :math:`i^{\text{th}}` conditioner.
  655. .. code-block:: c++
  656. ccf_residual[i] = f_i(my_cost_function_residual[i])
  657. and the Jacobian will be affected appropriately.
  658. :class:`GradientChecker`
  659. ========================
  660. .. class:: GradientChecker
  661. This class compares the Jacobians returned by a cost function
  662. against derivatives estimated using finite differencing. It is
  663. meant as a tool for unit testing, giving you more fine-grained
  664. control than the check_gradients option in the solver options.
  665. The condition enforced is that
  666. .. math:: \forall{i,j}: \frac{J_{ij} - J'_{ij}}{max_{ij}(J_{ij} - J'_{ij})} < r
  667. where :math:`J_{ij}` is the jacobian as computed by the supplied
  668. cost function multiplied by the `Manifold::PlusJacobian`,
  669. :math:`J'_{ij}` is the jacobian as computed by finite differences,
  670. multiplied by the `Manifold::PlusJacobian` as well, and :math:`r`
  671. is the relative precision.
  672. Usage:
  673. .. code-block:: c++
  674. // my_cost_function takes two parameter blocks. The first has a
  675. // manifold associated with it.
  676. CostFunction* my_cost_function = ...
  677. Manifold* my_manifold = ...
  678. NumericDiffOptions numeric_diff_options;
  679. std::vector<Manifold*> manifolds;
  680. manifolds.push_back(my_manifold);
  681. manifolds.push_back(nullptr);
  682. std::vector parameter1;
  683. std::vector parameter2;
  684. // Fill parameter 1 & 2 with test data...
  685. std::vector<double*> parameter_blocks;
  686. parameter_blocks.push_back(parameter1.data());
  687. parameter_blocks.push_back(parameter2.data());
  688. GradientChecker gradient_checker(my_cost_function,
  689. manifolds,
  690. numeric_diff_options);
  691. GradientCheckResults results;
  692. if (!gradient_checker.Probe(parameter_blocks.data(), 1e-9, &results) {
  693. LOG(ERROR) << "An error has occurred:\n" << results.error_log;
  694. }
  695. :class:`NormalPrior`
  696. ====================
  697. .. class:: NormalPrior
  698. .. code-block:: c++
  699. class NormalPrior: public CostFunction {
  700. public:
  701. // Check that the number of rows in the vector b are the same as the
  702. // number of columns in the matrix A, crash otherwise.
  703. NormalPrior(const Matrix& A, const Vector& b);
  704. virtual bool Evaluate(double const* const* parameters,
  705. double* residuals,
  706. double** jacobians) const;
  707. };
  708. Implements a cost function of the form
  709. .. math:: cost(x) = ||A(x - b)||^2
  710. where, the matrix :math:`A` and the vector :math:`b` are fixed and :math:`x`
  711. is the variable. In case the user is interested in implementing a cost
  712. function of the form
  713. .. math:: cost(x) = (x - \mu)^T S^{-1} (x - \mu)
  714. where, :math:`\mu` is a vector and :math:`S` is a covariance matrix,
  715. then, :math:`A = S^{-1/2}`, i.e the matrix :math:`A` is the square
  716. root of the inverse of the covariance, also known as the stiffness
  717. matrix. There are however no restrictions on the shape of
  718. :math:`A`. It is free to be rectangular, which would be the case if
  719. the covariance matrix :math:`S` is rank deficient.
  720. .. _`section-loss_function`:
  721. :class:`LossFunction`
  722. =====================
  723. .. class:: LossFunction
  724. For least squares problems where the minimization may encounter
  725. input terms that contain outliers, that is, completely bogus
  726. measurements, it is important to use a loss function that reduces
  727. their influence.
  728. Consider a structure from motion problem. The unknowns are 3D
  729. points and camera parameters, and the measurements are image
  730. coordinates describing the expected reprojected position for a
  731. point in a camera. For example, we want to model the geometry of a
  732. street scene with fire hydrants and cars, observed by a moving
  733. camera with unknown parameters, and the only 3D points we care
  734. about are the pointy tippy-tops of the fire hydrants. Our magic
  735. image processing algorithm, which is responsible for producing the
  736. measurements that are input to Ceres, has found and matched all
  737. such tippy-tops in all image frames, except that in one of the
  738. frame it mistook a car's headlight for a hydrant. If we didn't do
  739. anything special the residual for the erroneous measurement will
  740. result in the entire solution getting pulled away from the optimum
  741. to reduce the large error that would otherwise be attributed to the
  742. wrong measurement.
  743. Using a robust loss function, the cost for large residuals is
  744. reduced. In the example above, this leads to outlier terms getting
  745. down-weighted so they do not overly influence the final solution.
  746. .. code-block:: c++
  747. class LossFunction {
  748. public:
  749. virtual void Evaluate(double s, double out[3]) const = 0;
  750. };
  751. The key method is :func:`LossFunction::Evaluate`, which given a
  752. non-negative scalar ``s``, computes
  753. .. math:: out = \begin{bmatrix}\rho(s), & \rho'(s), & \rho''(s)\end{bmatrix}
  754. Here the convention is that the contribution of a term to the cost
  755. function is given by :math:`\frac{1}{2}\rho(s)`, where :math:`s
  756. =\|f_i\|^2`. Calling the method with a negative value of :math:`s`
  757. is an error and the implementations are not required to handle that
  758. case.
  759. Most sane choices of :math:`\rho` satisfy:
  760. .. math::
  761. \rho(0) &= 0\\
  762. \rho'(0) &= 1\\
  763. \rho'(s) &< 1 \text{ in the outlier region}\\
  764. \rho''(s) &< 0 \text{ in the outlier region}
  765. so that they mimic the squared cost for small residuals.
  766. **Scaling**
  767. Given one robustifier :math:`\rho(s)` one can change the length
  768. scale at which robustification takes place, by adding a scale
  769. factor :math:`a > 0` which gives us :math:`\rho(s,a) = a^2 \rho(s /
  770. a^2)` and the first and second derivatives as :math:`\rho'(s /
  771. a^2)` and :math:`(1 / a^2) \rho''(s / a^2)` respectively.
  772. The reason for the appearance of squaring is that :math:`a` is in
  773. the units of the residual vector norm whereas :math:`s` is a squared
  774. norm. For applications it is more convenient to specify :math:`a` than
  775. its square.
  776. Instances
  777. ---------
  778. Ceres includes a number of predefined loss functions. For simplicity
  779. we described their unscaled versions. The figure below illustrates
  780. their shape graphically. More details can be found in
  781. ``include/ceres/loss_function.h``.
  782. .. figure:: loss.png
  783. :figwidth: 500px
  784. :height: 400px
  785. :align: center
  786. Shape of the various common loss functions.
  787. .. class:: TrivialLoss
  788. .. math:: \rho(s) = s
  789. .. class:: HuberLoss
  790. .. math:: \rho(s) = \begin{cases} s & s \le 1\\ 2 \sqrt{s} - 1 & s > 1 \end{cases}
  791. .. class:: SoftLOneLoss
  792. .. math:: \rho(s) = 2 (\sqrt{1+s} - 1)
  793. .. class:: CauchyLoss
  794. .. math:: \rho(s) = \log(1 + s)
  795. .. class:: ArctanLoss
  796. .. math:: \rho(s) = \arctan(s)
  797. .. class:: TolerantLoss
  798. .. math:: \rho(s,a,b) = b \log(1 + e^{(s - a) / b}) - b \log(1 + e^{-a / b})
  799. .. class:: TukeyLoss
  800. .. math:: \rho(s) = \begin{cases} \frac{1}{3} (1 - (1 - s)^3) & s \le 1\\ \frac{1}{3} & s > 1 \end{cases}
  801. .. class:: ComposedLoss
  802. Given two loss functions ``f`` and ``g``, implements the loss
  803. function ``h(s) = f(g(s))``.
  804. .. code-block:: c++
  805. class ComposedLoss : public LossFunction {
  806. public:
  807. explicit ComposedLoss(const LossFunction* f,
  808. Ownership ownership_f,
  809. const LossFunction* g,
  810. Ownership ownership_g);
  811. };
  812. .. class:: ScaledLoss
  813. Sometimes you want to simply scale the output value of the
  814. robustifier. For example, you might want to weight different error
  815. terms differently (e.g., weight pixel reprojection errors
  816. differently from terrain errors).
  817. Given a loss function :math:`\rho(s)` and a scalar :math:`a`, :class:`ScaledLoss`
  818. implements the function :math:`a \rho(s)`.
  819. Since we treat a ``nullptr`` Loss function as the Identity loss
  820. function, :math:`rho` = ``nullptr``: is a valid input and will result
  821. in the input being scaled by :math:`a`. This provides a simple way
  822. of implementing a scaled ResidualBlock.
  823. .. class:: LossFunctionWrapper
  824. Sometimes after the optimization problem has been constructed, we
  825. wish to mutate the scale of the loss function. For example, when
  826. performing estimation from data which has substantial outliers,
  827. convergence can be improved by starting out with a large scale,
  828. optimizing the problem and then reducing the scale. This can have
  829. better convergence behavior than just using a loss function with a
  830. small scale.
  831. This templated class allows the user to implement a loss function
  832. whose scale can be mutated after an optimization problem has been
  833. constructed, e.g,
  834. .. code-block:: c++
  835. Problem problem;
  836. // Add parameter blocks
  837. CostFunction* cost_function =
  838. new AutoDiffCostFunction < UW_Camera_Mapper, 2, 9, 3>(
  839. new UW_Camera_Mapper(feature_x, feature_y));
  840. LossFunctionWrapper* loss_function(new HuberLoss(1.0), TAKE_OWNERSHIP);
  841. problem.AddResidualBlock(cost_function, loss_function, parameters);
  842. Solver::Options options;
  843. Solver::Summary summary;
  844. Solve(options, &problem, &summary);
  845. loss_function->Reset(new HuberLoss(1.0), TAKE_OWNERSHIP);
  846. Solve(options, &problem, &summary);
  847. Theory
  848. ------
  849. Let us consider a problem with a single parameter block.
  850. .. math::
  851. \min_x \frac{1}{2}\rho(f^2(x))
  852. Then, the robustified gradient and the Gauss-Newton Hessian are
  853. .. math::
  854. g(x) &= \rho'J^\top(x)f(x)\\
  855. H(x) &= J^\top(x)\left(\rho' + 2 \rho''f(x)f^\top(x)\right)J(x)
  856. where the terms involving the second derivatives of :math:`f(x)` have
  857. been ignored. Note that :math:`H(x)` is indefinite if
  858. :math:`\rho''f(x)^\top f(x) + \frac{1}{2}\rho' < 0`. If this is not
  859. the case, then its possible to re-weight the residual and the Jacobian
  860. matrix such that the robustified Gauss-Newton step corresponds to an
  861. ordinary linear least squares problem.
  862. Let :math:`\alpha` be a root of
  863. .. math:: \frac{1}{2}\alpha^2 - \alpha - \frac{\rho''}{\rho'}\|f(x)\|^2 = 0.
  864. Then, define the rescaled residual and Jacobian as
  865. .. math::
  866. \tilde{f}(x) &= \frac{\sqrt{\rho'}}{1 - \alpha} f(x)\\
  867. \tilde{J}(x) &= \sqrt{\rho'}\left(1 - \alpha
  868. \frac{f(x)f^\top(x)}{\left\|f(x)\right\|^2} \right)J(x)
  869. In the case :math:`2 \rho''\left\|f(x)\right\|^2 + \rho' \lesssim 0`,
  870. we limit :math:`\alpha \le 1- \epsilon` for some small
  871. :math:`\epsilon`. For more details see [Triggs]_.
  872. With this simple rescaling, one can apply any Jacobian based non-linear
  873. least squares algorithm to robustified non-linear least squares
  874. problems.
  875. While the theory described above is elegant, in practice we observe
  876. that using the Triggs correction when :math:`\rho'' > 0` leads to poor
  877. performance, so we upper bound it by zero. For more details see
  878. `corrector.cc <https://github.com/ceres-solver/ceres-solver/blob/master/internal/ceres/corrector.cc#L51>`_
  879. :class:`Manifold`
  880. ==================
  881. .. class:: Manifold
  882. In sensor fusion problems, we often have to model quantities that live
  883. in spaces known as `Manifolds
  884. <https://en.wikipedia.org/wiki/Manifold>`_, for example the
  885. rotation/orientation of a sensor that is represented by a `Quaternion
  886. <https://en.wikipedia.org/wiki/Quaternion>`_.
  887. Manifolds are spaces which locally look like Euclidean spaces. More
  888. precisely, at each point on the manifold there is a linear space that
  889. is tangent to the manifold. It has dimension equal to the intrinsic
  890. dimension of the manifold itself, which is less than or equal to the
  891. ambient space in which the manifold is embedded.
  892. For example, the tangent space to a point on a sphere in three
  893. dimensions is the two dimensional plane that is tangent to the sphere
  894. at that point. There are two reasons tangent spaces are interesting:
  895. 1. They are Eucliean spaces so the usual vector space operations apply
  896. there, which makes numerical operations easy.
  897. 2. Movements in the tangent space translate into movements along the
  898. manifold. Movements perpendicular to the tangent space do not
  899. translate into movements on the manifold.
  900. However, moving along the 2 dimensional plane tangent to the sphere
  901. and projecting back onto the sphere will move you away from the point
  902. you started from but moving along the normal at the same point and the
  903. projecting back onto the sphere brings you back to the point.
  904. Besides the mathematical niceness, modeling manifold valued
  905. quantities correctly and paying attention to their geometry has
  906. practical benefits too:
  907. 1. It naturally constrains the quantity to the manifold throughout the
  908. optimization, freeing the user from hacks like *quaternion
  909. normalization*.
  910. 2. It reduces the dimension of the optimization problem to its
  911. *natural* size. For example, a quantity restricted to a line is a
  912. one dimensional object regardless of the dimension of the ambient
  913. space in which this line lives.
  914. Working in the tangent space reduces not just the computational
  915. complexity of the optimization algorithm, but also improves the
  916. numerical behaviour of the algorithm.
  917. A basic operation one can perform on a manifold is the
  918. :math:`\boxplus` operation that computes the result of moving along
  919. :math:`\delta` in the tangent space at :math:`x`, and then projecting
  920. back onto the manifold that :math:`x` belongs to. Also known as a
  921. *Retraction*, :math:`\boxplus` is a generalization of vector addition
  922. in Euclidean spaces.
  923. The inverse of :math:`\boxplus` is :math:`\boxminus`, which given two
  924. points :math:`y` and :math:`x` on the manifold computes the tangent
  925. vector :math:`\Delta` at :math:`x` s.t. :math:`\boxplus(x, \Delta) =
  926. y`.
  927. Let us now consider two examples.
  928. The `Euclidean space <https://en.wikipedia.org/wiki/Euclidean_space>`_
  929. :math:`\mathbb{R}^n` is the simplest example of a manifold. It has
  930. dimension :math:`n` (and so does its tangent space) and
  931. :math:`\boxplus` and :math:`\boxminus` are the familiar vector sum and
  932. difference operations.
  933. .. math::
  934. \begin{align*}
  935. \boxplus(x, \Delta) &= x + \Delta = y\\
  936. \boxminus(y, x) &= y - x = \Delta.
  937. \end{align*}
  938. A more interesting case is the case :math:`SO(3)`, the `special
  939. orthogonal group <https://en.wikipedia.org/wiki/3D_rotation_group>`_
  940. in three dimensions - the space of :math:`3\times3` rotation
  941. matrices. :math:`SO(3)` is a three dimensional manifold embedded in
  942. :math:`\mathbb{R}^9` or :math:`\mathbb{R}^{3\times 3}`. So points on :math:`SO(3)` are
  943. represented using 9 dimensional vectors or :math:`3\times 3` matrices,
  944. and points in its tangent spaces are represented by 3 dimensional
  945. vectors.
  946. For :math:`SO(3)`, :math:`\boxplus` and :math:`\boxminus` are defined
  947. in terms of the matrix :math:`\exp` and :math:`\log` operations as
  948. follows:
  949. Given a 3-vector :math:`\Delta = [\begin{matrix}p,&q,&r\end{matrix}]`, we have
  950. .. math::
  951. \exp(\Delta) & = \left [ \begin{matrix}
  952. \cos \theta + cp^2 & -sr + cpq & sq + cpr \\
  953. sr + cpq & \cos \theta + cq^2& -sp + cqr \\
  954. -sq + cpr & sp + cqr & \cos \theta + cr^2
  955. \end{matrix} \right ]
  956. where,
  957. .. math::
  958. \begin{align}
  959. \theta &= \sqrt{p^2 + q^2 + r^2},\\
  960. s &= \frac{\sin \theta}{\theta},\\
  961. c &= \frac{1 - \cos \theta}{\theta^2}.
  962. \end{align}
  963. Given :math:`x \in SO(3)`, we have
  964. .. math::
  965. \log(x) = 1/(2 \sin(\theta)/\theta)\left[\begin{matrix} x_{32} - x_{23},& x_{13} - x_{31},& x_{21} - x_{12}\end{matrix} \right]
  966. where,
  967. .. math:: \theta = \cos^{-1}((\operatorname{Trace}(x) - 1)/2)
  968. Then,
  969. .. math::
  970. \begin{align*}
  971. \boxplus(x, \Delta) &= x \exp(\Delta)
  972. \\
  973. \boxminus(y, x) &= \log(x^T y)
  974. \end{align*}
  975. For :math:`\boxplus` and :math:`\boxminus` to be mathematically
  976. consistent, the following identities must be satisfied at all points
  977. :math:`x` on the manifold:
  978. 1. :math:`\boxplus(x, 0) = x`. This ensures that the tangent space is
  979. *centered* at :math:`x`, and the zero vector is the identity
  980. element.
  981. 2. For all :math:`y` on the manifold, :math:`\boxplus(x,
  982. \boxminus(y,x)) = y`. This ensures that any :math:`y` can be
  983. reached from math:`x`.
  984. 3. For all :math:`\Delta`, :math:`\boxminus(\boxplus(x, \Delta), x) =
  985. \Delta`. This ensures that :math:`\boxplus` is an injective
  986. (one-to-one) map.
  987. 4. For all :math:`\Delta_1, \Delta_2\ |\boxminus(\boxplus(x, \Delta_1),
  988. \boxplus(x, \Delta_2)) \leq |\Delta_1 - \Delta_2|`. Allows us to define
  989. a metric on the manifold.
  990. Additionally we require that :math:`\boxplus` and :math:`\boxminus` be
  991. sufficiently smooth. In particular they need to be differentiable
  992. everywhere on the manifold.
  993. For more details, please see [Hertzberg]_
  994. The :class:`Manifold` interface allows the user to define a manifold
  995. for the purposes optimization by implementing ``Plus`` and ``Minus``
  996. operations and their derivatives (corresponding naturally to
  997. :math:`\boxplus` and :math:`\boxminus`).
  998. .. code-block:: c++
  999. class Manifold {
  1000. public:
  1001. virtual ~Manifold();
  1002. virtual int AmbientSize() const = 0;
  1003. virtual int TangentSize() const = 0;
  1004. virtual bool Plus(const double* x,
  1005. const double* delta,
  1006. double* x_plus_delta) const = 0;
  1007. virtual bool PlusJacobian(const double* x, double* jacobian) const = 0;
  1008. virtual bool RightMultiplyByPlusJacobian(const double* x,
  1009. const int num_rows,
  1010. const double* ambient_matrix,
  1011. double* tangent_matrix) const;
  1012. virtual bool Minus(const double* y,
  1013. const double* x,
  1014. double* y_minus_x) const = 0;
  1015. virtual bool MinusJacobian(const double* x, double* jacobian) const = 0;
  1016. };
  1017. .. function:: int Manifold::AmbientSize() const;
  1018. Dimension of the ambient space in which the manifold is embedded.
  1019. .. function:: int Manifold::TangentSize() const;
  1020. Dimension of the manifold/tangent space.
  1021. .. function:: bool Plus(const double* x, const double* delta, double* x_plus_delta) const;
  1022. Implements the :math:`\boxplus(x,\Delta)` operation for the manifold.
  1023. A generalization of vector addition in Euclidean space, ``Plus``
  1024. computes the result of moving along ``delta`` in the tangent space
  1025. at ``x``, and then projecting back onto the manifold that ``x``
  1026. belongs to.
  1027. ``x`` and ``x_plus_delta`` are :func:`Manifold::AmbientSize` vectors.
  1028. ``delta`` is a :func:`Manifold::TangentSize` vector.
  1029. Return value indicates if the operation was successful or not.
  1030. .. function:: bool PlusJacobian(const double* x, double* jacobian) const;
  1031. Compute the derivative of :math:`\boxplus(x, \Delta)` w.r.t
  1032. :math:`\Delta` at :math:`\Delta = 0`, i.e. :math:`(D_2
  1033. \boxplus)(x, 0)`.
  1034. ``jacobian`` is a row-major :func:`Manifold::AmbientSize`
  1035. :math:`\times` :func:`Manifold::TangentSize` matrix.
  1036. Return value indicates whether the operation was successful or not.
  1037. .. function:: bool RightMultiplyByPlusJacobian(const double* x, const int num_rows, const double* ambient_matrix, double* tangent_matrix) const;
  1038. ``tangent_matrix`` = ``ambient_matrix`` :math:`\times` plus_jacobian.
  1039. ``ambient_matrix`` is a row-major ``num_rows`` :math:`\times`
  1040. :func:`Manifold::AmbientSize` matrix.
  1041. ``tangent_matrix`` is a row-major ``num_rows`` :math:`\times`
  1042. :func:`Manifold::TangentSize` matrix.
  1043. Return value indicates whether the operation was successful or not.
  1044. This function is only used by the :class:`GradientProblemSolver`,
  1045. where the dimension of the parameter block can be large and it may
  1046. be more efficient to compute this product directly rather than
  1047. first evaluating the Jacobian into a matrix and then doing a matrix
  1048. vector product.
  1049. Because this is not an often used function, we provide a default
  1050. implementation for convenience. If performance becomes an issue
  1051. then the user should consider implementing a specialization.
  1052. .. function:: bool Minus(const double* y, const double* x, double* y_minus_x) const;
  1053. Implements :math:`\boxminus(y,x)` operation for the manifold.
  1054. A generalization of vector subtraction in Euclidean spaces, given
  1055. two points ``x`` and ``y`` on the manifold, ``Minus`` computes the
  1056. change to ``x`` in the tangent space at ``x``, that will take it to
  1057. ``y``.
  1058. ``x`` and ``y`` are :func:`Manifold::AmbientSize` vectors.
  1059. ``y_minus_x`` is a ::func:`Manifold::TangentSize` vector.
  1060. Return value indicates if the operation was successful or not.
  1061. .. function:: bool MinusJacobian(const double* x, double* jacobian) const = 0;
  1062. Compute the derivative of :math:`\boxminus(y, x)` w.r.t :math:`y`
  1063. at :math:`y = x`, i.e :math:`(D_1 \boxminus) (x, x)`.
  1064. ``jacobian`` is a row-major :func:`Manifold::TangentSize`
  1065. :math:`\times` :func:`Manifold::AmbientSize` matrix.
  1066. Return value indicates whether the operation was successful or not.
  1067. Ceres Solver ships with a number of commonly used instances of
  1068. :class:`Manifold`.
  1069. For `Lie Groups <https://en.wikipedia.org/wiki/Lie_group>`_, a great
  1070. place to find high quality implementations is the `Sophus
  1071. <https://github.com/strasdat/Sophus>`_ library developed by Hauke
  1072. Strasdat and his collaborators.
  1073. :class:`EuclideanManifold`
  1074. --------------------------
  1075. .. class:: EuclideanManifold
  1076. :class:`EuclideanManifold` as the name implies represents a Euclidean
  1077. space, where the :math:`\boxplus` and :math:`\boxminus` operations are
  1078. the usual vector addition and subtraction.
  1079. .. math::
  1080. \begin{align*}
  1081. \boxplus(x, \Delta) &= x + \Delta\\
  1082. \boxminus(y,x) &= y - x
  1083. \end{align*}
  1084. By default parameter blocks are assumed to be Euclidean, so there is
  1085. no need to use this manifold on its own. It is provided for the
  1086. purpose of testing and for use in combination with other manifolds
  1087. using :class:`ProductManifold`.
  1088. The class works with dynamic and static ambient space dimensions. If
  1089. the ambient space dimensions is known at compile time use
  1090. .. code-block:: c++
  1091. EuclideanManifold<3> manifold;
  1092. If the ambient space dimensions is not known at compile time the
  1093. template parameter needs to be set to `ceres::DYNAMIC` and the actual
  1094. dimension needs to be provided as a constructor argument:
  1095. .. code-block:: c++
  1096. EuclideanManifold<ceres::DYNAMIC> manifold(ambient_dim);
  1097. :class:`SubsetManifold`
  1098. -----------------------
  1099. .. class:: SubsetManifold
  1100. Suppose :math:`x` is a two dimensional vector, and the user wishes to
  1101. hold the first coordinate constant. Then, :math:`\Delta` is a scalar
  1102. and :math:`\boxplus` is defined as
  1103. .. math::
  1104. \boxplus(x, \Delta) = x + \left[ \begin{array}{c} 0 \\ 1 \end{array} \right] \Delta
  1105. and given two, two-dimensional vectors :math:`x` and :math:`y` with
  1106. the same first coordinate, :math:`\boxminus` is defined as:
  1107. .. math::
  1108. \boxminus(y, x) = y[1] - x[1]
  1109. :class:`SubsetManifold` generalizes this construction to hold
  1110. any part of a parameter block constant by specifying the set of
  1111. coordinates that are held constant.
  1112. .. NOTE::
  1113. It is legal to hold *all* coordinates of a parameter block to
  1114. constant using a :class:`SubsetManifold`. It is the same as calling
  1115. :func:`Problem::SetParameterBlockConstant` on that parameter block.
  1116. :class:`ProductManifold`
  1117. ------------------------
  1118. .. class:: ProductManifold
  1119. In cases, where a parameter block is the Cartesian product of a number
  1120. of manifolds and you have the manifold of the individual
  1121. parameter blocks available, :class:`ProductManifold` can be used to
  1122. construct a :class:`Manifold` of the Cartesian product.
  1123. For the case of the rigid transformation, where say you have a
  1124. parameter block of size 7, where the first four entries represent the
  1125. rotation as a quaternion, and the next three the translation, a
  1126. manifold can be constructed as:
  1127. .. code-block:: c++
  1128. ProductManifold<QuaternionManifold, EuclideanManifold<3>> se3;
  1129. Manifolds can be copied and moved to :class:`ProductManifold`:
  1130. .. code-block:: c++
  1131. SubsetManifold manifold1(5, {2});
  1132. SubsetManifold manifold2(3, {0, 1});
  1133. ProductManifold<SubsetManifold, SubsetManifold> manifold(manifold1,
  1134. manifold2);
  1135. In advanced use cases, manifolds can be dynamically allocated and passed as (smart) pointers:
  1136. .. code-block:: c++
  1137. ProductManifold<std::unique_ptr<QuaternionManifold>, EuclideanManifold<3>> se3
  1138. {std::make_unique<QuaternionManifold>(), EuclideanManifold<3>{}};
  1139. In C++17, the template parameters can be left out as they are automatically
  1140. deduced making the initialization much simpler:
  1141. .. code-block:: c++
  1142. ProductManifold se3{QuaternionManifold{}, EuclideanManifold<3>{}};
  1143. :class:`QuaternionManifold`
  1144. ---------------------------
  1145. .. class:: QuaternionManifold
  1146. .. NOTE::
  1147. If you are using ``Eigen`` quaternions, then you should use
  1148. :class:`EigenQuaternionManifold` instead because ``Eigen`` uses a
  1149. different memory layout for its Quaternions.
  1150. Manifold for a Hamilton `Quaternion
  1151. <https://en.wikipedia.org/wiki/Quaternion>`_. Quaternions are a three
  1152. dimensional manifold represented as unit norm 4-vectors, i.e.
  1153. .. math:: q = \left [\begin{matrix}q_0,& q_1,& q_2,& q_3\end{matrix}\right], \quad \|q\| = 1
  1154. is the ambient space representation. Here :math:`q_0` is the scalar
  1155. part. :math:`q_1` is the coefficient of :math:`i`, :math:`q_2` is the
  1156. coefficient of :math:`j`, and :math:`q_3` is the coefficient of
  1157. :math:`k`. Where:
  1158. .. math::
  1159. \begin{align*}
  1160. i\times j &= k,\\
  1161. j\times k &= i,\\
  1162. k\times i &= j,\\
  1163. i\times i &= -1,\\
  1164. j\times j &= -1,\\
  1165. k\times k &= -1.
  1166. \end{align*}
  1167. The tangent space is three dimensional and the :math:`\boxplus` and
  1168. :math:`\boxminus` operators are defined in term of :math:`\exp` and
  1169. :math:`\log` operations.
  1170. .. math::
  1171. \begin{align*}
  1172. \boxplus(x, \Delta) &= \exp\left(\Delta\right) \otimes x \\
  1173. \boxminus(y,x) &= \log\left(y \otimes x^{-1}\right)
  1174. \end{align*}
  1175. Where :math:`\otimes` is the `Quaternion product
  1176. <https://en.wikipedia.org/wiki/Quaternion#Hamilton_product>`_ and
  1177. since :math:`x` is a unit quaternion, :math:`x^{-1} = [\begin{matrix}
  1178. q_0,& -q_1,& -q_2,& -q_3\end{matrix}]`. Given a vector :math:`\Delta
  1179. \in \mathbb{R}^3`,
  1180. .. math::
  1181. \exp(\Delta) = \left[ \begin{matrix}
  1182. \cos\left(\|\Delta\|\right)\\
  1183. \frac{\displaystyle \sin\left(|\Delta\|\right)}{\displaystyle \|\Delta\|} \Delta
  1184. \end{matrix} \right]
  1185. and given a unit quaternion :math:`q = \left [\begin{matrix}q_0,& q_1,& q_2,& q_3\end{matrix}\right]`
  1186. .. math::
  1187. \log(q) = \frac{\operatorname{atan2}\left(\sqrt{1-q_0^2},q_0\right)}{\sqrt{1-q_0^2}} \left [\begin{matrix}q_1,& q_2,& q_3\end{matrix}\right]
  1188. :class:`EigenQuaternionManifold`
  1189. --------------------------------
  1190. .. class:: EigenQuaternionManifold
  1191. Implements the quaternion manifold for `Eigen's
  1192. <http://eigen.tuxfamily.org/index.php?title=Main_Page>`_
  1193. representation of the Hamilton quaternion. Geometrically it is exactly
  1194. the same as the :class:`QuaternionManifold` defined above. However,
  1195. Eigen uses a different internal memory layout for the elements of the
  1196. quaternion than what is commonly used. It stores the quaternion in
  1197. memory as :math:`[q_1, q_2, q_3, q_0]` or :math:`[x, y, z, w]` where
  1198. the real (scalar) part is last.
  1199. Since Ceres operates on parameter blocks which are raw double pointers
  1200. this difference is important and requires a different manifold.
  1201. :class:`SphereManifold`
  1202. -----------------------
  1203. .. class:: SphereManifold
  1204. This provides a manifold on a sphere meaning that the norm of the
  1205. vector stays the same. Such cases often arises in Structure for Motion
  1206. problems. One example where they are used is in representing points
  1207. whose triangulation is ill-conditioned. Here it is advantageous to use
  1208. an over-parameterization since homogeneous vectors can represent
  1209. points at infinity.
  1210. The ambient space dimension is required to be greater than 1.
  1211. The class works with dynamic and static ambient space dimensions. If
  1212. the ambient space dimensions is known at compile time use
  1213. .. code-block:: c++
  1214. SphereManifold<3> manifold;
  1215. If the ambient space dimensions is not known at compile time the
  1216. template parameter needs to be set to `ceres::DYNAMIC` and the actual
  1217. dimension needs to be provided as a constructor argument:
  1218. .. code-block:: c++
  1219. SphereManifold<ceres::DYNAMIC> manifold(ambient_dim);
  1220. For more details, please see Section B.2 (p.25) in [Hertzberg]_
  1221. :class:`LineManifold`
  1222. ---------------------
  1223. .. class:: LineManifold
  1224. This class provides a manifold for lines, where the line is defined
  1225. using an origin point and a direction vector. So the ambient size
  1226. needs to be two times the dimension of the space in which the line
  1227. lives. The first half of the parameter block is interpreted as the
  1228. origin point and the second half as the direction. This manifold is a
  1229. special case of the `Affine Grassmannian manifold
  1230. <https://en.wikipedia.org/wiki/Affine_Grassmannian_(manifold))>`_ for
  1231. the case :math:`\operatorname{Graff}_1(R^n)`.
  1232. Note that this is a manifold for a line, rather than a point
  1233. constrained to lie on a line. It is useful when one wants to optimize
  1234. over the space of lines. For example, given :math:`n` distinct points
  1235. in 3D (measurements) we want to find the line that minimizes the sum
  1236. of squared distances to all the points.
  1237. :class:`AutoDiffManifold`
  1238. =========================
  1239. .. class:: AutoDiffManifold
  1240. Create a :class:`Manifold` with Jacobians computed via automatic
  1241. differentiation.
  1242. To get an auto differentiated manifold, you must define a Functor with
  1243. templated ``Plus`` and ``Minus`` functions that compute:
  1244. .. code-block:: c++
  1245. x_plus_delta = Plus(x, delta);
  1246. y_minus_x = Minus(y, x);
  1247. Where, ``x``, ``y`` and ``x_plus_y`` are vectors on the manifold in
  1248. the ambient space (so they are ``kAmbientSize`` vectors) and
  1249. ``delta``, ``y_minus_x`` are vectors in the tangent space (so they are
  1250. ``kTangentSize`` vectors).
  1251. The Functor should have the signature:
  1252. .. code-block:: c++
  1253. struct Functor {
  1254. template <typename T>
  1255. bool Plus(const T* x, const T* delta, T* x_plus_delta) const;
  1256. template <typename T>
  1257. bool Minus(const T* y, const T* x, T* y_minus_x) const;
  1258. };
  1259. Observe that the ``Plus`` and ``Minus`` operations are templated on
  1260. the parameter ``T``. The autodiff framework substitutes appropriate
  1261. ``Jet`` objects for ``T`` in order to compute the derivative when
  1262. necessary. This is the same mechanism that is used to compute
  1263. derivatives when using :class:`AutoDiffCostFunction`.
  1264. ``Plus`` and ``Minus`` should return true if the computation is
  1265. successful and false otherwise, in which case the result will not be
  1266. used.
  1267. Given this Functor, the corresponding :class:`Manifold` can be constructed as:
  1268. .. code-block:: c++
  1269. AutoDiffManifold<Functor, kAmbientSize, kTangentSize> manifold;
  1270. .. NOTE::
  1271. The following is only used for illustration purposes. Ceres Solver
  1272. ships with an optimized, production grade :class:`QuaternionManifold`
  1273. implementation.
  1274. As a concrete example consider the case of `Quaternions
  1275. <https://en.wikipedia.org/wiki/Quaternion>`_. Quaternions form a three
  1276. dimensional manifold embedded in :math:`\mathbb{R}^4`, i.e. they have
  1277. an ambient dimension of 4 and their tangent space has dimension 3. The
  1278. following Functor defines the ``Plus`` and ``Minus`` operations on the
  1279. Quaternion manifold. It assumes that the quaternions are laid out as
  1280. ``[w,x,y,z]`` in memory, i.e. the real or scalar part is the first
  1281. coordinate.
  1282. .. code-block:: c++
  1283. struct QuaternionFunctor {
  1284. template <typename T>
  1285. bool Plus(const T* x, const T* delta, T* x_plus_delta) const {
  1286. const T squared_norm_delta =
  1287. delta[0] * delta[0] + delta[1] * delta[1] + delta[2] * delta[2];
  1288. T q_delta[4];
  1289. if (squared_norm_delta > T(0.0)) {
  1290. T norm_delta = sqrt(squared_norm_delta);
  1291. const T sin_delta_by_delta = sin(norm_delta) / norm_delta;
  1292. q_delta[0] = cos(norm_delta);
  1293. q_delta[1] = sin_delta_by_delta * delta[0];
  1294. q_delta[2] = sin_delta_by_delta * delta[1];
  1295. q_delta[3] = sin_delta_by_delta * delta[2];
  1296. } else {
  1297. // We do not just use q_delta = [1,0,0,0] here because that is a
  1298. // constant and when used for automatic differentiation will
  1299. // lead to a zero derivative. Instead we take a first order
  1300. // approximation and evaluate it at zero.
  1301. q_delta[0] = T(1.0);
  1302. q_delta[1] = delta[0];
  1303. q_delta[2] = delta[1];
  1304. q_delta[3] = delta[2];
  1305. }
  1306. QuaternionProduct(q_delta, x, x_plus_delta);
  1307. return true;
  1308. }
  1309. template <typename T>
  1310. bool Minus(const T* y, const T* x, T* y_minus_x) const {
  1311. T minus_x[4] = {x[0], -x[1], -x[2], -x[3]};
  1312. T ambient_y_minus_x[4];
  1313. QuaternionProduct(y, minus_x, ambient_y_minus_x);
  1314. T u_norm = sqrt(ambient_y_minus_x[1] * ambient_y_minus_x[1] +
  1315. ambient_y_minus_x[2] * ambient_y_minus_x[2] +
  1316. ambient_y_minus_x[3] * ambient_y_minus_x[3]);
  1317. if (u_norm > 0.0) {
  1318. T theta = atan2(u_norm, ambient_y_minus_x[0]);
  1319. y_minus_x[0] = theta * ambient_y_minus_x[1] / u_norm;
  1320. y_minus_x[1] = theta * ambient_y_minus_x[2] / u_norm;
  1321. y_minus_x[2] = theta * ambient_y_minus_x[3] / u_norm;
  1322. } else {
  1323. We do not use [0,0,0] here because even though the value part is
  1324. a constant, the derivative part is not.
  1325. y_minus_x[0] = ambient_y_minus_x[1];
  1326. y_minus_x[1] = ambient_y_minus_x[2];
  1327. y_minus_x[2] = ambient_y_minus_x[3];
  1328. }
  1329. return true;
  1330. }
  1331. };
  1332. Then given this struct, the auto differentiated Quaternion Manifold can now
  1333. be constructed as
  1334. .. code-block:: c++
  1335. Manifold* manifold = new AutoDiffManifold<QuaternionFunctor, 4, 3>;
  1336. :class:`Problem`
  1337. ================
  1338. .. class:: Problem
  1339. :class:`Problem` holds the robustified bounds constrained
  1340. non-linear least squares problem :eq:`ceresproblem_modeling`. To
  1341. create a least squares problem, use the
  1342. :func:`Problem::AddResidalBlock` and
  1343. :func:`Problem::AddParameterBlock` methods.
  1344. For example a problem containing 3 parameter blocks of sizes 3, 4
  1345. and 5 respectively and two residual blocks of size 2 and 6:
  1346. .. code-block:: c++
  1347. double x1[] = { 1.0, 2.0, 3.0 };
  1348. double x2[] = { 1.0, 2.0, 3.0, 5.0 };
  1349. double x3[] = { 1.0, 2.0, 3.0, 6.0, 7.0 };
  1350. Problem problem;
  1351. problem.AddResidualBlock(new MyUnaryCostFunction(...), x1);
  1352. problem.AddResidualBlock(new MyBinaryCostFunction(...), x2, x3);
  1353. :func:`Problem::AddResidualBlock` as the name implies, adds a
  1354. residual block to the problem. It adds a :class:`CostFunction`, an
  1355. optional :class:`LossFunction` and connects the
  1356. :class:`CostFunction` to a set of parameter block.
  1357. The cost function carries with it information about the sizes of
  1358. the parameter blocks it expects. The function checks that these
  1359. match the sizes of the parameter blocks listed in
  1360. ``parameter_blocks``. The program aborts if a mismatch is
  1361. detected. ``loss_function`` can be ``nullptr``, in which case the cost
  1362. of the term is just the squared norm of the residuals.
  1363. The user has the option of explicitly adding the parameter blocks
  1364. using :func:`Problem::AddParameterBlock`. This causes additional
  1365. correctness checking; however, :func:`Problem::AddResidualBlock`
  1366. implicitly adds the parameter blocks if they are not present, so
  1367. calling :func:`Problem::AddParameterBlock` explicitly is not
  1368. required.
  1369. :func:`Problem::AddParameterBlock` explicitly adds a parameter
  1370. block to the :class:`Problem`. Optionally it allows the user to
  1371. associate a :class:`Manifold` object with the parameter block
  1372. too. Repeated calls with the same arguments are ignored. Repeated
  1373. calls with the same double pointer but a different size results in
  1374. undefined behavior.
  1375. You can set any parameter block to be constant using
  1376. :func:`Problem::SetParameterBlockConstant` and undo this using
  1377. :func:`SetParameterBlockVariable`.
  1378. In fact you can set any number of parameter blocks to be constant,
  1379. and Ceres is smart enough to figure out what part of the problem
  1380. you have constructed depends on the parameter blocks that are free
  1381. to change and only spends time solving it. So for example if you
  1382. constructed a problem with a million parameter blocks and 2 million
  1383. residual blocks, but then set all but one parameter blocks to be
  1384. constant and say only 10 residual blocks depend on this one
  1385. non-constant parameter block. Then the computational effort Ceres
  1386. spends in solving this problem will be the same if you had defined
  1387. a problem with one parameter block and 10 residual blocks.
  1388. **Ownership**
  1389. :class:`Problem` by default takes ownership of the
  1390. ``cost_function``, ``loss_function`` and ``manifold`` pointers. These
  1391. objects remain live for the life of the :class:`Problem`. If the user wishes
  1392. to keep control over the destruction of these objects, then they can do this
  1393. by setting the corresponding enums in the :class:`Problem::Options` struct.
  1394. Note that even though the Problem takes ownership of objects,
  1395. ``cost_function`` and ``loss_function``, it does not preclude the
  1396. user from re-using them in another residual block. Similarly the
  1397. same ``manifold`` object can be used with multiple parameter blocks. The
  1398. destructor takes care to call delete on each owned object exactly once.
  1399. .. class:: Problem::Options
  1400. Options struct that is used to control :class:`Problem`.
  1401. .. member:: Ownership Problem::Options::cost_function_ownership
  1402. Default: ``TAKE_OWNERSHIP``
  1403. This option controls whether the Problem object owns the cost
  1404. functions.
  1405. If set to ``TAKE_OWNERSHIP``, then the problem object will delete the
  1406. cost functions on destruction. The destructor is careful to delete
  1407. the pointers only once, since sharing cost functions is allowed.
  1408. .. member:: Ownership Problem::Options::loss_function_ownership
  1409. Default: ``TAKE_OWNERSHIP``
  1410. This option controls whether the Problem object owns the loss
  1411. functions.
  1412. If set to ``TAKE_OWNERSHIP``, then the problem object will delete the
  1413. loss functions on destruction. The destructor is careful to delete
  1414. the pointers only once, since sharing loss functions is allowed.
  1415. .. member:: Ownership Problem::Options::manifold_ownership
  1416. Default: ``TAKE_OWNERSHIP``
  1417. This option controls whether the Problem object owns the manifolds.
  1418. If set to ``TAKE_OWNERSHIP``, then the problem object will delete the
  1419. manifolds on destruction. The destructor is careful to delete the
  1420. pointers only once, since sharing manifolds is allowed.
  1421. .. member:: bool Problem::Options::enable_fast_removal
  1422. Default: ``false``
  1423. If true, trades memory for faster
  1424. :func:`Problem::RemoveResidualBlock` and
  1425. :func:`Problem::RemoveParameterBlock` operations.
  1426. By default, :func:`Problem::RemoveParameterBlock` and
  1427. :func:`Problem::RemoveResidualBlock` take time proportional to
  1428. the size of the entire problem. If you only ever remove
  1429. parameters or residuals from the problem occasionally, this might
  1430. be acceptable. However, if you have memory to spare, enable this
  1431. option to make :func:`Problem::RemoveParameterBlock` take time
  1432. proportional to the number of residual blocks that depend on it,
  1433. and :func:`Problem::RemoveResidualBlock` take (on average)
  1434. constant time.
  1435. The increase in memory usage is twofold: an additional hash set
  1436. per parameter block containing all the residuals that depend on
  1437. the parameter block; and a hash set in the problem containing all
  1438. residuals.
  1439. .. member:: bool Problem::Options::disable_all_safety_checks
  1440. Default: `false`
  1441. By default, Ceres performs a variety of safety checks when
  1442. constructing the problem. There is a small but measurable
  1443. performance penalty to these checks, typically around 5% of
  1444. construction time. If you are sure your problem construction is
  1445. correct, and 5% of the problem construction time is truly an
  1446. overhead you want to avoid, then you can set
  1447. disable_all_safety_checks to true.
  1448. .. warning::
  1449. Do not set this to true, unless you are absolutely sure of what you are
  1450. doing.
  1451. .. member:: Context* Problem::Options::context
  1452. Default: ``nullptr``
  1453. A Ceres global context to use for solving this problem. This may
  1454. help to reduce computation time as Ceres can reuse expensive
  1455. objects to create. The context object can be `nullptr`, in which
  1456. case Ceres may create one.
  1457. Ceres does NOT take ownership of the pointer.
  1458. .. member:: EvaluationCallback* Problem::Options::evaluation_callback
  1459. Default: ``nullptr``
  1460. Using this callback interface, Ceres will notify you when it is
  1461. about to evaluate the residuals or Jacobians.
  1462. If an ``evaluation_callback`` is present, Ceres will update the
  1463. user's parameter blocks to the values that will be used when
  1464. calling :func:`CostFunction::Evaluate` before calling
  1465. :func:`EvaluationCallback::PrepareForEvaluation`. One can then use
  1466. this callback to share (or cache) computation between cost
  1467. functions by doing the shared computation in
  1468. :func:`EvaluationCallback::PrepareForEvaluation` before Ceres
  1469. calls :func:`CostFunction::Evaluate`.
  1470. Problem does NOT take ownership of the callback.
  1471. .. NOTE::
  1472. Evaluation callbacks are incompatible with inner iterations. So
  1473. calling Solve with
  1474. :member:`Solver::Options::use_inner_iterations` set to ``true``
  1475. on a :class:`Problem` with a non-null evaluation callback is an
  1476. error.
  1477. .. function:: ResidualBlockId Problem::AddResidualBlock(CostFunction* cost_function, LossFunction* loss_function, const std::vector<double*> parameter_blocks)
  1478. .. function:: template <typename Ts...> ResidualBlockId Problem::AddResidualBlock(CostFunction* cost_function, LossFunction* loss_function, double* x0, Ts... xs)
  1479. Add a residual block to the overall cost function. The cost
  1480. function carries with it information about the sizes of the
  1481. parameter blocks it expects. The function checks that these match
  1482. the sizes of the parameter blocks listed in parameter_blocks. The
  1483. program aborts if a mismatch is detected. loss_function can be
  1484. ``nullptr``, in which case the cost of the term is just the squared
  1485. norm of the residuals.
  1486. The parameter blocks may be passed together as a
  1487. ``vector<double*>``, or ``double*`` pointers.
  1488. The user has the option of explicitly adding the parameter blocks
  1489. using AddParameterBlock. This causes additional correctness
  1490. checking; however, AddResidualBlock implicitly adds the parameter
  1491. blocks if they are not present, so calling AddParameterBlock
  1492. explicitly is not required.
  1493. The Problem object by default takes ownership of the
  1494. cost_function and loss_function pointers. These objects remain
  1495. live for the life of the Problem object. If the user wishes to
  1496. keep control over the destruction of these objects, then they can
  1497. do this by setting the corresponding enums in the Options struct.
  1498. .. note::
  1499. Even though the Problem takes ownership of ``cost_function``
  1500. and ``loss_function``, it does not preclude the user from re-using
  1501. them in another residual block. The destructor takes care to call
  1502. delete on each cost_function or loss_function pointer only once,
  1503. regardless of how many residual blocks refer to them.
  1504. Example usage:
  1505. .. code-block:: c++
  1506. double x1[] = {1.0, 2.0, 3.0};
  1507. double x2[] = {1.0, 2.0, 5.0, 6.0};
  1508. double x3[] = {3.0, 6.0, 2.0, 5.0, 1.0};
  1509. std::vector<double*> v1;
  1510. v1.push_back(x1);
  1511. std::vector<double*> v2;
  1512. v2.push_back(x2);
  1513. v2.push_back(x1);
  1514. Problem problem;
  1515. problem.AddResidualBlock(new MyUnaryCostFunction(...), nullptr, x1);
  1516. problem.AddResidualBlock(new MyBinaryCostFunction(...), nullptr, x2, x1);
  1517. problem.AddResidualBlock(new MyUnaryCostFunction(...), nullptr, v1);
  1518. problem.AddResidualBlock(new MyBinaryCostFunction(...), nullptr, v2);
  1519. .. function:: void Problem::AddParameterBlock(double* values, int size, Manifold* manifold)
  1520. Add a parameter block with appropriate size and Manifold to the
  1521. problem. It is okay for ``manifold`` to be ``nullptr``.
  1522. Repeated calls with the same arguments are ignored. Repeated calls
  1523. with the same double pointer but a different size results in a crash
  1524. (unless :member:`Solver::Options::disable_all_safety_checks` is set to true).
  1525. Repeated calls with the same double pointer and size but different
  1526. :class:`Manifold` is equivalent to calling `SetManifold(manifold)`,
  1527. i.e., any previously associated :class:`Manifold` object will be replaced
  1528. with the `manifold`.
  1529. .. function:: void Problem::AddParameterBlock(double* values, int size)
  1530. Add a parameter block with appropriate size and parameterization to
  1531. the problem. Repeated calls with the same arguments are
  1532. ignored. Repeated calls with the same double pointer but a
  1533. different size results in undefined behavior.
  1534. .. function:: void Problem::RemoveResidualBlock(ResidualBlockId residual_block)
  1535. Remove a residual block from the problem.
  1536. Since residual blocks are allowed to share cost function and loss
  1537. function objects, Ceres Solver uses a reference counting
  1538. mechanism. So when a residual block is deleted, the reference count
  1539. for the corresponding cost function and loss function objects are
  1540. decreased and when this count reaches zero, they are deleted.
  1541. If :member:`Problem::Options::enable_fast_removal` is ``true``, then the removal
  1542. is fast (almost constant time). Otherwise it is linear, requiring a
  1543. scan of the entire problem.
  1544. Removing a residual block has no effect on the parameter blocks
  1545. that the problem depends on.
  1546. .. warning::
  1547. Removing a residual or parameter block will destroy the implicit
  1548. ordering, rendering the jacobian or residuals returned from the solver
  1549. uninterpretable. If you depend on the evaluated jacobian, do not use
  1550. remove! This may change in a future release. Hold the indicated parameter
  1551. block constant during optimization.
  1552. .. function:: void Problem::RemoveParameterBlock(const double* values)
  1553. Remove a parameter block from the problem. Any residual blocks that
  1554. depend on the parameter are also removed, as described above in
  1555. :func:`RemoveResidualBlock()`.
  1556. The manifold of the parameter block, if it exists, will persist until the
  1557. deletion of the problem.
  1558. If :member:`Problem::Options::enable_fast_removal` is ``true``, then the removal
  1559. is fast (almost constant time). Otherwise, removing a parameter
  1560. block will scan the entire Problem.
  1561. .. warning::
  1562. Removing a residual or parameter block will destroy the implicit
  1563. ordering, rendering the jacobian or residuals returned from the solver
  1564. uninterpretable. If you depend on the evaluated jacobian, do not use
  1565. remove! This may change in a future release.
  1566. .. function:: void Problem::SetParameterBlockConstant(const double* values)
  1567. Hold the indicated parameter block constant during optimization.
  1568. .. function:: void Problem::SetParameterBlockVariable(double* values)
  1569. Allow the indicated parameter to vary during optimization.
  1570. .. function:: bool Problem::IsParameterBlockConstant(const double* values) const
  1571. Returns ``true`` if a parameter block is set constant, and false
  1572. otherwise. A parameter block may be set constant in two ways:
  1573. either by calling ``SetParameterBlockConstant`` or by associating a
  1574. :class:`Manifold` with a zero dimensional tangent space with it.
  1575. .. function:: void SetManifold(double* values, Manifold* manifold);
  1576. Set the :class:`Manifold` for the parameter block. Calling
  1577. :func:`Problem::SetManifold` with ``nullptr`` will clear any
  1578. previously set :class:`Manifold` for the parameter block.
  1579. Repeated calls will result in any previously associated
  1580. :class:`Manifold` object to be replaced with ``manifold``.
  1581. ``manifold`` is owned by :class:`Problem` by default (See
  1582. :class:`Problem::Options` to override this behaviour).
  1583. It is acceptable to set the same :class:`Manifold` for multiple
  1584. parameter blocks.
  1585. .. function:: const Manifold* GetManifold(const double* values) const;
  1586. Get the :class:`Manifold` object associated with this parameter block.
  1587. If there is no :class:`Manifold` object associated with the parameter block,
  1588. then ``nullptr`` is returned.
  1589. .. function:: bool HasManifold(const double* values) const;
  1590. Returns ``true`` if a :class:`Manifold` is associated with this parameter
  1591. block, ``false`` otherwise.
  1592. .. function:: void Problem::SetParameterLowerBound(double* values, int index, double lower_bound)
  1593. Set the lower bound for the parameter at position `index` in the
  1594. parameter block corresponding to `values`. By default the lower
  1595. bound is ``-std::numeric_limits<double>::max()``, which is treated
  1596. by the solver as the same as :math:`-\infty`.
  1597. .. function:: void Problem::SetParameterUpperBound(double* values, int index, double upper_bound)
  1598. Set the upper bound for the parameter at position `index` in the
  1599. parameter block corresponding to `values`. By default the value is
  1600. ``std::numeric_limits<double>::max()``, which is treated by the
  1601. solver as the same as :math:`\infty`.
  1602. .. function:: double Problem::GetParameterLowerBound(const double* values, int index)
  1603. Get the lower bound for the parameter with position `index`. If the
  1604. parameter is not bounded by the user, then its lower bound is
  1605. ``-std::numeric_limits<double>::max()``.
  1606. .. function:: double Problem::GetParameterUpperBound(const double* values, int index)
  1607. Get the upper bound for the parameter with position `index`. If the
  1608. parameter is not bounded by the user, then its upper bound is
  1609. ``std::numeric_limits<double>::max()``.
  1610. .. function:: int Problem::NumParameterBlocks() const
  1611. Number of parameter blocks in the problem. Always equals
  1612. parameter_blocks().size() and parameter_block_sizes().size().
  1613. .. function:: int Problem::NumParameters() const
  1614. The size of the parameter vector obtained by summing over the sizes
  1615. of all the parameter blocks.
  1616. .. function:: int Problem::NumResidualBlocks() const
  1617. Number of residual blocks in the problem. Always equals
  1618. residual_blocks().size().
  1619. .. function:: int Problem::NumResiduals() const
  1620. The size of the residual vector obtained by summing over the sizes
  1621. of all of the residual blocks.
  1622. .. function:: int Problem::ParameterBlockSize(const double* values) const
  1623. The size of the parameter block.
  1624. .. function:: int Problem::ParameterBlockTangentSize(const double* values) const
  1625. The dimension of the tangent space of the :class:`Manifold` for the
  1626. parameter block. If there is no :class:`Manifold` associated with this
  1627. parameter block, then ``ParameterBlockTangentSize = ParameterBlockSize``.
  1628. .. function:: bool Problem::HasParameterBlock(const double* values) const
  1629. Is the given parameter block present in the problem or not?
  1630. .. function:: void Problem::GetParameterBlocks(std::vector<double*>* parameter_blocks) const
  1631. Fills the passed ``parameter_blocks`` vector with pointers to the
  1632. parameter blocks currently in the problem. After this call,
  1633. ``parameter_block.size() == NumParameterBlocks``.
  1634. .. function:: void Problem::GetResidualBlocks(std::vector<ResidualBlockId>* residual_blocks) const
  1635. Fills the passed `residual_blocks` vector with pointers to the
  1636. residual blocks currently in the problem. After this call,
  1637. `residual_blocks.size() == NumResidualBlocks`.
  1638. .. function:: void Problem::GetParameterBlocksForResidualBlock(const ResidualBlockId residual_block, std::vector<double*>* parameter_blocks) const
  1639. Get all the parameter blocks that depend on the given residual
  1640. block.
  1641. .. function:: void Problem::GetResidualBlocksForParameterBlock(const double* values, std::vector<ResidualBlockId>* residual_blocks) const
  1642. Get all the residual blocks that depend on the given parameter
  1643. block.
  1644. If :member:`Problem::Options::enable_fast_removal` is
  1645. ``true``, then getting the residual blocks is fast and depends only
  1646. on the number of residual blocks. Otherwise, getting the residual
  1647. blocks for a parameter block will scan the entire problem.
  1648. .. function:: const CostFunction* Problem::GetCostFunctionForResidualBlock(const ResidualBlockId residual_block) const
  1649. Get the :class:`CostFunction` for the given residual block.
  1650. .. function:: const LossFunction* Problem::GetLossFunctionForResidualBlock(const ResidualBlockId residual_block) const
  1651. Get the :class:`LossFunction` for the given residual block.
  1652. .. function:: bool EvaluateResidualBlock(ResidualBlockId residual_block_id, bool apply_loss_function, double* cost,double* residuals, double** jacobians) const
  1653. Evaluates the residual block, storing the scalar cost in ``cost``, the
  1654. residual components in ``residuals``, and the jacobians between the
  1655. parameters and residuals in ``jacobians[i]``, in row-major order.
  1656. If ``residuals`` is ``nullptr``, the residuals are not computed.
  1657. If ``jacobians`` is ``nullptr``, no Jacobians are computed. If
  1658. ``jacobians[i]`` is ``nullptr``, then the Jacobian for that
  1659. parameter block is not computed.
  1660. It is not okay to request the Jacobian w.r.t a parameter block
  1661. that is constant.
  1662. The return value indicates the success or failure. Even if the
  1663. function returns false, the caller should expect the output
  1664. memory locations to have been modified.
  1665. The returned cost and jacobians have had robustification and
  1666. :class:`Manifold` applied already; for example, the jacobian for a
  1667. 4-dimensional quaternion parameter using the :class:`QuaternionManifold` is
  1668. ``num_residuals x 3`` instead of ``num_residuals x 4``.
  1669. ``apply_loss_function`` as the name implies allows the user to
  1670. switch the application of the loss function on and off.
  1671. .. NOTE:: If an :class:`EvaluationCallback` is associated with the
  1672. problem, then its
  1673. :func:`EvaluationCallback::PrepareForEvaluation` method will be
  1674. called every time this method is called with `new_point =
  1675. true`. This conservatively assumes that the user may have
  1676. changed the parameter values since the previous call to evaluate
  1677. / solve. For improved efficiency, and only if you know that the
  1678. parameter values have not changed between calls, see
  1679. :func:`Problem::EvaluateResidualBlockAssumingParametersUnchanged`.
  1680. .. function:: bool EvaluateResidualBlockAssumingParametersUnchanged(ResidualBlockId residual_block_id, bool apply_loss_function, double* cost,double* residuals, double** jacobians) const
  1681. Same as :func:`Problem::EvaluateResidualBlock` except that if an
  1682. :class:`EvaluationCallback` is associated with the problem, then
  1683. its :func:`EvaluationCallback::PrepareForEvaluation` method will
  1684. be called every time this method is called with new_point = false.
  1685. This means, if an :class:`EvaluationCallback` is associated with
  1686. the problem then it is the user's responsibility to call
  1687. :func:`EvaluationCallback::PrepareForEvaluation` before calling
  1688. this method if necessary, i.e. iff the parameter values have been
  1689. changed since the last call to evaluate / solve.'
  1690. This is because, as the name implies, we assume that the parameter
  1691. blocks did not change since the last time
  1692. :func:`EvaluationCallback::PrepareForEvaluation` was called (via
  1693. :func:`Solve`, :func:`Problem::Evaluate` or
  1694. :func:`Problem::EvaluateResidualBlock`).
  1695. .. function:: bool Problem::Evaluate(const Problem::EvaluateOptions& options, double* cost, std::vector<double>* residuals, std::vector<double>* gradient, CRSMatrix* jacobian)
  1696. Evaluate a :class:`Problem`. Any of the output pointers can be
  1697. ``nullptr``. Which residual blocks and parameter blocks are used is
  1698. controlled by the :class:`Problem::EvaluateOptions` struct below.
  1699. .. NOTE::
  1700. The evaluation will use the values stored in the memory
  1701. locations pointed to by the parameter block pointers used at the
  1702. time of the construction of the problem, for example in the
  1703. following code:
  1704. .. code-block:: c++
  1705. Problem problem;
  1706. double x = 1;
  1707. problem.Add(new MyCostFunction, nullptr, &x);
  1708. double cost = 0.0;
  1709. problem.Evaluate(Problem::EvaluateOptions(), &cost, nullptr, nullptr, nullptr);
  1710. The cost is evaluated at `x = 1`. If you wish to evaluate the
  1711. problem at `x = 2`, then
  1712. .. code-block:: c++
  1713. x = 2;
  1714. problem.Evaluate(Problem::EvaluateOptions(), &cost, nullptr, nullptr, nullptr);
  1715. is the way to do so.
  1716. .. NOTE::
  1717. If no :class:`Manifold` are used, then the size of the gradient vector is
  1718. the sum of the sizes of all the parameter blocks. If a parameter block has
  1719. a manifold then it contributes "TangentSize" entries to the gradient
  1720. vector.
  1721. .. NOTE::
  1722. This function cannot be called while the problem is being
  1723. solved, for example it cannot be called from an
  1724. :class:`IterationCallback` at the end of an iteration during a
  1725. solve.
  1726. .. NOTE::
  1727. If an EvaluationCallback is associated with the problem, then
  1728. its PrepareForEvaluation method will be called everytime this
  1729. method is called with ``new_point = true``.
  1730. .. class:: Problem::EvaluateOptions
  1731. Options struct that is used to control :func:`Problem::Evaluate`.
  1732. .. member:: std::vector<double*> Problem::EvaluateOptions::parameter_blocks
  1733. The set of parameter blocks for which evaluation should be
  1734. performed. This vector determines the order in which parameter
  1735. blocks occur in the gradient vector and in the columns of the
  1736. jacobian matrix. If parameter_blocks is empty, then it is assumed
  1737. to be equal to a vector containing ALL the parameter
  1738. blocks. Generally speaking the ordering of the parameter blocks in
  1739. this case depends on the order in which they were added to the
  1740. problem and whether or not the user removed any parameter blocks.
  1741. **NOTE** This vector should contain the same pointers as the ones
  1742. used to add parameter blocks to the Problem. These parameter block
  1743. should NOT point to new memory locations. Bad things will happen if
  1744. you do.
  1745. .. member:: std::vector<ResidualBlockId> Problem::EvaluateOptions::residual_blocks
  1746. The set of residual blocks for which evaluation should be
  1747. performed. This vector determines the order in which the residuals
  1748. occur, and how the rows of the jacobian are ordered. If
  1749. residual_blocks is empty, then it is assumed to be equal to the
  1750. vector containing all the residual blocks.
  1751. .. member:: bool Problem::EvaluateOptions::apply_loss_function
  1752. Even though the residual blocks in the problem may contain loss
  1753. functions, setting apply_loss_function to false will turn off the
  1754. application of the loss function to the output of the cost
  1755. function. This is of use for example if the user wishes to analyse
  1756. the solution quality by studying the distribution of residuals
  1757. before and after the solve.
  1758. .. member:: int Problem::EvaluateOptions::num_threads
  1759. Number of threads to use.
  1760. :class:`EvaluationCallback`
  1761. ===========================
  1762. .. class:: EvaluationCallback
  1763. Interface for receiving callbacks before Ceres evaluates residuals or
  1764. Jacobians:
  1765. .. code-block:: c++
  1766. class EvaluationCallback {
  1767. public:
  1768. virtual ~EvaluationCallback();
  1769. virtual void PrepareForEvaluation(bool evaluate_jacobians,
  1770. bool new_evaluation_point) = 0;
  1771. };
  1772. .. function:: void EvaluationCallback::PrepareForEvaluation(bool evaluate_jacobians, bool new_evaluation_point)
  1773. Ceres will call :func:`EvaluationCallback::PrepareForEvaluation`
  1774. every time, and once before it computes the residuals and/or the
  1775. Jacobians.
  1776. User parameters (the double* values provided by the user) are fixed
  1777. until the next call to
  1778. :func:`EvaluationCallback::PrepareForEvaluation`. If
  1779. ``new_evaluation_point == true``, then this is a new point that is
  1780. different from the last evaluated point. Otherwise, it is the same
  1781. point that was evaluated previously (either Jacobian or residual)
  1782. and the user can use cached results from previous evaluations. If
  1783. ``evaluate_jacobians`` is ``true``, then Ceres will request Jacobians
  1784. in the upcoming cost evaluation.
  1785. Using this callback interface, Ceres can notify you when it is
  1786. about to evaluate the residuals or Jacobians. With the callback,
  1787. you can share computation between residual blocks by doing the
  1788. shared computation in
  1789. :func:`EvaluationCallback::PrepareForEvaluation` before Ceres calls
  1790. :func:`CostFunction::Evaluate` on all the residuals. It also
  1791. enables caching results between a pure residual evaluation and a
  1792. residual & Jacobian evaluation, via the ``new_evaluation_point``
  1793. argument.
  1794. One use case for this callback is if the cost function compute is
  1795. moved to the GPU. In that case, the prepare call does the actual
  1796. cost function evaluation, and subsequent calls from Ceres to the
  1797. actual cost functions merely copy the results from the GPU onto the
  1798. corresponding blocks for Ceres to plug into the solver.
  1799. **Note**: Ceres provides no mechanism to share data other than the
  1800. notification from the callback. Users must provide access to
  1801. pre-computed shared data to their cost functions behind the scenes;
  1802. this all happens without Ceres knowing. One approach is to put a
  1803. pointer to the shared data in each cost function (recommended) or
  1804. to use a global shared variable (discouraged; bug-prone). As far
  1805. as Ceres is concerned, it is evaluating cost functions like any
  1806. other; it just so happens that behind the scenes the cost functions
  1807. reuse pre-computed data to execute faster. See
  1808. `examples/evaluation_callback_example.cc
  1809. <https://ceres-solver.googlesource.com/ceres-solver/+/master/examples/evaluation_callback_example.cc>`_
  1810. for an example.
  1811. See ``evaluation_callback_test.cc`` for code that explicitly
  1812. verifies the preconditions between
  1813. :func:`EvaluationCallback::PrepareForEvaluation` and
  1814. :func:`CostFunction::Evaluate`.
  1815. ``rotation.h``
  1816. ==============
  1817. Many applications of Ceres Solver involve optimization problems where
  1818. some of the variables correspond to rotations. To ease the pain of
  1819. work with the various representations of rotations (angle-axis,
  1820. quaternion and matrix) we provide a handy set of templated
  1821. functions. These functions are templated so that the user can use them
  1822. within Ceres Solver's automatic differentiation framework.
  1823. .. function:: template <typename T> void AngleAxisToQuaternion(T const* angle_axis, T* quaternion)
  1824. Convert a value in combined axis-angle representation to a
  1825. quaternion.
  1826. The value ``angle_axis`` is a triple whose norm is an angle in radians,
  1827. and whose direction is aligned with the axis of rotation, and
  1828. ``quaternion`` is a 4-tuple that will contain the resulting quaternion.
  1829. .. function:: template <typename T> void QuaternionToAngleAxis(T const* quaternion, T* angle_axis)
  1830. Convert a quaternion to the equivalent combined axis-angle
  1831. representation.
  1832. The value ``quaternion`` must be a unit quaternion - it is not
  1833. normalized first, and ``angle_axis`` will be filled with a value
  1834. whose norm is the angle of rotation in radians, and whose direction
  1835. is the axis of rotation.
  1836. .. function:: template <typename T, int row_stride, int col_stride> void RotationMatrixToAngleAxis(const MatrixAdapter<const T, row_stride, col_stride>& R, T * angle_axis)
  1837. .. function:: template <typename T, int row_stride, int col_stride> void AngleAxisToRotationMatrix(T const * angle_axis, const MatrixAdapter<T, row_stride, col_stride>& R)
  1838. .. function:: template <typename T> void RotationMatrixToAngleAxis(T const * R, T * angle_axis)
  1839. .. function:: template <typename T> void AngleAxisToRotationMatrix(T const * angle_axis, T * R)
  1840. Conversions between :math:`3\times3` rotation matrix with given column and row strides and
  1841. axis-angle rotation representations. The functions that take a pointer to T instead
  1842. of a MatrixAdapter assume a column major representation with unit row stride and a column stride of 3.
  1843. .. function:: template <typename T, int row_stride, int col_stride> void EulerAnglesToRotationMatrix(const T* euler, const MatrixAdapter<T, row_stride, col_stride>& R)
  1844. .. function:: template <typename T> void EulerAnglesToRotationMatrix(const T* euler, int row_stride, T* R)
  1845. Conversions between :math:`3\times3` rotation matrix with given column and row strides and
  1846. Euler angle (in degrees) rotation representations.
  1847. The {pitch,roll,yaw} Euler angles are rotations around the {x,y,z}
  1848. axes, respectively. They are applied in that same order, so the
  1849. total rotation R is Rz * Ry * Rx.
  1850. The function that takes a pointer to T as the rotation matrix assumes a row
  1851. major representation with unit column stride and a row stride of 3.
  1852. The additional parameter row_stride is required to be 3.
  1853. .. function:: template <typename T, int row_stride, int col_stride> void QuaternionToScaledRotation(const T q[4], const MatrixAdapter<T, row_stride, col_stride>& R)
  1854. .. function:: template <typename T> void QuaternionToScaledRotation(const T q[4], T R[3 * 3])
  1855. Convert a 4-vector to a :math:`3\times3` scaled rotation matrix.
  1856. The choice of rotation is such that the quaternion
  1857. :math:`\begin{bmatrix} 1 &0 &0 &0\end{bmatrix}` goes to an identity
  1858. matrix and for small :math:`a, b, c` the quaternion
  1859. :math:`\begin{bmatrix}1 &a &b &c\end{bmatrix}` goes to the matrix
  1860. .. math::
  1861. I + 2 \begin{bmatrix} 0 & -c & b \\ c & 0 & -a\\ -b & a & 0
  1862. \end{bmatrix} + O(q^2)
  1863. which corresponds to a Rodrigues approximation, the last matrix
  1864. being the cross-product matrix of :math:`\begin{bmatrix} a& b&
  1865. c\end{bmatrix}`. Together with the property that :math:`R(q_1 \otimes q_2)
  1866. = R(q_1) R(q_2)` this uniquely defines the mapping from :math:`q` to
  1867. :math:`R`.
  1868. In the function that accepts a pointer to T instead of a MatrixAdapter,
  1869. the rotation matrix ``R`` is a row-major matrix with unit column stride
  1870. and a row stride of 3.
  1871. No normalization of the quaternion is performed, i.e.
  1872. :math:`R = \|q\|^2 Q`, where :math:`Q` is an orthonormal matrix
  1873. such that :math:`\det(Q) = 1` and :math:`QQ' = I`.
  1874. .. function:: template <typename T> void QuaternionToRotation(const T q[4], const MatrixAdapter<T, row_stride, col_stride>& R)
  1875. .. function:: template <typename T> void QuaternionToRotation(const T q[4], T R[3 * 3])
  1876. Same as above except that the rotation matrix is normalized by the
  1877. Frobenius norm, so that :math:`R R' = I` (and :math:`\det(R) = 1`).
  1878. .. function:: template <typename T> void UnitQuaternionRotatePoint(const T q[4], const T pt[3], T result[3])
  1879. Rotates a point pt by a quaternion q:
  1880. .. math:: \text{result} = R(q) \text{pt}
  1881. Assumes the quaternion is unit norm. If you pass in a quaternion
  1882. with :math:`|q|^2 = 2` then you WILL NOT get back 2 times the
  1883. result you get for a unit quaternion.
  1884. .. function:: template <typename T> void QuaternionRotatePoint(const T q[4], const T pt[3], T result[3])
  1885. With this function you do not need to assume that :math:`q` has unit norm.
  1886. It does assume that the norm is non-zero.
  1887. .. function:: template <typename T> void QuaternionProduct(const T z[4], const T w[4], T zw[4])
  1888. .. math:: zw = z \otimes w
  1889. where :math:`\otimes` is the Quaternion product between 4-vectors.
  1890. .. function:: template <typename T> void CrossProduct(const T x[3], const T y[3], T x_cross_y[3])
  1891. .. math:: \text{x_cross_y} = x \times y
  1892. .. function:: template <typename T> void AngleAxisRotatePoint(const T angle_axis[3], const T pt[3], T result[3])
  1893. .. math:: y = R(\text{angle_axis}) x
  1894. Cubic Interpolation
  1895. ===================
  1896. Optimization problems often involve functions that are given in the
  1897. form of a table of values, for example an image. Evaluating these
  1898. functions and their derivatives requires interpolating these
  1899. values. Interpolating tabulated functions is a vast area of research
  1900. and there are a lot of libraries which implement a variety of
  1901. interpolation schemes. However, using them within the automatic
  1902. differentiation framework in Ceres is quite painful. To this end,
  1903. Ceres provides the ability to interpolate one dimensional and two
  1904. dimensional tabular functions.
  1905. The one dimensional interpolation is based on the Cubic Hermite
  1906. Spline, also known as the Catmull-Rom Spline. This produces a first
  1907. order differentiable interpolating function. The two dimensional
  1908. interpolation scheme is a generalization of the one dimensional scheme
  1909. where the interpolating function is assumed to be separable in the two
  1910. dimensions,
  1911. More details of the construction can be found `Linear Methods for
  1912. Image Interpolation <http://www.ipol.im/pub/art/2011/g_lmii/>`_ by
  1913. Pascal Getreuer.
  1914. .. class:: CubicInterpolator
  1915. Given as input an infinite one dimensional grid, which provides the
  1916. following interface.
  1917. .. code::
  1918. struct Grid1D {
  1919. enum { DATA_DIMENSION = 2; };
  1920. void GetValue(int n, double* f) const;
  1921. };
  1922. Where, ``GetValue`` gives us the value of a function :math:`f`
  1923. (possibly vector valued) for any integer :math:`n` and the enum
  1924. ``DATA_DIMENSION`` indicates the dimensionality of the function being
  1925. interpolated. For example if you are interpolating rotations in
  1926. axis-angle format over time, then ``DATA_DIMENSION = 3``.
  1927. :class:`CubicInterpolator` uses Cubic Hermite splines to produce a
  1928. smooth approximation to it that can be used to evaluate the
  1929. :math:`f(x)` and :math:`f'(x)` at any point on the real number
  1930. line. For example, the following code interpolates an array of four
  1931. numbers.
  1932. .. code::
  1933. const double x[] = {1.0, 2.0, 5.0, 6.0};
  1934. Grid1D<double, 1> array(x, 0, 4);
  1935. CubicInterpolator interpolator(array);
  1936. double f, dfdx;
  1937. interpolator.Evaluate(1.5, &f, &dfdx);
  1938. In the above code we use ``Grid1D`` a templated helper class that
  1939. allows easy interfacing between ``C++`` arrays and
  1940. :class:`CubicInterpolator`.
  1941. ``Grid1D`` supports vector valued functions where the various
  1942. coordinates of the function can be interleaved or stacked. It also
  1943. allows the use of any numeric type as input, as long as it can be
  1944. safely cast to a double.
  1945. .. class:: BiCubicInterpolator
  1946. Given as input an infinite two dimensional grid, which provides the
  1947. following interface:
  1948. .. code::
  1949. struct Grid2D {
  1950. enum { DATA_DIMENSION = 2 };
  1951. void GetValue(int row, int col, double* f) const;
  1952. };
  1953. Where, ``GetValue`` gives us the value of a function :math:`f`
  1954. (possibly vector valued) for any pair of integers :code:`row` and
  1955. :code:`col` and the enum ``DATA_DIMENSION`` indicates the
  1956. dimensionality of the function being interpolated. For example if you
  1957. are interpolating a color image with three channels (Red, Green &
  1958. Blue), then ``DATA_DIMENSION = 3``.
  1959. :class:`BiCubicInterpolator` uses the cubic convolution interpolation
  1960. algorithm of R. Keys [Keys]_, to produce a smooth approximation to it
  1961. that can be used to evaluate the :math:`f(r,c)`, :math:`\frac{\partial
  1962. f(r,c)}{\partial r}` and :math:`\frac{\partial f(r,c)}{\partial c}` at
  1963. any any point in the real plane.
  1964. For example the following code interpolates a two dimensional array.
  1965. .. code::
  1966. const double data[] = {1.0, 3.0, -1.0, 4.0,
  1967. 3.6, 2.1, 4.2, 2.0,
  1968. 2.0, 1.0, 3.1, 5.2};
  1969. Grid2D<double, 1> array(data, 0, 3, 0, 4);
  1970. BiCubicInterpolator interpolator(array);
  1971. double f, dfdr, dfdc;
  1972. interpolator.Evaluate(1.2, 2.5, &f, &dfdr, &dfdc);
  1973. In the above code, the templated helper class ``Grid2D`` is used to
  1974. make a ``C++`` array look like a two dimensional table to
  1975. :class:`BiCubicInterpolator`.
  1976. ``Grid2D`` supports row or column major layouts. It also supports
  1977. vector valued functions where the individual coordinates of the
  1978. function may be interleaved or stacked. It also allows the use of any
  1979. numeric type as input, as long as it can be safely cast to double.