Belos  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
BelosTFQMRIter.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 // This file contains an implementation of the TFQMR iteration
43 // for solving non-Hermitian linear systems of equations Ax = b,
44 // where b is a single-vector and x is the corresponding solution.
45 //
46 // The implementation is a slight modification on the TFQMR iteration
47 // found in Saad's "Iterative Methods for Sparse Linear Systems".
48 //
49 
50 #ifndef BELOS_TFQMR_ITER_HPP
51 #define BELOS_TFQMR_ITER_HPP
52 
60 #include "BelosConfigDefs.hpp"
61 #include "BelosIteration.hpp"
62 #include "BelosTypes.hpp"
63 
64 #include "BelosLinearProblem.hpp"
65 #include "BelosMatOrthoManager.hpp"
66 #include "BelosOutputManager.hpp"
67 #include "BelosStatusTest.hpp"
68 #include "BelosOperatorTraits.hpp"
69 #include "BelosMultiVecTraits.hpp"
70 
71 #include "Teuchos_BLAS.hpp"
74 #include "Teuchos_ScalarTraits.hpp"
76 #include "Teuchos_TimeMonitor.hpp"
77 
89 namespace Belos {
90 
95  template <class ScalarType, class MV>
96  struct TFQMRIterState {
97 
105 
106  TFQMRIterState() : R(Teuchos::null), W(Teuchos::null), U(Teuchos::null),
107  Rtilde(Teuchos::null), D(Teuchos::null), V(Teuchos::null)
108  {}
109  };
110 
111 
113 
114 
126  class TFQMRIterInitFailure : public BelosError {public:
127  TFQMRIterInitFailure(const std::string& what_arg) : BelosError(what_arg)
128  {}};
129 
136  class TFQMRIterateFailure : public BelosError {public:
137  TFQMRIterateFailure(const std::string& what_arg) : BelosError(what_arg)
138  {}};
139 
141 
142 
143  template <class ScalarType, class MV, class OP>
144  class TFQMRIter : public Iteration<ScalarType,MV,OP> {
145  public:
146  //
147  // Convenience typedefs
148  //
154 
156 
157 
160  const Teuchos::RCP<OutputManager<ScalarType> > &printer,
162  Teuchos::ParameterList &params );
163 
165  virtual ~TFQMRIter() {};
167 
168 
170 
171 
193  void iterate();
194 
217 
221  void initialize()
222  {
224  initializeTFQMR(empty);
225  }
226 
236  state.R = R_;
237  state.W = W_;
238  state.U = U_;
239  state.Rtilde = Rtilde_;
240  state.D = D_;
241  state.V = V_;
242  return state;
243  }
244 
246 
247 
249 
250 
252  int getNumIters() const { return iter_; }
253 
255  void resetNumIters( int iter = 0 ) { iter_ = iter; }
256 
259  Teuchos::RCP<const MV> getNativeResiduals( std::vector<MagnitudeType> *norms ) const;
260 
262 
264  Teuchos::RCP<MV> getCurrentUpdate() const { return Teuchos::null; }
265 
267 
268 
270 
271 
273  const LinearProblem<ScalarType,MV,OP>& getProblem() const { return *lp_; }
274 
276  int getBlockSize() const { return 1; }
277 
279  void setBlockSize(int blockSize) {
280  TEUCHOS_TEST_FOR_EXCEPTION(blockSize!=1,std::invalid_argument,
281  "Belos::TFQMRIter::setBlockSize(): Cannot use a block size that is not one.");
282  }
283 
285  bool isInitialized() { return initialized_; }
286 
288 
289 
290  private:
291 
292  //
293  // Internal methods
294  //
296  void setStateSize();
297 
298  //
299  // Classes inputed through constructor that define the linear problem to be solved.
300  //
304 
305  //
306  // Algorithmic parameters
307  //
308 
309  // Storage for QR factorization of the least squares system.
310  Teuchos::SerialDenseMatrix<int,ScalarType> alpha_, rho_, rho_old_;
311  std::vector<MagnitudeType> tau_, cs_, theta_;
312 
313  //
314  // Current solver state
315  //
316  // initialized_ specifies that the basis vectors have been initialized and the iterate() routine
317  // is capable of running; _initialize is controlled by the initialize() member method
318  // For the implications of the state of initialized_, please see documentation for initialize()
319  bool initialized_;
320 
321  // stateStorageInitialized_ specifies that the state storage has be initialized to the current
322  // blockSize_ and numBlocks_. This initialization may be postponed if the linear problem was
323  // generated without the right-hand side or solution vectors.
324  bool stateStorageInitialized_;
325 
326  // Current subspace dimension, and number of iterations performed.
327  int iter_;
328 
329  //
330  // State Storage
331  //
332  Teuchos::RCP<MV> R_;
333  Teuchos::RCP<MV> W_;
334  Teuchos::RCP<MV> U_, AU_;
335  Teuchos::RCP<MV> Rtilde_;
336  Teuchos::RCP<MV> D_;
337  Teuchos::RCP<MV> V_;
338 
339  };
340 
341 
342  //
343  // Implementation
344  //
345 
347  // Constructor.
348  template <class ScalarType, class MV, class OP>
350  const Teuchos::RCP<OutputManager<ScalarType> > &printer,
352  Teuchos::ParameterList &params
353  ) :
354  lp_(problem),
355  om_(printer),
356  stest_(tester),
357  alpha_(1,1),
358  rho_(1,1),
359  rho_old_(1,1),
360  tau_(1),
361  cs_(1),
362  theta_(1),
363  initialized_(false),
364  stateStorageInitialized_(false),
365  iter_(0)
366  {
367  }
368 
370  // Compute native residual from TFQMR recurrence.
371  template <class ScalarType, class MV, class OP>
373  TFQMRIter<ScalarType,MV,OP>::getNativeResiduals( std::vector<MagnitudeType> *normvec ) const
374  {
376  if (normvec)
377  (*normvec)[0] = Teuchos::ScalarTraits<MagnitudeType>::squareroot( iter_ + one )*tau_[0];
378 
379  return Teuchos::null;
380  }
381 
382 
384  // Setup the state storage.
385  template <class ScalarType, class MV, class OP>
387  {
388  if (!stateStorageInitialized_) {
389 
390  // Check if there is any multivector to clone from.
391  Teuchos::RCP<const MV> lhsMV = lp_->getLHS();
392  Teuchos::RCP<const MV> rhsMV = lp_->getRHS();
393  if (lhsMV == Teuchos::null && rhsMV == Teuchos::null) {
394  stateStorageInitialized_ = false;
395  return;
396  }
397  else {
398 
399  // Initialize the state storage
400  // If the subspace has not be initialized before, generate it using the LHS or RHS from lp_.
401  if (R_ == Teuchos::null) {
402  // Get the multivector that is not null.
403  Teuchos::RCP<const MV> tmp = ( (rhsMV!=Teuchos::null)? rhsMV: lhsMV );
404  TEUCHOS_TEST_FOR_EXCEPTION(tmp == Teuchos::null,std::invalid_argument,
405  "Belos::TFQMRIter::setStateSize(): linear problem does not specify multivectors to clone from.");
406  R_ = MVT::Clone( *tmp, 1 );
407  AU_ = MVT::Clone( *tmp, 1 );
408  D_ = MVT::Clone( *tmp, 1 );
409  V_ = MVT::Clone( *tmp, 1 );
410  }
411 
412  // State storage has now been initialized.
413  stateStorageInitialized_ = true;
414  }
415  }
416  }
417 
419  // Initialize this iteration object
420  template <class ScalarType, class MV, class OP>
422  {
423  // Initialize the state storage if it isn't already.
424  if (!stateStorageInitialized_)
425  setStateSize();
426 
427  TEUCHOS_TEST_FOR_EXCEPTION(!stateStorageInitialized_,std::invalid_argument,
428  "Belos::TFQMRIter::initialize(): Cannot initialize state storage!");
429 
430  // NOTE: In TFQMRIter R_, the initial residual, is required!!!
431  //
432  std::string errstr("Belos::TFQMRIter::initialize(): Specified multivectors must have a consistent length and width.");
433 
434  // Create convenience variables for zero and one.
435  const ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
436  const ScalarType STzero = Teuchos::ScalarTraits<ScalarType>::zero();
438 
439  if (newstate.R != Teuchos::null) {
440 
441  TEUCHOS_TEST_FOR_EXCEPTION( MVText::GetGlobalLength(*newstate.R) != MVText::GetGlobalLength(*R_),
442  std::invalid_argument, errstr );
443  TEUCHOS_TEST_FOR_EXCEPTION( MVT::GetNumberVecs(*newstate.R) != 1,
444  std::invalid_argument, errstr );
445 
446  // Copy basis vectors from newstate into V
447  if (newstate.R != R_) {
448  // copy over the initial residual (unpreconditioned).
449  MVT::MvAddMv( one, *newstate.R, STzero, *newstate.R, *R_ );
450  }
451 
452  // Compute initial vectors
453  // Initially, they are set to the preconditioned residuals
454  //
455  W_ = MVT::CloneCopy( *R_ );
456  U_ = MVT::CloneCopy( *R_ );
457  Rtilde_ = MVT::CloneCopy( *R_ );
458  MVT::MvInit( *D_ );
459  // Multiply the current residual by Op and store in V_
460  // V_ = Op * R_
461  //
462  lp_->apply( *U_, *V_ );
463  AU_ = MVT::CloneCopy( *V_ );
464  //
465  // Compute initial scalars: theta, eta, tau, rho_old
466  //
467  theta_[0] = MTzero;
468  MVT::MvNorm( *R_, tau_ ); // tau = ||r_0||
469  MVT::MvTransMv( one, *Rtilde_, *R_, rho_old_ ); // rho = (r_tilde, r0)
470  }
471  else {
472 
473  TEUCHOS_TEST_FOR_EXCEPTION(newstate.R == Teuchos::null,std::invalid_argument,
474  "Belos::TFQMRIter::initialize(): TFQMRIterState does not have initial residual.");
475  }
476 
477  // The solver is initialized
478  initialized_ = true;
479  }
480 
481 
483  // Iterate until the status test informs us we should stop.
484  template <class ScalarType, class MV, class OP>
486  {
487  //
488  // Allocate/initialize data structures
489  //
490  if (initialized_ == false) {
491  initialize();
492  }
493 
494  // Create convenience variables for zero and one.
495  const ScalarType STone = Teuchos::ScalarTraits<ScalarType>::one();
497  const ScalarType STzero = Teuchos::ScalarTraits<ScalarType>::zero();
498  ScalarType eta = STzero, beta = STzero;
499  //
500  // Start executable statements.
501  //
502  // Get the current solution vector.
503  Teuchos::RCP<MV> cur_soln_vec = lp_->getCurrLHSVec();
504 
505  // Check that the current solution vector only has one column.
506  TEUCHOS_TEST_FOR_EXCEPTION( MVT::GetNumberVecs(*cur_soln_vec) != 1, TFQMRIterateFailure,
507  "Belos::TFQMRIter::iterate(): current linear system has more than one vector!" );
508 
509 
511  // Iterate until the status test tells us to stop.
512  //
513  while (stest_->checkStatus(this) != Passed) {
514 
515  //
516  //--------------------------------------------------------
517  // Compute the new alpha if we need to
518  //--------------------------------------------------------
519  //
520  if (iter_%2 == 0) {
521  MVT::MvTransMv( STone, *Rtilde_, *V_, alpha_ ); // alpha = rho / (r_tilde, v)
522  alpha_(0,0) = rho_old_(0,0)/alpha_(0,0);
523  }
524  //
525  //--------------------------------------------------------
526  // Update w.
527  // w = w - alpha*Au
528  //--------------------------------------------------------
529  //
530  MVT::MvAddMv( STone, *W_, -alpha_(0,0), *AU_, *W_ );
531  //
532  //--------------------------------------------------------
533  // Update d.
534  // d = u + (theta^2/alpha)eta*d
535  //--------------------------------------------------------
536  //
537  MVT::MvAddMv( STone, *U_, (theta_[0]*theta_[0]/alpha_(0,0))*eta, *D_, *D_ );
538  //
539  //--------------------------------------------------------
540  // Update u if we need to.
541  // u = u - alpha*v
542  //
543  // Note: This is usually computed with alpha (above), but we're trying be memory efficient.
544  //--------------------------------------------------------
545  //
546  if (iter_%2 == 0) {
547  // Compute new U.
548  MVT::MvAddMv( STone, *U_, -alpha_(0,0), *V_, *U_ );
549 
550  // Update Au for the next iteration.
551  lp_->apply( *U_, *AU_ );
552  }
553  //
554  //--------------------------------------------------------
555  // Compute the new theta, c, eta, tau; i.e. the update to the least squares solution.
556  //--------------------------------------------------------
557  //
558  MVT::MvNorm( *W_, theta_ ); // theta = ||w|| / tau
559  theta_[0] /= tau_[0];
560  // cs = 1.0 / sqrt(1.0 + theta^2)
561  cs_[0] = MTone / Teuchos::ScalarTraits<MagnitudeType>::squareroot(MTone + theta_[0]*theta_[0]);
562  tau_[0] *= theta_[0]*cs_[0]; // tau = tau * theta * cs
563  eta = cs_[0]*cs_[0]*alpha_(0,0); // eta = cs^2 * alpha
564 
565  //
566  //--------------------------------------------------------
567  // Update the solution.
568  //--------------------------------------------------------
569  //
570  lp_->updateSolution( D_, true, eta );
571  //
572  if (iter_%2) {
573  //
574  //--------------------------------------------------------
575  // Compute the new rho, beta if we need to.
576  //--------------------------------------------------------
577  //
578  MVT::MvTransMv( STone, *Rtilde_, *W_, rho_ ); // rho = (r_tilde, w)
579  beta = rho_(0,0)/rho_old_(0,0); // beta = rho / rho_old
580  rho_old_(0,0) = rho_(0,0); // rho_old = rho
581  //
582  //--------------------------------------------------------
583  // Update u, v, and Au if we need to.
584  // Note: We are updating v in two stages to be memory efficient
585  //--------------------------------------------------------
586  //
587  MVT::MvAddMv( STone, *W_, beta, *U_, *U_ ); // u = w + beta*u
588 
589  // First stage of v update.
590  MVT::MvAddMv( STone, *AU_, beta, *V_, *V_ ); // v = Au + beta*v
591 
592  // Update Au.
593  lp_->apply( *U_, *AU_ ); // Au = A*u
594 
595  // Second stage of v update.
596  MVT::MvAddMv( STone, *AU_, beta, *V_, *V_ ); // v = Au + beta*v
597  }
598 
599  // Increment the iteration
600  iter_++;
601 
602  } // end while (sTest_->checkStatus(this) != Passed)
603  }
604 
605 } // namespace Belos
606 //
607 #endif // BELOS_TFQMR_ITER_HPP
608 //
609 // End of file BelosTFQMRIter.hpp
610 
611 
Teuchos::RCP< const MV > V
Collection of types and exceptions used within the Belos solvers.
This class implements the preconditioned transpose-free QMR algorithm for solving non-Hermitian linea...
Belos&#39;s basic output manager for sending information of select verbosity levels to the appropriate ou...
Teuchos::ScalarTraits< ScalarType > SCT
SCT::magnitudeType MagnitudeType
void initializeTFQMR(TFQMRIterState< ScalarType, MV > newstate)
Initialize the solver to an iterate, providing a complete state.
OperatorTraits< ScalarType, MV, OP > OPT
TFQMRIterateFailure(const std::string &what_arg)
void setBlockSize(int blockSize)
Set the blocksize.
Class which manages the output and verbosity of the Belos solvers.
Pure virtual base class for defining the status testing capabilities of Belos.
static T squareroot(T x)
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Declaration of basic traits for the multivector type.
void initialize()
Initialize the solver with the initial vectors from the linear problem or random data.
TFQMRIter(const Teuchos::RCP< LinearProblem< ScalarType, MV, OP > > &problem, const Teuchos::RCP< OutputManager< ScalarType > > &printer, const Teuchos::RCP< StatusTest< ScalarType, MV, OP > > &tester, Teuchos::ParameterList &params)
Belos::TFQMRIter constructor.
virtual ~TFQMRIter()
Belos::TFQMRIter destructor.
An extension of the MultiVecTraits class that adds a new vector length method.
Teuchos::RCP< const MV > R
The current residual basis.
Teuchos::RCP< const MV > getNativeResiduals(std::vector< MagnitudeType > *norms) const
Get the norms of the residuals native to the solver.
Teuchos::RCP< const MV > U
void resetNumIters(int iter=0)
Reset the iteration count.
Pure virtual base class which describes the basic interface to the linear solver iteration.
A pure virtual class for defining the status tests for the Belos iterative solvers.
Class which defines basic traits for the operator type.
Traits class which defines basic operations on multivectors.
Teuchos::RCP< MV > getCurrentUpdate() const
Get the current update to the linear system.
Teuchos::RCP< const MV > Rtilde
void iterate()
This method performs block TFQMR iterations until the status test indicates the need to stop or an er...
bool isInitialized()
States whether the solver has been initialized or not.
Teuchos::RCP< const MV > W
A linear system to solve, and its associated information.
Structure to contain pointers to TFQMRIter state variables.
Class which describes the linear problem to be solved by the iterative solver.
TFQMRIterInitFailure(const std::string &what_arg)
int getNumIters() const
Get the current iteration count.
MultiVecTraitsExt< ScalarType, MV > MVText
TFQMRIterInitFailure is thrown when the TFQMRIter object is unable to generate an initial iterate in ...
MultiVecTraits< ScalarType, MV > MVT
TFQMRIterateFailure is thrown when the TFQMRIter object is unable to compute the next iterate in the ...
int getBlockSize() const
Get the blocksize to be used by the iterative solver in solving this linear problem.
Class which defines basic traits for the operator type.
Parent class to all Belos exceptions.
Definition: BelosTypes.hpp:60
Teuchos::RCP< const MV > D
Belos header file which uses auto-configuration information to include necessary C++ headers...
const LinearProblem< ScalarType, MV, OP > & getProblem() const
Get a constant reference to the linear problem.
Templated virtual class for providing orthogonalization/orthonormalization methods with matrix-based ...
TFQMRIterState< ScalarType, MV > getState() const
Get the current state of the linear solver.