Ifpack2 Templated Preconditioning Package  Version 1.0
Ifpack2_Chebyshev_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_CHEBYSHEV_DEF_HPP
44 #define IFPACK2_CHEBYSHEV_DEF_HPP
45 
46 
47 namespace Ifpack2 {
48 
49 template<class MatrixType>
50 Chebyshev<MatrixType>::
51 Chebyshev (const Teuchos::RCP<const row_matrix_type>& A)
52  : impl_ (A),
53  Time_ (Teuchos::rcp (new Teuchos::Time ("Ifpack2::Chebyshev"))),
54  Condest_ (-1.0),
55  IsInitialized_ (false),
56  IsComputed_ (false),
57  NumInitialize_ (0),
58  NumCompute_ (0),
59  NumApply_ (0),
60  InitializeTime_ (0.0),
61  ComputeTime_ (0.0),
62  ApplyTime_ (0.0),
63  ComputeFlops_ (0.0),
64  ApplyFlops_ (0.0)
65 {this->setObjectLabel("Ifpack2::Chebyshev");}
66 
67 //==========================================================================
68 template<class MatrixType>
69 Chebyshev<MatrixType>::~Chebyshev() {
70 }
71 
72 //==========================================================================
73 template<class MatrixType>
74 void
75 Chebyshev<MatrixType>::setParameters (const Teuchos::ParameterList& List)
76 {
77  // FIXME (mfh 25 Jan 2013) Casting away const is bad here.
78  impl_.setParameters (const_cast<Teuchos::ParameterList&> (List));
79 }
80 
81 
82 //==========================================================================
83 template<class MatrixType>
84 const Teuchos::RCP<const Teuchos::Comm<int> > &
86  return impl_.getMatrix ()->getRowMap ()->getComm ();
87 }
88 
89 //==========================================================================
90 template<class MatrixType>
91 Teuchos::RCP<const typename Chebyshev<MatrixType>::row_matrix_type>
93 getMatrix() const {
94  return impl_.getMatrix ();
95 }
96 
97 //==========================================================================
98 template<class MatrixType>
99 const Teuchos::RCP<const typename Chebyshev<MatrixType>::map_type>&
101 getDomainMap() const {
102  return impl_.getMatrix ()->getDomainMap ();
103 }
104 
105 //==========================================================================
106 template<class MatrixType>
107 const Teuchos::RCP<const typename Chebyshev<MatrixType>::map_type>&
109 getRangeMap() const {
110  return impl_.getMatrix ()->getRangeMap ();
111 }
112 
113 //==========================================================================
114 template<class MatrixType>
116  return impl_.hasTransposeApply ();
117 }
118 
119 //==========================================================================
120 template<class MatrixType>
122  return(NumInitialize_);
123 }
124 
125 //==========================================================================
126 template<class MatrixType>
128  return(NumCompute_);
129 }
130 
131 //==========================================================================
132 template<class MatrixType>
134  return(NumApply_);
135 }
136 
137 //==========================================================================
138 template<class MatrixType>
140  return(InitializeTime_);
141 }
142 
143 //==========================================================================
144 template<class MatrixType>
146  return(ComputeTime_);
147 }
148 
149 //==========================================================================
150 template<class MatrixType>
152  return(ApplyTime_);
153 }
154 
155 //==========================================================================
156 template<class MatrixType>
158  return(ComputeFlops_);
159 }
160 
161 //==========================================================================
162 template<class MatrixType>
164  return(ApplyFlops_);
165 }
166 
167 //==========================================================================
168 template<class MatrixType>
171 getCondEst() const {
172  return(Condest_);
173 }
174 
175 //==========================================================================
176 template<class MatrixType>
180  local_ordinal_type MaxIters,
181  magnitude_type Tol,
182  const Teuchos::Ptr<const row_matrix_type>& matrix)
183 {
184  if (! isComputed ()) {
185  return -Teuchos::ScalarTraits<magnitude_type>::one ();
186  }
187  else {
188  // Always compute it. Call Condest() with no parameters to get
189  // the previous estimate.
190  Condest_ = Ifpack2::Condest (*this, CT, MaxIters, Tol, matrix);
191  return Condest_;
192  }
193 }
194 
195 
196 template<class MatrixType>
197 void
199 apply (const Tpetra::MultiVector<scalar_type, local_ordinal_type, global_ordinal_type, node_type>& X,
200  Tpetra::MultiVector<scalar_type, local_ordinal_type, global_ordinal_type, node_type>& Y,
201  Teuchos::ETransp mode,
202  scalar_type alpha,
203  scalar_type beta) const
204 {
205  {
206  Teuchos::TimeMonitor timeMon (*Time_);
207 
208  // compute() calls initialize() if it hasn't already been called.
209  // Thus, we only need to check isComputed().
210  TEUCHOS_TEST_FOR_EXCEPTION(! isComputed(), std::runtime_error,
211  "Ifpack2::Chebyshev::apply(): You must call the compute() method before "
212  "you may call apply().");
213  TEUCHOS_TEST_FOR_EXCEPTION(
214  X.getNumVectors() != Y.getNumVectors(),
215  std::runtime_error,
216  "Ifpack2::Chebyshev::apply(): X and Y must have the same number of "
217  "columns. X.getNumVectors() = " << X.getNumVectors() << " != "
218  << "Y.getNumVectors() = " << Y.getNumVectors() << ".");
219 #ifdef HAVE_TEUCHOS_DEBUG
220  {
221  // The relation 'isSameAs' is transitive. It's also a collective,
222  // so we don't have to do a "shared" test for exception (i.e., a
223  // global reduction on the test value).
224  TEUCHOS_TEST_FOR_EXCEPTION(
225  ! X.getMap ()->isSameAs (*getDomainMap ()),
226  std::runtime_error,
227  "Ifpack2::Chebyshev: The domain Map of the matrix must be the same as "
228  "the Map of the input vector(s) X.");
229  TEUCHOS_TEST_FOR_EXCEPTION(
230  ! Y.getMap ()->isSameAs (*getRangeMap ()),
231  std::runtime_error,
232  "Ifpack2::Chebyshev: The range Map of the matrix must be the same as "
233  "the Map of the output vector(s) Y.");
234  }
235 #endif // HAVE_TEUCHOS_DEBUG
236  applyImpl (X, Y, mode, alpha, beta);
237  }
238  ++NumApply_;
239  ApplyTime_ += Time_->totalElapsedTime ();
240 }
241 
242 
243 template<class MatrixType>
244 void
246 applyMat (const Tpetra::MultiVector<scalar_type, local_ordinal_type, global_ordinal_type, node_type>& X,
247  Tpetra::MultiVector<scalar_type, local_ordinal_type, global_ordinal_type, node_type>& Y,
248  Teuchos::ETransp mode) const
249 {
250  TEUCHOS_TEST_FOR_EXCEPTION(X.getNumVectors() != Y.getNumVectors(), std::runtime_error,
251  "Ifpack2::Chebyshev::applyMat(): X.getNumVectors() != Y.getNumVectors().");
252  impl_.getMatrix ()->apply (X, Y, mode);
253 }
254 
255 
256 template<class MatrixType>
258  // This method doesn't do anything anymore, so there's no need to time it.
259  IsInitialized_ = true;
260  ++NumInitialize_;
261  // Note to developers: Defer fetching any data that relate to the
262  // structure of the matrix until compute(). That way, it will
263  // always be correct to omit calling initialize(), even if the
264  // number of entries in the sparse matrix has changed since the last
265  // call to compute().
266 }
267 
268 
269 template<class MatrixType>
271 {
272  {
273  Teuchos::TimeMonitor timeMon (*Time_);
274  if (! isInitialized ()) {
275  initialize ();
276  }
277  IsComputed_ = false;
278  Condest_ = -1.0;
279  impl_.compute ();
280  }
281  IsComputed_ = true;
282  ++NumCompute_;
283  ComputeTime_ += Time_->totalElapsedTime();
284 }
285 
286 
287 template<class MatrixType>
288 void
290 PowerMethod (const Tpetra::Operator<scalar_type, local_ordinal_type, global_ordinal_type, node_type>& Operator,
291  const Tpetra::Vector<scalar_type, local_ordinal_type, global_ordinal_type, node_type>& InvPointDiagonal,
292  const int MaximumIterations,
293  scalar_type& lambda_max)
294 {
295  const scalar_type one = STS::one();
296  const scalar_type zero = STS::zero();
297 
298  lambda_max = zero;
299  Teuchos::Array<scalar_type> RQ_top(1), RQ_bottom(1);
300  vector_type x (Operator.getDomainMap ());
301  vector_type y (Operator.getRangeMap ());
302  x.randomize ();
303  Teuchos::Array<magnitude_type> norms (x.getNumVectors ());
304  x.norm2 (norms ());
305  x.scale (one / norms[0]);
306 
307  for (int iter = 0; iter < MaximumIterations; ++iter) {
308  Operator.apply (x, y);
309  y.elementWiseMultiply (one, InvPointDiagonal, y, zero);
310  y.dot (x, RQ_top ());
311  x.dot (x, RQ_bottom ());
312  lambda_max = RQ_top[0] / RQ_bottom[0];
313  y.norm2 (norms ());
314  TEUCHOS_TEST_FOR_EXCEPTION(
315  norms[0] == zero,
316  std::runtime_error,
317  "Ifpack2::Chebyshev::PowerMethod: norm == 0 at iteration " << (iter+1)
318  << " of " << MaximumIterations);
319  x.update (one / norms[0], y, zero);
320  }
321 }
322 
323 //==========================================================================
324 template<class MatrixType>
326 CG(const Tpetra::Operator<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& Operator,
327  const Tpetra::Vector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& InvPointDiagonal,
328  const int MaximumIterations,
329  scalar_type& lambda_min, scalar_type& lambda_max)
330 {
331  TEUCHOS_TEST_FOR_EXCEPTION(
332  true, std::logic_error,
333  "Ifpack2::Chebyshev::CG: Not implemented. "
334  "Please use Belos' implementation of CG with Tpetra objects.");
335 }
336 
337 //==========================================================================
338 template <class MatrixType>
340  std::ostringstream oss;
341  oss << Teuchos::LabeledObject::getObjectLabel();
342  if (isInitialized()) {
343  if (isComputed()) {
344  oss << "{status = initialized, computed, ";
345  }
346  else {
347  oss << "{status = initialized, not computed, ";
348  }
349  }
350  else {
351  oss << "{status = not initialized, not computed, ";
352  }
353 
354  oss << impl_.description();
355 
356  oss << ", global rows = " << impl_.getMatrix ()->getGlobalNumRows()
357  << ", global cols = " << impl_.getMatrix ()->getGlobalNumCols()
358  << "}";
359  return oss.str();
360 }
361 
362 //==========================================================================
363 template <class MatrixType>
364 void Chebyshev<MatrixType>::describe(Teuchos::FancyOStream &out, const Teuchos::EVerbosityLevel verbLevel) const {
365 #if 0
366  using Teuchos::Comm;
367  using Teuchos::RCP;
368  using Teuchos::VERB_DEFAULT;
369  using Teuchos::VERB_NONE;
370  using Teuchos::VERB_LOW;
371  using Teuchos::VERB_MEDIUM;
372  using Teuchos::VERB_HIGH;
373  using Teuchos::VERB_EXTREME;
374  using std::endl;
375  using std::setw;
376 
377  Teuchos::EVerbosityLevel vl = verbLevel;
378  if (vl == VERB_DEFAULT) {
379  vl = VERB_LOW;
380  }
381  RCP<const Comm<int> > comm = A_->getRowMap ()->getComm ();
382 
383  const int myImageID = comm->getRank();
384  Teuchos::OSTab tab(out);
385 
386  scalar_type MinVal, MaxVal;
387  if (IsComputed_) {
388  Teuchos::ArrayRCP<const scalar_type> DiagView = InvDiagonal_->get1dView();
389  scalar_type myMinVal = DiagView[0];
390  scalar_type myMaxVal = DiagView[0];
391  for(typename Teuchos::ArrayRCP<scalar_type>::size_type i=1; i<DiagView.size(); ++i) {
392  if (STS::magnitude(myMinVal) > STS::magnitude(DiagView[i])) myMinVal = DiagView[i];
393  if (STS::magnitude(myMaxVal) < STS::magnitude(DiagView[i])) myMaxVal = DiagView[i];
394  }
395  Teuchos::reduceAll(*comm, Teuchos::REDUCE_MIN, 1, &myMinVal, &MinVal);
396  Teuchos::reduceAll(*comm, Teuchos::REDUCE_MAX, 1, &myMaxVal, &MaxVal);
397  }
398 
399  // none: print nothing
400  // low: print O(1) info from node 0
401  // medium:
402  // high:
403  // extreme:
404  if (vl != VERB_NONE && myImageID == 0) {
405  out << this->description() << endl;
406  out << endl;
407  out << "===============================================================================" << std::endl;
408  out << "Degree of polynomial = " << PolyDegree_ << std::endl;
409  if (ZeroStartingSolution_) { out << "Using zero starting solution" << endl; }
410  else { out << "Using input starting solution" << endl; }
411  if (Condest_ == -1.0) { out << "Condition number estimate = N/A" << endl; }
412  else { out << "Condition number estimate = " << Condest_ << endl; }
413  if (IsComputed_) {
414  out << "Minimum value on stored inverse diagonal = " << MinVal << std::endl;
415  out << "Maximum value on stored inverse diagonal = " << MaxVal << std::endl;
416  }
417  out << std::endl;
418  out << "Phase # calls Total Time (s) Total MFlops MFlops/s " << endl;
419  out << "------------ ------- --------------- --------------- ---------------" << endl;
420  out << setw(12) << "initialize()" << setw(5) << getNumInitialize() << " " << setw(15) << getInitializeTime() << endl;
421  out << setw(12) << "compute()" << setw(5) << getNumCompute() << " " << setw(15) << getComputeTime() << " "
422  << setw(15) << getComputeFlops() << " "
423  << setw(15) << (getComputeTime() != 0.0 ? getComputeFlops() / getComputeTime() * 1.0e-6 : 0.0) << endl;
424  out << setw(12) << "apply()" << setw(5) << getNumApply() << " " << setw(15) << getApplyTime() << " "
425  << setw(15) << getApplyFlops() << " "
426  << setw(15) << (getApplyTime() != 0.0 ? getApplyFlops() / getApplyTime() * 1.0e-6 : 0.0) << endl;
427  out << "===============================================================================" << std::endl;
428  out << endl;
429  }
430 #endif // 0
431 }
432 
433 template<class MatrixType>
434 void
436 applyImpl (const MV& X,
437  MV& Y,
438  Teuchos::ETransp mode,
439  scalar_type alpha,
440  scalar_type beta) const
441 {
442  using Teuchos::ArrayRCP;
443  using Teuchos::as;
444  using Teuchos::RCP;
445  using Teuchos::rcp;
446  using Teuchos::rcp_const_cast;
447  using Teuchos::rcpFromRef;
448 
449  const scalar_type zero = STS::zero();
450  const scalar_type one = STS::one();
451 
452  // Y = beta*Y + alpha*M*X.
453 
454  // If alpha == 0, then we don't need to do Chebyshev at all.
455  if (alpha == zero) {
456  if (beta == zero) { // Obey Sparse BLAS rules; avoid 0*NaN.
457  Y.putScalar (zero);
458  }
459  else {
460  Y.scale (beta);
461  }
462  return;
463  }
464 
465  // If beta != 0, then we need to keep a copy of the initial value of
466  // Y, so that we can add beta*it to the Chebyshev result at the end.
467  // Usually this method is called with beta == 0, so we don't have to
468  // worry about caching Y_org.
469  RCP<MV> Y_orig;
470  if (beta != zero) {
471  Y_orig = rcp (new MV (Y));
472  }
473 
474  // If X and Y point to the same memory location, we need to use a
475  // copy of X (X_copy) as the input MV. Otherwise, just let X_copy
476  // point to X.
477  //
478  // This is hopefully an uncommon use case, so we don't bother to
479  // optimize for it by caching X_copy.
480  RCP<const MV> X_copy;
481  bool copiedInput = false;
482  if (X.getLocalMV().getValues() == Y.getLocalMV().getValues()) {
483  X_copy = rcp (new MV (X));
484  copiedInput = true;
485  }
486  else {
487  X_copy = rcpFromRef (X);
488  }
489 
490  // If alpha != 1, fold alpha into (a copy of) X.
491  //
492  // This is an uncommon use case, so we don't bother to optimize for
493  // it by caching X_copy. However, we do check whether we've already
494  // copied X above, to avoid a second copy.
495  if (alpha != one) {
496  RCP<MV> X_copy_nonConst = rcp_const_cast<MV> (X_copy);
497  if (! copiedInput) {
498  X_copy_nonConst = rcp (new MV (X));
499  copiedInput = true;
500  }
501  X_copy_nonConst->scale (alpha);
502  X_copy = rcp_const_cast<const MV> (X_copy_nonConst);
503  }
504 
505  impl_.apply (*X_copy, Y);
506 
507  if (beta != zero) {
508  Y.update (beta, *Y_orig, one); // Y = beta * Y_orig + 1 * Y
509  }
510 }
511 
512 //==========================================================================
513 template<class MatrixType>
514 typename MatrixType::scalar_type Chebyshev<MatrixType>::getLambdaMaxForApply() const {
515  return impl_.getLambdaMaxForApply();
516 }
517 
518 
519 }//namespace Ifpack2
520 
521 #endif // IFPACK2_CHEBYSHEV_DEF_HPP
522 
CondestType
Ifpack2::CondestType: enum to define the type of condition number estimate.
Definition: Ifpack2_CondestType.hpp:50
virtual const Teuchos::RCP< const Tpetra::Map< LocalOrdinal, GlobalOrdinal, Node > > & getDomainMap() const
Returns the Map associated with the domain of this operator, which must be compatible with X...
Definition: Ifpack2_BorderedOperator_def.hpp:69
Left-scaled Chebyshev iteration.
Definition: Ifpack2_Details_Chebyshev_decl.hpp:128
void setParameters(Teuchos::ParameterList &plist)
Set (or reset) parameters.
Definition: Ifpack2_Chebyshev_def.hpp:75
Definition: Ifpack2_BlockRelaxation_decl.hpp:64
bool hasTransposeApply() const
Whether it&#39;s possible to apply the transpose of this operator.
Definition: Ifpack2_Chebyshev_def.hpp:115
Ifpack2::Container: a pure virtual class for creating and solving local linear problems.
Definition: Ifpack2_AdditiveSchwarz_decl.hpp:67
Teuchos::RCP< const MAT > getMatrix() const
Get the matrix given to the constructor.
Definition: Ifpack2_Chebyshev_def.hpp:93
virtual const Teuchos::RCP< const Tpetra::Map< LocalOrdinal, GlobalOrdinal, Node > > & getRangeMap() const
Returns the Map associated with the range of this operator, which must be compatible with Y...
Definition: Ifpack2_BorderedOperator_def.hpp:76