xref: /aosp_15_r20/external/eigen/Eigen/src/Eigenvalues/RealSchur.h (revision bf2c37156dfe67e5dfebd6d394bad8b2ab5804d4)
1*bf2c3715SXin Li // This file is part of Eigen, a lightweight C++ template library
2*bf2c3715SXin Li // for linear algebra.
3*bf2c3715SXin Li //
4*bf2c3715SXin Li // Copyright (C) 2008 Gael Guennebaud <[email protected]>
5*bf2c3715SXin Li // Copyright (C) 2010,2012 Jitse Niesen <[email protected]>
6*bf2c3715SXin Li //
7*bf2c3715SXin Li // This Source Code Form is subject to the terms of the Mozilla
8*bf2c3715SXin Li // Public License v. 2.0. If a copy of the MPL was not distributed
9*bf2c3715SXin Li // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
10*bf2c3715SXin Li 
11*bf2c3715SXin Li #ifndef EIGEN_REAL_SCHUR_H
12*bf2c3715SXin Li #define EIGEN_REAL_SCHUR_H
13*bf2c3715SXin Li 
14*bf2c3715SXin Li #include "./HessenbergDecomposition.h"
15*bf2c3715SXin Li 
16*bf2c3715SXin Li namespace Eigen {
17*bf2c3715SXin Li 
18*bf2c3715SXin Li /** \eigenvalues_module \ingroup Eigenvalues_Module
19*bf2c3715SXin Li   *
20*bf2c3715SXin Li   *
21*bf2c3715SXin Li   * \class RealSchur
22*bf2c3715SXin Li   *
23*bf2c3715SXin Li   * \brief Performs a real Schur decomposition of a square matrix
24*bf2c3715SXin Li   *
25*bf2c3715SXin Li   * \tparam _MatrixType the type of the matrix of which we are computing the
26*bf2c3715SXin Li   * real Schur decomposition; this is expected to be an instantiation of the
27*bf2c3715SXin Li   * Matrix class template.
28*bf2c3715SXin Li   *
29*bf2c3715SXin Li   * Given a real square matrix A, this class computes the real Schur
30*bf2c3715SXin Li   * decomposition: \f$ A = U T U^T \f$ where U is a real orthogonal matrix and
31*bf2c3715SXin Li   * T is a real quasi-triangular matrix. An orthogonal matrix is a matrix whose
32*bf2c3715SXin Li   * inverse is equal to its transpose, \f$ U^{-1} = U^T \f$. A quasi-triangular
33*bf2c3715SXin Li   * matrix is a block-triangular matrix whose diagonal consists of 1-by-1
34*bf2c3715SXin Li   * blocks and 2-by-2 blocks with complex eigenvalues. The eigenvalues of the
35*bf2c3715SXin Li   * blocks on the diagonal of T are the same as the eigenvalues of the matrix
36*bf2c3715SXin Li   * A, and thus the real Schur decomposition is used in EigenSolver to compute
37*bf2c3715SXin Li   * the eigendecomposition of a matrix.
38*bf2c3715SXin Li   *
39*bf2c3715SXin Li   * Call the function compute() to compute the real Schur decomposition of a
40*bf2c3715SXin Li   * given matrix. Alternatively, you can use the RealSchur(const MatrixType&, bool)
41*bf2c3715SXin Li   * constructor which computes the real Schur decomposition at construction
42*bf2c3715SXin Li   * time. Once the decomposition is computed, you can use the matrixU() and
43*bf2c3715SXin Li   * matrixT() functions to retrieve the matrices U and T in the decomposition.
44*bf2c3715SXin Li   *
45*bf2c3715SXin Li   * The documentation of RealSchur(const MatrixType&, bool) contains an example
46*bf2c3715SXin Li   * of the typical use of this class.
47*bf2c3715SXin Li   *
48*bf2c3715SXin Li   * \note The implementation is adapted from
49*bf2c3715SXin Li   * <a href="http://math.nist.gov/javanumerics/jama/">JAMA</a> (public domain).
50*bf2c3715SXin Li   * Their code is based on EISPACK.
51*bf2c3715SXin Li   *
52*bf2c3715SXin Li   * \sa class ComplexSchur, class EigenSolver, class ComplexEigenSolver
53*bf2c3715SXin Li   */
54*bf2c3715SXin Li template<typename _MatrixType> class RealSchur
55*bf2c3715SXin Li {
56*bf2c3715SXin Li   public:
57*bf2c3715SXin Li     typedef _MatrixType MatrixType;
58*bf2c3715SXin Li     enum {
59*bf2c3715SXin Li       RowsAtCompileTime = MatrixType::RowsAtCompileTime,
60*bf2c3715SXin Li       ColsAtCompileTime = MatrixType::ColsAtCompileTime,
61*bf2c3715SXin Li       Options = MatrixType::Options,
62*bf2c3715SXin Li       MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
63*bf2c3715SXin Li       MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime
64*bf2c3715SXin Li     };
65*bf2c3715SXin Li     typedef typename MatrixType::Scalar Scalar;
66*bf2c3715SXin Li     typedef std::complex<typename NumTraits<Scalar>::Real> ComplexScalar;
67*bf2c3715SXin Li     typedef Eigen::Index Index; ///< \deprecated since Eigen 3.3
68*bf2c3715SXin Li 
69*bf2c3715SXin Li     typedef Matrix<ComplexScalar, ColsAtCompileTime, 1, Options & ~RowMajor, MaxColsAtCompileTime, 1> EigenvalueType;
70*bf2c3715SXin Li     typedef Matrix<Scalar, ColsAtCompileTime, 1, Options & ~RowMajor, MaxColsAtCompileTime, 1> ColumnVectorType;
71*bf2c3715SXin Li 
72*bf2c3715SXin Li     /** \brief Default constructor.
73*bf2c3715SXin Li       *
74*bf2c3715SXin Li       * \param [in] size  Positive integer, size of the matrix whose Schur decomposition will be computed.
75*bf2c3715SXin Li       *
76*bf2c3715SXin Li       * The default constructor is useful in cases in which the user intends to
77*bf2c3715SXin Li       * perform decompositions via compute().  The \p size parameter is only
78*bf2c3715SXin Li       * used as a hint. It is not an error to give a wrong \p size, but it may
79*bf2c3715SXin Li       * impair performance.
80*bf2c3715SXin Li       *
81*bf2c3715SXin Li       * \sa compute() for an example.
82*bf2c3715SXin Li       */
83*bf2c3715SXin Li     explicit RealSchur(Index size = RowsAtCompileTime==Dynamic ? 1 : RowsAtCompileTime)
m_matT(size,size)84*bf2c3715SXin Li             : m_matT(size, size),
85*bf2c3715SXin Li               m_matU(size, size),
86*bf2c3715SXin Li               m_workspaceVector(size),
87*bf2c3715SXin Li               m_hess(size),
88*bf2c3715SXin Li               m_isInitialized(false),
89*bf2c3715SXin Li               m_matUisUptodate(false),
90*bf2c3715SXin Li               m_maxIters(-1)
91*bf2c3715SXin Li     { }
92*bf2c3715SXin Li 
93*bf2c3715SXin Li     /** \brief Constructor; computes real Schur decomposition of given matrix.
94*bf2c3715SXin Li       *
95*bf2c3715SXin Li       * \param[in]  matrix    Square matrix whose Schur decomposition is to be computed.
96*bf2c3715SXin Li       * \param[in]  computeU  If true, both T and U are computed; if false, only T is computed.
97*bf2c3715SXin Li       *
98*bf2c3715SXin Li       * This constructor calls compute() to compute the Schur decomposition.
99*bf2c3715SXin Li       *
100*bf2c3715SXin Li       * Example: \include RealSchur_RealSchur_MatrixType.cpp
101*bf2c3715SXin Li       * Output: \verbinclude RealSchur_RealSchur_MatrixType.out
102*bf2c3715SXin Li       */
103*bf2c3715SXin Li     template<typename InputType>
104*bf2c3715SXin Li     explicit RealSchur(const EigenBase<InputType>& matrix, bool computeU = true)
105*bf2c3715SXin Li             : m_matT(matrix.rows(),matrix.cols()),
106*bf2c3715SXin Li               m_matU(matrix.rows(),matrix.cols()),
107*bf2c3715SXin Li               m_workspaceVector(matrix.rows()),
108*bf2c3715SXin Li               m_hess(matrix.rows()),
109*bf2c3715SXin Li               m_isInitialized(false),
110*bf2c3715SXin Li               m_matUisUptodate(false),
111*bf2c3715SXin Li               m_maxIters(-1)
112*bf2c3715SXin Li     {
113*bf2c3715SXin Li       compute(matrix.derived(), computeU);
114*bf2c3715SXin Li     }
115*bf2c3715SXin Li 
116*bf2c3715SXin Li     /** \brief Returns the orthogonal matrix in the Schur decomposition.
117*bf2c3715SXin Li       *
118*bf2c3715SXin Li       * \returns A const reference to the matrix U.
119*bf2c3715SXin Li       *
120*bf2c3715SXin Li       * \pre Either the constructor RealSchur(const MatrixType&, bool) or the
121*bf2c3715SXin Li       * member function compute(const MatrixType&, bool) has been called before
122*bf2c3715SXin Li       * to compute the Schur decomposition of a matrix, and \p computeU was set
123*bf2c3715SXin Li       * to true (the default value).
124*bf2c3715SXin Li       *
125*bf2c3715SXin Li       * \sa RealSchur(const MatrixType&, bool) for an example
126*bf2c3715SXin Li       */
matrixU()127*bf2c3715SXin Li     const MatrixType& matrixU() const
128*bf2c3715SXin Li     {
129*bf2c3715SXin Li       eigen_assert(m_isInitialized && "RealSchur is not initialized.");
130*bf2c3715SXin Li       eigen_assert(m_matUisUptodate && "The matrix U has not been computed during the RealSchur decomposition.");
131*bf2c3715SXin Li       return m_matU;
132*bf2c3715SXin Li     }
133*bf2c3715SXin Li 
134*bf2c3715SXin Li     /** \brief Returns the quasi-triangular matrix in the Schur decomposition.
135*bf2c3715SXin Li       *
136*bf2c3715SXin Li       * \returns A const reference to the matrix T.
137*bf2c3715SXin Li       *
138*bf2c3715SXin Li       * \pre Either the constructor RealSchur(const MatrixType&, bool) or the
139*bf2c3715SXin Li       * member function compute(const MatrixType&, bool) has been called before
140*bf2c3715SXin Li       * to compute the Schur decomposition of a matrix.
141*bf2c3715SXin Li       *
142*bf2c3715SXin Li       * \sa RealSchur(const MatrixType&, bool) for an example
143*bf2c3715SXin Li       */
matrixT()144*bf2c3715SXin Li     const MatrixType& matrixT() const
145*bf2c3715SXin Li     {
146*bf2c3715SXin Li       eigen_assert(m_isInitialized && "RealSchur is not initialized.");
147*bf2c3715SXin Li       return m_matT;
148*bf2c3715SXin Li     }
149*bf2c3715SXin Li 
150*bf2c3715SXin Li     /** \brief Computes Schur decomposition of given matrix.
151*bf2c3715SXin Li       *
152*bf2c3715SXin Li       * \param[in]  matrix    Square matrix whose Schur decomposition is to be computed.
153*bf2c3715SXin Li       * \param[in]  computeU  If true, both T and U are computed; if false, only T is computed.
154*bf2c3715SXin Li       * \returns    Reference to \c *this
155*bf2c3715SXin Li       *
156*bf2c3715SXin Li       * The Schur decomposition is computed by first reducing the matrix to
157*bf2c3715SXin Li       * Hessenberg form using the class HessenbergDecomposition. The Hessenberg
158*bf2c3715SXin Li       * matrix is then reduced to triangular form by performing Francis QR
159*bf2c3715SXin Li       * iterations with implicit double shift. The cost of computing the Schur
160*bf2c3715SXin Li       * decomposition depends on the number of iterations; as a rough guide, it
161*bf2c3715SXin Li       * may be taken to be \f$25n^3\f$ flops if \a computeU is true and
162*bf2c3715SXin Li       * \f$10n^3\f$ flops if \a computeU is false.
163*bf2c3715SXin Li       *
164*bf2c3715SXin Li       * Example: \include RealSchur_compute.cpp
165*bf2c3715SXin Li       * Output: \verbinclude RealSchur_compute.out
166*bf2c3715SXin Li       *
167*bf2c3715SXin Li       * \sa compute(const MatrixType&, bool, Index)
168*bf2c3715SXin Li       */
169*bf2c3715SXin Li     template<typename InputType>
170*bf2c3715SXin Li     RealSchur& compute(const EigenBase<InputType>& matrix, bool computeU = true);
171*bf2c3715SXin Li 
172*bf2c3715SXin Li     /** \brief Computes Schur decomposition of a Hessenberg matrix H = Z T Z^T
173*bf2c3715SXin Li      *  \param[in] matrixH Matrix in Hessenberg form H
174*bf2c3715SXin Li      *  \param[in] matrixQ orthogonal matrix Q that transform a matrix A to H : A = Q H Q^T
175*bf2c3715SXin Li      *  \param computeU Computes the matriX U of the Schur vectors
176*bf2c3715SXin Li      * \return Reference to \c *this
177*bf2c3715SXin Li      *
178*bf2c3715SXin Li      *  This routine assumes that the matrix is already reduced in Hessenberg form matrixH
179*bf2c3715SXin Li      *  using either the class HessenbergDecomposition or another mean.
180*bf2c3715SXin Li      *  It computes the upper quasi-triangular matrix T of the Schur decomposition of H
181*bf2c3715SXin Li      *  When computeU is true, this routine computes the matrix U such that
182*bf2c3715SXin Li      *  A = U T U^T =  (QZ) T (QZ)^T = Q H Q^T where A is the initial matrix
183*bf2c3715SXin Li      *
184*bf2c3715SXin Li      * NOTE Q is referenced if computeU is true; so, if the initial orthogonal matrix
185*bf2c3715SXin Li      * is not available, the user should give an identity matrix (Q.setIdentity())
186*bf2c3715SXin Li      *
187*bf2c3715SXin Li      * \sa compute(const MatrixType&, bool)
188*bf2c3715SXin Li      */
189*bf2c3715SXin Li     template<typename HessMatrixType, typename OrthMatrixType>
190*bf2c3715SXin Li     RealSchur& computeFromHessenberg(const HessMatrixType& matrixH, const OrthMatrixType& matrixQ,  bool computeU);
191*bf2c3715SXin Li     /** \brief Reports whether previous computation was successful.
192*bf2c3715SXin Li       *
193*bf2c3715SXin Li       * \returns \c Success if computation was successful, \c NoConvergence otherwise.
194*bf2c3715SXin Li       */
info()195*bf2c3715SXin Li     ComputationInfo info() const
196*bf2c3715SXin Li     {
197*bf2c3715SXin Li       eigen_assert(m_isInitialized && "RealSchur is not initialized.");
198*bf2c3715SXin Li       return m_info;
199*bf2c3715SXin Li     }
200*bf2c3715SXin Li 
201*bf2c3715SXin Li     /** \brief Sets the maximum number of iterations allowed.
202*bf2c3715SXin Li       *
203*bf2c3715SXin Li       * If not specified by the user, the maximum number of iterations is m_maxIterationsPerRow times the size
204*bf2c3715SXin Li       * of the matrix.
205*bf2c3715SXin Li       */
setMaxIterations(Index maxIters)206*bf2c3715SXin Li     RealSchur& setMaxIterations(Index maxIters)
207*bf2c3715SXin Li     {
208*bf2c3715SXin Li       m_maxIters = maxIters;
209*bf2c3715SXin Li       return *this;
210*bf2c3715SXin Li     }
211*bf2c3715SXin Li 
212*bf2c3715SXin Li     /** \brief Returns the maximum number of iterations. */
getMaxIterations()213*bf2c3715SXin Li     Index getMaxIterations()
214*bf2c3715SXin Li     {
215*bf2c3715SXin Li       return m_maxIters;
216*bf2c3715SXin Li     }
217*bf2c3715SXin Li 
218*bf2c3715SXin Li     /** \brief Maximum number of iterations per row.
219*bf2c3715SXin Li       *
220*bf2c3715SXin Li       * If not otherwise specified, the maximum number of iterations is this number times the size of the
221*bf2c3715SXin Li       * matrix. It is currently set to 40.
222*bf2c3715SXin Li       */
223*bf2c3715SXin Li     static const int m_maxIterationsPerRow = 40;
224*bf2c3715SXin Li 
225*bf2c3715SXin Li   private:
226*bf2c3715SXin Li 
227*bf2c3715SXin Li     MatrixType m_matT;
228*bf2c3715SXin Li     MatrixType m_matU;
229*bf2c3715SXin Li     ColumnVectorType m_workspaceVector;
230*bf2c3715SXin Li     HessenbergDecomposition<MatrixType> m_hess;
231*bf2c3715SXin Li     ComputationInfo m_info;
232*bf2c3715SXin Li     bool m_isInitialized;
233*bf2c3715SXin Li     bool m_matUisUptodate;
234*bf2c3715SXin Li     Index m_maxIters;
235*bf2c3715SXin Li 
236*bf2c3715SXin Li     typedef Matrix<Scalar,3,1> Vector3s;
237*bf2c3715SXin Li 
238*bf2c3715SXin Li     Scalar computeNormOfT();
239*bf2c3715SXin Li     Index findSmallSubdiagEntry(Index iu, const Scalar& considerAsZero);
240*bf2c3715SXin Li     void splitOffTwoRows(Index iu, bool computeU, const Scalar& exshift);
241*bf2c3715SXin Li     void computeShift(Index iu, Index iter, Scalar& exshift, Vector3s& shiftInfo);
242*bf2c3715SXin Li     void initFrancisQRStep(Index il, Index iu, const Vector3s& shiftInfo, Index& im, Vector3s& firstHouseholderVector);
243*bf2c3715SXin Li     void performFrancisQRStep(Index il, Index im, Index iu, bool computeU, const Vector3s& firstHouseholderVector, Scalar* workspace);
244*bf2c3715SXin Li };
245*bf2c3715SXin Li 
246*bf2c3715SXin Li 
247*bf2c3715SXin Li template<typename MatrixType>
248*bf2c3715SXin Li template<typename InputType>
compute(const EigenBase<InputType> & matrix,bool computeU)249*bf2c3715SXin Li RealSchur<MatrixType>& RealSchur<MatrixType>::compute(const EigenBase<InputType>& matrix, bool computeU)
250*bf2c3715SXin Li {
251*bf2c3715SXin Li   const Scalar considerAsZero = (std::numeric_limits<Scalar>::min)();
252*bf2c3715SXin Li 
253*bf2c3715SXin Li   eigen_assert(matrix.cols() == matrix.rows());
254*bf2c3715SXin Li   Index maxIters = m_maxIters;
255*bf2c3715SXin Li   if (maxIters == -1)
256*bf2c3715SXin Li     maxIters = m_maxIterationsPerRow * matrix.rows();
257*bf2c3715SXin Li 
258*bf2c3715SXin Li   Scalar scale = matrix.derived().cwiseAbs().maxCoeff();
259*bf2c3715SXin Li   if(scale<considerAsZero)
260*bf2c3715SXin Li   {
261*bf2c3715SXin Li     m_matT.setZero(matrix.rows(),matrix.cols());
262*bf2c3715SXin Li     if(computeU)
263*bf2c3715SXin Li       m_matU.setIdentity(matrix.rows(),matrix.cols());
264*bf2c3715SXin Li     m_info = Success;
265*bf2c3715SXin Li     m_isInitialized = true;
266*bf2c3715SXin Li     m_matUisUptodate = computeU;
267*bf2c3715SXin Li     return *this;
268*bf2c3715SXin Li   }
269*bf2c3715SXin Li 
270*bf2c3715SXin Li   // Step 1. Reduce to Hessenberg form
271*bf2c3715SXin Li   m_hess.compute(matrix.derived()/scale);
272*bf2c3715SXin Li 
273*bf2c3715SXin Li   // Step 2. Reduce to real Schur form
274*bf2c3715SXin Li   // Note: we copy m_hess.matrixQ() into m_matU here and not in computeFromHessenberg
275*bf2c3715SXin Li   //       to be able to pass our working-space buffer for the Householder to Dense evaluation.
276*bf2c3715SXin Li   m_workspaceVector.resize(matrix.cols());
277*bf2c3715SXin Li   if(computeU)
278*bf2c3715SXin Li     m_hess.matrixQ().evalTo(m_matU, m_workspaceVector);
279*bf2c3715SXin Li   computeFromHessenberg(m_hess.matrixH(), m_matU, computeU);
280*bf2c3715SXin Li 
281*bf2c3715SXin Li   m_matT *= scale;
282*bf2c3715SXin Li 
283*bf2c3715SXin Li   return *this;
284*bf2c3715SXin Li }
285*bf2c3715SXin Li template<typename MatrixType>
286*bf2c3715SXin Li template<typename HessMatrixType, typename OrthMatrixType>
computeFromHessenberg(const HessMatrixType & matrixH,const OrthMatrixType & matrixQ,bool computeU)287*bf2c3715SXin Li RealSchur<MatrixType>& RealSchur<MatrixType>::computeFromHessenberg(const HessMatrixType& matrixH, const OrthMatrixType& matrixQ,  bool computeU)
288*bf2c3715SXin Li {
289*bf2c3715SXin Li   using std::abs;
290*bf2c3715SXin Li 
291*bf2c3715SXin Li   m_matT = matrixH;
292*bf2c3715SXin Li   m_workspaceVector.resize(m_matT.cols());
293*bf2c3715SXin Li   if(computeU && !internal::is_same_dense(m_matU,matrixQ))
294*bf2c3715SXin Li     m_matU = matrixQ;
295*bf2c3715SXin Li 
296*bf2c3715SXin Li   Index maxIters = m_maxIters;
297*bf2c3715SXin Li   if (maxIters == -1)
298*bf2c3715SXin Li     maxIters = m_maxIterationsPerRow * matrixH.rows();
299*bf2c3715SXin Li   Scalar* workspace = &m_workspaceVector.coeffRef(0);
300*bf2c3715SXin Li 
301*bf2c3715SXin Li   // The matrix m_matT is divided in three parts.
302*bf2c3715SXin Li   // Rows 0,...,il-1 are decoupled from the rest because m_matT(il,il-1) is zero.
303*bf2c3715SXin Li   // Rows il,...,iu is the part we are working on (the active window).
304*bf2c3715SXin Li   // Rows iu+1,...,end are already brought in triangular form.
305*bf2c3715SXin Li   Index iu = m_matT.cols() - 1;
306*bf2c3715SXin Li   Index iter = 0;      // iteration count for current eigenvalue
307*bf2c3715SXin Li   Index totalIter = 0; // iteration count for whole matrix
308*bf2c3715SXin Li   Scalar exshift(0);   // sum of exceptional shifts
309*bf2c3715SXin Li   Scalar norm = computeNormOfT();
310*bf2c3715SXin Li   // sub-diagonal entries smaller than considerAsZero will be treated as zero.
311*bf2c3715SXin Li   // We use eps^2 to enable more precision in small eigenvalues.
312*bf2c3715SXin Li   Scalar considerAsZero = numext::maxi<Scalar>( norm * numext::abs2(NumTraits<Scalar>::epsilon()),
313*bf2c3715SXin Li                                                 (std::numeric_limits<Scalar>::min)() );
314*bf2c3715SXin Li 
315*bf2c3715SXin Li   if(norm!=Scalar(0))
316*bf2c3715SXin Li   {
317*bf2c3715SXin Li     while (iu >= 0)
318*bf2c3715SXin Li     {
319*bf2c3715SXin Li       Index il = findSmallSubdiagEntry(iu,considerAsZero);
320*bf2c3715SXin Li 
321*bf2c3715SXin Li       // Check for convergence
322*bf2c3715SXin Li       if (il == iu) // One root found
323*bf2c3715SXin Li       {
324*bf2c3715SXin Li         m_matT.coeffRef(iu,iu) = m_matT.coeff(iu,iu) + exshift;
325*bf2c3715SXin Li         if (iu > 0)
326*bf2c3715SXin Li           m_matT.coeffRef(iu, iu-1) = Scalar(0);
327*bf2c3715SXin Li         iu--;
328*bf2c3715SXin Li         iter = 0;
329*bf2c3715SXin Li       }
330*bf2c3715SXin Li       else if (il == iu-1) // Two roots found
331*bf2c3715SXin Li       {
332*bf2c3715SXin Li         splitOffTwoRows(iu, computeU, exshift);
333*bf2c3715SXin Li         iu -= 2;
334*bf2c3715SXin Li         iter = 0;
335*bf2c3715SXin Li       }
336*bf2c3715SXin Li       else // No convergence yet
337*bf2c3715SXin Li       {
338*bf2c3715SXin Li         // The firstHouseholderVector vector has to be initialized to something to get rid of a silly GCC warning (-O1 -Wall -DNDEBUG )
339*bf2c3715SXin Li         Vector3s firstHouseholderVector = Vector3s::Zero(), shiftInfo;
340*bf2c3715SXin Li         computeShift(iu, iter, exshift, shiftInfo);
341*bf2c3715SXin Li         iter = iter + 1;
342*bf2c3715SXin Li         totalIter = totalIter + 1;
343*bf2c3715SXin Li         if (totalIter > maxIters) break;
344*bf2c3715SXin Li         Index im;
345*bf2c3715SXin Li         initFrancisQRStep(il, iu, shiftInfo, im, firstHouseholderVector);
346*bf2c3715SXin Li         performFrancisQRStep(il, im, iu, computeU, firstHouseholderVector, workspace);
347*bf2c3715SXin Li       }
348*bf2c3715SXin Li     }
349*bf2c3715SXin Li   }
350*bf2c3715SXin Li   if(totalIter <= maxIters)
351*bf2c3715SXin Li     m_info = Success;
352*bf2c3715SXin Li   else
353*bf2c3715SXin Li     m_info = NoConvergence;
354*bf2c3715SXin Li 
355*bf2c3715SXin Li   m_isInitialized = true;
356*bf2c3715SXin Li   m_matUisUptodate = computeU;
357*bf2c3715SXin Li   return *this;
358*bf2c3715SXin Li }
359*bf2c3715SXin Li 
360*bf2c3715SXin Li /** \internal Computes and returns vector L1 norm of T */
361*bf2c3715SXin Li template<typename MatrixType>
computeNormOfT()362*bf2c3715SXin Li inline typename MatrixType::Scalar RealSchur<MatrixType>::computeNormOfT()
363*bf2c3715SXin Li {
364*bf2c3715SXin Li   const Index size = m_matT.cols();
365*bf2c3715SXin Li   // FIXME to be efficient the following would requires a triangular reduxion code
366*bf2c3715SXin Li   // Scalar norm = m_matT.upper().cwiseAbs().sum()
367*bf2c3715SXin Li   //               + m_matT.bottomLeftCorner(size-1,size-1).diagonal().cwiseAbs().sum();
368*bf2c3715SXin Li   Scalar norm(0);
369*bf2c3715SXin Li   for (Index j = 0; j < size; ++j)
370*bf2c3715SXin Li     norm += m_matT.col(j).segment(0, (std::min)(size,j+2)).cwiseAbs().sum();
371*bf2c3715SXin Li   return norm;
372*bf2c3715SXin Li }
373*bf2c3715SXin Li 
374*bf2c3715SXin Li /** \internal Look for single small sub-diagonal element and returns its index */
375*bf2c3715SXin Li template<typename MatrixType>
findSmallSubdiagEntry(Index iu,const Scalar & considerAsZero)376*bf2c3715SXin Li inline Index RealSchur<MatrixType>::findSmallSubdiagEntry(Index iu, const Scalar& considerAsZero)
377*bf2c3715SXin Li {
378*bf2c3715SXin Li   using std::abs;
379*bf2c3715SXin Li   Index res = iu;
380*bf2c3715SXin Li   while (res > 0)
381*bf2c3715SXin Li   {
382*bf2c3715SXin Li     Scalar s = abs(m_matT.coeff(res-1,res-1)) + abs(m_matT.coeff(res,res));
383*bf2c3715SXin Li 
384*bf2c3715SXin Li     s = numext::maxi<Scalar>(s * NumTraits<Scalar>::epsilon(), considerAsZero);
385*bf2c3715SXin Li 
386*bf2c3715SXin Li     if (abs(m_matT.coeff(res,res-1)) <= s)
387*bf2c3715SXin Li       break;
388*bf2c3715SXin Li     res--;
389*bf2c3715SXin Li   }
390*bf2c3715SXin Li   return res;
391*bf2c3715SXin Li }
392*bf2c3715SXin Li 
393*bf2c3715SXin Li /** \internal Update T given that rows iu-1 and iu decouple from the rest. */
394*bf2c3715SXin Li template<typename MatrixType>
splitOffTwoRows(Index iu,bool computeU,const Scalar & exshift)395*bf2c3715SXin Li inline void RealSchur<MatrixType>::splitOffTwoRows(Index iu, bool computeU, const Scalar& exshift)
396*bf2c3715SXin Li {
397*bf2c3715SXin Li   using std::sqrt;
398*bf2c3715SXin Li   using std::abs;
399*bf2c3715SXin Li   const Index size = m_matT.cols();
400*bf2c3715SXin Li 
401*bf2c3715SXin Li   // The eigenvalues of the 2x2 matrix [a b; c d] are
402*bf2c3715SXin Li   // trace +/- sqrt(discr/4) where discr = tr^2 - 4*det, tr = a + d, det = ad - bc
403*bf2c3715SXin Li   Scalar p = Scalar(0.5) * (m_matT.coeff(iu-1,iu-1) - m_matT.coeff(iu,iu));
404*bf2c3715SXin Li   Scalar q = p * p + m_matT.coeff(iu,iu-1) * m_matT.coeff(iu-1,iu);   // q = tr^2 / 4 - det = discr/4
405*bf2c3715SXin Li   m_matT.coeffRef(iu,iu) += exshift;
406*bf2c3715SXin Li   m_matT.coeffRef(iu-1,iu-1) += exshift;
407*bf2c3715SXin Li 
408*bf2c3715SXin Li   if (q >= Scalar(0)) // Two real eigenvalues
409*bf2c3715SXin Li   {
410*bf2c3715SXin Li     Scalar z = sqrt(abs(q));
411*bf2c3715SXin Li     JacobiRotation<Scalar> rot;
412*bf2c3715SXin Li     if (p >= Scalar(0))
413*bf2c3715SXin Li       rot.makeGivens(p + z, m_matT.coeff(iu, iu-1));
414*bf2c3715SXin Li     else
415*bf2c3715SXin Li       rot.makeGivens(p - z, m_matT.coeff(iu, iu-1));
416*bf2c3715SXin Li 
417*bf2c3715SXin Li     m_matT.rightCols(size-iu+1).applyOnTheLeft(iu-1, iu, rot.adjoint());
418*bf2c3715SXin Li     m_matT.topRows(iu+1).applyOnTheRight(iu-1, iu, rot);
419*bf2c3715SXin Li     m_matT.coeffRef(iu, iu-1) = Scalar(0);
420*bf2c3715SXin Li     if (computeU)
421*bf2c3715SXin Li       m_matU.applyOnTheRight(iu-1, iu, rot);
422*bf2c3715SXin Li   }
423*bf2c3715SXin Li 
424*bf2c3715SXin Li   if (iu > 1)
425*bf2c3715SXin Li     m_matT.coeffRef(iu-1, iu-2) = Scalar(0);
426*bf2c3715SXin Li }
427*bf2c3715SXin Li 
428*bf2c3715SXin Li /** \internal Form shift in shiftInfo, and update exshift if an exceptional shift is performed. */
429*bf2c3715SXin Li template<typename MatrixType>
computeShift(Index iu,Index iter,Scalar & exshift,Vector3s & shiftInfo)430*bf2c3715SXin Li inline void RealSchur<MatrixType>::computeShift(Index iu, Index iter, Scalar& exshift, Vector3s& shiftInfo)
431*bf2c3715SXin Li {
432*bf2c3715SXin Li   using std::sqrt;
433*bf2c3715SXin Li   using std::abs;
434*bf2c3715SXin Li   shiftInfo.coeffRef(0) = m_matT.coeff(iu,iu);
435*bf2c3715SXin Li   shiftInfo.coeffRef(1) = m_matT.coeff(iu-1,iu-1);
436*bf2c3715SXin Li   shiftInfo.coeffRef(2) = m_matT.coeff(iu,iu-1) * m_matT.coeff(iu-1,iu);
437*bf2c3715SXin Li 
438*bf2c3715SXin Li   // Wilkinson's original ad hoc shift
439*bf2c3715SXin Li   if (iter == 10)
440*bf2c3715SXin Li   {
441*bf2c3715SXin Li     exshift += shiftInfo.coeff(0);
442*bf2c3715SXin Li     for (Index i = 0; i <= iu; ++i)
443*bf2c3715SXin Li       m_matT.coeffRef(i,i) -= shiftInfo.coeff(0);
444*bf2c3715SXin Li     Scalar s = abs(m_matT.coeff(iu,iu-1)) + abs(m_matT.coeff(iu-1,iu-2));
445*bf2c3715SXin Li     shiftInfo.coeffRef(0) = Scalar(0.75) * s;
446*bf2c3715SXin Li     shiftInfo.coeffRef(1) = Scalar(0.75) * s;
447*bf2c3715SXin Li     shiftInfo.coeffRef(2) = Scalar(-0.4375) * s * s;
448*bf2c3715SXin Li   }
449*bf2c3715SXin Li 
450*bf2c3715SXin Li   // MATLAB's new ad hoc shift
451*bf2c3715SXin Li   if (iter == 30)
452*bf2c3715SXin Li   {
453*bf2c3715SXin Li     Scalar s = (shiftInfo.coeff(1) - shiftInfo.coeff(0)) / Scalar(2.0);
454*bf2c3715SXin Li     s = s * s + shiftInfo.coeff(2);
455*bf2c3715SXin Li     if (s > Scalar(0))
456*bf2c3715SXin Li     {
457*bf2c3715SXin Li       s = sqrt(s);
458*bf2c3715SXin Li       if (shiftInfo.coeff(1) < shiftInfo.coeff(0))
459*bf2c3715SXin Li         s = -s;
460*bf2c3715SXin Li       s = s + (shiftInfo.coeff(1) - shiftInfo.coeff(0)) / Scalar(2.0);
461*bf2c3715SXin Li       s = shiftInfo.coeff(0) - shiftInfo.coeff(2) / s;
462*bf2c3715SXin Li       exshift += s;
463*bf2c3715SXin Li       for (Index i = 0; i <= iu; ++i)
464*bf2c3715SXin Li         m_matT.coeffRef(i,i) -= s;
465*bf2c3715SXin Li       shiftInfo.setConstant(Scalar(0.964));
466*bf2c3715SXin Li     }
467*bf2c3715SXin Li   }
468*bf2c3715SXin Li }
469*bf2c3715SXin Li 
470*bf2c3715SXin Li /** \internal Compute index im at which Francis QR step starts and the first Householder vector. */
471*bf2c3715SXin Li template<typename MatrixType>
initFrancisQRStep(Index il,Index iu,const Vector3s & shiftInfo,Index & im,Vector3s & firstHouseholderVector)472*bf2c3715SXin Li inline void RealSchur<MatrixType>::initFrancisQRStep(Index il, Index iu, const Vector3s& shiftInfo, Index& im, Vector3s& firstHouseholderVector)
473*bf2c3715SXin Li {
474*bf2c3715SXin Li   using std::abs;
475*bf2c3715SXin Li   Vector3s& v = firstHouseholderVector; // alias to save typing
476*bf2c3715SXin Li 
477*bf2c3715SXin Li   for (im = iu-2; im >= il; --im)
478*bf2c3715SXin Li   {
479*bf2c3715SXin Li     const Scalar Tmm = m_matT.coeff(im,im);
480*bf2c3715SXin Li     const Scalar r = shiftInfo.coeff(0) - Tmm;
481*bf2c3715SXin Li     const Scalar s = shiftInfo.coeff(1) - Tmm;
482*bf2c3715SXin Li     v.coeffRef(0) = (r * s - shiftInfo.coeff(2)) / m_matT.coeff(im+1,im) + m_matT.coeff(im,im+1);
483*bf2c3715SXin Li     v.coeffRef(1) = m_matT.coeff(im+1,im+1) - Tmm - r - s;
484*bf2c3715SXin Li     v.coeffRef(2) = m_matT.coeff(im+2,im+1);
485*bf2c3715SXin Li     if (im == il) {
486*bf2c3715SXin Li       break;
487*bf2c3715SXin Li     }
488*bf2c3715SXin Li     const Scalar lhs = m_matT.coeff(im,im-1) * (abs(v.coeff(1)) + abs(v.coeff(2)));
489*bf2c3715SXin Li     const Scalar rhs = v.coeff(0) * (abs(m_matT.coeff(im-1,im-1)) + abs(Tmm) + abs(m_matT.coeff(im+1,im+1)));
490*bf2c3715SXin Li     if (abs(lhs) < NumTraits<Scalar>::epsilon() * rhs)
491*bf2c3715SXin Li       break;
492*bf2c3715SXin Li   }
493*bf2c3715SXin Li }
494*bf2c3715SXin Li 
495*bf2c3715SXin Li /** \internal Perform a Francis QR step involving rows il:iu and columns im:iu. */
496*bf2c3715SXin Li template<typename MatrixType>
performFrancisQRStep(Index il,Index im,Index iu,bool computeU,const Vector3s & firstHouseholderVector,Scalar * workspace)497*bf2c3715SXin Li inline void RealSchur<MatrixType>::performFrancisQRStep(Index il, Index im, Index iu, bool computeU, const Vector3s& firstHouseholderVector, Scalar* workspace)
498*bf2c3715SXin Li {
499*bf2c3715SXin Li   eigen_assert(im >= il);
500*bf2c3715SXin Li   eigen_assert(im <= iu-2);
501*bf2c3715SXin Li 
502*bf2c3715SXin Li   const Index size = m_matT.cols();
503*bf2c3715SXin Li 
504*bf2c3715SXin Li   for (Index k = im; k <= iu-2; ++k)
505*bf2c3715SXin Li   {
506*bf2c3715SXin Li     bool firstIteration = (k == im);
507*bf2c3715SXin Li 
508*bf2c3715SXin Li     Vector3s v;
509*bf2c3715SXin Li     if (firstIteration)
510*bf2c3715SXin Li       v = firstHouseholderVector;
511*bf2c3715SXin Li     else
512*bf2c3715SXin Li       v = m_matT.template block<3,1>(k,k-1);
513*bf2c3715SXin Li 
514*bf2c3715SXin Li     Scalar tau, beta;
515*bf2c3715SXin Li     Matrix<Scalar, 2, 1> ess;
516*bf2c3715SXin Li     v.makeHouseholder(ess, tau, beta);
517*bf2c3715SXin Li 
518*bf2c3715SXin Li     if (beta != Scalar(0)) // if v is not zero
519*bf2c3715SXin Li     {
520*bf2c3715SXin Li       if (firstIteration && k > il)
521*bf2c3715SXin Li         m_matT.coeffRef(k,k-1) = -m_matT.coeff(k,k-1);
522*bf2c3715SXin Li       else if (!firstIteration)
523*bf2c3715SXin Li         m_matT.coeffRef(k,k-1) = beta;
524*bf2c3715SXin Li 
525*bf2c3715SXin Li       // These Householder transformations form the O(n^3) part of the algorithm
526*bf2c3715SXin Li       m_matT.block(k, k, 3, size-k).applyHouseholderOnTheLeft(ess, tau, workspace);
527*bf2c3715SXin Li       m_matT.block(0, k, (std::min)(iu,k+3) + 1, 3).applyHouseholderOnTheRight(ess, tau, workspace);
528*bf2c3715SXin Li       if (computeU)
529*bf2c3715SXin Li         m_matU.block(0, k, size, 3).applyHouseholderOnTheRight(ess, tau, workspace);
530*bf2c3715SXin Li     }
531*bf2c3715SXin Li   }
532*bf2c3715SXin Li 
533*bf2c3715SXin Li   Matrix<Scalar, 2, 1> v = m_matT.template block<2,1>(iu-1, iu-2);
534*bf2c3715SXin Li   Scalar tau, beta;
535*bf2c3715SXin Li   Matrix<Scalar, 1, 1> ess;
536*bf2c3715SXin Li   v.makeHouseholder(ess, tau, beta);
537*bf2c3715SXin Li 
538*bf2c3715SXin Li   if (beta != Scalar(0)) // if v is not zero
539*bf2c3715SXin Li   {
540*bf2c3715SXin Li     m_matT.coeffRef(iu-1, iu-2) = beta;
541*bf2c3715SXin Li     m_matT.block(iu-1, iu-1, 2, size-iu+1).applyHouseholderOnTheLeft(ess, tau, workspace);
542*bf2c3715SXin Li     m_matT.block(0, iu-1, iu+1, 2).applyHouseholderOnTheRight(ess, tau, workspace);
543*bf2c3715SXin Li     if (computeU)
544*bf2c3715SXin Li       m_matU.block(0, iu-1, size, 2).applyHouseholderOnTheRight(ess, tau, workspace);
545*bf2c3715SXin Li   }
546*bf2c3715SXin Li 
547*bf2c3715SXin Li   // clean up pollution due to round-off errors
548*bf2c3715SXin Li   for (Index i = im+2; i <= iu; ++i)
549*bf2c3715SXin Li   {
550*bf2c3715SXin Li     m_matT.coeffRef(i,i-2) = Scalar(0);
551*bf2c3715SXin Li     if (i > im+2)
552*bf2c3715SXin Li       m_matT.coeffRef(i,i-3) = Scalar(0);
553*bf2c3715SXin Li   }
554*bf2c3715SXin Li }
555*bf2c3715SXin Li 
556*bf2c3715SXin Li } // end namespace Eigen
557*bf2c3715SXin Li 
558*bf2c3715SXin Li #endif // EIGEN_REAL_SCHUR_H
559