Belos  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
BelosCGIter.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_CG_ITER_HPP
43 #define BELOS_CG_ITER_HPP
44 
49 #include "BelosConfigDefs.hpp"
50 #include "BelosTypes.hpp"
51 #include "BelosCGIteration.hpp"
52 
53 #include "BelosLinearProblem.hpp"
54 #include "BelosOutputManager.hpp"
55 #include "BelosStatusTest.hpp"
56 #include "BelosOperatorTraits.hpp"
57 #include "BelosMultiVecTraits.hpp"
58 
61 #include "Teuchos_ScalarTraits.hpp"
63 #include "Teuchos_TimeMonitor.hpp"
64 
75 namespace Belos {
76 
77 template<class ScalarType, class MV, class OP>
78 class CGIter : virtual public CGIteration<ScalarType,MV,OP> {
79 
80  public:
81 
82  //
83  // Convenience typedefs
84  //
90 
92 
93 
100  const Teuchos::RCP<OutputManager<ScalarType> > &printer,
102  Teuchos::ParameterList &params );
103 
105  virtual ~CGIter() {};
107 
108 
110 
111 
124  void iterate();
125 
141 
145  void initialize()
146  {
148  initializeCG(empty);
149  }
150 
159  state.R = R_;
160  state.P = P_;
161  state.AP = AP_;
162  state.Z = Z_;
163  return state;
164  }
165 
167 
168 
170 
171 
173  int getNumIters() const { return iter_; }
174 
176  void resetNumIters( int iter = 0 ) { iter_ = iter; }
177 
180  Teuchos::RCP<const MV> getNativeResiduals( std::vector<MagnitudeType> *norms ) const { return R_; }
181 
183 
185  Teuchos::RCP<MV> getCurrentUpdate() const { return Teuchos::null; }
186 
188 
190 
191 
193  const LinearProblem<ScalarType,MV,OP>& getProblem() const { return *lp_; }
194 
196  int getBlockSize() const { return 1; }
197 
199  void setBlockSize(int blockSize) {
200  TEUCHOS_TEST_FOR_EXCEPTION(blockSize!=1,std::invalid_argument,
201  "Belos::CGIter::setBlockSize(): Cannot use a block size that is not one.");
202  }
203 
205  bool isInitialized() { return initialized_; }
206 
208 
209  private:
210 
211  //
212  // Internal methods
213  //
215  void setStateSize();
216 
217  //
218  // Classes inputed through constructor that define the linear problem to be solved.
219  //
223 
224  //
225  // Current solver state
226  //
227  // initialized_ specifies that the basis vectors have been initialized and the iterate() routine
228  // is capable of running; _initialize is controlled by the initialize() member method
229  // For the implications of the state of initialized_, please see documentation for initialize()
230  bool initialized_;
231 
232  // stateStorageInitialized_ specifies that the state storage has been initialized.
233  // This initialization may be postponed if the linear problem was generated without
234  // the right-hand side or solution vectors.
235  bool stateStorageInitialized_;
236 
237  // Current number of iterations performed.
238  int iter_;
239 
240  //
241  // State Storage
242  //
243  // Residual
244  Teuchos::RCP<MV> R_;
245  //
246  // Preconditioned residual
247  Teuchos::RCP<MV> Z_;
248  //
249  // Direction vector
250  Teuchos::RCP<MV> P_;
251  //
252  // Operator applied to direction vector
253  Teuchos::RCP<MV> AP_;
254 
255 };
256 
258  // Constructor.
259  template<class ScalarType, class MV, class OP>
261  const Teuchos::RCP<OutputManager<ScalarType> > &printer,
263  Teuchos::ParameterList &params ):
264  lp_(problem),
265  om_(printer),
266  stest_(tester),
267  initialized_(false),
268  stateStorageInitialized_(false),
269  iter_(0)
270  {
271  }
272 
274  // Setup the state storage.
275  template <class ScalarType, class MV, class OP>
277  {
278  if (!stateStorageInitialized_) {
279 
280  // Check if there is any multivector to clone from.
281  Teuchos::RCP<const MV> lhsMV = lp_->getLHS();
282  Teuchos::RCP<const MV> rhsMV = lp_->getRHS();
283  if (lhsMV == Teuchos::null && rhsMV == Teuchos::null) {
284  stateStorageInitialized_ = false;
285  return;
286  }
287  else {
288 
289  // Initialize the state storage
290  // If the subspace has not be initialized before, generate it using the LHS or RHS from lp_.
291  if (R_ == Teuchos::null) {
292  // Get the multivector that is not null.
293  Teuchos::RCP<const MV> tmp = ( (rhsMV!=Teuchos::null)? rhsMV: lhsMV );
294  TEUCHOS_TEST_FOR_EXCEPTION(tmp == Teuchos::null,std::invalid_argument,
295  "Belos::CGIter::setStateSize(): linear problem does not specify multivectors to clone from.");
296  R_ = MVT::Clone( *tmp, 1 );
297  Z_ = MVT::Clone( *tmp, 1 );
298  P_ = MVT::Clone( *tmp, 1 );
299  AP_ = MVT::Clone( *tmp, 1 );
300  }
301 
302  // State storage has now been initialized.
303  stateStorageInitialized_ = true;
304  }
305  }
306  }
307 
308 
310  // Initialize this iteration object
311  template <class ScalarType, class MV, class OP>
313  {
314  // Initialize the state storage if it isn't already.
315  if (!stateStorageInitialized_)
316  setStateSize();
317 
318  TEUCHOS_TEST_FOR_EXCEPTION(!stateStorageInitialized_,std::invalid_argument,
319  "Belos::CGIter::initialize(): Cannot initialize state storage!");
320 
321  // NOTE: In CGIter R_, the initial residual, is required!!!
322  //
323  std::string errstr("Belos::CGIter::initialize(): Specified multivectors must have a consistent length and width.");
324 
325  // Create convenience variables for zero and one.
326  const ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
327  const ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
328 
329  if (newstate.R != Teuchos::null) {
330 
331  TEUCHOS_TEST_FOR_EXCEPTION( MVText::GetGlobalLength(*newstate.R) != MVText::GetGlobalLength(*R_),
332  std::invalid_argument, errstr );
333  TEUCHOS_TEST_FOR_EXCEPTION( MVT::GetNumberVecs(*newstate.R) != 1,
334  std::invalid_argument, errstr );
335 
336  // Copy basis vectors from newstate into V
337  if (newstate.R != R_) {
338  // copy over the initial residual (unpreconditioned).
339  MVT::MvAddMv( one, *newstate.R, zero, *newstate.R, *R_ );
340  }
341 
342  // Compute initial direction vectors
343  // Initially, they are set to the preconditioned residuals
344  //
345  if ( lp_->getLeftPrec() != Teuchos::null ) {
346  lp_->applyLeftPrec( *R_, *Z_ );
347  if ( lp_->getRightPrec() != Teuchos::null ) {
348  Teuchos::RCP<MV> tmp = MVT::Clone( *Z_, 1 );
349  lp_->applyRightPrec( *Z_, *tmp );
350  Z_ = tmp;
351  }
352  }
353  else if ( lp_->getRightPrec() != Teuchos::null ) {
354  lp_->applyRightPrec( *R_, *Z_ );
355  }
356  else {
357  Z_ = R_;
358  }
359  MVT::MvAddMv( one, *Z_, zero, *Z_, *P_ );
360  }
361  else {
362 
363  TEUCHOS_TEST_FOR_EXCEPTION(newstate.R == Teuchos::null,std::invalid_argument,
364  "Belos::CGIter::initialize(): CGIterationState does not have initial residual.");
365  }
366 
367  // The solver is initialized
368  initialized_ = true;
369  }
370 
371 
373  // Iterate until the status test informs us we should stop.
374  template <class ScalarType, class MV, class OP>
376  {
377  //
378  // Allocate/initialize data structures
379  //
380  if (initialized_ == false) {
381  initialize();
382  }
383 
384  // Allocate memory for scalars.
387  Teuchos::SerialDenseMatrix<int,ScalarType> rHz( 1, 1 ), rHz_old( 1, 1 ), pAp( 1, 1 );
388 
389  // Create convenience variables for zero and one.
390  const ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
392 
393  // Get the current solution vector.
394  Teuchos::RCP<MV> cur_soln_vec = lp_->getCurrLHSVec();
395 
396  // Check that the current solution vector only has one column.
397  TEUCHOS_TEST_FOR_EXCEPTION( MVT::GetNumberVecs(*cur_soln_vec) != 1, CGIterateFailure,
398  "Belos::CGIter::iterate(): current linear system has more than one vector!" );
399 
400  // Compute first <r,z> a.k.a. rHz
401  MVT::MvTransMv( one, *R_, *Z_, rHz );
402 
404  // Iterate until the status test tells us to stop.
405  //
406  while (stest_->checkStatus(this) != Passed) {
407 
408  // Increment the iteration
409  iter_++;
410 
411  // Multiply the current direction vector by A and store in AP_
412  lp_->applyOp( *P_, *AP_ );
413 
414  // Compute alpha := <R_,Z_> / <P_,AP_>
415  MVT::MvTransMv( one, *P_, *AP_, pAp );
416  alpha(0,0) = rHz(0,0) / pAp(0,0);
417 
418  // Check that alpha is a positive number!
419  TEUCHOS_TEST_FOR_EXCEPTION( SCT::real(alpha(0,0)) <= zero, CGIterateFailure,
420  "Belos::CGIter::iterate(): non-positive value for p^H*A*p encountered!" );
421  //
422  // Update the solution vector x := x + alpha * P_
423  //
424  MVT::MvAddMv( one, *cur_soln_vec, alpha(0,0), *P_, *cur_soln_vec );
425  lp_->updateSolution();
426  //
427  // Save the denominator of beta before residual is updated [ old <R_, Z_> ]
428  //
429  rHz_old(0,0) = rHz(0,0);
430  //
431  // Compute the new residual R_ := R_ - alpha * AP_
432  //
433  MVT::MvAddMv( one, *R_, -alpha(0,0), *AP_, *R_ );
434  //
435  // Compute beta := [ new <R_, Z_> ] / [ old <R_, Z_> ],
436  // and the new direction vector p.
437  //
438  if ( lp_->getLeftPrec() != Teuchos::null ) {
439  lp_->applyLeftPrec( *R_, *Z_ );
440  if ( lp_->getRightPrec() != Teuchos::null ) {
441  Teuchos::RCP<MV> tmp = MVT::Clone( *Z_, 1 );
442  lp_->applyRightPrec( *Z_, *tmp );
443  Z_ = tmp;
444  }
445  }
446  else if ( lp_->getRightPrec() != Teuchos::null ) {
447  lp_->applyRightPrec( *R_, *Z_ );
448  }
449  else {
450  Z_ = R_;
451  }
452  //
453  MVT::MvTransMv( one, *R_, *Z_, rHz );
454  //
455  beta(0,0) = rHz(0,0) / rHz_old(0,0);
456  //
457  MVT::MvAddMv( one, *Z_, beta(0,0), *P_, *P_ );
458 
459  } // end while (sTest_->checkStatus(this) != Passed)
460  }
461 
462 } // end Belos namespace
463 
464 #endif /* BELOS_CG_ITER_HPP */
Teuchos::RCP< const MV > R
The current residual.
Collection of types and exceptions used within the Belos solvers.
Teuchos::ScalarTraits< ScalarType > SCT
Definition: BelosCGIter.hpp:88
Belos&#39;s basic output manager for sending information of select verbosity levels to the appropriate ou...
Class which manages the output and verbosity of the Belos solvers.
This class implements the preconditioned Conjugate Gradient (CG) iteration.
Definition: BelosCGIter.hpp:78
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.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Declaration of basic traits for the multivector type.
void setBlockSize(int blockSize)
Set the blocksize to be used by the iterative solver in solving this linear problem.
MultiVecTraitsExt< ScalarType, MV > MVText
Definition: BelosCGIter.hpp:86
void initializeCG(CGIterationState< ScalarType, MV > newstate)
Initialize the solver to an iterate, providing a complete state.
MultiVecTraits< ScalarType, MV > MVT
Definition: BelosCGIter.hpp:85
An extension of the MultiVecTraits class that adds a new vector length method.
A pure virtual class for defining the status tests for the Belos iterative solvers.
Class which defines basic traits for the operator type.
CGIter(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)
CGIter constructor with linear problem, solver utilities, and parameter list of solver options...
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.
Teuchos::RCP< const MV > getNativeResiduals(std::vector< MagnitudeType > *norms) const
Get the norms of the residuals native to the solver.
CGIterationState< ScalarType, MV > getState() const
Get the current state of the linear solver.
bool isInitialized()
States whether the solver has been initialized or not.
OperatorTraits< ScalarType, MV, OP > OPT
Definition: BelosCGIter.hpp:87
int getNumIters() const
Get the current iteration count.
Traits class which defines basic operations on multivectors.
int getBlockSize() const
Get the blocksize to be used by the iterative solver in solving this linear problem.
void iterate()
This method performs CG iterations until the status test indicates the need to stop or an error occur...
A linear system to solve, and its associated information.
Class which describes the linear problem to be solved by the iterative solver.
Teuchos::RCP< const MV > Z
The current preconditioned residual.
virtual ~CGIter()
Destructor.
void initialize()
Initialize the solver with the initial vectors from the linear problem or random data.
Teuchos::RCP< MV > getCurrentUpdate() const
Get the current update to the linear system.
SCT::magnitudeType MagnitudeType
Definition: BelosCGIter.hpp:89
void resetNumIters(int iter=0)
Reset the iteration count.
const LinearProblem< ScalarType, MV, OP > & getProblem() const
Get a constant reference to the linear problem.
Class which defines basic traits for the operator type.
Belos header file which uses auto-configuration information to include necessary C++ headers...
Teuchos::RCP< const MV > P
The current decent direction vector.