You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

226 lines
9.3 KiB

  1. namespace Eigen {
  2. /** \page TopicCustomizingEigen Customizing/Extending Eigen
  3. Eigen can be extended in several ways, for instance, by defining global methods, \ref ExtendingMatrixBase "by adding custom methods to MatrixBase", adding support to \ref CustomScalarType "custom types" etc.
  4. \eigenAutoToc
  5. \section ExtendingMatrixBase Extending MatrixBase (and other classes)
  6. In this section we will see how to add custom methods to MatrixBase. Since all expressions and matrix types inherit MatrixBase, adding a method to MatrixBase make it immediately available to all expressions ! A typical use case is, for instance, to make Eigen compatible with another API.
  7. You certainly know that in C++ it is not possible to add methods to an existing class. So how that's possible ? Here the trick is to include in the declaration of MatrixBase a file defined by the preprocessor token \c EIGEN_MATRIXBASE_PLUGIN:
  8. \code
  9. class MatrixBase {
  10. // ...
  11. #ifdef EIGEN_MATRIXBASE_PLUGIN
  12. #include EIGEN_MATRIXBASE_PLUGIN
  13. #endif
  14. };
  15. \endcode
  16. Therefore to extend MatrixBase with your own methods you just have to create a file with your method declaration and define EIGEN_MATRIXBASE_PLUGIN before you include any Eigen's header file.
  17. You can extend many of the other classes used in Eigen by defining similarly named preprocessor symbols. For instance, define \c EIGEN_ARRAYBASE_PLUGIN if you want to extend the ArrayBase class. A full list of classes that can be extended in this way and the corresponding preprocessor symbols can be found on our page \ref TopicPreprocessorDirectives.
  18. Here is an example of an extension file for adding methods to MatrixBase: \n
  19. \b MatrixBaseAddons.h
  20. \code
  21. inline Scalar at(uint i, uint j) const { return this->operator()(i,j); }
  22. inline Scalar& at(uint i, uint j) { return this->operator()(i,j); }
  23. inline Scalar at(uint i) const { return this->operator[](i); }
  24. inline Scalar& at(uint i) { return this->operator[](i); }
  25. inline RealScalar squaredLength() const { return squaredNorm(); }
  26. inline RealScalar length() const { return norm(); }
  27. inline RealScalar invLength(void) const { return fast_inv_sqrt(squaredNorm()); }
  28. template<typename OtherDerived>
  29. inline Scalar squaredDistanceTo(const MatrixBase<OtherDerived>& other) const
  30. { return (derived() - other.derived()).squaredNorm(); }
  31. template<typename OtherDerived>
  32. inline RealScalar distanceTo(const MatrixBase<OtherDerived>& other) const
  33. { return internal::sqrt(derived().squaredDistanceTo(other)); }
  34. inline void scaleTo(RealScalar l) { RealScalar vl = norm(); if (vl>1e-9) derived() *= (l/vl); }
  35. inline Transpose<Derived> transposed() {return this->transpose();}
  36. inline const Transpose<Derived> transposed() const {return this->transpose();}
  37. inline uint minComponentId(void) const { int i; this->minCoeff(&i); return i; }
  38. inline uint maxComponentId(void) const { int i; this->maxCoeff(&i); return i; }
  39. template<typename OtherDerived>
  40. void makeFloor(const MatrixBase<OtherDerived>& other) { derived() = derived().cwiseMin(other.derived()); }
  41. template<typename OtherDerived>
  42. void makeCeil(const MatrixBase<OtherDerived>& other) { derived() = derived().cwiseMax(other.derived()); }
  43. const CwiseUnaryOp<internal::scalar_add_op<Scalar>, Derived>
  44. operator+(const Scalar& scalar) const
  45. { return CwiseUnaryOp<internal::scalar_add_op<Scalar>, Derived>(derived(), internal::scalar_add_op<Scalar>(scalar)); }
  46. friend const CwiseUnaryOp<internal::scalar_add_op<Scalar>, Derived>
  47. operator+(const Scalar& scalar, const MatrixBase<Derived>& mat)
  48. { return CwiseUnaryOp<internal::scalar_add_op<Scalar>, Derived>(mat.derived(), internal::scalar_add_op<Scalar>(scalar)); }
  49. \endcode
  50. Then one can the following declaration in the config.h or whatever prerequisites header file of his project:
  51. \code
  52. #define EIGEN_MATRIXBASE_PLUGIN "MatrixBaseAddons.h"
  53. \endcode
  54. \section InheritingFromMatrix Inheriting from Matrix
  55. Before inheriting from Matrix, be really, I mean REALLY, sure that using
  56. EIGEN_MATRIX_PLUGIN is not what you really want (see previous section).
  57. If you just need to add few members to Matrix, this is the way to go.
  58. An example of when you actually need to inherit Matrix, is when you
  59. have several layers of heritage such as
  60. MyVerySpecificVector1, MyVerySpecificVector2 -> MyVector1 -> Matrix and
  61. MyVerySpecificVector3, MyVerySpecificVector4 -> MyVector2 -> Matrix.
  62. In order for your object to work within the %Eigen framework, you need to
  63. define a few members in your inherited class.
  64. Here is a minimalistic example:
  65. \include CustomizingEigen_Inheritance.cpp
  66. Output: \verbinclude CustomizingEigen_Inheritance.out
  67. This is the kind of error you can get if you don't provide those methods
  68. \verbatim
  69. error: no match for ‘operator=’ in ‘v = Eigen::operator*(
  70. const Eigen::MatrixBase<Eigen::Matrix<double, -0x000000001, 1, 0, -0x000000001, 1> >::Scalar&,
  71. const Eigen::MatrixBase<Eigen::Matrix<double, -0x000000001, 1> >::StorageBaseType&)
  72. (((const Eigen::MatrixBase<Eigen::Matrix<double, -0x000000001, 1> >::StorageBaseType&)
  73. ((const Eigen::MatrixBase<Eigen::Matrix<double, -0x000000001, 1> >::StorageBaseType*)(& v))))’
  74. \endverbatim
  75. \anchor user_defined_scalars \section CustomScalarType Using custom scalar types
  76. By default, Eigen currently supports standard floating-point types (\c float, \c double, \c std::complex<float>, \c std::complex<double>, \c long \c double), as well as all native integer types (e.g., \c int, \c unsigned \c int, \c short, etc.), and \c bool.
  77. On x86-64 systems, \c long \c double permits to locally enforces the use of x87 registers with extended accuracy (in comparison to SSE).
  78. In order to add support for a custom type \c T you need:
  79. -# make sure the common operator (+,-,*,/,etc.) are supported by the type \c T
  80. -# add a specialization of struct Eigen::NumTraits<T> (see \ref NumTraits)
  81. -# define the math functions that makes sense for your type. This includes standard ones like sqrt, pow, sin, tan, conj, real, imag, etc, as well as abs2 which is Eigen specific.
  82. (see the file Eigen/src/Core/MathFunctions.h)
  83. The math function should be defined in the same namespace than \c T, or in the \c std namespace though that second approach is not recommended.
  84. Here is a concrete example adding support for the Adolc's \c adouble type. <a href="https://projects.coin-or.org/ADOL-C">Adolc</a> is an automatic differentiation library. The type \c adouble is basically a real value tracking the values of any number of partial derivatives.
  85. \code
  86. #ifndef ADOLCSUPPORT_H
  87. #define ADOLCSUPPORT_H
  88. #define ADOLC_TAPELESS
  89. #include <adolc/adouble.h>
  90. #include <Eigen/Core>
  91. namespace Eigen {
  92. template<> struct NumTraits<adtl::adouble>
  93. : NumTraits<double> // permits to get the epsilon, dummy_precision, lowest, highest functions
  94. {
  95. typedef adtl::adouble Real;
  96. typedef adtl::adouble NonInteger;
  97. typedef adtl::adouble Nested;
  98. enum {
  99. IsComplex = 0,
  100. IsInteger = 0,
  101. IsSigned = 1,
  102. RequireInitialization = 1,
  103. ReadCost = 1,
  104. AddCost = 3,
  105. MulCost = 3
  106. };
  107. };
  108. }
  109. namespace adtl {
  110. inline const adouble& conj(const adouble& x) { return x; }
  111. inline const adouble& real(const adouble& x) { return x; }
  112. inline adouble imag(const adouble&) { return 0.; }
  113. inline adouble abs(const adouble& x) { return fabs(x); }
  114. inline adouble abs2(const adouble& x) { return x*x; }
  115. }
  116. #endif // ADOLCSUPPORT_H
  117. \endcode
  118. This other example adds support for the \c mpq_class type from <a href="https://gmplib.org/">GMP</a>. It shows in particular how to change the way Eigen picks the best pivot during LU factorization. It selects the coefficient with the highest score, where the score is by default the absolute value of a number, but we can define a different score, for instance to prefer pivots with a more compact representation (this is an example, not a recommendation). Note that the scores should always be non-negative and only zero is allowed to have a score of zero. Also, this can interact badly with thresholds for inexact scalar types.
  119. \code
  120. #include <gmpxx.h>
  121. #include <Eigen/Core>
  122. #include <boost/operators.hpp>
  123. namespace Eigen {
  124. template<class> struct NumTraits;
  125. template<> struct NumTraits<mpq_class>
  126. {
  127. typedef mpq_class Real;
  128. typedef mpq_class NonInteger;
  129. typedef mpq_class Nested;
  130. static inline Real epsilon() { return 0; }
  131. static inline Real dummy_precision() { return 0; }
  132. enum {
  133. IsInteger = 0,
  134. IsSigned = 1,
  135. IsComplex = 0,
  136. RequireInitialization = 1,
  137. ReadCost = 6,
  138. AddCost = 150,
  139. MulCost = 100
  140. };
  141. };
  142. namespace internal {
  143. template<>
  144. struct significant_decimals_impl<mpq_class>
  145. {
  146. // Infinite precision when printing
  147. static inline int run() { return 0; }
  148. };
  149. template<> struct scalar_score_coeff_op<mpq_class> {
  150. struct result_type : boost::totally_ordered1<result_type> {
  151. std::size_t len;
  152. result_type(int i = 0) : len(i) {} // Eigen uses Score(0) and Score()
  153. result_type(mpq_class const& q) :
  154. len(mpz_size(q.get_num_mpz_t())+
  155. mpz_size(q.get_den_mpz_t())-1) {}
  156. friend bool operator<(result_type x, result_type y) {
  157. // 0 is the worst possible pivot
  158. if (x.len == 0) return y.len > 0;
  159. if (y.len == 0) return false;
  160. // Prefer a pivot with a small representation
  161. return x.len > y.len;
  162. }
  163. friend bool operator==(result_type x, result_type y) {
  164. // Only used to test if the score is 0
  165. return x.len == y.len;
  166. }
  167. };
  168. result_type operator()(mpq_class const& x) const { return x; }
  169. };
  170. }
  171. }
  172. \endcode
  173. \sa \ref TopicPreprocessorDirectives
  174. */
  175. }