Belos  Version of the Day
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"
53 #include "Teuchos_LAPACK.hpp"
54 #include "Teuchos_ParameterList.hpp"
55 #include "Teuchos_ParameterListAcceptorDefaultBase.hpp"
56 #ifdef BELOS_TEUCHOS_TIME_MONITOR
57 # include "Teuchos_TimeMonitor.hpp"
58 #endif // BELOS_TEUCHOS_TIME_MONITOR
59 #include <algorithm>
60 #include <functional> // std::binary_function
61 
62 namespace Belos {
63 
67  class TsqrOrthoError : public OrthoError {
68  public:
69  TsqrOrthoError (const std::string& what_arg) :
70  OrthoError (what_arg) {}
71  };
72 
92  class TsqrOrthoFault : public OrthoError {
93  public:
94  TsqrOrthoFault (const std::string& what_arg) :
95  OrthoError (what_arg) {}
96  };
97 
130  template<class Scalar>
132  public std::binary_function<Teuchos::ArrayView<typename Teuchos::ScalarTraits<Scalar>::magnitudeType>,
133  Teuchos::ArrayView<typename Teuchos::ScalarTraits<Scalar>::magnitudeType>,
134  void>
135  {
136  public:
138  typedef Scalar scalar_type;
143  typedef typename Teuchos::ScalarTraits<Scalar>::magnitudeType magnitude_type;
144 
146  virtual ~ReorthogonalizationCallback ();
147 
152  virtual void
153  operator() (Teuchos::ArrayView<magnitude_type> normsBeforeFirstPass,
154  Teuchos::ArrayView<magnitude_type> normsAfterFirstPass) = 0;
155  };
156 
157  template<class Scalar>
159 
191  template<class Scalar, class MV>
193  public Teuchos::ParameterListAcceptorDefaultBase {
194  public:
195  typedef Scalar scalar_type;
196  typedef typename Teuchos::ScalarTraits<Scalar>::magnitudeType magnitude_type;
197  typedef MV multivector_type;
199  typedef Teuchos::SerialDenseMatrix<int, Scalar> mat_type;
200  typedef Teuchos::RCP<mat_type> mat_ptr;
201 
202  private:
203  typedef Teuchos::ScalarTraits<Scalar> SCT;
204  typedef Teuchos::ScalarTraits<magnitude_type> SCTM;
207  typedef typename MVT::tsqr_adaptor_type tsqr_adaptor_type;
208 
209  public:
217  Teuchos::RCP<const Teuchos::ParameterList> getValidParameters () const;
218 
220  void setParameterList (const Teuchos::RCP<Teuchos::ParameterList>& params);
221 
232  Teuchos::RCP<const Teuchos::ParameterList> getFastParameters ();
233 
250  TsqrOrthoManagerImpl (const Teuchos::RCP<Teuchos::ParameterList>& params,
251  const std::string& label);
252 
257  TsqrOrthoManagerImpl (const std::string& label);
258 
278  void
280  {
281  reorthogCallback_ = callback;
282  }
283 
291  void setLabel (const std::string& label) {
292  if (label != label_) {
293  label_ = label;
294 
295 #ifdef BELOS_TEUCHOS_TIME_MONITOR
296  clearTimer (label, "All orthogonalization");
297  clearTimer (label, "Projection");
298  clearTimer (label, "Normalization");
299 
300  timerOrtho_ = makeTimer (label, "All orthogonalization");
301  timerProject_ = makeTimer (label, "Projection");
302  timerNormalize_ = makeTimer (label, "Normalization");
303 #endif // BELOS_TEUCHOS_TIME_MONITOR
304  }
305  }
306 
308  const std::string& getLabel () const { return label_; }
309 
318  void
319  innerProd (const MV& X, const MV& Y, mat_type& Z) const
320  {
321  MVT::MvTransMv (SCT::one(), X, Y, Z);
322  }
323 
341  void
342  norm (const MV& X, std::vector<magnitude_type>& normVec) const;
343 
353  void
354  project (MV& X,
355  Teuchos::Array<mat_ptr> C,
356  Teuchos::ArrayView<Teuchos::RCP<const MV> > Q);
357 
371  int normalize (MV& X, mat_ptr B);
372 
391  int
392  normalizeOutOfPlace (MV& X, MV& Q, mat_ptr B);
393 
407  int
409  Teuchos::Array<mat_ptr> C,
410  mat_ptr B,
411  Teuchos::ArrayView<Teuchos::RCP<const MV> > Q)
412  {
413  // "false" means we work on X in place. The second argument is
414  // not read or written in that case.
415  return projectAndNormalizeImpl (X, X, false, C, B, Q);
416  }
417 
437  int
439  MV& X_out,
440  Teuchos::Array<mat_ptr> C,
441  mat_ptr B,
442  Teuchos::ArrayView<Teuchos::RCP<const MV> > Q)
443  {
444  // "true" means we work on X_in out of place, writing the
445  // results into X_out.
446  return projectAndNormalizeImpl (X_in, X_out, true, C, B, Q);
447  }
448 
453  magnitude_type
454  orthonormError (const MV &X) const
455  {
456  const Scalar ONE = SCT::one();
457  const int ncols = MVT::GetNumberVecs(X);
458  mat_type XTX (ncols, ncols);
459  innerProd (X, X, XTX);
460  for (int k = 0; k < ncols; ++k) {
461  XTX(k,k) -= ONE;
462  }
463  return XTX.normFrobenius();
464  }
465 
467  magnitude_type
468  orthogError (const MV &X1,
469  const MV &X2) const
470  {
471  const int ncols_X1 = MVT::GetNumberVecs (X1);
472  const int ncols_X2 = MVT::GetNumberVecs (X2);
473  mat_type X1_T_X2 (ncols_X1, ncols_X2);
474  innerProd (X1, X2, X1_T_X2);
475  return X1_T_X2.normFrobenius();
476  }
477 
481  magnitude_type blockReorthogThreshold() const { return blockReorthogThreshold_; }
482 
485  magnitude_type relativeRankTolerance() const { return relativeRankTolerance_; }
486 
487  private:
489  Teuchos::RCP<Teuchos::ParameterList> params_;
490 
492  mutable Teuchos::RCP<const Teuchos::ParameterList> defaultParams_;
493 
495  std::string label_;
496 
498  tsqr_adaptor_type tsqrAdaptor_;
499 
509  Teuchos::RCP<MV> Q_;
510 
512  magnitude_type eps_;
513 
517  bool randomizeNullSpace_;
518 
524  bool reorthogonalizeBlocks_;
525 
529  bool throwOnReorthogFault_;
530 
532  magnitude_type blockReorthogThreshold_;
533 
535  magnitude_type relativeRankTolerance_;
536 
543  bool forceNonnegativeDiagonal_;
544 
545 #ifdef BELOS_TEUCHOS_TIME_MONITOR
546  Teuchos::RCP<Teuchos::Time> timerOrtho_;
548 
550  Teuchos::RCP<Teuchos::Time> timerProject_;
551 
553  Teuchos::RCP<Teuchos::Time> timerNormalize_;
554 #endif // BELOS_TEUCHOS_TIME_MONITOR
555 
557  Teuchos::RCP<ReorthogonalizationCallback<Scalar> > reorthogCallback_;
558 
559 #ifdef BELOS_TEUCHOS_TIME_MONITOR
560  static Teuchos::RCP<Teuchos::Time>
569  makeTimer (const std::string& prefix,
570  const std::string& timerName)
571  {
572  const std::string timerLabel =
573  prefix.empty() ? timerName : (prefix + ": " + timerName);
574  return Teuchos::TimeMonitor::getNewCounter (timerLabel);
575  }
576 
582  void
583  clearTimer (const std::string& prefix,
584  const std::string& timerName)
585  {
586  const std::string timerLabel =
587  prefix.empty() ? timerName : (prefix + ": " + timerName);
588  Teuchos::TimeMonitor::clearCounter (timerLabel);
589  }
590 #endif // BELOS_TEUCHOS_TIME_MONITOR
591 
593  void
594  raiseReorthogFault (const std::vector<magnitude_type>& normsAfterFirstPass,
595  const std::vector<magnitude_type>& normsAfterSecondPass,
596  const std::vector<int>& faultIndices);
597 
607  void
608  checkProjectionDims (int& ncols_X,
609  int& num_Q_blocks,
610  int& ncols_Q_total,
611  const MV& X,
612  Teuchos::ArrayView<Teuchos::RCP<const MV> > Q) const;
613 
624  void
625  allocateProjectionCoefficients (Teuchos::Array<mat_ptr>& C,
626  Teuchos::ArrayView<Teuchos::RCP<const MV> > Q,
627  const MV& X,
628  const bool attemptToRecycle = true) const;
629 
638  int
639  projectAndNormalizeImpl (MV& X_in,
640  MV& X_out,
641  const bool outOfPlace,
642  Teuchos::Array<mat_ptr> C,
643  mat_ptr B,
644  Teuchos::ArrayView<Teuchos::RCP<const MV> > Q);
645 
651  void
652  rawProject (MV& X,
653  Teuchos::ArrayView<Teuchos::RCP<const MV> > Q,
654  Teuchos::ArrayView<mat_ptr> C) const;
655 
657  void
658  rawProject (MV& X,
659  const Teuchos::RCP<const MV>& Q,
660  const mat_ptr& C) const;
661 
688  int rawNormalize (MV& X, MV& Q, mat_type& B);
689 
707  int normalizeOne (MV& X, mat_ptr B) const;
708 
736  int normalizeImpl (MV& X, MV& Q, mat_ptr B, const bool outOfPlace);
737  };
738 
739  template<class Scalar, class MV>
740  void
742  setParameterList (const Teuchos::RCP<Teuchos::ParameterList>& params)
743  {
744  using Teuchos::ParameterList;
745  using Teuchos::parameterList;
746  using Teuchos::RCP;
747  using Teuchos::sublist;
748  typedef magnitude_type M; // abbreviation.
749 
750  RCP<const ParameterList> defaultParams = getValidParameters ();
751  // Sublist of TSQR implementation parameters; to get below.
752  RCP<ParameterList> tsqrParams;
753 
754  RCP<ParameterList> theParams;
755  if (params.is_null()) {
756  theParams = parameterList (*defaultParams);
757  } else {
758  theParams = params;
759 
760  // Don't call validateParametersAndSetDefaults(); we prefer to
761  // ignore parameters that we don't recognize, at least for now.
762  // However, we do fill in missing parameters with defaults.
763 
764  randomizeNullSpace_ =
765  theParams->get<bool> ("randomizeNullSpace",
766  defaultParams->get<bool> ("randomizeNullSpace"));
767  reorthogonalizeBlocks_ =
768  theParams->get<bool> ("reorthogonalizeBlocks",
769  defaultParams->get<bool> ("reorthogonalizeBlocks"));
770  throwOnReorthogFault_ =
771  theParams->get<bool> ("throwOnReorthogFault",
772  defaultParams->get<bool> ("throwOnReorthogFault"));
773  blockReorthogThreshold_ =
774  theParams->get<M> ("blockReorthogThreshold",
775  defaultParams->get<M> ("blockReorthogThreshold"));
776  relativeRankTolerance_ =
777  theParams->get<M> ("relativeRankTolerance",
778  defaultParams->get<M> ("relativeRankTolerance"));
779  forceNonnegativeDiagonal_ =
780  theParams->get<bool> ("forceNonnegativeDiagonal",
781  defaultParams->get<bool> ("forceNonnegativeDiagonal"));
782 
783  // Get the sublist of TSQR implementation parameters. Use the
784  // default sublist if one isn't provided.
785  if (! theParams->isSublist ("TSQR implementation")) {
786  theParams->set ("TSQR implementation",
787  defaultParams->sublist ("TSQR implementation"));
788  }
789  tsqrParams = sublist (theParams, "TSQR implementation", true);
790  }
791 
792  // Send the TSQR implementation parameters to the TSQR adaptor.
793  tsqrAdaptor_.setParameterList (tsqrParams);
794 
795  // Save the input parameter list.
796  setMyParamList (theParams);
797  }
798 
799  template<class Scalar, class MV>
801  TsqrOrthoManagerImpl (const Teuchos::RCP<Teuchos::ParameterList>& params,
802  const std::string& label) :
803  label_ (label),
804  Q_ (Teuchos::null), // Initialized on demand
805  eps_ (SCTM::eps()), // Machine precision
806  randomizeNullSpace_ (true),
807  reorthogonalizeBlocks_ (true),
808  throwOnReorthogFault_ (false),
809  blockReorthogThreshold_ (0),
810  relativeRankTolerance_ (0),
811  forceNonnegativeDiagonal_ (false)
812  {
813  setParameterList (params); // This also sets tsqrAdaptor_'s parameters.
814 
815 #ifdef BELOS_TEUCHOS_TIME_MONITOR
816  timerOrtho_ = makeTimer (label, "All orthogonalization");
817  timerProject_ = makeTimer (label, "Projection");
818  timerNormalize_ = makeTimer (label, "Normalization");
819 #endif // BELOS_TEUCHOS_TIME_MONITOR
820  }
821 
822  template<class Scalar, class MV>
824  TsqrOrthoManagerImpl (const std::string& label) :
825  label_ (label),
826  Q_ (Teuchos::null), // Initialized on demand
827  eps_ (SCTM::eps()), // Machine precision
828  randomizeNullSpace_ (true),
829  reorthogonalizeBlocks_ (true),
830  throwOnReorthogFault_ (false),
831  blockReorthogThreshold_ (0),
832  relativeRankTolerance_ (0),
833  forceNonnegativeDiagonal_ (false)
834  {
835  setParameterList (Teuchos::null); // Set default parameters.
836 
837 #ifdef BELOS_TEUCHOS_TIME_MONITOR
838  timerOrtho_ = makeTimer (label, "All orthogonalization");
839  timerProject_ = makeTimer (label, "Projection");
840  timerNormalize_ = makeTimer (label, "Normalization");
841 #endif // BELOS_TEUCHOS_TIME_MONITOR
842  }
843 
844  template<class Scalar, class MV>
845  void
847  norm (const MV& X, std::vector<magnitude_type>& normVec) const
848  {
849  const int numCols = MVT::GetNumberVecs (X);
850  // std::vector<T>::size_type is unsigned; int is signed. Mixed
851  // unsigned/signed comparisons trigger compiler warnings.
852  if (normVec.size() < static_cast<size_t>(numCols))
853  normVec.resize (numCols); // Resize normvec if necessary.
854  MVT::MvNorm (X, normVec);
855  }
856 
857  template<class Scalar, class MV>
858  void
860  Teuchos::Array<mat_ptr> C,
861  Teuchos::ArrayView<Teuchos::RCP<const MV> > Q)
862  {
863 #ifdef BELOS_TEUCHOS_TIME_MONITOR
864  // "Projection" only happens in rawProject(), so we only time
865  // projection inside rawProject(). However, we count the time
866  // spend in project() as part of the whole orthogonalization.
867  //
868  // If project() is called from projectAndNormalize(), the
869  // TimeMonitor won't start timerOrtho_, because it is already
870  // running in projectAndNormalize().
871  Teuchos::TimeMonitor timerMonitorOrtho(*timerOrtho_);
872 #endif // BELOS_TEUCHOS_TIME_MONITOR
873 
874  int ncols_X, num_Q_blocks, ncols_Q_total;
875  checkProjectionDims (ncols_X, num_Q_blocks, ncols_Q_total, X, Q);
876  // Test for quick exit: any dimension of X is zero, or there are
877  // zero Q blocks, or the total number of columns of the Q blocks
878  // is zero.
879  if (ncols_X == 0 || num_Q_blocks == 0 || ncols_Q_total == 0)
880  return;
881 
882  // Make space for first-pass projection coefficients
883  allocateProjectionCoefficients (C, Q, X, true);
884 
885  // We only use columnNormsBefore and compute pre-projection column
886  // norms if doing block reorthogonalization.
887  std::vector<magnitude_type> columnNormsBefore (ncols_X, magnitude_type(0));
888  if (reorthogonalizeBlocks_)
889  MVT::MvNorm (X, columnNormsBefore);
890 
891  // Project (first block orthogonalization step):
892  // C := Q^* X, X := X - Q C.
893  rawProject (X, Q, C);
894 
895  // If we are doing block reorthogonalization, reorthogonalize X if
896  // necessary.
897  if (reorthogonalizeBlocks_) {
898  std::vector<magnitude_type> columnNormsAfter (ncols_X, magnitude_type(0));
899  MVT::MvNorm (X, columnNormsAfter);
900 
901  // Relative block reorthogonalization threshold.
902  const magnitude_type relThres = blockReorthogThreshold();
903  // Reorthogonalize X if any of its column norms decreased by a
904  // factor more than the block reorthogonalization threshold.
905  // Don't bother trying to subset the columns; that will make the
906  // columns noncontiguous and thus hinder BLAS 3 optimizations.
907  bool reorthogonalize = false;
908  for (int j = 0; j < ncols_X; ++j) {
909  if (columnNormsAfter[j] < relThres * columnNormsBefore[j]) {
910  reorthogonalize = true;
911  break;
912  }
913  }
914  if (reorthogonalize) {
915  // Notify the caller via callback about the need for
916  // reorthogonalization.
917  if (! reorthogCallback_.is_null()) {
918  reorthogCallback_->operator() (Teuchos::arrayViewFromVector (columnNormsBefore),
919  Teuchos::arrayViewFromVector (columnNormsAfter));
920  }
921  // Second-pass projection coefficients
922  Teuchos::Array<mat_ptr> C2;
923  allocateProjectionCoefficients (C2, Q, X, false);
924 
925  // Perform the second projection pass:
926  // C2 = Q' X, X = X - Q*C2
927  rawProject (X, Q, C2);
928  // Update the projection coefficients
929  for (int k = 0; k < num_Q_blocks; ++k)
930  *C[k] += *C2[k];
931  }
932  }
933  }
934 
935 
936  template<class Scalar, class MV>
937  int
939  {
940  using Teuchos::Range1D;
941  using Teuchos::RCP;
942 
943 #ifdef BELOS_TEUCHOS_TIME_MONITOR
944  Teuchos::TimeMonitor timerMonitorNormalize(*timerNormalize_);
945  // If normalize() is called internally -- i.e., called from
946  // projectAndNormalize() -- the timer will not be started or
947  // stopped, because it is already running. TimeMonitor handles
948  // recursive invocation by doing nothing.
949  Teuchos::TimeMonitor timerMonitorOrtho(*timerOrtho_);
950 #endif // BELOS_TEUCHOS_TIME_MONITOR
951 
952  // MVT returns int for this, even though the "local ordinal
953  // type" of the MV may be some other type (for example,
954  // Tpetra::MultiVector<double, int32_t, int64_t, ...>).
955  const int numCols = MVT::GetNumberVecs (X);
956 
957  // This special case (for X having only one column) makes
958  // TsqrOrthoManagerImpl equivalent to Modified Gram-Schmidt
959  // orthogonalization with conditional full reorthogonalization,
960  // if all multivector inputs have only one column. It also
961  // avoids allocating Q_ scratch space and copying data when we
962  // don't need to invoke TSQR at all.
963  if (numCols == 1) {
964  return normalizeOne (X, B);
965  }
966 
967  // We use Q_ as scratch space for the normalization, since TSQR
968  // requires a scratch multivector (it can't factor in place). Q_
969  // should come from a vector space compatible with X's vector
970  // space, and Q_ should have at least as many columns as X.
971  // Otherwise, we have to reallocate. We also have to allocate
972  // (not "re-") Q_ if we haven't allocated it before. (We can't
973  // allocate Q_ until we have some X, so we need a multivector as
974  // the "prototype.")
975  //
976  // NOTE (mfh 11 Jan 2011) We only increase the number of columsn
977  // in Q_, never decrease. This is OK for typical uses of TSQR,
978  // but you might prefer different behavior in some cases.
979  //
980  // NOTE (mfh 10 Mar 2011) We should only reuse the scratch space
981  // Q_ if X and Q_ have compatible data distributions. However,
982  // Belos' current MultiVecTraits interface does not let us check
983  // for this. Thus, we can only check whether X and Q_ have the
984  // same number of rows. This will behave correctly for the common
985  // case in Belos that all multivectors with the same number of
986  // rows have the same data distribution.
987  //
988  // The specific MV implementation may do more checks than this on
989  // its own and throw an exception if X and Q_ are not compatible,
990  // but it may not. If you find that recycling the Q_ space causes
991  // troubles, you may consider modifying the code below to
992  // reallocate Q_ for every X that comes in.
993  if (Q_.is_null() ||
995  numCols > MVT::GetNumberVecs (*Q_)) {
996  Q_ = MVT::Clone (X, numCols);
997  }
998 
999  // normalizeImpl() wants the second MV argument to have the same
1000  // number of columns as X. To ensure this, we pass it a view of
1001  // Q_ if Q_ has more columns than X. (This is possible if we
1002  // previously called normalize() with a different multivector,
1003  // since we never reallocate Q_ if it has more columns than
1004  // necessary.)
1005  if (MVT::GetNumberVecs(*Q_) == numCols) {
1006  return normalizeImpl (X, *Q_, B, false);
1007  } else {
1008  RCP<MV> Q_view = MVT::CloneViewNonConst (*Q_, Range1D(0, numCols-1));
1009  return normalizeImpl (X, *Q_view, B, false);
1010  }
1011  }
1012 
1013  template<class Scalar, class MV>
1014  void
1016  allocateProjectionCoefficients (Teuchos::Array<mat_ptr>& C,
1017  Teuchos::ArrayView<Teuchos::RCP<const MV> > Q,
1018  const MV& X,
1019  const bool attemptToRecycle) const
1020  {
1021  const int num_Q_blocks = Q.size();
1022  const int ncols_X = MVT::GetNumberVecs (X);
1023  C.resize (num_Q_blocks);
1024  if (attemptToRecycle)
1025  {
1026  for (int i = 0; i < num_Q_blocks; ++i)
1027  {
1028  const int ncols_Qi = MVT::GetNumberVecs (*Q[i]);
1029  // Create a new C[i] if necessary, otherwise resize if
1030  // necessary, otherwise fill with zeros.
1031  if (C[i].is_null())
1032  C[i] = rcp (new mat_type (ncols_Qi, ncols_X));
1033  else
1034  {
1035  mat_type& Ci = *C[i];
1036  if (Ci.numRows() != ncols_Qi || Ci.numCols() != ncols_X)
1037  Ci.shape (ncols_Qi, ncols_X);
1038  else
1039  Ci.putScalar (SCT::zero());
1040  }
1041  }
1042  }
1043  else
1044  {
1045  for (int i = 0; i < num_Q_blocks; ++i)
1046  {
1047  const int ncols_Qi = MVT::GetNumberVecs (*Q[i]);
1048  C[i] = rcp (new mat_type (ncols_Qi, ncols_X));
1049  }
1050  }
1051  }
1052 
1053  template<class Scalar, class MV>
1054  int
1057  {
1058 #ifdef BELOS_TEUCHOS_TIME_MONITOR
1059  Teuchos::TimeMonitor timerMonitorOrtho(*timerOrtho_);
1060  Teuchos::TimeMonitor timerMonitorNormalize(*timerNormalize_);
1061 #endif // BELOS_TEUCHOS_TIME_MONITOR
1062 
1063  const int numVecs = MVT::GetNumberVecs(X);
1064  if (numVecs == 0) {
1065  return 0; // Nothing to do.
1066  } else if (numVecs == 1) {
1067  // Special case for a single column; scale and copy over.
1068  using Teuchos::Range1D;
1069  using Teuchos::RCP;
1070  using Teuchos::rcp;
1071 
1072  // Normalize X in place (faster than TSQR for one column).
1073  const int rank = normalizeOne (X, B);
1074  // Copy results to first column of Q.
1075  RCP<MV> Q_0 = MVT::CloneViewNonConst (Q, Range1D(0,0));
1076  MVT::Assign (X, *Q_0);
1077  return rank;
1078  } else {
1079  // The "true" argument to normalizeImpl() means the output
1080  // vectors go into Q, and the contents of X are overwritten with
1081  // invalid values.
1082  return normalizeImpl (X, Q, B, true);
1083  }
1084  }
1085 
1086  template<class Scalar, class MV>
1087  int
1089  projectAndNormalizeImpl (MV& X_in,
1090  MV& X_out, // Only written if outOfPlace==false.
1091  const bool outOfPlace,
1092  Teuchos::Array<mat_ptr> C,
1093  mat_ptr B,
1094  Teuchos::ArrayView<Teuchos::RCP<const MV> > Q)
1095  {
1096  using Teuchos::Range1D;
1097  using Teuchos::RCP;
1098  using Teuchos::rcp;
1099 
1100 #ifdef BELOS_TEUCHOS_TIME_MONITOR
1101  // Projection is only timed in rawProject(), and normalization is
1102  // only timed in normalize() and normalizeOutOfPlace().
1103  Teuchos::TimeMonitor timerMonitorOrtho(*timerOrtho_);
1104 #endif // BELOS_TEUCHOS_TIME_MONITOR
1105 
1106  if (outOfPlace) {
1107  // Make sure that X_out has at least as many columns as X_in.
1108  TEUCHOS_TEST_FOR_EXCEPTION(MVT::GetNumberVecs(X_out) < MVT::GetNumberVecs(X_in),
1109  std::invalid_argument,
1110  "Belos::TsqrOrthoManagerImpl::"
1111  "projectAndNormalizeImpl(..., outOfPlace=true, ...):"
1112  "X_out has " << MVT::GetNumberVecs(X_out)
1113  << " columns, but X_in has "
1114  << MVT::GetNumberVecs(X_in) << " columns.");
1115  }
1116  // Fetch dimensions of X_in and Q, and allocate space for first-
1117  // and second-pass projection coefficients (C resp. C2).
1118  int ncols_X, num_Q_blocks, ncols_Q_total;
1119  checkProjectionDims (ncols_X, num_Q_blocks, ncols_Q_total, X_in, Q);
1120 
1121  // Test for quick exit: if any dimension of X is zero.
1122  if (ncols_X == 0) {
1123  return 0;
1124  }
1125  // If there are zero Q blocks or zero Q columns, just normalize!
1126  if (num_Q_blocks == 0 || ncols_Q_total == 0) {
1127  if (outOfPlace) {
1128  return normalizeOutOfPlace (X_in, X_out, B);
1129  } else {
1130  return normalize (X_in, B);
1131  }
1132  }
1133 
1134  // The typical case is that the entries of C have been allocated
1135  // before, so we attempt to recycle the allocations. The call
1136  // below will reallocate if it cannot recycle.
1137  allocateProjectionCoefficients (C, Q, X_in, true);
1138 
1139  // If we are doing block reorthogonalization, then compute the
1140  // column norms of X before projecting for the first time. This
1141  // will help us decide whether we need to reorthogonalize X.
1142  std::vector<magnitude_type> normsBeforeFirstPass (ncols_X, SCTM::zero());
1143  if (reorthogonalizeBlocks_) {
1144  MVT::MvNorm (X_in, normsBeforeFirstPass);
1145  }
1146 
1147  // First (Modified) Block Gram-Schmidt pass, in place in X_in.
1148  rawProject (X_in, Q, C);
1149 
1150  // Make space for the normalization coefficients. This will
1151  // either be a freshly allocated matrix (if B is null), or a view
1152  // of the appropriately sized upper left submatrix of *B (if B is
1153  // not null).
1154  //
1155  // Note that if we let the normalize() routine allocate (in the
1156  // case that B is null), that storage will go away at the end of
1157  // normalize(). (This is because it passes the RCP by value, not
1158  // by reference.)
1159  mat_ptr B_out;
1160  if (B.is_null()) {
1161  B_out = rcp (new mat_type (ncols_X, ncols_X));
1162  } else {
1163  // Make sure that B is no smaller than numCols x numCols.
1164  TEUCHOS_TEST_FOR_EXCEPTION(B->numRows() < ncols_X || B->numCols() < ncols_X,
1165  std::invalid_argument,
1166  "normalizeOne: Input matrix B must be at "
1167  "least " << ncols_X << " x " << ncols_X
1168  << ", but is instead " << B->numRows()
1169  << " x " << B->numCols() << ".");
1170  // Create a view of the ncols_X by ncols_X upper left
1171  // submatrix of *B. TSQR will write the normalization
1172  // coefficients there.
1173  B_out = rcp (new mat_type (Teuchos::View, *B, ncols_X, ncols_X));
1174  }
1175 
1176  // Rank of X(_in) after first projection pass. If outOfPlace,
1177  // this overwrites X_in with invalid values, and the results go in
1178  // X_out. Otherwise, it's done in place in X_in.
1179  const int firstPassRank = outOfPlace ?
1180  normalizeOutOfPlace (X_in, X_out, B_out) :
1181  normalize (X_in, B_out);
1182  if (B.is_null()) {
1183  // The input matrix B is null, so assign B_out to it. If B was
1184  // not null on input, then B_out is a view of *B, so we don't
1185  // have to do anything here. Note that SerialDenseMatrix uses
1186  // raw pointers to store data and represent views, so we have to
1187  // be careful about scope.
1188  B = B_out;
1189  }
1190  int rank = firstPassRank; // Current rank of X.
1191 
1192  // If X was not full rank after projection and randomizeNullSpace_
1193  // is true, then normalize(OutOfPlace)() replaced the null space
1194  // basis of X with random vectors, and orthogonalized them against
1195  // the column space basis of X. However, we still need to
1196  // orthogonalize the random vectors against the Q[i], after which
1197  // we will need to renormalize them.
1198  //
1199  // If outOfPlace, then we need to work in X_out (where
1200  // normalizeOutOfPlace() wrote the normalized vectors).
1201  // Otherwise, we need to work in X_in.
1202  //
1203  // Note: We don't need to keep the new projection coefficients,
1204  // since they are multiplied by the "small" part of B
1205  // corresponding to the null space of the original X.
1206  if (firstPassRank < ncols_X && randomizeNullSpace_) {
1207  const int numNullSpaceCols = ncols_X - firstPassRank;
1208  const Range1D nullSpaceIndices (firstPassRank, ncols_X - 1);
1209 
1210  // Space for projection coefficients (will be thrown away)
1211  Teuchos::Array<mat_ptr> C_null (num_Q_blocks);
1212  for (int k = 0; k < num_Q_blocks; ++k) {
1213  const int numColsQk = MVT::GetNumberVecs(*Q[k]);
1214  C_null[k] = rcp (new mat_type (numColsQk, numNullSpaceCols));
1215  }
1216  // Space for normalization coefficients (will be thrown away).
1217  RCP<mat_type> B_null (new mat_type (numNullSpaceCols, numNullSpaceCols));
1218 
1219  int randomVectorsRank;
1220  if (outOfPlace) {
1221  // View of the null space basis columns of X.
1222  // normalizeOutOfPlace() wrote them into X_out.
1223  RCP<MV> X_out_null = MVT::CloneViewNonConst (X_out, nullSpaceIndices);
1224  // Use X_in for scratch space. Copy X_out_null into the
1225  // last few columns of X_in (X_in_null) and do projections
1226  // in there. (This saves us a copy wen we renormalize
1227  // (out of place) back into X_out.)
1228  RCP<MV> X_in_null = MVT::CloneViewNonConst (X_in, nullSpaceIndices);
1229  MVT::Assign (*X_out_null, *X_in_null);
1230  // Project the new random vectors against the Q blocks, and
1231  // renormalize the result into X_out_null.
1232  rawProject (*X_in_null, Q, C_null);
1233  randomVectorsRank = normalizeOutOfPlace (*X_in_null, *X_out_null, B_null);
1234  } else {
1235  // View of the null space columns of X.
1236  // They live in X_in.
1237  RCP<MV> X_null = MVT::CloneViewNonConst (X_in, nullSpaceIndices);
1238  // Project the new random vectors against the Q blocks,
1239  // and renormalize the result (in place).
1240  rawProject (*X_null, Q, C_null);
1241  randomVectorsRank = normalize (*X_null, B_null);
1242  }
1243  // While unusual, it is still possible for the random data not
1244  // to be full rank after projection and normalization. In that
1245  // case, we could try another set of random data and recurse as
1246  // necessary, but instead for now we just raise an exception.
1247  TEUCHOS_TEST_FOR_EXCEPTION(randomVectorsRank != numNullSpaceCols,
1249  "Belos::TsqrOrthoManagerImpl::projectAndNormalize"
1250  "OutOfPlace(): After projecting and normalizing the "
1251  "random vectors (used to replace the null space "
1252  "basis vectors from normalizing X), they have rank "
1253  << randomVectorsRank << ", but should have full "
1254  "rank " << numNullSpaceCols << ".");
1255  }
1256 
1257  // Whether or not X_in was full rank after projection, we still
1258  // might want to reorthogonalize against Q.
1259  if (reorthogonalizeBlocks_) {
1260  // We are only interested in the column space basis of X
1261  // resp. X_out.
1262  std::vector<magnitude_type>
1263  normsAfterFirstPass (firstPassRank, SCTM::zero());
1264  std::vector<magnitude_type>
1265  normsAfterSecondPass (firstPassRank, SCTM::zero());
1266 
1267  // Compute post-first-pass (pre-normalization) norms. We could
1268  // have done that using MVT::MvNorm() on X_in after projecting,
1269  // but before the first normalization. However, that operation
1270  // may be expensive. It is also unnecessary: after calling
1271  // normalize(), the 2-norm of B(:,j) is the 2-norm of X_in(:,j)
1272  // before normalization, in exact arithmetic.
1273  //
1274  // NOTE (mfh 06 Nov 2010) This is one way that combining
1275  // projection and normalization into a single kernel --
1276  // projectAndNormalize() -- pays off. In project(), we have to
1277  // compute column norms of X before and after projection. Here,
1278  // we get them for free from the normalization coefficients.
1279  Teuchos::BLAS<int, Scalar> blas;
1280  for (int j = 0; j < firstPassRank; ++j) {
1281  const Scalar* const B_j = &(*B_out)(0,j);
1282  // Teuchos::BLAS::NRM2 returns a magnitude_type result on
1283  // Scalar inputs.
1284  normsAfterFirstPass[j] = blas.NRM2 (firstPassRank, B_j, 1);
1285  }
1286  // Test whether any of the norms dropped below the
1287  // reorthogonalization threshold.
1288  bool reorthogonalize = false;
1289  for (int j = 0; j < firstPassRank; ++j) {
1290  // If any column's norm decreased too much, mark this block
1291  // for reorthogonalization. Note that this test will _not_
1292  // activate reorthogonalization if a column's norm before the
1293  // first project-and-normalize step was zero. It _will_
1294  // activate reorthogonalization if the column's norm before
1295  // was not zero, but is zero now.
1296  const magnitude_type curThreshold =
1297  blockReorthogThreshold() * normsBeforeFirstPass[j];
1298  if (normsAfterFirstPass[j] < curThreshold) {
1299  reorthogonalize = true;
1300  break;
1301  }
1302  }
1303 
1304  // Notify the caller via callback about the need for
1305  // reorthogonalization.
1306  if (! reorthogCallback_.is_null()) {
1307  using Teuchos::arrayViewFromVector;
1308  (*reorthogCallback_) (arrayViewFromVector (normsBeforeFirstPass),
1309  arrayViewFromVector (normsAfterFirstPass));
1310  }
1311 
1312  // Perform another Block Gram-Schmidt pass if necessary. "Twice
1313  // is enough" (Kahan's theorem) for a Krylov method, unless
1314  // (using Stewart's term) there is an "orthogonalization fault"
1315  // (indicated by reorthogFault).
1316  //
1317  // NOTE (mfh 07 Nov 2010) For now, we include the entire block
1318  // of X, including possible random data (that was already
1319  // projected and normalized above). It might make more sense
1320  // just to process the first firstPassRank columns of X.
1321  // However, the resulting reorthogonalization should still be
1322  // correct regardless.
1323  bool reorthogFault = false;
1324  // Indices of X at which there was an orthogonalization fault.
1325  std::vector<int> faultIndices;
1326  if (reorthogonalize) {
1327  using Teuchos::Copy;
1328  using Teuchos::NO_TRANS;
1329 
1330  // If we're using out-of-place normalization, copy X_out
1331  // (results of first project and normalize pass) back into
1332  // X_in, for the second project and normalize pass.
1333  if (outOfPlace) {
1334  MVT::Assign (X_out, X_in);
1335  }
1336 
1337  // C2 is only used internally, so we know that we are
1338  // allocating fresh and not recycling allocations. Stating
1339  // this lets us save time checking dimensions.
1340  Teuchos::Array<mat_ptr> C2;
1341  allocateProjectionCoefficients (C2, Q, X_in, false);
1342 
1343  // Block Gram-Schmidt (again). Delay updating the block
1344  // coefficients until we have the new normalization
1345  // coefficients, which we need in order to do the update.
1346  rawProject (X_in, Q, C2);
1347 
1348  // Coefficients for (re)normalization of X_in.
1349  RCP<mat_type> B2 (new mat_type (ncols_X, ncols_X));
1350 
1351  // Normalize X_in (into X_out, if working out of place).
1352  const int secondPassRank = outOfPlace ?
1353  normalizeOutOfPlace (X_in, X_out, B2) :
1354  normalize (X_in, B2);
1355  rank = secondPassRank; // Current rank of X
1356 
1357  // Update normalization coefficients. We begin with copying
1358  // B_out, since the BLAS' _GEMM routine doesn't let us alias
1359  // its input and output arguments.
1360  mat_type B_copy (Copy, *B_out, B_out->numRows(), B_out->numCols());
1361  // B_out := B2 * B_out (where input B_out is in B_copy).
1362  const int err = B_out->multiply (NO_TRANS, NO_TRANS, SCT::one(),
1363  *B2, B_copy, SCT::zero());
1364  TEUCHOS_TEST_FOR_EXCEPTION(err != 0, std::logic_error,
1365  "Teuchos::SerialDenseMatrix::multiply "
1366  "returned err = " << err << " != 0");
1367  // Update the block coefficients from the projection step. We
1368  // use B_copy for this (a copy of B_out, the first-pass
1369  // normalization coefficients).
1370  for (int k = 0; k < num_Q_blocks; ++k) {
1371  mat_type C_k_copy (Copy, *C[k], C[k]->numRows(), C[k]->numCols());
1372 
1373  // C[k] := C2[k]*B_copy + C[k].
1374  const int err1 = C[k]->multiply (NO_TRANS, NO_TRANS, SCT::one(),
1375  *C2[k], B_copy, SCT::one());
1376  TEUCHOS_TEST_FOR_EXCEPTION(err1 != 0, std::logic_error,
1377  "Teuchos::SerialDenseMatrix::multiply "
1378  "returned err = " << err1 << " != 0");
1379  }
1380  // Compute post-second-pass (pre-normalization) norms, using
1381  // B2 (the coefficients from the second normalization step) in
1382  // the same way as with B_out before.
1383  for (int j = 0; j < rank; ++j) {
1384  const Scalar* const B2_j = &(*B2)(0,j);
1385  normsAfterSecondPass[j] = blas.NRM2 (rank, B2_j, 1);
1386  }
1387  // Test whether any of the norms dropped below the
1388  // reorthogonalization threshold. If so, it's an
1389  // orthogonalization fault, which requires expensive recovery.
1390  reorthogFault = false;
1391  for (int j = 0; j < rank; ++j) {
1392  const magnitude_type relativeLowerBound =
1393  blockReorthogThreshold() * normsAfterFirstPass[j];
1394  if (normsAfterSecondPass[j] < relativeLowerBound) {
1395  reorthogFault = true;
1396  faultIndices.push_back (j);
1397  }
1398  }
1399  } // if (reorthogonalize) // reorthogonalization pass
1400 
1401  if (reorthogFault) {
1402  if (throwOnReorthogFault_) {
1403  raiseReorthogFault (normsAfterFirstPass,
1404  normsAfterSecondPass,
1405  faultIndices);
1406  } else {
1407  // NOTE (mfh 19 Jan 2011) We could handle the fault here by
1408  // slowly reorthogonalizing, one vector at a time, the
1409  // offending vectors of X. However, we choose not to
1410  // implement this for now. If it becomes a problem, let us
1411  // know and we will prioritize implementing this.
1412  TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error,
1413  "TsqrOrthoManagerImpl has not yet implemented"
1414  " recovery from an orthogonalization fault.");
1415  }
1416  }
1417  } // if (reorthogonalizeBlocks_)
1418  return rank;
1419  }
1420 
1421 
1422  template<class Scalar, class MV>
1423  void
1425  raiseReorthogFault (const std::vector<magnitude_type>& normsAfterFirstPass,
1426  const std::vector<magnitude_type>& normsAfterSecondPass,
1427  const std::vector<int>& faultIndices)
1428  {
1429  using std::endl;
1430  typedef std::vector<int>::size_type size_type;
1431  std::ostringstream os;
1432 
1433  os << "Orthogonalization fault at the following column(s) of X:" << endl;
1434  os << "Column\tNorm decrease factor" << endl;
1435  for (size_type k = 0; k < faultIndices.size(); ++k) {
1436  const int index = faultIndices[k];
1437  const magnitude_type decreaseFactor =
1438  normsAfterSecondPass[index] / normsAfterFirstPass[index];
1439  os << index << "\t" << decreaseFactor << endl;
1440  }
1441  throw TsqrOrthoFault (os.str());
1442  }
1443 
1444  template<class Scalar, class MV>
1445  Teuchos::RCP<const Teuchos::ParameterList>
1447  {
1448  using Teuchos::ParameterList;
1449  using Teuchos::parameterList;
1450  using Teuchos::RCP;
1451 
1452  if (defaultParams_.is_null()) {
1453  RCP<ParameterList> params = parameterList ("TsqrOrthoManagerImpl");
1454  //
1455  // TSQR parameters (set as a sublist).
1456  //
1457  params->set ("TSQR implementation", *(tsqrAdaptor_.getValidParameters()),
1458  "TSQR implementation parameters.");
1459  //
1460  // Orthogonalization parameters
1461  //
1462  const bool defaultRandomizeNullSpace = true;
1463  params->set ("randomizeNullSpace", defaultRandomizeNullSpace,
1464  "Whether to fill in null space vectors with random data.");
1465 
1466  const bool defaultReorthogonalizeBlocks = true;
1467  params->set ("reorthogonalizeBlocks", defaultReorthogonalizeBlocks,
1468  "Whether to do block reorthogonalization as necessary.");
1469 
1470  // This parameter corresponds to the "blk_tol_" parameter in
1471  // Belos' DGKSOrthoManager. We choose the same default value.
1472  const magnitude_type defaultBlockReorthogThreshold =
1473  magnitude_type(10) * SCTM::squareroot (SCTM::eps());
1474  params->set ("blockReorthogThreshold", defaultBlockReorthogThreshold,
1475  "If reorthogonalizeBlocks==true, and if the norm of "
1476  "any column within a block decreases by this much or "
1477  "more after orthogonalization, we reorthogonalize.");
1478 
1479  // This parameter corresponds to the "sing_tol_" parameter in
1480  // Belos' DGKSOrthoManager. We choose the same default value.
1481  const magnitude_type defaultRelativeRankTolerance =
1482  Teuchos::as<magnitude_type>(10) * SCTM::eps();
1483 
1484  // If the relative rank tolerance is zero, then we will always
1485  // declare blocks to be numerically full rank, as long as no
1486  // singular values are zero.
1487  params->set ("relativeRankTolerance", defaultRelativeRankTolerance,
1488  "Relative tolerance to determine the numerical rank of a "
1489  "block when normalizing.");
1490 
1491  // See Stewart's 2008 paper on block Gram-Schmidt for a definition
1492  // of "orthogonalization fault."
1493  const bool defaultThrowOnReorthogFault = true;
1494  params->set ("throwOnReorthogFault", defaultThrowOnReorthogFault,
1495  "Whether to throw an exception if an orthogonalization "
1496  "fault occurs. This only matters if reorthogonalization "
1497  "is enabled (reorthogonalizeBlocks==true).");
1498 
1499  const bool defaultForceNonnegativeDiagonal = false;
1500  params->set ("forceNonnegativeDiagonal", defaultForceNonnegativeDiagonal,
1501  "Whether to force the R factor produced by the normalization "
1502  "step to have a nonnegative diagonal.");
1503 
1504  defaultParams_ = params;
1505  }
1506  return defaultParams_;
1507  }
1508 
1509  template<class Scalar, class MV>
1510  Teuchos::RCP<const Teuchos::ParameterList>
1512  {
1513  using Teuchos::ParameterList;
1514  using Teuchos::RCP;
1515  using Teuchos::rcp;
1516 
1517  RCP<const ParameterList> defaultParams = getValidParameters();
1518  // Start with a clone of the default parameters.
1519  RCP<ParameterList> params = rcp (new ParameterList (*defaultParams));
1520 
1521  // Disable reorthogonalization and randomization of the null
1522  // space basis. Reorthogonalization tolerances don't matter,
1523  // since we aren't reorthogonalizing blocks in the fast
1524  // settings. We can leave the default values. Also,
1525  // (re)orthogonalization faults may only occur with
1526  // reorthogonalization, so we don't have to worry about the
1527  // "throwOnReorthogFault" setting.
1528  const bool randomizeNullSpace = false;
1529  params->set ("randomizeNullSpace", randomizeNullSpace);
1530  const bool reorthogonalizeBlocks = false;
1531  params->set ("reorthogonalizeBlocks", reorthogonalizeBlocks);
1532 
1533  return params;
1534  }
1535 
1536  template<class Scalar, class MV>
1537  int
1539  rawNormalize (MV& X,
1540  MV& Q,
1541  Teuchos::SerialDenseMatrix<int, Scalar>& B)
1542  {
1543  int rank;
1544  try {
1545  // This call only computes the QR factorization X = Q B.
1546  // It doesn't compute the rank of X. That comes from
1547  // revealRank() below.
1548  tsqrAdaptor_.factorExplicit (X, Q, B, forceNonnegativeDiagonal_);
1549  // This call will only modify *B if *B on input is not of full
1550  // numerical rank.
1551  rank = tsqrAdaptor_.revealRank (Q, B, relativeRankTolerance_);
1552  } catch (std::exception& e) {
1553  throw TsqrOrthoError (e.what()); // Toss the exception up the chain.
1554  }
1555  return rank;
1556  }
1557 
1558  template<class Scalar, class MV>
1559  int
1561  normalizeOne (MV& X,
1562  Teuchos::RCP<Teuchos::SerialDenseMatrix<int, Scalar> > B) const
1563  {
1564  // Make space for the normalization coefficient. This will either
1565  // be a freshly allocated matrix (if B is null), or a view of the
1566  // 1x1 upper left submatrix of *B (if B is not null).
1567  mat_ptr B_out;
1568  if (B.is_null()) {
1569  B_out = rcp (new mat_type (1, 1));
1570  } else {
1571  const int numRows = B->numRows();
1572  const int numCols = B->numCols();
1573  TEUCHOS_TEST_FOR_EXCEPTION(numRows < 1 || numCols < 1,
1574  std::invalid_argument,
1575  "normalizeOne: Input matrix B must be at "
1576  "least 1 x 1, but is instead " << numRows
1577  << " x " << numCols << ".");
1578  // Create a view of the 1x1 upper left submatrix of *B.
1579  B_out = rcp (new mat_type (Teuchos::View, *B, 1, 1));
1580  }
1581 
1582  // Compute the norm of X, and write the result to B_out.
1583  std::vector<magnitude_type> theNorm (1, SCTM::zero());
1584  MVT::MvNorm (X, theNorm);
1585  (*B_out)(0,0) = theNorm[0];
1586 
1587  if (B.is_null()) {
1588  // The input matrix B is null, so assign B_out to it. If B was
1589  // not null on input, then B_out is a view of *B, so we don't
1590  // have to do anything here. Note that SerialDenseMatrix uses
1591  // raw pointers to store data and represent views, so we have to
1592  // be careful about scope.
1593  B = B_out;
1594  }
1595 
1596  // Scale X by its norm, if its norm is zero. Otherwise, do the
1597  // right thing based on whether the user wants us to fill the null
1598  // space with random vectors.
1599  if (theNorm[0] == SCTM::zero()) {
1600  // Make a view of the first column of Q, fill it with random
1601  // data, and normalize it. Throw away the resulting norm.
1602  if (randomizeNullSpace_) {
1603  MVT::MvRandom(X);
1604  MVT::MvNorm (X, theNorm);
1605  if (theNorm[0] == SCTM::zero()) {
1606  // It is possible that a random vector could have all zero
1607  // entries, but unlikely. We could try again, but it's also
1608  // possible that multiple tries could result in zero
1609  // vectors. We choose instead to give up.
1610  throw TsqrOrthoError("normalizeOne: a supposedly random "
1611  "vector has norm zero!");
1612  } else {
1613  // NOTE (mfh 09 Nov 2010) I'm assuming that dividing a
1614  // Scalar by a magnitude_type is defined and that it results
1615  // in a Scalar.
1616  const Scalar alpha = SCT::one() / theNorm[0];
1617  MVT::MvScale (X, alpha);
1618  }
1619  }
1620  return 0; // The rank of the matrix (actually just one vector) X.
1621  } else {
1622  // NOTE (mfh 09 Nov 2010) I'm assuming that dividing a Scalar by
1623  // a magnitude_type is defined and that it results in a Scalar.
1624  const Scalar alpha = SCT::one() / theNorm[0];
1625  MVT::MvScale (X, alpha);
1626  return 1; // The rank of the matrix (actually just one vector) X.
1627  }
1628  }
1629 
1630 
1631  template<class Scalar, class MV>
1632  void
1634  rawProject (MV& X,
1635  Teuchos::ArrayView<Teuchos::RCP<const MV> > Q,
1636  Teuchos::ArrayView<Teuchos::RCP<Teuchos::SerialDenseMatrix<int, Scalar> > > C) const
1637  {
1638 #ifdef BELOS_TEUCHOS_TIME_MONITOR
1639  Teuchos::TimeMonitor timerMonitorNormalize(*timerProject_);
1640 #endif // BELOS_TEUCHOS_TIME_MONITOR
1641 
1642  // "Modified Gram-Schmidt" version of Block Gram-Schmidt.
1643  const int num_Q_blocks = Q.size();
1644  for (int i = 0; i < num_Q_blocks; ++i)
1645  {
1646  // TEUCHOS_TEST_FOR_EXCEPTION(C[i].is_null(), std::logic_error,
1647  // "TsqrOrthoManagerImpl::rawProject(): C["
1648  // << i << "] is null");
1649  // TEUCHOS_TEST_FOR_EXCEPTION(Q[i].is_null(), std::logic_error,
1650  // "TsqrOrthoManagerImpl::rawProject(): Q["
1651  // << i << "] is null");
1652  mat_type& Ci = *C[i];
1653  const MV& Qi = *Q[i];
1654  innerProd (Qi, X, Ci);
1655  MVT::MvTimesMatAddMv (-SCT::one(), Qi, Ci, SCT::one(), X);
1656  }
1657  }
1658 
1659 
1660  template<class Scalar, class MV>
1661  void
1663  rawProject (MV& X,
1664  const Teuchos::RCP<const MV>& Q,
1665  const Teuchos::RCP<Teuchos::SerialDenseMatrix<int, Scalar> >& C) const
1666  {
1667 #ifdef BELOS_TEUCHOS_TIME_MONITOR
1668  Teuchos::TimeMonitor timerMonitorNormalize(*timerProject_);
1669 #endif // BELOS_TEUCHOS_TIME_MONITOR
1670 
1671  // Block Gram-Schmidt
1672  innerProd (*Q, X, *C);
1673  MVT::MvTimesMatAddMv (-SCT::one(), *Q, *C, SCT::one(), X);
1674  }
1675 
1676  template<class Scalar, class MV>
1677  int
1679  normalizeImpl (MV& X,
1680  MV& Q,
1681  Teuchos::RCP<Teuchos::SerialDenseMatrix<int, Scalar> > B,
1682  const bool outOfPlace)
1683  {
1684  using Teuchos::Range1D;
1685  using Teuchos::RCP;
1686  using Teuchos::rcp;
1687  using Teuchos::ScalarTraits;
1688  using Teuchos::tuple;
1689 
1690  const int numCols = MVT::GetNumberVecs (X);
1691  if (numCols == 0) {
1692  return 0; // Fast exit for an empty input matrix.
1693  }
1694 
1695  // We allow Q to have more columns than X. In that case, we only
1696  // touch the first numCols columns of Q.
1697  TEUCHOS_TEST_FOR_EXCEPTION(
1698  MVT::GetNumberVecs (Q) < numCols, std::invalid_argument,
1699  "TsqrOrthoManagerImpl::normalizeImpl: Q has "
1700  << MVT::GetNumberVecs(Q) << " columns. This is too "
1701  "few, since X has " << numCols << " columns.");
1702  // TSQR wants a Q with the same number of columns as X, so have it
1703  // work on a nonconstant view of Q with the same number of columns
1704  // as X.
1705  RCP<MV> Q_view = MVT::CloneViewNonConst (Q, Range1D (0, numCols-1));
1706 
1707  // Make space for the normalization coefficients. This will
1708  // either be a freshly allocated matrix (if B is null), or a view
1709  // of the appropriately sized upper left submatrix of *B (if B is
1710  // not null).
1711  mat_ptr B_out;
1712  if (B.is_null ()) {
1713  B_out = rcp (new mat_type (numCols, numCols));
1714  } else {
1715  // Make sure that B is no smaller than numCols x numCols.
1716  TEUCHOS_TEST_FOR_EXCEPTION(
1717  B->numRows() < numCols || B->numCols() < numCols, std::invalid_argument,
1718  "TsqrOrthoManagerImpl::normalizeImpl: Input matrix B must be at least "
1719  << numCols << " x " << numCols << ", but is instead " << B->numRows ()
1720  << " x " << B->numCols() << ".");
1721  // Create a view of the numCols x numCols upper left submatrix
1722  // of *B. TSQR will write the normalization coefficients there.
1723  B_out = rcp (new mat_type (Teuchos::View, *B, numCols, numCols));
1724  }
1725 
1726  // Compute rank-revealing decomposition (in this case, TSQR of X
1727  // followed by SVD of the R factor and appropriate updating of the
1728  // resulting Q factor) of X. X is modified in place and filled
1729  // with garbage, and Q_view contains the resulting explicit Q
1730  // factor. Later, we will copy this back into X.
1731  //
1732  // The matrix *B_out will only be upper triangular if X is of full
1733  // numerical rank. Otherwise, the entries below the diagonal may
1734  // be filled in as well.
1735  const int rank = rawNormalize (X, *Q_view, *B_out);
1736  if (B.is_null ()) {
1737  // The input matrix B is null, so assign B_out to it. If B was
1738  // not null on input, then B_out is a view of *B, so we don't
1739  // have to do anything here. Note that SerialDenseMatrix uses
1740  // raw pointers to store data and represent views, so we have to
1741  // be careful about scope.
1742  B = B_out;
1743  }
1744 
1745  TEUCHOS_TEST_FOR_EXCEPTION(
1746  rank < 0 || rank > numCols, std::logic_error,
1747  "Belos::TsqrOrthoManagerImpl::normalizeImpl: rawNormalize returned rank "
1748  " = " << rank << " for a matrix X with " << numCols << " columns. "
1749  "Please report this bug to the Belos developers.");
1750 
1751  // If X is full rank or we don't want to replace its null space
1752  // basis with random vectors, then we're done.
1753  if (rank == numCols || ! randomizeNullSpace_) {
1754  // If we're supposed to be working in place in X, copy the
1755  // results back from Q_view into X.
1756  if (! outOfPlace) {
1757  MVT::Assign (*Q_view, X);
1758  }
1759  return rank;
1760  }
1761 
1762  if (randomizeNullSpace_ && rank < numCols) {
1763  // X wasn't full rank. Replace the null space basis of X (in
1764  // the last numCols-rank columns of Q_view) with random data,
1765  // project it against the first rank columns of Q_view, and
1766  // normalize.
1767  //
1768  // Number of columns to fill with random data.
1769  const int nullSpaceNumCols = numCols - rank;
1770  // Inclusive range of indices of columns of X to fill with
1771  // random data.
1772  Range1D nullSpaceIndices (rank, numCols-1);
1773 
1774  // rawNormalize wrote the null space basis vectors into Q_view.
1775  // We continue to work in place in Q_view by writing the random
1776  // data there and (if there is a nontrival column space)
1777  // projecting in place against the column space basis vectors
1778  // (also in Q_view).
1779  RCP<MV> Q_null = MVT::CloneViewNonConst (*Q_view, nullSpaceIndices);
1780  // Replace the null space basis with random data.
1781  MVT::MvRandom (*Q_null);
1782 
1783  // Make sure that the "random" data isn't all zeros. This is
1784  // statistically nearly impossible, but we test for debugging
1785  // purposes.
1786  {
1787  std::vector<magnitude_type> norms (MVT::GetNumberVecs (*Q_null));
1788  MVT::MvNorm (*Q_null, norms);
1789 
1790  bool anyZero = false;
1791  typedef typename std::vector<magnitude_type>::const_iterator iter_type;
1792  for (iter_type it = norms.begin(); it != norms.end(); ++it) {
1793  if (*it == SCTM::zero()) {
1794  anyZero = true;
1795  }
1796  }
1797  if (anyZero) {
1798  std::ostringstream os;
1799  os << "TsqrOrthoManagerImpl::normalizeImpl: "
1800  "We are being asked to randomize the null space, for a matrix "
1801  "with " << numCols << " columns and reported column rank "
1802  << rank << ". The inclusive range of columns to fill with "
1803  "random data is [" << nullSpaceIndices.lbound() << ","
1804  << nullSpaceIndices.ubound() << "]. After filling the null "
1805  "space vectors with random numbers, at least one of the vectors"
1806  " has norm zero. Here are the norms of all the null space "
1807  "vectors: [";
1808  for (iter_type it = norms.begin(); it != norms.end(); ++it) {
1809  os << *it;
1810  if (it+1 != norms.end())
1811  os << ", ";
1812  }
1813  os << "].) There is a tiny probability that this could happen "
1814  "randomly, but it is likely a bug. Please report it to the "
1815  "Belos developers, especially if you are able to reproduce the "
1816  "behavior.";
1817  TEUCHOS_TEST_FOR_EXCEPTION(anyZero, TsqrOrthoError, os.str());
1818  }
1819  }
1820 
1821  if (rank > 0) {
1822  // Project the random data against the column space basis of
1823  // X, using a simple block projection ("Block Classical
1824  // Gram-Schmidt"). This is accurate because we've already
1825  // orthogonalized the column space basis of X nearly to
1826  // machine precision via a QR factorization (TSQR) with
1827  // accuracy comparable to Householder QR.
1828  RCP<const MV> Q_col = MVT::CloneView (*Q_view, Range1D (0, rank-1));
1829 
1830  // Temporary storage for projection coefficients. We don't
1831  // need to keep them, since they represent the null space
1832  // basis (for which the coefficients are logically zero).
1833  mat_ptr C_null (new mat_type (rank, nullSpaceNumCols));
1834  rawProject (*Q_null, Q_col, C_null);
1835  }
1836  // Normalize the projected random vectors, so that they are
1837  // mutually orthogonal (as well as orthogonal to the column
1838  // space basis of X). We use X for the output of the
1839  // normalization: for out-of-place normalization (outOfPlace ==
1840  // true), X is overwritten with "invalid values" anyway, and for
1841  // in-place normalization (outOfPlace == false), we want the
1842  // result to be in X anyway.
1843  RCP<MV> X_null = MVT::CloneViewNonConst (X, nullSpaceIndices);
1844  // Normalization coefficients for projected random vectors.
1845  // Will be thrown away.
1846  mat_type B_null (nullSpaceNumCols, nullSpaceNumCols);
1847  // Write the normalized vectors to X_null (in X).
1848  const int nullSpaceBasisRank = rawNormalize (*Q_null, *X_null, B_null);
1849 
1850  // It's possible, but unlikely, that X_null doesn't have full
1851  // rank (after the projection step). We could recursively fill
1852  // in more random vectors until we finally get a full rank
1853  // matrix, but instead we just throw an exception.
1854  //
1855  // NOTE (mfh 08 Nov 2010) Perhaps we should deal with this case
1856  // more elegantly. Recursion might be one way to solve it, but
1857  // be sure to check that the recursion will terminate. We could
1858  // do this by supplying an additional argument to rawNormalize,
1859  // which is the null space basis rank from the previous
1860  // iteration. The rank has to decrease each time, or the
1861  // recursion may go on forever.
1862  if (nullSpaceBasisRank < nullSpaceNumCols) {
1863  std::vector<magnitude_type> norms (MVT::GetNumberVecs(*X_null));
1864  MVT::MvNorm (*X_null, norms);
1865  std::ostringstream os;
1866  os << "TsqrOrthoManagerImpl::normalizeImpl: "
1867  << "We are being asked to randomize the null space, "
1868  << "for a matrix with " << numCols << " columns and "
1869  << "column rank " << rank << ". After projecting and "
1870  << "normalizing the generated random vectors, they "
1871  << "only have rank " << nullSpaceBasisRank << ". They"
1872  << " should have full rank " << nullSpaceNumCols
1873  << ". (The inclusive range of columns to fill with "
1874  << "random data is [" << nullSpaceIndices.lbound()
1875  << "," << nullSpaceIndices.ubound() << "]. The "
1876  << "column norms of the resulting Q factor are: [";
1877  for (typename std::vector<magnitude_type>::size_type k = 0;
1878  k < norms.size(); ++k) {
1879  os << norms[k];
1880  if (k != norms.size()-1) {
1881  os << ", ";
1882  }
1883  }
1884  os << "].) There is a tiny probability that this could "
1885  << "happen randomly, but it is likely a bug. Please "
1886  << "report it to the Belos developers, especially if "
1887  << "you are able to reproduce the behavior.";
1888 
1889  TEUCHOS_TEST_FOR_EXCEPTION(nullSpaceBasisRank < nullSpaceNumCols,
1890  TsqrOrthoError, os.str ());
1891  }
1892  // If we're normalizing out of place, copy the X_null
1893  // vectors back into Q_null; the Q_col vectors are already
1894  // where they are supposed to be in that case.
1895  //
1896  // If we're normalizing in place, leave X_null alone (it's
1897  // already where it needs to be, in X), but copy Q_col back
1898  // into the first rank columns of X.
1899  if (outOfPlace) {
1900  MVT::Assign (*X_null, *Q_null);
1901  } else if (rank > 0) {
1902  // MVT::Assign() doesn't accept empty ranges of columns.
1903  RCP<const MV> Q_col = MVT::CloneView (*Q_view, Range1D (0, rank-1));
1904  RCP<MV> X_col = MVT::CloneViewNonConst (X, Range1D (0, rank-1));
1905  MVT::Assign (*Q_col, *X_col);
1906  }
1907  }
1908  return rank;
1909  }
1910 
1911 
1912  template<class Scalar, class MV>
1913  void
1915  checkProjectionDims (int& ncols_X,
1916  int& num_Q_blocks,
1917  int& ncols_Q_total,
1918  const MV& X,
1919  Teuchos::ArrayView<Teuchos::RCP<const MV> > Q) const
1920  {
1921  // First assign to temporary values, so the function won't
1922  // commit any externally visible side effects unless it will
1923  // return normally (without throwing an exception). (I'm being
1924  // cautious; MVT::GetNumberVecs() probably shouldn't have any
1925  // externally visible side effects, unless it is logging to a
1926  // file or something.)
1927  int the_ncols_X, the_num_Q_blocks, the_ncols_Q_total;
1928  the_num_Q_blocks = Q.size();
1929  the_ncols_X = MVT::GetNumberVecs (X);
1930 
1931  // Compute the total number of columns of all the Q[i] blocks.
1932  the_ncols_Q_total = 0;
1933  // You should be angry if your compiler doesn't support type
1934  // inference ("auto"). That's why I need this awful typedef.
1935  using Teuchos::ArrayView;
1936  using Teuchos::RCP;
1937  typedef typename ArrayView<RCP<const MV> >::const_iterator iter_type;
1938  for (iter_type it = Q.begin(); it != Q.end(); ++it) {
1939  const MV& Qi = **it;
1940  the_ncols_Q_total += MVT::GetNumberVecs (Qi);
1941  }
1942 
1943  // Commit temporary values to the output arguments.
1944  ncols_X = the_ncols_X;
1945  num_Q_blocks = the_num_Q_blocks;
1946  ncols_Q_total = the_ncols_Q_total;
1947  }
1948 
1949 } // namespace Belos
1950 
1951 #endif // __BelosTsqrOrthoManagerImpl_hpp
1952 
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.
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).
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.
static void MvRandom(MV &mv)
Replace the vectors in mv with random vectors.
void setParameterList(const Teuchos::RCP< Teuchos::ParameterList > &params)
Set parameters from the given parameter list.
static Teuchos::RCP< const MV > CloneView(const MV &mv, const std::vector< int > &index)
Creates a new const MV that shares the selected contents of mv (shallow copy).
Teuchos::RCP< const Teuchos::ParameterList > getFastParameters()
Get "fast" parameters for TsqrOrthoManagerImpl.
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.
Error in TsqrOrthoManager or TsqrOrthoManagerImpl.
int normalize(MV &X, mat_ptr B)
Orthogonalize the columns of X in place.
void setLabel(const std::string &label)
Set the label for timers.
An extension of the MultiVecTraits class that adds a new vector length method.
static int GetNumberVecs(const MV &mv)
Obtain the number of vectors in mv.
static void Assign(const MV &A, MV &mv)
mv := A
Teuchos::ScalarTraits< Scalar >::magnitudeType magnitude_type
The type of a norm result.
Teuchos::RCP< const Teuchos::ParameterList > getValidParameters() const
Default valid parameter list.
Traits class which defines basic operations on multivectors.
Scalar scalar_type
The template parameter of this class; the type of an inner product result.
static Teuchos::RCP< MV > CloneViewNonConst(MV &mv, const std::vector< int > &index)
Creates a new MV that shares the selected contents of mv (shallow copy).
static Teuchos::RCP< MV > Clone(const MV &mv, const int numvecs)
Creates a new empty MV containing numvecs columns.
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...
static void MvTimesMatAddMv(const ScalarType alpha, const MV &A, const Teuchos::SerialDenseMatrix< int, ScalarType > &B, const ScalarType beta, MV &mv)
Update mv with .
TsqrOrthoError(const std::string &what_arg)
virtual ~ReorthogonalizationCallback()
Destructor (virtual for memory safety of derived classes)
Templated virtual class for providing orthogonalization/orthonormalization methods.
TsqrOrthoFault(const std::string &what_arg)
static ptrdiff_t GetGlobalLength(const MV &mv)
Obtain the vector length of mv.
magnitude_type blockReorthogThreshold() const
Relative tolerance for triggering a block reorthogonalization.
static void MvNorm(const MV &mv, std::vector< typename Teuchos::ScalarTraits< ScalarType >::magnitudeType > &normvec, NormType type=TwoNorm)
Compute the 2-norm of each individual vector of mv. Upon return, normvec[i] holds the value of ...
static void MvScale(MV &mv, const ScalarType alpha)
Scale each element of the vectors in mv with alpha.
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.