Dot.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // This file is part of Eigen, a lightweight C++ template library
  2. // for linear algebra.
  3. //
  4. // Copyright (C) 2006-2008, 2010 Benoit Jacob <jacob.benoit.1@gmail.com>
  5. //
  6. // This Source Code Form is subject to the terms of the Mozilla
  7. // Public License v. 2.0. If a copy of the MPL was not distributed
  8. // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9. #ifndef EIGEN_DOT_H
  10. #define EIGEN_DOT_H
  11. namespace Eigen {
  12. namespace internal {
  13. // helper function for dot(). The problem is that if we put that in the body of dot(), then upon calling dot
  14. // with mismatched types, the compiler emits errors about failing to instantiate cwiseProduct BEFORE
  15. // looking at the static assertions. Thus this is a trick to get better compile errors.
  16. template<typename T, typename U,
  17. // the NeedToTranspose condition here is taken straight from Assign.h
  18. bool NeedToTranspose = T::IsVectorAtCompileTime
  19. && U::IsVectorAtCompileTime
  20. && ((int(T::RowsAtCompileTime) == 1 && int(U::ColsAtCompileTime) == 1)
  21. | // FIXME | instead of || to please GCC 4.4.0 stupid warning "suggest parentheses around &&".
  22. // revert to || as soon as not needed anymore.
  23. (int(T::ColsAtCompileTime) == 1 && int(U::RowsAtCompileTime) == 1))
  24. >
  25. struct dot_nocheck
  26. {
  27. typedef scalar_conj_product_op<typename traits<T>::Scalar,typename traits<U>::Scalar> conj_prod;
  28. typedef typename conj_prod::result_type ResScalar;
  29. EIGEN_DEVICE_FUNC
  30. EIGEN_STRONG_INLINE
  31. static ResScalar run(const MatrixBase<T>& a, const MatrixBase<U>& b)
  32. {
  33. return a.template binaryExpr<conj_prod>(b).sum();
  34. }
  35. };
  36. template<typename T, typename U>
  37. struct dot_nocheck<T, U, true>
  38. {
  39. typedef scalar_conj_product_op<typename traits<T>::Scalar,typename traits<U>::Scalar> conj_prod;
  40. typedef typename conj_prod::result_type ResScalar;
  41. EIGEN_DEVICE_FUNC
  42. EIGEN_STRONG_INLINE
  43. static ResScalar run(const MatrixBase<T>& a, const MatrixBase<U>& b)
  44. {
  45. return a.transpose().template binaryExpr<conj_prod>(b).sum();
  46. }
  47. };
  48. } // end namespace internal
  49. /** \fn MatrixBase::dot
  50. * \returns the dot product of *this with other.
  51. *
  52. * \only_for_vectors
  53. *
  54. * \note If the scalar type is complex numbers, then this function returns the hermitian
  55. * (sesquilinear) dot product, conjugate-linear in the first variable and linear in the
  56. * second variable.
  57. *
  58. * \sa squaredNorm(), norm()
  59. */
  60. template<typename Derived>
  61. template<typename OtherDerived>
  62. EIGEN_DEVICE_FUNC
  63. EIGEN_STRONG_INLINE
  64. typename ScalarBinaryOpTraits<typename internal::traits<Derived>::Scalar,typename internal::traits<OtherDerived>::Scalar>::ReturnType
  65. MatrixBase<Derived>::dot(const MatrixBase<OtherDerived>& other) const
  66. {
  67. EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived)
  68. EIGEN_STATIC_ASSERT_VECTOR_ONLY(OtherDerived)
  69. EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(Derived,OtherDerived)
  70. #if !(defined(EIGEN_NO_STATIC_ASSERT) && defined(EIGEN_NO_DEBUG))
  71. typedef internal::scalar_conj_product_op<Scalar,typename OtherDerived::Scalar> func;
  72. EIGEN_CHECK_BINARY_COMPATIBILIY(func,Scalar,typename OtherDerived::Scalar);
  73. #endif
  74. eigen_assert(size() == other.size());
  75. return internal::dot_nocheck<Derived,OtherDerived>::run(*this, other);
  76. }
  77. //---------- implementation of L2 norm and related functions ----------
  78. /** \returns, for vectors, the squared \em l2 norm of \c *this, and for matrices the Frobenius norm.
  79. * In both cases, it consists in the sum of the square of all the matrix entries.
  80. * For vectors, this is also equals to the dot product of \c *this with itself.
  81. *
  82. * \sa dot(), norm(), lpNorm()
  83. */
  84. template<typename Derived>
  85. EIGEN_STRONG_INLINE typename NumTraits<typename internal::traits<Derived>::Scalar>::Real MatrixBase<Derived>::squaredNorm() const
  86. {
  87. return numext::real((*this).cwiseAbs2().sum());
  88. }
  89. /** \returns, for vectors, the \em l2 norm of \c *this, and for matrices the Frobenius norm.
  90. * In both cases, it consists in the square root of the sum of the square of all the matrix entries.
  91. * For vectors, this is also equals to the square root of the dot product of \c *this with itself.
  92. *
  93. * \sa lpNorm(), dot(), squaredNorm()
  94. */
  95. template<typename Derived>
  96. EIGEN_STRONG_INLINE typename NumTraits<typename internal::traits<Derived>::Scalar>::Real MatrixBase<Derived>::norm() const
  97. {
  98. return numext::sqrt(squaredNorm());
  99. }
  100. /** \returns an expression of the quotient of \c *this by its own norm.
  101. *
  102. * \warning If the input vector is too small (i.e., this->norm()==0),
  103. * then this function returns a copy of the input.
  104. *
  105. * \only_for_vectors
  106. *
  107. * \sa norm(), normalize()
  108. */
  109. template<typename Derived>
  110. EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::PlainObject
  111. MatrixBase<Derived>::normalized() const
  112. {
  113. typedef typename internal::nested_eval<Derived,2>::type _Nested;
  114. _Nested n(derived());
  115. RealScalar z = n.squaredNorm();
  116. // NOTE: after extensive benchmarking, this conditional does not impact performance, at least on recent x86 CPU
  117. if(z>RealScalar(0))
  118. return n / numext::sqrt(z);
  119. else
  120. return n;
  121. }
  122. /** Normalizes the vector, i.e. divides it by its own norm.
  123. *
  124. * \only_for_vectors
  125. *
  126. * \warning If the input vector is too small (i.e., this->norm()==0), then \c *this is left unchanged.
  127. *
  128. * \sa norm(), normalized()
  129. */
  130. template<typename Derived>
  131. EIGEN_STRONG_INLINE void MatrixBase<Derived>::normalize()
  132. {
  133. RealScalar z = squaredNorm();
  134. // NOTE: after extensive benchmarking, this conditional does not impact performance, at least on recent x86 CPU
  135. if(z>RealScalar(0))
  136. derived() /= numext::sqrt(z);
  137. }
  138. /** \returns an expression of the quotient of \c *this by its own norm while avoiding underflow and overflow.
  139. *
  140. * \only_for_vectors
  141. *
  142. * This method is analogue to the normalized() method, but it reduces the risk of
  143. * underflow and overflow when computing the norm.
  144. *
  145. * \warning If the input vector is too small (i.e., this->norm()==0),
  146. * then this function returns a copy of the input.
  147. *
  148. * \sa stableNorm(), stableNormalize(), normalized()
  149. */
  150. template<typename Derived>
  151. EIGEN_STRONG_INLINE const typename MatrixBase<Derived>::PlainObject
  152. MatrixBase<Derived>::stableNormalized() const
  153. {
  154. typedef typename internal::nested_eval<Derived,3>::type _Nested;
  155. _Nested n(derived());
  156. RealScalar w = n.cwiseAbs().maxCoeff();
  157. RealScalar z = (n/w).squaredNorm();
  158. if(z>RealScalar(0))
  159. return n / (numext::sqrt(z)*w);
  160. else
  161. return n;
  162. }
  163. /** Normalizes the vector while avoid underflow and overflow
  164. *
  165. * \only_for_vectors
  166. *
  167. * This method is analogue to the normalize() method, but it reduces the risk of
  168. * underflow and overflow when computing the norm.
  169. *
  170. * \warning If the input vector is too small (i.e., this->norm()==0), then \c *this is left unchanged.
  171. *
  172. * \sa stableNorm(), stableNormalized(), normalize()
  173. */
  174. template<typename Derived>
  175. EIGEN_STRONG_INLINE void MatrixBase<Derived>::stableNormalize()
  176. {
  177. RealScalar w = cwiseAbs().maxCoeff();
  178. RealScalar z = (derived()/w).squaredNorm();
  179. if(z>RealScalar(0))
  180. derived() /= numext::sqrt(z)*w;
  181. }
  182. //---------- implementation of other norms ----------
  183. namespace internal {
  184. template<typename Derived, int p>
  185. struct lpNorm_selector
  186. {
  187. typedef typename NumTraits<typename traits<Derived>::Scalar>::Real RealScalar;
  188. EIGEN_DEVICE_FUNC
  189. static inline RealScalar run(const MatrixBase<Derived>& m)
  190. {
  191. EIGEN_USING_STD_MATH(pow)
  192. return pow(m.cwiseAbs().array().pow(p).sum(), RealScalar(1)/p);
  193. }
  194. };
  195. template<typename Derived>
  196. struct lpNorm_selector<Derived, 1>
  197. {
  198. EIGEN_DEVICE_FUNC
  199. static inline typename NumTraits<typename traits<Derived>::Scalar>::Real run(const MatrixBase<Derived>& m)
  200. {
  201. return m.cwiseAbs().sum();
  202. }
  203. };
  204. template<typename Derived>
  205. struct lpNorm_selector<Derived, 2>
  206. {
  207. EIGEN_DEVICE_FUNC
  208. static inline typename NumTraits<typename traits<Derived>::Scalar>::Real run(const MatrixBase<Derived>& m)
  209. {
  210. return m.norm();
  211. }
  212. };
  213. template<typename Derived>
  214. struct lpNorm_selector<Derived, Infinity>
  215. {
  216. typedef typename NumTraits<typename traits<Derived>::Scalar>::Real RealScalar;
  217. EIGEN_DEVICE_FUNC
  218. static inline RealScalar run(const MatrixBase<Derived>& m)
  219. {
  220. if(Derived::SizeAtCompileTime==0 || (Derived::SizeAtCompileTime==Dynamic && m.size()==0))
  221. return RealScalar(0);
  222. return m.cwiseAbs().maxCoeff();
  223. }
  224. };
  225. } // end namespace internal
  226. /** \returns the \b coefficient-wise \f$ \ell^p \f$ norm of \c *this, that is, returns the p-th root of the sum of the p-th powers of the absolute values
  227. * of the coefficients of \c *this. If \a p is the special value \a Eigen::Infinity, this function returns the \f$ \ell^\infty \f$
  228. * norm, that is the maximum of the absolute values of the coefficients of \c *this.
  229. *
  230. * In all cases, if \c *this is empty, then the value 0 is returned.
  231. *
  232. * \note For matrices, this function does not compute the <a href="https://en.wikipedia.org/wiki/Operator_norm">operator-norm</a>. That is, if \c *this is a matrix, then its coefficients are interpreted as a 1D vector. Nonetheless, you can easily compute the 1-norm and \f$\infty\f$-norm matrix operator norms using \link TutorialReductionsVisitorsBroadcastingReductionsNorm partial reductions \endlink.
  233. *
  234. * \sa norm()
  235. */
  236. template<typename Derived>
  237. template<int p>
  238. #ifndef EIGEN_PARSED_BY_DOXYGEN
  239. inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real
  240. #else
  241. MatrixBase<Derived>::RealScalar
  242. #endif
  243. MatrixBase<Derived>::lpNorm() const
  244. {
  245. return internal::lpNorm_selector<Derived, p>::run(*this);
  246. }
  247. //---------- implementation of isOrthogonal / isUnitary ----------
  248. /** \returns true if *this is approximately orthogonal to \a other,
  249. * within the precision given by \a prec.
  250. *
  251. * Example: \include MatrixBase_isOrthogonal.cpp
  252. * Output: \verbinclude MatrixBase_isOrthogonal.out
  253. */
  254. template<typename Derived>
  255. template<typename OtherDerived>
  256. bool MatrixBase<Derived>::isOrthogonal
  257. (const MatrixBase<OtherDerived>& other, const RealScalar& prec) const
  258. {
  259. typename internal::nested_eval<Derived,2>::type nested(derived());
  260. typename internal::nested_eval<OtherDerived,2>::type otherNested(other.derived());
  261. return numext::abs2(nested.dot(otherNested)) <= prec * prec * nested.squaredNorm() * otherNested.squaredNorm();
  262. }
  263. /** \returns true if *this is approximately an unitary matrix,
  264. * within the precision given by \a prec. In the case where the \a Scalar
  265. * type is real numbers, a unitary matrix is an orthogonal matrix, whence the name.
  266. *
  267. * \note This can be used to check whether a family of vectors forms an orthonormal basis.
  268. * Indeed, \c m.isUnitary() returns true if and only if the columns (equivalently, the rows) of m form an
  269. * orthonormal basis.
  270. *
  271. * Example: \include MatrixBase_isUnitary.cpp
  272. * Output: \verbinclude MatrixBase_isUnitary.out
  273. */
  274. template<typename Derived>
  275. bool MatrixBase<Derived>::isUnitary(const RealScalar& prec) const
  276. {
  277. typename internal::nested_eval<Derived,1>::type self(derived());
  278. for(Index i = 0; i < cols(); ++i)
  279. {
  280. if(!internal::isApprox(self.col(i).squaredNorm(), static_cast<RealScalar>(1), prec))
  281. return false;
  282. for(Index j = 0; j < i; ++j)
  283. if(!internal::isMuchSmallerThan(self.col(i).dot(self.col(j)), static_cast<Scalar>(1), prec))
  284. return false;
  285. }
  286. return true;
  287. }
  288. } // end namespace Eigen
  289. #endif // EIGEN_DOT_H