Belos  Version of the Day
BelosPseudoBlockStochasticCGIter.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_STOCHASTIC_CG_ITER_HPP
43 #define BELOS_PSEUDO_BLOCK_STOCHASTIC_CG_ITER_HPP
44 
49 #include "BelosConfigDefs.hpp"
50 #include "BelosTypes.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_SerialDenseMatrix.hpp"
62 #include "Teuchos_SerialDenseVector.hpp"
63 #include "Teuchos_ScalarTraits.hpp"
64 #include "Teuchos_ParameterList.hpp"
65 #include "Teuchos_TimeMonitor.hpp"
66 
82 namespace Belos {
83 
84  template<class ScalarType, class MV, class OP>
85  class PseudoBlockStochasticCGIter : virtual public StochasticCGIteration<ScalarType,MV,OP> {
86 
87  public:
88 
89  //
90  // Convenience typedefs
91  //
95  typedef Teuchos::ScalarTraits<ScalarType> SCT;
96  typedef typename SCT::magnitudeType MagnitudeType;
97 
99 
100 
106  PseudoBlockStochasticCGIter( const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > &problem,
107  const Teuchos::RCP<OutputManager<ScalarType> > &printer,
108  const Teuchos::RCP<StatusTest<ScalarType,MV,OP> > &tester,
109  Teuchos::ParameterList &params );
110 
114 
115 
117 
118 
132  void iterate();
133 
155 
159  void initialize()
160  {
162  initializeCG(empty);
163  }
164 
174  state.R = R_;
175  state.P = P_;
176  state.AP = AP_;
177  state.Z = Z_;
178  state.Y = Y_;
179  return state;
180  }
181 
183 
184 
186 
187 
189  int getNumIters() const { return iter_; }
190 
192  void resetNumIters( int iter = 0 ) { iter_ = iter; }
193 
196  Teuchos::RCP<const MV> getNativeResiduals( std::vector<MagnitudeType> *norms ) const { return R_; }
197 
199 
201  Teuchos::RCP<MV> getCurrentUpdate() const { return Teuchos::null; }
202 
204  Teuchos::RCP<MV> getStochasticVector() const { return Y_; }
205 
207 
209 
210 
212  const LinearProblem<ScalarType,MV,OP>& getProblem() const { return *lp_; }
213 
215  int getBlockSize() const { return 1; }
216 
218  void setBlockSize(int blockSize) {
219  TEUCHOS_TEST_FOR_EXCEPTION(blockSize!=1,std::invalid_argument,
220  "Belos::PseudoBlockStochasticCGIter::setBlockSize(): Cannot use a block size that is not one.");
221  }
222 
224  bool isInitialized() { return initialized_; }
225 
227 
228  private:
229 
231  inline ScalarType normal() {
232  // Do all of the calculations with doubles, because that is what the Odeh and Evans 1974 constants are for.
233  // Then cast to ScalarType.
234 
235  const double p0 = -0.322232431088;
236  const double p1 = -1.0;
237  const double p2 = -0.342242088547;
238  const double p3 = -0.204231210245e-1;
239  const double p4 = -0.453642210148e-4;
240  const double q0 = 0.993484626060e-1;
241  const double q1 = 0.588581570495;
242  const double q2 = 0.531103462366;
243  const double q3 = 0.103537752850;
244  const double q4 = 0.38560700634e-2;
245  double r,p,q,y,z;
246 
247  // Get a random number (-1,1) and rescale to (0,1).
248  r=0.5*(Teuchos::ScalarTraits<double>::random() + 1.0);
249 
250  // Odeh and Evans algorithm (as modified by Park & Geyer)
251  if(r < 0.5) y=std::sqrt(-2.0 * log(r));
252  else y=std::sqrt(-2.0 * log(1.0 - r));
253 
254  p = p0 + y * (p1 + y* (p2 + y * (p3 + y * p4)));
255  q = q0 + y * (q1 + y* (q2 + y * (q3 + y * q4)));
256 
257  if(r < 0.5) z = (p / q) - y;
258  else z = y - (p / q);
259 
260  return Teuchos::as<ScalarType,double>(z);
261  }
262 
263  //
264  // Classes inputed through constructor that define the linear problem to be solved.
265  //
266  const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > lp_;
267  const Teuchos::RCP<OutputManager<ScalarType> > om_;
268  const Teuchos::RCP<StatusTest<ScalarType,MV,OP> > stest_;
269 
270  //
271  // Algorithmic parameters
272  //
273  // numRHS_ is the current number of linear systems being solved.
274  int numRHS_;
275 
276  //
277  // Current solver state
278  //
279  // initialized_ specifies that the basis vectors have been initialized and the iterate() routine
280  // is capable of running; _initialize is controlled by the initialize() member method
281  // For the implications of the state of initialized_, please see documentation for initialize()
282  bool initialized_;
283 
284  // Current number of iterations performed.
285  int iter_;
286 
287  // Current number of iterations performed.
288  bool assertPositiveDefiniteness_;
289 
290  //
291  // State Storage
292  //
293  // Residual
294  Teuchos::RCP<MV> R_;
295  //
296  // Preconditioned residual
297  Teuchos::RCP<MV> Z_;
298  //
299  // Direction vector
300  Teuchos::RCP<MV> P_;
301  //
302  // Operator applied to direction vector
303  Teuchos::RCP<MV> AP_;
304  //
305  // Stochastic recurrence vector
306  Teuchos::RCP<MV> Y_;
307 
308 
309  };
310 
312  // Constructor.
313  template<class ScalarType, class MV, class OP>
315  const Teuchos::RCP<OutputManager<ScalarType> > &printer,
316  const Teuchos::RCP<StatusTest<ScalarType,MV,OP> > &tester,
317  Teuchos::ParameterList &params ):
318  lp_(problem),
319  om_(printer),
320  stest_(tester),
321  numRHS_(0),
322  initialized_(false),
323  iter_(0),
324  assertPositiveDefiniteness_( params.get("Assert Positive Definiteness", true) )
325  {
326  }
327 
328 
330  // Initialize this iteration object
331  template <class ScalarType, class MV, class OP>
333  {
334  // Check if there is any multivector to clone from.
335  Teuchos::RCP<const MV> lhsMV = lp_->getCurrLHSVec();
336  Teuchos::RCP<const MV> rhsMV = lp_->getCurrRHSVec();
337  TEUCHOS_TEST_FOR_EXCEPTION((lhsMV==Teuchos::null && rhsMV==Teuchos::null),std::invalid_argument,
338  "Belos::PseudoBlockStochasticCGIter::initialize(): Cannot initialize state storage!");
339 
340  // Get the multivector that is not null.
341  Teuchos::RCP<const MV> tmp = ( (rhsMV!=Teuchos::null)? rhsMV: lhsMV );
342 
343  // Get the number of right-hand sides we're solving for now.
344  int numRHS = MVT::GetNumberVecs(*tmp);
345  numRHS_ = numRHS;
346 
347  // Initialize the state storage
348  // If the subspace has not be initialized before or has changed sizes, generate it using the LHS or RHS from lp_.
349  if (Teuchos::is_null(R_) || MVT::GetNumberVecs(*R_)!=numRHS_) {
350  R_ = MVT::Clone( *tmp, numRHS_ );
351  Z_ = MVT::Clone( *tmp, numRHS_ );
352  P_ = MVT::Clone( *tmp, numRHS_ );
353  AP_ = MVT::Clone( *tmp, numRHS_ );
354  Y_ = MVT::Clone( *tmp, numRHS_ );
355  }
356 
357  // NOTE: In StochasticCGIter R_, the initial residual, is required!!!
358  //
359  std::string errstr("Belos::BlockPseudoStochasticCGIter::initialize(): Specified multivectors must have a consistent length and width.");
360 
361  // Create convenience variables for zero and one.
362  const ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
363  const MagnitudeType zero = Teuchos::ScalarTraits<MagnitudeType>::zero();
364 
365  if (!Teuchos::is_null(newstate.R)) {
366 
367  TEUCHOS_TEST_FOR_EXCEPTION( MVText::GetGlobalLength(*newstate.R) != MVText::GetGlobalLength(*R_),
368  std::invalid_argument, errstr );
369  TEUCHOS_TEST_FOR_EXCEPTION( MVT::GetNumberVecs(*newstate.R) != numRHS_,
370  std::invalid_argument, errstr );
371 
372  // Copy basis vectors from newstate into V
373  if (newstate.R != R_) {
374  // copy over the initial residual (unpreconditioned).
375  MVT::MvAddMv( one, *newstate.R, zero, *newstate.R, *R_ );
376  }
377 
378  // Compute initial direction vectors
379  // Initially, they are set to the preconditioned residuals
380 
381  if ( lp_->getLeftPrec() != Teuchos::null ) {
382  lp_->applyLeftPrec( *R_, *Z_ );
383  if ( lp_->getRightPrec() != Teuchos::null ) {
384  Teuchos::RCP<MV> tmp2 = MVT::Clone( *Z_, numRHS_ );
385  lp_->applyRightPrec( *Z_, *tmp2 );
386  Z_ = tmp2;
387  }
388  }
389  else if ( lp_->getRightPrec() != Teuchos::null ) {
390  lp_->applyRightPrec( *R_, *Z_ );
391  }
392  else {
393  Z_ = R_;
394  }
395  MVT::MvAddMv( one, *Z_, zero, *Z_, *P_ );
396  }
397  else {
398 
399  TEUCHOS_TEST_FOR_EXCEPTION(Teuchos::is_null(newstate.R),std::invalid_argument,
400  "Belos::StochasticCGIter::initialize(): CGStateIterState does not have initial residual.");
401  }
402 
403  // The solver is initialized
404  initialized_ = true;
405  }
406 
407 
409  // Iterate until the status test informs us we should stop.
410  template <class ScalarType, class MV, class OP>
412  {
413  //
414  // Allocate/initialize data structures
415  //
416  if (initialized_ == false) {
417  initialize();
418  }
419 
420  // Allocate memory for scalars.
421  int i=0;
422  std::vector<int> index(1);
423  std::vector<ScalarType> rHz( numRHS_ ), rHz_old( numRHS_ ), pAp( numRHS_ );
424  Teuchos::SerialDenseMatrix<int, ScalarType> alpha( numRHS_,numRHS_ ), beta( numRHS_,numRHS_ ), zeta(numRHS_,numRHS_);
425 
426  // Create convenience variables for zero and one.
427  const ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
428  const MagnitudeType zero = Teuchos::ScalarTraits<MagnitudeType>::zero();
429 
430  // Get the current solution std::vector.
431  Teuchos::RCP<MV> cur_soln_vec = lp_->getCurrLHSVec();
432 
433  // Compute first <r,z> a.k.a. rHz
434  MVT::MvDot( *R_, *Z_, rHz );
435 
436  if ( assertPositiveDefiniteness_ )
437  for (i=0; i<numRHS_; ++i)
438  TEUCHOS_TEST_FOR_EXCEPTION( SCT::real(rHz[i]) < zero,
440  "Belos::PseudoBlockStochasticCGIter::iterate(): negative value for r^H*M*r encountered!" );
441 
443  // Iterate until the status test tells us to stop.
444  //
445  while (stest_->checkStatus(this) != Passed) {
446 
447  // Increment the iteration
448  iter_++;
449 
450  // Multiply the current direction std::vector by A and store in AP_
451  lp_->applyOp( *P_, *AP_ );
452 
453  // Compute alpha := <R_,Z_> / <P_,AP_>
454  MVT::MvDot( *P_, *AP_, pAp );
455 
456  for (i=0; i<numRHS_; ++i) {
457  if ( assertPositiveDefiniteness_ )
458  // Check that pAp[i] is a positive number!
459  TEUCHOS_TEST_FOR_EXCEPTION( SCT::real(pAp[i]) <= zero,
461  "Belos::PseudoBlockStochasticCGIter::iterate(): non-positive value for p^H*A*p encountered!" );
462 
463  alpha(i,i) = rHz[i] / pAp[i];
464 
465 
466  // Compute the scaling parameter for the stochastic vector
467  ScalarType z = normal();
468  zeta(i,i) = z / Teuchos::ScalarTraits<ScalarType>::squareroot(pAp[i]);
469  }
470 
471  //
472  // Update the solution std::vector x := x + alpha * P_
473  //
474  MVT::MvTimesMatAddMv( one, *P_, alpha, one, *cur_soln_vec );
475  lp_->updateSolution();
476 
477  // Updates the stochastic vector y := y + zeta * P_
478  MVT::MvTimesMatAddMv( one, *P_, zeta, one, *Y_);
479 
480  //
481  // Save the denominator of beta before residual is updated [ old <R_, Z_> ]
482  //
483  for (i=0; i<numRHS_; ++i) {
484  rHz_old[i] = rHz[i];
485  }
486  //
487  // Compute the new residual R_ := R_ - alpha * AP_
488  //
489  MVT::MvTimesMatAddMv( -one, *AP_, alpha, one, *R_ );
490  //
491  // Compute beta := [ new <R_, Z_> ] / [ old <R_, Z_> ],
492  // and the new direction std::vector p.
493  //
494  if ( lp_->getLeftPrec() != Teuchos::null ) {
495  lp_->applyLeftPrec( *R_, *Z_ );
496  if ( lp_->getRightPrec() != Teuchos::null ) {
497  Teuchos::RCP<MV> tmp = MVT::Clone( *Z_, numRHS_ );
498  lp_->applyRightPrec( *Z_, *tmp );
499  Z_ = tmp;
500  }
501  }
502  else if ( lp_->getRightPrec() != Teuchos::null ) {
503  lp_->applyRightPrec( *R_, *Z_ );
504  }
505  else {
506  Z_ = R_;
507  }
508  //
509  MVT::MvDot( *R_, *Z_, rHz );
510  if ( assertPositiveDefiniteness_ )
511  for (i=0; i<numRHS_; ++i)
512  TEUCHOS_TEST_FOR_EXCEPTION( SCT::real(rHz[i]) < zero,
514  "Belos::PseudoBlockStochasticCGIter::iterate(): negative value for r^H*M*r encountered!" );
515  //
516  // Update the search directions.
517  for (i=0; i<numRHS_; ++i) {
518  beta(i,i) = rHz[i] / rHz_old[i];
519  index[0] = i;
520  Teuchos::RCP<const MV> Z_i = MVT::CloneView( *Z_, index );
521  Teuchos::RCP<MV> P_i = MVT::CloneViewNonConst( *P_, index );
522  MVT::MvAddMv( one, *Z_i, beta(i,i), *P_i, *P_i );
523  }
524  //
525  } // end while (sTest_->checkStatus(this) != Passed)
526  }
527 
528 } // end Belos namespace
529 
530 #endif /* BELOS_PSEUDO_BLOCK_STOCHASTIC_CG_ITER_HPP */
Pure virtual base class which augments the basic interface for a stochastic conjugate gradient linear...
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...
Class which manages the output and verbosity of the Belos solvers.
static void MvDot(const MV &mv, const MV &A, std::vector< ScalarType > &b)
Compute a vector b where the components are the individual dot-products of the i-th columns of A and ...
void initialize()
Initialize the solver with the initial vectors from the linear problem or random data.
void setBlockSize(int blockSize)
Set the blocksize.
void initializeCG(StochasticCGIterationState< ScalarType, MV > newstate)
Initialize the solver to an iterate, providing a complete state.
Pure virtual base class for defining the status testing capabilities of Belos.
Teuchos::RCP< MV > getStochasticVector() const
Get the stochastic vector.
static Teuchos::RCP< const MV > CloneView(const MV &mv, const std::vector< int > &index)
Creates a new const MV that shares the selected contents of mv (shallow copy).
Declaration of basic traits for the multivector type.
An extension of the MultiVecTraits class that adds a new vector length method.
Teuchos::RCP< const MV > Z
The current preconditioned residual.
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...
int getNumIters() const
Get the current iteration count.
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 .
const LinearProblem< ScalarType, MV, OP > & getProblem() const
Get a constant reference to the linear problem.
Traits class which defines basic operations on multivectors.
void resetNumIters(int iter=0)
Reset the iteration count.
StochasticCGIterationState< ScalarType, MV > getState() const
Get the current state of the linear solver.
static Teuchos::RCP< MV > CloneViewNonConst(MV &mv, const std::vector< int > &index)
Creates a new MV that shares the selected contents of mv (shallow copy).
static Teuchos::RCP< MV > Clone(const MV &mv, const int numvecs)
Creates a new empty MV containing numvecs columns.
Teuchos::RCP< const MV > getNativeResiduals(std::vector< MagnitudeType > *norms) const
Get the norms of the residuals native to the solver.
OperatorTraits< ScalarType, MV, OP > OPT
void iterate()
This method performs stochastic CG iterations on each linear system until the status test indicates t...
Teuchos::RCP< const MV > AP
The matrix A applied to current decent direction vector.
A linear system to solve, and its associated information.
bool isInitialized()
States whether the solver has been initialized or not.
Class which describes the linear problem to be solved by the iterative solver.
Teuchos::RCP< const MV > R
The current residual.
PseudoBlockStochasticCGIter(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)
PseudoBlockStochasticCGIter constructor with linear problem, solver utilities, and parameter list of ...
Teuchos::RCP< const MV > P
The current decent direction vector.
static void MvTimesMatAddMv(const ScalarType alpha, const MV &A, const Teuchos::SerialDenseMatrix< int, ScalarType > &B, const ScalarType beta, MV &mv)
Update mv with .
MultiVecTraitsExt< ScalarType, MV > MVText
int getBlockSize() const
Get the blocksize to be used by the iterative solver in solving this linear problem.
Teuchos::RCP< MV > getCurrentUpdate() const
Get the current update to the linear system.
This class implements the stochastic pseudo-block CG iteration, where the basic stochastic CG algorit...
static ptrdiff_t GetGlobalLength(const MV &mv)
Obtain the vector length of mv.
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 > Y
The current stochastic recurrence vector.
Templated virtual class for providing orthogonalization/orthonormalization methods with matrix-based ...
Structure to contain pointers to CGIteration state variables.