ComplexSchur.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. // This file is part of Eigen, a lightweight C++ template library
  2. // for linear algebra.
  3. //
  4. // Copyright (C) 2009 Claire Maurice
  5. // Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
  6. // Copyright (C) 2010,2012 Jitse Niesen <jitse@maths.leeds.ac.uk>
  7. //
  8. // This Source Code Form is subject to the terms of the Mozilla
  9. // Public License v. 2.0. If a copy of the MPL was not distributed
  10. // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
  11. #ifndef EIGEN_COMPLEX_SCHUR_H
  12. #define EIGEN_COMPLEX_SCHUR_H
  13. #include "./HessenbergDecomposition.h"
  14. namespace Eigen {
  15. namespace internal {
  16. template<typename MatrixType, bool IsComplex> struct complex_schur_reduce_to_hessenberg;
  17. }
  18. /** \eigenvalues_module \ingroup Eigenvalues_Module
  19. *
  20. *
  21. * \class ComplexSchur
  22. *
  23. * \brief Performs a complex Schur decomposition of a real or complex square matrix
  24. *
  25. * \tparam _MatrixType the type of the matrix of which we are
  26. * computing the Schur decomposition; this is expected to be an
  27. * instantiation of the Matrix class template.
  28. *
  29. * Given a real or complex square matrix A, this class computes the
  30. * Schur decomposition: \f$ A = U T U^*\f$ where U is a unitary
  31. * complex matrix, and T is a complex upper triangular matrix. The
  32. * diagonal of the matrix T corresponds to the eigenvalues of the
  33. * matrix A.
  34. *
  35. * Call the function compute() to compute the Schur decomposition of
  36. * a given matrix. Alternatively, you can use the
  37. * ComplexSchur(const MatrixType&, bool) constructor which computes
  38. * the Schur decomposition at construction time. Once the
  39. * decomposition is computed, you can use the matrixU() and matrixT()
  40. * functions to retrieve the matrices U and V in the decomposition.
  41. *
  42. * \note This code is inspired from Jampack
  43. *
  44. * \sa class RealSchur, class EigenSolver, class ComplexEigenSolver
  45. */
  46. template<typename _MatrixType> class ComplexSchur
  47. {
  48. public:
  49. typedef _MatrixType MatrixType;
  50. enum {
  51. RowsAtCompileTime = MatrixType::RowsAtCompileTime,
  52. ColsAtCompileTime = MatrixType::ColsAtCompileTime,
  53. Options = MatrixType::Options,
  54. MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
  55. MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime
  56. };
  57. /** \brief Scalar type for matrices of type \p _MatrixType. */
  58. typedef typename MatrixType::Scalar Scalar;
  59. typedef typename NumTraits<Scalar>::Real RealScalar;
  60. typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3
  61. /** \brief Complex scalar type for \p _MatrixType.
  62. *
  63. * This is \c std::complex<Scalar> if #Scalar is real (e.g.,
  64. * \c float or \c double) and just \c Scalar if #Scalar is
  65. * complex.
  66. */
  67. typedef std::complex<RealScalar> ComplexScalar;
  68. /** \brief Type for the matrices in the Schur decomposition.
  69. *
  70. * This is a square matrix with entries of type #ComplexScalar.
  71. * The size is the same as the size of \p _MatrixType.
  72. */
  73. typedef Matrix<ComplexScalar, RowsAtCompileTime, ColsAtCompileTime, Options, MaxRowsAtCompileTime, MaxColsAtCompileTime> ComplexMatrixType;
  74. /** \brief Default constructor.
  75. *
  76. * \param [in] size Positive integer, size of the matrix whose Schur decomposition will be computed.
  77. *
  78. * The default constructor is useful in cases in which the user
  79. * intends to perform decompositions via compute(). The \p size
  80. * parameter is only used as a hint. It is not an error to give a
  81. * wrong \p size, but it may impair performance.
  82. *
  83. * \sa compute() for an example.
  84. */
  85. explicit ComplexSchur(Index size = RowsAtCompileTime==Dynamic ? 1 : RowsAtCompileTime)
  86. : m_matT(size,size),
  87. m_matU(size,size),
  88. m_hess(size),
  89. m_isInitialized(false),
  90. m_matUisUptodate(false),
  91. m_maxIters(-1)
  92. {}
  93. /** \brief Constructor; computes Schur decomposition of given matrix.
  94. *
  95. * \param[in] matrix Square matrix whose Schur decomposition is to be computed.
  96. * \param[in] computeU If true, both T and U are computed; if false, only T is computed.
  97. *
  98. * This constructor calls compute() to compute the Schur decomposition.
  99. *
  100. * \sa matrixT() and matrixU() for examples.
  101. */
  102. template<typename InputType>
  103. explicit ComplexSchur(const EigenBase<InputType>& matrix, bool computeU = true)
  104. : m_matT(matrix.rows(),matrix.cols()),
  105. m_matU(matrix.rows(),matrix.cols()),
  106. m_hess(matrix.rows()),
  107. m_isInitialized(false),
  108. m_matUisUptodate(false),
  109. m_maxIters(-1)
  110. {
  111. compute(matrix.derived(), computeU);
  112. }
  113. /** \brief Returns the unitary matrix in the Schur decomposition.
  114. *
  115. * \returns A const reference to the matrix U.
  116. *
  117. * It is assumed that either the constructor
  118. * ComplexSchur(const MatrixType& matrix, bool computeU) or the
  119. * member function compute(const MatrixType& matrix, bool computeU)
  120. * has been called before to compute the Schur decomposition of a
  121. * matrix, and that \p computeU was set to true (the default
  122. * value).
  123. *
  124. * Example: \include ComplexSchur_matrixU.cpp
  125. * Output: \verbinclude ComplexSchur_matrixU.out
  126. */
  127. const ComplexMatrixType& matrixU() const
  128. {
  129. eigen_assert(m_isInitialized && "ComplexSchur is not initialized.");
  130. eigen_assert(m_matUisUptodate && "The matrix U has not been computed during the ComplexSchur decomposition.");
  131. return m_matU;
  132. }
  133. /** \brief Returns the triangular matrix in the Schur decomposition.
  134. *
  135. * \returns A const reference to the matrix T.
  136. *
  137. * It is assumed that either the constructor
  138. * ComplexSchur(const MatrixType& matrix, bool computeU) or the
  139. * member function compute(const MatrixType& matrix, bool computeU)
  140. * has been called before to compute the Schur decomposition of a
  141. * matrix.
  142. *
  143. * Note that this function returns a plain square matrix. If you want to reference
  144. * only the upper triangular part, use:
  145. * \code schur.matrixT().triangularView<Upper>() \endcode
  146. *
  147. * Example: \include ComplexSchur_matrixT.cpp
  148. * Output: \verbinclude ComplexSchur_matrixT.out
  149. */
  150. const ComplexMatrixType& matrixT() const
  151. {
  152. eigen_assert(m_isInitialized && "ComplexSchur is not initialized.");
  153. return m_matT;
  154. }
  155. /** \brief Computes Schur decomposition of given matrix.
  156. *
  157. * \param[in] matrix Square matrix whose Schur decomposition is to be computed.
  158. * \param[in] computeU If true, both T and U are computed; if false, only T is computed.
  159. * \returns Reference to \c *this
  160. *
  161. * The Schur decomposition is computed by first reducing the
  162. * matrix to Hessenberg form using the class
  163. * HessenbergDecomposition. The Hessenberg matrix is then reduced
  164. * to triangular form by performing QR iterations with a single
  165. * shift. The cost of computing the Schur decomposition depends
  166. * on the number of iterations; as a rough guide, it may be taken
  167. * on the number of iterations; as a rough guide, it may be taken
  168. * to be \f$25n^3\f$ complex flops, or \f$10n^3\f$ complex flops
  169. * if \a computeU is false.
  170. *
  171. * Example: \include ComplexSchur_compute.cpp
  172. * Output: \verbinclude ComplexSchur_compute.out
  173. *
  174. * \sa compute(const MatrixType&, bool, Index)
  175. */
  176. template<typename InputType>
  177. ComplexSchur& compute(const EigenBase<InputType>& matrix, bool computeU = true);
  178. /** \brief Compute Schur decomposition from a given Hessenberg matrix
  179. * \param[in] matrixH Matrix in Hessenberg form H
  180. * \param[in] matrixQ orthogonal matrix Q that transform a matrix A to H : A = Q H Q^T
  181. * \param computeU Computes the matriX U of the Schur vectors
  182. * \return Reference to \c *this
  183. *
  184. * This routine assumes that the matrix is already reduced in Hessenberg form matrixH
  185. * using either the class HessenbergDecomposition or another mean.
  186. * It computes the upper quasi-triangular matrix T of the Schur decomposition of H
  187. * When computeU is true, this routine computes the matrix U such that
  188. * A = U T U^T = (QZ) T (QZ)^T = Q H Q^T where A is the initial matrix
  189. *
  190. * NOTE Q is referenced if computeU is true; so, if the initial orthogonal matrix
  191. * is not available, the user should give an identity matrix (Q.setIdentity())
  192. *
  193. * \sa compute(const MatrixType&, bool)
  194. */
  195. template<typename HessMatrixType, typename OrthMatrixType>
  196. ComplexSchur& computeFromHessenberg(const HessMatrixType& matrixH, const OrthMatrixType& matrixQ, bool computeU=true);
  197. /** \brief Reports whether previous computation was successful.
  198. *
  199. * \returns \c Success if computation was succesful, \c NoConvergence otherwise.
  200. */
  201. ComputationInfo info() const
  202. {
  203. eigen_assert(m_isInitialized && "ComplexSchur is not initialized.");
  204. return m_info;
  205. }
  206. /** \brief Sets the maximum number of iterations allowed.
  207. *
  208. * If not specified by the user, the maximum number of iterations is m_maxIterationsPerRow times the size
  209. * of the matrix.
  210. */
  211. ComplexSchur& setMaxIterations(Index maxIters)
  212. {
  213. m_maxIters = maxIters;
  214. return *this;
  215. }
  216. /** \brief Returns the maximum number of iterations. */
  217. Index getMaxIterations()
  218. {
  219. return m_maxIters;
  220. }
  221. /** \brief Maximum number of iterations per row.
  222. *
  223. * If not otherwise specified, the maximum number of iterations is this number times the size of the
  224. * matrix. It is currently set to 30.
  225. */
  226. static const int m_maxIterationsPerRow = 30;
  227. protected:
  228. ComplexMatrixType m_matT, m_matU;
  229. HessenbergDecomposition<MatrixType> m_hess;
  230. ComputationInfo m_info;
  231. bool m_isInitialized;
  232. bool m_matUisUptodate;
  233. Index m_maxIters;
  234. private:
  235. bool subdiagonalEntryIsNeglegible(Index i);
  236. ComplexScalar computeShift(Index iu, Index iter);
  237. void reduceToTriangularForm(bool computeU);
  238. friend struct internal::complex_schur_reduce_to_hessenberg<MatrixType, NumTraits<Scalar>::IsComplex>;
  239. };
  240. /** If m_matT(i+1,i) is neglegible in floating point arithmetic
  241. * compared to m_matT(i,i) and m_matT(j,j), then set it to zero and
  242. * return true, else return false. */
  243. template<typename MatrixType>
  244. inline bool ComplexSchur<MatrixType>::subdiagonalEntryIsNeglegible(Index i)
  245. {
  246. RealScalar d = numext::norm1(m_matT.coeff(i,i)) + numext::norm1(m_matT.coeff(i+1,i+1));
  247. RealScalar sd = numext::norm1(m_matT.coeff(i+1,i));
  248. if (internal::isMuchSmallerThan(sd, d, NumTraits<RealScalar>::epsilon()))
  249. {
  250. m_matT.coeffRef(i+1,i) = ComplexScalar(0);
  251. return true;
  252. }
  253. return false;
  254. }
  255. /** Compute the shift in the current QR iteration. */
  256. template<typename MatrixType>
  257. typename ComplexSchur<MatrixType>::ComplexScalar ComplexSchur<MatrixType>::computeShift(Index iu, Index iter)
  258. {
  259. using std::abs;
  260. if (iter == 10 || iter == 20)
  261. {
  262. // exceptional shift, taken from http://www.netlib.org/eispack/comqr.f
  263. return abs(numext::real(m_matT.coeff(iu,iu-1))) + abs(numext::real(m_matT.coeff(iu-1,iu-2)));
  264. }
  265. // compute the shift as one of the eigenvalues of t, the 2x2
  266. // diagonal block on the bottom of the active submatrix
  267. Matrix<ComplexScalar,2,2> t = m_matT.template block<2,2>(iu-1,iu-1);
  268. RealScalar normt = t.cwiseAbs().sum();
  269. t /= normt; // the normalization by sf is to avoid under/overflow
  270. ComplexScalar b = t.coeff(0,1) * t.coeff(1,0);
  271. ComplexScalar c = t.coeff(0,0) - t.coeff(1,1);
  272. ComplexScalar disc = sqrt(c*c + RealScalar(4)*b);
  273. ComplexScalar det = t.coeff(0,0) * t.coeff(1,1) - b;
  274. ComplexScalar trace = t.coeff(0,0) + t.coeff(1,1);
  275. ComplexScalar eival1 = (trace + disc) / RealScalar(2);
  276. ComplexScalar eival2 = (trace - disc) / RealScalar(2);
  277. RealScalar eival1_norm = numext::norm1(eival1);
  278. RealScalar eival2_norm = numext::norm1(eival2);
  279. // A division by zero can only occur if eival1==eival2==0.
  280. // In this case, det==0, and all we have to do is checking that eival2_norm!=0
  281. if(eival1_norm > eival2_norm)
  282. eival2 = det / eival1;
  283. else if(eival2_norm!=RealScalar(0))
  284. eival1 = det / eival2;
  285. // choose the eigenvalue closest to the bottom entry of the diagonal
  286. if(numext::norm1(eival1-t.coeff(1,1)) < numext::norm1(eival2-t.coeff(1,1)))
  287. return normt * eival1;
  288. else
  289. return normt * eival2;
  290. }
  291. template<typename MatrixType>
  292. template<typename InputType>
  293. ComplexSchur<MatrixType>& ComplexSchur<MatrixType>::compute(const EigenBase<InputType>& matrix, bool computeU)
  294. {
  295. m_matUisUptodate = false;
  296. eigen_assert(matrix.cols() == matrix.rows());
  297. if(matrix.cols() == 1)
  298. {
  299. m_matT = matrix.derived().template cast<ComplexScalar>();
  300. if(computeU) m_matU = ComplexMatrixType::Identity(1,1);
  301. m_info = Success;
  302. m_isInitialized = true;
  303. m_matUisUptodate = computeU;
  304. return *this;
  305. }
  306. internal::complex_schur_reduce_to_hessenberg<MatrixType, NumTraits<Scalar>::IsComplex>::run(*this, matrix.derived(), computeU);
  307. computeFromHessenberg(m_matT, m_matU, computeU);
  308. return *this;
  309. }
  310. template<typename MatrixType>
  311. template<typename HessMatrixType, typename OrthMatrixType>
  312. ComplexSchur<MatrixType>& ComplexSchur<MatrixType>::computeFromHessenberg(const HessMatrixType& matrixH, const OrthMatrixType& matrixQ, bool computeU)
  313. {
  314. m_matT = matrixH;
  315. if(computeU)
  316. m_matU = matrixQ;
  317. reduceToTriangularForm(computeU);
  318. return *this;
  319. }
  320. namespace internal {
  321. /* Reduce given matrix to Hessenberg form */
  322. template<typename MatrixType, bool IsComplex>
  323. struct complex_schur_reduce_to_hessenberg
  324. {
  325. // this is the implementation for the case IsComplex = true
  326. static void run(ComplexSchur<MatrixType>& _this, const MatrixType& matrix, bool computeU)
  327. {
  328. _this.m_hess.compute(matrix);
  329. _this.m_matT = _this.m_hess.matrixH();
  330. if(computeU) _this.m_matU = _this.m_hess.matrixQ();
  331. }
  332. };
  333. template<typename MatrixType>
  334. struct complex_schur_reduce_to_hessenberg<MatrixType, false>
  335. {
  336. static void run(ComplexSchur<MatrixType>& _this, const MatrixType& matrix, bool computeU)
  337. {
  338. typedef typename ComplexSchur<MatrixType>::ComplexScalar ComplexScalar;
  339. // Note: m_hess is over RealScalar; m_matT and m_matU is over ComplexScalar
  340. _this.m_hess.compute(matrix);
  341. _this.m_matT = _this.m_hess.matrixH().template cast<ComplexScalar>();
  342. if(computeU)
  343. {
  344. // This may cause an allocation which seems to be avoidable
  345. MatrixType Q = _this.m_hess.matrixQ();
  346. _this.m_matU = Q.template cast<ComplexScalar>();
  347. }
  348. }
  349. };
  350. } // end namespace internal
  351. // Reduce the Hessenberg matrix m_matT to triangular form by QR iteration.
  352. template<typename MatrixType>
  353. void ComplexSchur<MatrixType>::reduceToTriangularForm(bool computeU)
  354. {
  355. Index maxIters = m_maxIters;
  356. if (maxIters == -1)
  357. maxIters = m_maxIterationsPerRow * m_matT.rows();
  358. // The matrix m_matT is divided in three parts.
  359. // Rows 0,...,il-1 are decoupled from the rest because m_matT(il,il-1) is zero.
  360. // Rows il,...,iu is the part we are working on (the active submatrix).
  361. // Rows iu+1,...,end are already brought in triangular form.
  362. Index iu = m_matT.cols() - 1;
  363. Index il;
  364. Index iter = 0; // number of iterations we are working on the (iu,iu) element
  365. Index totalIter = 0; // number of iterations for whole matrix
  366. while(true)
  367. {
  368. // find iu, the bottom row of the active submatrix
  369. while(iu > 0)
  370. {
  371. if(!subdiagonalEntryIsNeglegible(iu-1)) break;
  372. iter = 0;
  373. --iu;
  374. }
  375. // if iu is zero then we are done; the whole matrix is triangularized
  376. if(iu==0) break;
  377. // if we spent too many iterations, we give up
  378. iter++;
  379. totalIter++;
  380. if(totalIter > maxIters) break;
  381. // find il, the top row of the active submatrix
  382. il = iu-1;
  383. while(il > 0 && !subdiagonalEntryIsNeglegible(il-1))
  384. {
  385. --il;
  386. }
  387. /* perform the QR step using Givens rotations. The first rotation
  388. creates a bulge; the (il+2,il) element becomes nonzero. This
  389. bulge is chased down to the bottom of the active submatrix. */
  390. ComplexScalar shift = computeShift(iu, iter);
  391. JacobiRotation<ComplexScalar> rot;
  392. rot.makeGivens(m_matT.coeff(il,il) - shift, m_matT.coeff(il+1,il));
  393. m_matT.rightCols(m_matT.cols()-il).applyOnTheLeft(il, il+1, rot.adjoint());
  394. m_matT.topRows((std::min)(il+2,iu)+1).applyOnTheRight(il, il+1, rot);
  395. if(computeU) m_matU.applyOnTheRight(il, il+1, rot);
  396. for(Index i=il+1 ; i<iu ; i++)
  397. {
  398. rot.makeGivens(m_matT.coeffRef(i,i-1), m_matT.coeffRef(i+1,i-1), &m_matT.coeffRef(i,i-1));
  399. m_matT.coeffRef(i+1,i-1) = ComplexScalar(0);
  400. m_matT.rightCols(m_matT.cols()-i).applyOnTheLeft(i, i+1, rot.adjoint());
  401. m_matT.topRows((std::min)(i+2,iu)+1).applyOnTheRight(i, i+1, rot);
  402. if(computeU) m_matU.applyOnTheRight(i, i+1, rot);
  403. }
  404. }
  405. if(totalIter <= maxIters)
  406. m_info = Success;
  407. else
  408. m_info = NoConvergence;
  409. m_isInitialized = true;
  410. m_matUisUptodate = computeU;
  411. }
  412. } // end namespace Eigen
  413. #endif // EIGEN_COMPLEX_SCHUR_H