Anasazi  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
AnasaziBlockKrylovSchur.hpp
Go to the documentation of this file.
1 // @HEADER
2 // ***********************************************************************
3 //
4 // Anasazi: Block Eigensolvers Package
5 // Copyright (2004) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
9 //
10 // This library is free software; you can redistribute it and/or modify
11 // it under the terms of the GNU Lesser General Public License as
12 // published by the Free Software Foundation; either version 2.1 of the
13 // License, or (at your option) any later version.
14 //
15 // This library is distributed in the hope that it will be useful, but
16 // WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
19 //
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
23 // USA
24 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
25 //
26 // ***********************************************************************
27 // @HEADER
28 
33 #ifndef ANASAZI_BLOCK_KRYLOV_SCHUR_HPP
34 #define ANASAZI_BLOCK_KRYLOV_SCHUR_HPP
35 
36 #include "AnasaziTypes.hpp"
37 
38 #include "AnasaziEigensolver.hpp"
41 #include "Teuchos_ScalarTraits.hpp"
42 #include "AnasaziHelperTraits.hpp"
43 
44 #include "AnasaziOrthoManager.hpp"
45 
46 #include "Teuchos_LAPACK.hpp"
47 #include "Teuchos_BLAS.hpp"
50 #include "Teuchos_TimeMonitor.hpp"
51 
66 namespace Anasazi {
67 
69 
70 
75  template <class ScalarType, class MulVec>
81  int curDim;
94  BlockKrylovSchurState() : curDim(0), V(Teuchos::null),
95  H(Teuchos::null), S(Teuchos::null),
96  Q(Teuchos::null) {}
97  };
98 
100 
102 
103 
117  BlockKrylovSchurInitFailure(const std::string& what_arg) : AnasaziError(what_arg)
118  {}};
119 
127  BlockKrylovSchurOrthoFailure(const std::string& what_arg) : AnasaziError(what_arg)
128  {}};
129 
131 
132 
133  template <class ScalarType, class MV, class OP>
134  class BlockKrylovSchur : public Eigensolver<ScalarType,MV,OP> {
135  public:
137 
138 
152  const Teuchos::RCP<OutputManager<ScalarType> > &printer,
155  Teuchos::ParameterList &params
156  );
157 
159  virtual ~BlockKrylovSchur() {};
161 
162 
164 
165 
187  void iterate();
188 
211 
215  void initialize();
216 
225  bool isInitialized() const { return initialized_; }
226 
236  state.curDim = curDim_;
237  state.V = V_;
238  state.H = H_;
239  state.Q = Q_;
240  state.S = schurH_;
241  return state;
242  }
243 
245 
246 
248 
249 
251  int getNumIters() const { return(iter_); }
252 
254  void resetNumIters() { iter_=0; }
255 
263  Teuchos::RCP<const MV> getRitzVectors() { return ritzVectors_; }
264 
272  std::vector<Value<ScalarType> > getRitzValues() {
273  std::vector<Value<ScalarType> > ret = ritzValues_;
274  ret.resize(ritzIndex_.size());
275  return ret;
276  }
277 
283  std::vector<int> getRitzIndex() { return ritzIndex_; }
284 
289  std::vector<typename Teuchos::ScalarTraits<ScalarType>::magnitudeType> getResNorms() {
290  std::vector<typename Teuchos::ScalarTraits<ScalarType>::magnitudeType> ret(0);
291  return ret;
292  }
293 
298  std::vector<typename Teuchos::ScalarTraits<ScalarType>::magnitudeType> getRes2Norms() {
299  std::vector<typename Teuchos::ScalarTraits<ScalarType>::magnitudeType> ret(0);
300  return ret;
301  }
302 
307  std::vector<typename Teuchos::ScalarTraits<ScalarType>::magnitudeType> getRitzRes2Norms() {
308  std::vector<typename Teuchos::ScalarTraits<ScalarType>::magnitudeType> ret = ritzResiduals_;
309  ret.resize(ritzIndex_.size());
310  return ret;
311  }
312 
314 
316 
317 
320 
323 
325  const Eigenproblem<ScalarType,MV,OP>& getProblem() const { return(*problem_); };
326 
333  void setSize(int blockSize, int numBlocks);
334 
336  void setBlockSize(int blockSize);
337 
339  void setStepSize(int stepSize);
340 
342  void setNumRitzVectors(int numRitzVecs);
343 
345  int getStepSize() const { return(stepSize_); }
346 
348  int getBlockSize() const { return(blockSize_); }
349 
351  int getNumRitzVectors() const { return(numRitzVecs_); }
352 
358  int getCurSubspaceDim() const {
359  if (!initialized_) return 0;
360  return curDim_;
361  }
362 
364  int getMaxSubspaceDim() const { return (problem_->isHermitian()?blockSize_*numBlocks_:blockSize_*numBlocks_+1); }
365 
366 
379  void setAuxVecs(const Teuchos::Array<Teuchos::RCP<const MV> > &auxvecs);
380 
383 
385 
387 
388 
390  void currentStatus(std::ostream &os);
391 
393 
395 
396 
398  bool isRitzVecsCurrent() const { return ritzVecsCurrent_; }
399 
401  bool isRitzValsCurrent() const { return ritzValsCurrent_; }
402 
404  bool isSchurCurrent() const { return schurCurrent_; }
405 
407 
409 
410 
412  void computeRitzVectors();
413 
415  void computeRitzValues();
416 
418  void computeSchurForm( const bool sort = true );
419 
421 
422  private:
423  //
424  // Convenience typedefs
425  //
426  typedef MultiVecTraits<ScalarType,MV> MVT;
427  typedef MultiVecTraitsExt<ScalarType,MV> MVText;
430  typedef typename SCT::magnitudeType MagnitudeType;
431  typedef typename std::vector<ScalarType>::iterator STiter;
432  typedef typename std::vector<MagnitudeType>::iterator MTiter;
433  const MagnitudeType MT_ONE;
434  const MagnitudeType MT_ZERO;
435  const MagnitudeType NANVAL;
436  const ScalarType ST_ONE;
437  const ScalarType ST_ZERO;
438  //
439  // Internal structs
440  //
441  struct CheckList {
442  bool checkV;
443  bool checkArn;
444  bool checkAux;
445  CheckList() : checkV(false), checkArn(false), checkAux(false) {};
446  };
447  //
448  // Internal methods
449  //
450  std::string accuracyCheck(const CheckList &chk, const std::string &where) const;
451  void sortSchurForm( Teuchos::SerialDenseMatrix<int,ScalarType>& H,
453  std::vector<int>& order );
454  //
455  // Classes inputed through constructor that define the eigenproblem to be solved.
456  //
462  //
463  // Information obtained from the eigenproblem
464  //
466  //
467  // Internal timers
468  //
469  Teuchos::RCP<Teuchos::Time> timerOp_, timerSortRitzVal_,
470  timerCompSF_, timerSortSF_,
471  timerCompRitzVec_, timerOrtho_;
472  //
473  // Counters
474  //
475  int count_ApplyOp_;
476 
477  //
478  // Algorithmic parameters.
479  //
480  // blockSize_ is the solver block size; it controls the number of eigenvectors that
481  // we compute, the number of residual vectors that we compute, and therefore the number
482  // of vectors added to the basis on each iteration.
483  int blockSize_;
484  // numBlocks_ is the size of the allocated space for the Krylov basis, in blocks.
485  int numBlocks_;
486  // stepSize_ dictates how many iterations are performed before eigenvectors and eigenvalues
487  // are computed again
488  int stepSize_;
489 
490  //
491  // Current solver state
492  //
493  // initialized_ specifies that the basis vectors have been initialized and the iterate() routine
494  // is capable of running; _initialize is controlled by the initialize() member method
495  // For the implications of the state of initialized_, please see documentation for initialize()
496  bool initialized_;
497  //
498  // curDim_ reflects how much of the current basis is valid
499  // NOTE: for Hermitian, 0 <= curDim_ <= blockSize_*numBlocks_
500  // for non-Hermitian, 0 <= curDim_ <= blockSize_*numBlocks_ + 1
501  // this also tells us how many of the values in _theta are valid Ritz values
502  int curDim_;
503  //
504  // State Multivecs
505  Teuchos::RCP<MV> ritzVectors_, V_;
506  int numRitzVecs_;
507  //
508  // Projected matrices
509  // H_ : Projected matrix from the Krylov-Schur factorization AV = VH + FB^T
510  //
512  //
513  // Schur form of Projected matrices (these are only updated when the Ritz values/vectors are updated).
514  // schurH_: Schur form reduction of H
515  // Q_: Schur vectors of H
518  //
519  // Auxiliary vectors
521  int numAuxVecs_;
522  //
523  // Number of iterations that have been performed.
524  int iter_;
525  //
526  // State flags
527  bool ritzVecsCurrent_, ritzValsCurrent_, schurCurrent_;
528  //
529  // Current eigenvalues, residual norms
530  std::vector<Value<ScalarType> > ritzValues_;
531  std::vector<MagnitudeType> ritzResiduals_;
532  //
533  // Current index vector for Ritz values and vectors
534  std::vector<int> ritzIndex_; // computed by BKS
535  std::vector<int> ritzOrder_; // returned from sort manager
536  //
537  // Number of Ritz pairs to be printed upon output, if possible
538  int numRitzPrint_;
539  };
540 
541 
543  // Constructor
544  template <class ScalarType, class MV, class OP>
548  const Teuchos::RCP<OutputManager<ScalarType> > &printer,
551  Teuchos::ParameterList &params
552  ) :
553  MT_ONE(Teuchos::ScalarTraits<MagnitudeType>::one()),
554  MT_ZERO(Teuchos::ScalarTraits<MagnitudeType>::zero()),
555  NANVAL(Teuchos::ScalarTraits<MagnitudeType>::nan()),
556  ST_ONE(Teuchos::ScalarTraits<ScalarType>::one()),
557  ST_ZERO(Teuchos::ScalarTraits<ScalarType>::zero()),
558  // problem, tools
559  problem_(problem),
560  sm_(sorter),
561  om_(printer),
562  tester_(tester),
563  orthman_(ortho),
564  // timers, counters
565 #ifdef ANASAZI_TEUCHOS_TIME_MONITOR
566  timerOp_(Teuchos::TimeMonitor::getNewTimer("Anasazi: BlockKrylovSchur::Operation Op*x")),
567  timerSortRitzVal_(Teuchos::TimeMonitor::getNewTimer("Anasazi: BlockKrylovSchur::Sorting Ritz values")),
568  timerCompSF_(Teuchos::TimeMonitor::getNewTimer("Anasazi: BlockKrylovSchur::Computing Schur form")),
569  timerSortSF_(Teuchos::TimeMonitor::getNewTimer("Anasazi: BlockKrylovSchur::Sorting Schur form")),
570  timerCompRitzVec_(Teuchos::TimeMonitor::getNewTimer("Anasazi: BlockKrylovSchur::Computing Ritz vectors")),
571  timerOrtho_(Teuchos::TimeMonitor::getNewTimer("Anasazi: BlockKrylovSchur::Orthogonalization")),
572 #endif
573  count_ApplyOp_(0),
574  // internal data
575  blockSize_(0),
576  numBlocks_(0),
577  stepSize_(0),
578  initialized_(false),
579  curDim_(0),
580  numRitzVecs_(0),
581  auxVecs_( Teuchos::Array<Teuchos::RCP<const MV> >(0) ),
582  numAuxVecs_(0),
583  iter_(0),
584  ritzVecsCurrent_(false),
585  ritzValsCurrent_(false),
586  schurCurrent_(false),
587  numRitzPrint_(0)
588  {
589  TEUCHOS_TEST_FOR_EXCEPTION(problem_ == Teuchos::null,std::invalid_argument,
590  "Anasazi::BlockKrylovSchur::constructor: user specified null problem pointer.");
591  TEUCHOS_TEST_FOR_EXCEPTION(sm_ == Teuchos::null,std::invalid_argument,
592  "Anasazi::BlockKrylovSchur::constructor: user passed null sort manager pointer.");
593  TEUCHOS_TEST_FOR_EXCEPTION(om_ == Teuchos::null,std::invalid_argument,
594  "Anasazi::BlockKrylovSchur::constructor: user passed null output manager pointer.");
595  TEUCHOS_TEST_FOR_EXCEPTION(tester_ == Teuchos::null,std::invalid_argument,
596  "Anasazi::BlockKrylovSchur::constructor: user passed null status test pointer.");
597  TEUCHOS_TEST_FOR_EXCEPTION(orthman_ == Teuchos::null,std::invalid_argument,
598  "Anasazi::BlockKrylovSchur::constructor: user passed null orthogonalization manager pointer.");
599  TEUCHOS_TEST_FOR_EXCEPTION(problem_->isProblemSet() == false, std::invalid_argument,
600  "Anasazi::BlockKrylovSchur::constructor: user specified problem is not set.");
601  TEUCHOS_TEST_FOR_EXCEPTION(sorter == Teuchos::null,std::invalid_argument,
602  "Anasazi::BlockKrylovSchur::constructor: user specified null sort manager pointer.");
603  TEUCHOS_TEST_FOR_EXCEPTION(printer == Teuchos::null,std::invalid_argument,
604  "Anasazi::BlockKrylovSchur::constructor: user specified null output manager pointer.");
605  TEUCHOS_TEST_FOR_EXCEPTION(tester == Teuchos::null,std::invalid_argument,
606  "Anasazi::BlockKrylovSchur::constructor: user specified null status test pointer.");
607  TEUCHOS_TEST_FOR_EXCEPTION(ortho == Teuchos::null,std::invalid_argument,
608  "Anasazi::BlockKrylovSchur::constructor: user specified null ortho manager pointer.");
609 
610  // Get problem operator
611  Op_ = problem_->getOperator();
612 
613  // get the step size
614  TEUCHOS_TEST_FOR_EXCEPTION(!params.isParameter("Step Size"), std::invalid_argument,
615  "Anasazi::BlockKrylovSchur::constructor: mandatory parameter 'Step Size' is not specified.");
616  int ss = params.get("Step Size",numBlocks_);
617  setStepSize(ss);
618 
619  // set the block size and allocate data
620  int bs = params.get("Block Size", 1);
621  int nb = params.get("Num Blocks", 3*problem_->getNEV());
622  setSize(bs,nb);
623 
624  // get the number of Ritz vectors to compute and allocate data.
625  // --> if this parameter is not specified in the parameter list, then it's assumed that no Ritz vectors will be computed.
626  int numRitzVecs = params.get("Number of Ritz Vectors", 0);
627  setNumRitzVectors( numRitzVecs );
628 
629  // get the number of Ritz values to print out when currentStatus is called.
630  numRitzPrint_ = params.get("Print Number of Ritz Values", bs);
631  }
632 
633 
635  // Set the block size
636  // This simply calls setSize(), modifying the block size while retaining the number of blocks.
637  template <class ScalarType, class MV, class OP>
639  {
640  setSize(blockSize,numBlocks_);
641  }
642 
643 
645  // Set the step size.
646  template <class ScalarType, class MV, class OP>
648  {
649  TEUCHOS_TEST_FOR_EXCEPTION(stepSize <= 0, std::invalid_argument, "Anasazi::BlockKrylovSchur::setStepSize(): new step size must be positive and non-zero.");
650  stepSize_ = stepSize;
651  }
652 
654  // Set the number of Ritz vectors to compute.
655  template <class ScalarType, class MV, class OP>
657  {
658  // This routine only allocates space; it doesn't not perform any computation
659  // any change in size will invalidate the state of the solver.
660 
661  TEUCHOS_TEST_FOR_EXCEPTION(numRitzVecs < 0, std::invalid_argument, "Anasazi::BlockKrylovSchur::setNumRitzVectors(): number of Ritz vectors to compute must be positive.");
662 
663  // Check to see if the number of requested Ritz vectors has changed.
664  if (numRitzVecs != numRitzVecs_) {
665  if (numRitzVecs) {
666  ritzVectors_ = Teuchos::null;
667  ritzVectors_ = MVT::Clone(*V_, numRitzVecs);
668  } else {
669  ritzVectors_ = Teuchos::null;
670  }
671  numRitzVecs_ = numRitzVecs;
672  ritzVecsCurrent_ = false;
673  }
674  }
675 
677  // Set the block size and make necessary adjustments.
678  template <class ScalarType, class MV, class OP>
679  void BlockKrylovSchur<ScalarType,MV,OP>::setSize (int blockSize, int numBlocks)
680  {
681  // This routine only allocates space; it doesn't not perform any computation
682  // any change in size will invalidate the state of the solver.
683 
684  TEUCHOS_TEST_FOR_EXCEPTION(numBlocks <= 0 || blockSize <= 0, std::invalid_argument, "Anasazi::BlockKrylovSchur::setSize was passed a non-positive argument.");
685  TEUCHOS_TEST_FOR_EXCEPTION(numBlocks < 3, std::invalid_argument, "Anasazi::BlockKrylovSchur::setSize(): numBlocks must be at least three.");
686  if (blockSize == blockSize_ && numBlocks == numBlocks_) {
687  // do nothing
688  return;
689  }
690 
691  blockSize_ = blockSize;
692  numBlocks_ = numBlocks;
693 
695  // grab some Multivector to Clone
696  // in practice, getInitVec() should always provide this, but it is possible to use a
697  // Eigenproblem with nothing in getInitVec() by manually initializing with initialize();
698  // in case of that strange scenario, we will try to Clone from V_; first resort to getInitVec(),
699  // because we would like to clear the storage associated with V_ so we have room for the new V_
700  if (problem_->getInitVec() != Teuchos::null) {
701  tmp = problem_->getInitVec();
702  }
703  else {
704  tmp = V_;
705  TEUCHOS_TEST_FOR_EXCEPTION(tmp == Teuchos::null,std::invalid_argument,
706  "Anasazi::BlockKrylovSchur::setSize(): eigenproblem did not specify initial vectors to clone from.");
707  }
708 
709 
711  // blockSize*numBlocks dependent
712  //
713  int newsd;
714  if (problem_->isHermitian()) {
715  newsd = blockSize_*numBlocks_;
716  } else {
717  newsd = blockSize_*numBlocks_+1;
718  }
719  // check that new size is valid
720  TEUCHOS_TEST_FOR_EXCEPTION(static_cast<ptrdiff_t>(newsd) > MVText::GetGlobalLength(*tmp),std::invalid_argument,
721  "Anasazi::BlockKrylovSchur::setSize(): maximum basis size is larger than problem dimension.");
722 
723  ritzValues_.resize(newsd);
724  ritzResiduals_.resize(newsd,MT_ONE);
725  ritzOrder_.resize(newsd);
726  V_ = Teuchos::null;
727  V_ = MVT::Clone(*tmp,newsd+blockSize_);
728  H_ = Teuchos::rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>(newsd+blockSize_,newsd) );
730 
731  initialized_ = false;
732  curDim_ = 0;
733  }
734 
735 
737  // Set the auxiliary vectors
738  template <class ScalarType, class MV, class OP>
740  typedef typename Teuchos::Array<Teuchos::RCP<const MV> >::iterator tarcpmv;
741 
742  // set new auxiliary vectors
743  auxVecs_ = auxvecs;
744 
745  if (om_->isVerbosity( Debug ) ) {
746  // Check almost everything here
747  CheckList chk;
748  chk.checkAux = true;
749  om_->print( Debug, accuracyCheck(chk, ": in setAuxVecs()") );
750  }
751 
752  numAuxVecs_ = 0;
753  for (tarcpmv i=auxVecs_.begin(); i != auxVecs_.end(); i++) {
754  numAuxVecs_ += MVT::GetNumberVecs(**i);
755  }
756 
757  // If the solver has been initialized, X and P are not necessarily orthogonal to new auxiliary vectors
758  if (numAuxVecs_ > 0 && initialized_) {
759  initialized_ = false;
760  }
761  }
762 
764  /* Initialize the state of the solver
765  *
766  * POST-CONDITIONS:
767  *
768  * V_ is orthonormal, orthogonal to auxVecs_, for first curDim_ vectors
769  *
770  */
771 
772  template <class ScalarType, class MV, class OP>
774  {
775  // NOTE: memory has been allocated by setBlockSize(). Use SetBlock below; do not Clone
776 
777  std::vector<int> bsind(blockSize_);
778  for (int i=0; i<blockSize_; i++) bsind[i] = i;
779 
780  // in BlockKrylovSchur, V and H are required.
781  // if either doesn't exist, then we will start with the initial vector.
782  //
783  // inconsistent multivectors widths and lengths will not be tolerated, and
784  // will be treated with exceptions.
785  //
786  std::string errstr("Anasazi::BlockKrylovSchur::initialize(): specified multivectors must have a consistent length and width.");
787 
788  // set up V,H: if the user doesn't specify both of these these,
789  // we will start over with the initial vector.
790  if (newstate.V != Teuchos::null && newstate.H != Teuchos::null) {
791 
792  // initialize V_,H_, and curDim_
793 
794  TEUCHOS_TEST_FOR_EXCEPTION( MVText::GetGlobalLength(*newstate.V) != MVText::GetGlobalLength(*V_),
795  std::invalid_argument, errstr );
796  if (newstate.V != V_) {
797  TEUCHOS_TEST_FOR_EXCEPTION( MVT::GetNumberVecs(*newstate.V) < blockSize_,
798  std::invalid_argument, errstr );
799  TEUCHOS_TEST_FOR_EXCEPTION( MVT::GetNumberVecs(*newstate.V) > getMaxSubspaceDim(),
800  std::invalid_argument, errstr );
801  }
802  TEUCHOS_TEST_FOR_EXCEPTION( newstate.curDim > getMaxSubspaceDim(),
803  std::invalid_argument, errstr );
804 
805  curDim_ = newstate.curDim;
806  int lclDim = MVT::GetNumberVecs(*newstate.V);
807 
808  // check size of H
809  TEUCHOS_TEST_FOR_EXCEPTION(newstate.H->numRows() < curDim_ || newstate.H->numCols() < curDim_, std::invalid_argument, errstr);
810 
811  if (curDim_ == 0 && lclDim > blockSize_) {
812  om_->stream(Warnings) << "Anasazi::BlockKrylovSchur::initialize(): the solver was initialized with a kernel of " << lclDim << std::endl
813  << "The block size however is only " << blockSize_ << std::endl
814  << "The last " << lclDim - blockSize_ << " vectors of the kernel will be overwritten on the first call to iterate()." << std::endl;
815  }
816 
817 
818  // copy basis vectors from newstate into V
819  if (newstate.V != V_) {
820  std::vector<int> nevind(lclDim);
821  for (int i=0; i<lclDim; i++) nevind[i] = i;
822  MVT::SetBlock(*newstate.V,nevind,*V_);
823  }
824 
825  // put data into H_, make sure old information is not still hanging around.
826  if (newstate.H != H_) {
827  H_->putScalar( ST_ZERO );
828  Teuchos::SerialDenseMatrix<int,ScalarType> newH(Teuchos::View,*newstate.H,curDim_+blockSize_,curDim_);
830  lclH = Teuchos::rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>(Teuchos::View,*H_,curDim_+blockSize_,curDim_) );
831  lclH->assign(newH);
832 
833  // done with local pointers
834  lclH = Teuchos::null;
835  }
836 
837  }
838  else {
839  // user did not specify a basis V
840  // get vectors from problem or generate something, projectAndNormalize, call initialize() recursively
841  Teuchos::RCP<const MV> ivec = problem_->getInitVec();
842  TEUCHOS_TEST_FOR_EXCEPTION(ivec == Teuchos::null,std::invalid_argument,
843  "Anasazi::BlockKrylovSchur::initialize(): eigenproblem did not specify initial vectors to clone from.");
844 
845  int lclDim = MVT::GetNumberVecs(*ivec);
846  bool userand = false;
847  if (lclDim < blockSize_) {
848  // we need at least blockSize_ vectors
849  // use a random multivec
850  userand = true;
851  }
852 
853  if (userand) {
854  // make an index
855  std::vector<int> dimind2(lclDim);
856  for (int i=0; i<lclDim; i++) { dimind2[i] = i; }
857 
858  // alloc newV as a view of the first block of V
859  Teuchos::RCP<MV> newV1 = MVT::CloneViewNonConst(*V_,dimind2);
860 
861  // copy the initial vectors into the first lclDim vectors of V
862  MVT::SetBlock(*ivec,dimind2,*newV1);
863 
864  // resize / reinitialize the index vector
865  dimind2.resize(blockSize_-lclDim);
866  for (int i=0; i<blockSize_-lclDim; i++) { dimind2[i] = lclDim + i; }
867 
868  // initialize the rest of the vectors with random vectors
869  Teuchos::RCP<MV> newV2 = MVT::CloneViewNonConst(*V_,dimind2);
870  MVT::MvRandom(*newV2);
871  }
872  else {
873  // alloc newV as a view of the first block of V
874  Teuchos::RCP<MV> newV1 = MVT::CloneViewNonConst(*V_,bsind);
875 
876  // get a view of the first block of initial vectors
877  Teuchos::RCP<const MV> ivecV = MVT::CloneView(*ivec,bsind);
878 
879  // assign ivec to first part of newV
880  MVT::SetBlock(*ivecV,bsind,*newV1);
881  }
882 
883  // get pointer into first block of V
884  Teuchos::RCP<MV> newV = MVT::CloneViewNonConst(*V_,bsind);
885 
886  // remove auxVecs from newV and normalize newV
887  if (auxVecs_.size() > 0) {
888 #ifdef ANASAZI_TEUCHOS_TIME_MONITOR
889  Teuchos::TimeMonitor lcltimer( *timerOrtho_ );
890 #endif
891 
893  int rank = orthman_->projectAndNormalize(*newV,auxVecs_);
895  "Anasazi::BlockKrylovSchur::initialize(): couldn't generate initial basis of full rank." );
896  }
897  else {
898 #ifdef ANASAZI_TEUCHOS_TIME_MONITOR
899  Teuchos::TimeMonitor lcltimer( *timerOrtho_ );
900 #endif
901 
902  int rank = orthman_->normalize(*newV);
904  "Anasazi::BlockKrylovSchur::initialize(): couldn't generate initial basis of full rank." );
905  }
906 
907  // set curDim
908  curDim_ = 0;
909 
910  // clear pointer
911  newV = Teuchos::null;
912  }
913 
914  // The Ritz vectors/values and Schur form are no longer current.
915  ritzVecsCurrent_ = false;
916  ritzValsCurrent_ = false;
917  schurCurrent_ = false;
918 
919  // the solver is initialized
920  initialized_ = true;
921 
922  if (om_->isVerbosity( Debug ) ) {
923  // Check almost everything here
924  CheckList chk;
925  chk.checkV = true;
926  chk.checkArn = true;
927  chk.checkAux = true;
928  om_->print( Debug, accuracyCheck(chk, ": after initialize()") );
929  }
930 
931  // Print information on current status
932  if (om_->isVerbosity(Debug)) {
933  currentStatus( om_->stream(Debug) );
934  }
935  else if (om_->isVerbosity(IterationDetails)) {
936  currentStatus( om_->stream(IterationDetails) );
937  }
938  }
939 
940 
942  // initialize the solver with default state
943  template <class ScalarType, class MV, class OP>
945  {
947  initialize(empty);
948  }
949 
950 
952  // Perform BlockKrylovSchur iterations until the StatusTest tells us to stop.
953  template <class ScalarType, class MV, class OP>
955  {
956  //
957  // Allocate/initialize data structures
958  //
959  if (initialized_ == false) {
960  initialize();
961  }
962 
963  // Compute the current search dimension.
964  // If the problem is non-Hermitian and the blocksize is one, let the solver use the extra vector.
965  int searchDim = blockSize_*numBlocks_;
966  if (problem_->isHermitian() == false) {
967  searchDim++;
968  }
969 
971  // iterate until the status test tells us to stop.
972  //
973  // also break if our basis is full
974  //
975  while (tester_->checkStatus(this) != Passed && curDim_+blockSize_ <= searchDim) {
976 
977  iter_++;
978 
979  // F can be found at the curDim_ block, but the next block is at curDim_ + blockSize_.
980  int lclDim = curDim_ + blockSize_;
981 
982  // Get the current part of the basis.
983  std::vector<int> curind(blockSize_);
984  for (int i=0; i<blockSize_; i++) { curind[i] = lclDim + i; }
985  Teuchos::RCP<MV> Vnext = MVT::CloneViewNonConst(*V_,curind);
986 
987  // Get a view of the previous vectors
988  // this is used for orthogonalization and for computing V^H K H
989  for (int i=0; i<blockSize_; i++) { curind[i] = curDim_ + i; }
990  Teuchos::RCP<const MV> Vprev = MVT::CloneView(*V_,curind);
991  // om_->stream(Debug) << "Vprev: " << std::endl;
992  // MVT::MvPrint(*Vprev,om_->stream(Debug));
993 
994  // Compute the next vector in the Krylov basis: Vnext = Op*Vprev
995  {
996 #ifdef ANASAZI_TEUCHOS_TIME_MONITOR
997  Teuchos::TimeMonitor lcltimer( *timerOp_ );
998 #endif
999  OPT::Apply(*Op_,*Vprev,*Vnext);
1000  count_ApplyOp_ += blockSize_;
1001  }
1002  // om_->stream(Debug) << "Vnext: " << std::endl;
1003  // MVT::MvPrint(*Vnext,om_->stream(Debug));
1004  Vprev = Teuchos::null;
1005 
1006  // Remove all previous Krylov-Schur basis vectors and auxVecs from Vnext
1007  {
1008 #ifdef ANASAZI_TEUCHOS_TIME_MONITOR
1009  Teuchos::TimeMonitor lcltimer( *timerOrtho_ );
1010 #endif
1011 
1012  // Get a view of all the previous vectors
1013  std::vector<int> prevind(lclDim);
1014  for (int i=0; i<lclDim; i++) { prevind[i] = i; }
1015  Vprev = MVT::CloneView(*V_,prevind);
1016  Teuchos::Array<Teuchos::RCP<const MV> > AVprev(1, Vprev);
1017 
1018  // Get a view of the part of the Hessenberg matrix needed to hold the ortho coeffs.
1021  ( Teuchos::View,*H_,lclDim,blockSize_,0,curDim_ ) );
1023  AsubH.append( subH );
1024 
1025  // Add the auxiliary vectors to the current basis vectors if any exist
1026  if (auxVecs_.size() > 0) {
1027  for (Array_size_type i=0; i<auxVecs_.size(); i++) {
1028  AVprev.append( auxVecs_[i] );
1029  AsubH.append( Teuchos::null );
1030  }
1031  }
1032 
1033  // Get a view of the part of the Hessenberg matrix needed to hold the norm coeffs.
1034  // om_->stream(Debug) << "V before ortho: " << std::endl;
1035  // MVT::MvPrint(*Vprev,om_->stream(Debug));
1038  ( Teuchos::View,*H_,blockSize_,blockSize_,lclDim,curDim_ ) );
1039  int rank = orthman_->projectAndNormalize(*Vnext,AVprev,AsubH,subR);
1040  // om_->stream(Debug) << "Vnext after ortho: " << std::endl;
1041  // MVT::MvPrint(*Vnext,om_->stream(Debug));
1042  // om_->stream(Debug) << "subH: " << std::endl << *subH << std::endl;
1043  // om_->stream(Debug) << "subR: " << std::endl << *subR << std::endl;
1044  // om_->stream(Debug) << "H: " << std::endl << *H_ << std::endl;
1046  "Anasazi::BlockKrylovSchur::iterate(): couldn't generate basis of full rank.");
1047  }
1048  //
1049  // V has been extended, and H has been extended.
1050  //
1051  // Update basis dim and release all pointers.
1052  Vnext = Teuchos::null;
1053  curDim_ += blockSize_;
1054  // The Ritz vectors/values and Schur form are no longer current.
1055  ritzVecsCurrent_ = false;
1056  ritzValsCurrent_ = false;
1057  schurCurrent_ = false;
1058  //
1059  // Update Ritz values and residuals if needed
1060  if (!(iter_%stepSize_)) {
1061  computeRitzValues();
1062  }
1063 
1064  // When required, monitor some orthogonalities
1065  if (om_->isVerbosity( Debug ) ) {
1066  // Check almost everything here
1067  CheckList chk;
1068  chk.checkV = true;
1069  chk.checkArn = true;
1070  om_->print( Debug, accuracyCheck(chk, ": after local update") );
1071  }
1072  else if (om_->isVerbosity( OrthoDetails ) ) {
1073  CheckList chk;
1074  chk.checkV = true;
1075  om_->print( OrthoDetails, accuracyCheck(chk, ": after local update") );
1076  }
1077 
1078  // Print information on current iteration
1079  if (om_->isVerbosity(Debug)) {
1080  currentStatus( om_->stream(Debug) );
1081  }
1082  else if (om_->isVerbosity(IterationDetails)) {
1083  currentStatus( om_->stream(IterationDetails) );
1084  }
1085 
1086  } // end while (statusTest == false)
1087 
1088  } // end of iterate()
1089 
1090 
1092  // Check accuracy, orthogonality, and other debugging stuff
1093  //
1094  // bools specify which tests we want to run (instead of running more than we actually care about)
1095  //
1096  // checkV : V orthonormal
1097  // orthogonal to auxvecs
1098  // checkAux: check that auxiliary vectors are actually orthonormal
1099  //
1100  // checkArn: check the Arnoldi factorization
1101  //
1102  // NOTE: This method needs to check the current dimension of the subspace, since it is possible to
1103  // call this method when curDim_ = 0 (after initialization).
1104  template <class ScalarType, class MV, class OP>
1105  std::string BlockKrylovSchur<ScalarType,MV,OP>::accuracyCheck( const CheckList &chk, const std::string &where ) const
1106  {
1107  std::stringstream os;
1108  os.precision(2);
1109  os.setf(std::ios::scientific, std::ios::floatfield);
1110  MagnitudeType tmp;
1111 
1112  os << " Debugging checks: iteration " << iter_ << where << std::endl;
1113 
1114  // index vectors for V and F
1115  std::vector<int> lclind(curDim_);
1116  for (int i=0; i<curDim_; i++) lclind[i] = i;
1117  std::vector<int> bsind(blockSize_);
1118  for (int i=0; i<blockSize_; i++) { bsind[i] = curDim_ + i; }
1119 
1120  Teuchos::RCP<const MV> lclV,lclF;
1121  Teuchos::RCP<MV> lclAV;
1122  if (curDim_)
1123  lclV = MVT::CloneView(*V_,lclind);
1124  lclF = MVT::CloneView(*V_,bsind);
1125 
1126  if (chk.checkV) {
1127  if (curDim_) {
1128  tmp = orthman_->orthonormError(*lclV);
1129  os << " >> Error in V^H M V == I : " << tmp << std::endl;
1130  }
1131  tmp = orthman_->orthonormError(*lclF);
1132  os << " >> Error in F^H M F == I : " << tmp << std::endl;
1133  if (curDim_) {
1134  tmp = orthman_->orthogError(*lclV,*lclF);
1135  os << " >> Error in V^H M F == 0 : " << tmp << std::endl;
1136  }
1137  for (Array_size_type i=0; i<auxVecs_.size(); i++) {
1138  if (curDim_) {
1139  tmp = orthman_->orthogError(*lclV,*auxVecs_[i]);
1140  os << " >> Error in V^H M Aux[" << i << "] == 0 : " << tmp << std::endl;
1141  }
1142  tmp = orthman_->orthogError(*lclF,*auxVecs_[i]);
1143  os << " >> Error in F^H M Aux[" << i << "] == 0 : " << tmp << std::endl;
1144  }
1145  }
1146 
1147  if (chk.checkArn) {
1148 
1149  if (curDim_) {
1150  // Compute AV
1151  lclAV = MVT::Clone(*V_,curDim_);
1152  {
1153 #ifdef ANASAZI_TEUCHOS_TIME_MONITOR
1154  Teuchos::TimeMonitor lcltimer( *timerOp_ );
1155 #endif
1156  OPT::Apply(*Op_,*lclV,*lclAV);
1157  }
1158 
1159  // Compute AV - VH
1161  MVT::MvTimesMatAddMv( -ST_ONE, *lclV, subH, ST_ONE, *lclAV );
1162 
1163  // Compute FB_k^T - (AV-VH)
1165  blockSize_,curDim_, curDim_ );
1166  MVT::MvTimesMatAddMv( -ST_ONE, *lclF, curB, ST_ONE, *lclAV );
1167 
1168  // Compute || FE_k^T - (AV-VH) ||
1169  std::vector<MagnitudeType> arnNorms( curDim_ );
1170  orthman_->norm( *lclAV, arnNorms );
1171 
1172  for (int i=0; i<curDim_; i++) {
1173  os << " >> Error in Krylov-Schur factorization (R = AV-VS-FB^H), ||R[" << i << "]|| : " << arnNorms[i] << std::endl;
1174  }
1175  }
1176  }
1177 
1178  if (chk.checkAux) {
1179  for (Array_size_type i=0; i<auxVecs_.size(); i++) {
1180  tmp = orthman_->orthonormError(*auxVecs_[i]);
1181  os << " >> Error in Aux[" << i << "]^H M Aux[" << i << "] == I : " << tmp << std::endl;
1182  for (Array_size_type j=i+1; j<auxVecs_.size(); j++) {
1183  tmp = orthman_->orthogError(*auxVecs_[i],*auxVecs_[j]);
1184  os << " >> Error in Aux[" << i << "]^H M Aux[" << j << "] == 0 : " << tmp << std::endl;
1185  }
1186  }
1187  }
1188 
1189  os << std::endl;
1190 
1191  return os.str();
1192  }
1193 
1195  /* Get the current approximate eigenvalues, i.e. Ritz values.
1196  *
1197  * POST-CONDITIONS:
1198  *
1199  * ritzValues_ contains Ritz w.r.t. V, H
1200  * Q_ contains the Schur vectors w.r.t. H
1201  * schurH_ contains the Schur matrix w.r.t. H
1202  * ritzOrder_ contains the current ordering from sort manager
1203  */
1204 
1205  template <class ScalarType, class MV, class OP>
1207  {
1208  // Can only call this if the solver is initialized
1209  if (initialized_) {
1210 
1211  // This just updates the Ritz values and residuals.
1212  // --> ritzValsCurrent_ will be set to 'true' by this method.
1213  if (!ritzValsCurrent_) {
1214  // Compute the current Ritz values, through computing the Schur form
1215  // without updating the current projection matrix or sorting the Schur form.
1216  computeSchurForm( false );
1217  }
1218  }
1219  }
1220 
1222  /* Get the current approximate eigenvectors, i.e. Ritz vectors.
1223  *
1224  * POST-CONDITIONS:
1225  *
1226  * ritzValues_ contains Ritz w.r.t. V, H
1227  * ritzVectors_ is first blockSize_ Ritz vectors w.r.t. V, H
1228  * Q_ contains the Schur vectors w.r.t. H
1229  * schurH_ contains the Schur matrix w.r.t. H
1230  * ritzOrder_ contains the current ordering from sort manager
1231  */
1232 
1233  template <class ScalarType, class MV, class OP>
1235  {
1236 #ifdef ANASAZI_TEUCHOS_TIME_MONITOR
1237  Teuchos::TimeMonitor LocalTimer(*timerCompRitzVec_);
1238 #endif
1239 
1240  TEUCHOS_TEST_FOR_EXCEPTION(numRitzVecs_==0, std::invalid_argument,
1241  "Anasazi::BlockKrylovSchur::computeRitzVectors(): no Ritz vectors were required from this solver.");
1242 
1243  TEUCHOS_TEST_FOR_EXCEPTION(curDim_ < numRitzVecs_, std::invalid_argument,
1244  "Anasazi::BlockKrylovSchur::computeRitzVectors(): the current subspace is not large enough to compute the number of requested Ritz vectors.");
1245 
1246 
1247  // Check to see if the current subspace dimension is non-trivial and the solver is initialized
1248  if (curDim_ && initialized_) {
1249 
1250  // Check to see if the Ritz vectors are current.
1251  if (!ritzVecsCurrent_) {
1252 
1253  // Check to see if the Schur factorization of H (schurH_, Q) is current and sorted.
1254  if (!schurCurrent_) {
1255  // Compute the Schur factorization of the current H, which will not directly change H,
1256  // the factorization will be sorted and placed in (schurH_, Q)
1257  computeSchurForm( true );
1258  }
1259 
1260  // After the Schur form is computed, then the Ritz values are current.
1261  // Thus, I can check the Ritz index vector to see if I have enough space for the Ritz vectors requested.
1262  TEUCHOS_TEST_FOR_EXCEPTION(ritzIndex_[numRitzVecs_-1]==1, std::logic_error,
1263  "Anasazi::BlockKrylovSchur::computeRitzVectors(): the number of required Ritz vectors splits a complex conjugate pair.");
1264 
1267 
1268  // Compute the Ritz vectors.
1269  // --> For a Hermitian problem this is simply the current basis times the first numRitzVecs_ Schur vectors
1270  //
1271  // --> For a non-Hermitian problem, this involves solving the projected eigenproblem, then
1272  // placing the product of the current basis times the first numRitzVecs_ Schur vectors times the
1273  // eigenvectors of interest into the Ritz vectors.
1274 
1275  // Get a view of the current Krylov-Schur basis vectors and Schur vectors
1276  std::vector<int> curind( curDim_ );
1277  for (int i=0; i<curDim_; i++) { curind[i] = i; }
1278  Teuchos::RCP<const MV> Vtemp = MVT::CloneView( *V_, curind );
1279  if (problem_->isHermitian()) {
1280  // Get a view into the current Schur vectors
1281  Teuchos::SerialDenseMatrix<int,ScalarType> subQ( Teuchos::View, *Q_, curDim_, numRitzVecs_ );
1282 
1283  // Compute the current Ritz vectors
1284  MVT::MvTimesMatAddMv( ST_ONE, *Vtemp, subQ, ST_ZERO, *ritzVectors_ );
1285 
1286  } else {
1287 
1288  // Get a view into the current Schur vectors.
1289  Teuchos::SerialDenseMatrix<int,ScalarType> subQ( Teuchos::View, *Q_, curDim_, curDim_ );
1290 
1291  // Get a set of work vectors to hold the current Ritz vectors.
1292  Teuchos::RCP<MV> tmpritzVectors_ = MVT::Clone( *V_, curDim_ );
1293 
1294  // Compute the current Krylov-Schur vectors.
1295  MVT::MvTimesMatAddMv( ST_ONE, *Vtemp, subQ, ST_ZERO, *tmpritzVectors_ );
1296 
1297  // Now compute the eigenvectors of the Schur form
1298  // Reset the dense matrix and compute the eigenvalues of the Schur form.
1299  //
1300  // Allocate the work space. This space will be used below for calls to:
1301  // * TREVC (requires 3*N for real, 2*N for complex)
1302 
1303  int lwork = 3*curDim_;
1304  std::vector<ScalarType> work( lwork );
1305  std::vector<MagnitudeType> rwork( curDim_ );
1306  char side = 'R';
1307  int mm, info = 0;
1308  const int ldvl = 1;
1309  ScalarType vl[ ldvl ];
1310  Teuchos::SerialDenseMatrix<int,ScalarType> copyQ( Teuchos::Copy, *Q_, curDim_, curDim_ );
1311  lapack.TREVC( side, curDim_, schurH_->values(), schurH_->stride(), vl, ldvl,
1312  copyQ.values(), copyQ.stride(), curDim_, &mm, &work[0], &rwork[0], &info );
1313  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, std::logic_error,
1314  "Anasazi::BlockKrylovSchur::computeRitzVectors(): TREVC(n==" << curDim_ << ") returned info " << info << " != 0.");
1315 
1316  // Get a view into the eigenvectors of the Schur form
1317  Teuchos::SerialDenseMatrix<int,ScalarType> subCopyQ( Teuchos::View, copyQ, curDim_, numRitzVecs_ );
1318 
1319  // Convert back to Ritz vectors of the operator.
1320  curind.resize( numRitzVecs_ ); // This is already initialized above
1321  Teuchos::RCP<MV> view_ritzVectors = MVT::CloneViewNonConst( *ritzVectors_, curind );
1322  MVT::MvTimesMatAddMv( ST_ONE, *tmpritzVectors_, subCopyQ, ST_ZERO, *view_ritzVectors );
1323 
1324  // Compute the norm of the new Ritz vectors
1325  std::vector<MagnitudeType> ritzNrm( numRitzVecs_ );
1326  MVT::MvNorm( *view_ritzVectors, ritzNrm );
1327 
1328  // Release memory used to compute Ritz vectors before scaling the current vectors.
1329  tmpritzVectors_ = Teuchos::null;
1330  view_ritzVectors = Teuchos::null;
1331 
1332  // Scale the Ritz vectors to have Euclidean norm.
1333  ScalarType ritzScale = ST_ONE;
1334  for (int i=0; i<numRitzVecs_; i++) {
1335 
1336  // If this is a conjugate pair then normalize by the real and imaginary parts.
1337  if (ritzIndex_[i] == 1 ) {
1338  ritzScale = ST_ONE/lapack_mag.LAPY2(ritzNrm[i],ritzNrm[i+1]);
1339  std::vector<int> newind(2);
1340  newind[0] = i; newind[1] = i+1;
1341  tmpritzVectors_ = MVT::CloneCopy( *ritzVectors_, newind );
1342  view_ritzVectors = MVT::CloneViewNonConst( *ritzVectors_, newind );
1343  MVT::MvAddMv( ritzScale, *tmpritzVectors_, ST_ZERO, *tmpritzVectors_, *view_ritzVectors );
1344 
1345  // Increment counter for imaginary part
1346  i++;
1347  } else {
1348 
1349  // This is a real Ritz value, normalize the vector
1350  std::vector<int> newind(1);
1351  newind[0] = i;
1352  tmpritzVectors_ = MVT::CloneCopy( *ritzVectors_, newind );
1353  view_ritzVectors = MVT::CloneViewNonConst( *ritzVectors_, newind );
1354  MVT::MvAddMv( ST_ONE/ritzNrm[i], *tmpritzVectors_, ST_ZERO, *tmpritzVectors_, *view_ritzVectors );
1355  }
1356  }
1357 
1358  } // if (problem_->isHermitian())
1359 
1360  // The current Ritz vectors have been computed.
1361  ritzVecsCurrent_ = true;
1362 
1363  } // if (!ritzVecsCurrent_)
1364  } // if (curDim_)
1365  } // computeRitzVectors()
1366 
1367 
1369  // Set a new StatusTest for the solver.
1370  template <class ScalarType, class MV, class OP>
1372  TEUCHOS_TEST_FOR_EXCEPTION(test == Teuchos::null,std::invalid_argument,
1373  "Anasazi::BlockKrylovSchur::setStatusTest() was passed a null StatusTest.");
1374  tester_ = test;
1375  }
1376 
1378  // Get the current StatusTest used by the solver.
1379  template <class ScalarType, class MV, class OP>
1381  return tester_;
1382  }
1383 
1384 
1386  /* Get the current approximate eigenvalues, i.e. Ritz values.
1387  *
1388  * POST-CONDITIONS:
1389  *
1390  * ritzValues_ contains Ritz w.r.t. V, H
1391  * Q_ contains the Schur vectors w.r.t. H
1392  * schurH_ contains the Schur matrix w.r.t. H
1393  * ritzOrder_ contains the current ordering from sort manager
1394  * schurCurrent_ = true if sort = true; i.e. the Schur form is sorted according to the index
1395  * vector returned by the sort manager.
1396  */
1397  template <class ScalarType, class MV, class OP>
1399  {
1400  // local timer
1401 #ifdef ANASAZI_TEUCHOS_TIME_MONITOR
1402  Teuchos::TimeMonitor LocalTimer(*timerCompSF_);
1403 #endif
1404 
1405  // Check to see if the dimension of the factorization is greater than zero.
1406  if (curDim_) {
1407 
1408  // Check to see if the Schur factorization is current.
1409  if (!schurCurrent_) {
1410 
1411  // Check to see if the Ritz values are current
1412  // --> If they are then the Schur factorization is current but not sorted.
1413  if (!ritzValsCurrent_) {
1418 
1419  // Get a view into Q, the storage for H's Schur vectors.
1420  Teuchos::SerialDenseMatrix<int,ScalarType> subQ( Teuchos::View, *Q_, curDim_, curDim_ );
1421 
1422  // Get a copy of H to compute/sort the Schur form.
1423  schurH_ = Teuchos::rcp( new Teuchos::SerialDenseMatrix<int,ScalarType>( Teuchos::Copy, *H_, curDim_, curDim_ ) );
1424  //
1425  //---------------------------------------------------
1426  // Compute the Schur factorization of subH
1427  // ---> Use driver GEES to first reduce to upper Hessenberg
1428  // form and then compute Schur form, outputting Ritz values
1429  //---------------------------------------------------
1430  //
1431  // Allocate the work space. This space will be used below for calls to:
1432  // * GEES (requires 3*N for real, 2*N for complex)
1433  // * TREVC (requires 3*N for real, 2*N for complex)
1434  // * TREXC (requires N for real, none for complex)
1435  // Furthermore, GEES requires a real array of length curDim_ (for complex datatypes)
1436  //
1437  int lwork = 3*curDim_;
1438  std::vector<ScalarType> work( lwork );
1439  std::vector<MagnitudeType> rwork( curDim_ );
1440  std::vector<MagnitudeType> tmp_rRitzValues( curDim_ );
1441  std::vector<MagnitudeType> tmp_iRitzValues( curDim_ );
1442  std::vector<int> bwork( curDim_ );
1443  int info = 0, sdim = 0;
1444  char jobvs = 'V';
1445  lapack.GEES( jobvs,curDim_, schurH_->values(), schurH_->stride(), &sdim, &tmp_rRitzValues[0],
1446  &tmp_iRitzValues[0], subQ.values(), subQ.stride(), &work[0], lwork,
1447  &rwork[0], &bwork[0], &info );
1448 
1449  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, std::logic_error,
1450  "Anasazi::BlockKrylovSchur::computeSchurForm(): GEES(n==" << curDim_ << ") returned info " << info << " != 0.");
1451  //
1452  //---------------------------------------------------
1453  // Use the Krylov-Schur factorization to compute the current Ritz residuals
1454  // for ALL the eigenvalues estimates (Ritz values)
1455  // || Ax - x\theta || = || U_m+1*B_m+1^H*Q*s ||
1456  // = || B_m+1^H*Q*s ||
1457  //
1458  // where U_m+1 is the current Krylov-Schur basis, Q are the Schur vectors, and x = U_m+1*Q*s
1459  // NOTE: This means that s = e_i if the problem is hermitian, else the eigenvectors
1460  // of the Schur form need to be computed.
1461  //
1462  // First compute H_{m+1,m}*B_m^T, then determine what 's' is.
1463  //---------------------------------------------------
1464  //
1465  // Get current B_m+1
1467  blockSize_, curDim_, curDim_ );
1468  //
1469  // Compute B_m+1^H*Q
1470  Teuchos::SerialDenseMatrix<int,ScalarType> subB( blockSize_, curDim_ );
1471  blas.GEMM( Teuchos::NO_TRANS, Teuchos::NO_TRANS, blockSize_, curDim_, curDim_, ST_ONE,
1472  curB.values(), curB.stride(), subQ.values(), subQ.stride(),
1473  ST_ZERO, subB.values(), subB.stride() );
1474  //
1475  // Determine what 's' is and compute Ritz residuals.
1476  //
1477  ScalarType* b_ptr = subB.values();
1478  if (problem_->isHermitian()) {
1479  //
1480  // 's' is the i-th canonical basis vector.
1481  //
1482  for (int i=0; i<curDim_ ; i++) {
1483  ritzResiduals_[i] = blas.NRM2(blockSize_, b_ptr + i*blockSize_, 1);
1484  }
1485  } else {
1486  //
1487  // Compute S: the eigenvectors of the block upper triangular, Schur matrix.
1488  //
1489  char side = 'R';
1490  int mm;
1491  const int ldvl = 1;
1492  ScalarType vl[ ldvl ];
1493  Teuchos::SerialDenseMatrix<int,ScalarType> S( curDim_, curDim_ );
1494  lapack.TREVC( side, curDim_, schurH_->values(), schurH_->stride(), vl, ldvl,
1495  S.values(), S.stride(), curDim_, &mm, &work[0], &rwork[0], &info );
1496 
1497  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, std::logic_error,
1498  "Anasazi::BlockKrylovSchur::computeSchurForm(): TREVC(n==" << curDim_ << ") returned info " << info << " != 0.");
1499  //
1500  // Scale the eigenvectors so that their Euclidean norms are all one.
1501  //
1502  HelperTraits<ScalarType>::scaleRitzVectors( tmp_iRitzValues, &S );
1503  //
1504  // Compute ritzRes = *B_m+1^H*Q*S where the i-th column of S is 's' for the i-th Ritz-value
1505  //
1506  Teuchos::SerialDenseMatrix<int,ScalarType> ritzRes( blockSize_, curDim_ );
1507  blas.GEMM( Teuchos::NO_TRANS, Teuchos::NO_TRANS, blockSize_, curDim_, curDim_, ST_ONE,
1508  subB.values(), subB.stride(), S.values(), S.stride(),
1509  ST_ZERO, ritzRes.values(), ritzRes.stride() );
1510 
1511  /* TO DO: There's be an incorrect assumption made in the computation of the Ritz residuals.
1512  This assumption is that the next vector in the Krylov subspace is Euclidean orthonormal.
1513  It may not be normalized using Euclidean norm.
1514  Teuchos::RCP<MV> ritzResVecs = MVT::Clone( *V_, curDim_ );
1515  std::vector<int> curind(blockSize_);
1516  for (int i=0; i<blockSize_; i++) { curind[i] = curDim_ + i; }
1517  Teuchos::RCP<MV> Vtemp = MVT::CloneView(*V_,curind);
1518 
1519  MVT::MvTimesMatAddMv( ST_ONE, *Vtemp, ritzRes, ST_ZERO, *ritzResVecs );
1520  std::vector<MagnitudeType> ritzResNrms(curDim_);
1521  MVT::MvNorm( *ritzResVecs, ritzResNrms );
1522  i = 0;
1523  while( i < curDim_ ) {
1524  if ( tmp_ritzValues[curDim_+i] != MT_ZERO ) {
1525  ritzResiduals_[i] = lapack_mag.LAPY2( ritzResNrms[i], ritzResNrms[i+1] );
1526  ritzResiduals_[i+1] = ritzResiduals_[i];
1527  i = i+2;
1528  } else {
1529  ritzResiduals_[i] = ritzResNrms[i];
1530  i++;
1531  }
1532  }
1533  */
1534  //
1535  // Compute the Ritz residuals for each Ritz value.
1536  //
1537  HelperTraits<ScalarType>::computeRitzResiduals( tmp_iRitzValues, ritzRes, &ritzResiduals_ );
1538  }
1539  //
1540  // Sort the Ritz values.
1541  //
1542  {
1543 #ifdef ANASAZI_TEUCHOS_TIME_MONITOR
1544  Teuchos::TimeMonitor LocalTimer2(*timerSortRitzVal_);
1545 #endif
1546  int i=0;
1547  if (problem_->isHermitian()) {
1548  //
1549  // Sort using just the real part of the Ritz values.
1550  sm_->sort(tmp_rRitzValues, Teuchos::rcpFromRef(ritzOrder_), curDim_); // don't catch exception
1551  ritzIndex_.clear();
1552  while ( i < curDim_ ) {
1553  // The Ritz value is not complex.
1554  ritzValues_[i].set(tmp_rRitzValues[i], MT_ZERO);
1555  ritzIndex_.push_back(0);
1556  i++;
1557  }
1558  }
1559  else {
1560  //
1561  // Sort using both the real and imaginary parts of the Ritz values.
1562  sm_->sort(tmp_rRitzValues, tmp_iRitzValues, Teuchos::rcpFromRef(ritzOrder_) , curDim_);
1563  HelperTraits<ScalarType>::sortRitzValues( tmp_rRitzValues, tmp_iRitzValues, &ritzValues_, &ritzOrder_, &ritzIndex_ );
1564  }
1565  //
1566  // Sort the ritzResiduals_ based on the ordering from the Sort Manager.
1567  std::vector<MagnitudeType> ritz2( curDim_ );
1568  for (i=0; i<curDim_; i++) { ritz2[i] = ritzResiduals_[ ritzOrder_[i] ]; }
1569  blas_mag.COPY( curDim_, &ritz2[0], 1, &ritzResiduals_[0], 1 );
1570 
1571  // The Ritz values have now been updated.
1572  ritzValsCurrent_ = true;
1573  }
1574 
1575  } // if (!ritzValsCurrent_) ...
1576  //
1577  //---------------------------------------------------
1578  // * The Ritz values and residuals have been updated at this point.
1579  //
1580  // * The Schur factorization of the projected matrix has been computed,
1581  // and is stored in (schurH_, Q_).
1582  //
1583  // Now the Schur factorization needs to be sorted.
1584  //---------------------------------------------------
1585  //
1586  // Sort the Schur form using the ordering from the Sort Manager.
1587  if (sort) {
1588  sortSchurForm( *schurH_, *Q_, ritzOrder_ );
1589  //
1590  // Indicate the Schur form in (schurH_, Q_) is current and sorted
1591  schurCurrent_ = true;
1592  }
1593  } // if (!schurCurrent_) ...
1594 
1595  } // if (curDim_) ...
1596 
1597  } // computeSchurForm( ... )
1598 
1599 
1601  // Sort the Schur form of H stored in (H,Q) using the ordering vector.
1602  template <class ScalarType, class MV, class OP>
1605  std::vector<int>& order )
1606  {
1607  // local timer
1608 #ifdef ANASAZI_TEUCHOS_TIME_MONITOR
1609  Teuchos::TimeMonitor LocalTimer(*timerSortSF_);
1610 #endif
1611  //
1612  //---------------------------------------------------
1613  // Reorder real Schur factorization, remember to add one to the indices for the
1614  // fortran call and determine offset. The offset is necessary since the TREXC
1615  // method reorders in a nonsymmetric fashion, thus we use the reordering in
1616  // a stack-like fashion. Also take into account conjugate pairs, which may mess
1617  // up the reordering, since the pair is moved if one of the pair is moved.
1618  //---------------------------------------------------
1619  //
1620  int i = 0, nevtemp = 0;
1621  char compq = 'V';
1622  std::vector<int> offset2( curDim_ );
1623  std::vector<int> order2( curDim_ );
1624 
1625  // LAPACK objects.
1627  int lwork = 3*curDim_;
1628  std::vector<ScalarType> work( lwork );
1629 
1630  while (i < curDim_) {
1631  if ( ritzIndex_[i] != 0 ) { // This is the first value of a complex conjugate pair
1632  offset2[nevtemp] = 0;
1633  for (int j=i; j<curDim_; j++) {
1634  if (order[j] > order[i]) { offset2[nevtemp]++; }
1635  }
1636  order2[nevtemp] = order[i];
1637  i = i+2;
1638  } else {
1639  offset2[nevtemp] = 0;
1640  for (int j=i; j<curDim_; j++) {
1641  if (order[j] > order[i]) { offset2[nevtemp]++; }
1642  }
1643  order2[nevtemp] = order[i];
1644  i++;
1645  }
1646  nevtemp++;
1647  }
1648  ScalarType *ptr_h = H.values();
1649  ScalarType *ptr_q = Q.values();
1650  int ldh = H.stride(), ldq = Q.stride();
1651  int info = 0;
1652  for (i=nevtemp-1; i>=0; i--) {
1653  lapack.TREXC( compq, curDim_, ptr_h, ldh, ptr_q, ldq, order2[i]+1+offset2[i],
1654  1, &work[0], &info );
1655  TEUCHOS_TEST_FOR_EXCEPTION(info != 0, std::logic_error,
1656  "Anasazi::BlockKrylovSchur::computeSchurForm(): TREXC(n==" << curDim_ << ") returned info " << info << " != 0.");
1657  }
1658  }
1659 
1661  // Print the current status of the solver
1662  template <class ScalarType, class MV, class OP>
1664  {
1665  using std::endl;
1666 
1667  os.setf(std::ios::scientific, std::ios::floatfield);
1668  os.precision(6);
1669  os <<"================================================================================" << endl;
1670  os << endl;
1671  os <<" BlockKrylovSchur Solver Status" << endl;
1672  os << endl;
1673  os <<"The solver is "<<(initialized_ ? "initialized." : "not initialized.") << endl;
1674  os <<"The number of iterations performed is " <<iter_<<endl;
1675  os <<"The block size is " << blockSize_<<endl;
1676  os <<"The number of blocks is " << numBlocks_<<endl;
1677  os <<"The current basis size is " << curDim_<<endl;
1678  os <<"The number of auxiliary vectors is " << numAuxVecs_ << endl;
1679  os <<"The number of operations Op*x is "<<count_ApplyOp_<<endl;
1680 
1681  os.setf(std::ios_base::right, std::ios_base::adjustfield);
1682 
1683  os << endl;
1684  if (initialized_) {
1685  os <<"CURRENT RITZ VALUES "<<endl;
1686  if (ritzIndex_.size() != 0) {
1687  int numPrint = (curDim_ < numRitzPrint_? curDim_: numRitzPrint_);
1688  if (problem_->isHermitian()) {
1689  os << std::setw(20) << "Ritz Value"
1690  << std::setw(20) << "Ritz Residual"
1691  << endl;
1692  os <<"--------------------------------------------------------------------------------"<<endl;
1693  for (int i=0; i<numPrint; i++) {
1694  os << std::setw(20) << ritzValues_[i].realpart
1695  << std::setw(20) << ritzResiduals_[i]
1696  << endl;
1697  }
1698  } else {
1699  os << std::setw(24) << "Ritz Value"
1700  << std::setw(30) << "Ritz Residual"
1701  << endl;
1702  os <<"--------------------------------------------------------------------------------"<<endl;
1703  for (int i=0; i<numPrint; i++) {
1704  // Print out the real eigenvalue.
1705  os << std::setw(15) << ritzValues_[i].realpart;
1706  if (ritzValues_[i].imagpart < MT_ZERO) {
1707  os << " - i" << std::setw(15) << Teuchos::ScalarTraits<MagnitudeType>::magnitude(ritzValues_[i].imagpart);
1708  } else {
1709  os << " + i" << std::setw(15) << ritzValues_[i].imagpart;
1710  }
1711  os << std::setw(20) << ritzResiduals_[i] << endl;
1712  }
1713  }
1714  } else {
1715  os << std::setw(20) << "[ NONE COMPUTED ]" << endl;
1716  }
1717  }
1718  os << endl;
1719  os <<"================================================================================" << endl;
1720  os << endl;
1721  }
1722 
1723 } // End of namespace Anasazi
1724 
1725 #endif
1726 
1727 // End of file AnasaziBlockKrylovSchur.hpp
ScalarType * values() const
void computeRitzValues()
Compute the Ritz values using the current Krylov factorization.
BlockKrylovSchurOrthoFailure is thrown when the orthogonalization manager is unable to generate ortho...
Teuchos::Array< Teuchos::RCP< const MV > > getAuxVecs() const
Get the auxiliary vectors for the solver.
Teuchos::RCP< const Teuchos::SerialDenseMatrix< int, ScalarType > > H
The current Hessenberg matrix.
BlockKrylovSchurState< ScalarType, MV > getState() const
Get the current state of the eigensolver.
An extension of the MultiVecTraits class that adds a new vector length method.This traits class provi...
void setStepSize(int stepSize)
Set the step size.
bool isRitzValsCurrent() const
Get the status of the Ritz values currently stored in the eigensolver.
const Eigenproblem< ScalarType, MV, OP > & getProblem() const
Get a constant reference to the eigenvalue problem.
std::vector< typename Teuchos::ScalarTraits< ScalarType >::magnitudeType > getRitzRes2Norms()
Get the current Ritz residual 2-norms.
Array< T > & append(const T &x)
void TREXC(const char COMPQ, const OrdinalType n, ScalarType *T, const OrdinalType ldt, ScalarType *Q, const OrdinalType ldq, OrdinalType ifst, OrdinalType ilst, ScalarType *WORK, OrdinalType *info) const
Teuchos::RCP< const MV > getRitzVectors()
Get the Ritz vectors.
This class defines the interface required by an eigensolver and status test class to compute solution...
virtual ~BlockKrylovSchur()
BlockKrylovSchur destructor.
int getBlockSize() const
Get the blocksize to be used by the iterative solver in solving this eigenproblem.
Declaration of basic traits for the multivector type.
bool isInitialized() const
Indicates whether the solver has been initialized or not.
T & get(const std::string &name, T def_value)
std::vector< typename Teuchos::ScalarTraits< ScalarType >::magnitudeType > getResNorms()
Get the current residual norms.
void setAuxVecs(const Teuchos::Array< Teuchos::RCP< const MV > > &auxvecs)
Set the auxiliary vectors for the solver.
void COPY(const OrdinalType n, const ScalarType *x, const OrdinalType incx, ScalarType *y, const OrdinalType incy) const
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
void iterate()
This method performs Block Krylov-Schur iterations until the status test indicates the need to stop o...
Virtual base class which defines basic traits for the operator type.
void GEES(const char JOBVS, const char SORT, OrdinalType(*ptr2func)(ScalarType *, ScalarType *), const OrdinalType n, ScalarType *A, const OrdinalType lda, OrdinalType *sdim, ScalarType *WR, ScalarType *WI, ScalarType *VS, const OrdinalType ldvs, ScalarType *WORK, const OrdinalType lwork, OrdinalType *BWORK, OrdinalType *info) const
static void scaleRitzVectors(const std::vector< typename Teuchos::ScalarTraits< ScalarType >::magnitudeType > &iRV, Teuchos::SerialDenseMatrix< int, ScalarType > *S)
Helper function for correctly scaling the eigenvectors of the projected eigenproblem.
Structure to contain pointers to BlockKrylovSchur state variables.
An exception class parent to all Anasazi exceptions.
void setStatusTest(Teuchos::RCP< StatusTest< ScalarType, MV, OP > > test)
Set a new StatusTest for the solver.
void TREVC(const char SIDE, const char HOWMNY, OrdinalType *select, const OrdinalType n, const ScalarType *T, const OrdinalType ldt, ScalarType *VL, const OrdinalType ldvl, ScalarType *VR, const OrdinalType ldvr, const OrdinalType mm, OrdinalType *m, ScalarType *WORK, OrdinalType *info) const
int getCurSubspaceDim() const
Get the dimension of the search subspace used to generate the current eigenvectors and eigenvalues...
int getNumIters() const
Get the current iteration count.
Pure virtual base class which describes the basic interface to the iterative eigensolver.
bool isRitzVecsCurrent() const
Get the status of the Ritz vectors currently stored in the eigensolver.
void initialize()
Initialize the solver with the initial vectors from the eigenproblem or random data.
void computeRitzVectors()
Compute the Ritz vectors using the current Krylov factorization.
int getStepSize() const
Get the step size.
bool isParameter(const std::string &name) const
void setNumRitzVectors(int numRitzVecs)
Set the number of Ritz vectors to compute.
Teuchos::RCP< StatusTest< ScalarType, MV, OP > > getStatusTest() const
Get the current StatusTest used by the solver.
void computeSchurForm(const bool sort=true)
Compute the Schur form of the projected eigenproblem from the current Krylov factorization.
static void sortRitzValues(const std::vector< typename Teuchos::ScalarTraits< ScalarType >::magnitudeType > &rRV, const std::vector< typename Teuchos::ScalarTraits< ScalarType >::magnitudeType > &iRV, std::vector< Value< ScalarType > > *RV, std::vector< int > *RO, std::vector< int > *RI)
Helper function for correctly storing the Ritz values when the eigenproblem is non-Hermitian.
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
bool isSchurCurrent() const
Get the status of the Schur form currently stored in the eigensolver.
BlockKrylovSchur(const Teuchos::RCP< Eigenproblem< ScalarType, MV, OP > > &problem, const Teuchos::RCP< SortManager< typename Teuchos::ScalarTraits< ScalarType >::magnitudeType > > &sorter, const Teuchos::RCP< OutputManager< ScalarType > > &printer, const Teuchos::RCP< StatusTest< ScalarType, MV, OP > > &tester, const Teuchos::RCP< OrthoManager< ScalarType, MV > > &ortho, Teuchos::ParameterList &params)
BlockKrylovSchur constructor with eigenproblem, solver utilities, and parameter list of solver option...
Output managers remove the need for the eigensolver to know any information about the required output...
void resetNumIters()
Reset the iteration count.
void GEMM(ETransp transa, ETransp transb, const OrdinalType m, const OrdinalType n, const OrdinalType k, const alpha_type alpha, const A_type *A, const OrdinalType lda, const B_type *B, const OrdinalType ldb, const beta_type beta, ScalarType *C, const OrdinalType ldc) const
Templated virtual class for providing orthogonalization/orthonormalization methods.
Traits class which defines basic operations on multivectors.
Virtual base class which defines basic traits for the operator type.
int getMaxSubspaceDim() const
Get the maximum dimension allocated for the search subspace.
int getNumRitzVectors() const
Get the number of Ritz vectors to compute.
std::vector< Value< ScalarType > > getRitzValues()
Get the Ritz values.
std::vector< int > getRitzIndex()
Get the Ritz index vector.
static magnitudeType magnitude(T a)
std::vector< typename Teuchos::ScalarTraits< ScalarType >::magnitudeType > getRes2Norms()
Get the current residual 2-norms.
Teuchos::RCP< const MulVec > V
The current Krylov basis.
BlockKrylovSchurInitFailure is thrown when the BlockKrylovSchur solver is unable to generate an initi...
Types and exceptions used within Anasazi solvers and interfaces.
void currentStatus(std::ostream &os)
This method requests that the solver print out its current status to screen.
Anasazi&#39;s templated virtual class for providing routines for orthogonalization and orthonormalization...
Teuchos::RCP< const Teuchos::SerialDenseMatrix< int, ScalarType > > Q
The current Schur vectors of the valid part of H.
static void computeRitzResiduals(const std::vector< typename Teuchos::ScalarTraits< ScalarType >::magnitudeType > &iRV, const Teuchos::SerialDenseMatrix< int, ScalarType > &S, std::vector< typename Teuchos::ScalarTraits< ScalarType >::magnitudeType > *RR)
Helper function for correctly computing the Ritz residuals of the projected eigenproblem.
void setBlockSize(int blockSize)
Set the blocksize.
This class implements the block Krylov-Schur iteration, for solving linear eigenvalue problems...
Anasazi&#39;s templated pure virtual class for managing the sorting of approximate eigenvalues computed b...
void setSize(int blockSize, int numBlocks)
Set the blocksize and number of blocks to be used by the iterative solver in solving this eigenproble...
int curDim
The current dimension of the reduction.
A pure virtual class for defining the status tests for the Anasazi iterative solvers.
The Eigensolver is a templated virtual base class that defines the basic interface that any eigensolv...
Teuchos::RCP< const Teuchos::SerialDenseMatrix< int, ScalarType > > S
The current Schur form reduction of the valid part of H.
OrdinalType stride() const
ScalarType LAPY2(const ScalarType x, const ScalarType y) const
ScalarTraits< ScalarType >::magnitudeType NRM2(const OrdinalType n, const ScalarType *x, const OrdinalType incx) const