jet.h 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  1. // Ceres Solver - A fast non-linear least squares minimizer
  2. // Copyright 2023 Google Inc. All rights reserved.
  3. // http://ceres-solver.org/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are met:
  7. //
  8. // * Redistributions of source code must retain the above copyright notice,
  9. // this list of conditions and the following disclaimer.
  10. // * Redistributions in binary form must reproduce the above copyright notice,
  11. // this list of conditions and the following disclaimer in the documentation
  12. // and/or other materials provided with the distribution.
  13. // * Neither the name of Google Inc. nor the names of its contributors may be
  14. // used to endorse or promote products derived from this software without
  15. // specific prior written permission.
  16. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  21. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  22. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  23. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  24. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  25. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  26. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  27. // POSSIBILITY OF SUCH DAMAGE.
  28. //
  29. // Author: keir@google.com (Keir Mierle)
  30. //
  31. // A simple implementation of N-dimensional dual numbers, for automatically
  32. // computing exact derivatives of functions.
  33. //
  34. // While a complete treatment of the mechanics of automatic differentiation is
  35. // beyond the scope of this header (see
  36. // http://en.wikipedia.org/wiki/Automatic_differentiation for details), the
  37. // basic idea is to extend normal arithmetic with an extra element, "e," often
  38. // denoted with the greek symbol epsilon, such that e != 0 but e^2 = 0. Dual
  39. // numbers are extensions of the real numbers analogous to complex numbers:
  40. // whereas complex numbers augment the reals by introducing an imaginary unit i
  41. // such that i^2 = -1, dual numbers introduce an "infinitesimal" unit e such
  42. // that e^2 = 0. Dual numbers have two components: the "real" component and the
  43. // "infinitesimal" component, generally written as x + y*e. Surprisingly, this
  44. // leads to a convenient method for computing exact derivatives without needing
  45. // to manipulate complicated symbolic expressions.
  46. //
  47. // For example, consider the function
  48. //
  49. // f(x) = x^2 ,
  50. //
  51. // evaluated at 10. Using normal arithmetic, f(10) = 100, and df/dx(10) = 20.
  52. // Next, argument 10 with an infinitesimal to get:
  53. //
  54. // f(10 + e) = (10 + e)^2
  55. // = 100 + 2 * 10 * e + e^2
  56. // = 100 + 20 * e -+-
  57. // -- |
  58. // | +--- This is zero, since e^2 = 0
  59. // |
  60. // +----------------- This is df/dx!
  61. //
  62. // Note that the derivative of f with respect to x is simply the infinitesimal
  63. // component of the value of f(x + e). So, in order to take the derivative of
  64. // any function, it is only necessary to replace the numeric "object" used in
  65. // the function with one extended with infinitesimals. The class Jet, defined in
  66. // this header, is one such example of this, where substitution is done with
  67. // templates.
  68. //
  69. // To handle derivatives of functions taking multiple arguments, different
  70. // infinitesimals are used, one for each variable to take the derivative of. For
  71. // example, consider a scalar function of two scalar parameters x and y:
  72. //
  73. // f(x, y) = x^2 + x * y
  74. //
  75. // Following the technique above, to compute the derivatives df/dx and df/dy for
  76. // f(1, 3) involves doing two evaluations of f, the first time replacing x with
  77. // x + e, the second time replacing y with y + e.
  78. //
  79. // For df/dx:
  80. //
  81. // f(1 + e, y) = (1 + e)^2 + (1 + e) * 3
  82. // = 1 + 2 * e + 3 + 3 * e
  83. // = 4 + 5 * e
  84. //
  85. // --> df/dx = 5
  86. //
  87. // For df/dy:
  88. //
  89. // f(1, 3 + e) = 1^2 + 1 * (3 + e)
  90. // = 1 + 3 + e
  91. // = 4 + e
  92. //
  93. // --> df/dy = 1
  94. //
  95. // To take the gradient of f with the implementation of dual numbers ("jets") in
  96. // this file, it is necessary to create a single jet type which has components
  97. // for the derivative in x and y, and passing them to a templated version of f:
  98. //
  99. // template<typename T>
  100. // T f(const T &x, const T &y) {
  101. // return x * x + x * y;
  102. // }
  103. //
  104. // // The "2" means there should be 2 dual number components.
  105. // // It computes the partial derivative at x=10, y=20.
  106. // Jet<double, 2> x(10, 0); // Pick the 0th dual number for x.
  107. // Jet<double, 2> y(20, 1); // Pick the 1st dual number for y.
  108. // Jet<double, 2> z = f(x, y);
  109. //
  110. // LOG(INFO) << "df/dx = " << z.v[0]
  111. // << "df/dy = " << z.v[1];
  112. //
  113. // Most users should not use Jet objects directly; a wrapper around Jet objects,
  114. // which makes computing the derivative, gradient, or jacobian of templated
  115. // functors simple, is in autodiff.h. Even autodiff.h should not be used
  116. // directly; instead autodiff_cost_function.h is typically the file of interest.
  117. //
  118. // For the more mathematically inclined, this file implements first-order
  119. // "jets". A 1st order jet is an element of the ring
  120. //
  121. // T[N] = T[t_1, ..., t_N] / (t_1, ..., t_N)^2
  122. //
  123. // which essentially means that each jet consists of a "scalar" value 'a' from T
  124. // and a 1st order perturbation vector 'v' of length N:
  125. //
  126. // x = a + \sum_i v[i] t_i
  127. //
  128. // A shorthand is to write an element as x = a + u, where u is the perturbation.
  129. // Then, the main point about the arithmetic of jets is that the product of
  130. // perturbations is zero:
  131. //
  132. // (a + u) * (b + v) = ab + av + bu + uv
  133. // = ab + (av + bu) + 0
  134. //
  135. // which is what operator* implements below. Addition is simpler:
  136. //
  137. // (a + u) + (b + v) = (a + b) + (u + v).
  138. //
  139. // The only remaining question is how to evaluate the function of a jet, for
  140. // which we use the chain rule:
  141. //
  142. // f(a + u) = f(a) + f'(a) u
  143. //
  144. // where f'(a) is the (scalar) derivative of f at a.
  145. //
  146. // By pushing these things through sufficiently and suitably templated
  147. // functions, we can do automatic differentiation. Just be sure to turn on
  148. // function inlining and common-subexpression elimination, or it will be very
  149. // slow!
  150. //
  151. // WARNING: Most Ceres users should not directly include this file or know the
  152. // details of how jets work. Instead the suggested method for automatic
  153. // derivatives is to use autodiff_cost_function.h, which is a wrapper around
  154. // both jets.h and autodiff.h to make taking derivatives of cost functions for
  155. // use in Ceres easier.
  156. #ifndef CERES_PUBLIC_JET_H_
  157. #define CERES_PUBLIC_JET_H_
  158. #include <cmath>
  159. #include <complex>
  160. #include <iosfwd>
  161. #include <iostream> // NOLINT
  162. #include <limits>
  163. #include <numeric>
  164. #include <string>
  165. #include <type_traits>
  166. #include "Eigen/Core"
  167. #include "ceres/internal/jet_traits.h"
  168. #include "ceres/internal/port.h"
  169. #include "ceres/jet_fwd.h"
  170. // Here we provide partial specializations of std::common_type for the Jet class
  171. // to allow determining a Jet type with a common underlying arithmetic type.
  172. // Such an arithmetic type can be either a scalar or an another Jet. An example
  173. // for a common type, say, between a float and a Jet<double, N> is a Jet<double,
  174. // N> (i.e., std::common_type_t<float, ceres::Jet<double, N>> and
  175. // ceres::Jet<double, N> refer to the same type.)
  176. //
  177. // The partial specialization are also used for determining compatible types by
  178. // means of SFINAE and thus allow such types to be expressed as operands of
  179. // logical comparison operators. Missing (partial) specialization of
  180. // std::common_type for a particular (custom) type will therefore disable the
  181. // use of comparison operators defined by Ceres.
  182. //
  183. // Since these partial specializations are used as SFINAE constraints, they
  184. // enable standard promotion rules between various scalar types and consequently
  185. // their use in comparison against a Jet without providing implicit
  186. // conversions from a scalar, such as an int, to a Jet (see the implementation
  187. // of logical comparison operators below).
  188. template <typename T, int N, typename U>
  189. struct std::common_type<T, ceres::Jet<U, N>> {
  190. using type = ceres::Jet<common_type_t<T, U>, N>;
  191. };
  192. template <typename T, int N, typename U>
  193. struct std::common_type<ceres::Jet<T, N>, U> {
  194. using type = ceres::Jet<common_type_t<T, U>, N>;
  195. };
  196. template <typename T, int N, typename U>
  197. struct std::common_type<ceres::Jet<T, N>, ceres::Jet<U, N>> {
  198. using type = ceres::Jet<common_type_t<T, U>, N>;
  199. };
  200. namespace ceres {
  201. template <typename T, int N>
  202. struct Jet {
  203. enum { DIMENSION = N };
  204. using Scalar = T;
  205. // Default-construct "a" because otherwise this can lead to false errors about
  206. // uninitialized uses when other classes relying on default constructed T
  207. // (where T is a Jet<T, N>). This usually only happens in opt mode. Note that
  208. // the C++ standard mandates that e.g. default constructed doubles are
  209. // initialized to 0.0; see sections 8.5 of the C++03 standard.
  210. Jet() : a() { v.setConstant(Scalar()); }
  211. // Constructor from scalar: a + 0.
  212. explicit Jet(const T& value) {
  213. a = value;
  214. v.setConstant(Scalar());
  215. }
  216. // Constructor from scalar plus variable: a + t_i.
  217. Jet(const T& value, int k) {
  218. a = value;
  219. v.setConstant(Scalar());
  220. v[k] = T(1.0);
  221. }
  222. // Constructor from scalar and vector part
  223. // The use of Eigen::DenseBase allows Eigen expressions
  224. // to be passed in without being fully evaluated until
  225. // they are assigned to v
  226. template <typename Derived>
  227. EIGEN_STRONG_INLINE Jet(const T& a, const Eigen::DenseBase<Derived>& v)
  228. : a(a), v(v) {}
  229. // Compound operators
  230. Jet<T, N>& operator+=(const Jet<T, N>& y) {
  231. *this = *this + y;
  232. return *this;
  233. }
  234. Jet<T, N>& operator-=(const Jet<T, N>& y) {
  235. *this = *this - y;
  236. return *this;
  237. }
  238. Jet<T, N>& operator*=(const Jet<T, N>& y) {
  239. *this = *this * y;
  240. return *this;
  241. }
  242. Jet<T, N>& operator/=(const Jet<T, N>& y) {
  243. *this = *this / y;
  244. return *this;
  245. }
  246. // Compound with scalar operators.
  247. Jet<T, N>& operator+=(const T& s) {
  248. *this = *this + s;
  249. return *this;
  250. }
  251. Jet<T, N>& operator-=(const T& s) {
  252. *this = *this - s;
  253. return *this;
  254. }
  255. Jet<T, N>& operator*=(const T& s) {
  256. *this = *this * s;
  257. return *this;
  258. }
  259. Jet<T, N>& operator/=(const T& s) {
  260. *this = *this / s;
  261. return *this;
  262. }
  263. // The scalar part.
  264. T a;
  265. // The infinitesimal part.
  266. Eigen::Matrix<T, N, 1> v;
  267. // This struct needs to have an Eigen aligned operator new as it contains
  268. // fixed-size Eigen types.
  269. EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  270. };
  271. // Unary +
  272. template <typename T, int N>
  273. inline Jet<T, N> const& operator+(const Jet<T, N>& f) {
  274. return f;
  275. }
  276. // TODO(keir): Try adding __attribute__((always_inline)) to these functions to
  277. // see if it causes a performance increase.
  278. // Unary -
  279. template <typename T, int N>
  280. inline Jet<T, N> operator-(const Jet<T, N>& f) {
  281. return Jet<T, N>(-f.a, -f.v);
  282. }
  283. // Binary +
  284. template <typename T, int N>
  285. inline Jet<T, N> operator+(const Jet<T, N>& f, const Jet<T, N>& g) {
  286. return Jet<T, N>(f.a + g.a, f.v + g.v);
  287. }
  288. // Binary + with a scalar: x + s
  289. template <typename T, int N>
  290. inline Jet<T, N> operator+(const Jet<T, N>& f, T s) {
  291. return Jet<T, N>(f.a + s, f.v);
  292. }
  293. // Binary + with a scalar: s + x
  294. template <typename T, int N>
  295. inline Jet<T, N> operator+(T s, const Jet<T, N>& f) {
  296. return Jet<T, N>(f.a + s, f.v);
  297. }
  298. // Binary -
  299. template <typename T, int N>
  300. inline Jet<T, N> operator-(const Jet<T, N>& f, const Jet<T, N>& g) {
  301. return Jet<T, N>(f.a - g.a, f.v - g.v);
  302. }
  303. // Binary - with a scalar: x - s
  304. template <typename T, int N>
  305. inline Jet<T, N> operator-(const Jet<T, N>& f, T s) {
  306. return Jet<T, N>(f.a - s, f.v);
  307. }
  308. // Binary - with a scalar: s - x
  309. template <typename T, int N>
  310. inline Jet<T, N> operator-(T s, const Jet<T, N>& f) {
  311. return Jet<T, N>(s - f.a, -f.v);
  312. }
  313. // Binary *
  314. template <typename T, int N>
  315. inline Jet<T, N> operator*(const Jet<T, N>& f, const Jet<T, N>& g) {
  316. return Jet<T, N>(f.a * g.a, f.a * g.v + f.v * g.a);
  317. }
  318. // Binary * with a scalar: x * s
  319. template <typename T, int N>
  320. inline Jet<T, N> operator*(const Jet<T, N>& f, T s) {
  321. return Jet<T, N>(f.a * s, f.v * s);
  322. }
  323. // Binary * with a scalar: s * x
  324. template <typename T, int N>
  325. inline Jet<T, N> operator*(T s, const Jet<T, N>& f) {
  326. return Jet<T, N>(f.a * s, f.v * s);
  327. }
  328. // Binary /
  329. template <typename T, int N>
  330. inline Jet<T, N> operator/(const Jet<T, N>& f, const Jet<T, N>& g) {
  331. // This uses:
  332. //
  333. // a + u (a + u)(b - v) (a + u)(b - v)
  334. // ----- = -------------- = --------------
  335. // b + v (b + v)(b - v) b^2
  336. //
  337. // which holds because v*v = 0.
  338. const T g_a_inverse = T(1.0) / g.a;
  339. const T f_a_by_g_a = f.a * g_a_inverse;
  340. return Jet<T, N>(f_a_by_g_a, (f.v - f_a_by_g_a * g.v) * g_a_inverse);
  341. }
  342. // Binary / with a scalar: s / x
  343. template <typename T, int N>
  344. inline Jet<T, N> operator/(T s, const Jet<T, N>& g) {
  345. const T minus_s_g_a_inverse2 = -s / (g.a * g.a);
  346. return Jet<T, N>(s / g.a, g.v * minus_s_g_a_inverse2);
  347. }
  348. // Binary / with a scalar: x / s
  349. template <typename T, int N>
  350. inline Jet<T, N> operator/(const Jet<T, N>& f, T s) {
  351. const T s_inverse = T(1.0) / s;
  352. return Jet<T, N>(f.a * s_inverse, f.v * s_inverse);
  353. }
  354. // Binary comparison operators for both scalars and jets. At least one of the
  355. // operands must be a Jet. Promotable scalars (e.g., int, float, double etc.)
  356. // can appear on either side of the operator. std::common_type_t is used as an
  357. // SFINAE constraint to selectively enable compatible operand types. This allows
  358. // comparison, for instance, against int literals without implicit conversion.
  359. // In case the Jet arithmetic type is a Jet itself, a recursive expansion of Jet
  360. // value is performed.
  361. #define CERES_DEFINE_JET_COMPARISON_OPERATOR(op) \
  362. template <typename Lhs, \
  363. typename Rhs, \
  364. std::enable_if_t<PromotableJetOperands_v<Lhs, Rhs>>* = nullptr> \
  365. constexpr bool operator op(const Lhs& f, const Rhs& g) noexcept( \
  366. noexcept(internal::AsScalar(f) op internal::AsScalar(g))) { \
  367. using internal::AsScalar; \
  368. return AsScalar(f) op AsScalar(g); \
  369. }
  370. CERES_DEFINE_JET_COMPARISON_OPERATOR(<) // NOLINT
  371. CERES_DEFINE_JET_COMPARISON_OPERATOR(<=) // NOLINT
  372. CERES_DEFINE_JET_COMPARISON_OPERATOR(>) // NOLINT
  373. CERES_DEFINE_JET_COMPARISON_OPERATOR(>=) // NOLINT
  374. CERES_DEFINE_JET_COMPARISON_OPERATOR(==) // NOLINT
  375. CERES_DEFINE_JET_COMPARISON_OPERATOR(!=) // NOLINT
  376. #undef CERES_DEFINE_JET_COMPARISON_OPERATOR
  377. // Pull some functions from namespace std.
  378. //
  379. // This is necessary because we want to use the same name (e.g. 'sqrt') for
  380. // double-valued and Jet-valued functions, but we are not allowed to put
  381. // Jet-valued functions inside namespace std.
  382. using std::abs;
  383. using std::acos;
  384. using std::asin;
  385. using std::atan;
  386. using std::atan2;
  387. using std::cbrt;
  388. using std::ceil;
  389. using std::copysign;
  390. using std::cos;
  391. using std::cosh;
  392. using std::erf;
  393. using std::erfc;
  394. using std::exp;
  395. using std::exp2;
  396. using std::expm1;
  397. using std::fdim;
  398. using std::floor;
  399. using std::fma;
  400. using std::fmax;
  401. using std::fmin;
  402. using std::fpclassify;
  403. using std::hypot;
  404. using std::isfinite;
  405. using std::isinf;
  406. using std::isnan;
  407. using std::isnormal;
  408. using std::log;
  409. using std::log10;
  410. using std::log1p;
  411. using std::log2;
  412. using std::norm;
  413. using std::pow;
  414. using std::signbit;
  415. using std::sin;
  416. using std::sinh;
  417. using std::sqrt;
  418. using std::tan;
  419. using std::tanh;
  420. // MSVC (up to 1930) defines quiet comparison functions as template functions
  421. // which causes compilation errors due to ambiguity in the template parameter
  422. // type resolution for using declarations in the ceres namespace. Workaround the
  423. // issue by defining specific overload and bypass MSVC standard library
  424. // definitions.
  425. #if defined(_MSC_VER)
  426. inline bool isgreater(double lhs,
  427. double rhs) noexcept(noexcept(std::isgreater(lhs, rhs))) {
  428. return std::isgreater(lhs, rhs);
  429. }
  430. inline bool isless(double lhs,
  431. double rhs) noexcept(noexcept(std::isless(lhs, rhs))) {
  432. return std::isless(lhs, rhs);
  433. }
  434. inline bool islessequal(double lhs,
  435. double rhs) noexcept(noexcept(std::islessequal(lhs,
  436. rhs))) {
  437. return std::islessequal(lhs, rhs);
  438. }
  439. inline bool isgreaterequal(double lhs, double rhs) noexcept(
  440. noexcept(std::isgreaterequal(lhs, rhs))) {
  441. return std::isgreaterequal(lhs, rhs);
  442. }
  443. inline bool islessgreater(double lhs, double rhs) noexcept(
  444. noexcept(std::islessgreater(lhs, rhs))) {
  445. return std::islessgreater(lhs, rhs);
  446. }
  447. inline bool isunordered(double lhs,
  448. double rhs) noexcept(noexcept(std::isunordered(lhs,
  449. rhs))) {
  450. return std::isunordered(lhs, rhs);
  451. }
  452. #else
  453. using std::isgreater;
  454. using std::isgreaterequal;
  455. using std::isless;
  456. using std::islessequal;
  457. using std::islessgreater;
  458. using std::isunordered;
  459. #endif
  460. #ifdef CERES_HAS_CPP20
  461. using std::lerp;
  462. using std::midpoint;
  463. #endif // defined(CERES_HAS_CPP20)
  464. // Legacy names from pre-C++11 days.
  465. // clang-format off
  466. CERES_DEPRECATED_WITH_MSG("ceres::IsFinite will be removed in a future Ceres Solver release. Please use ceres::isfinite.")
  467. inline bool IsFinite(double x) { return std::isfinite(x); }
  468. CERES_DEPRECATED_WITH_MSG("ceres::IsInfinite will be removed in a future Ceres Solver release. Please use ceres::isinf.")
  469. inline bool IsInfinite(double x) { return std::isinf(x); }
  470. CERES_DEPRECATED_WITH_MSG("ceres::IsNaN will be removed in a future Ceres Solver release. Please use ceres::isnan.")
  471. inline bool IsNaN(double x) { return std::isnan(x); }
  472. CERES_DEPRECATED_WITH_MSG("ceres::IsNormal will be removed in a future Ceres Solver release. Please use ceres::isnormal.")
  473. inline bool IsNormal(double x) { return std::isnormal(x); }
  474. // clang-format on
  475. // In general, f(a + h) ~= f(a) + f'(a) h, via the chain rule.
  476. // abs(x + h) ~= abs(x) + sgn(x)h
  477. template <typename T, int N>
  478. inline Jet<T, N> abs(const Jet<T, N>& f) {
  479. return Jet<T, N>(abs(f.a), copysign(T(1), f.a) * f.v);
  480. }
  481. // copysign(a, b) composes a float with the magnitude of a and the sign of b.
  482. // Therefore, the function can be formally defined as
  483. //
  484. // copysign(a, b) = sgn(b)|a|
  485. //
  486. // where
  487. //
  488. // d/dx |x| = sgn(x)
  489. // d/dx sgn(x) = 2δ(x)
  490. //
  491. // sgn(x) being the signum function. Differentiating copysign(a, b) with respect
  492. // to a and b gives:
  493. //
  494. // d/da sgn(b)|a| = sgn(a) sgn(b)
  495. // d/db sgn(b)|a| = 2|a|δ(b)
  496. //
  497. // with the dual representation given by
  498. //
  499. // copysign(a + da, b + db) ~= sgn(b)|a| + (sgn(a)sgn(b) da + 2|a|δ(b) db)
  500. //
  501. // where δ(b) is the Dirac delta function.
  502. template <typename T, int N>
  503. inline Jet<T, N> copysign(const Jet<T, N>& f, const Jet<T, N> g) {
  504. // The Dirac delta function δ(b) is undefined at b=0 (here it's
  505. // infinite) and 0 everywhere else.
  506. T d = fpclassify(g) == FP_ZERO ? std::numeric_limits<T>::infinity() : T(0);
  507. T sa = copysign(T(1), f.a); // sgn(a)
  508. T sb = copysign(T(1), g.a); // sgn(b)
  509. // The second part of the infinitesimal is 2|a|δ(b) which is either infinity
  510. // or 0 unless a or any of the values of the b infinitesimal are 0. In the
  511. // latter case, the corresponding values become NaNs (multiplying 0 by
  512. // infinity gives NaN). We drop the constant factor 2 since it does not change
  513. // the result (its values will still be either 0, infinity or NaN).
  514. return Jet<T, N>(copysign(f.a, g.a), sa * sb * f.v + abs(f.a) * d * g.v);
  515. }
  516. // log(a + h) ~= log(a) + h / a
  517. template <typename T, int N>
  518. inline Jet<T, N> log(const Jet<T, N>& f) {
  519. const T a_inverse = T(1.0) / f.a;
  520. return Jet<T, N>(log(f.a), f.v * a_inverse);
  521. }
  522. // log10(a + h) ~= log10(a) + h / (a log(10))
  523. template <typename T, int N>
  524. inline Jet<T, N> log10(const Jet<T, N>& f) {
  525. // Most compilers will expand log(10) to a constant.
  526. const T a_inverse = T(1.0) / (f.a * log(T(10.0)));
  527. return Jet<T, N>(log10(f.a), f.v * a_inverse);
  528. }
  529. // log1p(a + h) ~= log1p(a) + h / (1 + a)
  530. template <typename T, int N>
  531. inline Jet<T, N> log1p(const Jet<T, N>& f) {
  532. const T a_inverse = T(1.0) / (T(1.0) + f.a);
  533. return Jet<T, N>(log1p(f.a), f.v * a_inverse);
  534. }
  535. // exp(a + h) ~= exp(a) + exp(a) h
  536. template <typename T, int N>
  537. inline Jet<T, N> exp(const Jet<T, N>& f) {
  538. const T tmp = exp(f.a);
  539. return Jet<T, N>(tmp, tmp * f.v);
  540. }
  541. // expm1(a + h) ~= expm1(a) + exp(a) h
  542. template <typename T, int N>
  543. inline Jet<T, N> expm1(const Jet<T, N>& f) {
  544. const T tmp = expm1(f.a);
  545. const T expa = tmp + T(1.0); // exp(a) = expm1(a) + 1
  546. return Jet<T, N>(tmp, expa * f.v);
  547. }
  548. // sqrt(a + h) ~= sqrt(a) + h / (2 sqrt(a))
  549. template <typename T, int N>
  550. inline Jet<T, N> sqrt(const Jet<T, N>& f) {
  551. const T tmp = sqrt(f.a);
  552. const T two_a_inverse = T(1.0) / (T(2.0) * tmp);
  553. return Jet<T, N>(tmp, f.v * two_a_inverse);
  554. }
  555. // cos(a + h) ~= cos(a) - sin(a) h
  556. template <typename T, int N>
  557. inline Jet<T, N> cos(const Jet<T, N>& f) {
  558. return Jet<T, N>(cos(f.a), -sin(f.a) * f.v);
  559. }
  560. // acos(a + h) ~= acos(a) - 1 / sqrt(1 - a^2) h
  561. template <typename T, int N>
  562. inline Jet<T, N> acos(const Jet<T, N>& f) {
  563. const T tmp = -T(1.0) / sqrt(T(1.0) - f.a * f.a);
  564. return Jet<T, N>(acos(f.a), tmp * f.v);
  565. }
  566. // sin(a + h) ~= sin(a) + cos(a) h
  567. template <typename T, int N>
  568. inline Jet<T, N> sin(const Jet<T, N>& f) {
  569. return Jet<T, N>(sin(f.a), cos(f.a) * f.v);
  570. }
  571. // asin(a + h) ~= asin(a) + 1 / sqrt(1 - a^2) h
  572. template <typename T, int N>
  573. inline Jet<T, N> asin(const Jet<T, N>& f) {
  574. const T tmp = T(1.0) / sqrt(T(1.0) - f.a * f.a);
  575. return Jet<T, N>(asin(f.a), tmp * f.v);
  576. }
  577. // tan(a + h) ~= tan(a) + (1 + tan(a)^2) h
  578. template <typename T, int N>
  579. inline Jet<T, N> tan(const Jet<T, N>& f) {
  580. const T tan_a = tan(f.a);
  581. const T tmp = T(1.0) + tan_a * tan_a;
  582. return Jet<T, N>(tan_a, tmp * f.v);
  583. }
  584. // atan(a + h) ~= atan(a) + 1 / (1 + a^2) h
  585. template <typename T, int N>
  586. inline Jet<T, N> atan(const Jet<T, N>& f) {
  587. const T tmp = T(1.0) / (T(1.0) + f.a * f.a);
  588. return Jet<T, N>(atan(f.a), tmp * f.v);
  589. }
  590. // sinh(a + h) ~= sinh(a) + cosh(a) h
  591. template <typename T, int N>
  592. inline Jet<T, N> sinh(const Jet<T, N>& f) {
  593. return Jet<T, N>(sinh(f.a), cosh(f.a) * f.v);
  594. }
  595. // cosh(a + h) ~= cosh(a) + sinh(a) h
  596. template <typename T, int N>
  597. inline Jet<T, N> cosh(const Jet<T, N>& f) {
  598. return Jet<T, N>(cosh(f.a), sinh(f.a) * f.v);
  599. }
  600. // tanh(a + h) ~= tanh(a) + (1 - tanh(a)^2) h
  601. template <typename T, int N>
  602. inline Jet<T, N> tanh(const Jet<T, N>& f) {
  603. const T tanh_a = tanh(f.a);
  604. const T tmp = T(1.0) - tanh_a * tanh_a;
  605. return Jet<T, N>(tanh_a, tmp * f.v);
  606. }
  607. // The floor function should be used with extreme care as this operation will
  608. // result in a zero derivative which provides no information to the solver.
  609. //
  610. // floor(a + h) ~= floor(a) + 0
  611. template <typename T, int N>
  612. inline Jet<T, N> floor(const Jet<T, N>& f) {
  613. return Jet<T, N>(floor(f.a));
  614. }
  615. // The ceil function should be used with extreme care as this operation will
  616. // result in a zero derivative which provides no information to the solver.
  617. //
  618. // ceil(a + h) ~= ceil(a) + 0
  619. template <typename T, int N>
  620. inline Jet<T, N> ceil(const Jet<T, N>& f) {
  621. return Jet<T, N>(ceil(f.a));
  622. }
  623. // Some new additions to C++11:
  624. // cbrt(a + h) ~= cbrt(a) + h / (3 a ^ (2/3))
  625. template <typename T, int N>
  626. inline Jet<T, N> cbrt(const Jet<T, N>& f) {
  627. const T derivative = T(1.0) / (T(3.0) * cbrt(f.a * f.a));
  628. return Jet<T, N>(cbrt(f.a), f.v * derivative);
  629. }
  630. // exp2(x + h) = 2^(x+h) ~= 2^x + h*2^x*log(2)
  631. template <typename T, int N>
  632. inline Jet<T, N> exp2(const Jet<T, N>& f) {
  633. const T tmp = exp2(f.a);
  634. const T derivative = tmp * log(T(2));
  635. return Jet<T, N>(tmp, f.v * derivative);
  636. }
  637. // log2(x + h) ~= log2(x) + h / (x * log(2))
  638. template <typename T, int N>
  639. inline Jet<T, N> log2(const Jet<T, N>& f) {
  640. const T derivative = T(1.0) / (f.a * log(T(2)));
  641. return Jet<T, N>(log2(f.a), f.v * derivative);
  642. }
  643. // Like sqrt(x^2 + y^2),
  644. // but acts to prevent underflow/overflow for small/large x/y.
  645. // Note that the function is non-smooth at x=y=0,
  646. // so the derivative is undefined there.
  647. template <typename T, int N>
  648. inline Jet<T, N> hypot(const Jet<T, N>& x, const Jet<T, N>& y) {
  649. // d/da sqrt(a) = 0.5 / sqrt(a)
  650. // d/dx x^2 + y^2 = 2x
  651. // So by the chain rule:
  652. // d/dx sqrt(x^2 + y^2) = 0.5 / sqrt(x^2 + y^2) * 2x = x / sqrt(x^2 + y^2)
  653. // d/dy sqrt(x^2 + y^2) = y / sqrt(x^2 + y^2)
  654. const T tmp = hypot(x.a, y.a);
  655. return Jet<T, N>(tmp, x.a / tmp * x.v + y.a / tmp * y.v);
  656. }
  657. // Like sqrt(x^2 + y^2 + z^2),
  658. // but acts to prevent underflow/overflow for small/large x/y/z.
  659. // Note that the function is non-smooth at x=y=z=0,
  660. // so the derivative is undefined there.
  661. template <typename T, int N>
  662. inline Jet<T, N> hypot(const Jet<T, N>& x,
  663. const Jet<T, N>& y,
  664. const Jet<T, N>& z) {
  665. // d/da sqrt(a) = 0.5 / sqrt(a)
  666. // d/dx x^2 + y^2 + z^2 = 2x
  667. // So by the chain rule:
  668. // d/dx sqrt(x^2 + y^2 + z^2)
  669. // = 0.5 / sqrt(x^2 + y^2 + z^2) * 2x
  670. // = x / sqrt(x^2 + y^2 + z^2)
  671. // d/dy sqrt(x^2 + y^2 + z^2) = y / sqrt(x^2 + y^2 + z^2)
  672. // d/dz sqrt(x^2 + y^2 + z^2) = z / sqrt(x^2 + y^2 + z^2)
  673. const T tmp = hypot(x.a, y.a, z.a);
  674. return Jet<T, N>(tmp, x.a / tmp * x.v + y.a / tmp * y.v + z.a / tmp * z.v);
  675. }
  676. // Like x * y + z but rounded only once.
  677. template <typename T, int N>
  678. inline Jet<T, N> fma(const Jet<T, N>& x,
  679. const Jet<T, N>& y,
  680. const Jet<T, N>& z) {
  681. // d/dx fma(x, y, z) = y
  682. // d/dy fma(x, y, z) = x
  683. // d/dz fma(x, y, z) = 1
  684. return Jet<T, N>(fma(x.a, y.a, z.a), y.a * x.v + x.a * y.v + z.v);
  685. }
  686. // Return value of fmax() and fmin() on equality
  687. // ---------------------------------------------
  688. //
  689. // There is arguably no good answer to what fmax() & fmin() should return on
  690. // equality, which for Jets by definition ONLY compares the scalar parts. We
  691. // choose what we think is the least worst option (averaging as Jets) which
  692. // minimises undesirable/unexpected behaviour as used, and also supports client
  693. // code written against Ceres versions prior to type promotion being supported
  694. // in Jet comparisons (< v2.1).
  695. //
  696. // The std::max() convention of returning the first argument on equality is
  697. // problematic, as it means that the derivative component may or may not be
  698. // preserved (when comparing a Jet with a scalar) depending upon the ordering.
  699. //
  700. // Always returning the Jet in {Jet, scalar} cases on equality is problematic
  701. // as it is inconsistent with the behaviour that would be obtained if the scalar
  702. // was first cast to Jet and the {Jet, Jet} case was used. Prior to type
  703. // promotion (Ceres v2.1) client code would typically cast constants to Jets
  704. // e.g: fmax(x, T(2.0)) which means the {Jet, Jet} case predominates, and we
  705. // still want the result to be order independent.
  706. //
  707. // Our intuition is that preserving a non-zero derivative is best, even if
  708. // its value does not match either of the inputs. Averaging achieves this
  709. // whilst ensuring argument ordering independence. This is also the approach
  710. // used by the Jax library, and TensorFlow's reduce_max().
  711. // Returns the larger of the two arguments, with Jet averaging on equality.
  712. // NaNs are treated as missing data.
  713. //
  714. // NOTE: This function is NOT subject to any of the error conditions specified
  715. // in `math_errhandling`.
  716. template <typename Lhs,
  717. typename Rhs,
  718. std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
  719. inline decltype(auto) fmax(const Lhs& x, const Rhs& y) {
  720. using J = std::common_type_t<Lhs, Rhs>;
  721. // As x == y may set FP exceptions in the presence of NaNs when used with
  722. // non-default compiler options so we avoid its use here.
  723. if (isnan(x) || isnan(y) || islessgreater(x, y)) {
  724. return isnan(x) || isless(x, y) ? J{y} : J{x};
  725. }
  726. // x == y (scalar parts) return the average of their Jet representations.
  727. #if defined(CERES_HAS_CPP20)
  728. return midpoint(J{x}, J{y});
  729. #else
  730. return (J{x} + J{y}) * typename J::Scalar(0.5);
  731. #endif // defined(CERES_HAS_CPP20)
  732. }
  733. // Returns the smaller of the two arguments, with Jet averaging on equality.
  734. // NaNs are treated as missing data.
  735. //
  736. // NOTE: This function is NOT subject to any of the error conditions specified
  737. // in `math_errhandling`.
  738. template <typename Lhs,
  739. typename Rhs,
  740. std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
  741. inline decltype(auto) fmin(const Lhs& x, const Rhs& y) {
  742. using J = std::common_type_t<Lhs, Rhs>;
  743. // As x == y may set FP exceptions in the presence of NaNs when used with
  744. // non-default compiler options so we avoid its use here.
  745. if (isnan(x) || isnan(y) || islessgreater(x, y)) {
  746. return isnan(x) || isgreater(x, y) ? J{y} : J{x};
  747. }
  748. // x == y (scalar parts) return the average of their Jet representations.
  749. #if defined(CERES_HAS_CPP20)
  750. return midpoint(J{x}, J{y});
  751. #else
  752. return (J{x} + J{y}) * typename J::Scalar(0.5);
  753. #endif // defined(CERES_HAS_CPP20)
  754. }
  755. // Returns the positive difference (f - g) of two arguments and zero if f <= g.
  756. // If at least one argument is NaN, a NaN is return.
  757. //
  758. // NOTE At least one of the argument types must be a Jet, the other one can be a
  759. // scalar. In case both arguments are Jets, their dimensionality must match.
  760. template <typename Lhs,
  761. typename Rhs,
  762. std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
  763. inline decltype(auto) fdim(const Lhs& f, const Rhs& g) {
  764. using J = std::common_type_t<Lhs, Rhs>;
  765. if (isnan(f) || isnan(g)) {
  766. return std::numeric_limits<J>::quiet_NaN();
  767. }
  768. return isgreater(f, g) ? J{f - g} : J{};
  769. }
  770. // erf is defined as an integral that cannot be expressed analytically
  771. // however, the derivative is trivial to compute
  772. // erf(x + h) = erf(x) + h * 2*exp(-x^2)/sqrt(pi)
  773. template <typename T, int N>
  774. inline Jet<T, N> erf(const Jet<T, N>& x) {
  775. // We evaluate the constant as follows:
  776. // 2 / sqrt(pi) = 1 / sqrt(atan(1.))
  777. // On POSIX systems it is defined as M_2_SQRTPI, but this is not
  778. // portable and the type may not be T. The above expression
  779. // evaluates to full precision with IEEE arithmetic and, since it's
  780. // constant, the compiler can generate exactly the same code. gcc
  781. // does so even at -O0.
  782. return Jet<T, N>(erf(x.a), x.v * exp(-x.a * x.a) * (T(1) / sqrt(atan(T(1)))));
  783. }
  784. // erfc(x) = 1-erf(x)
  785. // erfc(x + h) = erfc(x) + h * (-2*exp(-x^2)/sqrt(pi))
  786. template <typename T, int N>
  787. inline Jet<T, N> erfc(const Jet<T, N>& x) {
  788. // See in erf() above for the evaluation of the constant in the derivative.
  789. return Jet<T, N>(erfc(x.a),
  790. -x.v * exp(-x.a * x.a) * (T(1) / sqrt(atan(T(1)))));
  791. }
  792. // Bessel functions of the first kind with integer order equal to 0, 1, n.
  793. //
  794. // Microsoft has deprecated the j[0,1,n]() POSIX Bessel functions in favour of
  795. // _j[0,1,n](). Where available on MSVC, use _j[0,1,n]() to avoid deprecated
  796. // function errors in client code (the specific warning is suppressed when
  797. // Ceres itself is built).
  798. inline double BesselJ0(double x) {
  799. CERES_DISABLE_DEPRECATED_WARNING
  800. return j0(x);
  801. CERES_RESTORE_DEPRECATED_WARNING
  802. }
  803. inline double BesselJ1(double x) {
  804. CERES_DISABLE_DEPRECATED_WARNING
  805. return j1(x);
  806. CERES_RESTORE_DEPRECATED_WARNING
  807. }
  808. inline double BesselJn(int n, double x) {
  809. CERES_DISABLE_DEPRECATED_WARNING
  810. return jn(n, x);
  811. CERES_RESTORE_DEPRECATED_WARNING
  812. }
  813. // For the formulae of the derivatives of the Bessel functions see the book:
  814. // Olver, Lozier, Boisvert, Clark, NIST Handbook of Mathematical Functions,
  815. // Cambridge University Press 2010.
  816. //
  817. // Formulae are also available at http://dlmf.nist.gov
  818. // See formula http://dlmf.nist.gov/10.6#E3
  819. // j0(a + h) ~= j0(a) - j1(a) h
  820. template <typename T, int N>
  821. inline Jet<T, N> BesselJ0(const Jet<T, N>& f) {
  822. return Jet<T, N>(BesselJ0(f.a), -BesselJ1(f.a) * f.v);
  823. }
  824. // See formula http://dlmf.nist.gov/10.6#E1
  825. // j1(a + h) ~= j1(a) + 0.5 ( j0(a) - j2(a) ) h
  826. template <typename T, int N>
  827. inline Jet<T, N> BesselJ1(const Jet<T, N>& f) {
  828. return Jet<T, N>(BesselJ1(f.a),
  829. T(0.5) * (BesselJ0(f.a) - BesselJn(2, f.a)) * f.v);
  830. }
  831. // See formula http://dlmf.nist.gov/10.6#E1
  832. // j_n(a + h) ~= j_n(a) + 0.5 ( j_{n-1}(a) - j_{n+1}(a) ) h
  833. template <typename T, int N>
  834. inline Jet<T, N> BesselJn(int n, const Jet<T, N>& f) {
  835. return Jet<T, N>(
  836. BesselJn(n, f.a),
  837. T(0.5) * (BesselJn(n - 1, f.a) - BesselJn(n + 1, f.a)) * f.v);
  838. }
  839. // Classification and comparison functionality referencing only the scalar part
  840. // of a Jet. To classify the derivatives (e.g., for sanity checks), the dual
  841. // part should be referenced explicitly. For instance, to check whether the
  842. // derivatives of a Jet 'f' are reasonable, one can use
  843. //
  844. // isfinite(f.v.array()).all()
  845. // !isnan(f.v.array()).any()
  846. //
  847. // etc., depending on the desired semantics.
  848. //
  849. // NOTE: Floating-point classification and comparison functions and operators
  850. // should be used with care as no derivatives can be propagated by such
  851. // functions directly but only by expressions resulting from corresponding
  852. // conditional statements. At the same time, conditional statements can possibly
  853. // introduce a discontinuity in the cost function making it impossible to
  854. // evaluate its derivative and thus the optimization problem intractable.
  855. // Determines whether the scalar part of the Jet is finite.
  856. template <typename T, int N>
  857. inline bool isfinite(const Jet<T, N>& f) {
  858. return isfinite(f.a);
  859. }
  860. // Determines whether the scalar part of the Jet is infinite.
  861. template <typename T, int N>
  862. inline bool isinf(const Jet<T, N>& f) {
  863. return isinf(f.a);
  864. }
  865. // Determines whether the scalar part of the Jet is NaN.
  866. template <typename T, int N>
  867. inline bool isnan(const Jet<T, N>& f) {
  868. return isnan(f.a);
  869. }
  870. // Determines whether the scalar part of the Jet is neither zero, subnormal,
  871. // infinite, nor NaN.
  872. template <typename T, int N>
  873. inline bool isnormal(const Jet<T, N>& f) {
  874. return isnormal(f.a);
  875. }
  876. // Determines whether the scalar part of the Jet f is less than the scalar
  877. // part of g.
  878. //
  879. // NOTE: This function does NOT set any floating-point exceptions.
  880. template <typename Lhs,
  881. typename Rhs,
  882. std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
  883. inline bool isless(const Lhs& f, const Rhs& g) {
  884. using internal::AsScalar;
  885. return isless(AsScalar(f), AsScalar(g));
  886. }
  887. // Determines whether the scalar part of the Jet f is greater than the scalar
  888. // part of g.
  889. //
  890. // NOTE: This function does NOT set any floating-point exceptions.
  891. template <typename Lhs,
  892. typename Rhs,
  893. std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
  894. inline bool isgreater(const Lhs& f, const Rhs& g) {
  895. using internal::AsScalar;
  896. return isgreater(AsScalar(f), AsScalar(g));
  897. }
  898. // Determines whether the scalar part of the Jet f is less than or equal to the
  899. // scalar part of g.
  900. //
  901. // NOTE: This function does NOT set any floating-point exceptions.
  902. template <typename Lhs,
  903. typename Rhs,
  904. std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
  905. inline bool islessequal(const Lhs& f, const Rhs& g) {
  906. using internal::AsScalar;
  907. return islessequal(AsScalar(f), AsScalar(g));
  908. }
  909. // Determines whether the scalar part of the Jet f is less than or greater than
  910. // (f < g || f > g) the scalar part of g.
  911. //
  912. // NOTE: This function does NOT set any floating-point exceptions.
  913. template <typename Lhs,
  914. typename Rhs,
  915. std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
  916. inline bool islessgreater(const Lhs& f, const Rhs& g) {
  917. using internal::AsScalar;
  918. return islessgreater(AsScalar(f), AsScalar(g));
  919. }
  920. // Determines whether the scalar part of the Jet f is greater than or equal to
  921. // the scalar part of g.
  922. //
  923. // NOTE: This function does NOT set any floating-point exceptions.
  924. template <typename Lhs,
  925. typename Rhs,
  926. std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
  927. inline bool isgreaterequal(const Lhs& f, const Rhs& g) {
  928. using internal::AsScalar;
  929. return isgreaterequal(AsScalar(f), AsScalar(g));
  930. }
  931. // Determines if either of the scalar parts of the arguments are NaN and
  932. // thus cannot be ordered with respect to each other.
  933. template <typename Lhs,
  934. typename Rhs,
  935. std::enable_if_t<CompatibleJetOperands_v<Lhs, Rhs>>* = nullptr>
  936. inline bool isunordered(const Lhs& f, const Rhs& g) {
  937. using internal::AsScalar;
  938. return isunordered(AsScalar(f), AsScalar(g));
  939. }
  940. // Categorize scalar part as zero, subnormal, normal, infinite, NaN, or
  941. // implementation-defined.
  942. template <typename T, int N>
  943. inline int fpclassify(const Jet<T, N>& f) {
  944. return fpclassify(f.a);
  945. }
  946. // Determines whether the scalar part of the argument is negative.
  947. template <typename T, int N>
  948. inline bool signbit(const Jet<T, N>& f) {
  949. return signbit(f.a);
  950. }
  951. // Legacy functions from the pre-C++11 days.
  952. template <typename T, int N>
  953. CERES_DEPRECATED_WITH_MSG(
  954. "ceres::IsFinite will be removed in a future Ceres Solver release. Please "
  955. "use ceres::isfinite.")
  956. inline bool IsFinite(const Jet<T, N>& f) {
  957. return isfinite(f);
  958. }
  959. template <typename T, int N>
  960. CERES_DEPRECATED_WITH_MSG(
  961. "ceres::IsNaN will be removed in a future Ceres Solver release. Please use "
  962. "ceres::isnan.")
  963. inline bool IsNaN(const Jet<T, N>& f) {
  964. return isnan(f);
  965. }
  966. template <typename T, int N>
  967. CERES_DEPRECATED_WITH_MSG(
  968. "ceres::IsNormal will be removed in a future Ceres Solver release. Please "
  969. "use ceres::isnormal.")
  970. inline bool IsNormal(const Jet<T, N>& f) {
  971. return isnormal(f);
  972. }
  973. // The jet is infinite if any part of the jet is infinite.
  974. template <typename T, int N>
  975. CERES_DEPRECATED_WITH_MSG(
  976. "ceres::IsInfinite will be removed in a future Ceres Solver release. "
  977. "Please use ceres::isinf.")
  978. inline bool IsInfinite(const Jet<T, N>& f) {
  979. return isinf(f);
  980. }
  981. #ifdef CERES_HAS_CPP20
  982. // Computes the linear interpolation a + t(b - a) between a and b at the value
  983. // t. For arguments outside of the range 0 <= t <= 1, the values are
  984. // extrapolated.
  985. //
  986. // Differentiating lerp(a, b, t) with respect to a, b, and t gives:
  987. //
  988. // d/da lerp(a, b, t) = 1 - t
  989. // d/db lerp(a, b, t) = t
  990. // d/dt lerp(a, b, t) = b - a
  991. //
  992. // with the dual representation given by
  993. //
  994. // lerp(a + da, b + db, t + dt)
  995. // ~= lerp(a, b, t) + (1 - t) da + t db + (b - a) dt .
  996. template <typename T, int N>
  997. inline Jet<T, N> lerp(const Jet<T, N>& a,
  998. const Jet<T, N>& b,
  999. const Jet<T, N>& t) {
  1000. return Jet<T, N>{lerp(a.a, b.a, t.a),
  1001. (T(1) - t.a) * a.v + t.a * b.v + (b.a - a.a) * t.v};
  1002. }
  1003. // Computes the midpoint a + (b - a) / 2.
  1004. //
  1005. // Differentiating midpoint(a, b) with respect to a and b gives:
  1006. //
  1007. // d/da midpoint(a, b) = 1/2
  1008. // d/db midpoint(a, b) = 1/2
  1009. //
  1010. // with the dual representation given by
  1011. //
  1012. // midpoint(a + da, b + db) ~= midpoint(a, b) + (da + db) / 2 .
  1013. template <typename T, int N>
  1014. inline Jet<T, N> midpoint(const Jet<T, N>& a, const Jet<T, N>& b) {
  1015. Jet<T, N> result{midpoint(a.a, b.a)};
  1016. // To avoid overflow in the differential, compute
  1017. // (da + db) / 2 using midpoint.
  1018. for (int i = 0; i < N; ++i) {
  1019. result.v[i] = midpoint(a.v[i], b.v[i]);
  1020. }
  1021. return result;
  1022. }
  1023. #endif // defined(CERES_HAS_CPP20)
  1024. // atan2(b + db, a + da) ~= atan2(b, a) + (- b da + a db) / (a^2 + b^2)
  1025. //
  1026. // In words: the rate of change of theta is 1/r times the rate of
  1027. // change of (x, y) in the positive angular direction.
  1028. template <typename T, int N>
  1029. inline Jet<T, N> atan2(const Jet<T, N>& g, const Jet<T, N>& f) {
  1030. // Note order of arguments:
  1031. //
  1032. // f = a + da
  1033. // g = b + db
  1034. T const tmp = T(1.0) / (f.a * f.a + g.a * g.a);
  1035. return Jet<T, N>(atan2(g.a, f.a), tmp * (-g.a * f.v + f.a * g.v));
  1036. }
  1037. // Computes the square x^2 of a real number x (not the Euclidean L^2 norm as
  1038. // the name might suggest).
  1039. //
  1040. // NOTE: While std::norm is primarily intended for computing the squared
  1041. // magnitude of a std::complex<> number, the current Jet implementation does not
  1042. // support mixing a scalar T in its real part and std::complex<T> and in the
  1043. // infinitesimal. Mixed Jet support is necessary for the type decay from
  1044. // std::complex<T> to T (the squared magnitude of a complex number is always
  1045. // real) performed by std::norm.
  1046. //
  1047. // norm(x + h) ~= norm(x) + 2x h
  1048. template <typename T, int N>
  1049. inline Jet<T, N> norm(const Jet<T, N>& f) {
  1050. return Jet<T, N>(norm(f.a), T(2) * f.a * f.v);
  1051. }
  1052. // pow -- base is a differentiable function, exponent is a constant.
  1053. // (a+da)^p ~= a^p + p*a^(p-1) da
  1054. template <typename T, int N>
  1055. inline Jet<T, N> pow(const Jet<T, N>& f, double g) {
  1056. T const tmp = g * pow(f.a, g - T(1.0));
  1057. return Jet<T, N>(pow(f.a, g), tmp * f.v);
  1058. }
  1059. // pow -- base is a constant, exponent is a differentiable function.
  1060. // We have various special cases, see the comment for pow(Jet, Jet) for
  1061. // analysis:
  1062. //
  1063. // 1. For f > 0 we have: (f)^(g + dg) ~= f^g + f^g log(f) dg
  1064. //
  1065. // 2. For f == 0 and g > 0 we have: (f)^(g + dg) ~= f^g
  1066. //
  1067. // 3. For f < 0 and integer g we have: (f)^(g + dg) ~= f^g but if dg
  1068. // != 0, the derivatives are not defined and we return NaN.
  1069. template <typename T, int N>
  1070. inline Jet<T, N> pow(T f, const Jet<T, N>& g) {
  1071. Jet<T, N> result;
  1072. if (fpclassify(f) == FP_ZERO && g > 0) {
  1073. // Handle case 2.
  1074. result = Jet<T, N>(T(0.0));
  1075. } else {
  1076. if (f < 0 && g == floor(g.a)) { // Handle case 3.
  1077. result = Jet<T, N>(pow(f, g.a));
  1078. for (int i = 0; i < N; i++) {
  1079. if (fpclassify(g.v[i]) != FP_ZERO) {
  1080. // Return a NaN when g.v != 0.
  1081. result.v[i] = std::numeric_limits<T>::quiet_NaN();
  1082. }
  1083. }
  1084. } else {
  1085. // Handle case 1.
  1086. T const tmp = pow(f, g.a);
  1087. result = Jet<T, N>(tmp, log(f) * tmp * g.v);
  1088. }
  1089. }
  1090. return result;
  1091. }
  1092. // pow -- both base and exponent are differentiable functions. This has a
  1093. // variety of special cases that require careful handling.
  1094. //
  1095. // 1. For f > 0:
  1096. // (f + df)^(g + dg) ~= f^g + f^(g - 1) * (g * df + f * log(f) * dg)
  1097. // The numerical evaluation of f * log(f) for f > 0 is well behaved, even for
  1098. // extremely small values (e.g. 1e-99).
  1099. //
  1100. // 2. For f == 0 and g > 1: (f + df)^(g + dg) ~= 0
  1101. // This cases is needed because log(0) can not be evaluated in the f > 0
  1102. // expression. However the function f*log(f) is well behaved around f == 0
  1103. // and its limit as f-->0 is zero.
  1104. //
  1105. // 3. For f == 0 and g == 1: (f + df)^(g + dg) ~= 0 + df
  1106. //
  1107. // 4. For f == 0 and 0 < g < 1: The value is finite but the derivatives are not.
  1108. //
  1109. // 5. For f == 0 and g < 0: The value and derivatives of f^g are not finite.
  1110. //
  1111. // 6. For f == 0 and g == 0: The C standard incorrectly defines 0^0 to be 1
  1112. // "because there are applications that can exploit this definition". We
  1113. // (arbitrarily) decree that derivatives here will be nonfinite, since that
  1114. // is consistent with the behavior for f == 0, g < 0 and 0 < g < 1.
  1115. // Practically any definition could have been justified because mathematical
  1116. // consistency has been lost at this point.
  1117. //
  1118. // 7. For f < 0, g integer, dg == 0: (f + df)^(g + dg) ~= f^g + g * f^(g - 1) df
  1119. // This is equivalent to the case where f is a differentiable function and g
  1120. // is a constant (to first order).
  1121. //
  1122. // 8. For f < 0, g integer, dg != 0: The value is finite but the derivatives are
  1123. // not, because any change in the value of g moves us away from the point
  1124. // with a real-valued answer into the region with complex-valued answers.
  1125. //
  1126. // 9. For f < 0, g noninteger: The value and derivatives of f^g are not finite.
  1127. template <typename T, int N>
  1128. inline Jet<T, N> pow(const Jet<T, N>& f, const Jet<T, N>& g) {
  1129. Jet<T, N> result;
  1130. if (fpclassify(f) == FP_ZERO && g >= 1) {
  1131. // Handle cases 2 and 3.
  1132. if (g > 1) {
  1133. result = Jet<T, N>(T(0.0));
  1134. } else {
  1135. result = f;
  1136. }
  1137. } else {
  1138. if (f < 0 && g == floor(g.a)) {
  1139. // Handle cases 7 and 8.
  1140. T const tmp = g.a * pow(f.a, g.a - T(1.0));
  1141. result = Jet<T, N>(pow(f.a, g.a), tmp * f.v);
  1142. for (int i = 0; i < N; i++) {
  1143. if (fpclassify(g.v[i]) != FP_ZERO) {
  1144. // Return a NaN when g.v != 0.
  1145. result.v[i] = T(std::numeric_limits<double>::quiet_NaN());
  1146. }
  1147. }
  1148. } else {
  1149. // Handle the remaining cases. For cases 4,5,6,9 we allow the log()
  1150. // function to generate -HUGE_VAL or NaN, since those cases result in a
  1151. // nonfinite derivative.
  1152. T const tmp1 = pow(f.a, g.a);
  1153. T const tmp2 = g.a * pow(f.a, g.a - T(1.0));
  1154. T const tmp3 = tmp1 * log(f.a);
  1155. result = Jet<T, N>(tmp1, tmp2 * f.v + tmp3 * g.v);
  1156. }
  1157. }
  1158. return result;
  1159. }
  1160. // Note: This has to be in the ceres namespace for argument dependent lookup to
  1161. // function correctly. Otherwise statements like CHECK_LE(x, 2.0) fail with
  1162. // strange compile errors.
  1163. template <typename T, int N>
  1164. inline std::ostream& operator<<(std::ostream& s, const Jet<T, N>& z) {
  1165. s << "[" << z.a << " ; ";
  1166. for (int i = 0; i < N; ++i) {
  1167. s << z.v[i];
  1168. if (i != N - 1) {
  1169. s << ", ";
  1170. }
  1171. }
  1172. s << "]";
  1173. return s;
  1174. }
  1175. } // namespace ceres
  1176. namespace std {
  1177. template <typename T, int N>
  1178. struct numeric_limits<ceres::Jet<T, N>> {
  1179. static constexpr bool is_specialized = true;
  1180. static constexpr bool is_signed = std::numeric_limits<T>::is_signed;
  1181. static constexpr bool is_integer = std::numeric_limits<T>::is_integer;
  1182. static constexpr bool is_exact = std::numeric_limits<T>::is_exact;
  1183. static constexpr bool has_infinity = std::numeric_limits<T>::has_infinity;
  1184. static constexpr bool has_quiet_NaN = std::numeric_limits<T>::has_quiet_NaN;
  1185. static constexpr bool has_signaling_NaN =
  1186. std::numeric_limits<T>::has_signaling_NaN;
  1187. static constexpr bool is_iec559 = std::numeric_limits<T>::is_iec559;
  1188. static constexpr bool is_bounded = std::numeric_limits<T>::is_bounded;
  1189. static constexpr bool is_modulo = std::numeric_limits<T>::is_modulo;
  1190. // has_denorm (and has_denorm_loss, not defined for Jet) has been deprecated
  1191. // in C++23. However, without an intent to remove the declaration. Disable
  1192. // deprecation warnings temporarily just for the corresponding symbols.
  1193. CERES_DISABLE_DEPRECATED_WARNING
  1194. static constexpr std::float_denorm_style has_denorm =
  1195. std::numeric_limits<T>::has_denorm;
  1196. CERES_RESTORE_DEPRECATED_WARNING
  1197. static constexpr std::float_round_style round_style =
  1198. std::numeric_limits<T>::round_style;
  1199. static constexpr int digits = std::numeric_limits<T>::digits;
  1200. static constexpr int digits10 = std::numeric_limits<T>::digits10;
  1201. static constexpr int max_digits10 = std::numeric_limits<T>::max_digits10;
  1202. static constexpr int radix = std::numeric_limits<T>::radix;
  1203. static constexpr int min_exponent = std::numeric_limits<T>::min_exponent;
  1204. static constexpr int min_exponent10 = std::numeric_limits<T>::max_exponent10;
  1205. static constexpr int max_exponent = std::numeric_limits<T>::max_exponent;
  1206. static constexpr int max_exponent10 = std::numeric_limits<T>::max_exponent10;
  1207. static constexpr bool traps = std::numeric_limits<T>::traps;
  1208. static constexpr bool tinyness_before =
  1209. std::numeric_limits<T>::tinyness_before;
  1210. static constexpr ceres::Jet<T, N> min
  1211. CERES_PREVENT_MACRO_SUBSTITUTION() noexcept {
  1212. return ceres::Jet<T, N>((std::numeric_limits<T>::min)());
  1213. }
  1214. static constexpr ceres::Jet<T, N> lowest() noexcept {
  1215. return ceres::Jet<T, N>(std::numeric_limits<T>::lowest());
  1216. }
  1217. static constexpr ceres::Jet<T, N> epsilon() noexcept {
  1218. return ceres::Jet<T, N>(std::numeric_limits<T>::epsilon());
  1219. }
  1220. static constexpr ceres::Jet<T, N> round_error() noexcept {
  1221. return ceres::Jet<T, N>(std::numeric_limits<T>::round_error());
  1222. }
  1223. static constexpr ceres::Jet<T, N> infinity() noexcept {
  1224. return ceres::Jet<T, N>(std::numeric_limits<T>::infinity());
  1225. }
  1226. static constexpr ceres::Jet<T, N> quiet_NaN() noexcept {
  1227. return ceres::Jet<T, N>(std::numeric_limits<T>::quiet_NaN());
  1228. }
  1229. static constexpr ceres::Jet<T, N> signaling_NaN() noexcept {
  1230. return ceres::Jet<T, N>(std::numeric_limits<T>::signaling_NaN());
  1231. }
  1232. static constexpr ceres::Jet<T, N> denorm_min() noexcept {
  1233. return ceres::Jet<T, N>(std::numeric_limits<T>::denorm_min());
  1234. }
  1235. static constexpr ceres::Jet<T, N> max
  1236. CERES_PREVENT_MACRO_SUBSTITUTION() noexcept {
  1237. return ceres::Jet<T, N>((std::numeric_limits<T>::max)());
  1238. }
  1239. };
  1240. } // namespace std
  1241. namespace Eigen {
  1242. // Creating a specialization of NumTraits enables placing Jet objects inside
  1243. // Eigen arrays, getting all the goodness of Eigen combined with autodiff.
  1244. template <typename T, int N>
  1245. struct NumTraits<ceres::Jet<T, N>> {
  1246. using Real = ceres::Jet<T, N>;
  1247. using NonInteger = ceres::Jet<T, N>;
  1248. using Nested = ceres::Jet<T, N>;
  1249. using Literal = ceres::Jet<T, N>;
  1250. static typename ceres::Jet<T, N> dummy_precision() {
  1251. return ceres::Jet<T, N>(1e-12);
  1252. }
  1253. static inline Real epsilon() {
  1254. return Real(std::numeric_limits<T>::epsilon());
  1255. }
  1256. static inline int digits10() { return NumTraits<T>::digits10(); }
  1257. static inline int max_digits10() { return NumTraits<T>::max_digits10(); }
  1258. enum {
  1259. IsComplex = 0,
  1260. IsInteger = 0,
  1261. IsSigned,
  1262. ReadCost = 1,
  1263. AddCost = 1,
  1264. // For Jet types, multiplication is more expensive than addition.
  1265. MulCost = 3,
  1266. HasFloatingPoint = 1,
  1267. RequireInitialization = 1
  1268. };
  1269. template <bool Vectorized>
  1270. struct Div {
  1271. enum {
  1272. #if defined(EIGEN_VECTORIZE_AVX)
  1273. AVX = true,
  1274. #else
  1275. AVX = false,
  1276. #endif
  1277. // Assuming that for Jets, division is as expensive as
  1278. // multiplication.
  1279. Cost = 3
  1280. };
  1281. };
  1282. static inline Real highest() { return Real((std::numeric_limits<T>::max)()); }
  1283. static inline Real lowest() { return Real(-(std::numeric_limits<T>::max)()); }
  1284. };
  1285. // Specifying the return type of binary operations between Jets and scalar types
  1286. // allows you to perform matrix/array operations with Eigen matrices and arrays
  1287. // such as addition, subtraction, multiplication, and division where one Eigen
  1288. // matrix/array is of type Jet and the other is a scalar type. This improves
  1289. // performance by using the optimized scalar-to-Jet binary operations but
  1290. // is only available on Eigen versions >= 3.3
  1291. template <typename BinaryOp, typename T, int N>
  1292. struct ScalarBinaryOpTraits<ceres::Jet<T, N>, T, BinaryOp> {
  1293. using ReturnType = ceres::Jet<T, N>;
  1294. };
  1295. template <typename BinaryOp, typename T, int N>
  1296. struct ScalarBinaryOpTraits<T, ceres::Jet<T, N>, BinaryOp> {
  1297. using ReturnType = ceres::Jet<T, N>;
  1298. };
  1299. } // namespace Eigen
  1300. #endif // CERES_PUBLIC_JET_H_