Belos  Version of the Day
BelosBlockGCRODRSolMgr.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 
45 #ifndef BELOS_BLOCK_GCRODR_SOLMGR_HPP
46 #define BELOS_BLOCK_GCRODR_SOLMGR_HPP
47 
48 #include "BelosConfigDefs.hpp"
49 #include "BelosTypes.hpp"
51 #include "BelosLinearProblem.hpp"
52 #include "BelosSolverManager.hpp"
53 #include "BelosGmresIteration.hpp"
54 #include "BelosBlockGCRODRIter.hpp"
55 #include "BelosBlockGmresIter.hpp"
56 #include "BelosBlockFGmresIter.hpp"
59 #include "BelosStatusTestCombo.hpp"
61 #include "BelosOutputManager.hpp"
62 #include "Teuchos_BLAS.hpp"
63 #include "Teuchos_LAPACK.hpp"
64 #include "Teuchos_as.hpp"
65 #ifdef BELOS_TEUCHOS_TIME_MONITOR
66 #include "Teuchos_TimeMonitor.hpp"
67 #endif // BELOS_TEUCHOS_TIME_MONITOR
68 
69 // MLP: Add links to examples here
70 
71 namespace Belos{
72 
74 
75 
81  public:
82  BlockGCRODRSolMgrLinearProblemFailure(const std::string& what_arg) : BelosError(what_arg) {}
83  };
84 
90  public:
91  BlockGCRODRSolMgrOrthoFailure(const std::string& what_arg) : BelosError(what_arg) {}
92  };
93 
99  public:
100  BlockGCRODRSolMgrLAPACKFailure(const std::string& what_arg) : BelosError(what_arg) {}
101  };
102 
108  public:
109  BlockGCRODRSolMgrRecyclingFailure(const std::string& what_arg) : BelosError(what_arg) {}
110  };
111 
113 
125 
126 template<class ScalarType, class MV, class OP>
127 class BlockGCRODRSolMgr : public SolverManager<ScalarType, MV, OP> {
128 private:
129 
133  typedef Teuchos::ScalarTraits<ScalarType> SCT;
134  typedef typename Teuchos::ScalarTraits<ScalarType>::magnitudeType MagnitudeType;
135  typedef Teuchos::ScalarTraits<MagnitudeType> MT;
136  typedef Teuchos::ScalarTraits<MagnitudeType> SMT;
138  typedef Teuchos::SerialDenseMatrix<int,ScalarType> SDM;
139  typedef Teuchos::SerialDenseVector<int,ScalarType> SDV;
140 
141 public:
143 
144 
151 
177  BlockGCRODRSolMgr (const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > &problem,
178  const Teuchos::RCP<Teuchos::ParameterList> &pl);
179 
181  virtual ~BlockGCRODRSolMgr() {};
183 
186 
188  std::string description() const;
189 
191 
192 
194 
195 
198  return *problem_;
199  }
200 
202  Teuchos::RCP<const Teuchos::ParameterList> getValidParameters() const;
203 
205  Teuchos::RCP<const Teuchos::ParameterList> getCurrentParameters() const { return params_; }
206 
208  int getNumIters() const { return numIters_; }
209 
211  bool isLOADetected() const { return loaDetected_; }
212 
214 
216 
217 
219  void setProblem (const Teuchos::RCP<LinearProblem<ScalarType,MV,OP> >& problem) {
220  TEUCHOS_TEST_FOR_EXCEPTION(problem.is_null(), std::invalid_argument,
221  "Belos::BlockGCRODRSolMgr::setProblem: The input LinearProblem cannot be null.");
222 
223  // Check state of problem object before proceeding
224  if (! problem->isProblemSet()) {
225  const bool success = problem->setProblem();
226  TEUCHOS_TEST_FOR_EXCEPTION(success, std::runtime_error,
227  "Belos::BlockGCRODRSolMgr::setProblem: Calling the input LinearProblem's setProblem() method failed. This likely means that the "
228  "LinearProblem has a missing (null) matrix A, solution vector X, or right-hand side vector B. Please set these items in the LinearProblem and try again.");
229  }
230 
231  problem_ = problem;
232  }
233 
235  void setParameters( const Teuchos::RCP<Teuchos::ParameterList> &params );
236 
238 
240 
241 
248  void reset (const ResetType type) {
249  if ((type & Belos::Problem) && ! problem_.is_null ())
250  problem_->setProblem();
251  else if (type & Belos::RecycleSubspace)
252  keff = 0;
253  }
254 
256 
258 
259 
275  // \returns ::ReturnType specifying:
278  ReturnType solve();
279 
281 
282 private:
283 
284  // Called by all constructors; Contains init instructions common to all constructors
285  void init();
286 
287  // Initialize solver state storage
288  void initializeStateStorage();
289 
290  // Recycling Methods
291  // Appending Function name by:
292  // "Kryl" indicates it is specialized for building a recycle space after an
293  // initial run of Block GMRES which generates an initial unaugmented block Krylov subspace
294  // "AugKryl" indicates it is specialized for building a recycle space from the augmented Krylov subspace
295 
296  // Functions which control the building of a recycle space
297  void buildRecycleSpaceKryl(int& keff, Teuchos::RCP<BlockGmresIter<ScalarType,MV,OP> > block_gmres_iter);
298  void buildRecycleSpaceAugKryl(Teuchos::RCP<BlockGCRODRIter<ScalarType,MV,OP> > gcrodr_iter);
299 
300  // Recycling with Harmonic Ritz Vectors
301  // Computes harmonic eigenpairs of projected matrix created during the priming solve.
302  // The return value is the number of vectors needed to be stored, recycledBlocks or recycledBlocks+1.
303 
304  // HH is the projected problem from the initial cycle of Gmres, it is (at least) of dimension (numBlocks+1)*blockSize x numBlocks.
305  // PP contains the harmonic eigenvectors corresponding to the recycledBlocks eigenvalues of smallest magnitude.
306  int getHarmonicVecsKryl (int m, const SDM& HH, SDM& PP);
307 
308  // HH is the total block projected problem from the GCRO-DR algorithm, it is (at least) of dimension keff+(numBlocks+1)*blockSize x keff+numBlocksm.
309  // VV is the Krylov vectors from the projected GMRES algorithm, which has (at least) (numBlocks+1)*blockSize vectors.
310  // PP contains the harmonic eigenvectors corresponding to the recycledBlocks eigenvalues of smallest magnitude.
311  int getHarmonicVecsAugKryl (int keff,
312  int m,
313  const SDM& HH,
314  const Teuchos::RCP<const MV>& VV,
315  SDM& PP);
316 
317  // Sort list of n floating-point numbers and return permutation vector
318  void sort (std::vector<ScalarType>& dlist, int n, std::vector<int>& iperm);
319 
320  // Lapack interface
321  Teuchos::LAPACK<int,ScalarType> lapack;
322 
324  Teuchos::RCP<LinearProblem<ScalarType,MV,OP> > problem_;
325 
326  //Output Manager
327  Teuchos::RCP<OutputManager<ScalarType> > printer_;
328  Teuchos::RCP<std::ostream> outputStream_;
329 
330  //Status Test
331  Teuchos::RCP<StatusTest<ScalarType,MV,OP> > sTest_;
332  Teuchos::RCP<StatusTestMaxIters<ScalarType,MV,OP> > maxIterTest_;
333  Teuchos::RCP<StatusTest<ScalarType,MV,OP> > convTest_;
334  Teuchos::RCP<StatusTestGenResNorm<ScalarType,MV,OP> > expConvTest_, impConvTest_;
335  Teuchos::RCP<StatusTestOutput<ScalarType,MV,OP> > outputTest_;
336 
338  ortho_factory_type orthoFactory_;
339 
345  Teuchos::RCP<MatOrthoManager<ScalarType,MV,OP> > ortho_;
346 
348  Teuchos::RCP<Teuchos::ParameterList> params_;
349 
360  mutable Teuchos::RCP<const Teuchos::ParameterList> defaultParams_;
361 
362  //Default Solver Values
363  static const bool adaptiveBlockSize_default_;
364  static const std::string recycleMethod_default_;
365 
366  //Current Solver Values
367  MagnitudeType convTol_, orthoKappa_;
368  int blockSize_, maxRestarts_, maxIters_, numIters_;
369  int verbosity_, outputStyle_, outputFreq_;
370  bool adaptiveBlockSize_;
371  std::string orthoType_, recycleMethod_;
372  std::string impResScale_, expResScale_;
373  std::string label_;
374 
376  // Solver State Storage
378  //
379  // The number of blocks and recycle blocks (m and k, respectively)
380  int numBlocks_, recycledBlocks_;
381  // Current size of recycled subspace
382  int keff;
383  //
384  // Residual Vector
385  Teuchos::RCP<MV> R_;
386  //
387  // Search Space
388  Teuchos::RCP<MV> V_;
389  //
390  // Recycle subspace and its image under action of the operator
391  Teuchos::RCP<MV> U_, C_;
392  //
393  // Updated recycle Space and its image under action of the operator
394  Teuchos::RCP<MV> U1_, C1_;
395  //
396  // Storage used in constructing recycle space
397  Teuchos::RCP<SDM > G_;
398  Teuchos::RCP<SDM > H_;
399  Teuchos::RCP<SDM > B_;
400  Teuchos::RCP<SDM > PP_;
401  Teuchos::RCP<SDM > HP_;
402  std::vector<ScalarType> tau_;
403  std::vector<ScalarType> work_;
404  Teuchos::RCP<SDM > F_;
405  std::vector<int> ipiv_;
406 
408  Teuchos::RCP<Teuchos::Time> timerSolve_;
409 
411  bool isSet_;
412 
414  bool loaDetected_;
415 
417  bool builtRecycleSpace_;
418 };
419 
420  //
421  // Set default solver values
422  //
423  template<class ScalarType, class MV, class OP>
425 
426  template<class ScalarType, class MV, class OP>
428 
429  //
430  // Method definitions
431  //
432 
433  template<class ScalarType, class MV, class OP>
435  init();
436  }
437 
438  //Basic Constructor
439  template<class ScalarType, class MV, class OP>
442  const Teuchos::RCP<Teuchos::ParameterList> &pl ) {
443  // Initialize local pointers to null, and initialize local
444  // variables to default values.
445  init ();
446 
447  TEUCHOS_TEST_FOR_EXCEPTION(problem.is_null(), std::invalid_argument,
448  "Belos::BlockGCRODR constructor: The solver manager's constructor needs "
449  "the linear problem argument 'problem' to be nonnull.");
450 
451  problem_ = problem;
452 
453  // Set the parameters using the list that was passed in. If null, we defer initialization until a non-null list is set (by the
454  // client calling setParameters(), or by calling solve() -- in either case, a null parameter list indicates that default parameters should be used).
455  if (! pl.is_null())
456  setParameters (pl);
457  }
458 
459  template<class ScalarType, class MV, class OP>
461  adaptiveBlockSize_ = adaptiveBlockSize_default_;
462  recycleMethod_ = recycleMethod_default_;
463  isSet_ = false;
464  loaDetected_ = false;
465  builtRecycleSpace_ = false;
466  keff = 0;//Effective Size of Recycle Space
467  //The following are all RCP smart pointers to indicated matrices/vectors.
468  //Some MATLAB notation used in comments.
469  R_ = Teuchos::null;//The Block Residual
470  V_ = Teuchos::null;//Block Arnoldi Vectors
471  U_ = Teuchos::null;//Recycle Space
472  C_ = Teuchos::null;//Image of U Under Action of Operator
473  U1_ = Teuchos::null;//Newly Computed Recycle Space
474  C1_ = Teuchos::null;//Image of Newly Computed Recycle Space
475  PP_ = Teuchos::null;//Coordinates of New Recyc. Vectors in Augmented Space
476  HP_ = Teuchos::null;//H_*PP_ or G_*PP_
477  G_ = Teuchos::null;//G_ such that A*[U V(:,1:numBlocks_*blockSize_)] = [C V_]*G_
478  F_ = Teuchos::null;//Upper Triangular portion of QR factorization for HP_
479  H_ = Teuchos::null;//H_ such that A*V(:,1:numBlocks_*blockSize_) = V_*H_ + C_*C_'*V_
480  B_ = Teuchos::null;//B_ = C_'*V_
481 
482  //THIS BLOCK OF CODE IS COMMENTED OUT AND PLACED ELSEWHERE IN THE CODE
483 /*
484  //WE TEMPORARILY INITIALIZE STATUS TESTS HERE FOR TESTING PURPOSES, BUT THEY SHOULD BE
485  //INITIALIZED SOMEWHERE ELSE, LIKE THE setParameters() FUNCTION
486 
487  //INSTANTIATE AND INITIALIZE TEST OBJECTS AS NEEDED
488  if (maxIterTest_.is_null()){
489  maxIterTest_ = rcp (new StatusTestMaxIters<ScalarType,MV,OP> (maxIters_));
490  }
491  //maxIterTest_->setMaxIters (maxIters_);
492 
493  //INSTANTIATE THE PRINTER
494  if (printer_.is_null()) {
495  printer_ = Teuchos::rcp (new OutputManager<ScalarType> (verbosity_, outputStream_));
496  }
497 
498  if (ortho_.is_null()) // || changedOrthoType) %%%In other codes, this is also triggered if orthogonalization type changed {
499  // Create orthogonalization manager. This requires that the OutputManager (printer_) already be initialized.
500  Teuchos::RCP<const Teuchos::ParameterList> orthoParams = orthoFactory_.getDefaultParameters (orthoType_);
501  ortho_ = orthoFactory_.makeMatOrthoManager (orthoType_, Teuchos::null, printer_, label_, orthoParams);
502  }
503 
504  // Convenience typedefs
505  typedef Belos::StatusTestCombo<ScalarType,MV,OP> StatusTestCombo_t;
506  typedef Belos::StatusTestGenResNorm<ScalarType,MV,OP> StatusTestResNorm_t;
507 
508  if (impConvTest_.is_null()) {
509  impConvTest_ = rcp (new StatusTestResNorm_t (convTol_));
510  impConvTest_->defineScaleForm (convertStringToScaleType (impResScale_), Belos::TwoNorm);
511  impConvTest_->setShowMaxResNormOnly( true );
512  }
513 
514  if (expConvTest_.is_null()) {
515  expConvTest_ = rcp (new StatusTestResNorm_t (convTol_));
516  expConvTest_->defineResForm (StatusTestResNorm_t::Explicit, Belos::TwoNorm);
517  expConvTest_->defineScaleForm (convertStringToScaleType (expResScale_), Belos::TwoNorm);
518  expConvTest_->setShowMaxResNormOnly( true );
519  }
520 
521  if (convTest_.is_null()) {
522  convTest_ = rcp (new StatusTestCombo_t (StatusTestCombo_t::SEQ, impConvTest_, expConvTest_));
523  }
524 
525  sTest_ = rcp (new StatusTestCombo_t (StatusTestCombo_t::OR, maxIterTest_, convTest_));
526 
527  StatusTestOutputFactory<ScalarType,MV,OP> stoFactory (outputStyle_);
528  outputTest_ = stoFactory.create (printer_, sTest_, outputFreq_,
529  Passed+Failed+Undefined);
530 
531  */
532 
533  }
534 
535  // This method requires the solver manager to return a string that describes itself.
536  template<class ScalarType, class MV, class OP>
538  std::ostringstream oss;
539  oss << "Belos::BlockGCRODRSolMgr<" << SCT::name() << ", ...>";
540  oss << "{";
541  oss << "Ortho Type='"<<orthoType_ ;
542  oss << ", Num Blocks=" <<numBlocks_;
543  oss << ", Block Size=" <<blockSize_;
544  oss << ", Num Recycle Blocks=" << recycledBlocks_;
545  oss << ", Max Restarts=" << maxRestarts_;
546  oss << "}";
547  return oss.str();
548  }
549 
550  template<class ScalarType, class MV, class OP>
551  Teuchos::RCP<const Teuchos::ParameterList>
553  using Teuchos::ParameterList;
554  using Teuchos::parameterList;
555  using Teuchos::RCP;
556  using Teuchos::rcpFromRef;
557 
558  if (defaultParams_.is_null()) {
559  RCP<ParameterList> pl = parameterList ();
560 
561  const MagnitudeType convTol = SMT::squareroot (SCT::magnitude (SCT::eps()));
562  const int maxRestarts = 1000;
563  const int maxIters = 5000;
564  const int blockSize = 2;
565  const int numBlocks = 100;
566  const int numRecycledBlocks = 25;
568  const Belos::OutputType outputStyle = Belos::General;
569  const int outputFreq = 1;
570  RCP<std::ostream> outputStream = rcpFromRef (std::cout);
571  const std::string impResScale ("Norm of Preconditioned Initial Residual");
572  const std::string expResScale ("Norm of Initial Residual");
573  const std::string timerLabel ("Belos");
574  const std::string orthoType ("DGKS");
575  RCP<const ParameterList> orthoParams = orthoFactory_.getDefaultParameters (orthoType);
576  //const MagnitudeType orthoKappa = SCT::magnitude (SCT::eps());
577  //
578  // mfh 31 Dec 2011: Negative values of orthoKappa are ignored.
579  // Setting this to a negative value by default ensures that
580  // this parameter is only _not_ ignored if the user
581  // specifically sets a valid value.
582  const MagnitudeType orthoKappa = -SCT::one();
583 
584  // Set all the valid parameters and their default values.
585  pl->set ("Convergence Tolerance", convTol,
586  "The tolerance that the solver needs to achieve in order for "
587  "the linear system(s) to be declared converged. The meaning "
588  "of this tolerance depends on the convergence test details.");
589  pl->set("Maximum Restarts", maxRestarts,
590  "The maximum number of restart cycles (not counting the first) "
591  "allowed for each set of right-hand sides solved.");
592  pl->set("Maximum Iterations", maxIters,
593  "The maximum number of iterations allowed for each set of "
594  "right-hand sides solved.");
595  pl->set("Block Size", blockSize,
596  "How many linear systems to solve at once.");
597  pl->set("Num Blocks", numBlocks,
598  "The maximum number of blocks allowed in the Krylov subspace "
599  "for each set of right-hand sides solved. This includes the "
600  "initial block. Total Krylov basis storage, not counting the "
601  "recycled subspace, is \"Num Blocks\" times \"Block Size\".");
602  pl->set("Num Recycled Blocks", numRecycledBlocks,
603  "The maximum number of vectors in the recycled subspace." );
604  pl->set("Verbosity", verbosity,
605  "What type(s) of solver information should be written "
606  "to the output stream.");
607  pl->set("Output Style", outputStyle,
608  "What style is used for the solver information to write "
609  "to the output stream.");
610  pl->set("Output Frequency", outputFreq,
611  "How often convergence information should be written "
612  "to the output stream.");
613  pl->set("Output Stream", outputStream,
614  "A reference-counted pointer to the output stream where all "
615  "solver output is sent.");
616  pl->set("Implicit Residual Scaling", impResScale,
617  "The type of scaling used in the implicit residual convergence test.");
618  pl->set("Explicit Residual Scaling", expResScale,
619  "The type of scaling used in the explicit residual convergence test.");
620  pl->set("Timer Label", timerLabel,
621  "The string to use as a prefix for the timer labels.");
622  // pl->set("Restart Timers", restartTimers_);
623  pl->set("Orthogonalization", orthoType,
624  "The orthogonalization method to use. Valid options: " +
625  orthoFactory_.validNamesString());
626  pl->set ("Orthogonalization Parameters", *orthoParams,
627  "Sublist of parameters specific to the orthogonalization method to use.");
628  pl->set("Orthogonalization Constant", orthoKappa,
629  "When using DGKS orthogonalization: the \"depTol\" constant, used "
630  "to determine whether another step of classical Gram-Schmidt is "
631  "necessary. Otherwise ignored. Nonpositive values are ignored.");
632  defaultParams_ = pl;
633  }
634  return defaultParams_;
635  }
636 
637  template<class ScalarType, class MV, class OP>
638  void
640  setParameters (const Teuchos::RCP<Teuchos::ParameterList> &params) {
641  using Teuchos::isParameterType;
642  using Teuchos::getParameter;
643  using Teuchos::null;
644  using Teuchos::ParameterList;
645  using Teuchos::parameterList;
646  using Teuchos::RCP;
647  using Teuchos::rcp;
648  using Teuchos::rcp_dynamic_cast;
649  using Teuchos::rcpFromRef;
650  using Teuchos::Exceptions::InvalidParameter;
651  using Teuchos::Exceptions::InvalidParameterName;
652  using Teuchos::Exceptions::InvalidParameterType;
653 
654  // The default parameter list contains all parameters that BlockGCRODRSolMgr understands, and none that it doesn't
655  RCP<const ParameterList> defaultParams = getValidParameters();
656 
657  if (params.is_null()) {
658  // Users really should supply a non-null input ParameterList,
659  // so that we can fill it in. However, if they really did give
660  // us a null list, be nice and use default parameters. In this
661  // case, we don't have to do any validation.
662  params_ = parameterList (*defaultParams);
663  }
664  else {
665  // Validate the user's parameter list and fill in any missing parameters with default values.
666  //
667  // Currently, validation is quite strict. The following line
668  // will throw an exception for misspelled or extra parameters.
669  // However, it will _not_ throw an exception if there are
670  // missing parameters: these will be filled in with their
671  // default values. There is additional discussion of other
672  // validation strategies in the comments of this function for
673  // Belos::GCRODRSolMgr.
674  params->validateParametersAndSetDefaults (*defaultParams);
675  // No side effects on the solver until after validation passes.
676  params_ = params;
677  }
678 
679  //
680  // Validate and set parameters relating to the Krylov subspace
681  // dimensions and the number of blocks.
682  //
683  // We try to read and validate all these parameters' values
684  // before setting them in the solver. This is because the
685  // validity of each may depend on the others' values. Our goal
686  // is to avoid incorrect side effects, so we don't set the values
687  // in the solver until we know they are right.
688  //
689  {
690  const int maxRestarts = params_->get<int> ("Maximum Restarts");
691  TEUCHOS_TEST_FOR_EXCEPTION(maxRestarts <= 0, std::invalid_argument,
692  "Belos::BlockGCRODRSolMgr: The \"Maximum Restarts\" parameter "
693  "must be nonnegative, but you specified a negative value of "
694  << maxRestarts << ".");
695 
696  const int maxIters = params_->get<int> ("Maximum Iterations");
697  TEUCHOS_TEST_FOR_EXCEPTION(maxIters <= 0, std::invalid_argument,
698  "Belos::BlockGCRODRSolMgr: The \"Maximum Iterations\" parameter "
699  "must be positive, but you specified a nonpositive value of "
700  << maxIters << ".");
701 
702  const int numBlocks = params_->get<int> ("Num Blocks");
703  TEUCHOS_TEST_FOR_EXCEPTION(numBlocks <= 0, std::invalid_argument,
704  "Belos::BlockGCRODRSolMgr: The \"Num Blocks\" parameter must be "
705  "positive, but you specified a nonpositive value of " << numBlocks
706  << ".");
707 
708  const int blockSize = params_->get<int> ("Block Size");
709  TEUCHOS_TEST_FOR_EXCEPTION(blockSize <= 0, std::invalid_argument,
710  "Belos::BlockGCRODRSolMgr: The \"Block Size\" parameter must be "
711  "positive, but you specified a nonpositive value of " << blockSize
712  << ".");
713 
714  const int recycledBlocks = params_->get<int> ("Num Recycled Blocks");
715  TEUCHOS_TEST_FOR_EXCEPTION(recycledBlocks <= 0, std::invalid_argument,
716  "Belos::BlockGCRODRSolMgr: The \"Num Recycled Blocks\" parameter must "
717  "be positive, but you specified a nonpositive value of "
718  << recycledBlocks << ".");
719  TEUCHOS_TEST_FOR_EXCEPTION(recycledBlocks >= numBlocks,
720  std::invalid_argument, "Belos::BlockGCRODRSolMgr: The \"Num Recycled "
721  "Blocks\" parameter must be less than the \"Num Blocks\" parameter, "
722  "but you specified \"Num Recycled Blocks\" = " << recycledBlocks
723  << " and \"Num Blocks\" = " << numBlocks << ".");
724 
725  // Now that we've validated the various dimension-related
726  // parameters, we can set them in the solvers.
727  maxRestarts_ = maxRestarts;
728  maxIters_ = maxIters;
729  numBlocks_ = numBlocks;
730  blockSize_ = blockSize;
731  recycledBlocks_ = recycledBlocks;
732  }
733 
734  // Check to see if the timer label changed. If it did, update it in
735  // the parameter list, and create a new timer with that label (if
736  // Belos was compiled with timers enabled).
737  {
738  std::string tempLabel = params_->get<std::string> ("Timer Label");
739  const bool labelChanged = (tempLabel != label_);
740 
741 #ifdef BELOS_TEUCHOS_TIME_MONITOR
742  std::string solveLabel = label_ + ": BlockGCRODRSolMgr total solve time";
743  if (timerSolve_.is_null()) {
744  // We haven't created a timer yet.
745  timerSolve_ = Teuchos::TimeMonitor::getNewCounter (solveLabel);
746  } else if (labelChanged) {
747  // We created a timer before with a different label. In that
748  // case, clear the old timer and create a new timer with the
749  // new label. Clearing old timers prevents them from piling
750  // up, since they are stored statically, possibly without
751  // checking for duplicates.
752  Teuchos::TimeMonitor::clearCounter (solveLabel);
753  timerSolve_ = Teuchos::TimeMonitor::getNewCounter (solveLabel);
754  }
755 #endif // BELOS_TEUCHOS_TIME_MONITOR
756  }
757 
758  // Check for a change in verbosity level. Just in case, we allow
759  // the type of this parameter to be either int or MsgType (an
760  // enum).
761  if (params_->isParameter ("Verbosity")) {
762  if (isParameterType<int> (*params_, "Verbosity")) {
763  verbosity_ = params_->get<int> ("Verbosity");
764  }
765  else {
766  verbosity_ = (int) getParameter<MsgType> (*params_, "Verbosity");
767  }
768  }
769 
770  // Check for a change in output style. Just in case, we allow
771  // the type of this parameter to be either int or OutputType (an
772  // enum).
773  if (params_->isParameter ("Output Style")) {
774  if (isParameterType<int> (*params_, "Output Style")) {
775  outputStyle_ = params_->get<int> ("Output Style");
776  }
777  else {
778  outputStyle_ = (int) getParameter<OutputType> (*params_, "Output Style");
779  }
780 
781  // Currently, the only way we can update the output style is to
782  // create a new output test. This is because we must first
783  // instantiate a new StatusTestOutputFactory with the new
784  // style, and then use the factory to make a new output test.
785  // Thus, we set outputTest_ to null for now, so we remember
786  // later to create a new one.
787  outputTest_ = null;
788  }
789 
790  // Get the output stream for the output manager.
791  //
792  // It has been pointed out (mfh 28 Feb 2011 in GCRODRSolMgr code)
793  // that including an RCP<std::ostream> parameter makes it
794  // impossible to serialize the parameter list. If you serialize
795  // the list and read it back in from the serialized
796  // representation, you might not even get a valid
797  // RCP<std::ostream>, let alone the same output stream that you
798  // serialized.
799  //
800  // However, existing Belos users depend on setting the output
801  // stream in the parameter list. We retain this behavior for
802  // backwards compatibility.
803  //
804  // In case the output stream can't be read back in, we default to
805  // stdout (std::cout), just to ensure reasonable behavior.
806  if (params_->isParameter ("Output Stream")) {
807  try {
808  outputStream_ = getParameter<RCP<std::ostream> > (*params_, "Output Stream");
809  }
810  catch (InvalidParameter&) {
811  outputStream_ = rcpFromRef (std::cout);
812  }
813  // We assume that a null output stream indicates that the user
814  // doesn't want to print anything, so we replace it with a
815  // "black hole" stream that prints nothing sent to it. (We
816  // can't use outputStream_ = Teuchos::null, since the output
817  // manager assumes that operator<< works on its output stream.)
818  if (outputStream_.is_null()) {
819  outputStream_ = rcp (new Teuchos::oblackholestream);
820  }
821  }
822 
823  outputFreq_ = params_->get<int> ("Output Frequency");
824  if (verbosity_ & Belos::StatusTestDetails) {
825  // Update parameter in our output status test.
826  if (! outputTest_.is_null()) {
827  outputTest_->setOutputFrequency (outputFreq_);
828  }
829  }
830 
831  // Create output manager if we need to, using the verbosity level
832  // and output stream that we fetched above. We do this here because
833  // instantiating an OrthoManager using OrthoManagerFactory requires
834  // a valid OutputManager.
835  if (printer_.is_null()) {
836  printer_ = rcp (new OutputManager<ScalarType> (verbosity_, outputStream_));
837  } else {
838  printer_->setVerbosity (verbosity_);
839  printer_->setOStream (outputStream_);
840  }
841 
842  // Get the orthogonalization manager name ("Orthogonalization").
843  //
844  // Getting default values for the orthogonalization manager
845  // parameters ("Orthogonalization Parameters") requires knowing the
846  // orthogonalization manager name. Save it for later, and also
847  // record whether it's different than before.
848  bool changedOrthoType = false;
849  if (params_->isParameter ("Orthogonalization")) {
850  const std::string& tempOrthoType =
851  params_->get<std::string> ("Orthogonalization");
852  // Ensure that the specified orthogonalization type is valid.
853  if (! orthoFactory_.isValidName (tempOrthoType)) {
854  std::ostringstream os;
855  os << "Belos::BlockGCRODRSolMgr: Invalid orthogonalization name \""
856  << tempOrthoType << "\". The following are valid options "
857  << "for the \"Orthogonalization\" name parameter: ";
858  orthoFactory_.printValidNames (os);
859  TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument, os.str());
860  }
861  if (tempOrthoType != orthoType_) {
862  changedOrthoType = true;
863  orthoType_ = tempOrthoType;
864  }
865  }
866 
867  // Get any parameters for the orthogonalization
868  // ("Orthogonalization Parameters"). If not supplied, the
869  // orthogonalization manager factory will supply default values.
870  //
871  // NOTE (mfh 12 Jan 2011, summer 2011, 31 Dec 2011) For backwards
872  // compatibility with other Belos GMRES-type solvers, if params
873  // has an "Orthogonalization Constant" parameter and the DGKS
874  // orthogonalization manager is to be used, the value of this
875  // parameter will override DGKS's "depTol" parameter.
876  //
877  // Users must supply the orthogonalization manager parameters as
878  // a sublist (supplying it as an RCP<ParameterList> would make
879  // the resulting parameter list not serializable).
880  RCP<ParameterList> orthoParams = sublist (params, "Orthogonalization Parameters", true);
881  TEUCHOS_TEST_FOR_EXCEPTION(orthoParams.is_null(), std::logic_error,
882  "Failed to get orthogonalization parameters. "
883  "Please report this bug to the Belos developers.");
884 
885  // Check if the desired orthogonalization method changed, or if
886  // the orthogonalization manager has not yet been instantiated.
887  // If either is the case, instantiate a new MatOrthoManager
888  // subclass instance corresponding to the desired
889  // orthogonalization method. We've already fetched the
890  // orthogonalization method name (orthoType_) and its parameters
891  // (orthoParams) above.
892  //
893  // As suggested (by mfh 12 Jan 2011 in Belos::GCRODRSolMgr) In
894  // order to ensure parameter changes get propagated to the
895  // orthomanager we simply reinstantiate the OrthoManager every
896  // time, whether or not the orthogonalization method name or
897  // parameters have changed. This is not efficient for some
898  // orthogonalization managers that keep a lot of internal state.
899  // A more general way to fix this inefficiency would be to
900  //
901  // 1. make each orthogonalization implement
902  // Teuchos::ParameterListAcceptor, and
903  //
904  // 2. make each orthogonalization implement a way to set the
905  // OutputManager instance and timer label.
906  //
907  // Create orthogonalization manager. This requires that the
908  // OutputManager (printer_) already be initialized.
909  ortho_ = orthoFactory_.makeMatOrthoManager (orthoType_, null, printer_,
910  label_, orthoParams);
911 
912  // The DGKS orthogonalization accepts a "Orthogonalization
913  // Constant" parameter (also called kappa in the code, but not in
914  // the parameter list). If its value is provided in the given
915  // parameter list and its value is positive, use it. Ignore
916  // negative values.
917  //
918  // The "Orthogonalization Constant" parameter is retained only
919  // for backwards compatibility.
920  bool gotValidOrthoKappa = false;
921  if (params_->isParameter ("Orthogonalization Constant")) {
922  const MagnitudeType orthoKappa =
923  params_->get<MagnitudeType> ("Orthogonalization Constant");
924  if (orthoKappa > 0) {
925  orthoKappa_ = orthoKappa;
926  gotValidOrthoKappa = true;
927  // Only DGKS currently accepts this parameter.
928  if (orthoType_ == "DGKS" && ! ortho_.is_null()) {
929  typedef DGKSOrthoManager<ScalarType, MV, OP> ortho_man_type;
930  // This cast should always succeed; it's a bug otherwise.
931  // (If the cast fails, then orthoType_ doesn't correspond
932  // to the OrthoManager subclass instance that we think we
933  // have, so we initialized the wrong subclass somehow.)
934  rcp_dynamic_cast<ortho_man_type>(ortho_)->setDepTol (orthoKappa_);
935  }
936  }
937  }
938 
939  // Convergence
940  typedef Belos::StatusTestCombo<ScalarType,MV,OP> StatusTestCombo_t;
941  typedef Belos::StatusTestGenResNorm<ScalarType,MV,OP> StatusTestResNorm_t;
942 
943  // Check for convergence tolerance
944  convTol_ = params_->get<MagnitudeType> ("Convergence Tolerance");
945  if (! impConvTest_.is_null()) {
946  impConvTest_->setTolerance (convTol_);
947  }
948  if (! expConvTest_.is_null()) {
949  expConvTest_->setTolerance (convTol_);
950  }
951 
952  // Check for a change in scaling, if so we need to build new residual tests.
953  if (params_->isParameter ("Implicit Residual Scaling")) {
954  std::string tempImpResScale =
955  getParameter<std::string> (*params_, "Implicit Residual Scaling");
956 
957  // Only update the scaling if it's different.
958  if (impResScale_ != tempImpResScale) {
959  ScaleType impResScaleType = convertStringToScaleType (tempImpResScale);
960  impResScale_ = tempImpResScale;
961 
962  if (! impConvTest_.is_null()) {
963  try {
964  impConvTest_->defineScaleForm (impResScaleType, Belos::TwoNorm);
965  }
966  catch (StatusTestError&) {
967  // Delete the convergence test so it gets constructed again.
968  impConvTest_ = null;
969  convTest_ = null;
970  }
971  }
972  }
973  }
974 
975  if (params_->isParameter("Explicit Residual Scaling")) {
976  std::string tempExpResScale =
977  getParameter<std::string> (*params_, "Explicit Residual Scaling");
978 
979  // Only update the scaling if it's different.
980  if (expResScale_ != tempExpResScale) {
981  ScaleType expResScaleType = convertStringToScaleType (tempExpResScale);
982  expResScale_ = tempExpResScale;
983 
984  if (! expConvTest_.is_null()) {
985  try {
986  expConvTest_->defineScaleForm (expResScaleType, Belos::TwoNorm);
987  }
988  catch (StatusTestError&) {
989  // Delete the convergence test so it gets constructed again.
990  expConvTest_ = null;
991  convTest_ = null;
992  }
993  }
994  }
995  }
996 
997  //
998  // Create iteration stopping criteria ("status tests") if we need
999  // to, by combining three different stopping criteria.
1000  //
1001  // First, construct maximum-number-of-iterations stopping criterion.
1002  if (maxIterTest_.is_null()) {
1003  maxIterTest_ = rcp (new StatusTestMaxIters<ScalarType,MV,OP> (maxIters_));
1004  } else {
1005  maxIterTest_->setMaxIters (maxIters_);
1006  }
1007 
1008  // Implicit residual test, using the native residual to determine if
1009  // convergence was achieved.
1010  if (impConvTest_.is_null()) {
1011  impConvTest_ = rcp (new StatusTestResNorm_t (convTol_));
1012  impConvTest_->defineScaleForm (convertStringToScaleType (impResScale_),
1013  Belos::TwoNorm);
1014  }
1015 
1016  // Explicit residual test once the native residual is below the tolerance
1017  if (expConvTest_.is_null()) {
1018  expConvTest_ = rcp (new StatusTestResNorm_t (convTol_));
1019  expConvTest_->defineResForm (StatusTestResNorm_t::Explicit, Belos::TwoNorm);
1020  expConvTest_->defineScaleForm (convertStringToScaleType (expResScale_),
1021  Belos::TwoNorm);
1022  }
1023  // Convergence test first tests the implicit residual, then the
1024  // explicit residual if the implicit residual test passes.
1025  if (convTest_.is_null()) {
1026  convTest_ = rcp (new StatusTestCombo_t (StatusTestCombo_t::SEQ,
1027  impConvTest_,
1028  expConvTest_));
1029  }
1030  // Construct the complete iteration stopping criterion:
1031  //
1032  // "Stop iterating if the maximum number of iterations has been
1033  // reached, or if the convergence test passes."
1034  sTest_ = rcp (new StatusTestCombo_t (StatusTestCombo_t::OR,
1035  maxIterTest_, convTest_));
1036  // Create the status test output class.
1037  // This class manages and formats the output from the status test.
1038  StatusTestOutputFactory<ScalarType,MV,OP> stoFactory (outputStyle_);
1039  outputTest_ = stoFactory.create (printer_, sTest_, outputFreq_,
1041 
1042  // Set the solver string for the output test
1043  std::string solverDesc = "Block GCRODR ";
1044  outputTest_->setSolverDesc (solverDesc);
1045 
1046  // Inform the solver manager that the current parameters were set.
1047  isSet_ = true;
1048  }
1049 
1050  // initializeStateStorage.
1051  template<class ScalarType, class MV, class OP>
1052  void
1054  {
1055 
1056  ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
1057 
1058  // Check if there is any multivector to clone from.
1059  Teuchos::RCP<const MV> rhsMV = problem_->getRHS();
1060 
1061  //The Dimension of the Krylov Subspace
1062  int KrylSpaDim = (numBlocks_ - 1) * blockSize_;
1063 
1064  //Number of columns in [U_ V_(:,1:KrylSpaDim)]
1065  int augSpaDim = KrylSpaDim + recycledBlocks_ + 1;// + 1 is for possible extra recycle vector
1066 
1067  //Number of columns in [C_ V_]
1068  int augSpaImgDim = KrylSpaDim + blockSize_ + recycledBlocks_+1;
1069 
1070  //TEMPORARY SKELETON DEFINITION OF THIS FUNCTION TO GET THINGS WORKING
1071  //NOT EVERYTHING IS INITIALIZE CORRECTLY YET.
1072 
1073  //INITIALIZE RECYCLE SPACE VARIABLES HERE
1074 
1075  //WE DO NOT ALLOCATE V HERE IN THIS SOLVERMANAGER. If no recycle space exists, then block_gmres_iter
1076  //will allocated V for us. If a recycle space already exists, then we will allocate V after updating the
1077  //recycle space for the current problem.
1078  // If the block Krylov subspace has not been initialized before, generate it using the RHS from lp_.
1079  /*if (V_ == Teuchos::null) {
1080  V_ = MVT::Clone( *rhsMV, (numBlocks_+1)*blockSize_ );
1081  }
1082  else{
1083  // Generate V_ by cloning itself ONLY if more space is needed.
1084  if (MVT::GetNumberVecs(*V_) < numBlocks_+1) {
1085  Teuchos::RCP<const MV> tmp = V_;
1086  V_ = MVT::Clone( *tmp, numBlocks_+1 );
1087  }
1088  }*/
1089 
1090  //INTITIALIZE SPACE FOR THE NEWLY COMPUTED RECYCLE SPACE VARIABLES HERE
1091 
1092  if (U_ == Teuchos::null) {
1093  U_ = MVT::Clone( *rhsMV, recycledBlocks_+1 );
1094  }
1095  else {
1096  // Generate U_ by cloning itself ONLY if more space is needed.
1097  if (MVT::GetNumberVecs(*U_) < recycledBlocks_+1) {
1098  Teuchos::RCP<const MV> tmp = U_;
1099  U_ = MVT::Clone( *tmp, recycledBlocks_+1 );
1100  }
1101  }
1102 
1103  // If the subspace has not been initialized before, generate it using the RHS from lp_.
1104  if (C_ == Teuchos::null) {
1105  C_ = MVT::Clone( *rhsMV, recycledBlocks_+1 );
1106  }
1107  else {
1108  // Generate C_ by cloning itself ONLY if more space is needed.
1109  if (MVT::GetNumberVecs(*C_) < recycledBlocks_+1) {
1110  Teuchos::RCP<const MV> tmp = C_;
1111  C_ = MVT::Clone( *tmp, recycledBlocks_+1 );
1112  }
1113  }
1114 
1115  // If the subspace has not been initialized before, generate it using the RHS from lp_.
1116  if (U1_ == Teuchos::null) {
1117  U1_ = MVT::Clone( *rhsMV, recycledBlocks_+1 );
1118  }
1119  else {
1120  // Generate U1_ by cloning itself ONLY if more space is needed.
1121  if (MVT::GetNumberVecs(*U1_) < recycledBlocks_+1) {
1122  Teuchos::RCP<const MV> tmp = U1_;
1123  U1_ = MVT::Clone( *tmp, recycledBlocks_+1 );
1124  }
1125  }
1126 
1127  // If the subspace has not been initialized before, generate it using the RHS from lp_.
1128  if (C1_ == Teuchos::null) {
1129  C1_ = MVT::Clone( *rhsMV, recycledBlocks_+1 );
1130  }
1131  else {
1132  // Generate C1_ by cloning itself ONLY if more space is needed.
1133  if (MVT::GetNumberVecs(*U1_) < recycledBlocks_+1) {
1134  Teuchos::RCP<const MV> tmp = C1_;
1135  C1_ = MVT::Clone( *tmp, recycledBlocks_+1 );
1136  }
1137  }
1138 
1139  // Generate R_ only if it doesn't exist
1140  if (R_ == Teuchos::null){
1141  R_ = MVT::Clone( *rhsMV, blockSize_ );
1142  }
1143 
1144  //INITIALIZE SOME WORK VARIABLES
1145 
1146  // Generate G_ only if it doesn't exist, otherwise resize it.
1147  if (G_ == Teuchos::null){
1148  G_ = Teuchos::rcp( new SDM( augSpaImgDim, augSpaDim ) );
1149  }
1150  else{
1151  if ( (G_->numRows() != augSpaImgDim) || (G_->numCols() != augSpaDim) )
1152  {
1153  G_->reshape( augSpaImgDim, augSpaDim );
1154  }
1155  G_->putScalar(zero);
1156  }
1157 
1158  // Generate H_ only if it doesn't exist by pointing it to a view of G_.
1159  if (H_ == Teuchos::null){
1160  H_ = Teuchos::rcp (new SDM ( Teuchos::View, *G_, KrylSpaDim + blockSize_, KrylSpaDim, recycledBlocks_+1 ,recycledBlocks_+1 ) );
1161  }
1162 
1163  // Generate F_ only if it doesn't exist, otherwise resize it.
1164  if (F_ == Teuchos::null){
1165  F_ = Teuchos::rcp( new SDM( recycledBlocks_+1, recycledBlocks_+1 ) );
1166  }
1167  else {
1168  if ( (F_->numRows() != recycledBlocks_+1) || (F_->numCols() != recycledBlocks_+1) ){
1169  F_->reshape( recycledBlocks_+1, recycledBlocks_+1 );
1170  }
1171  }
1172  F_->putScalar(zero);
1173 
1174  // Generate PP_ only if it doesn't exist, otherwise resize it.
1175  if (PP_ == Teuchos::null){
1176  PP_ = Teuchos::rcp( new SDM( augSpaImgDim, recycledBlocks_+1 ) );
1177  }
1178  else{
1179  if ( (PP_->numRows() != augSpaImgDim) || (PP_->numCols() != recycledBlocks_+1) ){
1180  PP_->reshape( augSpaImgDim, recycledBlocks_+1 );
1181  }
1182  }
1183 
1184  // Generate HP_ only if it doesn't exist, otherwise resize it.
1185  if (HP_ == Teuchos::null)
1186  HP_ = Teuchos::rcp( new SDM( augSpaImgDim, augSpaDim ) );
1187  else{
1188  if ( (HP_->numRows() != augSpaImgDim) || (HP_->numCols() != augSpaDim) ){
1189  HP_->reshape( augSpaImgDim, augSpaDim );
1190  }
1191  }
1192 
1193  // Size of tau_ will change during computation, so just be sure it starts with appropriate size
1194  tau_.resize(recycledBlocks_+1);
1195 
1196  // Size of work_ will change during computation, so just be sure it starts with appropriate size
1197  work_.resize(recycledBlocks_+1);
1198 
1199  // Size of ipiv_ will change during computation, so just be sure it starts with appropriate size
1200  ipiv_.resize(recycledBlocks_+1);
1201 
1202  }
1203 
1204 template<class ScalarType, class MV, class OP>
1206 
1207  ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
1208  ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
1209 
1210 
1211  int p = block_gmres_iter->getState().curDim; //Dimension of the Krylov space generated
1212  std::vector<int> index(keff);//we use this to index certain columns of U, C, and V to
1213  //get views into pieces of these matrices.
1214 
1215  //GET CORRECT PIECE OF MATRIX H APPROPRIATE TO SIZE OF KRYLOV SUBSPACE
1216  SDM HH(Teuchos::Copy, *H_, p+blockSize_, p);
1217  if(recycledBlocks_ >= p + blockSize_){//keep whole block Krylov subspace
1218  //IF THIS HAS HAPPENED, THIS MEANS WE CONVERGED DURING THIS CYCLE
1219  //THEREFORE, WE DO NOT CONSTRUCT C = A*U;
1220  index.resize(p);
1221  for (int ii=0; ii < p; ++ii) index[ii] = ii;
1222  Teuchos::RCP<MV> Utmp = MVT::CloneViewNonConst( *U_, index );
1223  MVT::SetBlock(*V_, index, *Utmp);
1224  keff = p;
1225  }
1226  else{ //use a subspace selection method to get recycle space
1227  int info = 0;
1228  Teuchos::RCP<SDM > PPtmp = rcp (new SDM ( Teuchos::View, *PP_, p, recycledBlocks_+1 ) );
1229  if(recycleMethod_ == "harmvecs"){
1230  keff = getHarmonicVecsKryl(p, HH, *PPtmp);
1231  printer_->stream(Debug) << "keff = " << keff << std::endl;
1232  }
1233 // Hereafter, only keff columns of PP are needed
1234 PPtmp = rcp (new SDM ( Teuchos::View, *PP_, p, keff ) );
1235 // Now get views into C, U, V
1236 index.resize(keff);
1237 for (int ii=0; ii<keff; ++ii) index[ii] = ii;
1238 Teuchos::RCP<MV> Ctmp = MVT::CloneViewNonConst( *C_, index );
1239 Teuchos::RCP<MV> Utmp = MVT::CloneViewNonConst( *U_, index );
1240 Teuchos::RCP<MV> U1tmp = MVT::CloneViewNonConst( *U1_, index );
1241 index.resize(p);
1242 for (int ii=0; ii < p; ++ii) index[ii] = ii;
1243 Teuchos::RCP<const MV> Vtmp = MVT::CloneView( *V_, index );
1244 
1245 // Form U (the subspace to recycle)
1246 // U = newstate.V(:,1:p) * PP;
1247 MVT::MvTimesMatAddMv( one, *Vtmp, *PPtmp, zero, *U1tmp );
1248 
1249 // Step #1: Form HP = H*P
1250 SDM HPtmp( Teuchos::View, *HP_, p+blockSize_, keff );
1251 HPtmp.multiply( Teuchos::NO_TRANS, Teuchos::NO_TRANS, one, *H_, *PPtmp, zero );
1252 // Step #1.5: Perform workspace size query for QR factorization of HP
1253 int lwork = -1;
1254 tau_.resize(keff);
1255 lapack.GEQRF(HPtmp.numRows(),HPtmp.numCols(),HPtmp.values(),HPtmp.stride(),&tau_[0],&work_[0],lwork,&info);
1256 TEUCHOS_TEST_FOR_EXCEPTION(info != 0, BlockGCRODRSolMgrLAPACKFailure, "Belos::BlockGCRODRSolMgr::solve(): LAPACK _GEQRF failed to compute a workspace size.");
1257 
1258 // Step #2: Compute QR factorization of HP
1259 lwork = (int)work_[0];
1260 work_.resize(lwork);
1261 lapack.GEQRF(HPtmp.numRows(),HPtmp.numCols(),HPtmp.values(),HPtmp.stride(),&tau_[0],&work_[0],lwork,&info);
1262 TEUCHOS_TEST_FOR_EXCEPTION(info != 0, BlockGCRODRSolMgrLAPACKFailure, "Belos::BlockGCRODRSolMgr::solve(): LAPACK _GEQRF failed to compute a QR factorization.");
1263 
1264 // Step #3: Explicitly construct Q and R factors
1265 // The upper triangular part of HP is copied into R and HP becomes Q.
1266 SDM Rtmp( Teuchos::View, *F_, keff, keff );
1267 for(int ii=0;ii<keff;ii++) { for(int jj=ii;jj<keff;jj++) Rtmp(ii,jj) = HPtmp(ii,jj); }
1268 lapack.ORGQR(HPtmp.numRows(),HPtmp.numCols(),HPtmp.numCols(),HPtmp.values(),HPtmp.stride(),&tau_[0],&work_[0],lwork,&info);
1269 TEUCHOS_TEST_FOR_EXCEPTION(info != 0, BlockGCRODRSolMgrLAPACKFailure, "Belos::BlockGCRODRSolMgr::solve(): LAPACK _ORGQR failed to construct the Q factor.");
1270  // Now we have [Q,R] = qr(H*P)
1271 
1272  // Now compute C = V(:,1:p+blockSize_) * Q
1273  index.resize( p+blockSize_ );
1274  for (int ii=0; ii < (p+blockSize_); ++ii) { index[ii] = ii; }
1275  Vtmp = MVT::CloneView( *V_, index ); // need new view into V (p+blockSize_ vectors now; needed p above)
1276  MVT::MvTimesMatAddMv( one, *Vtmp, HPtmp, zero, *Ctmp );
1277 
1278  // Finally, compute U = U*R^{-1}.
1279  // This unfortuntely requires me to form R^{-1} explicitly and execute U = U * R^{-1}, as
1280  // backsolve capabilities don't exist in the Belos::MultiVec class
1281 
1282 // Step #1: First, compute LU factorization of R
1283 ipiv_.resize(Rtmp.numRows());
1284 lapack.GETRF(Rtmp.numRows(),Rtmp.numCols(),Rtmp.values(),Rtmp.stride(),&ipiv_[0],&info);
1285 TEUCHOS_TEST_FOR_EXCEPTION(info != 0, BlockGCRODRSolMgrLAPACKFailure, "Belos::GCRODRSolMgr::solve(): LAPACK _GETRF failed to compute an LU factorization.");
1286 // Step #2: Form inv(R)
1287 lwork = Rtmp.numRows();
1288 work_.resize(lwork);
1289 lapack.GETRI(Rtmp.numRows(),Rtmp.values(),Rtmp.stride(),&ipiv_[0],&work_[0],lwork,&info);
1290 //TEUCHOS_TEST_FOR_EXCEPTION(info != 0, BlockGCRODRSolMgrLAPACKFailure, "Belos::GCRODRSolMgr::solve(): LAPACK _GETRI failed to invert triangular matrix.");
1291 // Step #3: Let U = U * R^{-1}
1292 MVT::MvTimesMatAddMv( one, *U1tmp, Rtmp, zero, *Utmp );
1293 
1294 } //end else from if(recycledBlocks_ >= p + 1)
1295 return;
1296 } // end buildRecycleSpaceKryl defnition
1297 
1298 template<class ScalarType, class MV, class OP>
1300  ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
1301  ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
1302 
1303  std::vector<MagnitudeType> d(keff);
1304  std::vector<int> index(numBlocks_+1);
1305 
1306  // Get the state
1307  BlockGCRODRIterState<ScalarType,MV> oldState = block_gcrodr_iter->getState();
1308  int p = oldState.curDim;
1309 
1310  // insufficient new information to update recycle space
1311  if (p<1) return;
1312 
1313  if(recycledBlocks_ >= keff + p){ //we add new Krylov vectors to existing recycle space
1314  // If this has happened, we have converged during this cycle. Therefore, do not construct C = A*C;
1315  index.resize(p);
1316  for (int ii=0; ii < p; ++ii) { index[ii] = keff+ii; } //get a view after current reycle vectors
1317  Teuchos::RCP<MV> Utmp = MVT::CloneViewNonConst( *U_, index );
1318  for (int ii=0; ii < p; ++ii) { index[ii] =ii; }
1319  MVT::SetBlock(*V_, index, *Utmp);
1320  keff += p;
1321  }
1322 
1323  // Take the norm of the recycled vectors
1324  {
1325  index.resize(keff);
1326  for (int ii=0; ii<keff; ++ii) { index[ii] = ii; }
1327  Teuchos::RCP<MV> Utmp = MVT::CloneViewNonConst( *U_, index );
1328  d.resize(keff);
1329  MVT::MvNorm( *Utmp, d );
1330  for (int i=0; i<keff; ++i)
1331  d[i] = one / d[i];
1332  MVT::MvScale( *Utmp, d );
1333  }
1334 
1335  // Get view into current "full" upper Hessnburg matrix
1336  // note that p describes the dimension of the iter+1 block Krylov space so we have to adjust how we use it to index Gtmp
1337  Teuchos::RCP<SDM> Gtmp = Teuchos::rcp( new SDM( Teuchos::View, *G_, p+keff, p+keff-blockSize_ ) );
1338 
1339  // Insert D into the leading keff x keff block of G
1340  for (int i=0; i<keff; ++i)
1341  (*Gtmp)(i,i) = d[i];
1342 
1343  // Compute the harmoic Ritz pairs for the generalized eigenproblem
1344  // getHarmonicVecsKryl assumes PP has recycledBlocks_+1 columns available
1345  // See previous block of comments for why we subtract p-blockSize_
1346  int keff_new;
1347  {
1348  SDM PPtmp( Teuchos::View, *PP_, p+keff-blockSize_, recycledBlocks_+1 );
1349  keff_new = getHarmonicVecsAugKryl( keff, p-blockSize_, *Gtmp, oldState.V, PPtmp );
1350  }
1351 
1352  // Code to form new U, C
1353  // U = [U V(:,1:p)] * P; (in two steps)
1354 
1355  // U(:,1:keff) = matmul(U(:,1:keff_old),PP(1:keff_old,1:keff)) (step 1)
1356  Teuchos::RCP<MV> U1tmp;
1357  {
1358  index.resize( keff );
1359  for (int ii=0; ii<keff; ++ii) { index[ii] = ii; }
1360  Teuchos::RCP<const MV> Utmp = MVT::CloneView( *U_, index );
1361  index.resize( keff_new );
1362  for (int ii=0; ii<keff_new; ++ii) { index[ii] = ii; }
1363  U1tmp = MVT::CloneViewNonConst( *U1_, index );
1364  SDM PPtmp( Teuchos::View, *PP_, keff, keff_new );
1365  MVT::MvTimesMatAddMv( one, *Utmp, PPtmp, zero, *U1tmp );
1366  }
1367 
1368  // U(:,1:keff) = U(:,1:keff) + matmul(V(:,1:m-k),PP(keff_old+1:m-k+keff_old,1:keff)) (step 2)
1369  {
1370  index.resize(p-blockSize_);
1371  for (int ii=0; ii < p-blockSize_; ii++) { index[ii] = ii; }
1372  Teuchos::RCP<const MV> Vtmp = MVT::CloneView( *V_, index );
1373  SDM PPtmp( Teuchos::View, *PP_, p-blockSize_, keff_new, keff );
1374  MVT::MvTimesMatAddMv( one, *Vtmp, PPtmp, one, *U1tmp );
1375  }
1376 
1377  // Form GP = G*P
1378  SDM HPtmp( Teuchos::View, *HP_, p+keff, keff_new );
1379  {
1380  SDM PPtmp( Teuchos::View, *PP_, p-blockSize_+keff, keff_new );
1381  HPtmp.multiply(Teuchos::NO_TRANS,Teuchos::NO_TRANS,one,*Gtmp,PPtmp,zero);
1382  }
1383 
1384  // Workspace size query for QR factorization HP= QF (the worksize will be placed in work_[0])
1385  int info = 0, lwork = -1;
1386  tau_.resize(keff_new);
1387  lapack.GEQRF(HPtmp.numRows(),HPtmp.numCols(),HPtmp.values(),HPtmp.stride(),&tau_[0],&work_[0],lwork,&info);
1388  TEUCHOS_TEST_FOR_EXCEPTION(info != 0,BlockGCRODRSolMgrLAPACKFailure,"Belos::BlockGCRODRSolMgr::solve(): LAPACK _GEQRF failed to compute a workspace size.");
1389 
1390  lwork = (int)work_[0];
1391  work_.resize(lwork);
1392  lapack.GEQRF(HPtmp.numRows(),HPtmp.numCols(),HPtmp.values(),HPtmp.stride(),&tau_[0],&work_[0],lwork,&info);
1393  TEUCHOS_TEST_FOR_EXCEPTION(info != 0,BlockGCRODRSolMgrLAPACKFailure,"Belos::BlockGCRODRSolMgr::solve(): LAPACK _GEQRF failed to compute a QR factorization.");
1394 
1395  // Explicitly construct Q and F factors
1396  // NOTE: The upper triangular part of HP is copied into F and HP becomes Q.
1397  SDM Ftmp( Teuchos::View, *F_, keff_new, keff_new );
1398  for(int i=0;i<keff_new;i++) { for(int j=i;j<keff_new;j++) Ftmp(i,j) = HPtmp(i,j); }
1399  lapack.ORGQR(HPtmp.numRows(),HPtmp.numCols(),HPtmp.numCols(),HPtmp.values(),HPtmp.stride(),&tau_[0],&work_[0],lwork,&info);
1400  TEUCHOS_TEST_FOR_EXCEPTION(info != 0,BlockGCRODRSolMgrLAPACKFailure,"Belos::BlockGCRODRSolMgr::solve(): LAPACK _ORGQR failed to construct the Q factor.");
1401 
1402  // Form orthonormalized C and adjust U accordingly so that C = A*U
1403  // C = [C V] * Q;
1404 
1405  // C(:,1:keff) = matmul(C(:,1:keff_old),QQ(1:keff_old,1:keff))
1406  {
1407  Teuchos::RCP<MV> C1tmp;
1408  {
1409  index.resize(keff);
1410  for (int i=0; i < keff; i++) { index[i] = i; }
1411  Teuchos::RCP<const MV> Ctmp = MVT::CloneView( *C_, index );
1412  index.resize(keff_new);
1413  for (int i=0; i < keff_new; i++) { index[i] = i; }
1414  C1tmp = MVT::CloneViewNonConst( *C1_, index );
1415  SDM PPtmp( Teuchos::View, *HP_, keff, keff_new );
1416  MVT::MvTimesMatAddMv( one, *Ctmp, PPtmp, zero, *C1tmp );
1417  }
1418  // Now compute C += V(:,1:p+1) * Q
1419  {
1420  index.resize( p );
1421  for (int i=0; i < p; ++i) { index[i] = i; }
1422  Teuchos::RCP<const MV> Vtmp = MVT::CloneView( *V_, index );
1423  SDM PPtmp( Teuchos::View, *HP_, p, keff_new, keff, 0 );
1424  MVT::MvTimesMatAddMv( one, *Vtmp, PPtmp, one, *C1tmp );
1425  }
1426  }
1427 
1428  // C_ = C1_; (via a swap)
1429  std::swap(C_, C1_);
1430 
1431  // Finally, compute U_ = U_*R^{-1}
1432  // First, compute LU factorization of R
1433  ipiv_.resize(Ftmp.numRows());
1434  lapack.GETRF(Ftmp.numRows(),Ftmp.numCols(),Ftmp.values(),Ftmp.stride(),&ipiv_[0],&info);
1435  TEUCHOS_TEST_FOR_EXCEPTION(info != 0,BlockGCRODRSolMgrLAPACKFailure,"Belos::BlockGCRODRSolMgr::solve(): LAPACK _GETRF failed to compute an LU factorization.");
1436 
1437  // Now, form inv(R)
1438  lwork = Ftmp.numRows();
1439  work_.resize(lwork);
1440  lapack.GETRI(Ftmp.numRows(),Ftmp.values(),Ftmp.stride(),&ipiv_[0],&work_[0],lwork,&info);
1441  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, BlockGCRODRSolMgrLAPACKFailure,"Belos::BlockGCRODRSolMgr::solve(): LAPACK _GETRI failed to compute an LU factorization.");
1442 
1443  {
1444  index.resize(keff_new);
1445  for (int i=0; i < keff_new; i++) { index[i] = i; }
1446  Teuchos::RCP<MV> Utmp = MVT::CloneViewNonConst( *U_, index );
1447  MVT::MvTimesMatAddMv( one, *U1tmp, Ftmp, zero, *Utmp );
1448  }
1449 
1450  // Set the current number of recycled blocks and subspace
1451  // dimension with the Block GCRO-DR iteration.
1452  if (keff != keff_new) {
1453  keff = keff_new;
1454  block_gcrodr_iter->setSize( keff, numBlocks_ );
1455  // Important to zero this out before next cyle
1456  SDM b1( Teuchos::View, *G_, recycledBlocks_+2, 1, 0, recycledBlocks_ );
1457  b1.putScalar(zero);
1458  }
1459 
1460 } //end buildRecycleSpaceAugKryl definition
1461 
1462 template<class ScalarType, class MV, class OP>
1463 int BlockGCRODRSolMgr<ScalarType,MV,OP>::getHarmonicVecsAugKryl(int keff, int m, const SDM& GG, const Teuchos::RCP<const MV>& VV, SDM& PP){
1464  int i, j;
1465  int m2 = GG.numCols();
1466  bool xtraVec = false;
1467  ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
1468  ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
1469  std::vector<int> index;
1470 
1471  // Real and imaginary eigenvalue components
1472  std::vector<ScalarType> wr(m2), wi(m2);
1473 
1474  // Magnitude of harmonic Ritz values
1475  std::vector<MagnitudeType> w(m2);
1476 
1477  // Real and imaginary (right) eigenvectors; Don't zero out matrix when constructing
1478  SDM vr(m2,m2,false);
1479 
1480  // Sorted order of harmonic Ritz values
1481  std::vector<int> iperm(m2);
1482 
1483  // Set flag indicating recycle space has been generated this solve
1484  builtRecycleSpace_ = true;
1485 
1486  // Form matrices for generalized eigenproblem
1487 
1488  // B = G' * G; Don't zero out matrix when constructing
1489  SDM B(m2,m2,false);
1490  B.multiply(Teuchos::TRANS,Teuchos::NO_TRANS,one,GG,GG,zero);
1491 
1492  // A_tmp = | C'*U 0 |
1493  // | V_{m+1}'*U I |
1494  SDM A_tmp( keff+m+blockSize_, keff+m );
1495 
1496 
1497  // A_tmp(1:keff,1:keff) = C' * U;
1498  index.resize(keff);
1499  for (int i=0; i<keff; ++i) { index[i] = i; }
1500  Teuchos::RCP<const MV> Ctmp = MVT::CloneView( *C_, index );
1501  Teuchos::RCP<const MV> Utmp = MVT::CloneView( *U_, index );
1502  SDM A11( Teuchos::View, A_tmp, keff, keff );
1503  MVT::MvTransMv( one, *Ctmp, *Utmp, A11 );
1504 
1505  // A_tmp(keff+1:m-k+keff+1,1:keff) = V' * U;
1506  SDM A21( Teuchos::View, A_tmp, m+blockSize_, keff, keff );
1507  index.resize(m+blockSize_);
1508  for (i=0; i < m+blockSize_; i++) { index[i] = i; }
1509  Teuchos::RCP<const MV> Vp = MVT::CloneView( *VV, index );
1510  MVT::MvTransMv( one, *Vp, *Utmp, A21 );
1511 
1512  // A_tmp(keff+1:m-k+keff,keff+1:m-k+keff) = eye(m-k);
1513  for( i=keff; i<keff+m; i++)
1514  A_tmp(i,i) = one;
1515 
1516  // A = G' * A_tmp;
1517  SDM A( m2, A_tmp.numCols() );
1518  A.multiply( Teuchos::TRANS, Teuchos::NO_TRANS, one, GG, A_tmp, zero );
1519 
1520  // Compute k smallest harmonic Ritz pairs
1521  // SUBROUTINE DGGEVX( BALANC, JOBVL, JOBVR, SENSE, N, A, LDA, B, LDB,
1522  // ALPHAR, ALPHAI, BETA, VL, LDVL, VR, LDVR, ILO,
1523  // IHI, LSCALE, RSCALE, ABNRM, BBNRM, RCONDE,
1524  // RCONDV, WORK, LWORK, IWORK, BWORK, INFO )
1525  // MLP: 'SCALING' in DGGEVX generates incorrect eigenvalues. Therefore, only permuting
1526  char balanc='P', jobvl='N', jobvr='V', sense='N';
1527  int ld = A.numRows();
1528  int lwork = 6*ld;
1529  int ldvl = ld, ldvr = ld;
1530  int info = 0,ilo = 0,ihi = 0;
1531  ScalarType abnrm = zero, bbnrm = zero;
1532  ScalarType *vl = 0; // This is never referenced by dggevx if jobvl == 'N'
1533  std::vector<ScalarType> beta(ld);
1534  std::vector<ScalarType> work(lwork);
1535  std::vector<MagnitudeType> lscale(ld), rscale(ld);
1536  std::vector<MagnitudeType> rconde(ld), rcondv(ld);
1537  std::vector<int> iwork(ld+6);
1538  int *bwork = 0; // If sense == 'N', bwork is never referenced
1539  lapack.GGEVX(balanc, jobvl, jobvr, sense, ld, A.values(), ld, B.values(), ld, &wr[0], &wi[0],
1540  &beta[0], vl, ldvl, vr.values(), ldvr, &ilo, &ihi, &lscale[0], &rscale[0],
1541  &abnrm, &bbnrm, &rconde[0], &rcondv[0], &work[0], lwork, &iwork[0], bwork, &info);
1542  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, BlockGCRODRSolMgrLAPACKFailure, "Belos::BlockGCRODRSolMgr::solve(): LAPACK GGEVX failed to compute eigensolutions.");
1543 
1544  // Construct magnitude of each harmonic Ritz value
1545  // NOTE : Forming alpha/beta *should* be okay here, given assumptions on construction of matrix pencil above
1546  for( i=0; i<ld; i++ ) // Construct magnitude of each harmonic Ritz value
1547  w[i] = Teuchos::ScalarTraits<ScalarType>::squareroot( (wr[i]/beta[i])*(wr[i]/beta[i]) + (wi[i]/beta[i])*(wi[i]/beta[i]) );
1548 
1549  this->sort(w,ld,iperm);
1550 
1551  // Determine exact size for PP (i.e., determine if we need to store an additional vector)
1552  if (wi[iperm[ld-recycledBlocks_]] != zero) {
1553  int countImag = 0;
1554  for ( i=ld-recycledBlocks_; i<ld; i++ )
1555  if (wi[iperm[i]] != zero) countImag++;
1556  // Check to see if this count is even or odd:
1557  if (countImag % 2) xtraVec = true;
1558  }
1559 
1560  // Select recycledBlocks_ smallest eigenvectors
1561 
1562  for( i=0; i<recycledBlocks_; i++ )
1563  for( j=0; j<ld; j++ )
1564  PP(j,i) = vr(j,iperm[ld-recycledBlocks_+i]);
1565 
1566  if (xtraVec) { // we need to store one more vector
1567  if (wi[iperm[ld-recycledBlocks_]] > 0) { // I picked the "real" component
1568  for( j=0; j<ld; j++ ) // so get the "imag" component
1569  PP(j,recycledBlocks_) = vr(j,iperm[ld-recycledBlocks_]+1);
1570  }
1571  else { // I picked the "imag" component
1572  for( j=0; j<ld; j++ ) // so get the "real" component
1573  PP(j,recycledBlocks_) = vr(j,iperm[ld-recycledBlocks_]-1);
1574  }
1575  }
1576 
1577  // Return whether we needed to store an additional vector
1578  if (xtraVec)
1579  return recycledBlocks_+1;
1580  else
1581  return recycledBlocks_;
1582 
1583 } //end getHarmonicVecsAugKryl definition
1584 
1585 template<class ScalarType, class MV, class OP>
1586 int BlockGCRODRSolMgr<ScalarType,MV,OP>::getHarmonicVecsKryl(int m, const SDM& HH, SDM& PP){
1587  bool xtraVec = false;
1588  ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
1589  ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
1590 
1591  // Real and imaginary eigenvalue components
1592  std::vector<MagnitudeType> wr(m), wi(m);
1593 
1594  // Real and imaginary (right) eigenvectors; Don't zero out matrix when constructing
1595  SDM vr(m,m,false);
1596 
1597  // Magnitude of harmonic Ritz values
1598  std::vector<MagnitudeType> w(m);
1599 
1600  // Sorted order of harmonic Ritz values, also used for DGEEV
1601  std::vector<int> iperm(m);
1602 
1603  // Size of workspace and workspace for DGEEV
1604  int lwork = 4*m;
1605  std::vector<ScalarType> work(lwork);
1606 
1607  // Output info
1608  int info = 0;
1609 
1610  // Set flag indicating recycle space has been generated this solve
1611  builtRecycleSpace_ = true;
1612 
1613  // Solve linear system: H_m^{-H}*E_m where E_m is the last blockSize_ columns of the identity matrix
1614  SDM HHt( HH, Teuchos::TRANS );
1615  Teuchos::RCP<SDM> harmRitzMatrix = rcp( new SDM( m, blockSize_));
1616 
1617  //Initialize harmRitzMatrix as E_m
1618  for(int i=0; i<=blockSize_-1; i++) (*harmRitzMatrix)[blockSize_-1-i][harmRitzMatrix->numRows()-1-i] = 1;
1619 
1620  //compute harmRitzMatrix <- H_m^{-H}*E_m
1621  lapack.GESV(m, blockSize_, HHt.values(), HHt.stride(), &iperm[0], harmRitzMatrix->values(), harmRitzMatrix->stride(), &info);
1622 
1623  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, BlockGCRODRSolMgrLAPACKFailure, "Belos::BlockGCRODRSolMgr::solve(): LAPACK GESV failed to compute a solution.");
1624  // Compute H_m + H_m^{-H}*E_m*H_lbl^{H}*H_lbl
1625  // H_lbl is bottom-right block of H_, which is a blockSize_ x blockSize_ matrix
1626 
1627  Teuchos::SerialDenseMatrix<int, ScalarType> H_lbl(Teuchos::View, HH, blockSize_, blockSize_, (HH).numRows()-blockSize_, (HH).numCols()-blockSize_ );
1628  Teuchos::SerialDenseMatrix<int, ScalarType> H_lbl_t( H_lbl, Teuchos::TRANS );
1629 
1630  { //So that HTemp will fall out of scope
1631 
1632  // HH_lbl_t <- H_lbl_t*H_lbl
1633  Teuchos::RCP<SDM> Htemp = Teuchos::null;
1634  Htemp = Teuchos::rcp(new SDM(H_lbl_t.numRows(), H_lbl_t.numCols()));
1635  Htemp -> multiply(Teuchos::NO_TRANS, Teuchos::NO_TRANS, one, H_lbl_t, H_lbl, zero);
1636  H_lbl_t.assign(*Htemp);
1637  // harmRitzMatrix <- harmRitzMatrix*HH_lbl_t
1638  Htemp = Teuchos::rcp(new SDM(harmRitzMatrix -> numRows(), harmRitzMatrix -> numCols()));
1639  Htemp -> multiply(Teuchos::NO_TRANS, Teuchos::NO_TRANS, one, *harmRitzMatrix, H_lbl_t, zero);
1640  harmRitzMatrix -> assign(*Htemp);
1641 
1642  // We need to add harmRitzMatrix to the last blockSize_ columns of HH and store the result harmRitzMatrix
1643  int harmColIndex, HHColIndex;
1644  Htemp = Teuchos::rcp(new SDM(Teuchos::Copy,HH,HH.numRows()-blockSize_,HH.numCols()));
1645  for(int i = 0; i<blockSize_; i++){
1646  harmColIndex = harmRitzMatrix -> numCols() - i -1;
1647  HHColIndex = m-i-1;
1648  for(int j=0; j<m; j++) (*Htemp)[HHColIndex][j] += (*harmRitzMatrix)[harmColIndex][j];
1649  }
1650  harmRitzMatrix = Htemp;
1651  }
1652 
1653  // Revise to do query for optimal workspace first
1654  // Create simple storage for the left eigenvectors, which we don't care about.
1655 
1656  const int ldvl = m;
1657  ScalarType* vl = 0;
1658  lapack.GEEV('N', 'V', m, harmRitzMatrix -> values(), harmRitzMatrix -> stride(), &wr[0], &wi[0],
1659  vl, ldvl, vr.values(), vr.stride(), &work[0], lwork, &info);
1660  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, BlockGCRODRSolMgrLAPACKFailure,"Belos::BlockGCRODRSolMgr::solve(): LAPACK GEEV failed to compute eigensolutions.");
1661 
1662  // Construct magnitude of each harmonic Ritz value
1663  for( int i=0; i<m; ++i ) w[i] = Teuchos::ScalarTraits<ScalarType>::squareroot( wr[i]*wr[i] + wi[i]*wi[i] );
1664 
1665  this->sort(w, m, iperm);
1666 
1667  // Determine exact size for PP (i.e., determine if we need to store an additional vector)
1668  if (wi[iperm[recycledBlocks_-1]] != zero) {
1669  int countImag = 0;
1670  for (int i=0; i<recycledBlocks_; ++i )
1671  if (wi[iperm[i]] != zero) countImag++;
1672  // Check to see if this count is even or odd:
1673  if (countImag % 2) xtraVec = true;
1674  }
1675 
1676  // Select recycledBlocks_ smallest eigenvectors
1677  for( int i=0; i<recycledBlocks_; ++i )
1678  for(int j=0; j<m; j++ )
1679  PP(j,i) = vr(j,iperm[i]);
1680 
1681  if (xtraVec) { // we need to store one more vector
1682  if (wi[iperm[recycledBlocks_-1]] > 0) { // I picked the "real" component
1683  for(int j=0; j<m; ++j ) // so get the "imag" component
1684  PP(j,recycledBlocks_) = vr(j,iperm[recycledBlocks_-1]+1);
1685  }
1686  else{ // I picked the "imag" component
1687  for(int j=0; j<m; ++j ) // so get the "real" component
1688  PP(j,recycledBlocks_) = vr(j,iperm[recycledBlocks_-1]-1);
1689  }
1690  }
1691 
1692  // Return whether we needed to store an additional vector
1693  if (xtraVec) {
1694  printer_->stream(Debug) << "Recycled " << recycledBlocks_+1 << " vectors" << std::endl;
1695  return recycledBlocks_+1;
1696  }
1697  printer_->stream(Debug) << "Recycled " << recycledBlocks_ << " vectors" << std::endl;
1698  return recycledBlocks_;
1699 
1700 } //end getHarmonicVecsKryl
1701 
1702 
1703 // This method sorts list of n floating-point numbers and return permutation vector
1704 template<class ScalarType, class MV, class OP>
1705 void BlockGCRODRSolMgr<ScalarType,MV,OP>::sort(std::vector<ScalarType>& dlist, int n, std::vector<int>& iperm) {
1706  int l, r, j, i, flag;
1707  int RR2;
1708  ScalarType dRR, dK;
1709 
1710  // Initialize the permutation vector.
1711  for(j=0;j<n;j++)
1712  iperm[j] = j;
1713 
1714  if (n <= 1) return;
1715 
1716  l = n / 2 + 1;
1717  r = n - 1;
1718  l = l - 1;
1719  dRR = dlist[l - 1];
1720  dK = dlist[l - 1];
1721 
1722  RR2 = iperm[l - 1];
1723  while (r != 0) {
1724  j = l;
1725  flag = 1;
1726  while (flag == 1) {
1727  i = j;
1728  j = j + j;
1729  if (j > r + 1)
1730  flag = 0;
1731  else {
1732  if (j < r + 1)
1733  if (dlist[j] > dlist[j - 1]) j = j + 1;
1734  if (dlist[j - 1] > dK) {
1735  dlist[i - 1] = dlist[j - 1];
1736  iperm[i - 1] = iperm[j - 1];
1737  }
1738  else {
1739  flag = 0;
1740  }
1741  }
1742  }
1743  dlist[i - 1] = dRR;
1744  iperm[i - 1] = RR2;
1745  if (l == 1) {
1746  dRR = dlist [r];
1747  RR2 = iperm[r];
1748  dK = dlist[r];
1749  dlist[r] = dlist[0];
1750  iperm[r] = iperm[0];
1751  r = r - 1;
1752  }
1753  else {
1754  l = l - 1;
1755  dRR = dlist[l - 1];
1756  RR2 = iperm[l - 1];
1757  dK = dlist[l - 1];
1758  }
1759  }
1760  dlist[0] = dRR;
1761  iperm[0] = RR2;
1762 } //end sort() definition
1763 
1764 template<class ScalarType, class MV, class OP>
1766  using Teuchos::RCP;
1767  using Teuchos::rcp;
1768  using Teuchos::rcp_const_cast;
1769 
1770  // MLP: NEED TO ADD CHECK IF PARAMETERS ARE SET LATER
1771 
1772  ScalarType one = Teuchos::ScalarTraits<ScalarType>::one();
1773  ScalarType zero = Teuchos::ScalarTraits<ScalarType>::zero();
1774  std::vector<int> index(numBlocks_+1);
1775 
1776  // MLP: EXCEPTION TESTING SHOULD GO HERE
1777 
1778  //THE FOLLOWING BLOCK OF CODE IS TO INFORM THE PROBLEM HOW MANY RIGHT HAND
1779  //SIDES WILL BE SOLVED. IF THE CHOSEN BLOCK SIZE IS THE SAME AS THE NUMBER
1780  //OF RIGHT HAND SIDES IN THE PROBLEM THEN WE PASS THE PROBLEM
1781  //INDICES FOR ALL RIGHT HAND SIDES. IF BLOCK SIZE IS GREATER THAN
1782  //THE NUMBER OF RIGHT HAND SIDES AND THE USER HAS ADAPTIVE BLOCK SIZING
1783  //TURNED OFF, THEN THE PROBLEM WILL GENERATE RANDOM RIGHT HAND SIDES SO WE HAVE AS MANY
1784  //RIGHT HAND SIDES AS BLOCK SIZE INDICATES. THIS MAY NEED TO BE CHANGED
1785  //LATER TO ACCOMADATE SMARTER CHOOSING OF FICTITIOUS RIGHT HAND SIDES.
1786  //THIS CODE IS DIRECTLY LIFTED FROM BelosBlockGmresSolMgr.hpp.
1787 
1788  // Create indices for the linear systems to be solved.
1789  int startPtr = 0;
1790  int numRHS2Solve = MVT::GetNumberVecs( *(problem_->getRHS()) );
1791  int numCurrRHS = ( numRHS2Solve < blockSize_) ? numRHS2Solve : blockSize_;
1792 
1793  //currIdx holds indices to all right-hand sides to be solved
1794  //or -1's to indicate that random right-hand sides should be generated
1795  std::vector<int> currIdx;
1796 
1797  if ( adaptiveBlockSize_ ) {
1798  blockSize_ = numCurrRHS;
1799  currIdx.resize( numCurrRHS );
1800  for (int i=0; i<numCurrRHS; ++i)
1801  currIdx[i] = startPtr+i;
1802  }
1803  else {
1804  currIdx.resize( blockSize_ );
1805  for (int i=0; i<numCurrRHS; ++i)
1806  currIdx[i] = startPtr+i;
1807  for (int i=numCurrRHS; i<blockSize_; ++i)
1808  currIdx[i] = -1;
1809  }
1810 
1811  // Inform the linear problem of the linear systems to solve/generate.
1812  problem_->setLSIndex( currIdx );
1813 
1814  //ADD ERROR CHECKING TO MAKE SURE SIZE OF BLOCK KRYLOV SUBSPACE NOT LARGER THAN dim
1815  //ptrdiff_t dim = MVText::GetGlobalLength( *(problem_->getRHS()) );
1816 
1817  // reset loss of orthogonality flag
1818  loaDetected_ = false;
1819 
1820  // Assume convergence is achieved, then let any failed convergence set this to false.
1821  bool isConverged = true;
1822 
1823  // Initialize storage for all state variables
1824  initializeStateStorage();
1825 
1826  // Parameter list MLP: WE WILL NEED TO ASSIGN SOME PARAMETER VALUES LATER
1827  Teuchos::ParameterList plist;
1828 
1829  while (numRHS2Solve > 0){ //This loops through each block of RHS's being solved
1830  // **************************************************************************************************************************
1831  // Begin initial solver preparations. Either update U,C for new operator or generate an initial space using a cycle of GMRES
1832  // **************************************************************************************************************************
1833  int prime_iterations;
1834  if(keff > 0){//If there is already a subspace to recycle, then use it
1835  // Update U, C for the new operator
1836 
1837 // TEUCHOS_TEST_FOR_EXCEPTION(keff < recycledBlocks_,BlockGCRODRSolMgrRecyclingFailure,
1838 // "Belos::BlockGCRODRSolMgr::solve(): Requested size of recycled subspace is not consistent with the current recycle subspace.");
1839  printer_->stream(Debug) << " Now solving RHS index " << currIdx[0] << " using recycled subspace of dimension " << keff << std::endl << std::endl;
1840 
1841  // Compute image of U_ under the new operator
1842  index.resize(keff);
1843  for (int ii=0; ii<keff; ++ii) { index[ii] = ii; }
1844  RCP<const MV> Utmp = MVT::CloneView( *U_, index );
1845  RCP<MV> Ctmp = MVT::CloneViewNonConst( *C_, index );
1846  problem_->apply( *Utmp, *Ctmp );
1847 
1848  RCP<MV> U1tmp = MVT::CloneViewNonConst( *U1_, index );
1849 
1850  // Orthogonalize this block
1851  // Get a matrix to hold the orthonormalization coefficients.
1852  SDM Ftmp( Teuchos::View, *F_, keff, keff );
1853  int rank = ortho_->normalize(*Ctmp, rcp(&Ftmp,false));
1854  // Throw an error if we could not orthogonalize this block
1855  TEUCHOS_TEST_FOR_EXCEPTION(rank != keff,BlockGCRODRSolMgrOrthoFailure,"Belos::BlockGCRODRSolMgr::solve(): Failed to compute orthonormal basis for initial recycled subspace.");
1856 
1857  // U_ = U_*F^{-1}
1858  // First, compute LU factorization of R
1859  int info = 0;
1860  ipiv_.resize(Ftmp.numRows());
1861  lapack.GETRF(Ftmp.numRows(),Ftmp.numCols(),Ftmp.values(),Ftmp.stride(),&ipiv_[0],&info);
1862  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, BlockGCRODRSolMgrLAPACKFailure,"Belos::BlockGCRODRSolMgr::solve(): LAPACK _GETRF failed to compute an LU factorization.");
1863 
1864  // Now, form inv(F)
1865  int lwork = Ftmp.numRows();
1866  work_.resize(lwork);
1867  lapack.GETRI(Ftmp.numRows(),Ftmp.values(),Ftmp.stride(),&ipiv_[0],&work_[0],lwork,&info);
1868  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, BlockGCRODRSolMgrLAPACKFailure,"Belos::BlockGCRODRSolMgr::solve(): LAPACK _GETRI failed to invert triangular matrix.");
1869 
1870  // U_ = U1_; (via a swap)
1871  MVT::MvTimesMatAddMv( one, *Utmp, Ftmp, zero, *U1tmp );
1872  std::swap(U_, U1_);
1873 
1874  // Must reinitialize after swap
1875  index.resize(keff);
1876  for (int ii=0; ii<keff; ++ii) { index[ii] = ii; }
1877  Ctmp = MVT::CloneViewNonConst( *C_, index );
1878  Utmp = MVT::CloneView( *U_, index );
1879 
1880  // Compute C_'*R_
1881  SDM Ctr(keff,blockSize_);
1882  problem_->computeCurrPrecResVec( &*R_ );
1883  MVT::MvTransMv( one, *Ctmp, *R_, Ctr );
1884 
1885  // Update solution ( x += U_*C_'*R_ )
1886  RCP<MV> update = MVT::Clone( *problem_->getCurrLHSVec(), blockSize_ );
1887  MVT::MvInit( *update, 0.0 );
1888  MVT::MvTimesMatAddMv( one, *Utmp, Ctr, one, *update );
1889  problem_->updateSolution( update, true );
1890 
1891  // Update residual norm ( r -= C_*C_'*R_ )
1892  MVT::MvTimesMatAddMv( -one, *Ctmp, Ctr, one, *R_ );
1893 
1894  // We recycled space from previous call
1895  prime_iterations = 0;
1896 
1897  // Since we have a previous recycle space, we do not need block_gmres_iter
1898  // and we must allocate V ourselves. See comments in initialize() routine for
1899  // further explanation.
1900  if (V_ == Teuchos::null) {
1901  // Check if there is a multivector to clone from.
1902  Teuchos::RCP<const MV> rhsMV = problem_->getRHS();
1903  V_ = MVT::Clone( *rhsMV, (numBlocks_+1)*blockSize_ );
1904  }
1905  else{
1906  // Generate V_ by cloning itself ONLY if more space is needed.
1907  if (MVT::GetNumberVecs(*V_) < (numBlocks_+1)*blockSize_ ) {
1908  Teuchos::RCP<const MV> tmp = V_;
1909  V_ = MVT::Clone( *tmp, (numBlocks_+1)*blockSize_ );
1910  }
1911  }
1912  } //end if(keff > 0)
1913  else{ //if there was no subspace to recycle, then build one
1914  printer_->stream(Debug) << " No recycled subspace available for RHS index " << std::endl << std::endl;
1915 
1916  Teuchos::ParameterList primeList;
1917  //we set this as numBlocks-1 because that is the Krylov dimension we want
1918  //so that the size of the Hessenberg created matches that of what we were expecting.
1919  primeList.set("Num Blocks",numBlocks_-1);
1920  primeList.set("Block Size",blockSize_);
1921  primeList.set("Recycled Blocks",0);
1922  primeList.set("Keep Hessenberg",true);
1923  primeList.set("Initialize Hessenberg",true);
1924 
1925  ptrdiff_t dim = MVText::GetGlobalLength( *(problem_->getRHS()) );
1926  if (blockSize_*static_cast<ptrdiff_t>(numBlocks_) > dim) {//if user has selected a total subspace dimension larger than system dimension
1927  ptrdiff_t tmpNumBlocks = 0;
1928  if (blockSize_ == 1)
1929  tmpNumBlocks = dim / blockSize_; // Allow for a good breakdown.
1930  else{
1931  tmpNumBlocks = ( dim - blockSize_) / blockSize_; // Allow for restarting.
1932  printer_->stream(Warnings) << "Belos::BlockGmresSolMgr::solve(): Warning! Requested Krylov subspace dimension is larger than operator dimension!"
1933  << std::endl << "The maximum number of blocks allowed for the Krylov subspace will be adjusted to " << tmpNumBlocks << std::endl;
1934  primeList.set("Num Blocks",Teuchos::as<int>(tmpNumBlocks));
1935  }
1936  }
1937  else{
1938  primeList.set("Num Blocks",numBlocks_-1);
1939  }
1940  //Create Block GMRES iteration object to perform one cycle of GMRES
1941  Teuchos::RCP<BlockGmresIter<ScalarType,MV,OP> > block_gmres_iter;
1942  block_gmres_iter = Teuchos::rcp( new BlockGmresIter<ScalarType,MV,OP>(problem_,printer_,outputTest_,ortho_,primeList) );
1943 
1944  // MLP: ADD LOGIC TO DEAL WITH USER ASKING TO GENERATE A LARGER SPACE THAN dim AS IN HEIDI'S BlockGmresSolMgr CODE (DIDN'T WE ALREADY DO THIS SOMEWHERE?)
1945  block_gmres_iter->setSize( blockSize_, numBlocks_-1 );
1946 
1947  //Create the first block in the current BLOCK Krylov basis (using residual)
1948  Teuchos::RCP<MV> V_0;
1949  if (currIdx[blockSize_-1] == -1) {//if augmented with random RHS's
1950  V_0 = MVT::Clone( *(problem_->getInitPrecResVec()), blockSize_ );
1951  problem_->computeCurrPrecResVec( &*V_0 );
1952  }
1953  else {
1954  V_0 = MVT::CloneCopy( *(problem_->getInitPrecResVec()), currIdx );
1955  }
1956 
1957  // Get a matrix to hold the orthonormalization coefficients.
1958  Teuchos::RCP<SDM > z_0 = Teuchos::rcp( new SDM( blockSize_, blockSize_ ) );
1959 
1960  // Orthonormalize the new V_0
1961  int rank = ortho_->normalize( *V_0, z_0 );
1962  // MLP: ADD EXCEPTION IF INITIAL BLOCK IS RANK DEFFICIENT
1963 
1964  // Set the new state and initialize the iteration.
1966  newstate.V = V_0;
1967  newstate.z = z_0;
1968  newstate.curDim = 0;
1969  block_gmres_iter->initializeGmres(newstate);
1970 
1971  bool primeConverged = false;
1972 
1973  try {
1974  printer_->stream(Debug) << " Preparing to Iterate!!!!" << std::endl << std::endl;
1975  block_gmres_iter->iterate();
1976 
1977  // *********************
1978  // check for convergence
1979  // *********************
1980  if ( convTest_->getStatus() == Passed ) {
1981  printer_->stream(Debug) << "We converged during the prime the pump stage" << std::endl << std::endl;
1982  primeConverged = !(expConvTest_->getLOADetected());
1983  if ( expConvTest_->getLOADetected() ) {
1984  // we don't have convergence
1985  loaDetected_ = true;
1986  printer_->stream(Warnings) << "Belos::BlockGmresSolMgr::solve(): Warning! Solver has experienced a loss of accuracy!" << std::endl;
1987  }
1988  }
1989  // *******************************************
1990  // check for maximum iterations of block GMRES
1991  // *******************************************
1992  else if( maxIterTest_->getStatus() == Passed ) {
1993  // we don't have convergence
1994  primeConverged = false;
1995  }
1996  // ****************************************************************
1997  // We need to recycle and continue, print a message indicating this
1998  // ****************************************************************
1999  else{ //debug statements
2000  printer_->stream(Debug) << " We did not converge on priming cycle of Block GMRES. Therefore we recycle and restart. " << std::endl << std::endl;
2001  }
2002  } //end try
2003  catch (const GmresIterationOrthoFailure &e) {
2004  // If the block size is not one, it's not considered a lucky breakdown.
2005  if (blockSize_ != 1) {
2006  printer_->stream(Errors) << "Error! Caught std::exception in BlockGmresIter::iterate() at iteration "
2007  << block_gmres_iter->getNumIters() << std::endl
2008  << e.what() << std::endl;
2009  if (convTest_->getStatus() != Passed)
2010  primeConverged = false;
2011  }
2012  else {
2013  // If the block size is one, try to recover the most recent least-squares solution
2014  block_gmres_iter->updateLSQR( block_gmres_iter->getCurSubspaceDim() );
2015  // Check to see if the most recent least-squares solution yielded convergence.
2016  sTest_->checkStatus( &*block_gmres_iter );
2017  if (convTest_->getStatus() != Passed)
2018  isConverged = false;
2019  }
2020  } // end catch (const GmresIterationOrthoFailure &e)
2021  catch (const std::exception &e) {
2022  printer_->stream(Errors) << "Error! Caught std::exception in BlockGmresIter::iterate() at iteration "
2023  << block_gmres_iter->getNumIters() << std::endl
2024  << e.what() << std::endl;
2025  throw;
2026  }
2027 
2028  // Record number of iterations in generating initial recycle spacec
2029  prime_iterations = block_gmres_iter->getNumIters();//instantiated here because it is not needed outside of else{} scope; we'll see if this is true or not
2030 
2031  // Update the linear problem.
2032  RCP<MV> update = block_gmres_iter->getCurrentUpdate();
2033  problem_->updateSolution( update, true );
2034 
2035  // Update the block residual
2036 
2037  problem_->computeCurrPrecResVec( &*R_ );
2038 
2039  // Get the state.
2040  newstate = block_gmres_iter->getState();
2041  int p = newstate.curDim;
2042  H_->assign(*(newstate.H));//IS THIS A GOOD IDEA? I DID IT SO MEMBERS WOULD HAVE ACCESS TO H.
2043  // Get new Krylov vectors, store in V_
2044 
2045  // Since the block_gmres_iter returns the state
2046  // with const RCP's we need to cast newstate.V as
2047  // a non const RCP. This is okay because block_gmres_iter
2048  // is about to fall out of scope, so we are simply
2049  // rescuing *newstate.V from being destroyed so we can
2050  // use it for future block recycled GMRES cycles
2051  V_ = rcp_const_cast<MV>(newstate.V);
2052  newstate.V.release();
2053  //COMPUTE NEW RECYCLE SPACE SOMEHOW
2054  buildRecycleSpaceKryl(keff, block_gmres_iter);
2055  printer_->stream(Debug) << "Generated recycled subspace using RHS index " << currIdx[0] << " of dimension " << keff << std::endl << std::endl;
2056 
2057  // Return to outer loop if the priming solve
2058  // converged, set the next linear system.
2059  if (primeConverged) {
2060  /* MLP: POSSIBLY INCORRECT CODE WE ARE REPLACING *********************************
2061  // Inform the linear problem that we are
2062  // finished with this block linear system.
2063  problem_->setCurrLS();
2064 
2065  // Update indices for the linear systems to be solved.
2066  // KMS: Fix the numRHS2Solve; Copy from Heidi's BlockGmres code
2067  numRHS2Solve -= 1;
2068  printer_->stream(Debug) << numRHS2Solve << " Right hand sides left to solve" << std::endl;
2069  if ( numRHS2Solve > 0 ) {
2070  currIdx[0]++;
2071  // Set the next indices
2072  problem_->setLSIndex( currIdx );
2073  }
2074  else {
2075  currIdx.resize( numRHS2Solve );
2076  }
2077  *****************************************************************************/
2078 
2079  // Inform the linear problem that we are finished with this block linear system.
2080  problem_->setCurrLS();
2081 
2082  // Update indices for the linear systems to be solved.
2083  startPtr += numCurrRHS;
2084  numRHS2Solve -= numCurrRHS;
2085  if ( numRHS2Solve > 0 ) {
2086  numCurrRHS = ( numRHS2Solve < blockSize_) ? numRHS2Solve : blockSize_;
2087  if ( adaptiveBlockSize_ ) {
2088  blockSize_ = numCurrRHS;
2089  currIdx.resize( numCurrRHS );
2090  for (int i=0; i<numCurrRHS; ++i) currIdx[i] = startPtr+i;
2091  }
2092  else {
2093  currIdx.resize( blockSize_ );
2094  for (int i=0; i<numCurrRHS; ++i) currIdx[i] = startPtr+i;
2095  for (int i=numCurrRHS; i<blockSize_; ++i) currIdx[i] = -1;
2096  }
2097  // Set the next indices.
2098  problem_->setLSIndex( currIdx );
2099  }
2100  else {
2101  currIdx.resize( numRHS2Solve );
2102  }
2103  continue;//Begin solving the next block of RHS's
2104  } //end if (primeConverged)
2105  } //end else [if(keff > 0)]
2106 
2107  // *****************************************
2108  // Initial subspace update/construction done
2109  // Start cycles of recycled GMRES
2110  // *****************************************
2111  Teuchos::ParameterList blockgcrodrList;
2112  blockgcrodrList.set("Num Blocks",numBlocks_);
2113  blockgcrodrList.set("Block Size",blockSize_);
2114  blockgcrodrList.set("Recycled Blocks",keff);
2115 
2116  Teuchos::RCP<BlockGCRODRIter<ScalarType,MV,OP> > block_gcrodr_iter;
2117  block_gcrodr_iter = Teuchos::rcp( new BlockGCRODRIter<ScalarType,MV,OP>(problem_,printer_,outputTest_,ortho_,blockgcrodrList) );
2119 
2120  index.resize( blockSize_ );
2121  for(int ii = 0; ii < blockSize_; ii++) index[ii] = ii;
2122  Teuchos::RCP<MV> V0 = MVT::CloneViewNonConst( *V_, index );
2123 
2124  // MLP: MVT::SetBlock(*R_,index,*V0);
2125  MVT::Assign(*R_,*V0);
2126 
2127  index.resize(keff);//resize to get appropriate recycle space vectors
2128  for(int i=0; i < keff; i++){ index[i] = i;};
2129  B_ = rcp(new SDM(Teuchos::View, *G_, keff, numBlocks_*blockSize_, 0, keff));
2130  H_ = rcp(new SDM(Teuchos::View, *G_, (numBlocks_-1)*blockSize_ + blockSize_, (numBlocks_-1)*blockSize_, keff ,keff ));
2131 
2132  newstate.V = V_;
2133  newstate.B= B_;
2134  newstate.U = MVT::CloneViewNonConst(*U_, index);
2135  newstate.C = MVT::CloneViewNonConst(*C_, index);
2136  newstate.H = H_;
2137  newstate.curDim = blockSize_;
2138  block_gcrodr_iter -> initialize(newstate);
2139 
2140  int numRestarts = 0;
2141 
2142  while(1){//Each execution of this loop is a cycle of block GCRODR
2143  try{
2144  block_gcrodr_iter -> iterate();
2145 
2146  // ***********************
2147  // Check Convergence First
2148  // ***********************
2149  if( convTest_->getStatus() == Passed ) {
2150  // we have convergence
2151  break;//from while(1)
2152  } //end if converged
2153 
2154  // ***********************************
2155  // Check if maximum iterations reached
2156  // ***********************************
2157  else if(maxIterTest_->getStatus() == Passed ){
2158  // no convergence; hit maxit
2159  isConverged = false;
2160  break; // from while(1)
2161  } //end elseif reached maxit
2162 
2163  // **********************************************
2164  // Check if subspace full; do we need to restart?
2165  // **********************************************
2166  else if (block_gcrodr_iter->getCurSubspaceDim() == block_gcrodr_iter->getMaxSubspaceDim()){
2167 
2168  // Update recycled space even if we have reached max number of restarts
2169 
2170  // Update linear problem
2171  Teuchos::RCP<MV> update = block_gcrodr_iter->getCurrentUpdate();
2172  problem_->updateSolution(update, true);
2173  buildRecycleSpaceAugKryl(block_gcrodr_iter);
2174 
2175  printer_->stream(Debug) << " Generated new recycled subspace using RHS index " << currIdx[0] << " of dimension " << keff << std::endl << std::endl;
2176  // NOTE: If we have hit the maximum number of restarts, then we will quit
2177  if(numRestarts >= maxRestarts_) {
2178  isConverged = false;
2179  break; //from while(1)
2180  } //end if max restarts
2181 
2182  numRestarts++;
2183 
2184  printer_ -> stream(Debug) << " Performing restart number " << numRestarts << " of " << maxRestarts_ << std::endl << std::endl;
2185 
2186  // Create the restart vector (first block in the current Krylov basis)
2187  problem_->computeCurrPrecResVec( &*R_ );
2188  index.resize( blockSize_ );
2189  for (int ii=0; ii<blockSize_; ++ii) index[ii] = ii;
2190  Teuchos::RCP<MV> V0 = MVT::CloneViewNonConst( *V_, index );
2191  MVT::SetBlock(*R_,index,*V0);
2192 
2193  // Set the new state and initialize the solver.
2195  index.resize( numBlocks_*blockSize_ );
2196  for (int ii=0; ii<(numBlocks_*blockSize_); ++ii) index[ii] = ii;
2197  restartState.V = MVT::CloneViewNonConst( *V_, index );
2198  index.resize( keff );
2199  for (int ii=0; ii<keff; ++ii) index[ii] = ii;
2200  restartState.U = MVT::CloneViewNonConst( *U_, index );
2201  restartState.C = MVT::CloneViewNonConst( *C_, index );
2202  B_ = rcp(new SDM(Teuchos::View, *G_, keff, (numBlocks_-1)*blockSize_, 0, keff));
2203  H_ = rcp(new SDM(Teuchos::View, *G_, numBlocks_*blockSize_, (numBlocks_-1)*blockSize_, keff ,keff ));
2204  restartState.B = B_;
2205  restartState.H = H_;
2206  restartState.curDim = blockSize_;
2207  block_gcrodr_iter->initialize(restartState);
2208 
2209  } //end else if need to restart
2210 
2211  // ****************************************************************
2212  // We returned from iterate(), but none of our status tests passed.
2213  // Something is wrong, and it is probably our fault.
2214  // ****************************************************************
2215  else {
2216  TEUCHOS_TEST_FOR_EXCEPTION(true,std::logic_error,"Belos::BlockGCRODRSolMgr::solve(): Invalid return from BlockGCRODRIter::iterate().");
2217  } //end else (no status test passed)
2218 
2219  }//end try
2220  catch(const BlockGCRODRIterOrthoFailure &e){ //there was an exception
2221  // Try to recover the most recent least-squares solution
2222  block_gcrodr_iter->updateLSQR( block_gcrodr_iter->getCurSubspaceDim() );
2223  // Check to see if the most recent least-squares solution yielded convergence.
2224  sTest_->checkStatus( &*block_gcrodr_iter );
2225  if (convTest_->getStatus() != Passed) isConverged = false;
2226  break;
2227  } // end catch orthogonalization failure
2228  catch(const std::exception &e){
2229  printer_->stream(Errors) << "Error! Caught exception in BlockGCRODRIter::iterate() at iteration "
2230  << block_gcrodr_iter->getNumIters() << std::endl
2231  << e.what() << std::endl;
2232  throw;
2233  } //end catch standard exception
2234  } //end while(1)
2235 
2236  // Compute the current solution.
2237  // Update the linear problem.
2238  Teuchos::RCP<MV> update = block_gcrodr_iter->getCurrentUpdate();
2239  problem_->updateSolution( update, true );
2240 
2241  /* MLP: POSSIBLY INCORRECT CODE WE ARE REPLACING *********************************
2242  // Inform the linear problem that we are finished with this block linear system.
2243  problem_->setCurrLS();
2244 
2245  // Update indices for the linear systems to be solved.
2246  numRHS2Solve -= 1;
2247  if ( numRHS2Solve > 0 ) {
2248  currIdx[0]++;
2249  // Set the next indices.
2250  problem_->setLSIndex( currIdx );
2251  }
2252  else {
2253  currIdx.resize( numRHS2Solve );
2254  }
2255  ******************************************************************************/
2256 
2257  // Inform the linear problem that we are finished with this block linear system.
2258  problem_->setCurrLS();
2259 
2260  // Update indices for the linear systems to be solved.
2261  startPtr += numCurrRHS;
2262  numRHS2Solve -= numCurrRHS;
2263  if ( numRHS2Solve > 0 ) {
2264  numCurrRHS = ( numRHS2Solve < blockSize_) ? numRHS2Solve : blockSize_;
2265  if ( adaptiveBlockSize_ ) {
2266  blockSize_ = numCurrRHS;
2267  currIdx.resize( numCurrRHS );
2268  for (int i=0; i<numCurrRHS; ++i) currIdx[i] = startPtr+i;
2269  }
2270  else {
2271  currIdx.resize( blockSize_ );
2272  for (int i=0; i<numCurrRHS; ++i) currIdx[i] = startPtr+i;
2273  for (int i=numCurrRHS; i<blockSize_; ++i) currIdx[i] = -1;
2274  }
2275  // Set the next indices.
2276  problem_->setLSIndex( currIdx );
2277  }
2278  else {
2279  currIdx.resize( numRHS2Solve );
2280  }
2281 
2282  // If we didn't build a recycle space this solve but ran at least k iterations, force build of new recycle space
2283  if (!builtRecycleSpace_) {
2284  buildRecycleSpaceAugKryl(block_gcrodr_iter);
2285  printer_->stream(Debug) << " Generated new recycled subspace using RHS index " << currIdx[0] << " of dimension " << keff << std::endl << std::endl;
2286  }
2287  }//end while (numRHS2Solve > 0)
2288 
2289  // print final summary
2290  sTest_->print( printer_->stream(FinalSummary) );
2291 
2292  // print timing information
2293  #ifdef BELOS_TEUCHOS_TIME_MONITOR
2294  // Calling summarize() can be expensive, so don't call unless the user wants to print out timing details.
2295  // summarize() will do all the work even if it's passed a "black hole" output stream.
2296  if (verbosity_ & TimingDetails) Teuchos::TimeMonitor::summarize( printer_->stream(TimingDetails) );
2297  #endif
2298  // get iteration information for this solve
2299  numIters_ = maxIterTest_->getNumIters();
2300 
2301  if (!isConverged) return Unconverged; // return from BlockGCRODRSolMgr::solve()
2302  return Converged; // return from BlockGCRODRSolMgr::solve()
2303 } //end solve()
2304 
2305 } //End Belos Namespace
2306 
2307 #endif /* BELOS_BLOCK_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.
const LinearProblem< ScalarType, MV, OP > & getProblem() const
Get current linear problem being solved for in this object.
Belos&#39;s basic output manager for sending information of select verbosity levels to the appropriate ou...
Class which manages the output and verbosity of the Belos solvers.
Structure to contain pointers to BlockGCRODRIter state variables.
virtual ~BlockGCRODRSolMgr()
Destructor.
int getNumIters() const
Get the iteration count for the most recent call to solve().
ScaleType
The type of scaling to use on the residual norm value.
Definition: BelosTypes.hpp:119
Teuchos::RCP< Teuchos::SerialDenseMatrix< int, ScalarType > > B
The projection of the Krylov subspace against the recycled subspace *.
Exception thrown to signal error in a status test during Belos::StatusTest::checkStatus().
Teuchos::RCP< const Teuchos::ParameterList > getCurrentParameters() const
Get a parameter list containing the current parameters for this object.
This class implements the block GMRES iteration, where a block Krylov subspace is constructed...
Teuchos::RCP< const MV > V
The current Krylov basis.
BlockGCRODRIterOrthoFailure is thrown when the BlockGCRODRIter object is unable to compute independen...
Thrown when the linear problem was not set up correctly.
A factory class for generating StatusTestOutput objects.
void setParameters(const Teuchos::RCP< Teuchos::ParameterList > &params)
Set the parameters the solver should use to solve the linear problem.
Teuchos::RCP< const Teuchos::SerialDenseMatrix< int, ScalarType > > z
The current right-hand side of the least squares system RY = Z.
An implementation of StatusTestResNorm using a family of residual norms.
Structure to contain pointers to GmresIteration state variables.
An extension of the MultiVecTraits class that adds a new vector length method.
Belos::StatusTest class for specifying a maximum number of iterations.
BlockGCRODRSolMgrRecyclingFailure(const std::string &what_arg)
void reset(const ResetType type)
Performs a reset of the solver manager specified by the ResetType.
Thrown if any problem occurs in using or creating the recycle subspace.
A factory class for generating StatusTestOutput objects.
Teuchos::RCP< MV > V
The current Krylov basis.
BlockGCRODRSolMgrOrthoFailure(const std::string &what_arg)
int curDim
The current dimension of the reduction.
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.
ResetType
How to reset the solver.
Definition: BelosTypes.hpp:200
BlockGCRODRSolMgrLAPACKFailure(const std::string &what_arg)
A solver manager for the Block GCRO-DR (Block Recycling GMRES) linear solver.
Pure virtual base class which describes the basic interface for a solver manager. ...
int curDim
The current dimension of the reduction.
Belos concrete class for performing the block GCRO-DR (block GMRES with recycling) iteration...
BlockGCRODRSolMgr()
Default constructor.
A linear system to solve, and its associated information.
std::string description() const
A description of the Block GCRODR solver manager.
Class which describes the linear problem to be solved by the iterative solver.
void setProblem(const Teuchos::RCP< LinearProblem< ScalarType, MV, OP > > &problem)
Set the linear problem to solve on the next call to solve().
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 ...
Thrown when the solution manager was unable to orthogonalize the basis vectors.
Teuchos::RCP< MV > U
The recycled subspace and its projection.
Belos concrete class for performing the block GMRES iteration.
Implementation of the Block GCRO-DR (Block Recycling GMRES) iteration.
int setTolerance(MagnitudeType tolerance)
Set the value of the tolerance.
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.
Teuchos::RCP< const Teuchos::ParameterList > getValidParameters() const
Get a parameter list containing the valid parameters for this object.
Belos::StatusTestResNorm for specifying general residual norm stopping criteria.
Teuchos::RCP< Teuchos::SerialDenseMatrix< int, ScalarType > > H
The current Hessenberg matrix.
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.
Parent class to all Belos exceptions.
Definition: BelosTypes.hpp:60
Pure virtual base class which augments the basic interface for a Gmres linear solver iteration...
GmresIterationOrthoFailure is thrown when the GmresIteration object is unable to compute independent ...
Belos header file which uses auto-configuration information to include necessary C++ headers...
BlockGCRODRSolMgrLinearProblemFailure(const std::string &what_arg)
ReturnType solve()
Solve the current linear problem.
Thrown when an LAPACK call fails.
Belos concrete class for performing the block, flexible GMRES iteration.
bool isLOADetected() const
Whether a loss of accuracy was detected during the most recent solve.
OutputType
Style of output used to display status test information.
Definition: BelosTypes.hpp:136
Teuchos::RCP< const Teuchos::SerialDenseMatrix< int, ScalarType > > H
The current Hessenberg matrix.