Ifpack2 Templated Preconditioning Package  Version 1.0
Ifpack2_Relaxation_def.hpp
1 /*@HEADER
2 // ***********************************************************************
3 //
4 // Ifpack2: Tempated Object-Oriented Algebraic Preconditioner Package
5 // Copyright (2009) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
9 //
10 // 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 */
42 
43 #ifndef IFPACK2_RELAXATION_DEF_HPP
44 #define IFPACK2_RELAXATION_DEF_HPP
45 
46 #include "Ifpack2_Relaxation_decl.hpp"
47 #include "Teuchos_StandardParameterEntryValidators.hpp"
48 #include <Teuchos_TimeMonitor.hpp>
49 #include <Tpetra_ConfigDefs.hpp>
50 
51 // mfh 28 Mar 2013: Uncomment out these three lines to compute
52 // statistics on diagonal entries in compute().
53 // #ifndef IFPACK2_RELAXATION_COMPUTE_DIAGONAL_STATS
54 // # define IFPACK2_RELAXATION_COMPUTE_DIAGONAL_STATS 1
55 // #endif // IFPACK2_RELAXATION_COMPUTE_DIAGONAL_STATS
56 
57 namespace {
58  // Validate that a given int is nonnegative.
59  class NonnegativeIntValidator : public Teuchos::ParameterEntryValidator {
60  public:
61  // Constructor (does nothing).
62  NonnegativeIntValidator () {}
63 
64  // ParameterEntryValidator wants this method.
65  Teuchos::ParameterEntryValidator::ValidStringsList validStringValues () const {
66  return Teuchos::null;
67  }
68 
69  // Actually validate the parameter's value.
70  void
71  validate (const Teuchos::ParameterEntry& entry,
72  const std::string& paramName,
73  const std::string& sublistName) const
74  {
75  using std::endl;
76  Teuchos::any anyVal = entry.getAny (true);
77  const std::string entryName = entry.getAny (false).typeName ();
78 
79  TEUCHOS_TEST_FOR_EXCEPTION(
80  anyVal.type () != typeid (int),
81  Teuchos::Exceptions::InvalidParameterType,
82  "Parameter \"" << paramName << "\" in sublist \"" << sublistName
83  << "\" has the wrong type." << endl << "Parameter: " << paramName
84  << endl << "Type specified: " << entryName << endl
85  << "Type required: int" << endl);
86 
87  const int val = Teuchos::any_cast<int> (anyVal);
88  TEUCHOS_TEST_FOR_EXCEPTION(
89  val < 0, Teuchos::Exceptions::InvalidParameterValue,
90  "Parameter \"" << paramName << "\" in sublist \"" << sublistName
91  << "\" is negative." << endl << "Parameter: " << paramName
92  << endl << "Value specified: " << val << endl
93  << "Required range: [0, INT_MAX]" << endl);
94  }
95 
96  // ParameterEntryValidator wants this method.
97  const std::string getXMLTypeName () const {
98  return "NonnegativeIntValidator";
99  }
100 
101  // ParameterEntryValidator wants this method.
102  void
103  printDoc (const std::string& docString,
104  std::ostream &out) const
105  {
106  Teuchos::StrUtils::printLines (out, "# ", docString);
107  out << "#\tValidator Used: " << std::endl;
108  out << "#\t\tNonnegativeIntValidator" << std::endl;
109  }
110  };
111 
112  // A way to get a small positive number (eps() for floating-point
113  // types, or 1 for integer types) when Teuchos::ScalarTraits doesn't
114  // define it (for example, for integer values).
115  template<class Scalar, const bool isOrdinal=Teuchos::ScalarTraits<Scalar>::isOrdinal>
116  class SmallTraits {
117  public:
118  // Return eps if Scalar is a floating-point type, else return 1.
119  static const Scalar eps ();
120  };
121 
122  // Partial specialization for when Scalar is not a floating-point type.
123  template<class Scalar>
124  class SmallTraits<Scalar, true> {
125  public:
126  static const Scalar eps () {
127  return Teuchos::ScalarTraits<Scalar>::one ();
128  }
129  };
130 
131  // Partial specialization for when Scalar is a floating-point type.
132  template<class Scalar>
133  class SmallTraits<Scalar, false> {
134  public:
135  static const Scalar eps () {
136  return Teuchos::ScalarTraits<Scalar>::eps ();
137  }
138  };
139 } // namespace (anonymous)
140 
141 namespace Ifpack2 {
142 
143 //==========================================================================
144 template<class MatrixType>
145 Relaxation<MatrixType>::
146 Relaxation (const Teuchos::RCP<const Tpetra::RowMatrix<scalar_type, local_ordinal_type, global_ordinal_type, node_type> >& A)
147 : A_(A),
148  Time_ (Teuchos::rcp (new Teuchos::Time ("Ifpack2::Relaxation"))),
149  NumSweeps_ (1),
150  PrecType_ (Ifpack2::JACOBI),
151  DampingFactor_ (STS::one ()),
152  IsParallel_ (A->getRowMap ()->getComm ()->getSize () > 1),
153  ZeroStartingSolution_ (true),
154  DoBackwardGS_ (false),
155  DoL1Method_ (false),
156  L1Eta_ (Teuchos::as<magnitude_type> (1.5)),
157  MinDiagonalValue_ (STS::zero ()),
158  fixTinyDiagEntries_ (false),
159  checkDiagEntries_ (false),
160  Condest_ (-STM::one ()),
161  IsInitialized_ (false),
162  IsComputed_ (false),
163  NumInitialize_ (0),
164  NumCompute_ (0),
165  NumApply_ (0),
166  InitializeTime_ (0.0), // Times are double anyway, so no need for ScalarTraits.
167  ComputeTime_ (0.0),
168  ApplyTime_ (0.0),
169  ComputeFlops_ (0.0),
170  ApplyFlops_ (0.0),
171  globalMinMagDiagEntryMag_ (STM::zero ()),
172  globalMaxMagDiagEntryMag_ (STM::zero ()),
173  globalNumSmallDiagEntries_ (0),
174  globalNumZeroDiagEntries_ (0),
175  globalNumNegDiagEntries_ (0),
176  savedDiagOffsets_ (false)
177 {
178  this->setObjectLabel ("Ifpack2::Relaxation");
179  TEUCHOS_TEST_FOR_EXCEPTION(
180  A_.is_null (), std::runtime_error,
181  "Ifpack2::Relaxation constructor: The input matrix A must be non-null.");
182 }
183 
184 //==========================================================================
185 template<class MatrixType>
187 }
188 
189 template<class MatrixType>
190 Teuchos::RCP<const Teuchos::ParameterList>
192 {
193  using Teuchos::Array;
194  using Teuchos::ParameterList;
195  using Teuchos::parameterList;
196  using Teuchos::RCP;
197  using Teuchos::rcp;
198  using Teuchos::rcp_const_cast;
199  using Teuchos::rcp_implicit_cast;
200  using Teuchos::setStringToIntegralParameter;
201  typedef Teuchos::ParameterEntryValidator PEV;
202 
203  if (validParams_.is_null ()) {
204  RCP<ParameterList> pl = parameterList ("Ifpack2::Relaxation");
205 
206  // Set a validator that automatically converts from the valid
207  // string options to their enum values.
208  Array<std::string> precTypes (3);
209  precTypes[0] = "Jacobi";
210  precTypes[1] = "Gauss-Seidel";
211  precTypes[2] = "Symmetric Gauss-Seidel";
212  Array<RelaxationType> precTypeEnums (3);
213  precTypeEnums[0] = JACOBI;
214  precTypeEnums[1] = GS;
215  precTypeEnums[2] = SGS;
216  const std::string defaultPrecType ("Jacobi");
217  setStringToIntegralParameter<RelaxationType> ("relaxation: type",
218  defaultPrecType, "Relaxation method", precTypes (), precTypeEnums (),
219  pl.getRawPtr ());
220 
221  const int numSweeps = 1;
222  RCP<PEV> numSweepsValidator =
223  rcp_implicit_cast<PEV> (rcp (new NonnegativeIntValidator));
224  pl->set ("relaxation: sweeps", numSweeps, "Number of relaxation sweeps",
225  rcp_const_cast<const PEV> (numSweepsValidator));
226 
227  const scalar_type dampingFactor = STS::one ();
228  pl->set ("relaxation: damping factor", dampingFactor);
229 
230  const bool zeroStartingSolution = true;
231  pl->set ("relaxation: zero starting solution", zeroStartingSolution);
232 
233  const bool doBackwardGS = false;
234  pl->set ("relaxation: backward mode", doBackwardGS);
235 
236  const bool doL1Method = false;
237  pl->set ("relaxation: use l1", doL1Method);
238 
239  const magnitude_type l1eta = (STM::one() + STM::one() + STM::one()) /
240  (STM::one() + STM::one()); // 1.5
241  pl->set ("relaxation: l1 eta", l1eta);
242 
243  const scalar_type minDiagonalValue = STS::zero ();
244  pl->set ("relaxation: min diagonal value", minDiagonalValue);
245 
246  const bool fixTinyDiagEntries = false;
247  pl->set ("relaxation: fix tiny diagonal entries", fixTinyDiagEntries);
248 
249  const bool checkDiagEntries = false;
250  pl->set ("relaxation: check diagonal entries", checkDiagEntries);
251 
252  validParams_ = rcp_const_cast<const ParameterList> (pl);
253  }
254  return validParams_;
255 }
256 
257 
258 template<class MatrixType>
259 void Relaxation<MatrixType>::setParametersImpl (Teuchos::ParameterList& pl)
260 {
261  using Teuchos::getIntegralValue;
262  using Teuchos::ParameterList;
263  using Teuchos::RCP;
264  typedef scalar_type ST; // just to make code below shorter
265 
266  pl.validateParametersAndSetDefaults (* getValidParameters ());
267 
268  const RelaxationType precType =
269  getIntegralValue<RelaxationType> (pl, "relaxation: type");
270  const int numSweeps = pl.get<int> ("relaxation: sweeps");
271  const ST dampingFactor = pl.get<ST> ("relaxation: damping factor");
272  const bool zeroStartSol = pl.get<bool> ("relaxation: zero starting solution");
273  const bool doBackwardGS = pl.get<bool> ("relaxation: backward mode");
274  const bool doL1Method = pl.get<bool> ("relaxation: use l1");
275  const magnitude_type l1Eta = pl.get<magnitude_type> ("relaxation: l1 eta");
276  const ST minDiagonalValue = pl.get<ST> ("relaxation: min diagonal value");
277  const bool fixTinyDiagEntries = pl.get<bool> ("relaxation: fix tiny diagonal entries");
278  const bool checkDiagEntries = pl.get<bool> ("relaxation: check diagonal entries");
279 
280  // "Commit" the changes, now that we've validated everything.
281  PrecType_ = precType;
282  NumSweeps_ = numSweeps;
283  DampingFactor_ = dampingFactor;
284  ZeroStartingSolution_ = zeroStartSol;
285  DoBackwardGS_ = doBackwardGS;
286  DoL1Method_ = doL1Method;
287  L1Eta_ = l1Eta;
288  MinDiagonalValue_ = minDiagonalValue;
289  fixTinyDiagEntries_ = fixTinyDiagEntries;
290  checkDiagEntries_ = checkDiagEntries;
291 }
292 
293 //==========================================================================
294 template<class MatrixType>
295 void Relaxation<MatrixType>::setParameters (const Teuchos::ParameterList& pl)
296 {
297  Teuchos::ParameterList plCopy (pl); // pl is const, so we must copy it.
298  this->setParametersImpl (plCopy);
299 }
300 
301 //==========================================================================
302 template<class MatrixType>
303 const Teuchos::RCP<const Teuchos::Comm<int> > &
305  return A_->getRowMap ()->getComm ();
306 }
307 
308 //==========================================================================
309 template<class MatrixType>
310 Teuchos::RCP<const Tpetra::RowMatrix<typename MatrixType::scalar_type,
311  typename MatrixType::local_ordinal_type,
312  typename MatrixType::global_ordinal_type,
313  typename MatrixType::node_type> >
315  return(A_);
316 }
317 
318 //==========================================================================
319 template<class MatrixType>
320 const Teuchos::RCP<const Tpetra::Map<typename MatrixType::local_ordinal_type,
321  typename MatrixType::global_ordinal_type,
322  typename MatrixType::node_type> >&
324  return A_->getDomainMap();
325 }
326 
327 //==========================================================================
328 template<class MatrixType>
329 const Teuchos::RCP<const Tpetra::Map<typename MatrixType::local_ordinal_type,
330  typename MatrixType::global_ordinal_type,
331  typename MatrixType::node_type> >&
333  return A_->getRangeMap();
334 }
335 
336 //==========================================================================
337 template<class MatrixType>
339  return true;
340 }
341 
342 //==========================================================================
343 template<class MatrixType>
345  return(NumInitialize_);
346 }
347 
348 //==========================================================================
349 template<class MatrixType>
351  return(NumCompute_);
352 }
353 
354 //==========================================================================
355 template<class MatrixType>
357  return(NumApply_);
358 }
359 
360 //==========================================================================
361 template<class MatrixType>
363  return(InitializeTime_);
364 }
365 
366 //==========================================================================
367 template<class MatrixType>
369  return(ComputeTime_);
370 }
371 
372 //==========================================================================
373 template<class MatrixType>
375  return(ApplyTime_);
376 }
377 
378 //==========================================================================
379 template<class MatrixType>
381  return(ComputeFlops_);
382 }
383 
384 //==========================================================================
385 template<class MatrixType>
387  return(ApplyFlops_);
388 }
389 
390 //==========================================================================
391 template<class MatrixType>
392 typename Teuchos::ScalarTraits<typename MatrixType::scalar_type>::magnitudeType
394 {
395  return(Condest_);
396 }
397 
398 //==========================================================================
399 template<class MatrixType>
400 typename Teuchos::ScalarTraits<typename MatrixType::scalar_type>::magnitudeType
402  CondestType CT,
403  typename MatrixType::local_ordinal_type MaxIters,
404  magnitude_type Tol,
405  const Teuchos::Ptr<const Tpetra::RowMatrix<typename MatrixType::scalar_type,
406  typename MatrixType::local_ordinal_type,
407  typename MatrixType::global_ordinal_type,
408  typename MatrixType::node_type> > &matrix)
409 {
410  if (!isComputed()) // cannot compute right now
411  return(-1.0);
412 
413  // always compute it. Call Condest() with no parameters to get
414  // the previous estimate.
415  Condest_ = Ifpack2::Condest(*this, CT, MaxIters, Tol, matrix);
416 
417  return(Condest_);
418 }
419 
420 //==========================================================================
421 template<class MatrixType>
423  const Tpetra::MultiVector<typename MatrixType::scalar_type,
424  typename MatrixType::local_ordinal_type,
425  typename MatrixType::global_ordinal_type,
426  typename MatrixType::node_type>& X,
427  Tpetra::MultiVector<typename MatrixType::scalar_type,
428  typename MatrixType::local_ordinal_type,
429  typename MatrixType::global_ordinal_type,
430  typename MatrixType::node_type>& Y,
431  Teuchos::ETransp mode,
432  scalar_type alpha,
433  scalar_type beta) const
434 {
435  using Teuchos::as;
436  using Teuchos::RCP;
437  using Teuchos::rcp;
438  using Teuchos::rcpFromRef;
439  typedef Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type> MV;
440 
441  TEUCHOS_TEST_FOR_EXCEPTION(
442  ! isComputed (),
443  std::runtime_error,
444  "Ifpack2::Relaxation::apply: You must call compute() on this Ifpack2 "
445  "preconditioner instance before you may call apply(). You may call "
446  "isComputed() to find out if compute() has been called already.");
447 
448  TEUCHOS_TEST_FOR_EXCEPTION(
449  X.getNumVectors() != Y.getNumVectors(),
450  std::runtime_error,
451  "Ifpack2::Relaxation::apply: X and Y have different numbers of columns. "
452  "X has " << X.getNumVectors() << " columns, but Y has "
453  << Y.getNumVectors() << " columns.");
454 
455  TEUCHOS_TEST_FOR_EXCEPTION(
456  beta != STS::zero (), std::logic_error,
457  "Ifpack2::Relaxation::apply: beta = " << beta << " != 0 case not "
458  "implemented.");
459  {
460  // Reset the timer each time, since Relaxation uses the same Time
461  // object to track times for different methods.
462  Teuchos::TimeMonitor timeMon (*Time_, true);
463 
464  // Special case: alpha == 0.
465  if (alpha == STS::zero ()) {
466  // No floating-point operations, so no need to update a count.
467  Y.putScalar (STS::zero ());
468  }
469  else {
470  // If X and Y are pointing to the same memory location,
471  // we need to create an auxiliary vector, Xcopy
472  RCP<const MV> Xcopy;
473  if (X.getLocalMV().getValues() == Y.getLocalMV().getValues()) {
474  Xcopy = rcp (new MV (X));
475  }
476  else {
477  Xcopy = rcpFromRef (X);
478  }
479 
480  // Each of the following methods updates the flop count itself.
481  // All implementations handle zeroing out the starting solution
482  // (if necessary) themselves.
483  switch (PrecType_) {
484  case Ifpack2::JACOBI:
485  ApplyInverseJacobi(*Xcopy,Y);
486  break;
487  case Ifpack2::GS:
488  ApplyInverseGS(*Xcopy,Y);
489  break;
490  case Ifpack2::SGS:
491  ApplyInverseSGS(*Xcopy,Y);
492  break;
493  default:
494  TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error,
495  "Ifpack2::Relaxation::apply: Invalid preconditioner type enum value "
496  << PrecType_ << ". Please report this bug to the Ifpack2 developers.");
497  }
498  if (alpha != STS::one ()) {
499  Y.scale (alpha);
500  const double numGlobalRows = as<double> (A_->getGlobalNumRows ());
501  const double numVectors = as<double> (Y.getNumVectors ());
502  ApplyFlops_ += numGlobalRows * numVectors;
503  }
504  }
505  }
506  ApplyTime_ += Time_->totalElapsedTime ();
507  ++NumApply_;
508 }
509 
510 //==========================================================================
511 template<class MatrixType>
513  const Tpetra::MultiVector<typename MatrixType::scalar_type,
514  typename MatrixType::local_ordinal_type,
515  typename MatrixType::global_ordinal_type,
516  typename MatrixType::node_type>& X,
517  Tpetra::MultiVector<typename MatrixType::scalar_type,
518  typename MatrixType::local_ordinal_type,
519  typename MatrixType::global_ordinal_type,
520  typename MatrixType::node_type>& Y,
521  Teuchos::ETransp mode) const
522 {
523  TEUCHOS_TEST_FOR_EXCEPTION(isComputed() == false, std::runtime_error,
524  "Ifpack2::Relaxation::applyMat() ERROR: isComputed() must be true prior to calling applyMat().");
525  TEUCHOS_TEST_FOR_EXCEPTION(X.getNumVectors() != Y.getNumVectors(), std::runtime_error,
526  "Ifpack2::Relaxation::applyMat() ERROR: X.getNumVectors() != Y.getNumVectors().");
527  A_->apply(X, Y, mode);
528 }
529 
530 //==========================================================================
531 template<class MatrixType>
533  // Initialization for Relaxation is trivial, so we say it takes zero time.
534  //InitializeTime_ += Time_->totalElapsedTime ();
535  ++NumInitialize_;
536  IsInitialized_ = true;
537 }
538 
539 //==========================================================================
540 template<class MatrixType>
542 {
543  using Teuchos::Array;
544  using Teuchos::ArrayRCP;
545  using Teuchos::ArrayView;
546  using Teuchos::as;
547  using Teuchos::Comm;
548  using Teuchos::RCP;
549  using Teuchos::rcp;
550  using Teuchos::REDUCE_MAX;
551  using Teuchos::REDUCE_MIN;
552  using Teuchos::REDUCE_SUM;
553  using Teuchos::rcp_dynamic_cast;
554  using Teuchos::reduceAll;
555  typedef Tpetra::Vector<scalar_type,local_ordinal_type,global_ordinal_type,node_type> vector_type;
556  const scalar_type zero = STS::zero ();
557  const scalar_type one = STS::one ();
558 
559  // We don't count initialization in compute() time.
560  if (! isInitialized ()) {
561  initialize ();
562  }
563 
564  {
565  // Reset the timer each time, since Relaxation uses the same Time
566  // object to track times for different methods.
567  Teuchos::TimeMonitor timeMon (*Time_, true);
568 
569  // Reset state.
570  IsComputed_ = false;
571  Condest_ = -STM::one ();
572 
573  TEUCHOS_TEST_FOR_EXCEPTION(
574  NumSweeps_ < 0, std::logic_error,
575  "Ifpack2::Relaxation::compute: NumSweeps_ = " << NumSweeps_ << " < 0. "
576  "Please report this bug to the Ifpack2 developers.");
577 
578  Diagonal_ = rcp (new vector_type (A_->getRowMap ()));
579 
580  TEUCHOS_TEST_FOR_EXCEPTION(
581  Diagonal_.is_null (), std::logic_error,
582  "Ifpack2::Relaxation::compute: Vector of diagonal entries has not been "
583  "created yet. Please report this bug to the Ifpack2 developers.");
584 
585  // Extract the diagonal entries. The CrsMatrix static graph
586  // version is faster for subsequent calls to compute(), since it
587  // caches the diagonal offsets.
588  //
589  // isStaticGraph() == true means that the matrix was created with
590  // a const graph. The only requirement is that the structure of
591  // the matrix never changes, so isStaticGraph() == true is a bit
592  // more conservative than we need. However, Tpetra doesn't (as of
593  // 05 Apr 2013) have a way to tell if the graph hasn't changed
594  // since the last time we used it.
595  {
596  RCP<const MatrixType> crsMat = rcp_dynamic_cast<const MatrixType> (A_);
597  if (crsMat.is_null () || ! crsMat->isStaticGraph ()) {
598  A_->getLocalDiagCopy (*Diagonal_); // slow path
599  } else {
600  if (! savedDiagOffsets_) { // we haven't precomputed offsets
601  crsMat->getLocalDiagOffsets (diagOffsets_);
602  savedDiagOffsets_ = true;
603  }
604  crsMat->getLocalDiagCopy (*Diagonal_, diagOffsets_ ());
605 #ifdef HAVE_TPETRA_DEBUG
606  // Validate the fast-path diagonal against the slow-path diagonal.
607  vector_type D_copy (A_->getRowMap ());
608  A_->getLocalDiagCopy (D_copy);
609  D_copy.update (STS::one (), *Diagonal_, -STS::one ());
610  const magnitude_type err = D_copy.normInf ();
611  // The two diagonals should be exactly the same, so their
612  // difference should be exactly zero.
613  TEUCHOS_TEST_FOR_EXCEPTION(
614  err != STM::zero(), std::logic_error, "Ifpack2::Relaxation::compute: "
615  "\"fast-path\" diagonal computation failed. \\|D1 - D2\\|_inf = "
616  << err << ".");
617 #endif // HAVE_TPETRA_DEBUG
618  }
619  }
620 
621  // If we're checking the computed inverse diagonal, then keep a
622  // copy of the original diagonal entries for later comparison.
623  RCP<vector_type> origDiag;
624  if (checkDiagEntries_) {
625  origDiag = rcp (new vector_type (A_->getRowMap ()));
626  *origDiag = *Diagonal_;
627  }
628 
629  // "Host view" means that if the Node type is a GPU Node, the
630  // ArrayRCP points to host memory, not device memory. It will
631  // write back to device memory (Diagonal_) at end of scope.
632  ArrayRCP<scalar_type> diagHostView = Diagonal_->get1dViewNonConst ();
633 
634  // The view below is only valid as long as diagHostView is within
635  // scope. We extract a raw pointer in release mode because we
636  // don't trust older versions of compilers (like GCC 4.4.x or
637  // Intel < 13) to optimize away ArrayView::operator[].
638 #ifdef HAVE_IFPACK2_DEBUG
639  ArrayView<scalar_type> diag = diagHostView ();
640 #else
641  scalar_type* KOKKOSCLASSIC_RESTRICT const diag = diagHostView.getRawPtr ();
642 #endif // HAVE_IFPACK2_DEBUG
643 
644  const size_t numMyRows = A_->getNodeNumRows ();
645 
646  // Setup for L1 Methods.
647  // Here we add half the value of the off-processor entries in the row,
648  // but only if diagonal isn't sufficiently large.
649  //
650  // This follows from Equation (6.5) in: Baker, Falgout, Kolev and
651  // Yang. "Multigrid Smoothers for Ultraparallel Computing." SIAM
652  // J. Sci. Comput., Vol. 33, No. 5. (2011), pp. 2864-2887.
653  if (DoL1Method_ && IsParallel_) {
654  const scalar_type two = one + one;
655  const size_t maxLength = A_->getNodeMaxNumRowEntries ();
656  Array<local_ordinal_type> indices (maxLength);
657  Array<scalar_type> values (maxLength);
658  size_t numEntries;
659 
660  for (size_t i = 0; i < numMyRows; ++i) {
661  A_->getLocalRowCopy (i, indices (), values (), numEntries);
662  magnitude_type diagonal_boost = STM::zero ();
663  for (size_t k = 0 ; k < numEntries ; ++k) {
664  if (as<size_t> (indices[k]) > numMyRows) {
665  diagonal_boost += STS::magnitude (values[k] / two);
666  }
667  }
668  if (STS::magnitude (diag[i]) < L1Eta_ * diagonal_boost) {
669  diag[i] += diagonal_boost;
670  }
671  }
672  }
673 
674  //
675  // Invert the diagonal entries of the matrix (not in place).
676  //
677 
678  // Precompute some quantities for "fixing" zero or tiny diagonal
679  // entries. We'll only use them if this "fixing" is enabled.
680  //
681  // SmallTraits covers for the lack of eps() in
682  // Teuchos::ScalarTraits when its template parameter is not a
683  // floating-point type. (Ifpack2 sometimes gets instantiated for
684  // integer Scalar types.)
685  const scalar_type oneOverMinDiagVal = (MinDiagonalValue_ == zero) ?
686  one / SmallTraits<scalar_type>::eps () :
687  one / MinDiagonalValue_;
688  // It's helpful not to have to recompute this magnitude each time.
689  const magnitude_type minDiagValMag = STS::magnitude (MinDiagonalValue_);
690 
691  if (checkDiagEntries_) {
692  //
693  // Check diagonal elements, replace zero elements with the minimum
694  // diagonal value, and store their inverses. Count the number of
695  // "small" and zero diagonal entries while we're at it.
696  //
697  size_t numSmallDiagEntries = 0; // "small" includes zero
698  size_t numZeroDiagEntries = 0; // # zero diagonal entries
699  size_t numNegDiagEntries = 0; // # negative (real parts of) diagonal entries
700 
701  // As we go, keep track of the diagonal entries with the least and
702  // greatest magnitude. We could use the trick of starting the min
703  // with +Inf and the max with -Inf, but that doesn't work if
704  // scalar_type is a built-in integer type. Thus, we have to start
705  // by reading the first diagonal entry redundantly.
706  scalar_type minMagDiagEntry = zero;
707  scalar_type maxMagDiagEntry = zero;
708  magnitude_type minMagDiagEntryMag = STM::zero ();
709  magnitude_type maxMagDiagEntryMag = STM::zero ();
710  if (numMyRows > 0) {
711  const scalar_type d_0 = diag[0];
712  const magnitude_type d_0_mag = STS::magnitude (d_0);
713  minMagDiagEntry = d_0;
714  maxMagDiagEntry = d_0;
715  minMagDiagEntryMag = d_0_mag;
716  maxMagDiagEntryMag = d_0_mag;
717  }
718 
719  // Go through all the diagonal entries. Compute counts of
720  // small-magnitude, zero, and negative-real-part entries. Invert
721  // the diagonal entries that aren't too small. For those that are
722  // too small in magnitude, replace them with 1/MinDiagonalValue_
723  // (or 1/eps if MinDiagonalValue_ happens to be zero).
724  for (size_t i = 0 ; i < numMyRows; ++i) {
725  const scalar_type d_i = diag[i];
726  const magnitude_type d_i_mag = STS::magnitude (d_i);
727  const magnitude_type d_i_real = STS::real (d_i);
728 
729  // We can't compare complex numbers, but we can compare their
730  // real parts.
731  if (d_i_real < STM::zero ()) {
732  ++numNegDiagEntries;
733  }
734  if (d_i_mag < minMagDiagEntryMag) {
735  minMagDiagEntry = d_i;
736  minMagDiagEntryMag = d_i_mag;
737  }
738  if (d_i_mag > maxMagDiagEntryMag) {
739  maxMagDiagEntry = d_i;
740  maxMagDiagEntryMag = d_i_mag;
741  }
742 
743  if (fixTinyDiagEntries_) {
744  // <= not <, in case minDiagValMag is zero.
745  if (d_i_mag <= minDiagValMag) {
746  ++numSmallDiagEntries;
747  if (d_i_mag == STM::zero ()) {
748  ++numZeroDiagEntries;
749  }
750  diag[i] = oneOverMinDiagVal;
751  } else {
752  diag[i] = one / d_i;
753  }
754  }
755  else { // Don't fix zero or tiny diagonal entries.
756  // <= not <, in case minDiagValMag is zero.
757  if (d_i_mag <= minDiagValMag) {
758  ++numSmallDiagEntries;
759  if (d_i_mag == STM::zero ()) {
760  ++numZeroDiagEntries;
761  }
762  }
763  diag[i] = one / d_i;
764  }
765  }
766 
767  // We're done computing the inverse diagonal, so invalidate the view.
768  // This ensures that the operations below, that use methods on Vector,
769  // produce correct results even on a GPU Node.
770  diagHostView = Teuchos::null;
771 
772  // Count floating-point operations of computing the inverse diagonal.
773  //
774  // FIXME (mfh 30 Mar 2013) Shouldn't counts be global, not local?
775  if (STS::isComplex) { // magnitude: at least 3 flops per diagonal entry
776  ComputeFlops_ += 4.0 * numMyRows;
777  } else {
778  ComputeFlops_ += numMyRows;
779  }
780 
781  // Collect global data about the diagonal entries. Only do this
782  // (which involves O(1) all-reduces) if the user asked us to do
783  // the extra work.
784  //
785  // FIXME (mfh 28 Mar 2013) This is wrong if some processes have
786  // zero rows. Fixing this requires one of two options:
787  //
788  // 1. Use a custom reduction operation that ignores processes
789  // with zero diagonal entries.
790  // 2. Split the communicator, compute all-reduces using the
791  // subcommunicator over processes that have a nonzero number
792  // of diagonal entries, and then broadcast from one of those
793  // processes (if there is one) to the processes in the other
794  // subcommunicator.
795  const Comm<int>& comm = * (A_->getRowMap ()->getComm ());
796 
797  // Compute global min and max magnitude of entries.
798  Array<magnitude_type> localVals (2);
799  localVals[0] = minMagDiagEntryMag;
800  // (- (min (- x))) is the same as (max x).
801  localVals[1] = -maxMagDiagEntryMag;
802  Array<magnitude_type> globalVals (2);
803  reduceAll<int, magnitude_type> (comm, REDUCE_MIN, 2,
804  localVals.getRawPtr (),
805  globalVals.getRawPtr ());
806  globalMinMagDiagEntryMag_ = globalVals[0];
807  globalMaxMagDiagEntryMag_ = -globalVals[1];
808 
809  Array<size_t> localCounts (3);
810  localCounts[0] = numSmallDiagEntries;
811  localCounts[1] = numZeroDiagEntries;
812  localCounts[2] = numNegDiagEntries;
813  Array<size_t> globalCounts (3);
814  reduceAll<int, size_t> (comm, REDUCE_SUM, 3,
815  localCounts.getRawPtr (),
816  globalCounts.getRawPtr ());
817  globalNumSmallDiagEntries_ = globalCounts[0];
818  globalNumZeroDiagEntries_ = globalCounts[1];
819  globalNumNegDiagEntries_ = globalCounts[2];
820 
821  // Forestall "set but not used" compiler warnings.
822  (void) minMagDiagEntry;
823  (void) maxMagDiagEntry;
824 
825  // Compute and save the difference between the computed inverse
826  // diagonal, and the original diagonal's inverse.
827  RCP<vector_type> diff = rcp (new vector_type (A_->getRowMap ()));
828  diff->reciprocal (*origDiag);
829  diff->update (-one, *Diagonal_, one);
830  globalDiagNormDiff_ = diff->norm2 ();
831  }
832  else { // don't check diagonal elements
833  if (fixTinyDiagEntries_) {
834  // Go through all the diagonal entries. Invert those that
835  // aren't too small in magnitude. For those that are too
836  // small in magnitude, replace them with oneOverMinDiagVal.
837  for (size_t i = 0 ; i < numMyRows; ++i) {
838  const scalar_type d_i = diag[i];
839  const magnitude_type d_i_mag = STS::magnitude (d_i);
840 
841  // <= not <, in case minDiagValMag is zero.
842  if (d_i_mag <= minDiagValMag) {
843  diag[i] = oneOverMinDiagVal;
844  } else {
845  diag[i] = one / d_i;
846  }
847  }
848  }
849  else { // don't fix tiny or zero diagonal entries
850  for (size_t i = 0 ; i < numMyRows; ++i) {
851  diag[i] = one / diag[i];
852  }
853  }
854  if (STS::isComplex) { // magnitude: at least 3 flops per diagonal entry
855  ComputeFlops_ += 4.0 * numMyRows;
856  } else {
857  ComputeFlops_ += numMyRows;
858  }
859  }
860 
861  if (IsParallel_ && ((PrecType_ == Ifpack2::GS) || (PrecType_ == Ifpack2::SGS))) {
862  Importer_ = A_->getGraph ()->getImporter ();
863  // mfh 21 Mar 2013: The Import object may be null, but in that
864  // case, the domain and column Maps are the same and we don't
865  // need to Import anyway.
866  }
867  } // end TimeMonitor scope
868 
869  ComputeTime_ += Time_->totalElapsedTime ();
870  ++NumCompute_;
871  IsComputed_ = true;
872 }
873 
874 //==========================================================================
875 template<class MatrixType>
877  const Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& X,
878  Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& Y) const
879 {
880  using Teuchos::as;
881  typedef Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type> MV;
882 
883  const double numGlobalRows = as<double> (A_->getGlobalNumRows ());
884  const double numVectors = as<double> (X.getNumVectors ());
885  if (ZeroStartingSolution_) {
886  // For the first Jacobi sweep, if we are allowed to assume that
887  // the initial guess is zero, then Jacobi is just diagonal
888  // scaling. (A_ij * x_j = 0 for i != j, since x_j = 0.)
889  // Compute it as Y(i,j) = DampingFactor_ * X(i,j) * D(i).
890  Y.elementWiseMultiply (DampingFactor_, *Diagonal_, X, STS::zero ());
891 
892  // Count (global) floating-point operations. Ifpack2 represents
893  // this as a floating-point number rather than an integer, so that
894  // overflow (for a very large number of calls, or a very large
895  // problem) is approximate instead of catastrophic.
896  double flopUpdate = 0.0;
897  if (DampingFactor_ == STS::one ()) {
898  // Y(i,j) = X(i,j) * D(i): one multiply for each entry of Y.
899  flopUpdate = numGlobalRows * numVectors;
900  } else {
901  // Y(i,j) = DampingFactor_ * X(i,j) * D(i):
902  // Two multiplies per entry of Y.
903  flopUpdate = 2.0 * numGlobalRows * numVectors;
904  }
905  ApplyFlops_ += flopUpdate;
906  if (NumSweeps_ == 1) {
907  return;
908  }
909  }
910  // If we were allowed to assume that the starting guess was zero,
911  // then we have already done the first sweep above.
912  const int startSweep = ZeroStartingSolution_ ? 1 : 0;
913  // We don't need to initialize the result MV, since the sparse
914  // mat-vec will clobber its contents anyway.
915  MV A_times_Y (Y.getMap (), as<size_t>(numVectors), false);
916  for (int j = startSweep; j < NumSweeps_; ++j) {
917  // Each iteration: Y = Y + \omega D^{-1} (X - A*Y)
918  applyMat (Y, A_times_Y);
919  A_times_Y.update (STS::one (), X, -STS::one ());
920  Y.elementWiseMultiply (DampingFactor_, *Diagonal_, A_times_Y, STS::one ());
921  }
922 
923  // For each column of output, for each pass over the matrix:
924  //
925  // - One + and one * for each matrix entry
926  // - One / and one + for each row of the matrix
927  // - If the damping factor is not one: one * for each row of the
928  // matrix. (It's not fair to count this if the damping factor is
929  // one, since the implementation could skip it. Whether it does
930  // or not is the implementation's choice.)
931 
932  // Floating-point operations due to the damping factor, per matrix
933  // row, per direction, per columm of output.
934  const double numGlobalNonzeros = as<double> (A_->getGlobalNumEntries ());
935  const double dampingFlops = (DampingFactor_ == STS::one ()) ? 0.0 : 1.0;
936  ApplyFlops_ += as<double> (NumSweeps_ - startSweep) * numVectors *
937  (2.0 * numGlobalRows + 2.0 * numGlobalNonzeros + dampingFlops);
938 }
939 
940 //==========================================================================
941 template<class MatrixType>
943  const Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& X,
944  Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& Y) const
945 {
946  using Teuchos::RCP;
947  using Teuchos::rcp_dynamic_cast;
948 
949  // FIXME (mfh 02 Jan 2013) This assumes that MatrixType is a
950  // CrsMatrix specialization.
951  RCP<const MatrixType> crsMat = rcp_dynamic_cast<const MatrixType> (A_);
952 
953  // The CrsMatrix version is faster, because it can access the sparse
954  // matrix data directly, rather than by copying out each row's data
955  // in turn. Thus, we check whether the RowMatrix is really a
956  // CrsMatrix.
957  if (! crsMat.is_null ()) {
958  ApplyInverseGS_CrsMatrix (*crsMat, X, Y);
959  }
960  else {
961  ApplyInverseGS_RowMatrix (X, Y);
962  }
963 }
964 
965 //==========================================================================
966 template<class MatrixType>
968  const Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& X,
969  Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& Y) const
970 {
971  using Teuchos::Array;
972  using Teuchos::ArrayRCP;
973  using Teuchos::as;
974  using Teuchos::RCP;
975  using Teuchos::rcp;
976  using Teuchos::rcpFromRef;
977  typedef Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type> MV;
978 
979  // Tpetra's GS implementation for CrsMatrix handles zeroing out the
980  // starting multivector itself. The generic RowMatrix version here
981  // does not, so we have to zero out Y here.
982  if (ZeroStartingSolution_) {
983  Y.putScalar (STS::zero ());
984  }
985 
986  const size_t NumVectors = X.getNumVectors ();
987  const size_t maxLength = A_->getNodeMaxNumRowEntries ();
988  Array<local_ordinal_type> Indices (maxLength);
989  Array<scalar_type> Values (maxLength);
990 
991  RCP<MV> Y2;
992  if (IsParallel_) {
993  if (Importer_.is_null ()) { // domain and column Maps are the same.
994  // We will copy Y into Y2 below, so no need to fill with zeros here.
995  Y2 = rcp (new MV (Y.getMap (), NumVectors, false));
996  } else {
997  // FIXME (mfh 21 Mar 2013) We probably don't need to fill with
998  // zeros here, since we are doing an Import into Y2 below
999  // anyway. However, it doesn't hurt correctness.
1000  Y2 = rcp (new MV (Importer_->getTargetMap (), NumVectors));
1001  }
1002  }
1003  else {
1004  Y2 = rcpFromRef (Y);
1005  }
1006 
1007  // extract views (for nicer and faster code)
1008  ArrayRCP<ArrayRCP<scalar_type> > y_ptr = Y.get2dViewNonConst();
1009  ArrayRCP<ArrayRCP<scalar_type> > y2_ptr = Y2->get2dViewNonConst();
1010  ArrayRCP<ArrayRCP<const scalar_type> > x_ptr = X.get2dView();
1011  ArrayRCP<const scalar_type> d_ptr = Diagonal_->get1dView();
1012 
1013  const size_t numMyRows = A_->getNodeNumRows ();
1014  for (int j = 0; j < NumSweeps_; j++) {
1015  // data exchange is here, once per sweep
1016  if (IsParallel_) {
1017  if (Importer_.is_null ()) {
1018  *Y2 = Y; // just copy, since domain and column Maps are the same
1019  } else {
1020  Y2->doImport (Y, *Importer_, Tpetra::INSERT);
1021  }
1022  }
1023 
1024  if (! DoBackwardGS_) { // Forward sweep
1025  for (size_t i = 0; i < numMyRows; ++i) {
1026  size_t NumEntries;
1027  A_->getLocalRowCopy (as<local_ordinal_type> (i), Indices (), Values (), NumEntries);
1028 
1029  for (size_t m = 0; m < NumVectors; ++m) {
1030  scalar_type dtemp = STS::zero ();
1031  for (size_t k = 0; k < NumEntries; ++k) {
1032  const local_ordinal_type col = Indices[k];
1033  dtemp += Values[k] * y2_ptr[m][col];
1034  }
1035  y2_ptr[m][i] += DampingFactor_ * d_ptr[i] * (x_ptr[m][i] - dtemp);
1036  }
1037  }
1038  }
1039  else { // Backward sweep
1040  // ptrdiff_t is the same size as size_t, but is signed. Being
1041  // signed is important so that i >= 0 is not trivially true.
1042  for (ptrdiff_t i = as<ptrdiff_t> (numMyRows) - 1; i >= 0; --i) {
1043  size_t NumEntries;
1044  A_->getLocalRowCopy (as<local_ordinal_type> (i), Indices (), Values (), NumEntries);
1045 
1046  for (size_t m = 0; m < NumVectors; ++m) {
1047  scalar_type dtemp = STS::zero ();
1048  for (size_t k = 0; k < NumEntries; ++k) {
1049  const local_ordinal_type col = Indices[k];
1050  dtemp += Values[k] * y2_ptr[m][col];
1051  }
1052  y2_ptr[m][i] += DampingFactor_ * d_ptr[i] * (x_ptr[m][i] - dtemp);
1053  }
1054  }
1055  }
1056 
1057  // FIXME (mfh 02 Jan 2013) This is only correct if row Map == range Map.
1058  if (IsParallel_) {
1059  Y = *Y2;
1060  }
1061  }
1062 
1063  // See flop count discussion in implementation of ApplyInverseGS_CrsMatrix().
1064  const double dampingFlops = (DampingFactor_ == STS::one()) ? 0.0 : 1.0;
1065  const double numVectors = as<double> (X.getNumVectors ());
1066  const double numGlobalRows = as<double> (A_->getGlobalNumRows ());
1067  const double numGlobalNonzeros = as<double> (A_->getGlobalNumEntries ());
1068  ApplyFlops_ += 2.0 * NumSweeps_ * numVectors *
1069  (2.0 * numGlobalRows + 2.0 * numGlobalNonzeros + dampingFlops);
1070 }
1071 
1072 //==========================================================================
1073 template<class MatrixType>
1074 void
1076 ApplyInverseGS_CrsMatrix (const MatrixType& A,
1077  const Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& X,
1078  Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& Y) const
1079 {
1080  using Teuchos::as;
1081 
1082  const Tpetra::ESweepDirection direction =
1083  DoBackwardGS_ ? Tpetra::Backward : Tpetra::Forward;
1084  A.gaussSeidelCopy (Y, X, *Diagonal_, DampingFactor_, direction,
1085  NumSweeps_, ZeroStartingSolution_);
1086 
1087  // For each column of output, for each sweep over the matrix:
1088  //
1089  // - One + and one * for each matrix entry
1090  // - One / and one + for each row of the matrix
1091  // - If the damping factor is not one: one * for each row of the
1092  // matrix. (It's not fair to count this if the damping factor is
1093  // one, since the implementation could skip it. Whether it does
1094  // or not is the implementation's choice.)
1095 
1096  // Floating-point operations due to the damping factor, per matrix
1097  // row, per direction, per columm of output.
1098  const double dampingFlops = (DampingFactor_ == STS::one()) ? 0.0 : 1.0;
1099  const double numVectors = as<double> (X.getNumVectors ());
1100  const double numGlobalRows = as<double> (A_->getGlobalNumRows ());
1101  const double numGlobalNonzeros = as<double> (A_->getGlobalNumEntries ());
1102  ApplyFlops_ += NumSweeps_ * numVectors *
1103  (2.0 * numGlobalRows + 2.0 * numGlobalNonzeros + dampingFlops);
1104 }
1105 
1106 //==========================================================================
1107 template<class MatrixType>
1109  const Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& X,
1110  Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& Y) const
1111 {
1112  using Teuchos::RCP;
1113  using Teuchos::rcp_dynamic_cast;
1114 
1115  // FIXME (mfh 02 Jan 2013) This assumes that MatrixType is a
1116  // CrsMatrix specialization. Alas, C++ doesn't let me do pattern
1117  // matching on template types. I could just cast to the four
1118  // template argument specialization of CrsMatrix, but that would
1119  // miss nondefault values of the fifth template parameter of
1120  // CrsMatrix.
1121  //
1122  // Another way to solve this problem would be to move
1123  // implementations of relaxations into Tpetra. Tpetra::RowMatrix
1124  // could provide a gaussSeidel, etc. interface, with a default
1125  // implementation (same as the RowMatrix version here in Ifpack2
1126  // now), and Tpetra::CrsMatrix specializations could reimplement
1127  // this however they wish.
1128  RCP<const MatrixType> crsMat = rcp_dynamic_cast<const MatrixType> (A_);
1129 
1130  // The CrsMatrix version is faster, because it can access the sparse
1131  // matrix data directly, rather than by copying out each row's data
1132  // in turn. Thus, we check whether the RowMatrix is really a
1133  // CrsMatrix.
1134  if (! crsMat.is_null ()) {
1135  ApplyInverseSGS_CrsMatrix (*crsMat, X, Y);
1136  }
1137  else {
1138  ApplyInverseSGS_RowMatrix (X, Y);
1139  }
1140 }
1141 
1142 //==========================================================================
1143 template<class MatrixType>
1145  const Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& X,
1146  Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& Y) const
1147 {
1148  using Teuchos::Array;
1149  using Teuchos::ArrayRCP;
1150  using Teuchos::as;
1151  using Teuchos::RCP;
1152  using Teuchos::rcp;
1153  using Teuchos::rcpFromRef;
1154  typedef Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type> MV;
1155 
1156  // Tpetra's GS implementation for CrsMatrix handles zeroing out the
1157  // starting multivector itself. The generic RowMatrix version here
1158  // does not, so we have to zero out Y here.
1159  if (ZeroStartingSolution_) {
1160  Y.putScalar (STS::zero ());
1161  }
1162 
1163  const size_t NumVectors = X.getNumVectors ();
1164  const size_t maxLength = A_->getNodeMaxNumRowEntries ();
1165  Array<local_ordinal_type> Indices (maxLength);
1166  Array<scalar_type> Values (maxLength);
1167 
1168  RCP<MV> Y2;
1169  if (IsParallel_) {
1170  if (Importer_.is_null ()) { // domain and column Maps are the same.
1171  // We will copy Y into Y2 below, so no need to fill with zeros here.
1172  Y2 = rcp (new MV (Y.getMap (), NumVectors, false));
1173  } else {
1174  // FIXME (mfh 21 Mar 2013) We probably don't need to fill with
1175  // zeros here, since we are doing an Import into Y2 below
1176  // anyway. However, it doesn't hurt correctness.
1177  Y2 = rcp (new MV (Importer_->getTargetMap (), NumVectors));
1178  }
1179  }
1180  else {
1181  Y2 = rcpFromRef (Y);
1182  }
1183 
1184  ArrayRCP<ArrayRCP<scalar_type> > y_ptr = Y.get2dViewNonConst ();
1185  ArrayRCP<ArrayRCP<scalar_type> > y2_ptr = Y2->get2dViewNonConst ();
1186  ArrayRCP<ArrayRCP<const scalar_type> > x_ptr = X.get2dView ();
1187  ArrayRCP<const scalar_type> d_ptr = Diagonal_->get1dView ();
1188 
1189  const size_t numMyRows = A_->getNodeNumRows ();
1190 
1191  for (int iter = 0; iter < NumSweeps_; ++iter) {
1192  // only one data exchange per sweep
1193  if (IsParallel_) {
1194  if (Importer_.is_null ()) {
1195  *Y2 = Y; // just copy, since domain and column Maps are the same
1196  } else {
1197  Y2->doImport (Y, *Importer_, Tpetra::INSERT);
1198  }
1199  }
1200 
1201  for (size_t i = 0; i < numMyRows; ++i) {
1202  const scalar_type diag = d_ptr[i];
1203  size_t NumEntries;
1204  A_->getLocalRowCopy (as<local_ordinal_type> (i), Indices (), Values (), NumEntries);
1205 
1206  for (size_t m = 0; m < NumVectors; ++m) {
1207  scalar_type dtemp = STS::zero ();
1208  for (size_t k = 0; k < NumEntries; ++k) {
1209  const local_ordinal_type col = Indices[k];
1210  dtemp += Values[k] * y2_ptr[m][col];
1211  }
1212  y2_ptr[m][i] += DampingFactor_ * (x_ptr[m][i] - dtemp) * diag;
1213  }
1214  }
1215 
1216  // ptrdiff_t is the same size as size_t, but is signed. Being
1217  // signed is important so that i >= 0 is not trivially true.
1218  for (ptrdiff_t i = as<ptrdiff_t> (numMyRows) - 1; i >= 0; --i) {
1219  const scalar_type diag = d_ptr[i];
1220  size_t NumEntries;
1221  A_->getLocalRowCopy (as<local_ordinal_type> (i), Indices (), Values (), NumEntries);
1222 
1223  for (size_t m = 0; m < NumVectors; ++m) {
1224  scalar_type dtemp = STS::zero ();
1225  for (size_t k = 0; k < NumEntries; ++k) {
1226  const local_ordinal_type col = Indices[k];
1227  dtemp += Values[k] * y2_ptr[m][col];
1228  }
1229  y2_ptr[m][i] += DampingFactor_ * (x_ptr[m][i] - dtemp) * diag;
1230  }
1231  }
1232 
1233  // FIXME (mfh 02 Jan 2013) This is only correct if row Map == range Map.
1234  if (IsParallel_) {
1235  Y = *Y2;
1236  }
1237  }
1238 
1239  // See flop count discussion in implementation of ApplyInverseSGS_CrsMatrix().
1240  const double dampingFlops = (DampingFactor_ == STS::one()) ? 0.0 : 1.0;
1241  const double numVectors = as<double> (X.getNumVectors ());
1242  const double numGlobalRows = as<double> (A_->getGlobalNumRows ());
1243  const double numGlobalNonzeros = as<double> (A_->getGlobalNumEntries ());
1244  ApplyFlops_ += 2.0 * NumSweeps_ * numVectors *
1245  (2.0 * numGlobalRows + 2.0 * numGlobalNonzeros + dampingFlops);
1246 }
1247 
1248 //==========================================================================
1249 template<class MatrixType>
1250 void
1252 ApplyInverseSGS_CrsMatrix (const MatrixType& A,
1253  const Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& X,
1254  Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& Y) const
1255 {
1256  using Teuchos::as;
1257 
1258  const Tpetra::ESweepDirection direction = Tpetra::Symmetric;
1259  A.gaussSeidelCopy (Y, X, *Diagonal_, DampingFactor_, direction,
1260  NumSweeps_, ZeroStartingSolution_);
1261 
1262  // For each column of output, for each sweep over the matrix:
1263  //
1264  // - One + and one * for each matrix entry
1265  // - One / and one + for each row of the matrix
1266  // - If the damping factor is not one: one * for each row of the
1267  // matrix. (It's not fair to count this if the damping factor is
1268  // one, since the implementation could skip it. Whether it does
1269  // or not is the implementation's choice.)
1270  //
1271  // Each sweep of symmetric Gauss-Seidel / SOR counts as two sweeps,
1272  // one forward and one backward.
1273 
1274  // Floating-point operations due to the damping factor, per matrix
1275  // row, per direction, per columm of output.
1276  const double dampingFlops = (DampingFactor_ == STS::one()) ? 0.0 : 1.0;
1277  const double numVectors = as<double> (X.getNumVectors ());
1278  const double numGlobalRows = as<double> (A_->getGlobalNumRows ());
1279  const double numGlobalNonzeros = as<double> (A_->getGlobalNumEntries ());
1280  ApplyFlops_ += 2.0 * NumSweeps_ * numVectors *
1281  (2.0 * numGlobalRows + 2.0 * numGlobalNonzeros + dampingFlops);
1282 }
1283 
1284 //==========================================================================
1285 template<class MatrixType>
1287  using Teuchos::TypeNameTraits;
1288  std::ostringstream os;
1289 
1290  std::string status;
1291  if (isInitialized ()) {
1292  status = "initialized";
1293  if (isComputed ()) {
1294  status += ", computed";
1295  } else {
1296  status += ", not computed";
1297  }
1298  } else {
1299  status = "not initialized";
1300  }
1301 
1302  std::string type;
1303  if (PrecType_ == Ifpack2::JACOBI) {
1304  type = "Jacobi";
1305  } else if (PrecType_ == Ifpack2::GS) {
1306  type = "Gauss-Seidel";
1307  } else if (PrecType_ == Ifpack2::SGS) {
1308  type = "Symmetric Gauss-Seidel";
1309  } else {
1310  type = "INVALID";
1311  }
1312 
1313  // Output is a valid YAML dictionary in flow style. If you don't
1314  // like everything on a single line, you should call describe()
1315  // instead.
1316  os << "\"Ifpack2::Relaxation\": { "
1317  << "MatrixType: \"" << TypeNameTraits<MatrixType>::name () << "\", "
1318  << "Status: " << status << ", "
1319  << "\"relaxation: type\": " << type << ", "
1320  << "\"relaxation: sweeps\": " << NumSweeps_ << ", "
1321  << "\"relaxation: damping factor\": " << DampingFactor_ << ", ";
1322  if (DoL1Method_) {
1323  os << "\"relaxation: use l1\": " << DoL1Method_ << ", "
1324  << "\"relaxation: l1 eta\": " << L1Eta_ << ", ";
1325  }
1326  os << "\"Global number of rows\": " << A_->getGlobalNumRows () << ", "
1327  << "\"Global number of columns\": " << A_->getGlobalNumCols ()
1328  << " }";
1329  return os.str ();
1330 }
1331 
1332 //==========================================================================
1333 template<class MatrixType>
1334 void
1336 describe (Teuchos::FancyOStream &out,
1337  const Teuchos::EVerbosityLevel verbLevel) const
1338 {
1339  using Teuchos::OSTab;
1340  using Teuchos::TypeNameTraits;
1341  using Teuchos::VERB_DEFAULT;
1342  using Teuchos::VERB_NONE;
1343  using Teuchos::VERB_LOW;
1344  using Teuchos::VERB_MEDIUM;
1345  using Teuchos::VERB_HIGH;
1346  using Teuchos::VERB_EXTREME;
1347  using std::endl;
1348 
1349  const Teuchos::EVerbosityLevel vl =
1350  (verbLevel == VERB_DEFAULT) ? VERB_LOW : verbLevel;
1351 
1352  const int myRank = this->getComm ()->getRank ();
1353 
1354  // none: print nothing
1355  // low: print O(1) info from Proc 0
1356  // medium:
1357  // high:
1358  // extreme:
1359 
1360  if (vl != VERB_NONE && myRank == 0) {
1361  // Describable interface asks each implementation to start with a tab.
1362  OSTab tab1 (out);
1363  // Output is valid YAML; hence the quotes, to protect the colons.
1364  out << "\"Ifpack2::Relaxation\":" << endl;
1365  OSTab tab2 (out);
1366  out << "MatrixType: \"" << TypeNameTraits<MatrixType>::name () << "\"" << endl
1367  << "Label: " << this->getObjectLabel () << endl
1368  << "Parameters: " << endl;
1369  {
1370  OSTab tab3 (out);
1371  out << "\"relaxation: type\": ";
1372  if (PrecType_ == Ifpack2::JACOBI) {
1373  out << "Jacobi";
1374  } else if (PrecType_ == Ifpack2::GS) {
1375  out << "Gauss-Seidel";
1376  } else if (PrecType_ == Ifpack2::SGS) {
1377  out << "Symmetric Gauss-Seidel";
1378  } else {
1379  out << "INVALID";
1380  }
1381  // We quote these parameter names because they contain colons.
1382  // YAML uses the colon to distinguish key from value.
1383  out << endl
1384  << "\"relaxation: sweeps\": " << NumSweeps_ << endl
1385  << "\"relaxation: damping factor\": " << DampingFactor_ << endl
1386  << "\"relaxation: min diagonal value\": " << MinDiagonalValue_ << endl
1387  << "\"relaxation: zero starting solution\": " << ZeroStartingSolution_ << endl
1388  << "\"relaxation: backward mode\": " << DoBackwardGS_ << endl
1389  << "\"relaxation: use l1\": " << DoL1Method_ << endl
1390  << "\"relaxation: l1 eta\": " << L1Eta_ << endl;
1391  }
1392  out << "Computed quantities: " << endl;
1393  {
1394  OSTab tab3 (out);
1395  out << "initialized: " << (isInitialized () ? "true" : "false") << endl
1396  << "computed: " << (isComputed () ? "true" : "false") << endl
1397  << "Condition number estimate: " << Condest_ << endl
1398  << "Global number of rows: " << A_->getGlobalNumRows () << endl
1399  << "Global number of columns: " << A_->getGlobalNumCols () << endl;
1400  }
1401  if (checkDiagEntries_ && isComputed ()) {
1402  out << "Properties of input diagonal entries:" << endl;
1403  {
1404  OSTab tab3 (out);
1405  out << "Magnitude of minimum-magnitude diagonal entry: "
1406  << globalMinMagDiagEntryMag_ << endl
1407  << "Magnitude of maximum-magnitude diagonal entry: "
1408  << globalMaxMagDiagEntryMag_ << endl
1409  << "Number of diagonal entries with small magnitude: "
1410  << globalNumSmallDiagEntries_ << endl
1411  << "Number of zero diagonal entries: "
1412  << globalNumZeroDiagEntries_ << endl
1413  << "Number of diagonal entries with negative real part: "
1414  << globalNumNegDiagEntries_ << endl
1415  << "Abs 2-norm diff between computed and actual inverse "
1416  << "diagonal: " << globalDiagNormDiff_ << endl;
1417  }
1418  }
1419  if (isComputed ()) {
1420  out << "Saved diagonal offsets: "
1421  << (savedDiagOffsets_ ? "true" : "false") << endl;
1422  }
1423  out << "Call counts and total times (in seconds): " << endl;
1424  {
1425  OSTab tab3 (out);
1426  out << "initialize: " << endl;
1427  {
1428  OSTab tab4 (out);
1429  out << "Call count: " << NumInitialize_ << endl;
1430  out << "Total time: " << InitializeTime_ << endl;
1431  }
1432  out << "compute: " << endl;
1433  {
1434  OSTab tab4 (out);
1435  out << "Call count: " << NumCompute_ << endl;
1436  out << "Total time: " << ComputeTime_ << endl;
1437  }
1438  out << "apply: " << endl;
1439  {
1440  OSTab tab4 (out);
1441  out << "Call count: " << NumApply_ << endl;
1442  out << "Total time: " << ApplyTime_ << endl;
1443  }
1444  }
1445  }
1446 }
1447 
1448 } // namespace Ifpack2
1449 
1450 #endif // IFPACK2_RELAXATION_DEF_HPP
1451 
bool hasTransposeApply() const
Whether apply() and applyMat() let you apply the transpose or conjugate transpose.
Definition: Ifpack2_Relaxation_def.hpp:338
CondestType
Ifpack2::CondestType: enum to define the type of condition number estimate.
Definition: Ifpack2_CondestType.hpp:50
double getComputeFlops() const
Total number of floating-point operations over all calls to compute().
Definition: Ifpack2_Relaxation_def.hpp:380
double getApplyFlops() const
Total number of floating-point operations over all calls to apply().
Definition: Ifpack2_Relaxation_def.hpp:386
void describe(Teuchos::FancyOStream &out, const Teuchos::EVerbosityLevel verbLevel=Teuchos::Describable::verbLevel_default) const
Print the object&#39;s attributes to the given output stream.
Definition: Ifpack2_Relaxation_def.hpp:1336
void compute()
Compute the preconditioner for the specified matrix, diagonal perturbation thresholds and relaxation ...
Definition: Ifpack2_Relaxation_def.hpp:541
const Teuchos::RCP< const Teuchos::Comm< int > > & getComm() const
The communicator over which the matrix and vectors are distributed.
Definition: Ifpack2_Relaxation_def.hpp:304
Teuchos::RCP< const Tpetra::RowMatrix< scalar_type, local_ordinal_type, global_ordinal_type, node_type > > getMatrix() const
The matrix to be preconditioned.
Definition: Ifpack2_Relaxation_def.hpp:314
const Teuchos::RCP< const Tpetra::Map< local_ordinal_type, global_ordinal_type, node_type > > & getRangeMap() const
Returns the Tpetra::Map object associated with the range of this operator.
Definition: Ifpack2_Relaxation_def.hpp:332
int getNumApply() const
Total number of calls to apply().
Definition: Ifpack2_Relaxation_def.hpp:356
const Teuchos::RCP< const Tpetra::Map< local_ordinal_type, global_ordinal_type, node_type > > & getDomainMap() const
Returns the Tpetra::Map object associated with the domain of this operator.
Definition: Ifpack2_Relaxation_def.hpp:323
double getComputeTime() const
Total time in seconds spent in all calls to compute().
Definition: Ifpack2_Relaxation_def.hpp:368
magnitude_type getCondEst() const
The computed estimated condition number, or -1 if not previously computed.
Definition: Ifpack2_Relaxation_def.hpp:393
void setParameters(const Teuchos::ParameterList &params)
Set the relaxation / preconditioner parameters.
Definition: Ifpack2_Relaxation_def.hpp:295
std::string description() const
A simple one-line description of this object.
Definition: Ifpack2_Relaxation_def.hpp:1286
int getNumInitialize() const
Total number of calls to initialize().
Definition: Ifpack2_Relaxation_def.hpp:344
bool isComputed() const
Return true if compute() has been called.
Definition: Ifpack2_Relaxation_decl.hpp:416
magnitude_type computeCondEst(CondestType CT=Cheap, local_ordinal_type MaxIters=1550, magnitude_type Tol=1e-9, const Teuchos::Ptr< const Tpetra::RowMatrix< scalar_type, local_ordinal_type, global_ordinal_type, node_type > > &matrix=Teuchos::null)
Computes and returns the estimated condition number.
Definition: Ifpack2_Relaxation_def.hpp:401
double getInitializeTime() const
Total time in seconds spent in all calls to initialize().
Definition: Ifpack2_Relaxation_def.hpp:362
void applyMat(const Tpetra::MultiVector< scalar_type, local_ordinal_type, global_ordinal_type, node_type > &X, Tpetra::MultiVector< scalar_type, local_ordinal_type, global_ordinal_type, node_type > &Y, Teuchos::ETransp mode=Teuchos::NO_TRANS) const
Apply the preconditioner to X, returning the result in Y.
Definition: Ifpack2_Relaxation_def.hpp:512
Definition: Ifpack2_BlockRelaxation_decl.hpp:64
MatrixType::local_ordinal_type local_ordinal_type
The type of local indices in the input MatrixType.
Definition: Ifpack2_Relaxation_decl.hpp:249
MatrixType::scalar_type scalar_type
The type of the entries of the input MatrixType.
Definition: Ifpack2_Relaxation_decl.hpp:242
virtual ~Relaxation()
Destructor.
Definition: Ifpack2_Relaxation_def.hpp:186
int getNumCompute() const
Total number of calls to compute().
Definition: Ifpack2_Relaxation_def.hpp:350
bool isInitialized() const
Returns true if the preconditioner has been successfully initialized.
Definition: Ifpack2_Relaxation_decl.hpp:408
Relaxation preconditioners for Tpetra::RowMatrix and Tpetra::CrsMatrix sparse matrices.
Definition: Ifpack2_Relaxation_decl.hpp:231
Ifpack2::Container: a pure virtual class for creating and solving local linear problems.
Definition: Ifpack2_AdditiveSchwarz_decl.hpp:67
double getApplyTime() const
Total time in seconds spent in all calls to apply().
Definition: Ifpack2_Relaxation_def.hpp:374
void initialize()
Initialize the preconditioner.
Definition: Ifpack2_Relaxation_def.hpp:532
void apply(const Tpetra::MultiVector< scalar_type, local_ordinal_type, global_ordinal_type, node_type > &X, Tpetra::MultiVector< scalar_type, local_ordinal_type, global_ordinal_type, node_type > &Y, Teuchos::ETransp mode=Teuchos::NO_TRANS, scalar_type alpha=Teuchos::ScalarTraits< scalar_type >::one(), scalar_type beta=Teuchos::ScalarTraits< scalar_type >::zero()) const
Apply the preconditioner to X, returning the result in Y.
Definition: Ifpack2_Relaxation_def.hpp:422
Teuchos::RCP< const Teuchos::ParameterList > getValidParameters() const
Return a list of all the parameters that this class accepts.
Definition: Ifpack2_Relaxation_def.hpp:191
Teuchos::ScalarTraits< scalar_type >::magnitudeType magnitude_type
The type of the magnitude (absolute value) of a matrix entry.
Definition: Ifpack2_Relaxation_decl.hpp:270