LeastSquareConjugateGradient.h 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. // This file is part of Eigen, a lightweight C++ template library
  2. // for linear algebra.
  3. //
  4. // Copyright (C) 2015 Gael Guennebaud <gael.guennebaud@inria.fr>
  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_LEAST_SQUARE_CONJUGATE_GRADIENT_H
  10. #define EIGEN_LEAST_SQUARE_CONJUGATE_GRADIENT_H
  11. namespace Eigen {
  12. namespace internal {
  13. /** \internal Low-level conjugate gradient algorithm for least-square problems
  14. * \param mat The matrix A
  15. * \param rhs The right hand side vector b
  16. * \param x On input and initial solution, on output the computed solution.
  17. * \param precond A preconditioner being able to efficiently solve for an
  18. * approximation of A'Ax=b (regardless of b)
  19. * \param iters On input the max number of iteration, on output the number of performed iterations.
  20. * \param tol_error On input the tolerance error, on output an estimation of the relative error.
  21. */
  22. template<typename MatrixType, typename Rhs, typename Dest, typename Preconditioner>
  23. EIGEN_DONT_INLINE
  24. void least_square_conjugate_gradient(const MatrixType& mat, const Rhs& rhs, Dest& x,
  25. const Preconditioner& precond, Index& iters,
  26. typename Dest::RealScalar& tol_error)
  27. {
  28. using std::sqrt;
  29. using std::abs;
  30. typedef typename Dest::RealScalar RealScalar;
  31. typedef typename Dest::Scalar Scalar;
  32. typedef Matrix<Scalar,Dynamic,1> VectorType;
  33. RealScalar tol = tol_error;
  34. Index maxIters = iters;
  35. Index m = mat.rows(), n = mat.cols();
  36. VectorType residual = rhs - mat * x;
  37. VectorType normal_residual = mat.adjoint() * residual;
  38. RealScalar rhsNorm2 = (mat.adjoint()*rhs).squaredNorm();
  39. if(rhsNorm2 == 0)
  40. {
  41. x.setZero();
  42. iters = 0;
  43. tol_error = 0;
  44. return;
  45. }
  46. RealScalar threshold = tol*tol*rhsNorm2;
  47. RealScalar residualNorm2 = normal_residual.squaredNorm();
  48. if (residualNorm2 < threshold)
  49. {
  50. iters = 0;
  51. tol_error = sqrt(residualNorm2 / rhsNorm2);
  52. return;
  53. }
  54. VectorType p(n);
  55. p = precond.solve(normal_residual); // initial search direction
  56. VectorType z(n), tmp(m);
  57. RealScalar absNew = numext::real(normal_residual.dot(p)); // the square of the absolute value of r scaled by invM
  58. Index i = 0;
  59. while(i < maxIters)
  60. {
  61. tmp.noalias() = mat * p;
  62. Scalar alpha = absNew / tmp.squaredNorm(); // the amount we travel on dir
  63. x += alpha * p; // update solution
  64. residual -= alpha * tmp; // update residual
  65. normal_residual = mat.adjoint() * residual; // update residual of the normal equation
  66. residualNorm2 = normal_residual.squaredNorm();
  67. if(residualNorm2 < threshold)
  68. break;
  69. z = precond.solve(normal_residual); // approximately solve for "A'A z = normal_residual"
  70. RealScalar absOld = absNew;
  71. absNew = numext::real(normal_residual.dot(z)); // update the absolute value of r
  72. RealScalar beta = absNew / absOld; // calculate the Gram-Schmidt value used to create the new search direction
  73. p = z + beta * p; // update search direction
  74. i++;
  75. }
  76. tol_error = sqrt(residualNorm2 / rhsNorm2);
  77. iters = i;
  78. }
  79. }
  80. template< typename _MatrixType,
  81. typename _Preconditioner = LeastSquareDiagonalPreconditioner<typename _MatrixType::Scalar> >
  82. class LeastSquaresConjugateGradient;
  83. namespace internal {
  84. template< typename _MatrixType, typename _Preconditioner>
  85. struct traits<LeastSquaresConjugateGradient<_MatrixType,_Preconditioner> >
  86. {
  87. typedef _MatrixType MatrixType;
  88. typedef _Preconditioner Preconditioner;
  89. };
  90. }
  91. /** \ingroup IterativeLinearSolvers_Module
  92. * \brief A conjugate gradient solver for sparse (or dense) least-square problems
  93. *
  94. * This class allows to solve for A x = b linear problems using an iterative conjugate gradient algorithm.
  95. * The matrix A can be non symmetric and rectangular, but the matrix A' A should be positive-definite to guaranty stability.
  96. * Otherwise, the SparseLU or SparseQR classes might be preferable.
  97. * The matrix A and the vectors x and b can be either dense or sparse.
  98. *
  99. * \tparam _MatrixType the type of the matrix A, can be a dense or a sparse matrix.
  100. * \tparam _Preconditioner the type of the preconditioner. Default is LeastSquareDiagonalPreconditioner
  101. *
  102. * \implsparsesolverconcept
  103. *
  104. * The maximal number of iterations and tolerance value can be controlled via the setMaxIterations()
  105. * and setTolerance() methods. The defaults are the size of the problem for the maximal number of iterations
  106. * and NumTraits<Scalar>::epsilon() for the tolerance.
  107. *
  108. * This class can be used as the direct solver classes. Here is a typical usage example:
  109. \code
  110. int m=1000000, n = 10000;
  111. VectorXd x(n), b(m);
  112. SparseMatrix<double> A(m,n);
  113. // fill A and b
  114. LeastSquaresConjugateGradient<SparseMatrix<double> > lscg;
  115. lscg.compute(A);
  116. x = lscg.solve(b);
  117. std::cout << "#iterations: " << lscg.iterations() << std::endl;
  118. std::cout << "estimated error: " << lscg.error() << std::endl;
  119. // update b, and solve again
  120. x = lscg.solve(b);
  121. \endcode
  122. *
  123. * By default the iterations start with x=0 as an initial guess of the solution.
  124. * One can control the start using the solveWithGuess() method.
  125. *
  126. * \sa class ConjugateGradient, SparseLU, SparseQR
  127. */
  128. template< typename _MatrixType, typename _Preconditioner>
  129. class LeastSquaresConjugateGradient : public IterativeSolverBase<LeastSquaresConjugateGradient<_MatrixType,_Preconditioner> >
  130. {
  131. typedef IterativeSolverBase<LeastSquaresConjugateGradient> Base;
  132. using Base::matrix;
  133. using Base::m_error;
  134. using Base::m_iterations;
  135. using Base::m_info;
  136. using Base::m_isInitialized;
  137. public:
  138. typedef _MatrixType MatrixType;
  139. typedef typename MatrixType::Scalar Scalar;
  140. typedef typename MatrixType::RealScalar RealScalar;
  141. typedef _Preconditioner Preconditioner;
  142. public:
  143. /** Default constructor. */
  144. LeastSquaresConjugateGradient() : Base() {}
  145. /** Initialize the solver with matrix \a A for further \c Ax=b solving.
  146. *
  147. * This constructor is a shortcut for the default constructor followed
  148. * by a call to compute().
  149. *
  150. * \warning this class stores a reference to the matrix A as well as some
  151. * precomputed values that depend on it. Therefore, if \a A is changed
  152. * this class becomes invalid. Call compute() to update it with the new
  153. * matrix A, or modify a copy of A.
  154. */
  155. template<typename MatrixDerived>
  156. explicit LeastSquaresConjugateGradient(const EigenBase<MatrixDerived>& A) : Base(A.derived()) {}
  157. ~LeastSquaresConjugateGradient() {}
  158. /** \internal */
  159. template<typename Rhs,typename Dest>
  160. void _solve_vector_with_guess_impl(const Rhs& b, Dest& x) const
  161. {
  162. m_iterations = Base::maxIterations();
  163. m_error = Base::m_tolerance;
  164. internal::least_square_conjugate_gradient(matrix(), b, x, Base::m_preconditioner, m_iterations, m_error);
  165. m_info = m_error <= Base::m_tolerance ? Success : NoConvergence;
  166. }
  167. };
  168. } // end namespace Eigen
  169. #endif // EIGEN_LEAST_SQUARE_CONJUGATE_GRADIENT_H