DGMRES.h
Go to the documentation of this file.
1 // This file is part of Eigen, a lightweight C++ template library
2 // for linear algebra.
3 //
4 // Copyright (C) 2012 Désiré Nuentsa-Wakam <desire.nuentsa_wakam@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 
10 #ifndef EIGEN_DGMRES_H
11 #define EIGEN_DGMRES_H
12 
13 #include "../../../../Eigen/Eigenvalues"
14 
15 // IWYU pragma: private
16 #include "./InternalHeaderCheck.h"
17 
18 namespace Eigen {
19 
20 template <typename MatrixType_, typename Preconditioner_ = DiagonalPreconditioner<typename MatrixType_::Scalar> >
21 class DGMRES;
22 
23 namespace internal {
24 
25 template <typename MatrixType_, typename Preconditioner_>
26 struct traits<DGMRES<MatrixType_, Preconditioner_> > {
27  typedef MatrixType_ MatrixType;
28  typedef Preconditioner_ Preconditioner;
29 };
30 
39 template <typename VectorType, typename IndexType>
40 void sortWithPermutation(VectorType& vec, IndexType& perm, typename IndexType::Scalar& ncut) {
41  eigen_assert(vec.size() == perm.size());
42  bool flag;
43  for (Index k = 0; k < ncut; k++) {
44  flag = false;
45  for (Index j = 0; j < vec.size() - 1; j++) {
46  if (vec(perm(j)) < vec(perm(j + 1))) {
47  std::swap(perm(j), perm(j + 1));
48  flag = true;
49  }
50  if (!flag) break; // The vector is in sorted order
51  }
52  }
53 }
54 
55 } // namespace internal
97 template <typename MatrixType_, typename Preconditioner_>
98 class DGMRES : public IterativeSolverBase<DGMRES<MatrixType_, Preconditioner_> > {
100  using Base::m_error;
101  using Base::m_info;
102  using Base::m_isInitialized;
103  using Base::m_iterations;
104  using Base::m_tolerance;
105  using Base::matrix;
106 
107  public:
108  using Base::_solve_impl;
110  typedef MatrixType_ MatrixType;
111  typedef typename MatrixType::Scalar Scalar;
112  typedef typename MatrixType::StorageIndex StorageIndex;
114  typedef Preconditioner_ Preconditioner;
120 
123  : Base(), m_restart(30), m_neig(0), m_r(0), m_maxNeig(5), m_isDeflAllocated(false), m_isDeflInitialized(false) {}
124 
135  template <typename MatrixDerived>
137  : Base(A.derived()),
138  m_restart(30),
139  m_neig(0),
140  m_r(0),
141  m_maxNeig(5),
142  m_isDeflAllocated(false),
143  m_isDeflInitialized(false) {}
144 
145  ~DGMRES() {}
146 
148  template <typename Rhs, typename Dest>
149  void _solve_vector_with_guess_impl(const Rhs& b, Dest& x) const {
150  EIGEN_STATIC_ASSERT(Rhs::ColsAtCompileTime == 1 || Dest::ColsAtCompileTime == 1,
151  YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX);
152 
155 
157  }
158 
162  Index restart() { return m_restart; }
163 
168 
172  void setEigenv(const Index neig) {
173  m_neig = neig;
174  if (neig + 1 > m_maxNeig) m_maxNeig = neig + 1; // To allow for complex conjugates
175  }
176 
180  Index deflSize() { return m_r; }
181 
185  void setMaxEigenv(const Index maxNeig) { m_maxNeig = maxNeig; }
186 
187  protected:
188  // DGMRES algorithm
189  template <typename Rhs, typename Dest>
190  void dgmres(const MatrixType& mat, const Rhs& rhs, Dest& x, const Preconditioner& precond) const;
191  // Perform one cycle of GMRES
192  template <typename Dest>
193  Index dgmresCycle(const MatrixType& mat, const Preconditioner& precond, Dest& x, DenseVector& r0, RealScalar& beta,
194  const RealScalar& normRhs, Index& nbIts) const;
195  // Compute data to use for deflation
196  Index dgmresComputeDeflationData(const MatrixType& mat, const Preconditioner& precond, const Index& it,
197  StorageIndex& neig) const;
198  // Apply deflation to a vector
199  template <typename RhsType, typename DestType>
200  Index dgmresApplyDeflation(const RhsType& In, DestType& Out) const;
201  ComplexVector schurValues(const ComplexSchur<DenseMatrix>& schurofH) const;
202  ComplexVector schurValues(const RealSchur<DenseMatrix>& schurofH) const;
203  // Init data for deflation
204  void dgmresInitDeflation(Index& rows) const;
205  mutable DenseMatrix m_V; // Krylov basis vectors
206  mutable DenseMatrix m_H; // Hessenberg matrix
207  mutable DenseMatrix m_Hes; // Initial hessenberg matrix without Givens rotations applied
208  mutable Index m_restart; // Maximum size of the Krylov subspace
209  mutable DenseMatrix m_U; // Vectors that form the basis of the invariant subspace
210  mutable DenseMatrix m_MU; // matrix operator applied to m_U (for next cycles)
211  mutable DenseMatrix m_T; /* T=U^T*M^{-1}*A*U */
212  mutable PartialPivLU<DenseMatrix> m_luT; // LU factorization of m_T
213  mutable StorageIndex m_neig; // Number of eigenvalues to extract at each restart
214  mutable Index m_r; // Current number of deflated eigenvalues, size of m_U
215  mutable Index m_maxNeig; // Maximum number of eigenvalues to deflate
216  mutable RealScalar m_lambdaN; // Modulus of the largest eigenvalue of A
217  mutable bool m_isDeflAllocated;
218  mutable bool m_isDeflInitialized;
219 
220  // Adaptive strategy
221  mutable RealScalar m_smv; // Smaller multiple of the remaining number of steps allowed
222  mutable bool m_force; // Force the use of deflation at each restart
223 };
230 template <typename MatrixType_, typename Preconditioner_>
231 template <typename Rhs, typename Dest>
233  const Preconditioner& precond) const {
234  const RealScalar considerAsZero = (std::numeric_limits<RealScalar>::min)();
235 
236  RealScalar normRhs = rhs.norm();
237  if (normRhs <= considerAsZero) {
238  x.setZero();
239  m_error = 0;
240  return;
241  }
242 
243  // Initialization
244  m_isDeflInitialized = false;
245  Index n = mat.rows();
246  DenseVector r0(n);
247  Index nbIts = 0;
248  m_H.resize(m_restart + 1, m_restart);
249  m_Hes.resize(m_restart, m_restart);
250  m_V.resize(n, m_restart + 1);
251  // Initial residual vector and initial norm
252  if (x.squaredNorm() == 0) x = precond.solve(rhs);
253  r0 = rhs - mat * x;
254  RealScalar beta = r0.norm();
255 
256  m_error = beta / normRhs;
257  if (m_error < m_tolerance)
258  m_info = Success;
259  else
260  m_info = NoConvergence;
261 
262  // Iterative process
263  while (nbIts < m_iterations && m_info == NoConvergence) {
264  dgmresCycle(mat, precond, x, r0, beta, normRhs, nbIts);
265 
266  // Compute the new residual vector for the restart
267  if (nbIts < m_iterations && m_info == NoConvergence) {
268  r0 = rhs - mat * x;
269  beta = r0.norm();
270  }
271  }
272 }
273 
284 template <typename MatrixType_, typename Preconditioner_>
285 template <typename Dest>
287  DenseVector& r0, RealScalar& beta, const RealScalar& normRhs,
288  Index& nbIts) const {
289  // Initialization
290  DenseVector g(m_restart + 1); // Right hand side of the least square problem
291  g.setZero();
292  g(0) = Scalar(beta);
293  m_V.col(0) = r0 / beta;
294  m_info = NoConvergence;
295  std::vector<JacobiRotation<Scalar> > gr(m_restart); // Givens rotations
296  Index it = 0; // Number of inner iterations
297  Index n = mat.rows();
298  DenseVector tv1(n), tv2(n); // Temporary vectors
299  while (m_info == NoConvergence && it < m_restart && nbIts < m_iterations) {
300  // Apply preconditioner(s) at right
301  if (m_isDeflInitialized) {
302  dgmresApplyDeflation(m_V.col(it), tv1); // Deflation
303  tv2 = precond.solve(tv1);
304  } else {
305  tv2 = precond.solve(m_V.col(it)); // User's selected preconditioner
306  }
307  tv1 = mat * tv2;
308 
309  // Orthogonalize it with the previous basis in the basis using modified Gram-Schmidt
310  Scalar coef;
311  for (Index i = 0; i <= it; ++i) {
312  coef = tv1.dot(m_V.col(i));
313  tv1 = tv1 - coef * m_V.col(i);
314  m_H(i, it) = coef;
315  m_Hes(i, it) = coef;
316  }
317  // Normalize the vector
318  coef = tv1.norm();
319  m_V.col(it + 1) = tv1 / coef;
320  m_H(it + 1, it) = coef;
321  // m_Hes(it+1,it) = coef;
322 
323  // FIXME Check for happy breakdown
324 
325  // Update Hessenberg matrix with Givens rotations
326  for (Index i = 1; i <= it; ++i) {
327  m_H.col(it).applyOnTheLeft(i - 1, i, gr[i - 1].adjoint());
328  }
329  // Compute the new plane rotation
330  gr[it].makeGivens(m_H(it, it), m_H(it + 1, it));
331  // Apply the new rotation
332  m_H.col(it).applyOnTheLeft(it, it + 1, gr[it].adjoint());
333  g.applyOnTheLeft(it, it + 1, gr[it].adjoint());
334 
335  beta = std::abs(g(it + 1));
336  m_error = beta / normRhs;
337  // std::cerr << nbIts << " Relative Residual Norm " << m_error << std::endl;
338  it++;
339  nbIts++;
340 
341  if (m_error < m_tolerance) {
342  // The method has converged
343  m_info = Success;
344  break;
345  }
346  }
347 
348  // Compute the new coefficients by solving the least square problem
349  // it++;
350  // FIXME Check first if the matrix is singular ... zero diagonal
351  DenseVector nrs(m_restart);
352  nrs = m_H.topLeftCorner(it, it).template triangularView<Upper>().solve(g.head(it));
353 
354  // Form the new solution
355  if (m_isDeflInitialized) {
356  tv1 = m_V.leftCols(it) * nrs;
357  dgmresApplyDeflation(tv1, tv2);
358  x = x + precond.solve(tv2);
359  } else
360  x = x + precond.solve(m_V.leftCols(it) * nrs);
361 
362  // Go for a new cycle and compute data for deflation
363  if (nbIts < m_iterations && m_info == NoConvergence && m_neig > 0 && (m_r + m_neig) < m_maxNeig)
364  dgmresComputeDeflationData(mat, precond, it, m_neig);
365  return 0;
366 }
367 
368 template <typename MatrixType_, typename Preconditioner_>
370  m_U.resize(rows, m_maxNeig);
371  m_MU.resize(rows, m_maxNeig);
372  m_T.resize(m_maxNeig, m_maxNeig);
373  m_lambdaN = 0.0;
374  m_isDeflAllocated = true;
375 }
376 
377 template <typename MatrixType_, typename Preconditioner_>
379  const ComplexSchur<DenseMatrix>& schurofH) const {
380  return schurofH.matrixT().diagonal();
381 }
382 
383 template <typename MatrixType_, typename Preconditioner_>
385  const RealSchur<DenseMatrix>& schurofH) const {
386  const DenseMatrix& T = schurofH.matrixT();
387  Index it = T.rows();
388  ComplexVector eig(it);
389  Index j = 0;
390  while (j < it - 1) {
391  if (T(j + 1, j) == Scalar(0)) {
392  eig(j) = std::complex<RealScalar>(T(j, j), RealScalar(0));
393  j++;
394  } else {
395  eig(j) = std::complex<RealScalar>(T(j, j), T(j + 1, j));
396  eig(j + 1) = std::complex<RealScalar>(T(j, j + 1), T(j + 1, j + 1));
397  j++;
398  }
399  }
400  if (j < it - 1) eig(j) = std::complex<RealScalar>(T(j, j), RealScalar(0));
401  return eig;
402 }
403 
404 template <typename MatrixType_, typename Preconditioner_>
406  const Preconditioner& precond, const Index& it,
407  StorageIndex& neig) const {
408  // First, find the Schur form of the Hessenberg matrix H
410  bool computeU = true;
411  DenseMatrix matrixQ(it, it);
412  matrixQ.setIdentity();
413  schurofH.computeFromHessenberg(m_Hes.topLeftCorner(it, it), matrixQ, computeU);
414 
415  ComplexVector eig(it);
417  eig = this->schurValues(schurofH);
418 
419  // Reorder the absolute values of Schur values
420  DenseRealVector modulEig(it);
421  for (Index j = 0; j < it; ++j) modulEig(j) = std::abs(eig(j));
422  perm.setLinSpaced(it, 0, internal::convert_index<StorageIndex>(it - 1));
423  internal::sortWithPermutation(modulEig, perm, neig);
424 
425  if (!m_lambdaN) {
426  m_lambdaN = (std::max)(modulEig.maxCoeff(), m_lambdaN);
427  }
428  // Count the real number of extracted eigenvalues (with complex conjugates)
429  Index nbrEig = 0;
430  while (nbrEig < neig) {
431  if (eig(perm(it - nbrEig - 1)).imag() == RealScalar(0))
432  nbrEig++;
433  else
434  nbrEig += 2;
435  }
436  // Extract the Schur vectors corresponding to the smallest Ritz values
437  DenseMatrix Sr(it, nbrEig);
438  Sr.setZero();
439  for (Index j = 0; j < nbrEig; j++) {
440  Sr.col(j) = schurofH.matrixU().col(perm(it - j - 1));
441  }
442 
443  // Form the Schur vectors of the initial matrix using the Krylov basis
444  DenseMatrix X;
445  X = m_V.leftCols(it) * Sr;
446  if (m_r) {
447  // Orthogonalize X against m_U using modified Gram-Schmidt
448  for (Index j = 0; j < nbrEig; j++)
449  for (Index k = 0; k < m_r; k++) X.col(j) = X.col(j) - (m_U.col(k).dot(X.col(j))) * m_U.col(k);
450  }
451 
452  // Compute m_MX = A * M^-1 * X
453  Index m = m_V.rows();
454  if (!m_isDeflAllocated) dgmresInitDeflation(m);
455  DenseMatrix MX(m, nbrEig);
456  DenseVector tv1(m);
457  for (Index j = 0; j < nbrEig; j++) {
458  tv1 = mat * X.col(j);
459  MX.col(j) = precond.solve(tv1);
460  }
461 
462  // Update m_T = [U'MU U'MX; X'MU X'MX]
463  m_T.block(m_r, m_r, nbrEig, nbrEig) = X.transpose() * MX;
464  if (m_r) {
465  m_T.block(0, m_r, m_r, nbrEig) = m_U.leftCols(m_r).transpose() * MX;
466  m_T.block(m_r, 0, nbrEig, m_r) = X.transpose() * m_MU.leftCols(m_r);
467  }
468 
469  // Save X into m_U and m_MX in m_MU
470  for (Index j = 0; j < nbrEig; j++) m_U.col(m_r + j) = X.col(j);
471  for (Index j = 0; j < nbrEig; j++) m_MU.col(m_r + j) = MX.col(j);
472  // Increase the size of the invariant subspace
473  m_r += nbrEig;
474 
475  // Factorize m_T into m_luT
476  m_luT.compute(m_T.topLeftCorner(m_r, m_r));
477 
478  // FIXME CHeck if the factorization was correctly done (nonsingular matrix)
479  m_isDeflInitialized = true;
480  return 0;
481 }
482 template <typename MatrixType_, typename Preconditioner_>
483 template <typename RhsType, typename DestType>
485  DenseVector x1 = m_U.leftCols(m_r).transpose() * x;
486  y = x + m_U.leftCols(m_r) * (m_lambdaN * m_luT.solve(x1) - x1);
487  return 0;
488 }
489 
490 } // end namespace Eigen
491 #endif
AnnoyingScalar abs(const AnnoyingScalar &x)
Definition: AnnoyingScalar.h:135
int i
Definition: BiCGSTAB_step_by_step.cpp:9
const unsigned n
Definition: CG3DPackingUnitTest.cpp:11
Eigen::Triplet< double > T
Definition: EigenUnitTest.cpp:11
#define eigen_assert(x)
Definition: Macros.h:910
#define EIGEN_STATIC_ASSERT(X, MSG)
Definition: StaticAssert.h:26
int rows
Definition: Tutorial_commainit_02.cpp:1
void adjoint(const MatrixType &m)
Definition: adjoint.cpp:85
Scalar * b
Definition: benchVecAdd.cpp:17
SCALAR Scalar
Definition: bench_gemm.cpp:45
NumTraits< Scalar >::Real RealScalar
Definition: bench_gemm.cpp:46
MatrixXf MatrixType
Definition: benchmark-blocking-sizes.cpp:52
Performs a complex Schur decomposition of a real or complex square matrix.
Definition: ComplexSchur.h:56
const ComplexMatrixType & matrixT() const
Returns the triangular matrix in the Schur decomposition.
Definition: ComplexSchur.h:165
A Restarted GMRES with deflation. This class implements a modification of the GMRES solver for sparse...
Definition: DGMRES.h:98
Index dgmresCycle(const MatrixType &mat, const Preconditioner &precond, Dest &x, DenseVector &r0, RealScalar &beta, const RealScalar &normRhs, Index &nbIts) const
Perform one restart cycle of DGMRES.
Definition: DGMRES.h:286
Preconditioner_ Preconditioner
Definition: DGMRES.h:114
Index restart()
Definition: DGMRES.h:162
void dgmresInitDeflation(Index &rows) const
Definition: DGMRES.h:369
DGMRES(const EigenBase< MatrixDerived > &A)
Definition: DGMRES.h:136
Matrix< RealScalar, Dynamic, 1 > DenseRealVector
Definition: DGMRES.h:118
RealScalar m_smv
Definition: DGMRES.h:221
Matrix< RealScalar, Dynamic, Dynamic > DenseRealMatrix
Definition: DGMRES.h:116
IterativeSolverBase< DGMRES > Base
Definition: DGMRES.h:99
Index dgmresApplyDeflation(const RhsType &In, DestType &Out) const
Definition: DGMRES.h:484
void setMaxEigenv(const Index maxNeig)
Definition: DGMRES.h:185
DGMRES()
Definition: DGMRES.h:122
DenseMatrix m_H
Definition: DGMRES.h:206
~DGMRES()
Definition: DGMRES.h:145
Matrix< std::complex< RealScalar >, Dynamic, 1 > ComplexVector
Definition: DGMRES.h:119
DenseMatrix m_V
Definition: DGMRES.h:205
PartialPivLU< DenseMatrix > m_luT
Definition: DGMRES.h:212
StorageIndex m_neig
Definition: DGMRES.h:213
DenseMatrix m_T
Definition: DGMRES.h:211
void _solve_vector_with_guess_impl(const Rhs &b, Dest &x) const
Definition: DGMRES.h:149
Matrix< Scalar, Dynamic, Dynamic > DenseMatrix
Definition: DGMRES.h:115
DenseMatrix m_U
Definition: DGMRES.h:209
void dgmres(const MatrixType &mat, const Rhs &rhs, Dest &x, const Preconditioner &precond) const
Perform several cycles of restarted GMRES with modified Gram Schmidt,.
Definition: DGMRES.h:232
RealScalar m_error
Definition: IterativeSolverBase.h:387
bool m_isDeflAllocated
Definition: DGMRES.h:217
MatrixType::StorageIndex StorageIndex
Definition: DGMRES.h:112
void set_restart(const Index restart)
Definition: DGMRES.h:167
Index m_restart
Definition: DGMRES.h:208
Matrix< Scalar, Dynamic, 1 > DenseVector
Definition: DGMRES.h:117
DenseMatrix m_MU
Definition: DGMRES.h:210
DenseMatrix m_Hes
Definition: DGMRES.h:207
Index m_iterations
Definition: IterativeSolverBase.h:388
bool m_force
Definition: DGMRES.h:222
MatrixType::RealScalar RealScalar
Definition: DGMRES.h:113
Index deflSize()
Definition: DGMRES.h:180
void setEigenv(const Index neig)
Definition: DGMRES.h:172
MatrixType::Scalar Scalar
Definition: DGMRES.h:111
Index m_maxNeig
Definition: DGMRES.h:215
Index dgmresComputeDeflationData(const MatrixType &mat, const Preconditioner &precond, const Index &it, StorageIndex &neig) const
Definition: DGMRES.h:405
Index m_r
Definition: DGMRES.h:214
bool m_isDeflInitialized
Definition: DGMRES.h:218
ComplexVector schurValues(const ComplexSchur< DenseMatrix > &schurofH) const
Definition: DGMRES.h:378
const ActualMatrixType & matrix() const
Definition: IterativeSolverBase.h:374
MatrixType_ MatrixType
Definition: DGMRES.h:110
RealScalar m_lambdaN
Definition: DGMRES.h:216
Base class for linear iterative solvers.
Definition: IterativeSolverBase.h:124
Index maxIterations() const
Definition: IterativeSolverBase.h:251
ComputationInfo m_info
Definition: IterativeSolverBase.h:389
EIGEN_CONSTEXPR Index rows() const EIGEN_NOEXCEPT
Definition: IterativeSolverBase.h:221
RealScalar m_error
Definition: IterativeSolverBase.h:387
void _solve_impl(const Rhs &b, Dest &x) const
Definition: IterativeSolverBase.h:357
Preconditioner m_preconditioner
Definition: IterativeSolverBase.h:382
void _solve_with_guess_impl(const Rhs &b, SparseMatrixBase< DestDerived > &aDest) const
Definition: IterativeSolverBase.h:295
Index m_iterations
Definition: IterativeSolverBase.h:388
bool m_isInitialized
Definition: SparseSolverBase.h:110
RealScalar m_tolerance
Definition: IterativeSolverBase.h:385
DGMRES< MatrixType_, Preconditioner_ > & derived()
Definition: SparseSolverBase.h:76
const ActualMatrixType & matrix() const
Definition: IterativeSolverBase.h:374
LU decomposition of a matrix with partial pivoting, and related features.
Definition: PartialPivLU.h:77
EIGEN_DEVICE_FUNC Derived & setZero(Index size)
Definition: CwiseNullaryOp.h:569
Performs a real Schur decomposition of a square matrix.
Definition: RealSchur.h:58
const MatrixType & matrixT() const
Returns the quasi-triangular matrix in the Schur decomposition.
Definition: RealSchur.h:144
Index rows() const
Definition: SparseMatrix.h:159
Definition: restart2.cpp:8
@ IsComplex
Definition: common.h:73
#define min(a, b)
Definition: datatypes.h:22
#define max(a, b)
Definition: datatypes.h:23
@ Success
Definition: Constants.h:440
@ NoConvergence
Definition: Constants.h:444
#define X
Definition: icosphere.cpp:20
Scalar * y
Definition: level1_cplx_impl.h:128
EIGEN_BLAS_FUNC() swap(int *n, RealScalar *px, int *incx, RealScalar *py, int *incy)
Definition: level1_impl.h:117
int * m
Definition: level2_cplx_impl.h:294
Scalar beta
Definition: level2_cplx_impl.h:36
char char char int int * k
Definition: level2_impl.h:374
@ Rhs
Definition: TensorContractionMapper.h:20
void sortWithPermutation(VectorType &vec, IndexType &perm, typename IndexType::Scalar &ncut)
Computes a permutation vector to have a sorted sequence.
Definition: DGMRES.h:40
Namespace containing all symbols from the Eigen library.
Definition: bench_norm.cpp:70
EIGEN_DEFAULT_DENSE_INDEX_TYPE Index
The Index type as used for the API.
Definition: Meta.h:83
const int Dynamic
Definition: Constants.h:25
Vector< double > x1(const Vector< double > &coord)
Cartesian coordinates centered at the point (0.5,1)
Definition: poisson/poisson_with_singularity/two_d_poisson.cc:86
Definition: Eigen_Colamd.h:49
list x
Definition: plotDoE.py:28
Definition: EigenBase.h:33
Definition: ForwardDeclarations.h:21
Definition: fft_test_shared.h:66
std::ptrdiff_t j
Definition: tut_arithmetic_redux_minmax.cpp:2