Belos Package Browser (Single Doxygen Collection)  Development
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
BelosTsqrOrthoManagerImpl.hpp
Go to the documentation of this file.
1 //@HEADER
2 // ************************************************************************
3 //
4 // Belos: Block Linear Solvers Package
5 // Copyright 2004 Sandia Corporation
6 //
7 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
8 // the U.S. Government retains certain rights in this software.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
38 //
39 // ************************************************************************
40 //@HEADER
41 
45 #ifndef __BelosTsqrOrthoManagerImpl_hpp
46 #define __BelosTsqrOrthoManagerImpl_hpp
47 
48 #include "BelosConfigDefs.hpp" // HAVE_BELOS_TSQR
49 #include "BelosMultiVecTraits.hpp"
50 #include "BelosOrthoManager.hpp" // OrthoError, etc.
51 
52 #include "Teuchos_as.hpp"
55 #ifdef BELOS_TEUCHOS_TIME_MONITOR
56 # include "Teuchos_TimeMonitor.hpp"
57 #endif // BELOS_TEUCHOS_TIME_MONITOR
58 #include <algorithm>
59 #include <functional>
60 
61 namespace Belos {
62 
66  class TsqrOrthoError : public OrthoError {
67  public:
68  TsqrOrthoError (const std::string& what_arg) :
69  OrthoError (what_arg) {}
70  };
71 
91  class TsqrOrthoFault : public OrthoError {
92  public:
93  TsqrOrthoFault (const std::string& what_arg) :
94  OrthoError (what_arg) {}
95  };
96 
129  template<class Scalar>
131  {
132  public:
134  typedef Scalar scalar_type;
140 
142  virtual ~ReorthogonalizationCallback ();
143 
148  virtual void
149  operator() (Teuchos::ArrayView<magnitude_type> normsBeforeFirstPass,
150  Teuchos::ArrayView<magnitude_type> normsAfterFirstPass) = 0;
151  };
152 
153  template<class Scalar>
155 
187  template<class Scalar, class MV>
190  public:
191  typedef Scalar scalar_type;
193  typedef MV multivector_type;
197 
198  private:
202  typedef typename MVT::tsqr_adaptor_type tsqr_adaptor_type;
203 
204  public:
213 
216 
228 
246  const std::string& label);
247 
252  TsqrOrthoManagerImpl (const std::string& label);
253 
273  void
275  {
276  reorthogCallback_ = callback;
277  }
278 
286  void setLabel (const std::string& label) {
287  if (label != label_) {
288  label_ = label;
289 
290 #ifdef BELOS_TEUCHOS_TIME_MONITOR
291  clearTimer (label, "All orthogonalization");
292  clearTimer (label, "Projection");
293  clearTimer (label, "Normalization");
294 
295  timerOrtho_ = makeTimer (label, "All orthogonalization");
296  timerProject_ = makeTimer (label, "Projection");
297  timerNormalize_ = makeTimer (label, "Normalization");
298 #endif // BELOS_TEUCHOS_TIME_MONITOR
299  }
300  }
301 
303  const std::string& getLabel () const { return label_; }
304 
313  void
314  innerProd (const MV& X, const MV& Y, mat_type& Z) const
315  {
316  MVT::MvTransMv (SCT::one(), X, Y, Z);
317  }
318 
336  void
337  norm (const MV& X, std::vector<magnitude_type>& normVec) const;
338 
348  void
349  project (MV& X,
352 
366  int normalize (MV& X, mat_ptr B);
367 
386  int
387  normalizeOutOfPlace (MV& X, MV& Q, mat_ptr B);
388 
402  int
405  mat_ptr B,
407  {
408  // "false" means we work on X in place. The second argument is
409  // not read or written in that case.
410  return projectAndNormalizeImpl (X, X, false, C, B, Q);
411  }
412 
432  int
434  MV& X_out,
436  mat_ptr B,
438  {
439  // "true" means we work on X_in out of place, writing the
440  // results into X_out.
441  return projectAndNormalizeImpl (X_in, X_out, true, C, B, Q);
442  }
443 
449  orthonormError (const MV &X) const
450  {
451  const Scalar ONE = SCT::one();
452  const int ncols = MVT::GetNumberVecs(X);
453  mat_type XTX (ncols, ncols);
454  innerProd (X, X, XTX);
455  for (int k = 0; k < ncols; ++k) {
456  XTX(k,k) -= ONE;
457  }
458  return XTX.normFrobenius();
459  }
460 
463  orthogError (const MV &X1,
464  const MV &X2) const
465  {
466  const int ncols_X1 = MVT::GetNumberVecs (X1);
467  const int ncols_X2 = MVT::GetNumberVecs (X2);
468  mat_type X1_T_X2 (ncols_X1, ncols_X2);
469  innerProd (X1, X2, X1_T_X2);
470  return X1_T_X2.normFrobenius();
471  }
472 
477 
481 
482  private:
485 
488 
490  std::string label_;
491 
494 
505 
508 
513 
520 
525 
528 
531 
539 
540 #ifdef BELOS_TEUCHOS_TIME_MONITOR
541  Teuchos::RCP<Teuchos::Time> timerOrtho_;
543 
545  Teuchos::RCP<Teuchos::Time> timerProject_;
546 
548  Teuchos::RCP<Teuchos::Time> timerNormalize_;
549 #endif // BELOS_TEUCHOS_TIME_MONITOR
550 
553 
554 #ifdef BELOS_TEUCHOS_TIME_MONITOR
564  makeTimer (const std::string& prefix,
565  const std::string& timerName)
566  {
567  const std::string timerLabel =
568  prefix.empty() ? timerName : (prefix + ": " + timerName);
569  return Teuchos::TimeMonitor::getNewCounter (timerLabel);
570  }
571 
577  void
578  clearTimer (const std::string& prefix,
579  const std::string& timerName)
580  {
581  const std::string timerLabel =
582  prefix.empty() ? timerName : (prefix + ": " + timerName);
584  }
585 #endif // BELOS_TEUCHOS_TIME_MONITOR
586 
588  void
589  raiseReorthogFault (const std::vector<magnitude_type>& normsAfterFirstPass,
590  const std::vector<magnitude_type>& normsAfterSecondPass,
591  const std::vector<int>& faultIndices);
592 
602  void
603  checkProjectionDims (int& ncols_X,
604  int& num_Q_blocks,
605  int& ncols_Q_total,
606  const MV& X,
608 
619  void
622  const MV& X,
623  const bool attemptToRecycle = true) const;
624 
633  int
634  projectAndNormalizeImpl (MV& X_in,
635  MV& X_out,
636  const bool outOfPlace,
638  mat_ptr B,
640 
646  void
647  rawProject (MV& X,
650 
652  void
653  rawProject (MV& X,
654  const Teuchos::RCP<const MV>& Q,
655  const mat_ptr& C) const;
656 
683  int rawNormalize (MV& X, MV& Q, mat_type& B);
684 
702  int normalizeOne (MV& X, mat_ptr B) const;
703 
731  int normalizeImpl (MV& X, MV& Q, mat_ptr B, const bool outOfPlace);
732  };
733 
734  template<class Scalar, class MV>
735  void
738  {
740  using Teuchos::parameterList;
741  using Teuchos::RCP;
742  using Teuchos::sublist;
743  typedef magnitude_type M; // abbreviation.
744 
745  RCP<const ParameterList> defaultParams = getValidParameters ();
746  // Sublist of TSQR implementation parameters; to get below.
747  RCP<ParameterList> tsqrParams;
748 
749  RCP<ParameterList> theParams;
750  if (params.is_null()) {
751  theParams = parameterList (*defaultParams);
752  } else {
753  theParams = params;
754 
755  // Don't call validateParametersAndSetDefaults(); we prefer to
756  // ignore parameters that we don't recognize, at least for now.
757  // However, we do fill in missing parameters with defaults.
758 
759  randomizeNullSpace_ =
760  theParams->get<bool> ("randomizeNullSpace",
761  defaultParams->get<bool> ("randomizeNullSpace"));
762  reorthogonalizeBlocks_ =
763  theParams->get<bool> ("reorthogonalizeBlocks",
764  defaultParams->get<bool> ("reorthogonalizeBlocks"));
765  throwOnReorthogFault_ =
766  theParams->get<bool> ("throwOnReorthogFault",
767  defaultParams->get<bool> ("throwOnReorthogFault"));
768  blockReorthogThreshold_ =
769  theParams->get<M> ("blockReorthogThreshold",
770  defaultParams->get<M> ("blockReorthogThreshold"));
771  relativeRankTolerance_ =
772  theParams->get<M> ("relativeRankTolerance",
773  defaultParams->get<M> ("relativeRankTolerance"));
774  forceNonnegativeDiagonal_ =
775  theParams->get<bool> ("forceNonnegativeDiagonal",
776  defaultParams->get<bool> ("forceNonnegativeDiagonal"));
777 
778  // Get the sublist of TSQR implementation parameters. Use the
779  // default sublist if one isn't provided.
780  if (! theParams->isSublist ("TSQR implementation")) {
781  theParams->set ("TSQR implementation",
782  defaultParams->sublist ("TSQR implementation"));
783  }
784  tsqrParams = sublist (theParams, "TSQR implementation", true);
785  }
786 
787  // Send the TSQR implementation parameters to the TSQR adaptor.
788  tsqrAdaptor_.setParameterList (tsqrParams);
789 
790  // Save the input parameter list.
791  setMyParamList (theParams);
792  }
793 
794  template<class Scalar, class MV>
797  const std::string& label) :
798  label_ (label),
799  Q_ (Teuchos::null), // Initialized on demand
800  eps_ (SCTM::eps()), // Machine precision
801  randomizeNullSpace_ (true),
802  reorthogonalizeBlocks_ (true),
803  throwOnReorthogFault_ (false),
804  blockReorthogThreshold_ (0),
805  relativeRankTolerance_ (0),
806  forceNonnegativeDiagonal_ (false)
807  {
808  setParameterList (params); // This also sets tsqrAdaptor_'s parameters.
809 
810 #ifdef BELOS_TEUCHOS_TIME_MONITOR
811  timerOrtho_ = makeTimer (label, "All orthogonalization");
812  timerProject_ = makeTimer (label, "Projection");
813  timerNormalize_ = makeTimer (label, "Normalization");
814 #endif // BELOS_TEUCHOS_TIME_MONITOR
815  }
816 
817  template<class Scalar, class MV>
819  TsqrOrthoManagerImpl (const std::string& label) :
820  label_ (label),
821  Q_ (Teuchos::null), // Initialized on demand
822  eps_ (SCTM::eps()), // Machine precision
823  randomizeNullSpace_ (true),
824  reorthogonalizeBlocks_ (true),
825  throwOnReorthogFault_ (false),
826  blockReorthogThreshold_ (0),
827  relativeRankTolerance_ (0),
828  forceNonnegativeDiagonal_ (false)
829  {
830  setParameterList (Teuchos::null); // Set default parameters.
831 
832 #ifdef BELOS_TEUCHOS_TIME_MONITOR
833  timerOrtho_ = makeTimer (label, "All orthogonalization");
834  timerProject_ = makeTimer (label, "Projection");
835  timerNormalize_ = makeTimer (label, "Normalization");
836 #endif // BELOS_TEUCHOS_TIME_MONITOR
837  }
838 
839  template<class Scalar, class MV>
840  void
842  norm (const MV& X, std::vector<magnitude_type>& normVec) const
843  {
844  const int numCols = MVT::GetNumberVecs (X);
845  // std::vector<T>::size_type is unsigned; int is signed. Mixed
846  // unsigned/signed comparisons trigger compiler warnings.
847  if (normVec.size() < static_cast<size_t>(numCols))
848  normVec.resize (numCols); // Resize normvec if necessary.
849  MVT::MvNorm (X, normVec);
850  }
851 
852  template<class Scalar, class MV>
853  void
857  {
858 #ifdef BELOS_TEUCHOS_TIME_MONITOR
859  // "Projection" only happens in rawProject(), so we only time
860  // projection inside rawProject(). However, we count the time
861  // spend in project() as part of the whole orthogonalization.
862  //
863  // If project() is called from projectAndNormalize(), the
864  // TimeMonitor won't start timerOrtho_, because it is already
865  // running in projectAndNormalize().
866  Teuchos::TimeMonitor timerMonitorOrtho(*timerOrtho_);
867 #endif // BELOS_TEUCHOS_TIME_MONITOR
868 
869  int ncols_X, num_Q_blocks, ncols_Q_total;
870  checkProjectionDims (ncols_X, num_Q_blocks, ncols_Q_total, X, Q);
871  // Test for quick exit: any dimension of X is zero, or there are
872  // zero Q blocks, or the total number of columns of the Q blocks
873  // is zero.
874  if (ncols_X == 0 || num_Q_blocks == 0 || ncols_Q_total == 0)
875  return;
876 
877  // Make space for first-pass projection coefficients
878  allocateProjectionCoefficients (C, Q, X, true);
879 
880  // We only use columnNormsBefore and compute pre-projection column
881  // norms if doing block reorthogonalization.
882  std::vector<magnitude_type> columnNormsBefore (ncols_X, magnitude_type(0));
883  if (reorthogonalizeBlocks_)
884  MVT::MvNorm (X, columnNormsBefore);
885 
886  // Project (first block orthogonalization step):
887  // C := Q^* X, X := X - Q C.
888  rawProject (X, Q, C);
889 
890  // If we are doing block reorthogonalization, reorthogonalize X if
891  // necessary.
892  if (reorthogonalizeBlocks_) {
893  std::vector<magnitude_type> columnNormsAfter (ncols_X, magnitude_type(0));
894  MVT::MvNorm (X, columnNormsAfter);
895 
896  // Relative block reorthogonalization threshold.
897  const magnitude_type relThres = blockReorthogThreshold();
898  // Reorthogonalize X if any of its column norms decreased by a
899  // factor more than the block reorthogonalization threshold.
900  // Don't bother trying to subset the columns; that will make the
901  // columns noncontiguous and thus hinder BLAS 3 optimizations.
902  bool reorthogonalize = false;
903  for (int j = 0; j < ncols_X; ++j) {
904  if (columnNormsAfter[j] < relThres * columnNormsBefore[j]) {
905  reorthogonalize = true;
906  break;
907  }
908  }
909  if (reorthogonalize) {
910  // Notify the caller via callback about the need for
911  // reorthogonalization.
912  if (! reorthogCallback_.is_null()) {
913  reorthogCallback_->operator() (Teuchos::arrayViewFromVector (columnNormsBefore),
914  Teuchos::arrayViewFromVector (columnNormsAfter));
915  }
916  // Second-pass projection coefficients
918  allocateProjectionCoefficients (C2, Q, X, false);
919 
920  // Perform the second projection pass:
921  // C2 = Q' X, X = X - Q*C2
922  rawProject (X, Q, C2);
923  // Update the projection coefficients
924  for (int k = 0; k < num_Q_blocks; ++k)
925  *C[k] += *C2[k];
926  }
927  }
928  }
929 
930 
931  template<class Scalar, class MV>
932  int
934  {
935  using Teuchos::Range1D;
936  using Teuchos::RCP;
937 
938 #ifdef BELOS_TEUCHOS_TIME_MONITOR
939  Teuchos::TimeMonitor timerMonitorNormalize(*timerNormalize_);
940  // If normalize() is called internally -- i.e., called from
941  // projectAndNormalize() -- the timer will not be started or
942  // stopped, because it is already running. TimeMonitor handles
943  // recursive invocation by doing nothing.
944  Teuchos::TimeMonitor timerMonitorOrtho(*timerOrtho_);
945 #endif // BELOS_TEUCHOS_TIME_MONITOR
946 
947  // MVT returns int for this, even though the "local ordinal
948  // type" of the MV may be some other type (for example,
949  // Tpetra::MultiVector<double, int32_t, int64_t, ...>).
950  const int numCols = MVT::GetNumberVecs (X);
951 
952  // This special case (for X having only one column) makes
953  // TsqrOrthoManagerImpl equivalent to Modified Gram-Schmidt
954  // orthogonalization with conditional full reorthogonalization,
955  // if all multivector inputs have only one column. It also
956  // avoids allocating Q_ scratch space and copying data when we
957  // don't need to invoke TSQR at all.
958  if (numCols == 1) {
959  return normalizeOne (X, B);
960  }
961 
962  // We use Q_ as scratch space for the normalization, since TSQR
963  // requires a scratch multivector (it can't factor in place). Q_
964  // should come from a vector space compatible with X's vector
965  // space, and Q_ should have at least as many columns as X.
966  // Otherwise, we have to reallocate. We also have to allocate
967  // (not "re-") Q_ if we haven't allocated it before. (We can't
968  // allocate Q_ until we have some X, so we need a multivector as
969  // the "prototype.")
970  //
971  // NOTE (mfh 11 Jan 2011) We only increase the number of columsn
972  // in Q_, never decrease. This is OK for typical uses of TSQR,
973  // but you might prefer different behavior in some cases.
974  //
975  // NOTE (mfh 10 Mar 2011) We should only reuse the scratch space
976  // Q_ if X and Q_ have compatible data distributions. However,
977  // Belos' current MultiVecTraits interface does not let us check
978  // for this. Thus, we can only check whether X and Q_ have the
979  // same number of rows. This will behave correctly for the common
980  // case in Belos that all multivectors with the same number of
981  // rows have the same data distribution.
982  //
983  // The specific MV implementation may do more checks than this on
984  // its own and throw an exception if X and Q_ are not compatible,
985  // but it may not. If you find that recycling the Q_ space causes
986  // troubles, you may consider modifying the code below to
987  // reallocate Q_ for every X that comes in.
988  if (Q_.is_null() ||
989  MVT::GetGlobalLength(*Q_) != MVT::GetGlobalLength(X) ||
990  numCols > MVT::GetNumberVecs (*Q_)) {
991  Q_ = MVT::Clone (X, numCols);
992  }
993 
994  // normalizeImpl() wants the second MV argument to have the same
995  // number of columns as X. To ensure this, we pass it a view of
996  // Q_ if Q_ has more columns than X. (This is possible if we
997  // previously called normalize() with a different multivector,
998  // since we never reallocate Q_ if it has more columns than
999  // necessary.)
1000  if (MVT::GetNumberVecs(*Q_) == numCols) {
1001  return normalizeImpl (X, *Q_, B, false);
1002  } else {
1003  RCP<MV> Q_view = MVT::CloneViewNonConst (*Q_, Range1D(0, numCols-1));
1004  return normalizeImpl (X, *Q_view, B, false);
1005  }
1006  }
1007 
1008  template<class Scalar, class MV>
1009  void
1013  const MV& X,
1014  const bool attemptToRecycle) const
1015  {
1016  const int num_Q_blocks = Q.size();
1017  const int ncols_X = MVT::GetNumberVecs (X);
1018  C.resize (num_Q_blocks);
1019  if (attemptToRecycle)
1020  {
1021  for (int i = 0; i < num_Q_blocks; ++i)
1022  {
1023  const int ncols_Qi = MVT::GetNumberVecs (*Q[i]);
1024  // Create a new C[i] if necessary, otherwise resize if
1025  // necessary, otherwise fill with zeros.
1026  if (C[i].is_null())
1027  C[i] = Teuchos::rcp (new mat_type (ncols_Qi, ncols_X));
1028  else
1029  {
1030  mat_type& Ci = *C[i];
1031  if (Ci.numRows() != ncols_Qi || Ci.numCols() != ncols_X)
1032  Ci.shape (ncols_Qi, ncols_X);
1033  else
1034  Ci.putScalar (SCT::zero());
1035  }
1036  }
1037  }
1038  else
1039  {
1040  for (int i = 0; i < num_Q_blocks; ++i)
1041  {
1042  const int ncols_Qi = MVT::GetNumberVecs (*Q[i]);
1043  C[i] = Teuchos::rcp (new mat_type (ncols_Qi, ncols_X));
1044  }
1045  }
1046  }
1047 
1048  template<class Scalar, class MV>
1049  int
1052  {
1053 #ifdef BELOS_TEUCHOS_TIME_MONITOR
1054  Teuchos::TimeMonitor timerMonitorOrtho(*timerOrtho_);
1055  Teuchos::TimeMonitor timerMonitorNormalize(*timerNormalize_);
1056 #endif // BELOS_TEUCHOS_TIME_MONITOR
1057 
1058  const int numVecs = MVT::GetNumberVecs(X);
1059  if (numVecs == 0) {
1060  return 0; // Nothing to do.
1061  } else if (numVecs == 1) {
1062  // Special case for a single column; scale and copy over.
1063  using Teuchos::Range1D;
1064  using Teuchos::RCP;
1065  using Teuchos::rcp;
1066 
1067  // Normalize X in place (faster than TSQR for one column).
1068  const int rank = normalizeOne (X, B);
1069  // Copy results to first column of Q.
1070  RCP<MV> Q_0 = MVT::CloneViewNonConst (Q, Range1D(0,0));
1071  MVT::Assign (X, *Q_0);
1072  return rank;
1073  } else {
1074  // The "true" argument to normalizeImpl() means the output
1075  // vectors go into Q, and the contents of X are overwritten with
1076  // invalid values.
1077  return normalizeImpl (X, Q, B, true);
1078  }
1079  }
1080 
1081  template<class Scalar, class MV>
1082  int
1085  MV& X_out, // Only written if outOfPlace==false.
1086  const bool outOfPlace,
1088  mat_ptr B,
1090  {
1091  using Teuchos::Range1D;
1092  using Teuchos::RCP;
1093  using Teuchos::rcp;
1094 
1095 #ifdef BELOS_TEUCHOS_TIME_MONITOR
1096  // Projection is only timed in rawProject(), and normalization is
1097  // only timed in normalize() and normalizeOutOfPlace().
1098  Teuchos::TimeMonitor timerMonitorOrtho(*timerOrtho_);
1099 #endif // BELOS_TEUCHOS_TIME_MONITOR
1100 
1101  if (outOfPlace) {
1102  // Make sure that X_out has at least as many columns as X_in.
1103  TEUCHOS_TEST_FOR_EXCEPTION(MVT::GetNumberVecs(X_out) < MVT::GetNumberVecs(X_in),
1104  std::invalid_argument,
1105  "Belos::TsqrOrthoManagerImpl::"
1106  "projectAndNormalizeImpl(..., outOfPlace=true, ...):"
1107  "X_out has " << MVT::GetNumberVecs(X_out)
1108  << " columns, but X_in has "
1109  << MVT::GetNumberVecs(X_in) << " columns.");
1110  }
1111  // Fetch dimensions of X_in and Q, and allocate space for first-
1112  // and second-pass projection coefficients (C resp. C2).
1113  int ncols_X, num_Q_blocks, ncols_Q_total;
1114  checkProjectionDims (ncols_X, num_Q_blocks, ncols_Q_total, X_in, Q);
1115 
1116  // Test for quick exit: if any dimension of X is zero.
1117  if (ncols_X == 0) {
1118  return 0;
1119  }
1120  // If there are zero Q blocks or zero Q columns, just normalize!
1121  if (num_Q_blocks == 0 || ncols_Q_total == 0) {
1122  if (outOfPlace) {
1123  return normalizeOutOfPlace (X_in, X_out, B);
1124  } else {
1125  return normalize (X_in, B);
1126  }
1127  }
1128 
1129  // The typical case is that the entries of C have been allocated
1130  // before, so we attempt to recycle the allocations. The call
1131  // below will reallocate if it cannot recycle.
1132  allocateProjectionCoefficients (C, Q, X_in, true);
1133 
1134  // If we are doing block reorthogonalization, then compute the
1135  // column norms of X before projecting for the first time. This
1136  // will help us decide whether we need to reorthogonalize X.
1137  std::vector<magnitude_type> normsBeforeFirstPass (ncols_X, SCTM::zero());
1138  if (reorthogonalizeBlocks_) {
1139  MVT::MvNorm (X_in, normsBeforeFirstPass);
1140  }
1141 
1142  // First (Modified) Block Gram-Schmidt pass, in place in X_in.
1143  rawProject (X_in, Q, C);
1144 
1145  // Make space for the normalization coefficients. This will
1146  // either be a freshly allocated matrix (if B is null), or a view
1147  // of the appropriately sized upper left submatrix of *B (if B is
1148  // not null).
1149  //
1150  // Note that if we let the normalize() routine allocate (in the
1151  // case that B is null), that storage will go away at the end of
1152  // normalize(). (This is because it passes the RCP by value, not
1153  // by reference.)
1154  mat_ptr B_out;
1155  if (B.is_null()) {
1156  B_out = rcp (new mat_type (ncols_X, ncols_X));
1157  } else {
1158  // Make sure that B is no smaller than numCols x numCols.
1159  TEUCHOS_TEST_FOR_EXCEPTION(B->numRows() < ncols_X || B->numCols() < ncols_X,
1160  std::invalid_argument,
1161  "normalizeOne: Input matrix B must be at "
1162  "least " << ncols_X << " x " << ncols_X
1163  << ", but is instead " << B->numRows()
1164  << " x " << B->numCols() << ".");
1165  // Create a view of the ncols_X by ncols_X upper left
1166  // submatrix of *B. TSQR will write the normalization
1167  // coefficients there.
1168  B_out = rcp (new mat_type (Teuchos::View, *B, ncols_X, ncols_X));
1169  }
1170 
1171  // Rank of X(_in) after first projection pass. If outOfPlace,
1172  // this overwrites X_in with invalid values, and the results go in
1173  // X_out. Otherwise, it's done in place in X_in.
1174  const int firstPassRank = outOfPlace ?
1175  normalizeOutOfPlace (X_in, X_out, B_out) :
1176  normalize (X_in, B_out);
1177  if (B.is_null()) {
1178  // The input matrix B is null, so assign B_out to it. If B was
1179  // not null on input, then B_out is a view of *B, so we don't
1180  // have to do anything here. Note that SerialDenseMatrix uses
1181  // raw pointers to store data and represent views, so we have to
1182  // be careful about scope.
1183  B = B_out;
1184  }
1185  int rank = firstPassRank; // Current rank of X.
1186 
1187  // If X was not full rank after projection and randomizeNullSpace_
1188  // is true, then normalize(OutOfPlace)() replaced the null space
1189  // basis of X with random vectors, and orthogonalized them against
1190  // the column space basis of X. However, we still need to
1191  // orthogonalize the random vectors against the Q[i], after which
1192  // we will need to renormalize them.
1193  //
1194  // If outOfPlace, then we need to work in X_out (where
1195  // normalizeOutOfPlace() wrote the normalized vectors).
1196  // Otherwise, we need to work in X_in.
1197  //
1198  // Note: We don't need to keep the new projection coefficients,
1199  // since they are multiplied by the "small" part of B
1200  // corresponding to the null space of the original X.
1201  if (firstPassRank < ncols_X && randomizeNullSpace_) {
1202  const int numNullSpaceCols = ncols_X - firstPassRank;
1203  const Range1D nullSpaceIndices (firstPassRank, ncols_X - 1);
1204 
1205  // Space for projection coefficients (will be thrown away)
1206  Teuchos::Array<mat_ptr> C_null (num_Q_blocks);
1207  for (int k = 0; k < num_Q_blocks; ++k) {
1208  const int numColsQk = MVT::GetNumberVecs(*Q[k]);
1209  C_null[k] = rcp (new mat_type (numColsQk, numNullSpaceCols));
1210  }
1211  // Space for normalization coefficients (will be thrown away).
1212  RCP<mat_type> B_null (new mat_type (numNullSpaceCols, numNullSpaceCols));
1213 
1214  int randomVectorsRank;
1215  if (outOfPlace) {
1216  // View of the null space basis columns of X.
1217  // normalizeOutOfPlace() wrote them into X_out.
1218  RCP<MV> X_out_null = MVT::CloneViewNonConst (X_out, nullSpaceIndices);
1219  // Use X_in for scratch space. Copy X_out_null into the
1220  // last few columns of X_in (X_in_null) and do projections
1221  // in there. (This saves us a copy wen we renormalize
1222  // (out of place) back into X_out.)
1223  RCP<MV> X_in_null = MVT::CloneViewNonConst (X_in, nullSpaceIndices);
1224  MVT::Assign (*X_out_null, *X_in_null);
1225  // Project the new random vectors against the Q blocks, and
1226  // renormalize the result into X_out_null.
1227  rawProject (*X_in_null, Q, C_null);
1228  randomVectorsRank = normalizeOutOfPlace (*X_in_null, *X_out_null, B_null);
1229  } else {
1230  // View of the null space columns of X.
1231  // They live in X_in.
1232  RCP<MV> X_null = MVT::CloneViewNonConst (X_in, nullSpaceIndices);
1233  // Project the new random vectors against the Q blocks,
1234  // and renormalize the result (in place).
1235  rawProject (*X_null, Q, C_null);
1236  randomVectorsRank = normalize (*X_null, B_null);
1237  }
1238  // While unusual, it is still possible for the random data not
1239  // to be full rank after projection and normalization. In that
1240  // case, we could try another set of random data and recurse as
1241  // necessary, but instead for now we just raise an exception.
1242  TEUCHOS_TEST_FOR_EXCEPTION(randomVectorsRank != numNullSpaceCols,
1244  "Belos::TsqrOrthoManagerImpl::projectAndNormalize"
1245  "OutOfPlace(): After projecting and normalizing the "
1246  "random vectors (used to replace the null space "
1247  "basis vectors from normalizing X), they have rank "
1248  << randomVectorsRank << ", but should have full "
1249  "rank " << numNullSpaceCols << ".");
1250  }
1251 
1252  // Whether or not X_in was full rank after projection, we still
1253  // might want to reorthogonalize against Q.
1254  if (reorthogonalizeBlocks_) {
1255  // We are only interested in the column space basis of X
1256  // resp. X_out.
1257  std::vector<magnitude_type>
1258  normsAfterFirstPass (firstPassRank, SCTM::zero());
1259  std::vector<magnitude_type>
1260  normsAfterSecondPass (firstPassRank, SCTM::zero());
1261 
1262  // Compute post-first-pass (pre-normalization) norms. We could
1263  // have done that using MVT::MvNorm() on X_in after projecting,
1264  // but before the first normalization. However, that operation
1265  // may be expensive. It is also unnecessary: after calling
1266  // normalize(), the 2-norm of B(:,j) is the 2-norm of X_in(:,j)
1267  // before normalization, in exact arithmetic.
1268  //
1269  // NOTE (mfh 06 Nov 2010) This is one way that combining
1270  // projection and normalization into a single kernel --
1271  // projectAndNormalize() -- pays off. In project(), we have to
1272  // compute column norms of X before and after projection. Here,
1273  // we get them for free from the normalization coefficients.
1275  for (int j = 0; j < firstPassRank; ++j) {
1276  const Scalar* const B_j = &(*B_out)(0,j);
1277  // Teuchos::BLAS::NRM2 returns a magnitude_type result on
1278  // Scalar inputs.
1279  normsAfterFirstPass[j] = blas.NRM2 (firstPassRank, B_j, 1);
1280  }
1281  // Test whether any of the norms dropped below the
1282  // reorthogonalization threshold.
1283  bool reorthogonalize = false;
1284  for (int j = 0; j < firstPassRank; ++j) {
1285  // If any column's norm decreased too much, mark this block
1286  // for reorthogonalization. Note that this test will _not_
1287  // activate reorthogonalization if a column's norm before the
1288  // first project-and-normalize step was zero. It _will_
1289  // activate reorthogonalization if the column's norm before
1290  // was not zero, but is zero now.
1291  const magnitude_type curThreshold =
1292  blockReorthogThreshold() * normsBeforeFirstPass[j];
1293  if (normsAfterFirstPass[j] < curThreshold) {
1294  reorthogonalize = true;
1295  break;
1296  }
1297  }
1298 
1299  // Notify the caller via callback about the need for
1300  // reorthogonalization.
1301  if (! reorthogCallback_.is_null()) {
1302  using Teuchos::arrayViewFromVector;
1303  (*reorthogCallback_) (arrayViewFromVector (normsBeforeFirstPass),
1304  arrayViewFromVector (normsAfterFirstPass));
1305  }
1306 
1307  // Perform another Block Gram-Schmidt pass if necessary. "Twice
1308  // is enough" (Kahan's theorem) for a Krylov method, unless
1309  // (using Stewart's term) there is an "orthogonalization fault"
1310  // (indicated by reorthogFault).
1311  //
1312  // NOTE (mfh 07 Nov 2010) For now, we include the entire block
1313  // of X, including possible random data (that was already
1314  // projected and normalized above). It might make more sense
1315  // just to process the first firstPassRank columns of X.
1316  // However, the resulting reorthogonalization should still be
1317  // correct regardless.
1318  bool reorthogFault = false;
1319  // Indices of X at which there was an orthogonalization fault.
1320  std::vector<int> faultIndices;
1321  if (reorthogonalize) {
1322  using Teuchos::Copy;
1323  using Teuchos::NO_TRANS;
1324 
1325  // If we're using out-of-place normalization, copy X_out
1326  // (results of first project and normalize pass) back into
1327  // X_in, for the second project and normalize pass.
1328  if (outOfPlace) {
1329  MVT::Assign (X_out, X_in);
1330  }
1331 
1332  // C2 is only used internally, so we know that we are
1333  // allocating fresh and not recycling allocations. Stating
1334  // this lets us save time checking dimensions.
1336  allocateProjectionCoefficients (C2, Q, X_in, false);
1337 
1338  // Block Gram-Schmidt (again). Delay updating the block
1339  // coefficients until we have the new normalization
1340  // coefficients, which we need in order to do the update.
1341  rawProject (X_in, Q, C2);
1342 
1343  // Coefficients for (re)normalization of X_in.
1344  RCP<mat_type> B2 (new mat_type (ncols_X, ncols_X));
1345 
1346  // Normalize X_in (into X_out, if working out of place).
1347  const int secondPassRank = outOfPlace ?
1348  normalizeOutOfPlace (X_in, X_out, B2) :
1349  normalize (X_in, B2);
1350  rank = secondPassRank; // Current rank of X
1351 
1352  // Update normalization coefficients. We begin with copying
1353  // B_out, since the BLAS' _GEMM routine doesn't let us alias
1354  // its input and output arguments.
1355  mat_type B_copy (Copy, *B_out, B_out->numRows(), B_out->numCols());
1356  // B_out := B2 * B_out (where input B_out is in B_copy).
1357  const int err = B_out->multiply (NO_TRANS, NO_TRANS, SCT::one(),
1358  *B2, B_copy, SCT::zero());
1359  TEUCHOS_TEST_FOR_EXCEPTION(err != 0, std::logic_error,
1360  "Teuchos::SerialDenseMatrix::multiply "
1361  "returned err = " << err << " != 0");
1362  // Update the block coefficients from the projection step. We
1363  // use B_copy for this (a copy of B_out, the first-pass
1364  // normalization coefficients).
1365  for (int k = 0; k < num_Q_blocks; ++k) {
1366  mat_type C_k_copy (Copy, *C[k], C[k]->numRows(), C[k]->numCols());
1367 
1368  // C[k] := C2[k]*B_copy + C[k].
1369  const int err1 = C[k]->multiply (NO_TRANS, NO_TRANS, SCT::one(),
1370  *C2[k], B_copy, SCT::one());
1371  TEUCHOS_TEST_FOR_EXCEPTION(err1 != 0, std::logic_error,
1372  "Teuchos::SerialDenseMatrix::multiply "
1373  "returned err = " << err1 << " != 0");
1374  }
1375  // Compute post-second-pass (pre-normalization) norms, using
1376  // B2 (the coefficients from the second normalization step) in
1377  // the same way as with B_out before.
1378  for (int j = 0; j < rank; ++j) {
1379  const Scalar* const B2_j = &(*B2)(0,j);
1380  normsAfterSecondPass[j] = blas.NRM2 (rank, B2_j, 1);
1381  }
1382  // Test whether any of the norms dropped below the
1383  // reorthogonalization threshold. If so, it's an
1384  // orthogonalization fault, which requires expensive recovery.
1385  reorthogFault = false;
1386  for (int j = 0; j < rank; ++j) {
1387  const magnitude_type relativeLowerBound =
1388  blockReorthogThreshold() * normsAfterFirstPass[j];
1389  if (normsAfterSecondPass[j] < relativeLowerBound) {
1390  reorthogFault = true;
1391  faultIndices.push_back (j);
1392  }
1393  }
1394  } // if (reorthogonalize) // reorthogonalization pass
1395 
1396  if (reorthogFault) {
1397  if (throwOnReorthogFault_) {
1398  raiseReorthogFault (normsAfterFirstPass,
1399  normsAfterSecondPass,
1400  faultIndices);
1401  } else {
1402  // NOTE (mfh 19 Jan 2011) We could handle the fault here by
1403  // slowly reorthogonalizing, one vector at a time, the
1404  // offending vectors of X. However, we choose not to
1405  // implement this for now. If it becomes a problem, let us
1406  // know and we will prioritize implementing this.
1407  TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error,
1408  "TsqrOrthoManagerImpl has not yet implemented"
1409  " recovery from an orthogonalization fault.");
1410  }
1411  }
1412  } // if (reorthogonalizeBlocks_)
1413  return rank;
1414  }
1415 
1416 
1417  template<class Scalar, class MV>
1418  void
1420  raiseReorthogFault (const std::vector<magnitude_type>& normsAfterFirstPass,
1421  const std::vector<magnitude_type>& normsAfterSecondPass,
1422  const std::vector<int>& faultIndices)
1423  {
1424  using std::endl;
1425  typedef std::vector<int>::size_type size_type;
1426  std::ostringstream os;
1427 
1428  os << "Orthogonalization fault at the following column(s) of X:" << endl;
1429  os << "Column\tNorm decrease factor" << endl;
1430  for (size_type k = 0; k < faultIndices.size(); ++k) {
1431  const int index = faultIndices[k];
1432  const magnitude_type decreaseFactor =
1433  normsAfterSecondPass[index] / normsAfterFirstPass[index];
1434  os << index << "\t" << decreaseFactor << endl;
1435  }
1436  throw TsqrOrthoFault (os.str());
1437  }
1438 
1439  template<class Scalar, class MV>
1442  {
1443  using Teuchos::ParameterList;
1444  using Teuchos::parameterList;
1445  using Teuchos::RCP;
1446 
1447  if (defaultParams_.is_null()) {
1448  RCP<ParameterList> params = parameterList ("TsqrOrthoManagerImpl");
1449  //
1450  // TSQR parameters (set as a sublist).
1451  //
1452  params->set ("TSQR implementation", *(tsqrAdaptor_.getValidParameters()),
1453  "TSQR implementation parameters.");
1454  //
1455  // Orthogonalization parameters
1456  //
1457  const bool defaultRandomizeNullSpace = true;
1458  params->set ("randomizeNullSpace", defaultRandomizeNullSpace,
1459  "Whether to fill in null space vectors with random data.");
1460 
1461  const bool defaultReorthogonalizeBlocks = true;
1462  params->set ("reorthogonalizeBlocks", defaultReorthogonalizeBlocks,
1463  "Whether to do block reorthogonalization as necessary.");
1464 
1465  // This parameter corresponds to the "blk_tol_" parameter in
1466  // Belos' DGKSOrthoManager. We choose the same default value.
1467  const magnitude_type defaultBlockReorthogThreshold =
1468  magnitude_type(10) * SCTM::squareroot (SCTM::eps());
1469  params->set ("blockReorthogThreshold", defaultBlockReorthogThreshold,
1470  "If reorthogonalizeBlocks==true, and if the norm of "
1471  "any column within a block decreases by this much or "
1472  "more after orthogonalization, we reorthogonalize.");
1473 
1474  // This parameter corresponds to the "sing_tol_" parameter in
1475  // Belos' DGKSOrthoManager. We choose the same default value.
1476  const magnitude_type defaultRelativeRankTolerance =
1477  Teuchos::as<magnitude_type>(10) * SCTM::eps();
1478 
1479  // If the relative rank tolerance is zero, then we will always
1480  // declare blocks to be numerically full rank, as long as no
1481  // singular values are zero.
1482  params->set ("relativeRankTolerance", defaultRelativeRankTolerance,
1483  "Relative tolerance to determine the numerical rank of a "
1484  "block when normalizing.");
1485 
1486  // See Stewart's 2008 paper on block Gram-Schmidt for a definition
1487  // of "orthogonalization fault."
1488  const bool defaultThrowOnReorthogFault = true;
1489  params->set ("throwOnReorthogFault", defaultThrowOnReorthogFault,
1490  "Whether to throw an exception if an orthogonalization "
1491  "fault occurs. This only matters if reorthogonalization "
1492  "is enabled (reorthogonalizeBlocks==true).");
1493 
1494  const bool defaultForceNonnegativeDiagonal = false;
1495  params->set ("forceNonnegativeDiagonal", defaultForceNonnegativeDiagonal,
1496  "Whether to force the R factor produced by the normalization "
1497  "step to have a nonnegative diagonal.");
1498 
1499  defaultParams_ = params;
1500  }
1501  return defaultParams_;
1502  }
1503 
1504  template<class Scalar, class MV>
1507  {
1508  using Teuchos::ParameterList;
1509  using Teuchos::RCP;
1510  using Teuchos::rcp;
1511 
1512  RCP<const ParameterList> defaultParams = getValidParameters();
1513  // Start with a clone of the default parameters.
1514  RCP<ParameterList> params = rcp (new ParameterList (*defaultParams));
1515 
1516  // Disable reorthogonalization and randomization of the null
1517  // space basis. Reorthogonalization tolerances don't matter,
1518  // since we aren't reorthogonalizing blocks in the fast
1519  // settings. We can leave the default values. Also,
1520  // (re)orthogonalization faults may only occur with
1521  // reorthogonalization, so we don't have to worry about the
1522  // "throwOnReorthogFault" setting.
1523  const bool randomizeNullSpace = false;
1524  params->set ("randomizeNullSpace", randomizeNullSpace);
1525  const bool reorthogonalizeBlocks = false;
1526  params->set ("reorthogonalizeBlocks", reorthogonalizeBlocks);
1527 
1528  return params;
1529  }
1530 
1531  template<class Scalar, class MV>
1532  int
1535  MV& Q,
1537  {
1538  int rank;
1539  try {
1540  // This call only computes the QR factorization X = Q B.
1541  // It doesn't compute the rank of X. That comes from
1542  // revealRank() below.
1543  tsqrAdaptor_.factorExplicit (X, Q, B, forceNonnegativeDiagonal_);
1544  // This call will only modify *B if *B on input is not of full
1545  // numerical rank.
1546  rank = tsqrAdaptor_.revealRank (Q, B, relativeRankTolerance_);
1547  } catch (std::exception& e) {
1548  throw TsqrOrthoError (e.what()); // Toss the exception up the chain.
1549  }
1550  return rank;
1551  }
1552 
1553  template<class Scalar, class MV>
1554  int
1558  {
1559  // Make space for the normalization coefficient. This will either
1560  // be a freshly allocated matrix (if B is null), or a view of the
1561  // 1x1 upper left submatrix of *B (if B is not null).
1562  mat_ptr B_out;
1563  if (B.is_null()) {
1564  B_out = Teuchos::rcp (new mat_type (1, 1));
1565  } else {
1566  const int theNumRows = B->numRows ();
1567  const int theNumCols = B->numCols ();
1569  theNumRows < 1 || theNumCols < 1, std::invalid_argument,
1570  "normalizeOne: Input matrix B must be at least 1 x 1, but "
1571  "is instead " << theNumRows << " x " << theNumCols << ".");
1572  // Create a view of the 1x1 upper left submatrix of *B.
1573  B_out = Teuchos::rcp (new mat_type (Teuchos::View, *B, 1, 1));
1574  }
1575 
1576  // Compute the norm of X, and write the result to B_out.
1577  std::vector<magnitude_type> theNorm (1, SCTM::zero());
1578  MVT::MvNorm (X, theNorm);
1579  (*B_out)(0,0) = theNorm[0];
1580 
1581  if (B.is_null()) {
1582  // The input matrix B is null, so assign B_out to it. If B was
1583  // not null on input, then B_out is a view of *B, so we don't
1584  // have to do anything here. Note that SerialDenseMatrix uses
1585  // raw pointers to store data and represent views, so we have to
1586  // be careful about scope.
1587  B = B_out;
1588  }
1589 
1590  // Scale X by its norm, if its norm is zero. Otherwise, do the
1591  // right thing based on whether the user wants us to fill the null
1592  // space with random vectors.
1593  if (theNorm[0] == SCTM::zero()) {
1594  // Make a view of the first column of Q, fill it with random
1595  // data, and normalize it. Throw away the resulting norm.
1596  if (randomizeNullSpace_) {
1597  MVT::MvRandom(X);
1598  MVT::MvNorm (X, theNorm);
1599  if (theNorm[0] == SCTM::zero()) {
1600  // It is possible that a random vector could have all zero
1601  // entries, but unlikely. We could try again, but it's also
1602  // possible that multiple tries could result in zero
1603  // vectors. We choose instead to give up.
1604  throw TsqrOrthoError("normalizeOne: a supposedly random "
1605  "vector has norm zero!");
1606  } else {
1607  // NOTE (mfh 09 Nov 2010) I'm assuming that dividing a
1608  // Scalar by a magnitude_type is defined and that it results
1609  // in a Scalar.
1610  const Scalar alpha = SCT::one() / theNorm[0];
1611  MVT::MvScale (X, alpha);
1612  }
1613  }
1614  return 0; // The rank of the matrix (actually just one vector) X.
1615  } else {
1616  // NOTE (mfh 09 Nov 2010) I'm assuming that dividing a Scalar by
1617  // a magnitude_type is defined and that it results in a Scalar.
1618  const Scalar alpha = SCT::one() / theNorm[0];
1619  MVT::MvScale (X, alpha);
1620  return 1; // The rank of the matrix (actually just one vector) X.
1621  }
1622  }
1623 
1624 
1625  template<class Scalar, class MV>
1626  void
1628  rawProject (MV& X,
1631  {
1632 #ifdef BELOS_TEUCHOS_TIME_MONITOR
1633  Teuchos::TimeMonitor timerMonitorNormalize(*timerProject_);
1634 #endif // BELOS_TEUCHOS_TIME_MONITOR
1635 
1636  // "Modified Gram-Schmidt" version of Block Gram-Schmidt.
1637  const int num_Q_blocks = Q.size();
1638  for (int i = 0; i < num_Q_blocks; ++i)
1639  {
1640  // TEUCHOS_TEST_FOR_EXCEPTION(C[i].is_null(), std::logic_error,
1641  // "TsqrOrthoManagerImpl::rawProject(): C["
1642  // << i << "] is null");
1643  // TEUCHOS_TEST_FOR_EXCEPTION(Q[i].is_null(), std::logic_error,
1644  // "TsqrOrthoManagerImpl::rawProject(): Q["
1645  // << i << "] is null");
1646  mat_type& Ci = *C[i];
1647  const MV& Qi = *Q[i];
1648  innerProd (Qi, X, Ci);
1649  MVT::MvTimesMatAddMv (-SCT::one(), Qi, Ci, SCT::one(), X);
1650  }
1651  }
1652 
1653 
1654  template<class Scalar, class MV>
1655  void
1657  rawProject (MV& X,
1658  const Teuchos::RCP<const MV>& Q,
1660  {
1661 #ifdef BELOS_TEUCHOS_TIME_MONITOR
1662  Teuchos::TimeMonitor timerMonitorNormalize(*timerProject_);
1663 #endif // BELOS_TEUCHOS_TIME_MONITOR
1664 
1665  // Block Gram-Schmidt
1666  innerProd (*Q, X, *C);
1667  MVT::MvTimesMatAddMv (-SCT::one(), *Q, *C, SCT::one(), X);
1668  }
1669 
1670  template<class Scalar, class MV>
1671  int
1674  MV& Q,
1676  const bool outOfPlace)
1677  {
1678  using Teuchos::Range1D;
1679  using Teuchos::RCP;
1680  using Teuchos::rcp;
1681  using Teuchos::ScalarTraits;
1682  using Teuchos::tuple;
1683 
1684  const int numCols = MVT::GetNumberVecs (X);
1685  if (numCols == 0) {
1686  return 0; // Fast exit for an empty input matrix.
1687  }
1688 
1689  // We allow Q to have more columns than X. In that case, we only
1690  // touch the first numCols columns of Q.
1692  MVT::GetNumberVecs (Q) < numCols, std::invalid_argument,
1693  "TsqrOrthoManagerImpl::normalizeImpl: Q has "
1694  << MVT::GetNumberVecs(Q) << " columns. This is too "
1695  "few, since X has " << numCols << " columns.");
1696  // TSQR wants a Q with the same number of columns as X, so have it
1697  // work on a nonconstant view of Q with the same number of columns
1698  // as X.
1699  RCP<MV> Q_view = MVT::CloneViewNonConst (Q, Range1D (0, numCols-1));
1700 
1701  // Make space for the normalization coefficients. This will
1702  // either be a freshly allocated matrix (if B is null), or a view
1703  // of the appropriately sized upper left submatrix of *B (if B is
1704  // not null).
1705  mat_ptr B_out;
1706  if (B.is_null ()) {
1707  B_out = rcp (new mat_type (numCols, numCols));
1708  } else {
1709  // Make sure that B is no smaller than numCols x numCols.
1711  B->numRows() < numCols || B->numCols() < numCols, std::invalid_argument,
1712  "TsqrOrthoManagerImpl::normalizeImpl: Input matrix B must be at least "
1713  << numCols << " x " << numCols << ", but is instead " << B->numRows ()
1714  << " x " << B->numCols() << ".");
1715  // Create a view of the numCols x numCols upper left submatrix
1716  // of *B. TSQR will write the normalization coefficients there.
1717  B_out = rcp (new mat_type (Teuchos::View, *B, numCols, numCols));
1718  }
1719 
1720  // Compute rank-revealing decomposition (in this case, TSQR of X
1721  // followed by SVD of the R factor and appropriate updating of the
1722  // resulting Q factor) of X. X is modified in place and filled
1723  // with garbage, and Q_view contains the resulting explicit Q
1724  // factor. Later, we will copy this back into X.
1725  //
1726  // The matrix *B_out will only be upper triangular if X is of full
1727  // numerical rank. Otherwise, the entries below the diagonal may
1728  // be filled in as well.
1729  const int rank = rawNormalize (X, *Q_view, *B_out);
1730  if (B.is_null ()) {
1731  // The input matrix B is null, so assign B_out to it. If B was
1732  // not null on input, then B_out is a view of *B, so we don't
1733  // have to do anything here. Note that SerialDenseMatrix uses
1734  // raw pointers to store data and represent views, so we have to
1735  // be careful about scope.
1736  B = B_out;
1737  }
1738 
1740  rank < 0 || rank > numCols, std::logic_error,
1741  "Belos::TsqrOrthoManagerImpl::normalizeImpl: rawNormalize returned rank "
1742  " = " << rank << " for a matrix X with " << numCols << " columns. "
1743  "Please report this bug to the Belos developers.");
1744 
1745  // If X is full rank or we don't want to replace its null space
1746  // basis with random vectors, then we're done.
1747  if (rank == numCols || ! randomizeNullSpace_) {
1748  // If we're supposed to be working in place in X, copy the
1749  // results back from Q_view into X.
1750  if (! outOfPlace) {
1751  MVT::Assign (*Q_view, X);
1752  }
1753  return rank;
1754  }
1755 
1756  if (randomizeNullSpace_ && rank < numCols) {
1757  // X wasn't full rank. Replace the null space basis of X (in
1758  // the last numCols-rank columns of Q_view) with random data,
1759  // project it against the first rank columns of Q_view, and
1760  // normalize.
1761  //
1762  // Number of columns to fill with random data.
1763  const int nullSpaceNumCols = numCols - rank;
1764  // Inclusive range of indices of columns of X to fill with
1765  // random data.
1766  Range1D nullSpaceIndices (rank, numCols-1);
1767 
1768  // rawNormalize wrote the null space basis vectors into Q_view.
1769  // We continue to work in place in Q_view by writing the random
1770  // data there and (if there is a nontrival column space)
1771  // projecting in place against the column space basis vectors
1772  // (also in Q_view).
1773  RCP<MV> Q_null = MVT::CloneViewNonConst (*Q_view, nullSpaceIndices);
1774  // Replace the null space basis with random data.
1775  MVT::MvRandom (*Q_null);
1776 
1777  // Make sure that the "random" data isn't all zeros. This is
1778  // statistically nearly impossible, but we test for debugging
1779  // purposes.
1780  {
1781  std::vector<magnitude_type> norms (MVT::GetNumberVecs (*Q_null));
1782  MVT::MvNorm (*Q_null, norms);
1783 
1784  bool anyZero = false;
1785  typedef typename std::vector<magnitude_type>::const_iterator iter_type;
1786  for (iter_type it = norms.begin(); it != norms.end(); ++it) {
1787  if (*it == SCTM::zero()) {
1788  anyZero = true;
1789  }
1790  }
1791  if (anyZero) {
1792  std::ostringstream os;
1793  os << "TsqrOrthoManagerImpl::normalizeImpl: "
1794  "We are being asked to randomize the null space, for a matrix "
1795  "with " << numCols << " columns and reported column rank "
1796  << rank << ". The inclusive range of columns to fill with "
1797  "random data is [" << nullSpaceIndices.lbound() << ","
1798  << nullSpaceIndices.ubound() << "]. After filling the null "
1799  "space vectors with random numbers, at least one of the vectors"
1800  " has norm zero. Here are the norms of all the null space "
1801  "vectors: [";
1802  for (iter_type it = norms.begin(); it != norms.end(); ++it) {
1803  os << *it;
1804  if (it+1 != norms.end())
1805  os << ", ";
1806  }
1807  os << "].) There is a tiny probability that this could happen "
1808  "randomly, but it is likely a bug. Please report it to the "
1809  "Belos developers, especially if you are able to reproduce the "
1810  "behavior.";
1811  TEUCHOS_TEST_FOR_EXCEPTION(anyZero, TsqrOrthoError, os.str());
1812  }
1813  }
1814 
1815  if (rank > 0) {
1816  // Project the random data against the column space basis of
1817  // X, using a simple block projection ("Block Classical
1818  // Gram-Schmidt"). This is accurate because we've already
1819  // orthogonalized the column space basis of X nearly to
1820  // machine precision via a QR factorization (TSQR) with
1821  // accuracy comparable to Householder QR.
1822  RCP<const MV> Q_col = MVT::CloneView (*Q_view, Range1D (0, rank-1));
1823 
1824  // Temporary storage for projection coefficients. We don't
1825  // need to keep them, since they represent the null space
1826  // basis (for which the coefficients are logically zero).
1827  mat_ptr C_null (new mat_type (rank, nullSpaceNumCols));
1828  rawProject (*Q_null, Q_col, C_null);
1829  }
1830  // Normalize the projected random vectors, so that they are
1831  // mutually orthogonal (as well as orthogonal to the column
1832  // space basis of X). We use X for the output of the
1833  // normalization: for out-of-place normalization (outOfPlace ==
1834  // true), X is overwritten with "invalid values" anyway, and for
1835  // in-place normalization (outOfPlace == false), we want the
1836  // result to be in X anyway.
1837  RCP<MV> X_null = MVT::CloneViewNonConst (X, nullSpaceIndices);
1838  // Normalization coefficients for projected random vectors.
1839  // Will be thrown away.
1840  mat_type B_null (nullSpaceNumCols, nullSpaceNumCols);
1841  // Write the normalized vectors to X_null (in X).
1842  const int nullSpaceBasisRank = rawNormalize (*Q_null, *X_null, B_null);
1843 
1844  // It's possible, but unlikely, that X_null doesn't have full
1845  // rank (after the projection step). We could recursively fill
1846  // in more random vectors until we finally get a full rank
1847  // matrix, but instead we just throw an exception.
1848  //
1849  // NOTE (mfh 08 Nov 2010) Perhaps we should deal with this case
1850  // more elegantly. Recursion might be one way to solve it, but
1851  // be sure to check that the recursion will terminate. We could
1852  // do this by supplying an additional argument to rawNormalize,
1853  // which is the null space basis rank from the previous
1854  // iteration. The rank has to decrease each time, or the
1855  // recursion may go on forever.
1856  if (nullSpaceBasisRank < nullSpaceNumCols) {
1857  std::vector<magnitude_type> norms (MVT::GetNumberVecs(*X_null));
1858  MVT::MvNorm (*X_null, norms);
1859  std::ostringstream os;
1860  os << "TsqrOrthoManagerImpl::normalizeImpl: "
1861  << "We are being asked to randomize the null space, "
1862  << "for a matrix with " << numCols << " columns and "
1863  << "column rank " << rank << ". After projecting and "
1864  << "normalizing the generated random vectors, they "
1865  << "only have rank " << nullSpaceBasisRank << ". They"
1866  << " should have full rank " << nullSpaceNumCols
1867  << ". (The inclusive range of columns to fill with "
1868  << "random data is [" << nullSpaceIndices.lbound()
1869  << "," << nullSpaceIndices.ubound() << "]. The "
1870  << "column norms of the resulting Q factor are: [";
1871  for (typename std::vector<magnitude_type>::size_type k = 0;
1872  k < norms.size(); ++k) {
1873  os << norms[k];
1874  if (k != norms.size()-1) {
1875  os << ", ";
1876  }
1877  }
1878  os << "].) There is a tiny probability that this could "
1879  << "happen randomly, but it is likely a bug. Please "
1880  << "report it to the Belos developers, especially if "
1881  << "you are able to reproduce the behavior.";
1882 
1883  TEUCHOS_TEST_FOR_EXCEPTION(nullSpaceBasisRank < nullSpaceNumCols,
1884  TsqrOrthoError, os.str ());
1885  }
1886  // If we're normalizing out of place, copy the X_null
1887  // vectors back into Q_null; the Q_col vectors are already
1888  // where they are supposed to be in that case.
1889  //
1890  // If we're normalizing in place, leave X_null alone (it's
1891  // already where it needs to be, in X), but copy Q_col back
1892  // into the first rank columns of X.
1893  if (outOfPlace) {
1894  MVT::Assign (*X_null, *Q_null);
1895  } else if (rank > 0) {
1896  // MVT::Assign() doesn't accept empty ranges of columns.
1897  RCP<const MV> Q_col = MVT::CloneView (*Q_view, Range1D (0, rank-1));
1898  RCP<MV> X_col = MVT::CloneViewNonConst (X, Range1D (0, rank-1));
1899  MVT::Assign (*Q_col, *X_col);
1900  }
1901  }
1902  return rank;
1903  }
1904 
1905 
1906  template<class Scalar, class MV>
1907  void
1909  checkProjectionDims (int& ncols_X,
1910  int& num_Q_blocks,
1911  int& ncols_Q_total,
1912  const MV& X,
1914  {
1915  // First assign to temporary values, so the function won't
1916  // commit any externally visible side effects unless it will
1917  // return normally (without throwing an exception). (I'm being
1918  // cautious; MVT::GetNumberVecs() probably shouldn't have any
1919  // externally visible side effects, unless it is logging to a
1920  // file or something.)
1921  int the_ncols_X, the_num_Q_blocks, the_ncols_Q_total;
1922  the_num_Q_blocks = Q.size();
1923  the_ncols_X = MVT::GetNumberVecs (X);
1924 
1925  // Compute the total number of columns of all the Q[i] blocks.
1926  the_ncols_Q_total = 0;
1927  // You should be angry if your compiler doesn't support type
1928  // inference ("auto"). That's why I need this awful typedef.
1929  using Teuchos::ArrayView;
1930  using Teuchos::RCP;
1931  typedef typename ArrayView<RCP<const MV> >::const_iterator iter_type;
1932  for (iter_type it = Q.begin(); it != Q.end(); ++it) {
1933  const MV& Qi = **it;
1934  the_ncols_Q_total += MVT::GetNumberVecs (Qi);
1935  }
1936 
1937  // Commit temporary values to the output arguments.
1938  ncols_X = the_ncols_X;
1939  num_Q_blocks = the_num_Q_blocks;
1940  ncols_Q_total = the_ncols_Q_total;
1941  }
1942 
1943 } // namespace Belos
1944 
1945 #endif // __BelosTsqrOrthoManagerImpl_hpp
1946 
Teuchos::ScalarTraits< magnitude_type > SCTM
magnitude_type relativeRankTolerance_
Relative tolerance for measuring the numerical rank of a matrix.
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.
Interface of callback invoked by TsqrOrthoManager on reorthogonalization.
bool is_null(const boost::shared_ptr< T > &p)
magnitude_type blockReorthogThreshold_
Relative reorthogonalization threshold in Block Gram-Schmidt.
void project(MV &X, Teuchos::Array< mat_ptr > C, Teuchos::ArrayView< Teuchos::RCP< const MV > > Q)
Compute and .
void norm(const MV &X, std::vector< magnitude_type > &normVec) const
Compute the 2-norm of each column j of X.
TsqrOrthoManagerImpl(const Teuchos::RCP< Teuchos::ParameterList > &params, const std::string &label)
Constructor (that sets user-specified parameters).
void checkProjectionDims(int &ncols_X, int &num_Q_blocks, int &ncols_Q_total, const MV &X, Teuchos::ArrayView< Teuchos::RCP< const MV > > Q) const
Return through output arguments some relevant dimension information about X and Q.
static void clearCounter(const std::string &name)
magnitude_type orthogError(const MV &X1, const MV &X2) const
Return the Frobenius norm of the inner product of X1 with itself.
Teuchos::SerialDenseMatrix< int, Scalar > mat_type
Type of the projection and normalization coefficients.
Teuchos::RCP< MV > Q_
Scratch space for TSQR.
T & get(ParameterList &l, const std::string &name)
static RCP< Time > getNewCounter(const std::string &name)
void setParameterList(const Teuchos::RCP< Teuchos::ParameterList > &params)
Set parameters from the given parameter list.
int projectAndNormalizeImpl(MV &X_in, MV &X_out, const bool outOfPlace, Teuchos::Array< mat_ptr > C, mat_ptr B, Teuchos::ArrayView< Teuchos::RCP< const MV > > Q)
Implementation of projection and normalization.
magnitude_type eps_
Machine precision for Scalar.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Teuchos::RCP< const Teuchos::ParameterList > getFastParameters()
Get &quot;fast&quot; parameters for TsqrOrthoManagerImpl.
void rawProject(MV &X, Teuchos::ArrayView< Teuchos::RCP< const MV > > Q, Teuchos::ArrayView< mat_ptr > C) const
One projection pass of X against the Q[i] blocks.
TSQR-based OrthoManager subclass implementation.
Declaration of basic traits for the multivector type.
void setReorthogonalizationCallback(const Teuchos::RCP< ReorthogonalizationCallback< Scalar > > &callback)
Set callback to be invoked on reorthogonalization.
Teuchos::RCP< ReorthogonalizationCallback< Scalar > > reorthogCallback_
Callback invoked if reorthogonalization is necessary.
Error in TsqrOrthoManager or TsqrOrthoManagerImpl.
ScalarTraits< ScalarType >::magnitudeType NRM2(const OrdinalType &n, const ScalarType *x, const OrdinalType &incx) const
bool forceNonnegativeDiagonal_
Force R factor of normalization to have a nonnegative diagonal.
int normalize(MV &X, mat_ptr B)
Orthogonalize the columns of X in place.
bool throwOnReorthogFault_
Whether to throw an exception on a orthogonalization fault.
void setLabel(const std::string &label)
Set the label for timers.
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 .
ScalarTraits< ScalarType >::magnitudeType normFrobenius() const
static int GetNumberVecs(const MV &mv)
Obtain the number of vectors in mv.
Teuchos::ScalarTraits< Scalar >::magnitudeType magnitude_type
The type of a norm result.
Teuchos::RCP< const Teuchos::ParameterList > getValidParameters() const
Default valid parameter list.
tsqr_adaptor_type tsqrAdaptor_
Interface to TSQR implementation.
Traits class which defines basic operations on multivectors.
Teuchos::RCP< const Teuchos::ParameterList > defaultParams_
Default configuration parameters.
Scalar scalar_type
The template parameter of this class; the type of an inner product result.
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
Teuchos::ScalarTraits< Scalar > SCT
bool is_null(const RCP< T > &p)
virtual void operator()(Teuchos::ArrayView< magnitude_type > normsBeforeFirstPass, Teuchos::ArrayView< magnitude_type > normsAfterFirstPass)=0
Callback invoked by TsqrOrthoManager on reorthogonalization.
int putScalar(const ScalarType value=Teuchos::ScalarTraits< ScalarType >::zero())
const std::string & getLabel() const
Get the label for timers (if timers are enabled).
magnitude_type orthonormError(const MV &X) const
Return .
Exception thrown to signal error in an orthogonalization manager method.
Teuchos::ScalarTraits< Scalar >::magnitudeType magnitude_type
magnitude_type relativeRankTolerance() const
Relative tolerance for determining (via the SVD) whether a block is of full numerical rank...
void resize(size_type new_size, const value_type &x=value_type())
TsqrOrthoError(const std::string &what_arg)
int normalizeOne(MV &X, mat_ptr B) const
Normalize a &quot;multivector&quot; of only one column.
OrdinalType numCols() const
int normalizeImpl(MV &X, MV &Q, mat_ptr B, const bool outOfPlace)
Normalize X into Q*B, with out-of-place option.
Teuchos::RCP< Teuchos::ParameterList > params_
Configuration parameters.
virtual ~ReorthogonalizationCallback()
Destructor (virtual for memory safety of derived classes)
Templated virtual class for providing orthogonalization/orthonormalization methods.
int rawNormalize(MV &X, MV &Q, mat_type &B)
One out-of-place normalization pass.
bool reorthogonalizeBlocks_
Whether to reorthogonalize blocks at all.
TsqrOrthoFault(const std::string &what_arg)
void raiseReorthogFault(const std::vector< magnitude_type > &normsAfterFirstPass, const std::vector< magnitude_type > &normsAfterSecondPass, const std::vector< int > &faultIndices)
Throw an exception indicating a reorthgonalization fault.
std::string label_
Label for timers (if timers are used).
magnitude_type blockReorthogThreshold() const
Relative tolerance for triggering a block reorthogonalization.
void allocateProjectionCoefficients(Teuchos::Array< mat_ptr > &C, Teuchos::ArrayView< Teuchos::RCP< const MV > > Q, const MV &X, const bool attemptToRecycle=true) const
Allocate projection coefficients.
int shape(OrdinalType numRows, OrdinalType numCols)
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.
void innerProd(const MV &X, const MV &Y, mat_type &Z) const
Euclidean inner product.
Belos header file which uses auto-configuration information to include necessary C++ headers...
Orthogonalization fault.
bool randomizeNullSpace_
Whether to fill null space vectors with random data.
OrdinalType numRows() const
MultiVecTraits< Scalar, MV > MVT