Belos  Version of the Day
BelosBlockCGSolMgr.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_SOLMGR_HPP
43 #define BELOS_BLOCK_CG_SOLMGR_HPP
44 
49 #include "BelosConfigDefs.hpp"
50 #include "BelosTypes.hpp"
51 
52 #include "BelosLinearProblem.hpp"
53 #include "BelosSolverManager.hpp"
54 
55 #include "BelosCGIter.hpp"
56 #include "BelosBlockCGIter.hpp"
62 #include "BelosStatusTestCombo.hpp"
64 #include "BelosOutputManager.hpp"
65 #include "Teuchos_BLAS.hpp"
66 #include "Teuchos_LAPACK.hpp"
67 #ifdef BELOS_TEUCHOS_TIME_MONITOR
68 # include "Teuchos_TimeMonitor.hpp"
69 #endif
70 #include <algorithm>
71 
88 namespace Belos {
89 
91 
92 
100  BlockCGSolMgrLinearProblemFailure(const std::string& what_arg) : BelosError(what_arg)
101  {}};
102 
109  class BlockCGSolMgrOrthoFailure : public BelosError {public:
110  BlockCGSolMgrOrthoFailure(const std::string& what_arg) : BelosError(what_arg)
111  {}};
112 
113  template<class ScalarType, class MV, class OP>
114  class BlockCGSolMgr : public SolverManager<ScalarType,MV,OP> {
115 
116  private:
119  typedef Teuchos::ScalarTraits<ScalarType> SCT;
120  typedef typename Teuchos::ScalarTraits<ScalarType>::magnitudeType MagnitudeType;
121  typedef Teuchos::ScalarTraits<MagnitudeType> MT;
122 
123  public:
124 
126 
127 
133  BlockCGSolMgr();
134 
163  BlockCGSolMgr( const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > &problem,
164  const Teuchos::RCP<Teuchos::ParameterList> &pl );
165 
167  virtual ~BlockCGSolMgr() {};
169 
171 
172 
174  return *problem_;
175  }
176 
179  Teuchos::RCP<const Teuchos::ParameterList> getValidParameters() const;
180 
183  Teuchos::RCP<const Teuchos::ParameterList> getCurrentParameters() const { return params_; }
184 
190  Teuchos::Array<Teuchos::RCP<Teuchos::Time> > getTimers() const {
191  return Teuchos::tuple(timerSolve_);
192  }
193 
199  MagnitudeType achievedTol() const {
200  return achievedTol_;
201  }
202 
204  int getNumIters() const {
205  return numIters_;
206  }
207 
210  bool isLOADetected() const { return false; }
211 
213 
215 
216 
218  void setProblem( const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > &problem ) { problem_ = problem; }
219 
221  void setParameters( const Teuchos::RCP<Teuchos::ParameterList> &params );
222 
224 
226 
227 
231  void reset( const ResetType type ) { if ((type & Belos::Problem) && !Teuchos::is_null(problem_)) problem_->setProblem(); }
233 
235 
236 
254  ReturnType solve();
255 
257 
260 
262  std::string description() const;
263 
265 
266  private:
267 
269  Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > problem_;
270 
272  Teuchos::RCP<OutputManager<ScalarType> > printer_;
274  Teuchos::RCP<std::ostream> outputStream_;
275 
280  Teuchos::RCP<StatusTest<ScalarType,MV,OP> > sTest_;
281 
283  Teuchos::RCP<StatusTestMaxIters<ScalarType,MV,OP> > maxIterTest_;
284 
286  Teuchos::RCP<StatusTestGenResNorm<ScalarType,MV,OP> > convTest_;
287 
289  Teuchos::RCP<StatusTestOutput<ScalarType,MV,OP> > outputTest_;
290 
292  Teuchos::RCP<MatOrthoManager<ScalarType,MV,OP> > ortho_;
293 
295  Teuchos::RCP<Teuchos::ParameterList> params_;
296 
297  //
298  // Default solver parameters.
299  //
300  static const MagnitudeType convtol_default_;
301  static const MagnitudeType orthoKappa_default_;
302  static const int maxIters_default_;
303  static const bool adaptiveBlockSize_default_;
304  static const bool showMaxResNormOnly_default_;
305  static const int blockSize_default_;
306  static const int verbosity_default_;
307  static const int outputStyle_default_;
308  static const int outputFreq_default_;
309  static const std::string label_default_;
310  static const std::string orthoType_default_;
311  static const Teuchos::RCP<std::ostream> outputStream_default_;
312 
313  //
314  // Current solver parameters and other values.
315  //
316 
318  MagnitudeType convtol_;
319 
321  MagnitudeType orthoKappa_;
322 
328  MagnitudeType achievedTol_;
329 
331  int maxIters_;
332 
334  int numIters_;
335 
336  int blockSize_, verbosity_, outputStyle_, outputFreq_;
337  bool adaptiveBlockSize_, showMaxResNormOnly_;
338  std::string orthoType_;
339 
341  std::string label_;
342 
344  Teuchos::RCP<Teuchos::Time> timerSolve_;
345 
347  bool isSet_;
348  };
349 
350 
351 // Default solver values.
352 template<class ScalarType, class MV, class OP>
353 const typename BlockCGSolMgr<ScalarType,MV,OP>::MagnitudeType BlockCGSolMgr<ScalarType,MV,OP>::convtol_default_ = 1e-8;
354 
355 template<class ScalarType, class MV, class OP>
356 const typename BlockCGSolMgr<ScalarType,MV,OP>::MagnitudeType BlockCGSolMgr<ScalarType,MV,OP>::orthoKappa_default_ = -1.0;
357 
358 template<class ScalarType, class MV, class OP>
360 
361 template<class ScalarType, class MV, class OP>
363 
364 template<class ScalarType, class MV, class OP>
366 
367 template<class ScalarType, class MV, class OP>
369 
370 template<class ScalarType, class MV, class OP>
372 
373 template<class ScalarType, class MV, class OP>
375 
376 template<class ScalarType, class MV, class OP>
378 
379 template<class ScalarType, class MV, class OP>
380 const std::string BlockCGSolMgr<ScalarType,MV,OP>::label_default_ = "Belos";
381 
382 template<class ScalarType, class MV, class OP>
383 const std::string BlockCGSolMgr<ScalarType,MV,OP>::orthoType_default_ = "DGKS";
384 
385 template<class ScalarType, class MV, class OP>
386 const Teuchos::RCP<std::ostream> BlockCGSolMgr<ScalarType,MV,OP>::outputStream_default_ = Teuchos::rcp(&std::cout,false);
387 
388 
389 // Empty Constructor
390 template<class ScalarType, class MV, class OP>
392  outputStream_(outputStream_default_),
393  convtol_(convtol_default_),
394  orthoKappa_(orthoKappa_default_),
395  achievedTol_(Teuchos::ScalarTraits<MagnitudeType>::zero()),
396  maxIters_(maxIters_default_),
397  numIters_(0),
398  blockSize_(blockSize_default_),
399  verbosity_(verbosity_default_),
400  outputStyle_(outputStyle_default_),
401  outputFreq_(outputFreq_default_),
402  adaptiveBlockSize_(adaptiveBlockSize_default_),
403  showMaxResNormOnly_(showMaxResNormOnly_default_),
404  orthoType_(orthoType_default_),
405  label_(label_default_),
406  isSet_(false)
407 {}
408 
409 
410 // Basic Constructor
411 template<class ScalarType, class MV, class OP>
413 BlockCGSolMgr(const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > &problem,
414  const Teuchos::RCP<Teuchos::ParameterList> &pl) :
415  problem_(problem),
416  outputStream_(outputStream_default_),
417  convtol_(convtol_default_),
418  orthoKappa_(orthoKappa_default_),
419  achievedTol_(Teuchos::ScalarTraits<MagnitudeType>::zero()),
420  maxIters_(maxIters_default_),
421  numIters_(0),
422  blockSize_(blockSize_default_),
423  verbosity_(verbosity_default_),
424  outputStyle_(outputStyle_default_),
425  outputFreq_(outputFreq_default_),
426  adaptiveBlockSize_(adaptiveBlockSize_default_),
427  showMaxResNormOnly_(showMaxResNormOnly_default_),
428  orthoType_(orthoType_default_),
429  label_(label_default_),
430  isSet_(false)
431 {
432  TEUCHOS_TEST_FOR_EXCEPTION(problem_.is_null(), std::invalid_argument,
433  "BlockCGSolMgr's constructor requires a nonnull LinearProblem instance.");
434 
435  // If the user passed in a nonnull parameter list, set parameters.
436  // Otherwise, the next solve() call will use default parameters,
437  // unless the user calls setParameters() first.
438  if (! pl.is_null()) {
439  setParameters (pl);
440  }
441 }
442 
443 template<class ScalarType, class MV, class OP>
444 void
446 setParameters (const Teuchos::RCP<Teuchos::ParameterList> &params)
447 {
448  // Create the internal parameter list if one doesn't already exist.
449  if (params_ == Teuchos::null) {
450  params_ = Teuchos::rcp( new Teuchos::ParameterList(*getValidParameters()) );
451  }
452  else {
453  params->validateParameters(*getValidParameters());
454  }
455 
456  // Check for maximum number of iterations
457  if (params->isParameter("Maximum Iterations")) {
458  maxIters_ = params->get("Maximum Iterations",maxIters_default_);
459 
460  // Update parameter in our list and in status test.
461  params_->set("Maximum Iterations", maxIters_);
462  if (maxIterTest_!=Teuchos::null)
463  maxIterTest_->setMaxIters( maxIters_ );
464  }
465 
466  // Check for blocksize
467  if (params->isParameter("Block Size")) {
468  blockSize_ = params->get("Block Size",blockSize_default_);
469  TEUCHOS_TEST_FOR_EXCEPTION(blockSize_ <= 0, std::invalid_argument,
470  "Belos::BlockCGSolMgr: \"Block Size\" must be strictly positive.");
471 
472  // Update parameter in our list.
473  params_->set("Block Size", blockSize_);
474  }
475 
476  // Check if the blocksize should be adaptive
477  if (params->isParameter("Adaptive Block Size")) {
478  adaptiveBlockSize_ = params->get("Adaptive Block Size",adaptiveBlockSize_default_);
479 
480  // Update parameter in our list.
481  params_->set("Adaptive Block Size", adaptiveBlockSize_);
482  }
483 
484  // Check to see if the timer label changed.
485  if (params->isParameter("Timer Label")) {
486  std::string tempLabel = params->get("Timer Label", label_default_);
487 
488  // Update parameter in our list and solver timer
489  if (tempLabel != label_) {
490  label_ = tempLabel;
491  params_->set("Timer Label", label_);
492  std::string solveLabel = label_ + ": BlockCGSolMgr total solve time";
493 #ifdef BELOS_TEUCHOS_TIME_MONITOR
494  timerSolve_ = Teuchos::TimeMonitor::getNewCounter(solveLabel);
495 #endif
496  if (ortho_ != Teuchos::null) {
497  ortho_->setLabel( label_ );
498  }
499  }
500  }
501 
502  // Check if the orthogonalization changed.
503  if (params->isParameter("Orthogonalization")) {
504  std::string tempOrthoType = params->get("Orthogonalization",orthoType_default_);
505  TEUCHOS_TEST_FOR_EXCEPTION( tempOrthoType != "DGKS" && tempOrthoType != "ICGS" && tempOrthoType != "IMGS",
506  std::invalid_argument,
507  "Belos::BlockCGSolMgr: \"Orthogonalization\" must be either \"DGKS\", \"ICGS\", or \"IMGS\".");
508  if (tempOrthoType != orthoType_) {
509  orthoType_ = tempOrthoType;
510  // Create orthogonalization manager
511  if (orthoType_=="DGKS") {
512  if (orthoKappa_ <= 0) {
513  ortho_ = Teuchos::rcp( new DGKSOrthoManager<ScalarType,MV,OP>( label_ ) );
514  }
515  else {
516  ortho_ = Teuchos::rcp( new DGKSOrthoManager<ScalarType,MV,OP>( label_ ) );
517  Teuchos::rcp_dynamic_cast<DGKSOrthoManager<ScalarType,MV,OP> >(ortho_)->setDepTol( orthoKappa_ );
518  }
519  }
520  else if (orthoType_=="ICGS") {
521  ortho_ = Teuchos::rcp( new ICGSOrthoManager<ScalarType,MV,OP>( label_ ) );
522  }
523  else if (orthoType_=="IMGS") {
524  ortho_ = Teuchos::rcp( new IMGSOrthoManager<ScalarType,MV,OP>( label_ ) );
525  }
526  }
527  }
528 
529  // Check which orthogonalization constant to use.
530  if (params->isParameter("Orthogonalization Constant")) {
531  orthoKappa_ = params->get("Orthogonalization Constant",orthoKappa_default_);
532 
533  // Update parameter in our list.
534  params_->set("Orthogonalization Constant",orthoKappa_);
535  if (orthoType_=="DGKS") {
536  if (orthoKappa_ > 0 && ortho_ != Teuchos::null) {
537  Teuchos::rcp_dynamic_cast<DGKSOrthoManager<ScalarType,MV,OP> >(ortho_)->setDepTol( orthoKappa_ );
538  }
539  }
540  }
541 
542  // Check for a change in verbosity level
543  if (params->isParameter("Verbosity")) {
544  if (Teuchos::isParameterType<int>(*params,"Verbosity")) {
545  verbosity_ = params->get("Verbosity", verbosity_default_);
546  } else {
547  verbosity_ = (int)Teuchos::getParameter<Belos::MsgType>(*params,"Verbosity");
548  }
549 
550  // Update parameter in our list.
551  params_->set("Verbosity", verbosity_);
552  if (printer_ != Teuchos::null)
553  printer_->setVerbosity(verbosity_);
554  }
555 
556  // Check for a change in output style
557  if (params->isParameter("Output Style")) {
558  if (Teuchos::isParameterType<int>(*params,"Output Style")) {
559  outputStyle_ = params->get("Output Style", outputStyle_default_);
560  } else {
561  outputStyle_ = (int)Teuchos::getParameter<Belos::OutputType>(*params,"Output Style");
562  }
563 
564  // Update parameter in our list.
565  params_->set("Output Style", outputStyle_);
566  outputTest_ = Teuchos::null;
567  }
568 
569  // output stream
570  if (params->isParameter("Output Stream")) {
571  outputStream_ = Teuchos::getParameter<Teuchos::RCP<std::ostream> >(*params,"Output Stream");
572 
573  // Update parameter in our list.
574  params_->set("Output Stream", outputStream_);
575  if (printer_ != Teuchos::null)
576  printer_->setOStream( outputStream_ );
577  }
578 
579  // frequency level
580  if (verbosity_ & Belos::StatusTestDetails) {
581  if (params->isParameter("Output Frequency")) {
582  outputFreq_ = params->get("Output Frequency", outputFreq_default_);
583  }
584 
585  // Update parameter in out list and output status test.
586  params_->set("Output Frequency", outputFreq_);
587  if (outputTest_ != Teuchos::null)
588  outputTest_->setOutputFrequency( outputFreq_ );
589  }
590 
591  // Create output manager if we need to.
592  if (printer_ == Teuchos::null) {
593  printer_ = Teuchos::rcp( new OutputManager<ScalarType>(verbosity_, outputStream_) );
594  }
595 
596  // Convergence
597  typedef Belos::StatusTestCombo<ScalarType,MV,OP> StatusTestCombo_t;
598  typedef Belos::StatusTestGenResNorm<ScalarType,MV,OP> StatusTestResNorm_t;
599 
600  // Check for convergence tolerance
601  if (params->isParameter("Convergence Tolerance")) {
602  convtol_ = params->get("Convergence Tolerance",convtol_default_);
603 
604  // Update parameter in our list and residual tests.
605  params_->set("Convergence Tolerance", convtol_);
606  if (convTest_ != Teuchos::null)
607  convTest_->setTolerance( convtol_ );
608  }
609 
610  if (params->isParameter("Show Maximum Residual Norm Only")) {
611  showMaxResNormOnly_ = Teuchos::getParameter<bool>(*params,"Show Maximum Residual Norm Only");
612 
613  // Update parameter in our list and residual tests
614  params_->set("Show Maximum Residual Norm Only", showMaxResNormOnly_);
615  if (convTest_ != Teuchos::null)
616  convTest_->setShowMaxResNormOnly( showMaxResNormOnly_ );
617  }
618 
619  // Create status tests if we need to.
620 
621  // Basic test checks maximum iterations and native residual.
622  if (maxIterTest_ == Teuchos::null)
623  maxIterTest_ = Teuchos::rcp( new StatusTestMaxIters<ScalarType,MV,OP>( maxIters_ ) );
624 
625  // Implicit residual test, using the native residual to determine if convergence was achieved.
626  if (convTest_ == Teuchos::null)
627  convTest_ = Teuchos::rcp( new StatusTestResNorm_t( convtol_, 1 ) );
628 
629  if (sTest_ == Teuchos::null)
630  sTest_ = Teuchos::rcp( new StatusTestCombo_t( StatusTestCombo_t::OR, maxIterTest_, convTest_ ) );
631 
632  if (outputTest_ == Teuchos::null) {
633 
634  // Create the status test output class.
635  // This class manages and formats the output from the status test.
636  StatusTestOutputFactory<ScalarType,MV,OP> stoFactory( outputStyle_ );
637  outputTest_ = stoFactory.create( printer_, sTest_, outputFreq_, Passed+Failed+Undefined );
638 
639  // Set the solver string for the output test
640  std::string solverDesc = " Block CG ";
641  outputTest_->setSolverDesc( solverDesc );
642 
643  }
644 
645  // Create orthogonalization manager if we need to.
646  if (ortho_ == Teuchos::null) {
647  if (orthoType_=="DGKS") {
648  if (orthoKappa_ <= 0) {
649  ortho_ = Teuchos::rcp( new DGKSOrthoManager<ScalarType,MV,OP>( label_ ) );
650  }
651  else {
652  ortho_ = Teuchos::rcp( new DGKSOrthoManager<ScalarType,MV,OP>( label_ ) );
653  Teuchos::rcp_dynamic_cast<DGKSOrthoManager<ScalarType,MV,OP> >(ortho_)->setDepTol( orthoKappa_ );
654  }
655  }
656  else if (orthoType_=="ICGS") {
657  ortho_ = Teuchos::rcp( new ICGSOrthoManager<ScalarType,MV,OP>( label_ ) );
658  }
659  else if (orthoType_=="IMGS") {
660  ortho_ = Teuchos::rcp( new IMGSOrthoManager<ScalarType,MV,OP>( label_ ) );
661  }
662  else {
663  TEUCHOS_TEST_FOR_EXCEPTION(orthoType_!="ICGS"&&orthoType_!="DGKS"&&orthoType_!="IMGS",std::logic_error,
664  "Belos::BlockCGSolMgr(): Invalid orthogonalization type.");
665  }
666  }
667 
668  // Create the timer if we need to.
669  if (timerSolve_ == Teuchos::null) {
670  std::string solveLabel = label_ + ": BlockCGSolMgr total solve time";
671 #ifdef BELOS_TEUCHOS_TIME_MONITOR
672  timerSolve_ = Teuchos::TimeMonitor::getNewCounter(solveLabel);
673 #endif
674  }
675 
676  // Inform the solver manager that the current parameters were set.
677  isSet_ = true;
678 }
679 
680 
681 template<class ScalarType, class MV, class OP>
682 Teuchos::RCP<const Teuchos::ParameterList>
684 {
685  static Teuchos::RCP<const Teuchos::ParameterList> validPL;
686 
687  // Set all the valid parameters and their default values.
688  if(is_null(validPL)) {
689  Teuchos::RCP<Teuchos::ParameterList> pl = Teuchos::parameterList();
690  pl->set("Convergence Tolerance", convtol_default_,
691  "The relative residual tolerance that needs to be achieved by the\n"
692  "iterative solver in order for the linear system to be declared converged.");
693  pl->set("Maximum Iterations", maxIters_default_,
694  "The maximum number of block iterations allowed for each\n"
695  "set of RHS solved.");
696  pl->set("Block Size", blockSize_default_,
697  "The number of vectors in each block.");
698  pl->set("Adaptive Block Size", adaptiveBlockSize_default_,
699  "Whether the solver manager should adapt to the block size\n"
700  "based on the number of RHS to solve.");
701  pl->set("Verbosity", verbosity_default_,
702  "What type(s) of solver information should be outputted\n"
703  "to the output stream.");
704  pl->set("Output Style", outputStyle_default_,
705  "What style is used for the solver information outputted\n"
706  "to the output stream.");
707  pl->set("Output Frequency", outputFreq_default_,
708  "How often convergence information should be outputted\n"
709  "to the output stream.");
710  pl->set("Output Stream", outputStream_default_,
711  "A reference-counted pointer to the output stream where all\n"
712  "solver output is sent.");
713  pl->set("Show Maximum Residual Norm Only", showMaxResNormOnly_default_,
714  "When convergence information is printed, only show the maximum\n"
715  "relative residual norm when the block size is greater than one.");
716  pl->set("Timer Label", label_default_,
717  "The string to use as a prefix for the timer labels.");
718  // pl->set("Restart Timers", restartTimers_);
719  pl->set("Orthogonalization", orthoType_default_,
720  "The type of orthogonalization to use: DGKS, ICGS, or IMGS.");
721  pl->set("Orthogonalization Constant",orthoKappa_default_,
722  "The constant used by DGKS orthogonalization to determine\n"
723  "whether another step of classical Gram-Schmidt is necessary.");
724  validPL = pl;
725  }
726  return validPL;
727 }
728 
729 
730 // solve()
731 template<class ScalarType, class MV, class OP>
733  using Teuchos::RCP;
734  using Teuchos::rcp;
735  using Teuchos::rcp_const_cast;
736  using Teuchos::rcp_dynamic_cast;
737 
738  // Set the current parameters if they were not set before. NOTE:
739  // This may occur if the user generated the solver manager with the
740  // default constructor and then didn't set any parameters using
741  // setParameters().
742  if (!isSet_) {
743  setParameters(Teuchos::parameterList(*getValidParameters()));
744  }
745 
746  Teuchos::BLAS<int,ScalarType> blas;
747  Teuchos::LAPACK<int,ScalarType> lapack;
748 
749  TEUCHOS_TEST_FOR_EXCEPTION( !problem_->isProblemSet(),
751  "Belos::BlockCGSolMgr::solve(): Linear problem is not ready, setProblem() "
752  "has not been called.");
753 
754  // Create indices for the linear systems to be solved.
755  int startPtr = 0;
756  int numRHS2Solve = MVT::GetNumberVecs( *(problem_->getRHS()) );
757  int numCurrRHS = ( numRHS2Solve < blockSize_) ? numRHS2Solve : blockSize_;
758 
759  std::vector<int> currIdx, currIdx2;
760  // If an adaptive block size is allowed then only the linear
761  // systems that need to be solved are solved. Otherwise, the index
762  // set is generated that informs the linear problem that some
763  // linear systems are augmented.
764  if ( adaptiveBlockSize_ ) {
765  blockSize_ = numCurrRHS;
766  currIdx.resize( numCurrRHS );
767  currIdx2.resize( numCurrRHS );
768  for (int i=0; i<numCurrRHS; ++i)
769  { currIdx[i] = startPtr+i; currIdx2[i]=i; }
770 
771  }
772  else {
773  currIdx.resize( blockSize_ );
774  currIdx2.resize( blockSize_ );
775  for (int i=0; i<numCurrRHS; ++i)
776  { currIdx[i] = startPtr+i; currIdx2[i]=i; }
777  for (int i=numCurrRHS; i<blockSize_; ++i)
778  { currIdx[i] = -1; currIdx2[i] = i; }
779  }
780 
781  // Inform the linear problem of the current linear system to solve.
782  problem_->setLSIndex( currIdx );
783 
785  // Set up the parameter list for the Iteration subclass.
786  Teuchos::ParameterList plist;
787  plist.set("Block Size",blockSize_);
788 
789  // Reset the output status test (controls all the other status tests).
790  outputTest_->reset();
791 
792  // Assume convergence is achieved, then let any failed convergence
793  // set this to false. "Innocent until proven guilty."
794  bool isConverged = true;
795 
797  // Set up the BlockCG Iteration subclass.
798 
799  RCP<CGIteration<ScalarType,MV,OP> > block_cg_iter;
800  if (blockSize_ == 1) {
801  // Standard (nonblock) CG is faster for the special case of a
802  // block size of 1.
803  block_cg_iter =
804  rcp (new CGIter<ScalarType,MV,OP> (problem_, printer_,
805  outputTest_, plist));
806  } else {
807  block_cg_iter =
808  rcp (new BlockCGIter<ScalarType,MV,OP> (problem_, printer_, outputTest_,
809  ortho_, plist));
810  }
811 
812 
813  // Enter solve() iterations
814  {
815 #ifdef BELOS_TEUCHOS_TIME_MONITOR
816  Teuchos::TimeMonitor slvtimer(*timerSolve_);
817 #endif
818 
819  while ( numRHS2Solve > 0 ) {
820  //
821  // Reset the active / converged vectors from this block
822  std::vector<int> convRHSIdx;
823  std::vector<int> currRHSIdx( currIdx );
824  currRHSIdx.resize(numCurrRHS);
825 
826  // Reset the number of iterations.
827  block_cg_iter->resetNumIters();
828 
829  // Reset the number of calls that the status test output knows about.
830  outputTest_->resetNumCalls();
831 
832  // Get the current residual for this block of linear systems.
833  RCP<MV> R_0 = MVT::CloneViewNonConst( *(rcp_const_cast<MV>(problem_->getInitResVec())), currIdx );
834 
835  // Set the new state and initialize the solver.
837  newstate.R = R_0;
838  block_cg_iter->initializeCG(newstate);
839 
840  while(1) {
841 
842  // tell block_cg_iter to iterate
843  try {
844  block_cg_iter->iterate();
845  //
846  // Check whether any of the linear systems converged.
847  //
848  if (convTest_->getStatus() == Passed) {
849  // At least one of the linear system(s) converged.
850  //
851  // Get the column indices of the linear systems that converged.
852  typedef StatusTestGenResNorm<ScalarType,MV,OP> conv_test_type;
853  std::vector<int> convIdx =
854  rcp_dynamic_cast<conv_test_type>(convTest_)->convIndices();
855 
856  // If the number of converged linear systems equals the
857  // number of linear systems currently being solved, then
858  // we are done with this block.
859  if (convIdx.size() == currRHSIdx.size())
860  break; // break from while(1){block_cg_iter->iterate()}
861 
862  // Inform the linear problem that we are finished with
863  // this current linear system.
864  problem_->setCurrLS();
865 
866  // Reset currRHSIdx to contain the right-hand sides that
867  // are left to converge for this block.
868  int have = 0;
869  std::vector<int> unconvIdx(currRHSIdx.size());
870  for (unsigned int i=0; i<currRHSIdx.size(); ++i) {
871  bool found = false;
872  for (unsigned int j=0; j<convIdx.size(); ++j) {
873  if (currRHSIdx[i] == convIdx[j]) {
874  found = true;
875  break;
876  }
877  }
878  if (!found) {
879  currIdx2[have] = currIdx2[i];
880  currRHSIdx[have++] = currRHSIdx[i];
881  }
882  else {
883  }
884  }
885  currRHSIdx.resize(have);
886  currIdx2.resize(have);
887 
888  // Set the remaining indices after deflation.
889  problem_->setLSIndex( currRHSIdx );
890 
891  // Get the current residual vector.
892  std::vector<MagnitudeType> norms;
893  R_0 = MVT::CloneCopy( *(block_cg_iter->getNativeResiduals(&norms)),currIdx2 );
894  for (int i=0; i<have; ++i) { currIdx2[i] = i; }
895 
896  // Set the new blocksize for the solver.
897  block_cg_iter->setBlockSize( have );
898 
899  // Set the new state and initialize the solver.
901  defstate.R = R_0;
902  block_cg_iter->initializeCG(defstate);
903  }
904  //
905  // None of the linear systems converged. Check whether the
906  // maximum iteration count was reached.
907  //
908  else if (maxIterTest_->getStatus() == Passed) {
909  isConverged = false; // None of the linear systems converged.
910  break; // break from while(1){block_cg_iter->iterate()}
911  }
912  //
913  // iterate() returned, but none of our status tests Passed.
914  // This indicates a bug.
915  //
916  else {
917  TEUCHOS_TEST_FOR_EXCEPTION(true,std::logic_error,
918  "Belos::BlockCGSolMgr::solve(): Neither the convergence test nor "
919  "the maximum iteration count test passed. Please report this bug "
920  "to the Belos developers.");
921  }
922  }
923  catch (const std::exception &e) {
924  std::ostream& err = printer_->stream (Errors);
925  err << "Error! Caught std::exception in CGIteration::iterate() at "
926  << "iteration " << block_cg_iter->getNumIters() << std::endl
927  << e.what() << std::endl;
928  throw;
929  }
930  }
931 
932  // Inform the linear problem that we are finished with this
933  // block linear system.
934  problem_->setCurrLS();
935 
936  // Update indices for the linear systems to be solved.
937  startPtr += numCurrRHS;
938  numRHS2Solve -= numCurrRHS;
939  if ( numRHS2Solve > 0 ) {
940  numCurrRHS = ( numRHS2Solve < blockSize_) ? numRHS2Solve : blockSize_;
941 
942  if ( adaptiveBlockSize_ ) {
943  blockSize_ = numCurrRHS;
944  currIdx.resize( numCurrRHS );
945  currIdx2.resize( numCurrRHS );
946  for (int i=0; i<numCurrRHS; ++i)
947  { currIdx[i] = startPtr+i; currIdx2[i] = i; }
948  }
949  else {
950  currIdx.resize( blockSize_ );
951  currIdx2.resize( blockSize_ );
952  for (int i=0; i<numCurrRHS; ++i)
953  { currIdx[i] = startPtr+i; currIdx2[i] = i; }
954  for (int i=numCurrRHS; i<blockSize_; ++i)
955  { currIdx[i] = -1; currIdx2[i] = i; }
956  }
957  // Set the next indices.
958  problem_->setLSIndex( currIdx );
959 
960  // Set the new blocksize for the solver.
961  block_cg_iter->setBlockSize( blockSize_ );
962  }
963  else {
964  currIdx.resize( numRHS2Solve );
965  }
966 
967  }// while ( numRHS2Solve > 0 )
968 
969  }
970 
971  // print final summary
972  sTest_->print( printer_->stream(FinalSummary) );
973 
974  // print timing information
975 #ifdef BELOS_TEUCHOS_TIME_MONITOR
976  // Calling summarize() requires communication in general, so don't
977  // call it unless the user wants to print out timing details.
978  // summarize() will do all the work even if it's passed a "black
979  // hole" output stream.
980  if (verbosity_ & TimingDetails) {
981  Teuchos::TimeMonitor::summarize( printer_->stream(TimingDetails) );
982  }
983 #endif
984 
985  // Save the iteration count for this solve.
986  numIters_ = maxIterTest_->getNumIters();
987 
988  // Save the convergence test value ("achieved tolerance") for this solve.
989  {
990  typedef StatusTestGenResNorm<ScalarType,MV,OP> conv_test_type;
991  // testValues is nonnull and not persistent.
992  const std::vector<MagnitudeType>* pTestValues =
993  rcp_dynamic_cast<conv_test_type>(convTest_)->getTestValue();
994 
995  TEUCHOS_TEST_FOR_EXCEPTION(pTestValues == NULL, std::logic_error,
996  "Belos::BlockCGSolMgr::solve(): The convergence test's getTestValue() "
997  "method returned NULL. Please report this bug to the Belos developers.");
998 
999  TEUCHOS_TEST_FOR_EXCEPTION(pTestValues->size() < 1, std::logic_error,
1000  "Belos::BlockCGSolMgr::solve(): The convergence test's getTestValue() "
1001  "method returned a vector of length zero. Please report this bug to the "
1002  "Belos developers.");
1003 
1004  // FIXME (mfh 12 Dec 2011) Does pTestValues really contain the
1005  // achieved tolerances for all vectors in the current solve(), or
1006  // just for the vectors from the last deflation?
1007  achievedTol_ = *std::max_element (pTestValues->begin(), pTestValues->end());
1008  }
1009 
1010  if (!isConverged) {
1011  return Unconverged; // return from BlockCGSolMgr::solve()
1012  }
1013  return Converged; // return from BlockCGSolMgr::solve()
1014 }
1015 
1016 // This method requires the solver manager to return a std::string that describes itself.
1017 template<class ScalarType, class MV, class OP>
1019 {
1020  std::ostringstream oss;
1021  oss << "Belos::BlockCGSolMgr<...,"<<Teuchos::ScalarTraits<ScalarType>::name()<<">";
1022  oss << "{";
1023  oss << "Ortho Type='"<<orthoType_<<"\', Block Size=" << blockSize_;
1024  oss << "}";
1025  return oss.str();
1026 }
1027 
1028 } // end Belos namespace
1029 
1030 #endif /* BELOS_BLOCK_CG_SOLMGR_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...
virtual ~BlockCGSolMgr()
Destructor.
void setParameters(const Teuchos::RCP< Teuchos::ParameterList > &params)
Set the parameters the solver manager should use to solve the linear problem.
Class which manages the output and verbosity of the Belos solvers.
int getNumIters() const
Get the iteration count for the most recent call to solve().
MagnitudeType achievedTol() const
Tolerance achieved by the last solve() invocation.
Teuchos::RCP< const Teuchos::ParameterList > getValidParameters() const
Get a parameter list containing the valid parameters for this object.
This class implements the preconditioned Conjugate Gradient (CG) iteration.
Definition: BelosCGIter.hpp:78
Structure to contain pointers to CGIteration state variables.
Belos concrete class for performing the conjugate-gradient (CG) iteration.
A factory class for generating StatusTestOutput objects.
bool isLOADetected() const
Return whether a loss of accuracy was detected by this solver during the most current solve...
Belos concrete class for performing the block conjugate-gradient (CG) iteration.
An implementation of StatusTestResNorm using a family of residual norms.
The Belos::BlockCGSolMgr provides a powerful and fully-featured solver manager over the CG and BlockC...
Belos::StatusTest class for specifying a maximum number of iterations.
BlockCGSolMgrLinearProblemFailure(const std::string &what_arg)
BlockCGSolMgrLinearProblemFailure is thrown when the linear problem is not setup (i.e.
static int GetNumberVecs(const MV &mv)
Obtain the number of vectors in mv.
A factory class for generating StatusTestOutput objects.
Iterated Modified Gram-Schmidt (IMGS) implementation of the Belos::OrthoManager class.
Traits class which defines basic operations on multivectors.
std::string description() const
Method to return description of the block CG solver manager.
Belos::StatusTest for logically combining several status tests.
Classical Gram-Schmidt (with DGKS correction) implementation of the Belos::OrthoManager class...
A Belos::StatusTest class for specifying a maximum number of iterations.
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).
ResetType
How to reset the solver.
Definition: BelosTypes.hpp:200
Pure virtual base class which describes the basic interface for a solver manager. ...
Teuchos::RCP< const Teuchos::ParameterList > getCurrentParameters() const
Get a parameter list containing the current parameters for this object.
A linear system to solve, and its associated information.
Class which describes the linear problem to be solved by the iterative solver.
BlockCGSolMgrOrthoFailure is thrown when the orthogonalization manager is unable to generate orthonor...
static Teuchos::RCP< MV > CloneCopy(const MV &mv)
Creates a new MV and copies contents of mv into the new vector (deep copy).
ReturnType
Whether the Belos solve converged for all linear systems.
Definition: BelosTypes.hpp:149
The Belos::SolverManager is a templated virtual base class that defines the basic interface that any ...
void reset(const ResetType type)
Performs a reset of the solver manager specified by the ResetType. This informs the solver manager th...
Iterated Classical Gram-Schmidt (ICGS) implementation of the Belos::OrthoManager class.
An implementation of the Belos::MatOrthoManager that performs orthogonalization using multiple steps ...
BlockCGSolMgrOrthoFailure(const std::string &what_arg)
An implementation of the Belos::MatOrthoManager that performs orthogonalization using multiple steps ...
Teuchos::RCP< StatusTestOutput< ScalarType, MV, OP > > create(const Teuchos::RCP< OutputManager< ScalarType > > &printer, Teuchos::RCP< StatusTest< ScalarType, MV, OP > > test, int mod, int printStates)
Create the StatusTestOutput object specified by the outputStyle.
ReturnType solve()
This method performs possibly repeated calls to the underlying linear solver&#39;s iterate() routine unti...
Belos::StatusTestResNorm for specifying general residual norm stopping criteria.
Teuchos::Array< Teuchos::RCP< Teuchos::Time > > getTimers() const
Return the timers for this object.
An implementation of the Belos::MatOrthoManager that performs orthogonalization using (potentially) m...
A class for extending the status testing capabilities of Belos via logical combinations.
BlockCGSolMgr()
Empty constructor for BlockCGSolMgr. This constructor takes no arguments and sets the default values ...
Class which defines basic traits for the operator type.
const LinearProblem< ScalarType, MV, OP > & getProblem() const
Return a reference to the linear problem being solved by this solver manager.
Parent class to all Belos exceptions.
Definition: BelosTypes.hpp:60
void setProblem(const Teuchos::RCP< LinearProblem< ScalarType, MV, OP > > &problem)
Set the linear problem that needs to be solved.
Belos header file which uses auto-configuration information to include necessary C++ headers...
This class implements the block, preconditioned Conjugate Gradient (CG) iteration.