Belos  Version of the Day
BelosBlockCGIter.hpp
Go to the documentation of this file.
1 //@HEADER
2 // ************************************************************************
3 //
4 // Belos: Block Linear Solvers Package
5 // Copyright 2004 Sandia Corporation
6 //
7 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
8 // the U.S. Government retains certain rights in this software.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
38 //
39 // ************************************************************************
40 //@HEADER
41 
42 #ifndef BELOS_BLOCK_CG_ITER_HPP
43 #define BELOS_BLOCK_CG_ITER_HPP
44 
49 #include "BelosConfigDefs.hpp"
50 #include "BelosTypes.hpp"
51 #include "BelosCGIteration.hpp"
52 
53 #include "BelosLinearProblem.hpp"
54 #include "BelosMatOrthoManager.hpp"
55 #include "BelosOutputManager.hpp"
56 #include "BelosStatusTest.hpp"
57 #include "BelosOperatorTraits.hpp"
58 #include "BelosMultiVecTraits.hpp"
59 
60 #include "Teuchos_BLAS.hpp"
61 #include "Teuchos_LAPACK.hpp"
62 #include "Teuchos_SerialDenseMatrix.hpp"
63 #include "Teuchos_SerialDenseVector.hpp"
64 #include "Teuchos_SerialSymDenseMatrix.hpp"
65 #include "Teuchos_SerialSpdDenseSolver.hpp"
66 #include "Teuchos_ScalarTraits.hpp"
67 #include "Teuchos_ParameterList.hpp"
68 #include "Teuchos_TimeMonitor.hpp"
69 
80 namespace Belos {
81 
82 template<class ScalarType, class MV, class OP>
83 class BlockCGIter : virtual public CGIteration<ScalarType,MV,OP> {
84 
85  public:
86 
87  //
88  // Convenience typedefs
89  //
93  typedef Teuchos::ScalarTraits<ScalarType> SCT;
94  typedef typename SCT::magnitudeType MagnitudeType;
95 
97 
98 
104  BlockCGIter( const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > &problem,
105  const Teuchos::RCP<OutputManager<ScalarType> > &printer,
106  const Teuchos::RCP<StatusTest<ScalarType,MV,OP> > &tester,
107  const Teuchos::RCP<MatOrthoManager<ScalarType,MV,OP> > &ortho,
108  Teuchos::ParameterList &params );
109 
111  virtual ~BlockCGIter() {};
113 
114 
116 
117 
130  void iterate();
131 
147 
151  void initialize()
152  {
154  initializeCG(empty);
155  }
156 
165  state.R = R_;
166  state.P = P_;
167  state.AP = AP_;
168  state.Z = Z_;
169  return state;
170  }
171 
173 
174 
176 
177 
179  int getNumIters() const { return iter_; }
180 
182  void resetNumIters( int iter=0 ) { iter_ = iter; }
183 
186  Teuchos::RCP<const MV> getNativeResiduals( std::vector<MagnitudeType> *norms ) const { return R_; }
187 
189 
191  Teuchos::RCP<MV> getCurrentUpdate() const { return Teuchos::null; }
192 
194 
196 
197 
199  const LinearProblem<ScalarType,MV,OP>& getProblem() const { return *lp_; }
200 
202  int getBlockSize() const { return blockSize_; }
203 
205  void setBlockSize(int blockSize);
206 
208  bool isInitialized() { return initialized_; }
209 
211 
212  private:
213 
214  //
215  // Internal methods
216  //
218  void setStateSize();
219 
220  //
221  // Classes inputed through constructor that define the linear problem to be solved.
222  //
223  const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > lp_;
224  const Teuchos::RCP<OutputManager<ScalarType> > om_;
225  const Teuchos::RCP<StatusTest<ScalarType,MV,OP> > stest_;
226  const Teuchos::RCP<OrthoManager<ScalarType,MV> > ortho_;
227 
228  //
229  // Algorithmic parameters
230  //
231  // blockSize_ is the solver block size.
232  int blockSize_;
233 
234  //
235  // Current solver state
236  //
237  // initialized_ specifies that the basis vectors have been initialized and the iterate() routine
238  // is capable of running; _initialize is controlled by the initialize() member method
239  // For the implications of the state of initialized_, please see documentation for initialize()
240  bool initialized_;
241 
242  // stateStorageInitialized_ specified that the state storage has be initialized.
243  // This initialization may be postponed if the linear problem was generated without
244  // the right-hand side or solution vectors.
245  bool stateStorageInitialized_;
246 
247  // Current subspace dimension, and number of iterations performed.
248  int iter_;
249 
250  //
251  // State Storage
252  //
253  // Residual
254  Teuchos::RCP<MV> R_;
255  //
256  // Preconditioned residual
257  Teuchos::RCP<MV> Z_;
258  //
259  // Direction std::vector
260  Teuchos::RCP<MV> P_;
261  //
262  // Operator applied to direction std::vector
263  Teuchos::RCP<MV> AP_;
264 
265 };
266 
268  // Constructor.
269  template<class ScalarType, class MV, class OP>
271  const Teuchos::RCP<OutputManager<ScalarType> > &printer,
272  const Teuchos::RCP<StatusTest<ScalarType,MV,OP> > &tester,
273  const Teuchos::RCP<MatOrthoManager<ScalarType,MV,OP> > &ortho,
274  Teuchos::ParameterList &params ):
275  lp_(problem),
276  om_(printer),
277  stest_(tester),
278  ortho_(ortho),
279  blockSize_(0),
280  initialized_(false),
281  stateStorageInitialized_(false),
282  iter_(0)
283  {
284  // Set the block size and allocate data
285  int bs = params.get("Block Size", 1);
286  setBlockSize( bs );
287  }
288 
290  // Setup the state storage.
291  template <class ScalarType, class MV, class OP>
293  {
294  if (!stateStorageInitialized_) {
295 
296  // Check if there is any multivector to clone from.
297  Teuchos::RCP<const MV> lhsMV = lp_->getLHS();
298  Teuchos::RCP<const MV> rhsMV = lp_->getRHS();
299  if (lhsMV == Teuchos::null && rhsMV == Teuchos::null) {
300  stateStorageInitialized_ = false;
301  return;
302  }
303  else {
304 
305  // Initialize the state storage
306  // If the subspace has not be initialized before, generate it using the LHS or RHS from lp_.
307  if (R_ == Teuchos::null || MVT::GetNumberVecs(*R_)!=blockSize_) {
308  // Get the multivector that is not null.
309  Teuchos::RCP<const MV> tmp = ( (rhsMV!=Teuchos::null)? rhsMV: lhsMV );
310  TEUCHOS_TEST_FOR_EXCEPTION(tmp == Teuchos::null,std::invalid_argument,
311  "Belos::BlockCGIter::setStateSize(): linear problem does not specify multivectors to clone from.");
312  R_ = MVT::Clone( *tmp, blockSize_ );
313  Z_ = MVT::Clone( *tmp, blockSize_ );
314  P_ = MVT::Clone( *tmp, blockSize_ );
315  AP_ = MVT::Clone( *tmp, blockSize_ );
316  }
317 
318  // State storage has now been initialized.
319  stateStorageInitialized_ = true;
320  }
321  }
322  }
323 
325  // Set the block size and make necessary adjustments.
326  template <class ScalarType, class MV, class OP>
328  {
329  // This routine only allocates space; it doesn't not perform any computation
330  // any change in size will invalidate the state of the solver.
331 
332  TEUCHOS_TEST_FOR_EXCEPTION(blockSize <= 0, std::invalid_argument, "Belos::BlockGmresIter::setBlockSize was passed a non-positive argument.");
333  if (blockSize == blockSize_) {
334  // do nothing
335  return;
336  }
337 
338  if (blockSize!=blockSize_)
339  stateStorageInitialized_ = false;
340 
341  blockSize_ = blockSize;
342 
343  initialized_ = false;
344 
345  // Use the current blockSize_ to initialize the state storage.
346  setStateSize();
347 
348  }
349 
351  // Initialize this iteration object
352  template <class ScalarType, class MV, class OP>
354  {
355  // Initialize the state storage if it isn't already.
356  if (!stateStorageInitialized_)
357  setStateSize();
358 
359  TEUCHOS_TEST_FOR_EXCEPTION(!stateStorageInitialized_,std::invalid_argument,
360  "Belos::BlockCGIter::initialize(): Cannot initialize state storage!");
361 
362  // NOTE: In BlockCGIter R_, the initial residual, is required!!!
363  //
364  std::string errstr("Belos::BlockCGIter::initialize(): Specified multivectors must have a consistent length and width.");
365 
366  // Create convenience variables for zero and one.
367  const ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
368  const MagnitudeType zero = Teuchos::ScalarTraits<MagnitudeType>::zero();
369 
370  if (newstate.R != Teuchos::null) {
371 
372  TEUCHOS_TEST_FOR_EXCEPTION( MVText::GetGlobalLength(*newstate.R) != MVText::GetGlobalLength(*R_),
373  std::invalid_argument, errstr );
374  TEUCHOS_TEST_FOR_EXCEPTION( MVT::GetNumberVecs(*newstate.R) != blockSize_,
375  std::invalid_argument, errstr );
376 
377  // Copy basis vectors from newstate into V
378  if (newstate.R != R_) {
379  // copy over the initial residual (unpreconditioned).
380  MVT::MvAddMv( one, *newstate.R, zero, *newstate.R, *R_ );
381  }
382  // Compute initial direction vectors
383  // Initially, they are set to the preconditioned residuals
384  //
385  if ( lp_->getLeftPrec() != Teuchos::null ) {
386  lp_->applyLeftPrec( *R_, *Z_ );
387  if ( lp_->getRightPrec() != Teuchos::null ) {
388  Teuchos::RCP<MV> tmp = MVT::Clone( *Z_, blockSize_ );
389  lp_->applyRightPrec( *Z_, *tmp );
390  Z_ = tmp;
391  }
392  }
393  else if ( lp_->getRightPrec() != Teuchos::null ) {
394  lp_->applyRightPrec( *R_, *Z_ );
395  }
396  else {
397  Z_ = R_;
398  }
399  MVT::MvAddMv( one, *Z_, zero, *Z_, *P_ );
400  }
401  else {
402 
403  TEUCHOS_TEST_FOR_EXCEPTION(newstate.R == Teuchos::null,std::invalid_argument,
404  "Belos::BlockCGIter::initialize(): BlockCGStateIterState does not have initial residual.");
405  }
406 
407  // The solver is initialized
408  initialized_ = true;
409  }
410 
411 
413  // Iterate until the status test informs us we should stop.
414  template <class ScalarType, class MV, class OP>
416  {
417  //
418  // Allocate/initialize data structures
419  //
420  if (initialized_ == false) {
421  initialize();
422  }
423  // Allocate data needed for LAPACK work.
424  int info = 0;
425  char UPLO = 'U';
426  (void) UPLO; // silence "unused variable" compiler warnings
427  bool uplo = true;
428  Teuchos::LAPACK<int,ScalarType> lapack;
429 
430  // Allocate memory for scalars.
431  Teuchos::SerialDenseMatrix<int,ScalarType> alpha( blockSize_, blockSize_ );
432  Teuchos::SerialDenseMatrix<int,ScalarType> beta( blockSize_, blockSize_ );
433  Teuchos::SerialDenseMatrix<int,ScalarType> rHz( blockSize_, blockSize_ ),
434  rHz_old( blockSize_, blockSize_ ), pAp( blockSize_, blockSize_ );
435  Teuchos::SerialSymDenseMatrix<int,ScalarType> pApHerm(Teuchos::View, uplo, pAp.values(), blockSize_, blockSize_);
436 
437  // Create dense spd solver.
438  Teuchos::SerialSpdDenseSolver<int,ScalarType> lltSolver;
439 
440  // Create convenience variables for zero and one.
441  const ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
442 
443  // Get the current solution std::vector.
444  Teuchos::RCP<MV> cur_soln_vec = lp_->getCurrLHSVec();
445 
446  // Check that the current solution std::vector has blockSize_ columns.
447  TEUCHOS_TEST_FOR_EXCEPTION( MVT::GetNumberVecs(*cur_soln_vec) != blockSize_, CGIterateFailure,
448  "Belos::BlockCGIter::iterate(): current linear system does not have the right number of vectors!" );
449  int rank = ortho_->normalize( *P_, Teuchos::null );
450  TEUCHOS_TEST_FOR_EXCEPTION(rank != blockSize_,CGIterationOrthoFailure,
451  "Belos::BlockCGIter::iterate(): Failed to compute initial block of orthonormal direction vectors.");
452 
453 
455  // Iterate until the status test tells us to stop.
456  //
457  while (stest_->checkStatus(this) != Passed) {
458 
459  // Increment the iteration
460  iter_++;
461 
462  // Multiply the current direction std::vector by A and store in Ap_
463  lp_->applyOp( *P_, *AP_ );
464 
465  // Compute alpha := <P_,R_> / <P_,AP_>
466  // 1) Compute P^T * A * P = pAp and P^T * R
467  // 2) Compute the Cholesky Factorization of pAp
468  // 3) Back and forward solves to compute alpha
469  //
470  MVT::MvTransMv( one, *P_, *R_, alpha );
471  MVT::MvTransMv( one, *P_, *AP_, pAp );
472 
473  // Compute Cholesky factorization of pAp
474  lltSolver.setMatrix( Teuchos::rcp(&pApHerm, false) );
475  lltSolver.factorWithEquilibration( true );
476  info = lltSolver.factor();
477  TEUCHOS_TEST_FOR_EXCEPTION(info != 0,CGIterationLAPACKFailure,
478  "Belos::BlockCGIter::iterate(): Failed to compute Cholesky factorization using LAPACK routine POTRF.");
479 
480  // Compute alpha by performing a back and forward solve with the Cholesky factorization in pAp.
481  lltSolver.setVectors( Teuchos::rcp( &alpha, false ), Teuchos::rcp( &alpha, false ) );
482  info = lltSolver.solve();
483  TEUCHOS_TEST_FOR_EXCEPTION(info != 0,CGIterationLAPACKFailure,
484  "Belos::BlockCGIter::iterate(): Failed to compute alpha using Cholesky factorization (POTRS).");
485 
486  //
487  // Update the solution std::vector X := X + alpha * P_
488  //
489  MVT::MvTimesMatAddMv( one, *P_, alpha, one, *cur_soln_vec );
490  lp_->updateSolution();
491  //
492  // Compute the new residual R_ := R_ - alpha * AP_
493  //
494  MVT::MvTimesMatAddMv( -one, *AP_, alpha, one, *R_ );
495  //
496  // Compute the new preconditioned residual, Z_.
497  if ( lp_->getLeftPrec() != Teuchos::null ) {
498  lp_->applyLeftPrec( *R_, *Z_ );
499  if ( lp_->getRightPrec() != Teuchos::null ) {
500  Teuchos::RCP<MV> tmp = MVT::Clone( *Z_, blockSize_ );
501  lp_->applyRightPrec( *Z_, *tmp );
502  Z_ = tmp;
503  }
504  }
505  else if ( lp_->getRightPrec() != Teuchos::null ) {
506  lp_->applyRightPrec( *R_, *Z_ );
507  }
508  else {
509  Z_ = R_;
510  }
511  //
512  // Compute beta := <AP_,Z_> / <P_,AP_>
513  // 1) Compute AP_^T * Z_
514  // 2) Compute the Cholesky Factorization of pAp (already have)
515  // 3) Back and forward solves to compute beta
516 
517  // Compute <AP_,Z>
518  MVT::MvTransMv( -one, *AP_, *Z_, beta );
519  //
520  lltSolver.setVectors( Teuchos::rcp( &beta, false ), Teuchos::rcp( &beta, false ) );
521  info = lltSolver.solve();
522  TEUCHOS_TEST_FOR_EXCEPTION(info != 0,CGIterationLAPACKFailure,
523  "Belos::BlockCGIter::iterate(): Failed to compute beta using Cholesky factorization (POTRS).");
524  //
525  // Compute the new direction vectors P_ = Z_ + P_ * beta
526  //
527  Teuchos::RCP<MV> Pnew = MVT::CloneCopy( *Z_ );
528  MVT::MvTimesMatAddMv(one, *P_, beta, one, *Pnew);
529  P_ = Pnew;
530 
531  // Compute orthonormal block of new direction vectors.
532  rank = ortho_->normalize( *P_, Teuchos::null );
533  TEUCHOS_TEST_FOR_EXCEPTION(rank != blockSize_,CGIterationOrthoFailure,
534  "Belos::BlockCGIter::iterate(): Failed to compute block of orthonormal direction vectors.");
535 
536  } // end while (sTest_->checkStatus(this) != Passed)
537  }
538 
539 } // end Belos namespace
540 
541 #endif /* BELOS_BLOCK_CG_ITER_HPP */
Teuchos::RCP< const MV > R
The current residual.
Collection of types and exceptions used within the Belos solvers.
Belos&#39;s basic output manager for sending information of select verbosity levels to the appropriate ou...
void resetNumIters(int iter=0)
Reset the iteration count.
Class which manages the output and verbosity of the Belos solvers.
OperatorTraits< ScalarType, MV, OP > OPT
Structure to contain pointers to CGIteration state variables.
Pure virtual base class which augments the basic interface for a conjugate gradient linear solver ite...
Pure virtual base class for defining the status testing capabilities of Belos.
Declaration of basic traits for the multivector type.
Teuchos::RCP< MV > getCurrentUpdate() const
Get the current update to the linear system.
An extension of the MultiVecTraits class that adds a new vector length method.
MultiVecTraitsExt< ScalarType, MV > MVText
BlockCGIter(const Teuchos::RCP< LinearProblem< ScalarType, MV, OP > > &problem, const Teuchos::RCP< OutputManager< ScalarType > > &printer, const Teuchos::RCP< StatusTest< ScalarType, MV, OP > > &tester, const Teuchos::RCP< MatOrthoManager< ScalarType, MV, OP > > &ortho, Teuchos::ParameterList &params)
BlockCGIter constructor with linear problem, solver utilities, and parameter list of solver options...
static void MvTransMv(const ScalarType alpha, const MV &A, const MV &mv, Teuchos::SerialDenseMatrix< int, ScalarType > &B)
Compute a dense matrix B through the matrix-matrix multiply .
A pure virtual class for defining the status tests for the Belos iterative solvers.
Class which defines basic traits for the operator type.
CGIterateFailure is thrown when the CGIteration object is unable to compute the next iterate in the C...
Teuchos::RCP< const MV > AP
The matrix A applied to current decent direction vector.
bool isInitialized()
States whether the solver has been initialized or not.
static int GetNumberVecs(const MV &mv)
Obtain the number of vectors in mv.
static void MvAddMv(const ScalarType alpha, const MV &A, const ScalarType beta, const MV &B, MV &mv)
Replace mv with .
Traits class which defines basic operations on multivectors.
const LinearProblem< ScalarType, MV, OP > & getProblem() const
Get a constant reference to the linear problem.
MultiVecTraits< ScalarType, MV > MVT
CGIterationLAPACKFailure is thrown when a nonzero return value is passed back from an LAPACK routine...
Teuchos::ScalarTraits< ScalarType > SCT
static Teuchos::RCP< MV > Clone(const MV &mv, const int numvecs)
Creates a new empty MV containing numvecs columns.
SCT::magnitudeType MagnitudeType
A linear system to solve, and its associated information.
Class which describes the linear problem to be solved by the iterative solver.
static Teuchos::RCP< MV > CloneCopy(const MV &mv)
Creates a new MV and copies contents of mv into the new vector (deep copy).
void iterate()
This method performs BlockCG iterations until the status test indicates the need to stop or an error ...
static void MvTimesMatAddMv(const ScalarType alpha, const MV &A, const Teuchos::SerialDenseMatrix< int, ScalarType > &B, const ScalarType beta, MV &mv)
Update mv with .
virtual ~BlockCGIter()
Destructor.
Teuchos::RCP< const MV > Z
The current preconditioned residual.
Teuchos::RCP< const MV > getNativeResiduals(std::vector< MagnitudeType > *norms) const
Get the norms of the residuals native to the solver.
void setBlockSize(int blockSize)
Set the block size to be used by the iterative solver in solving this linear problem.
CGIterationOrthoFailure is thrown when the CGIteration object is unable to compute independent direct...
int getNumIters() const
Get the current iteration count.
CGIterationState< ScalarType, MV > getState() const
Get the current state of the linear solver.
static ptrdiff_t GetGlobalLength(const MV &mv)
Obtain the vector length of mv.
Class which defines basic traits for the operator type.
void initializeCG(CGIterationState< ScalarType, MV > newstate)
Initialize the solver to an iterate, providing a complete state.
Belos&#39;s templated virtual class for providing routines for orthogonalization and orthonormzalition of...
int getBlockSize() const
Get the block size to be used by the iterative solver in solving this linear problem.
Belos header file which uses auto-configuration information to include necessary C++ headers...
Teuchos::RCP< const MV > P
The current decent direction vector.
Templated virtual class for providing orthogonalization/orthonormalization methods with matrix-based ...
void initialize()
Initialize the solver with the initial vectors from the linear problem or random data.
This class implements the block, preconditioned Conjugate Gradient (CG) iteration.