Belos  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
BelosPseudoBlockCGIter.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_PSEUDO_BLOCK_CG_ITER_HPP
43 #define BELOS_PSEUDO_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"
63 #include "Teuchos_ScalarTraits.hpp"
65 #include "Teuchos_TimeMonitor.hpp"
66 
78 namespace Belos {
79 
80  template<class ScalarType, class MV, class OP>
81  class PseudoBlockCGIter : virtual public CGIteration<ScalarType,MV,OP> {
82 
83  public:
84 
85  //
86  // Convenience typedefs
87  //
93 
95 
96 
103  const Teuchos::RCP<OutputManager<ScalarType> > &printer,
105  Teuchos::ParameterList &params );
106 
108  virtual ~PseudoBlockCGIter() {};
110 
111 
113 
114 
128  void iterate();
129 
151 
155  void initialize()
156  {
158  initializeCG(empty);
159  }
160 
170  state.R = R_;
171  state.P = P_;
172  state.AP = AP_;
173  state.Z = Z_;
174  return state;
175  }
176 
178 
179 
181 
182 
184  int getNumIters() const { return iter_; }
185 
187  void resetNumIters( int iter = 0 ) { iter_ = iter; }
188 
191  Teuchos::RCP<const MV> getNativeResiduals( std::vector<MagnitudeType> *norms ) const { return R_; }
192 
194 
196  Teuchos::RCP<MV> getCurrentUpdate() const { return Teuchos::null; }
197 
199 
201 
202 
204  const LinearProblem<ScalarType,MV,OP>& getProblem() const { return *lp_; }
205 
207  int getBlockSize() const { return 1; }
208 
210  void setBlockSize(int blockSize) {
211  TEUCHOS_TEST_FOR_EXCEPTION(blockSize!=1,std::invalid_argument,
212  "Belos::PseudoBlockCGIter::setBlockSize(): Cannot use a block size that is not one.");
213  }
214 
216  bool isInitialized() { return initialized_; }
217 
219 
220  private:
221 
222  //
223  // Classes inputed through constructor that define the linear problem to be solved.
224  //
228 
229  //
230  // Algorithmic parameters
231  //
232  // numRHS_ is the current number of linear systems being solved.
233  int numRHS_;
234 
235  //
236  // Current solver state
237  //
238  // initialized_ specifies that the basis vectors have been initialized and the iterate() routine
239  // is capable of running; _initialize is controlled by the initialize() member method
240  // For the implications of the state of initialized_, please see documentation for initialize()
241  bool initialized_;
242 
243  // Current number of iterations performed.
244  int iter_;
245 
246  // Current number of iterations performed.
247  bool assertPositiveDefiniteness_;
248 
249  //
250  // State Storage
251  //
252  // Residual
253  Teuchos::RCP<MV> R_;
254  //
255  // Preconditioned residual
256  Teuchos::RCP<MV> Z_;
257  //
258  // Direction vector
259  Teuchos::RCP<MV> P_;
260  //
261  // Operator applied to direction vector
262  Teuchos::RCP<MV> AP_;
263 
264  };
265 
267  // Constructor.
268  template<class ScalarType, class MV, class OP>
270  const Teuchos::RCP<OutputManager<ScalarType> > &printer,
272  Teuchos::ParameterList &params ):
273  lp_(problem),
274  om_(printer),
275  stest_(tester),
276  numRHS_(0),
277  initialized_(false),
278  iter_(0),
279  assertPositiveDefiniteness_( params.get("Assert Positive Definiteness", true) )
280  {
281  }
282 
283 
285  // Initialize this iteration object
286  template <class ScalarType, class MV, class OP>
288  {
289  // Check if there is any multivector to clone from.
290  Teuchos::RCP<const MV> lhsMV = lp_->getCurrLHSVec();
291  Teuchos::RCP<const MV> rhsMV = lp_->getCurrRHSVec();
292  TEUCHOS_TEST_FOR_EXCEPTION((lhsMV==Teuchos::null && rhsMV==Teuchos::null),std::invalid_argument,
293  "Belos::PseudoBlockCGIter::initialize(): Cannot initialize state storage!");
294 
295  // Get the multivector that is not null.
296  Teuchos::RCP<const MV> tmp = ( (rhsMV!=Teuchos::null)? rhsMV: lhsMV );
297 
298  // Get the number of right-hand sides we're solving for now.
299  int numRHS = MVT::GetNumberVecs(*tmp);
300  numRHS_ = numRHS;
301 
302  // Initialize the state storage
303  // If the subspace has not be initialized before or has changed sizes, generate it using the LHS or RHS from lp_.
304  if (Teuchos::is_null(R_) || MVT::GetNumberVecs(*R_)!=numRHS_) {
305  R_ = MVT::Clone( *tmp, numRHS_ );
306  Z_ = MVT::Clone( *tmp, numRHS_ );
307  P_ = MVT::Clone( *tmp, numRHS_ );
308  AP_ = MVT::Clone( *tmp, numRHS_ );
309  }
310 
311  // NOTE: In CGIter R_, the initial residual, is required!!!
312  //
313  std::string errstr("Belos::BlockPseudoCGIter::initialize(): Specified multivectors must have a consistent length and width.");
314 
315  // Create convenience variables for zero and one.
316  const ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
318 
319  if (!Teuchos::is_null(newstate.R)) {
320 
321  TEUCHOS_TEST_FOR_EXCEPTION( MVText::GetGlobalLength(*newstate.R) != MVText::GetGlobalLength(*R_),
322  std::invalid_argument, errstr );
323  TEUCHOS_TEST_FOR_EXCEPTION( MVT::GetNumberVecs(*newstate.R) != numRHS_,
324  std::invalid_argument, errstr );
325 
326  // Copy basis vectors from newstate into V
327  if (newstate.R != R_) {
328  // copy over the initial residual (unpreconditioned).
329  MVT::MvAddMv( one, *newstate.R, zero, *newstate.R, *R_ );
330  }
331 
332  // Compute initial direction vectors
333  // Initially, they are set to the preconditioned residuals
334  //
335  if ( lp_->getLeftPrec() != Teuchos::null ) {
336  lp_->applyLeftPrec( *R_, *Z_ );
337  if ( lp_->getRightPrec() != Teuchos::null ) {
338  Teuchos::RCP<MV> tmp1 = MVT::Clone( *Z_, numRHS_ );
339  lp_->applyRightPrec( *Z_, *tmp1 );
340  Z_ = tmp1;
341  }
342  }
343  else if ( lp_->getRightPrec() != Teuchos::null ) {
344  lp_->applyRightPrec( *R_, *Z_ );
345  }
346  else {
347  Z_ = R_;
348  }
349  MVT::MvAddMv( one, *Z_, zero, *Z_, *P_ );
350  }
351  else {
352 
353  TEUCHOS_TEST_FOR_EXCEPTION(Teuchos::is_null(newstate.R),std::invalid_argument,
354  "Belos::CGIter::initialize(): CGStateIterState does not have initial residual.");
355  }
356 
357  // The solver is initialized
358  initialized_ = true;
359  }
360 
361 
363  // Iterate until the status test informs us we should stop.
364  template <class ScalarType, class MV, class OP>
366  {
367  //
368  // Allocate/initialize data structures
369  //
370  if (initialized_ == false) {
371  initialize();
372  }
373 
374  // Allocate memory for scalars.
375  int i=0;
376  std::vector<int> index(1);
377  std::vector<ScalarType> rHz( numRHS_ ), rHz_old( numRHS_ ), pAp( numRHS_ );
378  Teuchos::SerialDenseMatrix<int, ScalarType> alpha( numRHS_,numRHS_ ), beta( numRHS_,numRHS_ );
379 
380  // Create convenience variables for zero and one.
381  const ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
383 
384  // Get the current solution std::vector.
385  Teuchos::RCP<MV> cur_soln_vec = lp_->getCurrLHSVec();
386 
387  // Compute first <r,z> a.k.a. rHz
388  MVT::MvDot( *R_, *Z_, rHz );
389 
390  if ( assertPositiveDefiniteness_ )
391  for (i=0; i<numRHS_; ++i)
392  TEUCHOS_TEST_FOR_EXCEPTION( SCT::real(rHz[i]) < zero,
394  "Belos::PseudoBlockCGIter::iterate(): negative value for r^H*M*r encountered!" );
395 
397  // Iterate until the status test tells us to stop.
398  //
399  while (stest_->checkStatus(this) != Passed) {
400 
401  // Increment the iteration
402  iter_++;
403 
404  // Multiply the current direction std::vector by A and store in AP_
405  lp_->applyOp( *P_, *AP_ );
406 
407  // Compute alpha := <R_,Z_> / <P_,AP_>
408  MVT::MvDot( *P_, *AP_, pAp );
409 
410  for (i=0; i<numRHS_; ++i) {
411  if ( assertPositiveDefiniteness_ )
412  // Check that pAp[i] is a positive number!
413  TEUCHOS_TEST_FOR_EXCEPTION( SCT::real(pAp[i]) <= zero,
415  "Belos::PseudoBlockCGIter::iterate(): non-positive value for p^H*A*p encountered!" );
416 
417  alpha(i,i) = rHz[i] / pAp[i];
418  }
419 
420  //
421  // Update the solution std::vector x := x + alpha * P_
422  //
423  MVT::MvTimesMatAddMv( one, *P_, alpha, one, *cur_soln_vec );
424  lp_->updateSolution();
425  //
426  // Save the denominator of beta before residual is updated [ old <R_, Z_> ]
427  //
428  for (i=0; i<numRHS_; ++i) {
429  rHz_old[i] = rHz[i];
430  }
431  //
432  // Compute the new residual R_ := R_ - alpha * AP_
433  //
434  MVT::MvTimesMatAddMv( -one, *AP_, alpha, one, *R_ );
435  //
436  // Compute beta := [ new <R_, Z_> ] / [ old <R_, Z_> ],
437  // and the new direction std::vector p.
438  //
439  if ( lp_->getLeftPrec() != Teuchos::null ) {
440  lp_->applyLeftPrec( *R_, *Z_ );
441  if ( lp_->getRightPrec() != Teuchos::null ) {
442  Teuchos::RCP<MV> tmp = MVT::Clone( *Z_, numRHS_ );
443  lp_->applyRightPrec( *Z_, *tmp );
444  Z_ = tmp;
445  }
446  }
447  else if ( lp_->getRightPrec() != Teuchos::null ) {
448  lp_->applyRightPrec( *R_, *Z_ );
449  }
450  else {
451  Z_ = R_;
452  }
453  //
454  MVT::MvDot( *R_, *Z_, rHz );
455  if ( assertPositiveDefiniteness_ )
456  for (i=0; i<numRHS_; ++i)
457  TEUCHOS_TEST_FOR_EXCEPTION( SCT::real(rHz[i]) < zero,
459  "Belos::PseudoBlockCGIter::iterate(): negative value for r^H*M*r encountered!" );
460  //
461  // Update the search directions.
462  for (i=0; i<numRHS_; ++i) {
463  beta(i,i) = rHz[i] / rHz_old[i];
464  index[0] = i;
465  Teuchos::RCP<const MV> Z_i = MVT::CloneView( *Z_, index );
466  Teuchos::RCP<MV> P_i = MVT::CloneViewNonConst( *P_, index );
467  MVT::MvAddMv( one, *Z_i, beta(i,i), *P_i, *P_i );
468  }
469  //
470  } // end while (sTest_->checkStatus(this) != Passed)
471  }
472 
473 } // end Belos namespace
474 
475 #endif /* BELOS_PSEUDO_BLOCK_CG_ITER_HPP */
Teuchos::RCP< const MV > R
The current residual.
Collection of types and exceptions used within the Belos solvers.
void initialize()
Initialize the solver with the initial vectors from the linear problem or random data.
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.
bool is_null(const boost::shared_ptr< T > &p)
virtual ~PseudoBlockCGIter()
Destructor.
const LinearProblem< ScalarType, MV, OP > & getProblem() const
Get a constant reference to the linear problem.
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.
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.
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.
OperatorTraits< ScalarType, MV, OP > OPT
Traits class which defines basic operations on multivectors.
Teuchos::RCP< MV > getCurrentUpdate() const
Get the current update to the linear system.
void resetNumIters(int iter=0)
Reset the iteration count.
This class implements the pseudo-block CG iteration, where the basic CG algorithm is performed on all...
int getBlockSize() const
Get the blocksize to be used by the iterative solver in solving this linear problem.
MultiVecTraits< ScalarType, MV > MVT
void iterate()
This method performs CG iterations on each linear system until the status test indicates the need to ...
A linear system to solve, and its associated information.
int getNumIters() const
Get the current iteration count.
Class which describes the linear problem to be solved by the iterative solver.
MultiVecTraitsExt< ScalarType, MV > MVText
Teuchos::ScalarTraits< ScalarType > SCT
void initializeCG(CGIterationState< ScalarType, MV > newstate)
Initialize the solver to an iterate, providing a complete state.
CGIterationState< ScalarType, MV > getState() const
Get the current state of the linear solver.
Teuchos::RCP< const MV > Z
The current preconditioned residual.
PseudoBlockCGIter(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)
PseudoBlockCGIter constructor with linear problem, solver utilities, and parameter list of solver opt...
bool isInitialized()
States whether the solver has been initialized or not.
Class which defines basic traits for the operator type.
Teuchos::RCP< const MV > getNativeResiduals(std::vector< MagnitudeType > *norms) const
Get the norms of the residuals native to the solver.
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 ...