Tpetra Matrix/Vector Services  Version of the Day
RTIInlineCG.hpp
1 /*
2 // @HEADER
3 // ***********************************************************************
4 //
5 // Tpetra: Templated Linear Algebra Services Package
6 // Copyright (2008) Sandia Corporation
7 //
8 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
9 // the U.S. Government retains certain rights in this software.
10 //
11 // Redistribution and use in source and binary forms, with or without
12 // modification, are permitted provided that the following conditions are
13 // met:
14 //
15 // 1. Redistributions of source code must retain the above copyright
16 // notice, this list of conditions and the following disclaimer.
17 //
18 // 2. Redistributions in binary form must reproduce the above copyright
19 // notice, this list of conditions and the following disclaimer in the
20 // documentation and/or other materials provided with the distribution.
21 //
22 // 3. Neither the name of the Corporation nor the names of the
23 // contributors may be used to endorse or promote products derived from
24 // this software without specific prior written permission.
25 //
26 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
27 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
30 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
31 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
32 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
33 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
34 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
35 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
36 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 //
38 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
39 //
40 // ************************************************************************
41 // @HEADER
42 */
43 
44 #include <iostream>
45 #include <functional>
46 
48 #include <Teuchos_FancyOStream.hpp>
50 #include <Teuchos_oblackholestream.hpp>
52 #include <Teuchos_TimeMonitor.hpp>
55 
56 
57 #include <Tpetra_CrsMatrix.hpp>
58 #include <Tpetra_DefaultPlatform.hpp>
59 
60 // no gpu support for RTI
61 #undef HAVE_KOKKOSCLASSIC_THRUST
62 #include <Tpetra_HybridPlatform.hpp>
63 
64 #include <Tpetra_MatrixIO.hpp>
65 #include <Tpetra_RTI.hpp>
66 #include <Tpetra_RTIOp.hpp>
67 #include <Tpetra_Vector.hpp>
68 #include <Tpetra_Version.hpp>
69 
70 namespace Tpetra {
71  namespace RTI {
72  // specialization for pair
73  template <class T1, class T2>
74  class ZeroOp<std::pair<T1,T2>> {
75  public:
76  static inline std::pair<T1,T2> identity() {
77  return std::make_pair( Teuchos::ScalarTraits<T1>::zero(),
79  }
80  };
81  }
82 }
83 
84 namespace TpetraExamples {
85 
86  using Teuchos::RCP;
88  using Teuchos::Time;
89  using Teuchos::null;
90  using std::binary_function;
91  using std::pair;
92  using std::make_pair;
93  using std::plus;
94  using std::multiplies;
95 
96  template <class T1, class T2, class Op>
97  class pair_op : public binary_function<pair<T1,T2>,pair<T1,T2>,pair<T1,T2>> {
98  private:
99  Op op_;
100  public:
101  pair_op(Op op) : op_(op) {}
102  inline pair<T1,T2> operator()(const pair<T1,T2>& a, const pair<T1,T2>& b) const {
103  return make_pair(op_(a.first,b.first),op_(a.second,b.second));
104  }
105  };
106 
107  template <class T1, class T2, class Op>
108  pair_op<T1,T2,Op> make_pair_op(Op op) { return pair_op<T1,T2,Op>(op); }
109 
111  template <class S>
113  {
114  protected:
115  int N_;
116  S kappa_;
117  public:
118  DiagKernel(int N, const S & kappa) : N_(N), kappa_(kappa) {}
119  inline void execute(int i) {
120  this->_vec_inout[i] = this->_alpha * ((kappa_-1.0) * (S)(i)/(S)(N_-1) + 1.0) * this->_vec_in2[i] + this->_beta * this->_vec_inout[i];
121  }
122  };
123 
124 
125 
127  template <class S, class LO, class GO, class Node>
129  const RCP<Teuchos::FancyOStream> &out, ParameterList &plist)
130  {
131  using Teuchos::as;
132  using Tpetra::RTI::ZeroOp;
133  typedef Tpetra::Vector<S ,LO,GO,Node> Vector;
135  typedef Teuchos::ScalarTraits<S> ST;
136  // get objects from level database
137  const int numIters = plist.get<int>("numIters");
138  const S tolerance = plist.get<double>("tolerance");
139  const int verbose = plist.get<int>("verbose");
142  );
143  auto r = Tpetra::createVector<S>(A->getRangeMap()),
144  p = Tpetra::createVector<S>(A->getRangeMap()),
145  Ap = Tpetra::createVector<S>(A->getRangeMap());
146  auto x = b;
147 
148  Teuchos::OSTab tab(out);
149 
150  if (verbose) {
151  *out << "Beginning CG<" << Teuchos::TypeNameTraits<S>::name() << ">" << std::endl;
152  }
153  int k;
154  { // begin timer scop
155  Teuchos::TimeMonitor lcltimer(*timer);
156  // initial guess is x=0, so initial residual is r = b - A*x = b
157  const S r2 = TPETRA_BINARY_PRETRANSFORM_REDUCE(
158  r, b, // fused:
159  b, // : r = x
160  r*r, ZeroOp<S>, plus<S>() ); // : sum r'*r
161  // forget b; refer to it as x now
162  b = null;
163  // b comes in, x goes out. now we're done with b, so zero the solution.
164  TPETRA_UNARY_TRANSFORM( x, ST::zero() ); // x = 0
165  S rr = r2;
166  TPETRA_BINARY_TRANSFORM( p, r, r ); // p = r
168  for (k=0; k<numIters; ++k)
169  {
170  A->apply(*p,*Ap); // Ap = A*p
171  S pAp = TPETRA_REDUCE2( p, Ap,
172  p*Ap, ZeroOp<S>, plus<S>() ); // p'*Ap
173  const S alpha = rr / pAp;
174  TPETRA_BINARY_TRANSFORM( x, p, x + alpha*p ); // x = x + alpha*p
175  S rrold = rr;
176  rr = TPETRA_BINARY_PRETRANSFORM_REDUCE(
177  r, Ap, // fused:
178  r - alpha*Ap, // : r - alpha*Ap
179  r*r, ZeroOp<S>, plus<S>() ); // : sum r'*r
180  if (verbose > 1) *out << "|res|/|res_0|: " << ST::squareroot(rr/r2)
181  << std::endl;
182  if (rr/r2 < tolerance*tolerance) {
183  if (verbose) {
184  *out << "Convergence detected!" << std::endl;
185  }
186  break;
187  }
188  const S beta = rr / rrold;
189  TPETRA_BINARY_TRANSFORM( p, r, r + beta*p ); // p = z + beta*p
190  }
191  } // end timer scop
192  if (verbose) {
193  *out << "Leaving recursiveFPCG<" << Teuchos::TypeNameTraits<S>::name()
194  << "> after " << k << " iterations." << std::endl;
195  }
196  }
197 
198 } // end of namespace TpetraExamples
199 
200 template <class S>
201 class CGDriver {
202  public:
203  // input
206  // output
207  bool testPassed;
208 
209  template <class Node>
210  void run(Teuchos::ParameterList &myMachPL, const Teuchos::RCP<const Teuchos::Comm<int> > &comm, const Teuchos::RCP<Node> &node)
211  {
212  using std::pair;
213  using std::make_pair;
214  using std::plus;
215  using std::endl;
216  using Teuchos::RCP;
218  using Teuchos::null;
221  using Tpetra::RTI::ZeroOp;
224 
225  // Static types
226  typedef int LO;
227  typedef int GO;
228  typedef Tpetra::Operator<S,LO,GO,Node> Operator;
229  typedef Tpetra::Vector<S,LO,GO,Node> Vector;
230  const int N = params->get<int>("size");
231  const double kappa = params->get<double>("kappa");
232 
233  *out << "Running test with Node==" << Teuchos::typeName(*node) << " on rank " << comm->getRank() << "/" << comm->getSize() << std::endl;
234 
235  // create the operator
236  *out << "Building problem of size " << N << " with condition number " << kappa << std::endl;
238  {
239  auto map = Tpetra::createUniformContigMapWithNode<LO,GO,Node>(N,comm,node);
240  A = Tpetra::RTI::kernelOp<S>( TpetraExamples::DiagKernel<S>(N,kappa), map );
241  }
242 
243  testPassed = true;
244 
245  // choose a solution, compute a right-hand-side
246  auto x = Tpetra::createVector<S>(A->getDomainMap()),
247  b = Tpetra::createVector<S>(A->getDomainMap()),
248  xhat = Tpetra::createVector<S>(A->getDomainMap());
249  x->randomize();
250  A->apply(*x,*b);
251  TPETRA_BINARY_TRANSFORM(xhat, b, b); // xhat = b
252 
253  // call the solve
254  TpetraExamples::RTICG(A,xhat,out,*params);
255 
256  // check that residual is as requested
257  {
258  auto bhat = Tpetra::createVector<S>(A->getDomainMap());
259  A->apply(*xhat,*bhat);
260  // compute bhat-b, while simultaneously computing |bhat-b|^2 and |b|^2
261  typedef ZeroOp<pair<S,S>> ZERO;
262  const pair<S,S> nrms = TPETRA_BINARY_PRETRANSFORM_REDUCE(
263  bhat, b,
264  b - bhat,
265  make_pair(bhat*bhat, b*b), ZERO, (make_pair_op<S,S>(plus<S>()))
266  );
267  //auto nrms = binary_pre_transform_reduce(*bhat, *b,
268  // reductionGlob<ZeroOp<pair<S,S>>>(
269  // [](S bhati, S bi){ return bi-bhati;}, // bhati = bi-bhat
270  // [](S bhati, S bi){ return make_pair(bhati*bhati, bi*bi); },
271  // make_pair_op<S,S>(plus<S>())) );
272  const S enrm = Teuchos::ScalarTraits<S>::squareroot(nrms.first),
273  bnrm = Teuchos::ScalarTraits<S>::squareroot(nrms.second);
274  // check that residual is as requested
275  *out << "|b - A*x|/|b|: " << enrm / bnrm << endl;
276  const double tolerance = params->get<double>("tolerance");
277  // give a little slack
278  if (enrm / bnrm > 5*tolerance) testPassed = false;
279  }
280 
281  // print timings
283  }
284 };
Namespace Tpetra contains the class and methods constituting the Tpetra library.
Utility base class for kernels used to define Tpetra::Operator objects.
pair_op< T1, T2, Op > make_pair_op(Op op)
Non-member constructor to create a pair_op.
Definition: RTIExample.cpp:121
void binary_transform(Vector< S1, LO, GO, Node > &vec_inout, const Vector< S2, LO, GO, Node > &vec_in2, OP op)
Transform values of vec_inout using vec_inout, vec_in2 and operator op.
Definition: Tpetra_RTI.hpp:167
T & get(const std::string &name, T def_value)
Glob::RedOP::result_type binary_pre_transform_reduce(Vector< S1, LO, GO, Node > &vec_inout, const Vector< S2, LO, GO, Node > &vec_in2, Glob glob)
Transforms values of vec_inout while simultaneously performing a parallel reduction.
Definition: Tpetra_RTI.hpp:253
static T squareroot(T x)
Namespace for Tpetra example classes and methods.
Class to demonstrate a simple diagonal matrix.
static RCP< Time > getNewTimer(const std::string &name)
static void summarize(Ptr< const Comm< int > > comm, std::ostream &out=std::cout, const bool alwaysWriteLocal=false, const bool writeGlobalStats=true, const bool writeZeroTimers=true, const ECounterSetOp setOp=Intersection, const std::string &filter="")
ReductionGlob< GOP, ROP, IOP > reductionGlob(GOP gop, ROP rop)
Non-member constructor to instantiate a type glob of a static identity functor and generation and red...
Definition: Tpetra_RTI.hpp:137
void RTICG(const RCP< const Tpetra::Operator< S, LO, GO, Node >> &A, RCP< Tpetra::Vector< S, LO, GO, Node >> b, const RCP< Teuchos::FancyOStream > &out, ParameterList &plist)
Recursive, self-preconditioning flexible CG.
TypeTo as(const TypeFrom &t)
A distributed dense vector.
A static identity functor, providing a static method identity() that returns zero.
Definition: Tpetra_RTI.hpp:67
static std::string name()
std::string typeName(const T &t)