Anasazi  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
AnasaziTsqrOrthoManagerImpl.hpp
1 // @HEADER
2 // ***********************************************************************
3 //
4 // Anasazi: Block Eigensolvers Package
5 // Copyright (2010) 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 
32 #ifndef __AnasaziTsqrOrthoManagerImpl_hpp
33 #define __AnasaziTsqrOrthoManagerImpl_hpp
34 
35 #include "AnasaziConfigDefs.hpp"
37 #include "AnasaziOrthoManager.hpp" // OrthoError, etc.
38 
39 #include "Teuchos_as.hpp"
40 #include "Teuchos_LAPACK.hpp"
42 #include "Teuchos_ParameterListAcceptorDefaultBase.hpp"
43 #include <algorithm>
44 
45 
46 namespace Anasazi {
47 
51  class TsqrOrthoError : public OrthoError {
52  public:
53  TsqrOrthoError (const std::string& what_arg) :
54  OrthoError (what_arg) {}
55  };
56 
76  class TsqrOrthoFault : public OrthoError {
77  public:
78  TsqrOrthoFault (const std::string& what_arg) :
79  OrthoError (what_arg) {}
80  };
81 
114  template<class Scalar, class MV>
117  public:
118  typedef Scalar scalar_type;
119  typedef typename Teuchos::ScalarTraits<Scalar>::magnitudeType magnitude_type;
120  typedef MV multivector_type;
125 
126  private:
131  typedef typename MVT::tsqr_adaptor_type tsqr_adaptor_type;
132 
133  public:
142 
145 
157 
175  const std::string& label);
176 
181  TsqrOrthoManagerImpl (const std::string& label);
182 
190  void setLabel (const std::string& label) {
191  if (label != label_) {
192  label_ = label;
193  }
194  }
195 
197  const std::string& getLabel () const { return label_; }
198 
207  void
208  innerProd (const MV& X, const MV& Y, mat_type& Z) const
209  {
210  MVT::MvTransMv (SCT::one(), X, Y, Z);
211  }
212 
230  void
231  norm (const MV& X, std::vector<magnitude_type>& normvec) const;
232 
242  void
243  project (MV& X,
246 
260  int normalize (MV& X, mat_ptr B);
261 
280  int
281  normalizeOutOfPlace (MV& X, MV& Q, mat_ptr B);
282 
296  int
299  mat_ptr B,
301  {
302  // "false" means we work on X in place. The second argument is
303  // not read or written in that case.
304  return projectAndNormalizeImpl (X, X, false, C, B, Q);
305  }
306 
326  int
328  MV& X_out,
330  mat_ptr B,
332  {
333  // "true" means we work on X_in out of place, writing the
334  // results into X_out.
335  return projectAndNormalizeImpl (X_in, X_out, true, C, B, Q);
336  }
337 
342  magnitude_type
343  orthonormError (const MV &X) const
344  {
345  const Scalar ONE = SCT::one();
346  const int ncols = MVT::GetNumberVecs(X);
347  mat_type XTX (ncols, ncols);
348  innerProd (X, X, XTX);
349  for (int k = 0; k < ncols; ++k) {
350  XTX(k,k) -= ONE;
351  }
352  return XTX.normFrobenius();
353  }
354 
356  magnitude_type
357  orthogError (const MV &X1,
358  const MV &X2) const
359  {
360  const int ncols_X1 = MVT::GetNumberVecs (X1);
361  const int ncols_X2 = MVT::GetNumberVecs (X2);
362  mat_type X1_T_X2 (ncols_X1, ncols_X2);
363  innerProd (X1, X2, X1_T_X2);
364  return X1_T_X2.normFrobenius();
365  }
366 
370  magnitude_type blockReorthogThreshold() const { return blockReorthogThreshold_; }
371 
374  magnitude_type relativeRankTolerance() const { return relativeRankTolerance_; }
375 
376  private:
379 
381  mutable Teuchos::RCP<const Teuchos::ParameterList> defaultParams_;
382 
384  std::string label_;
385 
387  tsqr_adaptor_type tsqrAdaptor_;
388 
398  Teuchos::RCP<MV> Q_;
399 
401  magnitude_type eps_;
402 
403 
407  bool randomizeNullSpace_;
408 
414  bool reorthogonalizeBlocks_;
415 
419  bool throwOnReorthogFault_;
420 
422  magnitude_type blockReorthogThreshold_;
423 
425  magnitude_type relativeRankTolerance_;
426 
433  bool forceNonnegativeDiagonal_;
434 
436  void
437  raiseReorthogFault (const std::vector<magnitude_type>& normsAfterFirstPass,
438  const std::vector<magnitude_type>& normsAfterSecondPass,
439  const std::vector<int>& faultIndices);
440 
450  void
451  checkProjectionDims (int& ncols_X,
452  int& num_Q_blocks,
453  int& ncols_Q_total,
454  const MV& X,
456 
467  void
468  allocateProjectionCoefficients (Teuchos::Array<mat_ptr>& C,
470  const MV& X,
471  const bool attemptToRecycle = true) const;
472 
481  int
482  projectAndNormalizeImpl (MV& X_in,
483  MV& X_out,
484  const bool outOfPlace,
486  mat_ptr B,
488 
494  void
495  rawProject (MV& X,
498 
500  void
501  rawProject (MV& X,
502  const Teuchos::RCP<const MV>& Q,
503  const mat_ptr& C) const;
504 
531  int rawNormalize (MV& X, MV& Q, mat_type& B);
532 
550  int normalizeOne (MV& X, mat_ptr B) const;
551 
579  int normalizeImpl (MV& X, MV& Q, mat_ptr B, const bool outOfPlace);
580  };
581 
582  template<class Scalar, class MV>
583  void
586  {
588  using Teuchos::parameterList;
589  using Teuchos::RCP;
590  using Teuchos::sublist;
591  typedef magnitude_type M; // abbreviation.
592 
593  RCP<const ParameterList> defaultParams = getValidParameters ();
594  // Sublist of TSQR implementation parameters; to get below.
595  RCP<ParameterList> tsqrParams;
596 
597  RCP<ParameterList> theParams;
598  if (params.is_null()) {
599  theParams = parameterList (*defaultParams);
600  } else {
601  theParams = params;
602 
603  // Don't call validateParametersAndSetDefaults(); we prefer to
604  // ignore parameters that we don't recognize, at least for now.
605  // However, we do fill in missing parameters with defaults.
606 
607  randomizeNullSpace_ =
608  theParams->get<bool> ("randomizeNullSpace",
609  defaultParams->get<bool> ("randomizeNullSpace"));
610  reorthogonalizeBlocks_ =
611  theParams->get<bool> ("reorthogonalizeBlocks",
612  defaultParams->get<bool> ("reorthogonalizeBlocks"));
613  throwOnReorthogFault_ =
614  theParams->get<bool> ("throwOnReorthogFault",
615  defaultParams->get<bool> ("throwOnReorthogFault"));
616  blockReorthogThreshold_ =
617  theParams->get<M> ("blockReorthogThreshold",
618  defaultParams->get<M> ("blockReorthogThreshold"));
619  relativeRankTolerance_ =
620  theParams->get<M> ("relativeRankTolerance",
621  defaultParams->get<M> ("relativeRankTolerance"));
622  forceNonnegativeDiagonal_ =
623  theParams->get<bool> ("forceNonnegativeDiagonal",
624  defaultParams->get<bool> ("forceNonnegativeDiagonal"));
625 
626  // Get the sublist of TSQR implementation parameters. Use the
627  // default sublist if one isn't provided.
628  if (! theParams->isSublist ("TSQR implementation")) {
629  theParams->set ("TSQR implementation",
630  defaultParams->sublist ("TSQR implementation"));
631  }
632  tsqrParams = sublist (theParams, "TSQR implementation", true);
633  }
634 
635  // Send the TSQR implementation parameters to the TSQR adaptor.
636  tsqrAdaptor_.setParameterList (tsqrParams);
637 
638  // Save the input parameter list.
639  setMyParamList (theParams);
640  }
641 
642  template<class Scalar, class MV>
645  const std::string& label) :
646  label_ (label),
647  Q_ (Teuchos::null), // Initialized on demand
648  eps_ (SCTM::eps()), // Machine precision
649  randomizeNullSpace_ (true),
650  reorthogonalizeBlocks_ (true),
651  throwOnReorthogFault_ (false),
652  blockReorthogThreshold_ (0),
653  relativeRankTolerance_ (0),
654  forceNonnegativeDiagonal_ (false)
655  {
656  setParameterList (params); // This also sets tsqrAdaptor_'s parameters.
657  }
658 
659  template<class Scalar, class MV>
661  TsqrOrthoManagerImpl (const std::string& label) :
662  label_ (label),
663  Q_ (Teuchos::null), // Initialized on demand
664  eps_ (SCTM::eps()), // Machine precision
665  randomizeNullSpace_ (true),
666  reorthogonalizeBlocks_ (true),
667  throwOnReorthogFault_ (false),
668  blockReorthogThreshold_ (0),
669  relativeRankTolerance_ (0),
670  forceNonnegativeDiagonal_ (false)
671  {
672  setParameterList (Teuchos::null); // Set default parameters.
673  }
674 
675  template<class Scalar, class MV>
676  void
678  norm (const MV& X, std::vector<magnitude_type>& normVec) const
679  {
680  const int numCols = MVT::GetNumberVecs (X);
681  // std::vector<T>::size_type is unsigned; int is signed. Mixed
682  // unsigned/signed comparisons trigger compiler warnings.
683  if (normVec.size() < static_cast<size_t>(numCols))
684  normVec.resize (numCols); // Resize normvec if necessary.
685  MVT::MvNorm (X, normVec);
686  }
687 
688  template<class Scalar, class MV>
689  void
693  {
694  int ncols_X, num_Q_blocks, ncols_Q_total;
695  checkProjectionDims (ncols_X, num_Q_blocks, ncols_Q_total, X, Q);
696  // Test for quick exit: any dimension of X is zero, or there are
697  // zero Q blocks, or the total number of columns of the Q blocks
698  // is zero.
699  if (ncols_X == 0 || num_Q_blocks == 0 || ncols_Q_total == 0)
700  return;
701 
702  // Make space for first-pass projection coefficients
703  allocateProjectionCoefficients (C, Q, X, true);
704 
705  // We only use columnNormsBefore and compute pre-projection column
706  // norms if doing block reorthogonalization.
707  std::vector<magnitude_type> columnNormsBefore (ncols_X, magnitude_type(0));
708  if (reorthogonalizeBlocks_)
709  MVT::MvNorm (X, columnNormsBefore);
710 
711  // Project (first block orthogonalization step):
712  // C := Q^* X, X := X - Q C.
713  rawProject (X, Q, C);
714 
715  // If we are doing block reorthogonalization, reorthogonalize X if
716  // necessary.
717  if (reorthogonalizeBlocks_)
718  {
719  std::vector<magnitude_type> columnNormsAfter (ncols_X, magnitude_type(0));
720  MVT::MvNorm (X, columnNormsAfter);
721 
722  // Relative block reorthogonalization threshold
723  const magnitude_type relThres = blockReorthogThreshold();
724  // Reorthogonalize X if any of its column norms decreased by a
725  // factor more than the block reorthogonalization threshold.
726  // Don't bother trying to subset the columns; that will make
727  // the columns noncontiguous and thus hinder BLAS 3
728  // optimizations.
729  bool reorthogonalize = false;
730  for (int j = 0; j < ncols_X; ++j)
731  if (columnNormsAfter[j] < relThres * columnNormsBefore[j])
732  {
733  reorthogonalize = true;
734  break;
735  }
736  if (reorthogonalize)
737  {
738  // Second-pass projection coefficients
740  allocateProjectionCoefficients (C2, Q, X, false);
741 
742  // Perform the second projection pass:
743  // C2 = Q' X, X = X - Q*C2
744  rawProject (X, Q, C2);
745  // Update the projection coefficients
746  for (int k = 0; k < num_Q_blocks; ++k)
747  *C[k] += *C2[k];
748  }
749  }
750  }
751 
752 
753 
754  template<class Scalar, class MV>
755  int
757  {
758  using Teuchos::Range1D;
759  using Teuchos::RCP;
760 
761  // MVT returns int for this, even though the "local ordinal
762  // type" of the MV may be some other type (for example,
763  // Tpetra::MultiVector<double, int32_t, int64_t, ...>).
764  const int numCols = MVT::GetNumberVecs (X);
765 
766  // This special case (for X having only one column) makes
767  // TsqrOrthoManagerImpl equivalent to Modified Gram-Schmidt
768  // orthogonalization with conditional full reorthogonalization,
769  // if all multivector inputs have only one column. It also
770  // avoids allocating Q_ scratch space and copying data when we
771  // don't need to invoke TSQR at all.
772  if (numCols == 1) {
773  return normalizeOne (X, B);
774  }
775 
776  // We use Q_ as scratch space for the normalization, since TSQR
777  // requires a scratch multivector (it can't factor in place). Q_
778  // should come from a vector space compatible with X's vector
779  // space, and Q_ should have at least as many columns as X.
780  // Otherwise, we have to reallocate. We also have to allocate
781  // (not "re-") Q_ if we haven't allocated it before. (We can't
782  // allocate Q_ until we have some X, so we need a multivector as
783  // the "prototype.")
784  //
785  // NOTE (mfh 11 Jan 2011) We only increase the number of columsn
786  // in Q_, never decrease. This is OK for typical uses of TSQR,
787  // but you might prefer different behavior in some cases.
788  //
789  // NOTE (mfh 10 Mar 2011) We should only reuse the scratch space
790  // Q_ if X and Q_ have compatible data distributions. However,
791  // Belos' current MultiVecTraits interface does not let us check
792  // for this. Thus, we can only check whether X and Q_ have the
793  // same number of rows. This will behave correctly for the common
794  // case in Belos that all multivectors with the same number of
795  // rows have the same data distribution.
796  //
797  // The specific MV implementation may do more checks than this on
798  // its own and throw an exception if X and Q_ are not compatible,
799  // but it may not. If you find that recycling the Q_ space causes
800  // troubles, you may consider modifying the code below to
801  // reallocate Q_ for every X that comes in.
802  if (Q_.is_null() ||
803  MVText::GetGlobalLength(*Q_) != MVText::GetGlobalLength(X) ||
804  numCols > MVT::GetNumberVecs (*Q_)) {
805  Q_ = MVT::Clone (X, numCols);
806  }
807 
808  // normalizeImpl() wants the second MV argument to have the same
809  // number of columns as X. To ensure this, we pass it a view of
810  // Q_ if Q_ has more columns than X. (This is possible if we
811  // previously called normalize() with a different multivector,
812  // since we never reallocate Q_ if it has more columns than
813  // necessary.)
814  if (MVT::GetNumberVecs(*Q_) == numCols) {
815  return normalizeImpl (X, *Q_, B, false);
816  } else {
817  RCP<MV> Q_view = MVT::CloneViewNonConst (*Q_, Range1D(0, numCols-1));
818  return normalizeImpl (X, *Q_view, B, false);
819  }
820  }
821 
822  template<class Scalar, class MV>
823  void
827  const MV& X,
828  const bool attemptToRecycle) const
829  {
830  const int num_Q_blocks = Q.size();
831  const int ncols_X = MVT::GetNumberVecs (X);
832  C.resize (num_Q_blocks);
833  if (attemptToRecycle)
834  {
835  for (int i = 0; i < num_Q_blocks; ++i)
836  {
837  const int ncols_Qi = MVT::GetNumberVecs (*Q[i]);
838  // Create a new C[i] if necessary, otherwise resize if
839  // necessary, otherwise fill with zeros.
840  if (C[i].is_null())
841  C[i] = rcp (new mat_type (ncols_Qi, ncols_X));
842  else
843  {
844  mat_type& Ci = *C[i];
845  if (Ci.numRows() != ncols_Qi || Ci.numCols() != ncols_X)
846  Ci.shape (ncols_Qi, ncols_X);
847  else
848  Ci.putScalar (SCT::zero());
849  }
850  }
851  }
852  else
853  {
854  for (int i = 0; i < num_Q_blocks; ++i)
855  {
856  const int ncols_Qi = MVT::GetNumberVecs (*Q[i]);
857  C[i] = rcp (new mat_type (ncols_Qi, ncols_X));
858  }
859  }
860  }
861 
862  template<class Scalar, class MV>
863  int
865  normalizeOutOfPlace (MV& X, MV& Q, mat_ptr B)
866  {
867  const int numVecs = MVT::GetNumberVecs(X);
868  if (numVecs == 0) {
869  return 0; // Nothing to do.
870  } else if (numVecs == 1) {
871  // Special case for a single column; scale and copy over.
872  using Teuchos::Range1D;
873  using Teuchos::RCP;
874  using Teuchos::rcp;
875 
876  // Normalize X in place (faster than TSQR for one column).
877  const int rank = normalizeOne (X, B);
878  // Copy results to first column of Q.
879  RCP<MV> Q_0 = MVT::CloneViewNonConst (Q, Range1D(0,0));
880  MVT::Assign (X, *Q_0);
881  return rank;
882  } else {
883  // The "true" argument to normalizeImpl() means the output
884  // vectors go into Q, and the contents of X are overwritten with
885  // invalid values.
886  return normalizeImpl (X, Q, B, true);
887  }
888  }
889 
890  template<class Scalar, class MV>
891  int
893  projectAndNormalizeImpl (MV& X_in,
894  MV& X_out, // Only written if outOfPlace==false.
895  const bool outOfPlace,
897  mat_ptr B,
899  {
900  using Teuchos::Range1D;
901  using Teuchos::RCP;
902  using Teuchos::rcp;
903 
904  if (outOfPlace) {
905  // Make sure that X_out has at least as many columns as X_in.
906  TEUCHOS_TEST_FOR_EXCEPTION(MVT::GetNumberVecs(X_out) < MVT::GetNumberVecs(X_in),
907  std::invalid_argument,
908  "Belos::TsqrOrthoManagerImpl::"
909  "projectAndNormalizeOutOfPlace(...):"
910  "X_out has " << MVT::GetNumberVecs(X_out)
911  << " columns, but X_in has "
912  << MVT::GetNumberVecs(X_in) << " columns.");
913  }
914  // Fetch dimensions of X_in and Q, and allocate space for first-
915  // and second-pass projection coefficients (C resp. C2).
916  int ncols_X, num_Q_blocks, ncols_Q_total;
917  checkProjectionDims (ncols_X, num_Q_blocks, ncols_Q_total, X_in, Q);
918 
919  // Test for quick exit: if any dimension of X is zero.
920  if (ncols_X == 0) {
921  return 0;
922  }
923  // If there are zero Q blocks or zero Q columns, just normalize!
924  if (num_Q_blocks == 0 || ncols_Q_total == 0) {
925  if (outOfPlace) {
926  return normalizeOutOfPlace (X_in, X_out, B);
927  } else {
928  return normalize (X_in, B);
929  }
930  }
931 
932  // The typical case is that the entries of C have been allocated
933  // before, so we attempt to recycle the allocations. The call
934  // below will reallocate if it cannot recycle.
935  allocateProjectionCoefficients (C, Q, X_in, true);
936 
937  // If we are doing block reorthogonalization, then compute the
938  // column norms of X before projecting for the first time. This
939  // will help us decide whether we need to reorthogonalize X.
940  std::vector<magnitude_type> normsBeforeFirstPass (ncols_X, SCTM::zero());
941  if (reorthogonalizeBlocks_) {
942  MVT::MvNorm (X_in, normsBeforeFirstPass);
943  }
944 
945  // First (Modified) Block Gram-Schmidt pass, in place in X_in.
946  rawProject (X_in, Q, C);
947 
948  // Make space for the normalization coefficients. This will
949  // either be a freshly allocated matrix (if B is null), or a view
950  // of the appropriately sized upper left submatrix of *B (if B is
951  // not null).
952  //
953  // Note that if we let the normalize() routine allocate (in the
954  // case that B is null), that storage will go away at the end of
955  // normalize(). (This is because it passes the RCP by value, not
956  // by reference.)
957  mat_ptr B_out;
958  if (B.is_null()) {
959  B_out = rcp (new mat_type (ncols_X, ncols_X));
960  } else {
961  // Make sure that B is no smaller than numCols x numCols.
962  TEUCHOS_TEST_FOR_EXCEPTION(B->numRows() < ncols_X || B->numCols() < ncols_X,
963  std::invalid_argument,
964  "normalizeOne: Input matrix B must be at "
965  "least " << ncols_X << " x " << ncols_X
966  << ", but is instead " << B->numRows()
967  << " x " << B->numCols() << ".");
968  // Create a view of the ncols_X by ncols_X upper left
969  // submatrix of *B. TSQR will write the normalization
970  // coefficients there.
971  B_out = rcp (new mat_type (Teuchos::View, *B, ncols_X, ncols_X));
972  }
973 
974  // Rank of X(_in) after first projection pass. If outOfPlace,
975  // this overwrites X_in with invalid values, and the results go in
976  // X_out. Otherwise, it's done in place in X_in.
977  const int firstPassRank = outOfPlace ?
978  normalizeOutOfPlace (X_in, X_out, B_out) :
979  normalize (X_in, B_out);
980  if (B.is_null()) {
981  // The input matrix B is null, so assign B_out to it. If B was
982  // not null on input, then B_out is a view of *B, so we don't
983  // have to do anything here. Note that SerialDenseMatrix uses
984  // raw pointers to store data and represent views, so we have to
985  // be careful about scope.
986  B = B_out;
987  }
988  int rank = firstPassRank; // Current rank of X.
989 
990  // If X was not full rank after projection and randomizeNullSpace_
991  // is true, then normalize(OutOfPlace)() replaced the null space
992  // basis of X with random vectors, and orthogonalized them against
993  // the column space basis of X. However, we still need to
994  // orthogonalize the random vectors against the Q[i], after which
995  // we will need to renormalize them.
996  //
997  // If outOfPlace, then we need to work in X_out (where
998  // normalizeOutOfPlace() wrote the normalized vectors).
999  // Otherwise, we need to work in X_in.
1000  //
1001  // Note: We don't need to keep the new projection coefficients,
1002  // since they are multiplied by the "small" part of B
1003  // corresponding to the null space of the original X.
1004  if (firstPassRank < ncols_X && randomizeNullSpace_) {
1005  const int numNullSpaceCols = ncols_X - firstPassRank;
1006  const Range1D nullSpaceIndices (firstPassRank, ncols_X - 1);
1007 
1008  // Space for projection coefficients (will be thrown away)
1009  Teuchos::Array<mat_ptr> C_null (num_Q_blocks);
1010  for (int k = 0; k < num_Q_blocks; ++k) {
1011  const int numColsQk = MVT::GetNumberVecs(*Q[k]);
1012  C_null[k] = rcp (new mat_type (numColsQk, numNullSpaceCols));
1013  }
1014  // Space for normalization coefficients (will be thrown away).
1015  RCP<mat_type> B_null (new mat_type (numNullSpaceCols, numNullSpaceCols));
1016 
1017  int randomVectorsRank;
1018  if (outOfPlace) {
1019  // View of the null space basis columns of X.
1020  // normalizeOutOfPlace() wrote them into X_out.
1021  RCP<MV> X_out_null = MVT::CloneViewNonConst (X_out, nullSpaceIndices);
1022  // Use X_in for scratch space. Copy X_out_null into the
1023  // last few columns of X_in (X_in_null) and do projections
1024  // in there. (This saves us a copy wen we renormalize
1025  // (out of place) back into X_out.)
1026  RCP<MV> X_in_null = MVT::CloneViewNonConst (X_in, nullSpaceIndices);
1027  MVT::Assign (*X_out_null, *X_in_null);
1028  // Project the new random vectors against the Q blocks, and
1029  // renormalize the result into X_out_null.
1030  rawProject (*X_in_null, Q, C_null);
1031  randomVectorsRank = normalizeOutOfPlace (*X_in_null, *X_out_null, B_null);
1032  } else {
1033  // View of the null space columns of X.
1034  // They live in X_in.
1035  RCP<MV> X_null = MVT::CloneViewNonConst (X_in, nullSpaceIndices);
1036  // Project the new random vectors against the Q blocks,
1037  // and renormalize the result (in place).
1038  rawProject (*X_null, Q, C_null);
1039  randomVectorsRank = normalize (*X_null, B_null);
1040  }
1041  // While unusual, it is still possible for the random data not
1042  // to be full rank after projection and normalization. In that
1043  // case, we could try another set of random data and recurse as
1044  // necessary, but instead for now we just raise an exception.
1045  TEUCHOS_TEST_FOR_EXCEPTION(randomVectorsRank != numNullSpaceCols,
1046  TsqrOrthoError,
1047  "Belos::TsqrOrthoManagerImpl::projectAndNormalize"
1048  "OutOfPlace(): After projecting and normalizing the "
1049  "random vectors (used to replace the null space "
1050  "basis vectors from normalizing X), they have rank "
1051  << randomVectorsRank << ", but should have full "
1052  "rank " << numNullSpaceCols << ".");
1053  }
1054 
1055  // Whether or not X_in was full rank after projection, we still
1056  // might want to reorthogonalize against Q.
1057  if (reorthogonalizeBlocks_) {
1058  // We are only interested in the column space basis of X
1059  // resp. X_out.
1060  std::vector<magnitude_type>
1061  normsAfterFirstPass (firstPassRank, SCTM::zero());
1062  std::vector<magnitude_type>
1063  normsAfterSecondPass (firstPassRank, SCTM::zero());
1064 
1065  // Compute post-first-pass (pre-normalization) norms. We could
1066  // have done that using MVT::MvNorm() on X_in after projecting,
1067  // but before the first normalization. However, that operation
1068  // may be expensive. It is also unnecessary: after calling
1069  // normalize(), the 2-norm of B(:,j) is the 2-norm of X_in(:,j)
1070  // before normalization, in exact arithmetic.
1071  //
1072  // NOTE (mfh 06 Nov 2010) This is one way that combining
1073  // projection and normalization into a single kernel --
1074  // projectAndNormalize() -- pays off. In project(), we have to
1075  // compute column norms of X before and after projection. Here,
1076  // we get them for free from the normalization coefficients.
1078  for (int j = 0; j < firstPassRank; ++j) {
1079  const Scalar* const B_j = &(*B_out)(0,j);
1080  // Teuchos::BLAS::NRM2 returns a magnitude_type result on
1081  // Scalar inputs.
1082  normsAfterFirstPass[j] = blas.NRM2 (firstPassRank, B_j, 1);
1083  }
1084  // Test whether any of the norms dropped below the
1085  // reorthogonalization threshold.
1086  bool reorthogonalize = false;
1087  for (int j = 0; j < firstPassRank; ++j) {
1088  // If any column's norm decreased too much, mark this block
1089  // for reorthogonalization. Note that this test will _not_
1090  // activate reorthogonalization if a column's norm before the
1091  // first project-and-normalize step was zero. It _will_
1092  // activate reorthogonalization if the column's norm before
1093  // was not zero, but is zero now.
1094  const magnitude_type curThreshold =
1095  blockReorthogThreshold() * normsBeforeFirstPass[j];
1096  if (normsAfterFirstPass[j] < curThreshold) {
1097  reorthogonalize = true;
1098  break;
1099  }
1100  }
1101  // Perform another Block Gram-Schmidt pass if necessary. "Twice
1102  // is enough" (Kahan's theorem) for a Krylov method, unless
1103  // (using Stewart's term) there is an "orthogonalization fault"
1104  // (indicated by reorthogFault).
1105  //
1106  // NOTE (mfh 07 Nov 2010) For now, we include the entire block
1107  // of X, including possible random data (that was already
1108  // projected and normalized above). It might make more sense
1109  // just to process the first firstPassRank columns of X.
1110  // However, the resulting reorthogonalization should still be
1111  // correct regardless.
1112  bool reorthogFault = false;
1113  // Indices of X at which there was an orthogonalization fault.
1114  std::vector<int> faultIndices;
1115  if (reorthogonalize) {
1116  using Teuchos::Copy;
1117  using Teuchos::NO_TRANS;
1118 
1119  // If we're using out-of-place normalization, copy X_out
1120  // (results of first project and normalize pass) back into
1121  // X_in, for the second project and normalize pass.
1122  if (outOfPlace)
1123  MVT::Assign (X_out, X_in);
1124 
1125  // C2 is only used internally, so we know that we are
1126  // allocating fresh and not recycling allocations. Stating
1127  // this lets us save time checking dimensions.
1129  allocateProjectionCoefficients (C2, Q, X_in, false);
1130 
1131  // Block Gram-Schmidt (again). Delay updating the block
1132  // coefficients until we have the new normalization
1133  // coefficients, which we need in order to do the update.
1134  rawProject (X_in, Q, C2);
1135 
1136  // Coefficients for (re)normalization of X_in.
1137  RCP<mat_type> B2 (new mat_type (ncols_X, ncols_X));
1138 
1139  // Normalize X_in (into X_out, if working out of place).
1140  const int secondPassRank = outOfPlace ?
1141  normalizeOutOfPlace (X_in, X_out, B2) :
1142  normalize (X_in, B2);
1143  rank = secondPassRank; // Current rank of X
1144 
1145  // Update normalization coefficients. We begin with copying
1146  // B_out, since the BLAS' _GEMM routine doesn't let us alias
1147  // its input and output arguments.
1148  mat_type B_copy (Copy, *B_out, B_out->numRows(), B_out->numCols());
1149  // B_out := B2 * B_out (where input B_out is in B_copy).
1150  const int err = B_out->multiply (NO_TRANS, NO_TRANS, SCT::one(),
1151  *B2, B_copy, SCT::zero());
1152  TEUCHOS_TEST_FOR_EXCEPTION(err != 0, std::logic_error,
1153  "Teuchos::SerialDenseMatrix::multiply "
1154  "returned err = " << err << " != 0");
1155  // Update the block coefficients from the projection step. We
1156  // use B_copy for this (a copy of B_out, the first-pass
1157  // normalization coefficients).
1158  for (int k = 0; k < num_Q_blocks; ++k) {
1159  mat_type C_k_copy (Copy, *C[k], C[k]->numRows(), C[k]->numCols());
1160 
1161  // C[k] := C2[k]*B_copy + C[k].
1162  const int err2 = C[k]->multiply (NO_TRANS, NO_TRANS, SCT::one(),
1163  *C2[k], B_copy, SCT::one());
1164  TEUCHOS_TEST_FOR_EXCEPTION(err2 != 0, std::logic_error,
1165  "Teuchos::SerialDenseMatrix::multiply "
1166  "returned err = " << err << " != 0");
1167  }
1168  // Compute post-second-pass (pre-normalization) norms, using
1169  // B2 (the coefficients from the second normalization step) in
1170  // the same way as with B_out before.
1171  for (int j = 0; j < rank; ++j) {
1172  const Scalar* const B2_j = &(*B2)(0,j);
1173  normsAfterSecondPass[j] = blas.NRM2 (rank, B2_j, 1);
1174  }
1175  // Test whether any of the norms dropped below the
1176  // reorthogonalization threshold. If so, it's an
1177  // orthogonalization fault, which requires expensive recovery.
1178  reorthogFault = false;
1179  for (int j = 0; j < rank; ++j) {
1180  const magnitude_type relativeLowerBound =
1181  blockReorthogThreshold() * normsAfterFirstPass[j];
1182  if (normsAfterSecondPass[j] < relativeLowerBound) {
1183  reorthogFault = true;
1184  faultIndices.push_back (j);
1185  }
1186  }
1187  } // if (reorthogonalize) // reorthogonalization pass
1188 
1189  if (reorthogFault) {
1190  if (throwOnReorthogFault_) {
1191  raiseReorthogFault (normsAfterFirstPass,
1192  normsAfterSecondPass,
1193  faultIndices);
1194  } else {
1195  // NOTE (mfh 19 Jan 2011) We could handle the fault here by
1196  // slowly reorthogonalizing, one vector at a time, the
1197  // offending vectors of X. However, we choose not to
1198  // implement this for now. If it becomes a problem, let us
1199  // know and we will prioritize implementing this.
1200  TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error,
1201  "TsqrOrthoManagerImpl has not yet implemented"
1202  " recovery from an orthogonalization fault.");
1203  }
1204  }
1205  } // if (reorthogonalizeBlocks_)
1206  return rank;
1207  }
1208 
1209 
1210  template<class Scalar, class MV>
1211  void
1212  TsqrOrthoManagerImpl<Scalar, MV>::
1213  raiseReorthogFault (const std::vector<magnitude_type>& normsAfterFirstPass,
1214  const std::vector<magnitude_type>& normsAfterSecondPass,
1215  const std::vector<int>& faultIndices)
1216  {
1217  using std::endl;
1218  typedef std::vector<int>::size_type size_type;
1219  std::ostringstream os;
1220 
1221  os << "Orthogonalization fault at the following column(s) of X:" << endl;
1222  os << "Column\tNorm decrease factor" << endl;
1223  for (size_type k = 0; k < faultIndices.size(); ++k)
1224  {
1225  const int index = faultIndices[k];
1226  const magnitude_type decreaseFactor =
1227  normsAfterSecondPass[index] / normsAfterFirstPass[index];
1228  os << index << "\t" << decreaseFactor << endl;
1229  }
1230  throw TsqrOrthoFault (os.str());
1231  }
1232 
1233  template<class Scalar, class MV>
1236  {
1237  using Teuchos::ParameterList;
1238  using Teuchos::parameterList;
1239  using Teuchos::RCP;
1240 
1241  if (defaultParams_.is_null()) {
1242  RCP<ParameterList> params = parameterList ("TsqrOrthoManagerImpl");
1243  //
1244  // TSQR parameters (set as a sublist).
1245  //
1246  params->set ("TSQR implementation", *(tsqrAdaptor_.getValidParameters()),
1247  "TSQR implementation parameters.");
1248  //
1249  // Orthogonalization parameters
1250  //
1251  const bool defaultRandomizeNullSpace = true;
1252  params->set ("randomizeNullSpace", defaultRandomizeNullSpace,
1253  "Whether to fill in null space vectors with random data.");
1254 
1255  const bool defaultReorthogonalizeBlocks = true;
1256  params->set ("reorthogonalizeBlocks", defaultReorthogonalizeBlocks,
1257  "Whether to do block reorthogonalization as necessary.");
1258 
1259  // This parameter corresponds to the "blk_tol_" parameter in
1260  // Belos' DGKSOrthoManager. We choose the same default value.
1261  const magnitude_type defaultBlockReorthogThreshold =
1262  magnitude_type(10) * SCTM::squareroot (SCTM::eps());
1263  params->set ("blockReorthogThreshold", defaultBlockReorthogThreshold,
1264  "If reorthogonalizeBlocks==true, and if the norm of "
1265  "any column within a block decreases by this much or "
1266  "more after orthogonalization, we reorthogonalize.");
1267 
1268  // This parameter corresponds to the "sing_tol_" parameter in
1269  // Belos' DGKSOrthoManager. We choose the same default value.
1270  const magnitude_type defaultRelativeRankTolerance =
1271  Teuchos::as<magnitude_type>(10) * SCTM::eps();
1272 
1273  // If the relative rank tolerance is zero, then we will always
1274  // declare blocks to be numerically full rank, as long as no
1275  // singular values are zero.
1276  params->set ("relativeRankTolerance", defaultRelativeRankTolerance,
1277  "Relative tolerance to determine the numerical rank of a "
1278  "block when normalizing.");
1279 
1280  // See Stewart's 2008 paper on block Gram-Schmidt for a definition
1281  // of "orthogonalization fault."
1282  const bool defaultThrowOnReorthogFault = true;
1283  params->set ("throwOnReorthogFault", defaultThrowOnReorthogFault,
1284  "Whether to throw an exception if an orthogonalization "
1285  "fault occurs. This only matters if reorthogonalization "
1286  "is enabled (reorthogonalizeBlocks==true).");
1287 
1288  const bool defaultForceNonnegativeDiagonal = false;
1289  params->set ("forceNonnegativeDiagonal", defaultForceNonnegativeDiagonal,
1290  "Whether to force the R factor produced by the normalization "
1291  "step to have a nonnegative diagonal.");
1292 
1293  defaultParams_ = params;
1294  }
1295  return defaultParams_;
1296  }
1297 
1298  template<class Scalar, class MV>
1301  {
1302  using Teuchos::ParameterList;
1303  using Teuchos::RCP;
1304  using Teuchos::rcp;
1305 
1306  RCP<const ParameterList> defaultParams = getValidParameters();
1307  // Start with a clone of the default parameters.
1308  RCP<ParameterList> params = rcp (new ParameterList (*defaultParams));
1309 
1310  // Disable reorthogonalization and randomization of the null
1311  // space basis. Reorthogonalization tolerances don't matter,
1312  // since we aren't reorthogonalizing blocks in the fast
1313  // settings. We can leave the default values. Also,
1314  // (re)orthogonalization faults may only occur with
1315  // reorthogonalization, so we don't have to worry about the
1316  // "throwOnReorthogFault" setting.
1317  const bool randomizeNullSpace = false;
1318  params->set ("randomizeNullSpace", randomizeNullSpace);
1319  const bool reorthogonalizeBlocks = false;
1320  params->set ("reorthogonalizeBlocks", reorthogonalizeBlocks);
1321 
1322  return params;
1323  }
1324 
1325  template<class Scalar, class MV>
1326  int
1328  rawNormalize (MV& X,
1329  MV& Q,
1331  {
1332  int rank;
1333  try {
1334  // This call only computes the QR factorization X = Q B.
1335  // It doesn't compute the rank of X. That comes from
1336  // revealRank() below.
1337  tsqrAdaptor_.factorExplicit (X, Q, B, forceNonnegativeDiagonal_);
1338  // This call will only modify *B if *B on input is not of full
1339  // numerical rank.
1340  rank = tsqrAdaptor_.revealRank (Q, B, relativeRankTolerance_);
1341  } catch (std::exception& e) {
1342  throw TsqrOrthoError (e.what()); // Toss the exception up the chain.
1343  }
1344  return rank;
1345  }
1346 
1347  template<class Scalar, class MV>
1348  int
1349  TsqrOrthoManagerImpl<Scalar, MV>::
1350  normalizeOne (MV& X,
1352  {
1353  // Make space for the normalization coefficient. This will either
1354  // be a freshly allocated matrix (if B is null), or a view of the
1355  // 1x1 upper left submatrix of *B (if B is not null).
1356  mat_ptr B_out;
1357  if (B.is_null()) {
1358  B_out = rcp (new mat_type (1, 1));
1359  } else {
1360  const int numRows = B->numRows();
1361  const int numCols = B->numCols();
1362  TEUCHOS_TEST_FOR_EXCEPTION(numRows < 1 || numCols < 1,
1363  std::invalid_argument,
1364  "normalizeOne: Input matrix B must be at "
1365  "least 1 x 1, but is instead " << numRows
1366  << " x " << numCols << ".");
1367  // Create a view of the 1x1 upper left submatrix of *B.
1368  B_out = rcp (new mat_type (Teuchos::View, *B, 1, 1));
1369  }
1370 
1371  // Compute the norm of X, and write the result to B_out.
1372  std::vector<magnitude_type> theNorm (1, SCTM::zero());
1373  MVT::MvNorm (X, theNorm);
1374  (*B_out)(0,0) = theNorm[0];
1375 
1376  if (B.is_null()) {
1377  // The input matrix B is null, so assign B_out to it. If B was
1378  // not null on input, then B_out is a view of *B, so we don't
1379  // have to do anything here. Note that SerialDenseMatrix uses
1380  // raw pointers to store data and represent views, so we have to
1381  // be careful about scope.
1382  B = B_out;
1383  }
1384 
1385  // Scale X by its norm, if its norm is zero. Otherwise, do the
1386  // right thing based on whether the user wants us to fill the null
1387  // space with random vectors.
1388  if (theNorm[0] == SCTM::zero()) {
1389  // Make a view of the first column of Q, fill it with random
1390  // data, and normalize it. Throw away the resulting norm.
1391  if (randomizeNullSpace_) {
1392  MVT::MvRandom(X);
1393  MVT::MvNorm (X, theNorm);
1394  if (theNorm[0] == SCTM::zero()) {
1395  // It is possible that a random vector could have all zero
1396  // entries, but unlikely. We could try again, but it's also
1397  // possible that multiple tries could result in zero
1398  // vectors. We choose instead to give up.
1399  throw TsqrOrthoError("normalizeOne: a supposedly random "
1400  "vector has norm zero!");
1401  } else {
1402  // NOTE (mfh 09 Nov 2010) I'm assuming that dividing a
1403  // Scalar by a magnitude_type is defined and that it results
1404  // in a Scalar.
1405  const Scalar alpha = SCT::one() / theNorm[0];
1406  MVT::MvScale (X, alpha);
1407  }
1408  }
1409  return 0; // The rank of the matrix (actually just one vector) X.
1410  } else {
1411  // NOTE (mfh 09 Nov 2010) I'm assuming that dividing a Scalar by
1412  // a magnitude_type is defined and that it results in a Scalar.
1413  const Scalar alpha = SCT::one() / theNorm[0];
1414  MVT::MvScale (X, alpha);
1415  return 1; // The rank of the matrix (actually just one vector) X.
1416  }
1417  }
1418 
1419 
1420  template<class Scalar, class MV>
1421  void
1422  TsqrOrthoManagerImpl<Scalar, MV>::
1423  rawProject (MV& X,
1426  {
1427  // "Modified Gram-Schmidt" version of Block Gram-Schmidt.
1428  const int num_Q_blocks = Q.size();
1429  for (int i = 0; i < num_Q_blocks; ++i)
1430  {
1431  // TEUCHOS_TEST_FOR_EXCEPTION(C[i].is_null(), std::logic_error,
1432  // "TsqrOrthoManagerImpl::rawProject(): C["
1433  // << i << "] is null");
1434  // TEUCHOS_TEST_FOR_EXCEPTION(Q[i].is_null(), std::logic_error,
1435  // "TsqrOrthoManagerImpl::rawProject(): Q["
1436  // << i << "] is null");
1437  mat_type& Ci = *C[i];
1438  const MV& Qi = *Q[i];
1439  innerProd (Qi, X, Ci);
1440  MVT::MvTimesMatAddMv (-SCT::one(), Qi, Ci, SCT::one(), X);
1441  }
1442  }
1443 
1444 
1445  template<class Scalar, class MV>
1446  void
1447  TsqrOrthoManagerImpl<Scalar, MV>::
1448  rawProject (MV& X,
1449  const Teuchos::RCP<const MV>& Q,
1451  {
1452  // Block Gram-Schmidt
1453  innerProd (*Q, X, *C);
1454  MVT::MvTimesMatAddMv (-SCT::one(), *Q, *C, SCT::one(), X);
1455  }
1456 
1457  template<class Scalar, class MV>
1458  int
1459  TsqrOrthoManagerImpl<Scalar, MV>::
1460  normalizeImpl (MV& X,
1461  MV& Q,
1463  const bool outOfPlace)
1464  {
1465  using Teuchos::Range1D;
1466  using Teuchos::RCP;
1467  using Teuchos::rcp;
1468  using Teuchos::ScalarTraits;
1469  using Teuchos::tuple;
1470  using std::cerr;
1471  using std::endl;
1472  // Don't set this to true unless you want lots of debugging
1473  // messages written to stderr on every MPI process.
1474  const bool extraDebug = false;
1475 
1476  const int numCols = MVT::GetNumberVecs (X);
1477  if (numCols == 0) {
1478  return 0; // Fast exit for an empty input matrix.
1479  }
1480 
1481  // We allow Q to have more columns than X. In that case, we only
1482  // touch the first numCols columns of Q.
1483  TEUCHOS_TEST_FOR_EXCEPTION(MVT::GetNumberVecs(Q) < numCols,
1484  std::invalid_argument,
1485  "TsqrOrthoManagerImpl::normalizeImpl(X,Q,B): Q has "
1486  << MVT::GetNumberVecs(Q) << " columns. This is too "
1487  "few, since X has " << numCols << " columns.");
1488  // TSQR wants a Q with the same number of columns as X, so have it
1489  // work on a nonconstant view of Q with the same number of columns
1490  // as X.
1491  RCP<MV> Q_view = MVT::CloneViewNonConst (Q, Range1D(0, numCols-1));
1492 
1493  // Make space for the normalization coefficients. This will
1494  // either be a freshly allocated matrix (if B is null), or a view
1495  // of the appropriately sized upper left submatrix of *B (if B is
1496  // not null).
1497  mat_ptr B_out;
1498  if (B.is_null()) {
1499  B_out = rcp (new mat_type (numCols, numCols));
1500  } else {
1501  // Make sure that B is no smaller than numCols x numCols.
1502  TEUCHOS_TEST_FOR_EXCEPTION(B->numRows() < numCols || B->numCols() < numCols,
1503  std::invalid_argument,
1504  "normalizeOne: Input matrix B must be at "
1505  "least " << numCols << " x " << numCols
1506  << ", but is instead " << B->numRows()
1507  << " x " << B->numCols() << ".");
1508  // Create a view of the numCols x numCols upper left submatrix
1509  // of *B. TSQR will write the normalization coefficients there.
1510  B_out = rcp (new mat_type (Teuchos::View, *B, numCols, numCols));
1511  }
1512 
1513  if (extraDebug) {
1514  std::vector<magnitude_type> norms (numCols);
1515  MVT::MvNorm (X, norms);
1516  cerr << "Column norms of X before orthogonalization: ";
1517  typedef typename std::vector<magnitude_type>::const_iterator iter_type;
1518  for (iter_type iter = norms.begin(); iter != norms.end(); ++iter) {
1519  cerr << *iter;
1520  if (iter+1 != norms.end())
1521  cerr << ", ";
1522  }
1523  }
1524 
1525  // Compute rank-revealing decomposition (in this case, TSQR of X
1526  // followed by SVD of the R factor and appropriate updating of the
1527  // resulting Q factor) of X. X is modified in place and filled
1528  // with garbage, and Q_view contains the resulting explicit Q
1529  // factor. Later, we will copy this back into X.
1530  //
1531  // The matrix *B_out will only be upper triangular if X is of full
1532  // numerical rank. Otherwise, the entries below the diagonal may
1533  // be filled in as well.
1534  const int rank = rawNormalize (X, *Q_view, *B_out);
1535  if (B.is_null()) {
1536  // The input matrix B is null, so assign B_out to it. If B was
1537  // not null on input, then B_out is a view of *B, so we don't
1538  // have to do anything here. Note that SerialDenseMatrix uses
1539  // raw pointers to store data and represent views, so we have to
1540  // be careful about scope.
1541  B = B_out;
1542  }
1543 
1544  if (extraDebug) {
1545  std::vector<magnitude_type> norms (numCols);
1546  MVT::MvNorm (*Q_view, norms);
1547  cerr << "Column norms of Q_view after orthogonalization: ";
1548  for (typename std::vector<magnitude_type>::const_iterator iter = norms.begin();
1549  iter != norms.end(); ++iter) {
1550  cerr << *iter;
1551  if (iter+1 != norms.end())
1552  cerr << ", ";
1553  }
1554  }
1555  TEUCHOS_TEST_FOR_EXCEPTION(rank < 0 || rank > numCols, std::logic_error,
1556  "Belos::TsqrOrthoManagerImpl::normalizeImpl: "
1557  "rawNormalize() returned rank = " << rank << " for a "
1558  "matrix X with " << numCols << " columns. Please report"
1559  " this bug to the Belos developers.");
1560  if (extraDebug && rank == 0) {
1561  // Sanity check: ensure that the columns of X are sufficiently
1562  // small for X to be reported as rank zero.
1563  const mat_type& B_ref = *B;
1564  std::vector<magnitude_type> norms (B_ref.numCols());
1565  for (typename mat_type::ordinalType j = 0; j < B_ref.numCols(); ++j) {
1566  typedef typename mat_type::scalarType mat_scalar_type;
1567  mat_scalar_type sumOfSquares = ScalarTraits<mat_scalar_type>::zero();
1568  for (typename mat_type::ordinalType i = 0; i <= j; ++i) {
1569  const mat_scalar_type B_ij =
1570  ScalarTraits<mat_scalar_type>::magnitude (B_ref(i,j));
1571  sumOfSquares += B_ij*B_ij;
1572  }
1573  norms[j] = ScalarTraits<mat_scalar_type>::squareroot (sumOfSquares);
1574  }
1575  using std::cerr;
1576  using std::endl;
1577  cerr << "Norms of columns of B after orthogonalization: ";
1578  for (typename mat_type::ordinalType j = 0; j < B_ref.numCols(); ++j) {
1579  cerr << norms[j];
1580  if (j != B_ref.numCols() - 1)
1581  cerr << ", ";
1582  }
1583  cerr << endl;
1584  }
1585 
1586  // If X is full rank or we don't want to replace its null space
1587  // basis with random vectors, then we're done.
1588  if (rank == numCols || ! randomizeNullSpace_) {
1589  // If we're supposed to be working in place in X, copy the
1590  // results back from Q_view into X.
1591  if (! outOfPlace) {
1592  MVT::Assign (*Q_view, X);
1593  }
1594  return rank;
1595  }
1596 
1597  if (randomizeNullSpace_ && rank < numCols) {
1598  // X wasn't full rank. Replace the null space basis of X (in
1599  // the last numCols-rank columns of Q_view) with random data,
1600  // project it against the first rank columns of Q_view, and
1601  // normalize.
1602  //
1603  // Number of columns to fill with random data.
1604  const int nullSpaceNumCols = numCols - rank;
1605  // Inclusive range of indices of columns of X to fill with
1606  // random data.
1607  Range1D nullSpaceIndices (rank, numCols-1);
1608 
1609  // rawNormalize() wrote the null space basis vectors into
1610  // Q_view. We continue to work in place in Q_view by writing
1611  // the random data there and (if there is a nontrival column
1612  // space) projecting in place against the column space basis
1613  // vectors (also in Q_view).
1614  RCP<MV> Q_null = MVT::CloneViewNonConst (*Q_view, nullSpaceIndices);
1615  // Replace the null space basis with random data.
1616  MVT::MvRandom (*Q_null);
1617 
1618  // Make sure that the "random" data isn't all zeros. This is
1619  // statistically nearly impossible, but we test for debugging
1620  // purposes.
1621  {
1622  std::vector<magnitude_type> norms (MVT::GetNumberVecs(*Q_null));
1623  MVT::MvNorm (*Q_null, norms);
1624 
1625  bool anyZero = false;
1626  typedef typename std::vector<magnitude_type>::const_iterator iter_type;
1627  for (iter_type it = norms.begin(); it != norms.end(); ++it) {
1628  if (*it == SCTM::zero()) {
1629  anyZero = true;
1630  }
1631  }
1632  if (anyZero) {
1633  std::ostringstream os;
1634  os << "TsqrOrthoManagerImpl::normalizeImpl: "
1635  "We are being asked to randomize the null space, for a matrix "
1636  "with " << numCols << " columns and reported column rank "
1637  << rank << ". The inclusive range of columns to fill with "
1638  "random data is [" << nullSpaceIndices.lbound() << ","
1639  << nullSpaceIndices.ubound() << "]. After filling the null "
1640  "space vectors with random numbers, at least one of the vectors"
1641  " has norm zero. Here are the norms of all the null space "
1642  "vectors: [";
1643  for (iter_type it = norms.begin(); it != norms.end(); ++it) {
1644  os << *it;
1645  if (it+1 != norms.end())
1646  os << ", ";
1647  }
1648  os << "].) There is a tiny probability that this could happen "
1649  "randomly, but it is likely a bug. Please report it to the "
1650  "Belos developers, especially if you are able to reproduce the "
1651  "behavior.";
1652  TEUCHOS_TEST_FOR_EXCEPTION(anyZero, TsqrOrthoError, os.str());
1653  }
1654  }
1655 
1656  if (rank > 0) {
1657  // Project the random data against the column space basis of
1658  // X, using a simple block projection ("Block Classical
1659  // Gram-Schmidt"). This is accurate because we've already
1660  // orthogonalized the column space basis of X nearly to
1661  // machine precision via a QR factorization (TSQR) with
1662  // accuracy comparable to Householder QR.
1663  RCP<const MV> Q_col = MVT::CloneView (*Q_view, Range1D(0, rank-1));
1664 
1665  // Temporary storage for projection coefficients. We don't
1666  // need to keep them, since they represent the null space
1667  // basis (for which the coefficients are logically zero).
1668  mat_ptr C_null (new mat_type (rank, nullSpaceNumCols));
1669  rawProject (*Q_null, Q_col, C_null);
1670  }
1671  // Normalize the projected random vectors, so that they are
1672  // mutually orthogonal (as well as orthogonal to the column
1673  // space basis of X). We use X for the output of the
1674  // normalization: for out-of-place normalization (outOfPlace ==
1675  // true), X is overwritten with "invalid values" anyway, and for
1676  // in-place normalization (outOfPlace == false), we want the
1677  // result to be in X anyway.
1678  RCP<MV> X_null = MVT::CloneViewNonConst (X, nullSpaceIndices);
1679  // Normalization coefficients for projected random vectors.
1680  // Will be thrown away.
1681  mat_type B_null (nullSpaceNumCols, nullSpaceNumCols);
1682  // Write the normalized vectors to X_null (in X).
1683  const int nullSpaceBasisRank = rawNormalize (*Q_null, *X_null, B_null);
1684 
1685  // It's possible, but unlikely, that X_null doesn't have full
1686  // rank (after the projection step). We could recursively fill
1687  // in more random vectors until we finally get a full rank
1688  // matrix, but instead we just throw an exception.
1689  //
1690  // NOTE (mfh 08 Nov 2010) Perhaps we should deal with this case
1691  // more elegantly. Recursion might be one way to solve it, but
1692  // be sure to check that the recursion will terminate. We could
1693  // do this by supplying an additional argument to rawNormalize,
1694  // which is the null space basis rank from the previous
1695  // iteration. The rank has to decrease each time, or the
1696  // recursion may go on forever.
1697  if (nullSpaceBasisRank < nullSpaceNumCols) {
1698  std::vector<magnitude_type> norms (MVT::GetNumberVecs(*X_null));
1699  MVT::MvNorm (*X_null, norms);
1700  std::ostringstream os;
1701  os << "TsqrOrthoManagerImpl::normalizeImpl: "
1702  << "We are being asked to randomize the null space, "
1703  << "for a matrix with " << numCols << " columns and "
1704  << "column rank " << rank << ". After projecting and "
1705  << "normalizing the generated random vectors, they "
1706  << "only have rank " << nullSpaceBasisRank << ". They"
1707  << " should have full rank " << nullSpaceNumCols
1708  << ". (The inclusive range of columns to fill with "
1709  << "random data is [" << nullSpaceIndices.lbound()
1710  << "," << nullSpaceIndices.ubound() << "]. The "
1711  << "column norms of the resulting Q factor are: [";
1712  for (typename std::vector<magnitude_type>::size_type k = 0;
1713  k < norms.size(); ++k) {
1714  os << norms[k];
1715  if (k != norms.size()-1) {
1716  os << ", ";
1717  }
1718  }
1719  os << "].) There is a tiny probability that this could "
1720  << "happen randomly, but it is likely a bug. Please "
1721  << "report it to the Belos developers, especially if "
1722  << "you are able to reproduce the behavior.";
1723 
1724  TEUCHOS_TEST_FOR_EXCEPTION(nullSpaceBasisRank < nullSpaceNumCols,
1725  TsqrOrthoError, os.str());
1726  }
1727  // If we're normalizing out of place, copy the X_null
1728  // vectors back into Q_null; the Q_col vectors are already
1729  // where they are supposed to be in that case.
1730  //
1731  // If we're normalizing in place, leave X_null alone (it's
1732  // already where it needs to be, in X), but copy Q_col back
1733  // into the first rank columns of X.
1734  if (outOfPlace) {
1735  MVT::Assign (*X_null, *Q_null);
1736  } else if (rank > 0) {
1737  // MVT::Assign() doesn't accept empty ranges of columns.
1738  RCP<const MV> Q_col = MVT::CloneView (*Q_view, Range1D(0, rank-1));
1739  RCP<MV> X_col = MVT::CloneViewNonConst (X, Range1D(0, rank-1));
1740  MVT::Assign (*Q_col, *X_col);
1741  }
1742  }
1743  return rank;
1744  }
1745 
1746 
1747  template<class Scalar, class MV>
1748  void
1749  TsqrOrthoManagerImpl<Scalar, MV>::
1750  checkProjectionDims (int& ncols_X,
1751  int& num_Q_blocks,
1752  int& ncols_Q_total,
1753  const MV& X,
1755  {
1756  // First assign to temporary values, so the function won't
1757  // commit any externally visible side effects unless it will
1758  // return normally (without throwing an exception). (I'm being
1759  // cautious; MVT::GetNumberVecs() probably shouldn't have any
1760  // externally visible side effects, unless it is logging to a
1761  // file or something.)
1762  int the_ncols_X, the_num_Q_blocks, the_ncols_Q_total;
1763  the_num_Q_blocks = Q.size();
1764  the_ncols_X = MVT::GetNumberVecs (X);
1765 
1766  // Compute the total number of columns of all the Q[i] blocks.
1767  the_ncols_Q_total = 0;
1768  // You should be angry if your compiler doesn't support type
1769  // inference ("auto"). That's why I need this awful typedef.
1770  using Teuchos::ArrayView;
1771  using Teuchos::RCP;
1772  typedef typename ArrayView<RCP<const MV> >::const_iterator iter_type;
1773  for (iter_type it = Q.begin(); it != Q.end(); ++it) {
1774  const MV& Qi = **it;
1775  the_ncols_Q_total += MVT::GetNumberVecs (Qi);
1776  }
1777 
1778  // Commit temporary values to the output arguments.
1779  ncols_X = the_ncols_X;
1780  num_Q_blocks = the_num_Q_blocks;
1781  ncols_Q_total = the_ncols_Q_total;
1782  }
1783 
1784 } // namespace Anasazi
1785 
1786 #endif // __AnasaziTsqrOrthoManagerImpl_hpp
An extension of the MultiVecTraits class that adds a new vector length method.This traits class provi...
bool is_null(const boost::shared_ptr< T > &p)
TSQR-based OrthoManager subclass implementation.
Declaration of basic traits for the multivector type.
T & get(const std::string &name, T def_value)
int projectAndNormalize(MV &X, Teuchos::Array< mat_ptr > C, mat_ptr B, Teuchos::ArrayView< Teuchos::RCP< const MV > > Q)
Project X against Q and normalize X.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Teuchos::SerialDenseMatrix< int, Scalar > mat_type
magnitude_type orthonormError(const MV &X) const
Return .
void innerProd(const MV &X, const MV &Y, mat_type &Z) const
Euclidean inner product.
void norm(const MV &X, std::vector< magnitude_type > &normvec) const
ScalarTraits< ScalarType >::magnitudeType normFrobenius() const
void setParameterList(const Teuchos::RCP< Teuchos::ParameterList > &params)
Set parameters from the given parameter list.
TsqrOrthoManagerImpl(const Teuchos::RCP< Teuchos::ParameterList > &params, const std::string &label)
Constructor (that sets user-specified parameters).
TsqrOrthoManager(Impl) error.
static void MvTransMv(const ScalarType alpha, const MV &A, const MV &mv, Teuchos::SerialDenseMatrix< int, ScalarType > &B)
Compute a dense matrix B through the matrix-matrix multiply .
void setLabel(const std::string &label)
Set the label for timers.
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
Templated virtual class for providing orthogonalization/orthonormalization methods.
Traits class which defines basic operations on multivectors.
const std::string & getLabel() const
Get the label for timers (if timers are enabled).
Teuchos::RCP< const Teuchos::ParameterList > getFastParameters()
Get &quot;fast&quot; parameters for TsqrOrthoManagerImpl.
void project(MV &X, Teuchos::Array< mat_ptr > C, Teuchos::ArrayView< Teuchos::RCP< const MV > > Q)
Compute and .
Anasazi header file which uses auto-configuration information to include necessary C++ headers...
void resize(size_type new_size, const value_type &x=value_type())
Exception thrown to signal error in an orthogonalization manager method.
int projectAndNormalizeOutOfPlace(MV &X_in, MV &X_out, Teuchos::Array< mat_ptr > C, mat_ptr B, Teuchos::ArrayView< Teuchos::RCP< const MV > > Q)
Project and normalize X_in into X_out; overwrite X_in.
int normalizeOutOfPlace(MV &X, MV &Q, mat_ptr B)
Normalize X into Q*B, overwriting X.
static int GetNumberVecs(const MV &mv)
Obtain the number of vectors in mv.
OrdinalType numCols() const
Teuchos::RCP< const Teuchos::ParameterList > getValidParameters() const
Default valid parameter list.
magnitude_type orthogError(const MV &X1, const MV &X2) const
Return the Frobenius norm of the inner product of X1 with itself.
int normalize(MV &X, mat_ptr B)
Orthogonalize the columns of X in place.
OrdinalType numRows() const
ScalarTraits< ScalarType >::magnitudeType NRM2(const OrdinalType n, const ScalarType *x, const OrdinalType incx) const
bool is_null() const