Belos  Version of the Day
BelosGCRODRSolMgr.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_GCRODR_SOLMGR_HPP
43 #define BELOS_GCRODR_SOLMGR_HPP
44 
49 #include "BelosConfigDefs.hpp"
50 #include "BelosTypes.hpp"
52 
53 #include "BelosLinearProblem.hpp"
54 #include "BelosSolverManager.hpp"
55 
56 #include "BelosGCRODRIter.hpp"
57 #include "BelosBlockFGmresIter.hpp"
60 #include "BelosStatusTestCombo.hpp"
62 #include "BelosOutputManager.hpp"
63 #include "Teuchos_BLAS.hpp"
64 #include "Teuchos_LAPACK.hpp"
65 #include "Teuchos_as.hpp"
66 #ifdef BELOS_TEUCHOS_TIME_MONITOR
67 #include "Teuchos_TimeMonitor.hpp"
68 #endif // BELOS_TEUCHOS_TIME_MONITOR
69 
106 namespace Belos {
107 
109 
110 
118  public:
119  GCRODRSolMgrLinearProblemFailure(const std::string& what_arg) : BelosError(what_arg) {}
120  };
121 
129  public:
130  GCRODRSolMgrOrthoFailure(const std::string& what_arg) : BelosError(what_arg) {}
131  };
132 
140  public:
141  GCRODRSolMgrLAPACKFailure(const std::string& what_arg) : BelosError(what_arg) {}
142  };
143 
151  public:
152  GCRODRSolMgrRecyclingFailure(const std::string& what_arg) : BelosError(what_arg) {}
153  };
154 
156 
157  template<class ScalarType, class MV, class OP>
158  class GCRODRSolMgr : public SolverManager<ScalarType,MV,OP> {
159 
160  private:
164  typedef Teuchos::ScalarTraits<ScalarType> SCT;
165  typedef typename Teuchos::ScalarTraits<ScalarType>::magnitudeType MagnitudeType;
166  typedef Teuchos::ScalarTraits<MagnitudeType> MT;
168 
169 
170  public:
172 
173 
179  GCRODRSolMgr();
180 
233  GCRODRSolMgr (const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > &problem,
234  const Teuchos::RCP<Teuchos::ParameterList> &pl);
235 
237  virtual ~GCRODRSolMgr() {};
239 
241 
242 
246  return *problem_;
247  }
248 
251  Teuchos::RCP<const Teuchos::ParameterList> getValidParameters() const;
252 
255  Teuchos::RCP<const Teuchos::ParameterList> getCurrentParameters() const {
256  return params_;
257  }
258 
264  Teuchos::Array<Teuchos::RCP<Teuchos::Time> > getTimers() const {
265  return Teuchos::tuple(timerSolve_);
266  }
267 
273  MagnitudeType achievedTol() const {
274  return achievedTol_;
275  }
276 
278  int getNumIters() const {
279  return numIters_;
280  }
281 
284  bool isLOADetected() const { return false; }
285 
287 
289 
290 
292  void setProblem( const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > &problem ) {
293  problem_ = problem;
294  }
295 
297  void setParameters( const Teuchos::RCP<Teuchos::ParameterList> &params );
298 
300 
302 
303 
307  void reset( const ResetType type ) {
308  if ((type & Belos::Problem) && !Teuchos::is_null(problem_)) problem_->setProblem();
309  else if (type & Belos::RecycleSubspace) keff = 0;
310  }
312 
314 
315 
332  ReturnType solve();
333 
335 
338 
340  std::string description() const;
341 
343 
344  private:
345 
346  // Called by all constructors; Contains init instructions common to all constructors
347  void init();
348 
349  // Initialize solver state storage
350  void initializeStateStorage();
351 
352  // Compute updated recycle space given existing recycle space and newly generated Krylov space
353  void buildRecycleSpace2(Teuchos::RCP<GCRODRIter<ScalarType,MV,OP> > gcrodr_iter);
354 
355  // Computes harmonic eigenpairs of projected matrix created during the priming solve.
356  // HH is the projected problem from the initial cycle of Gmres, it is (at least) of dimension m+1 x m.
357  // PP contains the harmonic eigenvectors corresponding to the recycledBlocks eigenvalues of smallest magnitude.
358  // The return value is the number of vectors needed to be stored, recycledBlocks or recycledBlocks+1.
359  int getHarmonicVecs1(int m,
360  const Teuchos::SerialDenseMatrix<int,ScalarType>& HH,
361  Teuchos::SerialDenseMatrix<int,ScalarType>& PP);
362 
363  // Computes harmonic eigenpairs of projected matrix created during one cycle.
364  // HH is the total block projected problem from the GCRO-DR algorithm, it is (at least) of dimension keff+m+1 x keff+m.
365  // VV is the Krylov vectors from the projected GMRES algorithm, which has (at least) m+1 vectors.
366  // PP contains the harmonic eigenvectors corresponding to the recycledBlocks eigenvalues of smallest magnitude.
367  // The return value is the number of vectors needed to be stored, recycledBlocks or recycledBlocks+1.
368  int getHarmonicVecs2(int keff, int m,
369  const Teuchos::SerialDenseMatrix<int,ScalarType>& HH,
370  const Teuchos::RCP<const MV>& VV,
371  Teuchos::SerialDenseMatrix<int,ScalarType>& PP);
372 
373  // Sort list of n floating-point numbers and return permutation vector
374  void sort(std::vector<ScalarType>& dlist, int n, std::vector<int>& iperm);
375 
376  // Lapack interface
377  Teuchos::LAPACK<int,ScalarType> lapack;
378 
379  // Linear problem.
380  Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > problem_;
381 
382  // Output manager.
383  Teuchos::RCP<OutputManager<ScalarType> > printer_;
384  Teuchos::RCP<std::ostream> outputStream_;
385 
386  // Status test.
387  Teuchos::RCP<StatusTest<ScalarType,MV,OP> > sTest_;
388  Teuchos::RCP<StatusTestMaxIters<ScalarType,MV,OP> > maxIterTest_;
389  Teuchos::RCP<StatusTest<ScalarType,MV,OP> > convTest_;
390  Teuchos::RCP<StatusTestGenResNorm<ScalarType,MV,OP> > expConvTest_, impConvTest_;
391  Teuchos::RCP<StatusTestOutput<ScalarType,MV,OP> > outputTest_;
392 
396  Teuchos::RCP<MatOrthoManager<ScalarType,MV,OP> > ortho_;
397 
398  // Current parameter list.
399  Teuchos::RCP<Teuchos::ParameterList> params_;
400 
401  // Default solver values.
402  static const MagnitudeType convTol_default_;
403  static const MagnitudeType orthoKappa_default_;
404  static const int maxRestarts_default_;
405  static const int maxIters_default_;
406  static const int numBlocks_default_;
407  static const int blockSize_default_;
408  static const int recycledBlocks_default_;
409  static const int verbosity_default_;
410  static const int outputStyle_default_;
411  static const int outputFreq_default_;
412  static const std::string impResScale_default_;
413  static const std::string expResScale_default_;
414  static const std::string label_default_;
415  static const std::string orthoType_default_;
416  static const Teuchos::RCP<std::ostream> outputStream_default_;
417 
418  // Current solver values.
419  MagnitudeType convTol_, orthoKappa_, achievedTol_;
420  int maxRestarts_, maxIters_, numIters_;
421  int verbosity_, outputStyle_, outputFreq_;
422  std::string orthoType_;
423  std::string impResScale_, expResScale_;
424 
426  // Solver State Storage
428  //
429  // The number of blocks and recycle blocks (m and k, respectively)
430  int numBlocks_, recycledBlocks_;
431  // Current size of recycled subspace
432  int keff;
433  //
434  // Residual vector
435  Teuchos::RCP<MV> r_;
436  //
437  // Search space
438  Teuchos::RCP<MV> V_;
439  //
440  // Recycled subspace and its image
441  Teuchos::RCP<MV> U_, C_;
442  //
443  // Updated recycle space and its image
444  Teuchos::RCP<MV> U1_, C1_;
445  //
446  // Storage used in constructing harmonic Ritz values/vectors
447  Teuchos::RCP<Teuchos::SerialDenseMatrix<int,ScalarType> > H2_;
448  Teuchos::RCP<Teuchos::SerialDenseMatrix<int,ScalarType> > H_;
449  Teuchos::RCP<Teuchos::SerialDenseMatrix<int,ScalarType> > B_;
450  Teuchos::RCP<Teuchos::SerialDenseMatrix<int,ScalarType> > PP_;
451  Teuchos::RCP<Teuchos::SerialDenseMatrix<int,ScalarType> > HP_;
452  std::vector<ScalarType> tau_;
453  std::vector<ScalarType> work_;
454  Teuchos::RCP<Teuchos::SerialDenseMatrix<int,ScalarType> > R_;
455  std::vector<int> ipiv_;
457 
458  // Timers.
459  std::string label_;
460  Teuchos::RCP<Teuchos::Time> timerSolve_;
461 
462  // Internal state variables.
463  bool isSet_;
464 
465  // Have we generated or regenerated a recycle space yet this solve?
466  bool builtRecycleSpace_;
467  };
468 
469 
470 // Default solver values.
471 template<class ScalarType, class MV, class OP>
472 const typename GCRODRSolMgr<ScalarType,MV,OP>::MagnitudeType GCRODRSolMgr<ScalarType,MV,OP>::convTol_default_ = 1e-8;
473 
474 template<class ScalarType, class MV, class OP>
475 const typename GCRODRSolMgr<ScalarType,MV,OP>::MagnitudeType GCRODRSolMgr<ScalarType,MV,OP>::orthoKappa_default_ = 0.0;
476 
477 template<class ScalarType, class MV, class OP>
479 
480 template<class ScalarType, class MV, class OP>
482 
483 template<class ScalarType, class MV, class OP>
485 
486 template<class ScalarType, class MV, class OP>
488 
489 template<class ScalarType, class MV, class OP>
491 
492 template<class ScalarType, class MV, class OP>
494 
495 template<class ScalarType, class MV, class OP>
497 
498 template<class ScalarType, class MV, class OP>
500 
501 template<class ScalarType, class MV, class OP>
502 const std::string GCRODRSolMgr<ScalarType,MV,OP>::impResScale_default_ = "Norm of Preconditioned Initial Residual";
503 
504 template<class ScalarType, class MV, class OP>
505 const std::string GCRODRSolMgr<ScalarType,MV,OP>::expResScale_default_ = "Norm of Initial Residual";
506 
507 template<class ScalarType, class MV, class OP>
508 const std::string GCRODRSolMgr<ScalarType,MV,OP>::label_default_ = "Belos";
509 
510 template<class ScalarType, class MV, class OP>
511 const std::string GCRODRSolMgr<ScalarType,MV,OP>::orthoType_default_ = "DGKS";
512 
513 template<class ScalarType, class MV, class OP>
514 const Teuchos::RCP<std::ostream> GCRODRSolMgr<ScalarType,MV,OP>::outputStream_default_ = Teuchos::rcp(&std::cout,false);
515 
516 
517 // Empty Constructor
518 template<class ScalarType, class MV, class OP>
520  init();
521 }
522 
523 
524 // Basic Constructor
525 template<class ScalarType, class MV, class OP>
527 GCRODRSolMgr(const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > &problem,
528  const Teuchos::RCP<Teuchos::ParameterList> &pl )
529 {
530  // Initialize local pointers to null, and initialize local variables
531  // to default values.
532  init();
533 
534  TEUCHOS_TEST_FOR_EXCEPTION(problem == Teuchos::null, std::invalid_argument,
535  "Belos::GCRODRSolMgr constructor: The solver manager's "
536  "constructor needs the linear problem argument 'problem' "
537  "to be non-null.");
538  problem_ = problem;
539 
540  // Set the parameters using the list that was passed in. If null,
541  // we defer initialization until a non-null list is set (by the
542  // client calling setParameters(), or by calling solve() -- in
543  // either case, a null parameter list indicates that default
544  // parameters should be used).
545  if (! is_null (pl))
546  setParameters (pl);
547 }
548 
549 // Common instructions executed in all constructors
550 template<class ScalarType, class MV, class OP>
552  outputStream_ = outputStream_default_;
553  convTol_ = convTol_default_;
554  orthoKappa_ = orthoKappa_default_;
555  maxRestarts_ = maxRestarts_default_;
556  maxIters_ = maxIters_default_;
557  numBlocks_ = numBlocks_default_;
558  recycledBlocks_ = recycledBlocks_default_;
559  verbosity_ = verbosity_default_;
560  outputStyle_ = outputStyle_default_;
561  outputFreq_ = outputFreq_default_;
562  orthoType_ = orthoType_default_;
563  impResScale_ = impResScale_default_;
564  expResScale_ = expResScale_default_;
565  label_ = label_default_;
566  isSet_ = false;
567  builtRecycleSpace_ = false;
568  keff = 0;
569  r_ = Teuchos::null;
570  V_ = Teuchos::null;
571  U_ = Teuchos::null;
572  C_ = Teuchos::null;
573  U1_ = Teuchos::null;
574  C1_ = Teuchos::null;
575  PP_ = Teuchos::null;
576  HP_ = Teuchos::null;
577  H2_ = Teuchos::null;
578  R_ = Teuchos::null;
579  H_ = Teuchos::null;
580  B_ = Teuchos::null;
581 }
582 
583 template<class ScalarType, class MV, class OP>
584 void
586 setParameters (const Teuchos::RCP<Teuchos::ParameterList> &params)
587 {
588  using Teuchos::isParameterType;
589  using Teuchos::getParameter;
590  using Teuchos::null;
591  using Teuchos::ParameterList;
592  using Teuchos::parameterList;
593  using Teuchos::RCP;
594  using Teuchos::rcp;
595  using Teuchos::rcp_dynamic_cast;
596  using Teuchos::rcpFromRef;
597  using Teuchos::Exceptions::InvalidParameter;
598  using Teuchos::Exceptions::InvalidParameterName;
599  using Teuchos::Exceptions::InvalidParameterType;
600 
601  // The default parameter list contains all parameters that
602  // GCRODRSolMgr understands, and none that it doesn't understand.
603  RCP<const ParameterList> defaultParams = getValidParameters();
604 
605  // Create the internal parameter list if one doesn't already exist.
606  //
607  // (mfh 28 Feb 2011, 10 Mar 2011) At the time this code was written,
608  // ParameterList did not have validators or validateParameters().
609  // This is why the code below carefully validates the parameters one
610  // by one and fills in defaults. This code could be made a lot
611  // shorter by using validators. To do so, we would have to define
612  // appropriate validators for all the parameters. (This would more
613  // or less just move all that validation code out of this routine
614  // into to getValidParameters().)
615  //
616  // For an analogous reason, GCRODRSolMgr defines default parameter
617  // values as class data, as well as in the default ParameterList.
618  // This redundancy could be removed by defining the default
619  // parameter values only in the default ParameterList (which
620  // documents each parameter as well -- handy!).
621  if (params_.is_null()) {
622  params_ = parameterList (*defaultParams);
623  } else {
624  // A common case for setParameters() is for it to be called at the
625  // beginning of the solve() routine. This follows the Belos
626  // pattern of delaying initialization until the last possible
627  // moment (when the user asks Belos to perform the solve). In
628  // this common case, we save ourselves a deep copy of the input
629  // parameter list.
630  if (params_ != params) {
631  // Make a deep copy of the input parameter list. This allows
632  // the caller to modify or change params later, without
633  // affecting the behavior of this solver. This solver will then
634  // only change its internal parameters if setParameters() is
635  // called again.
636  params_ = parameterList (*params);
637  }
638 
639  // Fill in any missing parameters and their default values. Also,
640  // throw an exception if the parameter list has any misspelled or
641  // "extra" parameters. If you don't like this behavior, you'll
642  // want to replace the line of code below with your desired
643  // validation scheme. Note that Teuchos currently only implements
644  // two options:
645  //
646  // 1. validateParameters() requires that params_ has all the
647  // parameters that the default list has, and none that it
648  // doesn't have.
649  //
650  // 2. validateParametersAndSetDefaults() fills in missing
651  // parameters in params_ using the default list, but requires
652  // that any parameter provided in params_ is also in the
653  // default list.
654  //
655  // Here is an easy way to ignore any "extra" or misspelled
656  // parameters: Make a deep copy of the default list, fill in any
657  // "missing" parameters from the _input_ list, and then validate
658  // the input list using the deep copy of the default list. We
659  // show this in code:
660  //
661  // RCP<ParameterList> defaultCopy = parameterList (*getValidParameters ());
662  // defaultCopy->validateParametersAndSetDefaults (params);
663  // params->validateParametersAndSetDefaults (defaultCopy);
664  //
665  // This method is not entirely robust, because the input list may
666  // have incorrect validators set for existing parameters in the
667  // default list. This would then cause "validation" of the
668  // default list to throw an exception. As a result, we've chosen
669  // for now to be intolerant of misspellings and "extra" parameters
670  // in the input list.
671  params_->validateParametersAndSetDefaults (*defaultParams);
672  }
673 
674  // Check for maximum number of restarts.
675  if (params->isParameter ("Maximum Restarts")) {
676  maxRestarts_ = params->get("Maximum Restarts", maxRestarts_default_);
677 
678  // Update parameter in our list.
679  params_->set ("Maximum Restarts", maxRestarts_);
680  }
681 
682  // Check for maximum number of iterations
683  if (params->isParameter ("Maximum Iterations")) {
684  maxIters_ = params->get ("Maximum Iterations", maxIters_default_);
685 
686  // Update parameter in our list and in status test.
687  params_->set ("Maximum Iterations", maxIters_);
688  if (! maxIterTest_.is_null())
689  maxIterTest_->setMaxIters (maxIters_);
690  }
691 
692  // Check for the maximum number of blocks.
693  if (params->isParameter ("Num Blocks")) {
694  numBlocks_ = params->get ("Num Blocks", numBlocks_default_);
695  TEUCHOS_TEST_FOR_EXCEPTION(numBlocks_ <= 0, std::invalid_argument,
696  "Belos::GCRODRSolMgr: The \"Num Blocks\" parameter must "
697  "be strictly positive, but you specified a value of "
698  << numBlocks_ << ".");
699  // Update parameter in our list.
700  params_->set ("Num Blocks", numBlocks_);
701  }
702 
703  // Check for the maximum number of blocks.
704  if (params->isParameter ("Num Recycled Blocks")) {
705  recycledBlocks_ = params->get ("Num Recycled Blocks",
706  recycledBlocks_default_);
707  TEUCHOS_TEST_FOR_EXCEPTION(recycledBlocks_ <= 0, std::invalid_argument,
708  "Belos::GCRODRSolMgr: The \"Num Recycled Blocks\" "
709  "parameter must be strictly positive, but you specified "
710  "a value of " << recycledBlocks_ << ".");
711  TEUCHOS_TEST_FOR_EXCEPTION(recycledBlocks_ >= numBlocks_, std::invalid_argument,
712  "Belos::GCRODRSolMgr: The \"Num Recycled Blocks\" "
713  "parameter must be less than the \"Num Blocks\" "
714  "parameter, but you specified \"Num Recycled Blocks\" "
715  "= " << recycledBlocks_ << " and \"Num Blocks\" = "
716  << numBlocks_ << ".");
717  // Update parameter in our list.
718  params_->set("Num Recycled Blocks", recycledBlocks_);
719  }
720 
721  // Check to see if the timer label changed. If it did, update it in
722  // the parameter list, and create a new timer with that label (if
723  // Belos was compiled with timers enabled).
724  if (params->isParameter ("Timer Label")) {
725  std::string tempLabel = params->get ("Timer Label", label_default_);
726 
727  // Update parameter in our list and solver timer
728  if (tempLabel != label_) {
729  label_ = tempLabel;
730  params_->set ("Timer Label", label_);
731  std::string solveLabel = label_ + ": GCRODRSolMgr total solve time";
732 #ifdef BELOS_TEUCHOS_TIME_MONITOR
733  timerSolve_ = Teuchos::TimeMonitor::getNewCounter (solveLabel);
734 #endif
735  if (ortho_ != Teuchos::null) {
736  ortho_->setLabel( label_ );
737  }
738  }
739  }
740 
741  // Check for a change in verbosity level
742  if (params->isParameter ("Verbosity")) {
743  if (isParameterType<int> (*params, "Verbosity")) {
744  verbosity_ = params->get ("Verbosity", verbosity_default_);
745  } else {
746  verbosity_ = (int) getParameter<Belos::MsgType> (*params, "Verbosity");
747  }
748  // Update parameter in our list.
749  params_->set ("Verbosity", verbosity_);
750  // If the output manager (printer_) is null, then we will
751  // instantiate it later with the correct verbosity.
752  if (! printer_.is_null())
753  printer_->setVerbosity (verbosity_);
754  }
755 
756  // Check for a change in output style
757  if (params->isParameter ("Output Style")) {
758  if (isParameterType<int> (*params, "Output Style")) {
759  outputStyle_ = params->get ("Output Style", outputStyle_default_);
760  } else {
761  outputStyle_ = (int) getParameter<OutputType> (*params, "Output Style");
762  }
763 
764  // Update parameter in our list.
765  params_->set ("Output Style", outputStyle_);
766  // We will (re)instantiate the output status test afresh below.
767  outputTest_ = null;
768  }
769 
770  // Get the output stream for the output manager.
771  //
772  // While storing the output stream in the parameter list (either as
773  // an RCP or as a nonconst reference) is convenient and safe for
774  // programming, it makes it impossible to serialize the parameter
775  // list, read it back in from the serialized representation, and get
776  // the same output stream as before. This is because output streams
777  // may be arbitrary constructed objects.
778  //
779  // In case the user tried reading in the parameter list from a
780  // serialized representation and the output stream can't be read
781  // back in, we set the output stream to point to std::cout. This
782  // ensures reasonable behavior.
783  if (params->isParameter ("Output Stream")) {
784  try {
785  outputStream_ = getParameter<RCP<std::ostream> > (*params, "Output Stream");
786  } catch (InvalidParameter&) {
787  outputStream_ = rcpFromRef (std::cout);
788  }
789  // We assume that a null output stream indicates that the user
790  // doesn't want to print anything, so we replace it with a "black
791  // hole" stream that prints nothing sent to it. (We can't use a
792  // null output stream, since the output manager always sends
793  // things it wants to print to the output stream.)
794  if (outputStream_.is_null()) {
795  outputStream_ = rcp (new Teuchos::oblackholestream);
796  }
797  // Update parameter in our list.
798  params_->set ("Output Stream", outputStream_);
799  // If the output manager (printer_) is null, then we will
800  // instantiate it later with the correct output stream.
801  if (! printer_.is_null()) {
802  printer_->setOStream (outputStream_);
803  }
804  }
805 
806  // frequency level
807  if (verbosity_ & Belos::StatusTestDetails) {
808  if (params->isParameter ("Output Frequency")) {
809  outputFreq_ = params->get ("Output Frequency", outputFreq_default_);
810  }
811 
812  // Update parameter in out list and output status test.
813  params_->set("Output Frequency", outputFreq_);
814  if (! outputTest_.is_null())
815  outputTest_->setOutputFrequency (outputFreq_);
816  }
817 
818  // Create output manager if we need to, using the verbosity level
819  // and output stream that we fetched above. We do this here because
820  // instantiating an OrthoManager using OrthoManagerFactory requires
821  // a valid OutputManager.
822  if (printer_.is_null()) {
823  printer_ = rcp (new OutputManager<ScalarType> (verbosity_, outputStream_));
824  }
825 
826  // Get the orthogonalization manager name ("Orthogonalization").
827  //
828  // Getting default values for the orthogonalization manager
829  // parameters ("Orthogonalization Parameters") requires knowing the
830  // orthogonalization manager name. Save it for later, and also
831  // record whether it's different than before.
833  bool changedOrthoType = false;
834  if (params->isParameter ("Orthogonalization")) {
835  const std::string& tempOrthoType =
836  params->get ("Orthogonalization", orthoType_default_);
837  // Ensure that the specified orthogonalization type is valid.
838  if (! factory.isValidName (tempOrthoType)) {
839  std::ostringstream os;
840  os << "Belos::GCRODRSolMgr: Invalid orthogonalization name \""
841  << tempOrthoType << "\". The following are valid options "
842  << "for the \"Orthogonalization\" name parameter: ";
843  factory.printValidNames (os);
844  throw std::invalid_argument (os.str());
845  }
846  if (tempOrthoType != orthoType_) {
847  changedOrthoType = true;
848  orthoType_ = tempOrthoType;
849  // Update parameter in our list.
850  params_->set ("Orthogonalization", orthoType_);
851  }
852  }
853 
854  // Get any parameters for the orthogonalization ("Orthogonalization
855  // Parameters"). If not supplied, the orthogonalization manager
856  // factory will supply default values.
857  //
858  // NOTE (mfh 12 Jan 2011) For the sake of backwards compatibility,
859  // if params has an "Orthogonalization Constant" parameter and the
860  // DGKS orthogonalization manager is to be used, the value of this
861  // parameter will override DGKS's "depTol" parameter.
862  //
863  // Users must supply the orthogonalization manager parameters as a
864  // sublist (supplying it as an RCP<ParameterList> would make the
865  // resulting parameter list not serializable).
866  RCP<ParameterList> orthoParams;
867  { // The nonmember function sublist() returns an RCP<ParameterList>,
868  // which is what we want here.
869  using Teuchos::sublist;
870  // Abbreviation to avoid typos.
871  const std::string paramName ("Orthogonalization Parameters");
872 
873  try {
874  orthoParams = sublist (params_, paramName, true);
875  } catch (InvalidParameter&) {
876  // We didn't get the parameter list from params, so get a
877  // default parameter list from the OrthoManagerFactory. Modify
878  // params_ so that it has the default parameter list, and set
879  // orthoParams to ensure it's a sublist of params_ (and not just
880  // a copy of one).
881  params_->set (paramName, factory.getDefaultParameters (orthoType_));
882  orthoParams = sublist (params_, paramName, true);
883  }
884  }
885  TEUCHOS_TEST_FOR_EXCEPTION(orthoParams.is_null(), std::logic_error,
886  "Failed to get orthogonalization parameters. "
887  "Please report this bug to the Belos developers.");
888 
889  // Instantiate a new MatOrthoManager subclass instance if necessary.
890  // If not necessary, then tell the existing instance about the new
891  // parameters.
892  if (ortho_.is_null() || changedOrthoType) {
893  // We definitely need to make a new MatOrthoManager, since either
894  // we haven't made one yet, or we've changed orthogonalization
895  // methods. Creating the orthogonalization manager requires that
896  // the OutputManager (printer_) already be initialized.
897  ortho_ = factory.makeMatOrthoManager (orthoType_, null, printer_,
898  label_, orthoParams);
899  } else {
900  // If the MatOrthoManager implements the ParameterListAcceptor
901  // mix-in interface, we can propagate changes to its parameters
902  // without reinstantiating the MatOrthoManager.
903  //
904  // We recommend that all MatOrthoManager subclasses implement
905  // Teuchos::ParameterListAcceptor, but do not (yet) require this.
906  typedef Teuchos::ParameterListAcceptor PLA;
907  RCP<PLA> pla = rcp_dynamic_cast<PLA> (ortho_);
908  if (pla.is_null()) {
909  // Oops, it's not a ParameterListAcceptor. We have to
910  // reinstantiate the MatOrthoManager in order to pass in the
911  // possibly new parameters.
912  ortho_ = factory.makeMatOrthoManager (orthoType_, null, printer_,
913  label_, orthoParams);
914  } else {
915  pla->setParameterList (orthoParams);
916  }
917  }
918 
919  // The DGKS orthogonalization accepts a "Orthogonalization Constant"
920  // parameter (also called kappa in the code, but not in the
921  // parameter list). If its value is provided in the given parameter
922  // list, and its value is positive, use it. Ignore negative values.
923  //
924  // NOTE (mfh 12 Jan 2011) This overrides the "depTol" parameter that
925  // may have been specified in "Orthogonalization Parameters". We
926  // retain this behavior for backwards compatibility.
927  if (params->isParameter ("Orthogonalization Constant")) {
928  const MagnitudeType orthoKappa =
929  params->get ("Orthogonalization Constant", orthoKappa_default_);
930  if (orthoKappa > 0) {
931  orthoKappa_ = orthoKappa;
932  // Update parameter in our list.
933  params_->set("Orthogonalization Constant", orthoKappa_);
934  // Only DGKS currently accepts this parameter.
935  if (orthoType_ == "DGKS" && ! ortho_.is_null()) {
936  typedef DGKSOrthoManager<ScalarType, MV, OP> ortho_man_type;
937  // This cast should always succeed; it's a bug
938  // otherwise. (If the cast fails, then orthoType_
939  // doesn't correspond to the OrthoManager subclass
940  // instance that we think we have, so we initialized the
941  // wrong subclass somehow.)
942  rcp_dynamic_cast<ortho_man_type>(ortho_)->setDepTol (orthoKappa_);
943  }
944  }
945  }
946 
947  // Convergence
948  typedef Belos::StatusTestCombo<ScalarType,MV,OP> StatusTestCombo_t;
949  typedef Belos::StatusTestGenResNorm<ScalarType,MV,OP> StatusTestResNorm_t;
950 
951  // Check for convergence tolerance
952  if (params->isParameter("Convergence Tolerance")) {
953  convTol_ = params->get ("Convergence Tolerance", convTol_default_);
954 
955  // Update parameter in our list and residual tests.
956  params_->set ("Convergence Tolerance", convTol_);
957  if (! impConvTest_.is_null())
958  impConvTest_->setTolerance (convTol_);
959  if (! expConvTest_.is_null())
960  expConvTest_->setTolerance (convTol_);
961  }
962 
963  // Check for a change in scaling, if so we need to build new residual tests.
964  if (params->isParameter ("Implicit Residual Scaling")) {
965  std::string tempImpResScale =
966  getParameter<std::string> (*params, "Implicit Residual Scaling");
967 
968  // Only update the scaling if it's different.
969  if (impResScale_ != tempImpResScale) {
970  ScaleType impResScaleType = convertStringToScaleType (tempImpResScale);
971  impResScale_ = tempImpResScale;
972 
973  // Update parameter in our list and residual tests
974  params_->set("Implicit Residual Scaling", impResScale_);
975  // NOTE (mfh 28 Feb 2011) StatusTestImpResNorm only lets you
976  // call defineScaleForm() once. The code below attempts to call
977  // defineScaleForm(); if the scale form has already been
978  // defined, it constructs a new StatusTestImpResNorm instance.
979  // StatusTestImpResNorm really should not expose the
980  // defineScaleForm() method, since it's serving an
981  // initialization purpose; all initialization should happen in
982  // the constructor whenever possible. In that case, the code
983  // below could be simplified into a single (re)instantiation.
984  if (! impConvTest_.is_null()) {
985  try {
986  impConvTest_->defineScaleForm (impResScaleType, Belos::TwoNorm);
987  }
988  catch (StatusTestError&) {
989  // Delete the convergence test so it gets constructed again.
990  impConvTest_ = null;
991  convTest_ = null;
992  }
993  }
994  }
995  }
996 
997  if (params->isParameter("Explicit Residual Scaling")) {
998  std::string tempExpResScale =
999  getParameter<std::string> (*params, "Explicit Residual Scaling");
1000 
1001  // Only update the scaling if it's different.
1002  if (expResScale_ != tempExpResScale) {
1003  ScaleType expResScaleType = convertStringToScaleType (tempExpResScale);
1004  expResScale_ = tempExpResScale;
1005 
1006  // Update parameter in our list and residual tests
1007  params_->set("Explicit Residual Scaling", expResScale_);
1008  // NOTE (mfh 28 Feb 2011) See note above on the (re)construction
1009  // of StatusTestImpResNorm.
1010  if (! expConvTest_.is_null()) {
1011  try {
1012  expConvTest_->defineScaleForm (expResScaleType, Belos::TwoNorm);
1013  }
1014  catch (StatusTestError&) {
1015  // Delete the convergence test so it gets constructed again.
1016  expConvTest_ = null;
1017  convTest_ = null;
1018  }
1019  }
1020  }
1021  }
1022  //
1023  // Create iteration stopping criteria ("status tests") if we need
1024  // to, by combining three different stopping criteria.
1025  //
1026  // First, construct maximum-number-of-iterations stopping criterion.
1027  if (maxIterTest_.is_null())
1028  maxIterTest_ = rcp (new StatusTestMaxIters<ScalarType,MV,OP> (maxIters_));
1029 
1030  // Implicit residual test, using the native residual to determine if
1031  // convergence was achieved.
1032  if (impConvTest_.is_null()) {
1033  impConvTest_ = rcp (new StatusTestResNorm_t (convTol_));
1034  impConvTest_->defineScaleForm (convertStringToScaleType (impResScale_),
1035  Belos::TwoNorm);
1036  }
1037 
1038  // Explicit residual test once the native residual is below the tolerance
1039  if (expConvTest_.is_null()) {
1040  expConvTest_ = rcp (new StatusTestResNorm_t (convTol_));
1041  expConvTest_->defineResForm (StatusTestResNorm_t::Explicit, Belos::TwoNorm);
1042  expConvTest_->defineScaleForm (convertStringToScaleType (expResScale_),
1043  Belos::TwoNorm);
1044  }
1045  // Convergence test first tests the implicit residual, then the
1046  // explicit residual if the implicit residual test passes.
1047  if (convTest_.is_null()) {
1048  convTest_ = rcp (new StatusTestCombo_t (StatusTestCombo_t::SEQ,
1049  impConvTest_,
1050  expConvTest_));
1051  }
1052  // Construct the complete iteration stopping criterion:
1053  //
1054  // "Stop iterating if the maximum number of iterations has been
1055  // reached, or if the convergence test passes."
1056  sTest_ = rcp (new StatusTestCombo_t (StatusTestCombo_t::OR,
1057  maxIterTest_,
1058  convTest_));
1059  // Create the status test output class.
1060  // This class manages and formats the output from the status test.
1061  StatusTestOutputFactory<ScalarType,MV,OP> stoFactory (outputStyle_);
1062  outputTest_ = stoFactory.create (printer_, sTest_, outputFreq_,
1064 
1065  // Set the solver string for the output test
1066  std::string solverDesc = " GCRODR ";
1067  outputTest_->setSolverDesc( solverDesc );
1068 
1069  // Create the timer if we need to.
1070  if (timerSolve_.is_null()) {
1071  std::string solveLabel = label_ + ": GCRODRSolMgr total solve time";
1072 #ifdef BELOS_TEUCHOS_TIME_MONITOR
1073  timerSolve_ = Teuchos::TimeMonitor::getNewCounter(solveLabel);
1074 #endif
1075  }
1076 
1077  // Inform the solver manager that the current parameters were set.
1078  isSet_ = true;
1079 }
1080 
1081 
1082 template<class ScalarType, class MV, class OP>
1083 Teuchos::RCP<const Teuchos::ParameterList>
1085 {
1086  using Teuchos::ParameterList;
1087  using Teuchos::parameterList;
1088  using Teuchos::RCP;
1089 
1090  static RCP<const ParameterList> validPL;
1091  if (is_null(validPL)) {
1092  RCP<ParameterList> pl = parameterList ();
1093 
1094  // Set all the valid parameters and their default values.
1095  pl->set("Convergence Tolerance", convTol_default_,
1096  "The relative residual tolerance that needs to be achieved by the\n"
1097  "iterative solver in order for the linear system to be declared converged.");
1098  pl->set("Maximum Restarts", maxRestarts_default_,
1099  "The maximum number of cycles allowed for each\n"
1100  "set of RHS solved.");
1101  pl->set("Maximum Iterations", maxIters_default_,
1102  "The maximum number of iterations allowed for each\n"
1103  "set of RHS solved.");
1104  // mfh 25 Oct 2010: "Block Size" must be 1 because GCRODR is
1105  // currently not a block method: i.e., it does not work on
1106  // multiple right-hand sides at once.
1107  pl->set("Block Size", blockSize_default_,
1108  "Block Size Parameter -- currently must be 1 for GCRODR");
1109  pl->set("Num Blocks", numBlocks_default_,
1110  "The maximum number of vectors allowed in the Krylov subspace\n"
1111  "for each set of RHS solved.");
1112  pl->set("Num Recycled Blocks", recycledBlocks_default_,
1113  "The maximum number of vectors in the recycled subspace." );
1114  pl->set("Verbosity", verbosity_default_,
1115  "What type(s) of solver information should be outputted\n"
1116  "to the output stream.");
1117  pl->set("Output Style", outputStyle_default_,
1118  "What style is used for the solver information outputted\n"
1119  "to the output stream.");
1120  pl->set("Output Frequency", outputFreq_default_,
1121  "How often convergence information should be outputted\n"
1122  "to the output stream.");
1123  pl->set("Output Stream", outputStream_default_,
1124  "A reference-counted pointer to the output stream where all\n"
1125  "solver output is sent.");
1126  pl->set("Implicit Residual Scaling", impResScale_default_,
1127  "The type of scaling used in the implicit residual convergence test.");
1128  pl->set("Explicit Residual Scaling", expResScale_default_,
1129  "The type of scaling used in the explicit residual convergence test.");
1130  pl->set("Timer Label", label_default_,
1131  "The string to use as a prefix for the timer labels.");
1132  // pl->set("Restart Timers", restartTimers_);
1133  {
1135  pl->set("Orthogonalization", orthoType_default_,
1136  "The type of orthogonalization to use. Valid options: " +
1137  factory.validNamesString());
1138  RCP<const ParameterList> orthoParams =
1139  factory.getDefaultParameters (orthoType_default_);
1140  pl->set ("Orthogonalization Parameters", *orthoParams,
1141  "Parameters specific to the type of orthogonalization used.");
1142  }
1143  pl->set("Orthogonalization Constant", orthoKappa_default_,
1144  "When using DGKS orthogonalization: the \"depTol\" constant, used "
1145  "to determine whether another step of classical Gram-Schmidt is "
1146  "necessary. Otherwise ignored.");
1147  validPL = pl;
1148  }
1149  return validPL;
1150 }
1151 
1152 // initializeStateStorage
1153 template<class ScalarType, class MV, class OP>
1155 
1156  ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
1157 
1158  // Check if there is any multivector to clone from.
1159  Teuchos::RCP<const MV> rhsMV = problem_->getRHS();
1160  if (rhsMV == Teuchos::null) {
1161  // Nothing to do
1162  return;
1163  }
1164  else {
1165 
1166  // Initialize the state storage
1167  TEUCHOS_TEST_FOR_EXCEPTION(static_cast<ptrdiff_t>(numBlocks_) > MVText::GetGlobalLength(*rhsMV),std::invalid_argument,
1168  "Belos::GCRODRSolMgr::initializeStateStorage(): Cannot generate a Krylov basis with dimension larger the operator!");
1169 
1170  // If the subspace has not been initialized before, generate it using the RHS from lp_.
1171  if (U_ == Teuchos::null) {
1172  U_ = MVT::Clone( *rhsMV, recycledBlocks_+1 );
1173  }
1174  else {
1175  // Generate U_ by cloning itself ONLY if more space is needed.
1176  if (MVT::GetNumberVecs(*U_) < recycledBlocks_+1) {
1177  Teuchos::RCP<const MV> tmp = U_;
1178  U_ = MVT::Clone( *tmp, recycledBlocks_+1 );
1179  }
1180  }
1181 
1182  // If the subspace has not been initialized before, generate it using the RHS from lp_.
1183  if (C_ == Teuchos::null) {
1184  C_ = MVT::Clone( *rhsMV, recycledBlocks_+1 );
1185  }
1186  else {
1187  // Generate C_ by cloning itself ONLY if more space is needed.
1188  if (MVT::GetNumberVecs(*C_) < recycledBlocks_+1) {
1189  Teuchos::RCP<const MV> tmp = C_;
1190  C_ = MVT::Clone( *tmp, recycledBlocks_+1 );
1191  }
1192  }
1193 
1194  // If the subspace has not been initialized before, generate it using the RHS from lp_.
1195  if (V_ == Teuchos::null) {
1196  V_ = MVT::Clone( *rhsMV, numBlocks_+1 );
1197  }
1198  else {
1199  // Generate V_ by cloning itself ONLY if more space is needed.
1200  if (MVT::GetNumberVecs(*V_) < numBlocks_+1) {
1201  Teuchos::RCP<const MV> tmp = V_;
1202  V_ = MVT::Clone( *tmp, numBlocks_+1 );
1203  }
1204  }
1205 
1206  // If the subspace has not been initialized before, generate it using the RHS from lp_.
1207  if (U1_ == Teuchos::null) {
1208  U1_ = MVT::Clone( *rhsMV, recycledBlocks_+1 );
1209  }
1210  else {
1211  // Generate U1_ by cloning itself ONLY if more space is needed.
1212  if (MVT::GetNumberVecs(*U1_) < recycledBlocks_+1) {
1213  Teuchos::RCP<const MV> tmp = U1_;
1214  U1_ = MVT::Clone( *tmp, recycledBlocks_+1 );
1215  }
1216  }
1217 
1218  // If the subspace has not been initialized before, generate it using the RHS from lp_.
1219  if (C1_ == Teuchos::null) {
1220  C1_ = MVT::Clone( *rhsMV, recycledBlocks_+1 );
1221  }
1222  else {
1223  // Generate C1_ by cloning itself ONLY if more space is needed.
1224  if (MVT::GetNumberVecs(*U1_) < recycledBlocks_+1) {
1225  Teuchos::RCP<const MV> tmp = C1_;
1226  C1_ = MVT::Clone( *tmp, recycledBlocks_+1 );
1227  }
1228  }
1229 
1230  // Generate r_ only if it doesn't exist
1231  if (r_ == Teuchos::null)
1232  r_ = MVT::Clone( *rhsMV, 1 );
1233 
1234  // Size of tau_ will change during computation, so just be sure it starts with appropriate size
1235  tau_.resize(recycledBlocks_+1);
1236 
1237  // Size of work_ will change during computation, so just be sure it starts with appropriate size
1238  work_.resize(recycledBlocks_+1);
1239 
1240  // Size of ipiv_ will change during computation, so just be sure it starts with appropriate size
1241  ipiv_.resize(recycledBlocks_+1);
1242 
1243  // Generate H2_ only if it doesn't exist, otherwise resize it.
1244  if (H2_ == Teuchos::null)
1245  H2_ = Teuchos::rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>( numBlocks_+recycledBlocks_+2, numBlocks_+recycledBlocks_+1 ) );
1246  else {
1247  if ( (H2_->numRows() != numBlocks_+recycledBlocks_+2) || (H2_->numCols() != numBlocks_+recycledBlocks_+1) )
1248  H2_->reshape( numBlocks_+recycledBlocks_+2, numBlocks_+recycledBlocks_+1 );
1249  }
1250  H2_->putScalar(zero);
1251 
1252  // Generate R_ only if it doesn't exist, otherwise resize it.
1253  if (R_ == Teuchos::null)
1254  R_ = Teuchos::rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>( recycledBlocks_+1, recycledBlocks_+1 ) );
1255  else {
1256  if ( (R_->numRows() != recycledBlocks_+1) || (R_->numCols() != recycledBlocks_+1) )
1257  R_->reshape( recycledBlocks_+1, recycledBlocks_+1 );
1258  }
1259  R_->putScalar(zero);
1260 
1261  // Generate PP_ only if it doesn't exist, otherwise resize it.
1262  if (PP_ == Teuchos::null)
1263  PP_ = Teuchos::rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>( numBlocks_+recycledBlocks_+2, recycledBlocks_+1 ) );
1264  else {
1265  if ( (PP_->numRows() != numBlocks_+recycledBlocks_+2) || (PP_->numCols() != recycledBlocks_+1) )
1266  PP_->reshape( numBlocks_+recycledBlocks_+2, recycledBlocks_+1 );
1267  }
1268 
1269  // Generate HP_ only if it doesn't exist, otherwise resize it.
1270  if (HP_ == Teuchos::null)
1271  HP_ = Teuchos::rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>( numBlocks_+recycledBlocks_+2, numBlocks_+recycledBlocks_+1 ) );
1272  else {
1273  if ( (HP_->numRows() != numBlocks_+recycledBlocks_+2) || (HP_->numCols() != numBlocks_+recycledBlocks_+1) )
1274  HP_->reshape( numBlocks_+recycledBlocks_+2, numBlocks_+recycledBlocks_+1 );
1275  }
1276 
1277  } // end else
1278 }
1279 
1280 
1281 // solve()
1282 template<class ScalarType, class MV, class OP>
1284  using Teuchos::RCP;
1285  using Teuchos::rcp;
1286 
1287  // Set the current parameters if they were not set before.
1288  // NOTE: This may occur if the user generated the solver manager with the default constructor and
1289  // then didn't set any parameters using setParameters().
1290  if (!isSet_) { setParameters( params_ ); }
1291 
1292  ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
1293  ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
1294  std::vector<int> index(numBlocks_+1);
1295 
1296  TEUCHOS_TEST_FOR_EXCEPTION(problem_ == Teuchos::null,GCRODRSolMgrLinearProblemFailure, "Belos::GCRODRSolMgr::solve(): Linear problem is not a valid object.");
1297 
1298  TEUCHOS_TEST_FOR_EXCEPTION(!problem_->isProblemSet(),GCRODRSolMgrLinearProblemFailure,"Belos::GCRODRSolMgr::solve(): Linear problem is not ready, setProblem() has not been called.");
1299 
1300  // Create indices for the linear systems to be solved.
1301  int numRHS2Solve = MVT::GetNumberVecs( *(problem_->getRHS()) );
1302  std::vector<int> currIdx(1);
1303  currIdx[0] = 0;
1304 
1305  // Inform the linear problem of the current linear system to solve.
1306  problem_->setLSIndex( currIdx );
1307 
1308  // Check the number of blocks and change them is necessary.
1309  ptrdiff_t dim = MVText::GetGlobalLength( *(problem_->getRHS()) );
1310  if (static_cast<ptrdiff_t>(numBlocks_) > dim) {
1311  numBlocks_ = Teuchos::as<int>(dim);
1312  printer_->stream(Warnings) <<
1313  "Warning! Requested Krylov subspace dimension is larger than operator dimension!" << std::endl <<
1314  " The maximum number of blocks allowed for the Krylov subspace will be adjusted to " << numBlocks_ << std::endl;
1315  params_->set("Num Blocks", numBlocks_);
1316  }
1317 
1318  // Assume convergence is achieved, then let any failed convergence set this to false.
1319  bool isConverged = true;
1320 
1321  // Initialize storage for all state variables
1322  initializeStateStorage();
1323 
1325  // Parameter list
1326  Teuchos::ParameterList plist;
1327 
1328  plist.set("Num Blocks",numBlocks_);
1329  plist.set("Recycled Blocks",recycledBlocks_);
1330 
1332  // GCRODR solver
1333 
1334  RCP<GCRODRIter<ScalarType,MV,OP> > gcrodr_iter;
1335  gcrodr_iter = rcp( new GCRODRIter<ScalarType,MV,OP>(problem_,printer_,outputTest_,ortho_,plist) );
1336  // Number of iterations required to generate initial recycle space (if needed)
1337  int prime_iterations = 0;
1338 
1339  // Enter solve() iterations
1340  {
1341 #ifdef BELOS_TEUCHOS_TIME_MONITOR
1342  Teuchos::TimeMonitor slvtimer(*timerSolve_);
1343 #endif
1344 
1345  while ( numRHS2Solve > 0 ) {
1346 
1347  // Set flag indicating recycle space has not been generated this solve
1348  builtRecycleSpace_ = false;
1349 
1350  // Reset the status test.
1351  outputTest_->reset();
1352 
1354  // Initialize recycled subspace for GCRODR
1355 
1356  // If there is a subspace to recycle, recycle it, otherwise generate the initial recycled subspace.
1357  if (keff > 0) {
1358  TEUCHOS_TEST_FOR_EXCEPTION(keff < recycledBlocks_,GCRODRSolMgrRecyclingFailure,
1359  "Belos::GCRODRSolMgr::solve(): Requested size of recycled subspace is not consistent with the current recycle subspace.");
1360 
1361  printer_->stream(Debug) << " Now solving RHS index " << currIdx[0] << " using recycled subspace of dimension " << keff << std::endl << std::endl;
1362  // Compute image of U_ under the new operator
1363  index.resize(keff);
1364  for (int ii=0; ii<keff; ++ii) { index[ii] = ii; }
1365  RCP<const MV> Utmp = MVT::CloneView( *U_, index );
1366  RCP<MV> Ctmp = MVT::CloneViewNonConst( *C_, index );
1367  problem_->apply( *Utmp, *Ctmp );
1368 
1369  RCP<MV> U1tmp = MVT::CloneViewNonConst( *U1_, index );
1370 
1371  // Orthogonalize this block
1372  // Get a matrix to hold the orthonormalization coefficients.
1373  Teuchos::SerialDenseMatrix<int,ScalarType> Rtmp( Teuchos::View, *R_, keff, keff );
1374  int rank = ortho_->normalize(*Ctmp, rcp(&Rtmp,false));
1375  // Throw an error if we could not orthogonalize this block
1376  TEUCHOS_TEST_FOR_EXCEPTION(rank != keff,GCRODRSolMgrOrthoFailure,"Belos::GCRODRSolMgr::solve(): Failed to compute orthonormal basis for initial recycled subspace.");
1377 
1378  // U_ = U_*R^{-1}
1379  // First, compute LU factorization of R
1380  int info = 0;
1381  ipiv_.resize(Rtmp.numRows());
1382  lapack.GETRF(Rtmp.numRows(),Rtmp.numCols(),Rtmp.values(),Rtmp.stride(),&ipiv_[0],&info);
1383  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, GCRODRSolMgrLAPACKFailure,"Belos::GCRODRSolMgr::solve(): LAPACK _GETRF failed to compute an LU factorization.");
1384 
1385  // Now, form inv(R)
1386  int lwork = Rtmp.numRows();
1387  work_.resize(lwork);
1388  lapack.GETRI(Rtmp.numRows(),Rtmp.values(),Rtmp.stride(),&ipiv_[0],&work_[0],lwork,&info);
1389  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, GCRODRSolMgrLAPACKFailure,"Belos::GCRODRSolMgr::solve(): LAPACK _GETRI failed to invert triangular matrix.");
1390 
1391  // U_ = U1_; (via a swap)
1392  MVT::MvTimesMatAddMv( one, *Utmp, Rtmp, zero, *U1tmp );
1393  std::swap(U_, U1_);
1394 
1395  // Must reinitialize after swap
1396  index.resize(keff);
1397  for (int ii=0; ii<keff; ++ii) { index[ii] = ii; }
1398  Ctmp = MVT::CloneViewNonConst( *C_, index );
1399  Utmp = MVT::CloneView( *U_, index );
1400 
1401  // Compute C_'*r_
1402  Teuchos::SerialDenseMatrix<int,ScalarType> Ctr(keff,1);
1403  problem_->computeCurrPrecResVec( &*r_ );
1404  MVT::MvTransMv( one, *Ctmp, *r_, Ctr );
1405 
1406  // Update solution ( x += U_*C_'*r_ )
1407  RCP<MV> update = MVT::Clone( *problem_->getCurrLHSVec(), 1 );
1408  MVT::MvInit( *update, 0.0 );
1409  MVT::MvTimesMatAddMv( one, *Utmp, Ctr, one, *update );
1410  problem_->updateSolution( update, true );
1411 
1412  // Update residual norm ( r -= C_*C_'*r_ )
1413  MVT::MvTimesMatAddMv( -one, *Ctmp, Ctr, one, *r_ );
1414 
1415  // We recycled space from previous call
1416  prime_iterations = 0;
1417 
1418  }
1419  else {
1420 
1421  // Do one cycle of Gmres to "prime the pump" if there is no subspace to recycle
1422  printer_->stream(Debug) << " No recycled subspace available for RHS index " << currIdx[0] << std::endl << std::endl;
1423 
1424  Teuchos::ParameterList primeList;
1425 
1426  // Tell the block solver that the block size is one.
1427  primeList.set("Num Blocks",numBlocks_);
1428  primeList.set("Recycled Blocks",0);
1429 
1430  // Create GCRODR iterator object to perform one cycle of GMRES.
1431  RCP<GCRODRIter<ScalarType,MV,OP> > gcrodr_prime_iter;
1432  gcrodr_prime_iter = rcp( new GCRODRIter<ScalarType,MV,OP>(problem_,printer_,outputTest_,ortho_,primeList) );
1433 
1434  // Create the first block in the current Krylov basis (residual).
1435  problem_->computeCurrPrecResVec( &*r_ );
1436  index.resize( 1 ); index[0] = 0;
1437  RCP<MV> v0 = MVT::CloneViewNonConst( *V_, index );
1438  MVT::SetBlock(*r_,index,*v0); // V(:,0) = r
1439 
1440  // Set the new state and initialize the solver.
1442  index.resize( numBlocks_+1 );
1443  for (int ii=0; ii<(numBlocks_+1); ++ii) { index[ii] = ii; }
1444  newstate.V = MVT::CloneViewNonConst( *V_, index );
1445  newstate.U = Teuchos::null;
1446  newstate.C = Teuchos::null;
1447  newstate.H = rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>( Teuchos::View, *H2_, numBlocks_+1, numBlocks_, recycledBlocks_+1, recycledBlocks_+1 ) );
1448  newstate.B = Teuchos::null;
1449  newstate.curDim = 0;
1450  gcrodr_prime_iter->initialize(newstate);
1451 
1452  // Perform one cycle of GMRES
1453  bool primeConverged = false;
1454  try {
1455  gcrodr_prime_iter->iterate();
1456 
1457  // Check convergence first
1458  if ( convTest_->getStatus() == Passed ) {
1459  // we have convergence
1460  primeConverged = true;
1461  }
1462  }
1463  catch (const GCRODRIterOrthoFailure &e) {
1464  // Try to recover the most recent least-squares solution
1465  gcrodr_prime_iter->updateLSQR( gcrodr_prime_iter->getCurSubspaceDim() );
1466 
1467  // Check to see if the most recent least-squares solution yielded convergence.
1468  sTest_->checkStatus( &*gcrodr_prime_iter );
1469  if (convTest_->getStatus() == Passed)
1470  primeConverged = true;
1471  }
1472  catch (const std::exception &e) {
1473  printer_->stream(Errors) << "Error! Caught exception in GCRODRIter::iterate() at iteration "
1474  << gcrodr_prime_iter->getNumIters() << std::endl
1475  << e.what() << std::endl;
1476  throw;
1477  }
1478  // Record number of iterations in generating initial recycle spacec
1479  prime_iterations = gcrodr_prime_iter->getNumIters();
1480 
1481  // Update the linear problem.
1482  RCP<MV> update = gcrodr_prime_iter->getCurrentUpdate();
1483  problem_->updateSolution( update, true );
1484 
1485  // Get the state.
1486  newstate = gcrodr_prime_iter->getState();
1487  int p = newstate.curDim;
1488 
1489  // Compute harmonic Ritz vectors
1490  // NOTE: The storage for the harmonic Ritz vectors (PP) is made one column larger
1491  // just in case we split a complex conjugate pair.
1492  // NOTE: Generate a recycled subspace only if we have enough vectors. If we converged
1493  // too early, move on to the next linear system and try to generate a subspace again.
1494  if (recycledBlocks_ < p+1) {
1495  int info = 0;
1496  RCP<Teuchos::SerialDenseMatrix<int,ScalarType> > PPtmp = rcp (new Teuchos::SerialDenseMatrix<int,ScalarType> ( Teuchos::View, *PP_, p, recycledBlocks_+1 ) );
1497  // getHarmonicVecs1 assumes PP has recycledBlocks_+1 columns available
1498  keff = getHarmonicVecs1( p, *newstate.H, *PPtmp );
1499  // Hereafter, only keff columns of PP are needed
1500  PPtmp = rcp (new Teuchos::SerialDenseMatrix<int,ScalarType> ( Teuchos::View, *PP_, p, keff ) );
1501  // Now get views into C, U, V
1502  index.resize(keff);
1503  for (int ii=0; ii<keff; ++ii) { index[ii] = ii; }
1504  RCP<MV> Ctmp = MVT::CloneViewNonConst( *C_, index );
1505  RCP<MV> Utmp = MVT::CloneViewNonConst( *U_, index );
1506  RCP<MV> U1tmp = MVT::CloneViewNonConst( *U1_, index );
1507  index.resize(p);
1508  for (int ii=0; ii < p; ++ii) { index[ii] = ii; }
1509  RCP<const MV> Vtmp = MVT::CloneView( *V_, index );
1510 
1511  // Form U (the subspace to recycle)
1512  // U = newstate.V(:,1:p) * PP;
1513  MVT::MvTimesMatAddMv( one, *Vtmp, *PPtmp, zero, *U1tmp );
1514 
1515  // Form orthonormalized C and adjust U so that C = A*U
1516 
1517  // First, compute [Q, R] = qr(H*P);
1518 
1519  // Step #1: Form HP = H*P
1520  Teuchos::SerialDenseMatrix<int,ScalarType> Htmp( Teuchos::View, *H2_, p+1, p, recycledBlocks_+1,recycledBlocks_+1);
1521  Teuchos::SerialDenseMatrix<int,ScalarType> HPtmp( Teuchos::View, *HP_, p+1, keff );
1522  HPtmp.multiply( Teuchos::NO_TRANS, Teuchos::NO_TRANS, one, Htmp, *PPtmp, zero );
1523 
1524  // Step #1.5: Perform workspace size query for QR factorization of HP (the worksize will be placed in work_[0])
1525  int lwork = -1;
1526  tau_.resize(keff);
1527  lapack.GEQRF(HPtmp.numRows(),HPtmp.numCols(),HPtmp.values(),HPtmp.stride(),&tau_[0],&work_[0],lwork,&info);
1528  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, GCRODRSolMgrLAPACKFailure, "Belos::GCRODRSolMgr::solve(): LAPACK _GEQRF failed to compute a workspace size.");
1529 
1530  // Step #2: Compute QR factorization of HP
1531  lwork = (int)work_[0];
1532  work_.resize(lwork);
1533  lapack.GEQRF(HPtmp.numRows(),HPtmp.numCols(),HPtmp.values(),HPtmp.stride(),&tau_[0],&work_[0],lwork,&info);
1534  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, GCRODRSolMgrLAPACKFailure, "Belos::GCRODRSolMgr::solve(): LAPACK _GEQRF failed to compute a QR factorization.");
1535 
1536  // Step #3: Explicitly construct Q and R factors
1537  // NOTE: The upper triangular part of HP is copied into R and HP becomes Q.
1538  Teuchos::SerialDenseMatrix<int,ScalarType> Rtmp( Teuchos::View, *R_, keff, keff );
1539  for(int ii=0;ii<keff;ii++) { for(int jj=ii;jj<keff;jj++) Rtmp(ii,jj) = HPtmp(ii,jj); }
1540  lapack.ORGQR(HPtmp.numRows(),HPtmp.numCols(),HPtmp.numCols(),HPtmp.values(),HPtmp.stride(),&tau_[0],&work_[0],lwork,&info);
1541  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, GCRODRSolMgrLAPACKFailure, "Belos::GCRODRSolMgr::solve(): LAPACK _ORGQR failed to construct the Q factor.");
1542 
1543  // Now we have [Q,R] = qr(H*P)
1544 
1545  // Now compute C = V(:,1:p+1) * Q
1546  index.resize( p+1 );
1547  for (int ii=0; ii < (p+1); ++ii) { index[ii] = ii; }
1548  Vtmp = MVT::CloneView( *V_, index ); // need new view into V (p+1 vectors now; needed p above)
1549  MVT::MvTimesMatAddMv( one, *Vtmp, HPtmp, zero, *Ctmp );
1550 
1551  // Finally, compute U = U*R^{-1}.
1552  // This unfortuntely requires me to form R^{-1} explicitly and execute U = U * R^{-1}, as
1553  // backsolve capabilities don't exist in the Belos::MultiVec class
1554 
1555  // Step #1: First, compute LU factorization of R
1556  ipiv_.resize(Rtmp.numRows());
1557  lapack.GETRF(Rtmp.numRows(),Rtmp.numCols(),Rtmp.values(),Rtmp.stride(),&ipiv_[0],&info);
1558  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, GCRODRSolMgrLAPACKFailure, "Belos::GCRODRSolMgr::solve(): LAPACK _GETRF failed to compute an LU factorization.");
1559 
1560  // Step #2: Form inv(R)
1561  lwork = Rtmp.numRows();
1562  work_.resize(lwork);
1563  lapack.GETRI(Rtmp.numRows(),Rtmp.values(),Rtmp.stride(),&ipiv_[0],&work_[0],lwork,&info);
1564  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, GCRODRSolMgrLAPACKFailure, "Belos::GCRODRSolMgr::solve(): LAPACK _GETRI failed to invert triangular matrix.");
1565 
1566  // Step #3: Let U = U * R^{-1}
1567  MVT::MvTimesMatAddMv( one, *U1tmp, Rtmp, zero, *Utmp );
1568 
1569  printer_->stream(Debug) << " Generated recycled subspace using RHS index " << currIdx[0] << " of dimension " << keff << std::endl << std::endl;
1570 
1571  } // if (recycledBlocks_ < p+1)
1572 
1573  // Return to outer loop if the priming solve converged, set the next linear system.
1574  if (primeConverged) {
1575  // Inform the linear problem that we are finished with this block linear system.
1576  problem_->setCurrLS();
1577 
1578  // Update indices for the linear systems to be solved.
1579  numRHS2Solve -= 1;
1580  if ( numRHS2Solve > 0 ) {
1581  currIdx[0]++;
1582 
1583  // Set the next indices.
1584  problem_->setLSIndex( currIdx );
1585  }
1586  else {
1587  currIdx.resize( numRHS2Solve );
1588  }
1589 
1590  continue;
1591  }
1592  } // if (keff > 0) ...
1593 
1594  // Prepare for the Gmres iterations with the recycled subspace.
1595 
1596  // Set the current number of recycled blocks and subspace dimension with the GCRO-DR iteration.
1597  gcrodr_iter->setSize( keff, numBlocks_ );
1598 
1599  // Reset the number of iterations.
1600  gcrodr_iter->resetNumIters(prime_iterations);
1601 
1602  // Reset the number of calls that the status test output knows about.
1603  outputTest_->resetNumCalls();
1604 
1605  // Compute the residual after the priming solve, it will be the first block in the current Krylov basis.
1606  problem_->computeCurrPrecResVec( &*r_ );
1607  index.resize( 1 ); index[0] = 0;
1608  RCP<MV> v0 = MVT::CloneViewNonConst( *V_, index );
1609  MVT::SetBlock(*r_,index,*v0); // V(:,0) = r
1610 
1611  // Set the new state and initialize the solver.
1613  index.resize( numBlocks_+1 );
1614  for (int ii=0; ii<(numBlocks_+1); ++ii) { index[ii] = ii; }
1615  newstate.V = MVT::CloneViewNonConst( *V_, index );
1616  index.resize( keff );
1617  for (int ii=0; ii<keff; ++ii) { index[ii] = ii; }
1618  newstate.C = MVT::CloneViewNonConst( *C_, index );
1619  newstate.U = MVT::CloneViewNonConst( *U_, index );
1620  newstate.B = rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>( Teuchos::View, *H2_, keff, numBlocks_, 0, keff ) );
1621  newstate.H = rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>( Teuchos::View, *H2_, numBlocks_+1, numBlocks_, keff, keff ) );
1622  newstate.curDim = 0;
1623  gcrodr_iter->initialize(newstate);
1624 
1625  // variables needed for inner loop
1626  int numRestarts = 0;
1627  while(1) {
1628 
1629  // tell gcrodr_iter to iterate
1630  try {
1631  gcrodr_iter->iterate();
1632 
1634  //
1635  // check convergence first
1636  //
1638  if ( convTest_->getStatus() == Passed ) {
1639  // we have convergence
1640  break; // break from while(1){gcrodr_iter->iterate()}
1641  }
1643  //
1644  // check for maximum iterations
1645  //
1647  else if ( maxIterTest_->getStatus() == Passed ) {
1648  // we don't have convergence
1649  isConverged = false;
1650  break; // break from while(1){gcrodr_iter->iterate()}
1651  }
1653  //
1654  // check for restarting, i.e. the subspace is full
1655  //
1657  else if ( gcrodr_iter->getCurSubspaceDim() == gcrodr_iter->getMaxSubspaceDim() ) {
1658 
1659  // Update the recycled subspace even if we have hit the maximum number of restarts.
1660 
1661  // Update the linear problem.
1662  RCP<MV> update = gcrodr_iter->getCurrentUpdate();
1663  problem_->updateSolution( update, true );
1664 
1665  buildRecycleSpace2(gcrodr_iter);
1666 
1667  printer_->stream(Debug) << " Generated new recycled subspace using RHS index " << currIdx[0] << " of dimension " << keff << std::endl << std::endl;
1668 
1669  // NOTE: If we have hit the maximum number of restarts then quit
1670  if ( numRestarts >= maxRestarts_ ) {
1671  isConverged = false;
1672  break; // break from while(1){gcrodr_iter->iterate()}
1673  }
1674  numRestarts++;
1675 
1676  printer_->stream(Debug) << " Performing restart number " << numRestarts << " of " << maxRestarts_ << std::endl << std::endl;
1677 
1678  // Create the restart vector (first block in the current Krylov basis)
1679  problem_->computeCurrPrecResVec( &*r_ );
1680  index.resize( 1 ); index[0] = 0;
1681  RCP<MV> v00 = MVT::CloneViewNonConst( *V_, index );
1682  MVT::SetBlock(*r_,index,*v00); // V(:,0) = r
1683 
1684  // Set the new state and initialize the solver.
1685  GCRODRIterState<ScalarType,MV> restartState;
1686  index.resize( numBlocks_+1 );
1687  for (int ii=0; ii<(numBlocks_+1); ++ii) { index[ii] = ii; }
1688  restartState.V = MVT::CloneViewNonConst( *V_, index );
1689  index.resize( keff );
1690  for (int ii=0; ii<keff; ++ii) { index[ii] = ii; }
1691  restartState.U = MVT::CloneViewNonConst( *U_, index );
1692  restartState.C = MVT::CloneViewNonConst( *C_, index );
1693  restartState.B = rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>( Teuchos::View, *H2_, keff, numBlocks_, 0, keff ) );
1694  restartState.H = rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>( Teuchos::View, *H2_, numBlocks_+1, numBlocks_, keff, keff ) );
1695  restartState.curDim = 0;
1696  gcrodr_iter->initialize(restartState);
1697 
1698 
1699  } // end of restarting
1700 
1702  //
1703  // we returned from iterate(), but none of our status tests Passed.
1704  // something is wrong, and it is probably our fault.
1705  //
1707 
1708  else {
1709  TEUCHOS_TEST_FOR_EXCEPTION(true,std::logic_error,"Belos::GCRODRSolMgr::solve(): Invalid return from GCRODRIter::iterate().");
1710  }
1711  }
1712  catch (const GCRODRIterOrthoFailure &e) {
1713  // Try to recover the most recent least-squares solution
1714  gcrodr_iter->updateLSQR( gcrodr_iter->getCurSubspaceDim() );
1715 
1716  // Check to see if the most recent least-squares solution yielded convergence.
1717  sTest_->checkStatus( &*gcrodr_iter );
1718  if (convTest_->getStatus() != Passed)
1719  isConverged = false;
1720  break;
1721  }
1722  catch (const std::exception &e) {
1723  printer_->stream(Errors) << "Error! Caught exception in GCRODRIter::iterate() at iteration "
1724  << gcrodr_iter->getNumIters() << std::endl
1725  << e.what() << std::endl;
1726  throw;
1727  }
1728  }
1729 
1730  // Compute the current solution.
1731  // Update the linear problem.
1732  RCP<MV> update = gcrodr_iter->getCurrentUpdate();
1733  problem_->updateSolution( update, true );
1734 
1735  // Inform the linear problem that we are finished with this block linear system.
1736  problem_->setCurrLS();
1737 
1738  // If we didn't build a recycle space this solve but ran at least k iterations,
1739  // force build of new recycle space
1740 
1741  if (!builtRecycleSpace_) {
1742  buildRecycleSpace2(gcrodr_iter);
1743  printer_->stream(Debug) << " Generated new recycled subspace using RHS index " << currIdx[0] << " of dimension " << keff << std::endl << std::endl;
1744  }
1745 
1746  // Update indices for the linear systems to be solved.
1747  numRHS2Solve -= 1;
1748  if ( numRHS2Solve > 0 ) {
1749  currIdx[0]++;
1750 
1751  // Set the next indices.
1752  problem_->setLSIndex( currIdx );
1753  }
1754  else {
1755  currIdx.resize( numRHS2Solve );
1756  }
1757 
1758  }// while ( numRHS2Solve > 0 )
1759 
1760  }
1761 
1762  // print final summary
1763  sTest_->print( printer_->stream(FinalSummary) );
1764 
1765  // print timing information
1766 #ifdef BELOS_TEUCHOS_TIME_MONITOR
1767  // Calling summarize() can be expensive, so don't call unless the
1768  // user wants to print out timing details. summarize() will do all
1769  // the work even if it's passed a "black hole" output stream.
1770  if (verbosity_ & TimingDetails)
1771  Teuchos::TimeMonitor::summarize( printer_->stream(TimingDetails) );
1772 #endif
1773 
1774  // get iteration information for this solve
1775  numIters_ = maxIterTest_->getNumIters();
1776 
1777  // Save the convergence test value ("achieved tolerance") for this
1778  // solve. This solver (unlike BlockGmresSolMgr) always has two
1779  // residual norm status tests: an explicit and an implicit test.
1780  // The master convergence test convTest_ is a SEQ combo of the
1781  // implicit resp. explicit tests. If the implicit test never
1782  // passes, then the explicit test won't ever be executed. This
1783  // manifests as expConvTest_->getTestValue()->size() < 1. We deal
1784  // with this case by using the values returned by
1785  // impConvTest_->getTestValue().
1786  {
1787  const std::vector<MagnitudeType>* pTestValues = expConvTest_->getTestValue();
1788  if (pTestValues == NULL || pTestValues->size() < 1) {
1789  pTestValues = impConvTest_->getTestValue();
1790  }
1791  TEUCHOS_TEST_FOR_EXCEPTION(pTestValues == NULL, std::logic_error,
1792  "Belos::GCRODRSolMgr::solve(): The implicit convergence test's getTestValue() "
1793  "method returned NULL. Please report this bug to the Belos developers.");
1794  TEUCHOS_TEST_FOR_EXCEPTION(pTestValues->size() < 1, std::logic_error,
1795  "Belos::GCRODRSolMgr::solve(): The implicit convergence test's getTestValue() "
1796  "method returned a vector of length zero. Please report this bug to the "
1797  "Belos developers.");
1798 
1799  // FIXME (mfh 12 Dec 2011) Does pTestValues really contain the
1800  // achieved tolerances for all vectors in the current solve(), or
1801  // just for the vectors from the last deflation?
1802  achievedTol_ = *std::max_element (pTestValues->begin(), pTestValues->end());
1803  }
1804 
1805  if (!isConverged) {
1806  return Unconverged; // return from GCRODRSolMgr::solve()
1807  }
1808  return Converged; // return from GCRODRSolMgr::solve()
1809 }
1810 
1811 // Given existing recycle space and Krylov space, build new recycle space
1812 template<class ScalarType, class MV, class OP>
1814 
1815  ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
1816  ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
1817 
1818  std::vector<MagnitudeType> d(keff);
1819  std::vector<int> index(numBlocks_+1);
1820 
1821  // Get the state
1822  GCRODRIterState<ScalarType,MV> oldState = gcrodr_iter->getState();
1823  int p = oldState.curDim;
1824 
1825  // insufficient new information to update recycle space
1826  if (p<1) return;
1827 
1828  // Take the norm of the recycled vectors
1829  {
1830  index.resize(keff);
1831  for (int ii=0; ii<keff; ++ii) { index[ii] = ii; }
1832  Teuchos::RCP<MV> Utmp = MVT::CloneViewNonConst( *U_, index );
1833  d.resize(keff);
1834  MVT::MvNorm( *Utmp, d );
1835  for (int i=0; i<keff; ++i) {
1836  d[i] = one / d[i];
1837  }
1838  MVT::MvScale( *Utmp, d );
1839  }
1840 
1841  // Get view into current "full" upper Hessnburg matrix
1842  Teuchos::RCP<Teuchos::SerialDenseMatrix<int,ScalarType> > H2tmp = Teuchos::rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>( Teuchos::View, *H2_, p+keff+1, p+keff ) );
1843 
1844  // Insert D into the leading keff x keff block of H2
1845  for (int i=0; i<keff; ++i) {
1846  (*H2tmp)(i,i) = d[i];
1847  }
1848 
1849  // Compute the harmoic Ritz pairs for the generalized eigenproblem
1850  // getHarmonicVecs2 assumes PP has recycledBlocks_+1 columns available
1851  int keff_new;
1852  {
1853  Teuchos::SerialDenseMatrix<int,ScalarType> PPtmp( Teuchos::View, *PP_, p+keff, recycledBlocks_+1 );
1854  keff_new = getHarmonicVecs2( keff, p, *H2tmp, oldState.V, PPtmp );
1855  }
1856 
1857  // Code to form new U, C
1858  // U = [U V(:,1:p)] * P; (in two steps)
1859 
1860  // U(:,1:keff) = matmul(U(:,1:keff_old),PP(1:keff_old,1:keff)) (step 1)
1861  Teuchos::RCP<MV> U1tmp;
1862  {
1863  index.resize( keff );
1864  for (int ii=0; ii<keff; ++ii) { index[ii] = ii; }
1865  Teuchos::RCP<const MV> Utmp = MVT::CloneView( *U_, index );
1866  index.resize( keff_new );
1867  for (int ii=0; ii<keff_new; ++ii) { index[ii] = ii; }
1868  U1tmp = MVT::CloneViewNonConst( *U1_, index );
1869  Teuchos::SerialDenseMatrix<int,ScalarType> PPtmp( Teuchos::View, *PP_, keff, keff_new );
1870  MVT::MvTimesMatAddMv( one, *Utmp, PPtmp, zero, *U1tmp );
1871  }
1872 
1873  // U(:,1:keff) = U(:,1:keff) + matmul(V(:,1:m-k),PP(keff_old+1:m-k+keff_old,1:keff)) (step 2)
1874  {
1875  index.resize(p);
1876  for (int ii=0; ii < p; ii++) { index[ii] = ii; }
1877  Teuchos::RCP<const MV> Vtmp = MVT::CloneView( *V_, index );
1878  Teuchos::SerialDenseMatrix<int,ScalarType> PPtmp( Teuchos::View, *PP_, p, keff_new, keff );
1879  MVT::MvTimesMatAddMv( one, *Vtmp, PPtmp, one, *U1tmp );
1880  }
1881 
1882  // Form HP = H*P
1883  Teuchos::SerialDenseMatrix<int,ScalarType> HPtmp( Teuchos::View, *HP_, p+keff+1, keff_new );
1884  {
1885  Teuchos::SerialDenseMatrix<int,ScalarType> PPtmp( Teuchos::View, *PP_, p+keff, keff_new );
1886  HPtmp.multiply(Teuchos::NO_TRANS,Teuchos::NO_TRANS,one,*H2tmp,PPtmp,zero);
1887  }
1888 
1889  // Workspace size query for QR factorization of HP (the worksize will be placed in work_[0])
1890  int info = 0, lwork = -1;
1891  tau_.resize(keff_new);
1892  lapack.GEQRF(HPtmp.numRows(),HPtmp.numCols(),HPtmp.values(),HPtmp.stride(),&tau_[0],&work_[0],lwork,&info);
1893  TEUCHOS_TEST_FOR_EXCEPTION(info != 0,GCRODRSolMgrLAPACKFailure,"Belos::GCRODRSolMgr::solve(): LAPACK _GEQRF failed to compute a workspace size.");
1894 
1895  lwork = (int)work_[0];
1896  work_.resize(lwork);
1897  lapack.GEQRF(HPtmp.numRows(),HPtmp.numCols(),HPtmp.values(),HPtmp.stride(),&tau_[0],&work_[0],lwork,&info);
1898  TEUCHOS_TEST_FOR_EXCEPTION(info != 0,GCRODRSolMgrLAPACKFailure,"Belos::GCRODRSolMgr::solve(): LAPACK _GEQRF failed to compute a QR factorization.");
1899 
1900  // Explicitly construct Q and R factors
1901  // NOTE: The upper triangular part of HP is copied into R and HP becomes Q.
1902  Teuchos::SerialDenseMatrix<int,ScalarType> Rtmp( Teuchos::View, *R_, keff_new, keff_new );
1903  for(int i=0;i<keff_new;i++) { for(int j=i;j<keff_new;j++) Rtmp(i,j) = HPtmp(i,j); }
1904  lapack.ORGQR(HPtmp.numRows(),HPtmp.numCols(),HPtmp.numCols(),HPtmp.values(),HPtmp.stride(),&tau_[0],&work_[0],lwork,&info);
1905  TEUCHOS_TEST_FOR_EXCEPTION(info != 0,GCRODRSolMgrLAPACKFailure,"Belos::GCRODRSolMgr::solve(): LAPACK _ORGQR failed to construct the Q factor.");
1906 
1907  // Form orthonormalized C and adjust U accordingly so that C = A*U
1908  // C = [C V] * Q;
1909 
1910  // C(:,1:keff) = matmul(C(:,1:keff_old),QQ(1:keff_old,1:keff))
1911  {
1912  Teuchos::RCP<MV> C1tmp;
1913  {
1914  index.resize(keff);
1915  for (int i=0; i < keff; i++) { index[i] = i; }
1916  Teuchos::RCP<const MV> Ctmp = MVT::CloneView( *C_, index );
1917  index.resize(keff_new);
1918  for (int i=0; i < keff_new; i++) { index[i] = i; }
1919  C1tmp = MVT::CloneViewNonConst( *C1_, index );
1920  Teuchos::SerialDenseMatrix<int,ScalarType> PPtmp( Teuchos::View, *HP_, keff, keff_new );
1921  MVT::MvTimesMatAddMv( one, *Ctmp, PPtmp, zero, *C1tmp );
1922  }
1923  // Now compute C += V(:,1:p+1) * Q
1924  {
1925  index.resize( p+1 );
1926  for (int i=0; i < p+1; ++i) { index[i] = i; }
1927  Teuchos::RCP<const MV> Vtmp = MVT::CloneView( *V_, index );
1928  Teuchos::SerialDenseMatrix<int,ScalarType> PPtmp( Teuchos::View, *HP_, p+1, keff_new, keff, 0 );
1929  MVT::MvTimesMatAddMv( one, *Vtmp, PPtmp, one, *C1tmp );
1930  }
1931  }
1932 
1933  // C_ = C1_; (via a swap)
1934  std::swap(C_, C1_);
1935 
1936  // Finally, compute U_ = U_*R^{-1}
1937  // First, compute LU factorization of R
1938  ipiv_.resize(Rtmp.numRows());
1939  lapack.GETRF(Rtmp.numRows(),Rtmp.numCols(),Rtmp.values(),Rtmp.stride(),&ipiv_[0],&info);
1940  TEUCHOS_TEST_FOR_EXCEPTION(info != 0,GCRODRSolMgrLAPACKFailure,"Belos::GCRODRSolMgr::solve(): LAPACK _GETRF failed to compute an LU factorization.");
1941 
1942  // Now, form inv(R)
1943  lwork = Rtmp.numRows();
1944  work_.resize(lwork);
1945  lapack.GETRI(Rtmp.numRows(),Rtmp.values(),Rtmp.stride(),&ipiv_[0],&work_[0],lwork,&info);
1946  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, GCRODRSolMgrLAPACKFailure,"Belos::GCRODRSolMgr::solve(): LAPACK _GETRI failed to compute an LU factorization.");
1947 
1948  {
1949  index.resize(keff_new);
1950  for (int i=0; i < keff_new; i++) { index[i] = i; }
1951  Teuchos::RCP<MV> Utmp = MVT::CloneViewNonConst( *U_, index );
1952  MVT::MvTimesMatAddMv( one, *U1tmp, Rtmp, zero, *Utmp );
1953  }
1954 
1955  // Set the current number of recycled blocks and subspace dimension with the GCRO-DR iteration.
1956  if (keff != keff_new) {
1957  keff = keff_new;
1958  gcrodr_iter->setSize( keff, numBlocks_ );
1959  // Important to zero this out before next cyle
1960  Teuchos::SerialDenseMatrix<int,ScalarType> b1( Teuchos::View, *H2_, recycledBlocks_+2, 1, 0, recycledBlocks_ );
1961  b1.putScalar(zero);
1962  }
1963 
1964 }
1965 
1966 
1967 // Compute the harmonic eigenpairs of the projected, dense system.
1968 template<class ScalarType, class MV, class OP>
1970  const Teuchos::SerialDenseMatrix<int,ScalarType>& HH,
1971  Teuchos::SerialDenseMatrix<int,ScalarType>& PP) {
1972  int i, j;
1973  bool xtraVec = false;
1974  ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
1975  ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
1976 
1977  // Real and imaginary eigenvalue components
1978  std::vector<MagnitudeType> wr(m), wi(m);
1979 
1980  // Real and imaginary (right) eigenvectors; Don't zero out matrix when constructing
1981  Teuchos::SerialDenseMatrix<int,ScalarType> vr(m,m,false);
1982 
1983  // Magnitude of harmonic Ritz values
1984  std::vector<MagnitudeType> w(m);
1985 
1986  // Sorted order of harmonic Ritz values, also used for DGEEV
1987  std::vector<int> iperm(m);
1988 
1989  // Size of workspace and workspace for DGEEV
1990  int lwork = 4*m;
1991  std::vector<ScalarType> work(lwork);
1992 
1993  // Output info
1994  int info = 0;
1995 
1996  // Set flag indicating recycle space has been generated this solve
1997  builtRecycleSpace_ = true;
1998 
1999  // Solve linear system: H_m^{-H}*e_m
2000  Teuchos::SerialDenseMatrix<int, ScalarType> HHt( HH, Teuchos::TRANS );
2001  Teuchos::SerialDenseVector<int, ScalarType> e_m( m );
2002  e_m[m-1] = one;
2003  lapack.GESV(m, 1, HHt.values(), HHt.stride(), &iperm[0], e_m.values(), e_m.stride(), &info);
2004  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, GCRODRSolMgrLAPACKFailure, "Belos::GCRODRSolMgr::solve(): LAPACK GESV failed to compute a solution.");
2005 
2006  // Compute H_m + d*H_m^{-H}*e_m*e_m^H
2007  ScalarType d = HH(m, m-1) * HH(m, m-1);
2008  Teuchos::SerialDenseMatrix<int, ScalarType> harmHH( HH );
2009  for( i=0; i<m; ++i )
2010  harmHH(i, m-1) += d * e_m[i];
2011 
2012  // Revise to do query for optimal workspace first
2013  // Create simple storage for the left eigenvectors, which we don't care about.
2014  const int ldvl = m;
2015  ScalarType* vl = 0;
2016  lapack.GEEV('N', 'V', m, harmHH.values(), harmHH.stride(), &wr[0], &wi[0],
2017  vl, ldvl, vr.values(), vr.stride(), &work[0], lwork, &info);
2018  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, GCRODRSolMgrLAPACKFailure,"Belos::GCRODRSolMgr::solve(): LAPACK GEEV failed to compute eigensolutions.");
2019 
2020  // Construct magnitude of each harmonic Ritz value
2021  for( i=0; i<m; ++i )
2022  w[i] = Teuchos::ScalarTraits<ScalarType>::squareroot( wr[i]*wr[i] + wi[i]*wi[i] );
2023 
2024  // Construct magnitude of each harmonic Ritz value
2025  this->sort(w, m, iperm);
2026 
2027  // Determine exact size for PP (i.e., determine if we need to store an additional vector)
2028  if (wi[iperm[recycledBlocks_-1]] != zero) {
2029  int countImag = 0;
2030  for ( i=0; i<recycledBlocks_; ++i ) {
2031  if (wi[iperm[i]] != zero)
2032  countImag++;
2033  }
2034  // Check to see if this count is even or odd:
2035  if (countImag % 2)
2036  xtraVec = true;
2037  }
2038 
2039  // Select recycledBlocks_ smallest eigenvectors
2040  for( i=0; i<recycledBlocks_; ++i ) {
2041  for( j=0; j<m; j++ ) {
2042  PP(j,i) = vr(j,iperm[i]);
2043  }
2044  }
2045 
2046  if (xtraVec) { // we need to store one more vector
2047  if (wi[iperm[recycledBlocks_-1]] > 0) { // I picked the "real" component
2048  for( j=0; j<m; ++j ) { // so get the "imag" component
2049  PP(j,recycledBlocks_) = vr(j,iperm[recycledBlocks_-1]+1);
2050  }
2051  }
2052  else { // I picked the "imag" component
2053  for( j=0; j<m; ++j ) { // so get the "real" component
2054  PP(j,recycledBlocks_) = vr(j,iperm[recycledBlocks_-1]-1);
2055  }
2056  }
2057  }
2058 
2059  // Return whether we needed to store an additional vector
2060  if (xtraVec) {
2061  return recycledBlocks_+1;
2062  }
2063  return recycledBlocks_;
2064 }
2065 
2066 // Compute the harmonic eigenpairs of the projected, dense system.
2067 template<class ScalarType, class MV, class OP>
2068 int GCRODRSolMgr<ScalarType,MV,OP>::getHarmonicVecs2(int keffloc, int m,
2069  const Teuchos::SerialDenseMatrix<int,ScalarType>& HH,
2070  const Teuchos::RCP<const MV>& VV,
2071  Teuchos::SerialDenseMatrix<int,ScalarType>& PP) {
2072  int i, j;
2073  int m2 = HH.numCols();
2074  bool xtraVec = false;
2075  ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
2076  ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
2077  std::vector<int> index;
2078 
2079  // Real and imaginary eigenvalue components
2080  std::vector<ScalarType> wr(m2), wi(m2);
2081 
2082  // Magnitude of harmonic Ritz values
2083  std::vector<MagnitudeType> w(m2);
2084 
2085  // Real and imaginary (right) eigenvectors; Don't zero out matrix when constructing
2086  Teuchos::SerialDenseMatrix<int,ScalarType> vr(m2,m2,false);
2087 
2088  // Sorted order of harmonic Ritz values
2089  std::vector<int> iperm(m2);
2090 
2091  // Set flag indicating recycle space has been generated this solve
2092  builtRecycleSpace_ = true;
2093 
2094  // Form matrices for generalized eigenproblem
2095 
2096  // B = H2' * H2; Don't zero out matrix when constructing
2097  Teuchos::SerialDenseMatrix<int,ScalarType> B(m2,m2,false);
2098  B.multiply(Teuchos::TRANS,Teuchos::NO_TRANS,one,HH,HH,zero);
2099 
2100  // A_tmp = | C'*U 0 |
2101  // | V_{m+1}'*U I |
2102  Teuchos::SerialDenseMatrix<int,ScalarType> A_tmp( keffloc+m+1, keffloc+m );
2103 
2104  // A_tmp(1:keffloc,1:keffloc) = C' * U;
2105  index.resize(keffloc);
2106  for (i=0; i<keffloc; ++i) { index[i] = i; }
2107  Teuchos::RCP<const MV> Ctmp = MVT::CloneView( *C_, index );
2108  Teuchos::RCP<const MV> Utmp = MVT::CloneView( *U_, index );
2109  Teuchos::SerialDenseMatrix<int,ScalarType> A11( Teuchos::View, A_tmp, keffloc, keffloc );
2110  MVT::MvTransMv( one, *Ctmp, *Utmp, A11 );
2111 
2112  // A_tmp(keffloc+1:m-k+keffloc+1,1:keffloc) = V' * U;
2113  Teuchos::SerialDenseMatrix<int,ScalarType> A21( Teuchos::View, A_tmp, m+1, keffloc, keffloc );
2114  index.resize(m+1);
2115  for (i=0; i < m+1; i++) { index[i] = i; }
2116  Teuchos::RCP<const MV> Vp = MVT::CloneView( *VV, index );
2117  MVT::MvTransMv( one, *Vp, *Utmp, A21 );
2118 
2119  // A_tmp(keffloc+1:m-k+keffloc,keffloc+1:m-k+keffloc) = eye(m-k);
2120  for( i=keffloc; i<keffloc+m; i++ ) {
2121  A_tmp(i,i) = one;
2122  }
2123 
2124  // A = H2' * A_tmp;
2125  Teuchos::SerialDenseMatrix<int,ScalarType> A( m2, A_tmp.numCols() );
2126  A.multiply( Teuchos::TRANS, Teuchos::NO_TRANS, one, HH, A_tmp, zero );
2127 
2128  // Compute k smallest harmonic Ritz pairs
2129  // SUBROUTINE DGGEVX( BALANC, JOBVL, JOBVR, SENSE, N, A, LDA, B, LDB,
2130  // ALPHAR, ALPHAI, BETA, VL, LDVL, VR, LDVR, ILO,
2131  // IHI, LSCALE, RSCALE, ABNRM, BBNRM, RCONDE,
2132  // RCONDV, WORK, LWORK, IWORK, BWORK, INFO )
2133  // MLP: 'SCALING' in DGGEVX generates incorrect eigenvalues. Therefore, only permuting
2134  char balanc='P', jobvl='N', jobvr='V', sense='N';
2135  int ld = A.numRows();
2136  int lwork = 6*ld;
2137  int ldvl = ld, ldvr = ld;
2138  int info = 0,ilo = 0,ihi = 0;
2139  ScalarType abnrm = zero, bbnrm = zero;
2140  ScalarType *vl = 0; // This is never referenced by dggevx if jobvl == 'N'
2141  std::vector<ScalarType> beta(ld);
2142  std::vector<ScalarType> work(lwork);
2143  std::vector<MagnitudeType> lscale(ld), rscale(ld);
2144  std::vector<MagnitudeType> rconde(ld), rcondv(ld);
2145  std::vector<int> iwork(ld+6);
2146  int *bwork = 0; // If sense == 'N', bwork is never referenced
2147  lapack.GGEVX(balanc, jobvl, jobvr, sense, ld, A.values(), ld, B.values(), ld, &wr[0], &wi[0],
2148  &beta[0], vl, ldvl, vr.values(), ldvr, &ilo, &ihi, &lscale[0], &rscale[0],
2149  &abnrm, &bbnrm, &rconde[0], &rcondv[0], &work[0], lwork, &iwork[0], bwork, &info);
2150  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, GCRODRSolMgrLAPACKFailure, "Belos::GCRODRSolMgr::solve(): LAPACK GGEVX failed to compute eigensolutions.");
2151 
2152  // Construct magnitude of each harmonic Ritz value
2153  // NOTE : Forming alpha/beta *should* be okay here, given assumptions on construction of matrix pencil above
2154  for( i=0; i<ld; i++ ) {
2155  w[i] = Teuchos::ScalarTraits<ScalarType>::squareroot( (wr[i]/beta[i])*(wr[i]/beta[i]) + (wi[i]/beta[i])*(wi[i]/beta[i]) );
2156  }
2157 
2158  // Construct magnitude of each harmonic Ritz value
2159  this->sort(w,ld,iperm);
2160 
2161  // Determine exact size for PP (i.e., determine if we need to store an additional vector)
2162  if (wi[iperm[ld-recycledBlocks_]] != zero) {
2163  int countImag = 0;
2164  for ( i=ld-recycledBlocks_; i<ld; i++ ) {
2165  if (wi[iperm[i]] != zero)
2166  countImag++;
2167  }
2168  // Check to see if this count is even or odd:
2169  if (countImag % 2)
2170  xtraVec = true;
2171  }
2172 
2173  // Select recycledBlocks_ smallest eigenvectors
2174  for( i=0; i<recycledBlocks_; i++ ) {
2175  for( j=0; j<ld; j++ ) {
2176  PP(j,i) = vr(j,iperm[ld-recycledBlocks_+i]);
2177  }
2178  }
2179 
2180  if (xtraVec) { // we need to store one more vector
2181  if (wi[iperm[ld-recycledBlocks_]] > 0) { // I picked the "real" component
2182  for( j=0; j<ld; j++ ) { // so get the "imag" component
2183  PP(j,recycledBlocks_) = vr(j,iperm[ld-recycledBlocks_]+1);
2184  }
2185  }
2186  else { // I picked the "imag" component
2187  for( j=0; j<ld; j++ ) { // so get the "real" component
2188  PP(j,recycledBlocks_) = vr(j,iperm[ld-recycledBlocks_]-1);
2189  }
2190  }
2191  }
2192 
2193  // Return whether we needed to store an additional vector
2194  if (xtraVec) {
2195  return recycledBlocks_+1;
2196  }
2197  return recycledBlocks_;
2198 }
2199 
2200 
2201 // This method sorts list of n floating-point numbers and return permutation vector
2202 template<class ScalarType, class MV, class OP>
2203 void GCRODRSolMgr<ScalarType,MV,OP>::sort(std::vector<ScalarType>& dlist, int n, std::vector<int>& iperm) {
2204  int l, r, j, i, flag;
2205  int RR2;
2206  double dRR, dK;
2207 
2208  // Initialize the permutation vector.
2209  for(j=0;j<n;j++)
2210  iperm[j] = j;
2211 
2212  if (n <= 1) return;
2213 
2214  l = n / 2 + 1;
2215  r = n - 1;
2216  l = l - 1;
2217  dRR = dlist[l - 1];
2218  dK = dlist[l - 1];
2219 
2220  RR2 = iperm[l - 1];
2221  while (r != 0) {
2222  j = l;
2223  flag = 1;
2224 
2225  while (flag == 1) {
2226  i = j;
2227  j = j + j;
2228 
2229  if (j > r + 1)
2230  flag = 0;
2231  else {
2232  if (j < r + 1)
2233  if (dlist[j] > dlist[j - 1]) j = j + 1;
2234 
2235  if (dlist[j - 1] > dK) {
2236  dlist[i - 1] = dlist[j - 1];
2237  iperm[i - 1] = iperm[j - 1];
2238  }
2239  else {
2240  flag = 0;
2241  }
2242  }
2243  }
2244  dlist[i - 1] = dRR;
2245  iperm[i - 1] = RR2;
2246 
2247  if (l == 1) {
2248  dRR = dlist [r];
2249  RR2 = iperm[r];
2250  dK = dlist[r];
2251  dlist[r] = dlist[0];
2252  iperm[r] = iperm[0];
2253  r = r - 1;
2254  }
2255  else {
2256  l = l - 1;
2257  dRR = dlist[l - 1];
2258  RR2 = iperm[l - 1];
2259  dK = dlist[l - 1];
2260  }
2261  }
2262  dlist[0] = dRR;
2263  iperm[0] = RR2;
2264 }
2265 
2266 
2267 // This method requires the solver manager to return a string that describes itself.
2268 template<class ScalarType, class MV, class OP>
2270  std::ostringstream oss;
2271  oss << "Belos::GCRODRSolMgr<...,"<<Teuchos::ScalarTraits<ScalarType>::name()<<">";
2272  oss << "{";
2273  oss << "Ortho Type='"<<orthoType_;
2274  oss << ", Num Blocks=" <<numBlocks_;
2275  oss << ", Num Recycle Blocks=" << recycledBlocks_;
2276  oss << ", Max Restarts=" << maxRestarts_;
2277  oss << "}";
2278  return oss.str();
2279 }
2280 
2281 
2282 } // end Belos namespace
2283 
2284 #endif /* BELOS_GCRODR_SOLMGR_HPP */
ScaleType convertStringToScaleType(const std::string &scaleType)
Convert the given string to its ScaleType enum value.
Definition: BelosTypes.cpp:93
Collection of types and exceptions used within the Belos solvers.
std::string description() const
Method to return description of the block GMRES solver manager.
Belos&#39;s basic output manager for sending information of select verbosity levels to the appropriate ou...
GCRODRSolMgrLAPACKFailure(const std::string &what_arg)
Class which manages the output and verbosity of the Belos solvers.
void reset(const ResetType type)
Performs a reset of the solver manager specified by the ResetType. This informs the solver manager th...
bool isLOADetected() const
Return whether a loss of accuracy was detected by this solver during the most current solve...
ScaleType
The type of scaling to use on the residual norm value.
Definition: BelosTypes.hpp:119
Exception thrown to signal error in a status test during Belos::StatusTest::checkStatus().
GCRODRSolMgrLAPACKFailure is thrown when a nonzero value is retuned from an LAPACK call...
A factory class for generating StatusTestOutput objects.
Teuchos::RCP< const Teuchos::ParameterList > getDefaultParameters(const std::string &name) const
Default parameters for the given MatOrthoManager subclass.
An implementation of StatusTestResNorm using a family of residual norms.
GCRODRSolMgr()
Empty constructor for GCRODRSolMgr. This constructor takes no arguments and sets the default values f...
GCRODRSolMgrLinearProblemFailure is thrown when the linear problem is not setup (i.e.
GCRODRSolMgrRecyclingFailure(const std::string &what_arg)
This class implements the GCRODR iteration, where a single-std::vector Krylov subspace is constructed...
An extension of the MultiVecTraits class that adds a new vector length method.
Belos::StatusTest class for specifying a maximum number of iterations.
int curDim
The current dimension of the reduction.
A factory class for generating StatusTestOutput objects.
std::string validNamesString() const
List (as a string) of recognized MatOrthoManager names.
Teuchos::RCP< Belos::MatOrthoManager< Scalar, MV, OP > > makeMatOrthoManager(const std::string &ortho, const Teuchos::RCP< const OP > &M, const Teuchos::RCP< OutputManager< Scalar > > &outMan, const std::string &label, const Teuchos::RCP< Teuchos::ParameterList > &params)
Return an instance of the specified MatOrthoManager subclass.
Traits class which defines basic operations on multivectors.
Belos::StatusTest for logically combining several status tests.
A Belos::StatusTest class for specifying a maximum number of iterations.
GCRODRSolMgrOrthoFailure(const std::string &what_arg)
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< MV > V
The current Krylov basis.
bool isValidName(const std::string &name) const
Whether this factory recognizes the MatOrthoManager with the given name.
Teuchos::RCP< MV > U
The recycled subspace and its projection.
std::ostream & printValidNames(std::ostream &out) const
Print all recognized MatOrthoManager names to the given ostream.
A linear system to solve, and its associated information.
GCRODRSolMgrOrthoFailure is thrown when the orthogonalization manager is unable to generate orthonorm...
Class which describes the linear problem to be solved by the iterative solver.
GCRODRIterOrthoFailure is thrown when the GCRODRIter object is unable to compute independent directio...
The Belos::GCRODRSolMgr provides a powerful and fully-featured solver manager over the GCRODR linear ...
virtual ~GCRODRSolMgr()
Destructor.
void setParameters(const Teuchos::RCP< Teuchos::ParameterList > &params)
Set the parameters the solver manager should use to solve the linear problem.
ReturnType
Whether the Belos solve converged for all linear systems.
Definition: BelosTypes.hpp:149
Belos concrete class for performing the GCRO-DR iteration.
void setProblem(const Teuchos::RCP< LinearProblem< ScalarType, MV, OP > > &problem)
Set the linear problem that needs to be solved.
The Belos::SolverManager is a templated virtual base class that defines the basic interface that any ...
Structure to contain pointers to GCRODRIter state variables.
GCRODRSolMgrRecyclingFailure is thrown when any problem occurs in using/creating the recycling subspa...
Teuchos::RCP< const Teuchos::ParameterList > getValidParameters() const
Get a parameter list containing the valid parameters for this object.
Teuchos::RCP< const Teuchos::ParameterList > getCurrentParameters() const
Get a parameter list containing the current parameters for this object.
int setTolerance(MagnitudeType tolerance)
Set the value of the tolerance.
GCRODRSolMgrLinearProblemFailure(const std::string &what_arg)
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.
MagnitudeType achievedTol() const
Tolerance achieved by the last solve() invocation.
Belos::StatusTestResNorm for specifying general residual norm stopping criteria.
Teuchos::RCP< Teuchos::SerialDenseMatrix< int, ScalarType > > B
The projection of the Krylov subspace against the recycled subspace.
Teuchos::Array< Teuchos::RCP< Teuchos::Time > > getTimers() const
Return the timers for this object.
ReturnType solve()
This method performs possibly repeated calls to the underlying linear solver&#39;s iterate() routine unti...
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.
Class which defines basic traits for the operator type.
Teuchos::RCP< MV > C
Teuchos::RCP< Teuchos::SerialDenseMatrix< int, ScalarType > > H
The current Hessenberg matrix.
Parent class to all Belos exceptions.
Definition: BelosTypes.hpp:60
const LinearProblem< ScalarType, MV, OP > & getProblem() const
Get current linear problem being solved for in this object.
Belos header file which uses auto-configuration information to include necessary C++ headers...
Belos concrete class for performing the block, flexible GMRES iteration.
int getNumIters() const
Get the iteration count for the most recent call to solve().