Tpetra Matrix/Vector Services  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
IRTR_solvers.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 #ifndef MULTIPRECCG_HPP_
45 #define MULTIPRECCG_HPP_
46 
47 #include <Teuchos_TimeMonitor.hpp>
48 #include <Teuchos_TypeNameTraits.hpp>
49 #include <Teuchos_ParameterList.hpp>
50 #include <Teuchos_XMLParameterListHelpers.hpp>
51 #include <Teuchos_FancyOStream.hpp>
52 
53 #include <Tpetra_CrsMatrix.hpp>
54 #include <Tpetra_Vector.hpp>
55 #include <Tpetra_RTI.hpp>
56 #include <Tpetra_MatrixIO.hpp>
57 
58 #include <iostream>
59 #include <functional>
60 
61 #ifdef HAVE_TPETRA_QD
62 # include <qd/qd_real.h>
63 #endif
64 
65 #define XFORM1 TPETRA_UNARY_TRANSFORM
66 #define XFORM2 TPETRA_BINARY_TRANSFORM
67 #define XFORM3 TPETRA_TERTIARY_TRANSFORM
68 
69 #define REDUCE1(in, gexp) \
70  Tpetra::RTI::reduce( *in, \
71  Tpetra::RTI::reductionGlob<Tpetra::RTI::ZeroOp<decltype((in)->meanValue())>>( \
72  [=]( decltype((in)->meanValue()) in ){ return gexp; }, \
73  std::plus<decltype((in)->meanValue())>() ) )
74 
75 #define REDUCE2(in1, in2, gexp) \
76  Tpetra::RTI::reduce( *in1, *in2, \
77  Tpetra::RTI::reductionGlob<Tpetra::RTI::ZeroOp<decltype((in1)->meanValue())>>( \
78  [=]( decltype((in1)->meanValue()) in1, \
79  decltype((in2)->meanValue()) in2 ) { return gexp; },\
80  std::plus<decltype((in1)->meanValue())>() ) )
81 
82 #define XFORM2RED(out,in,texp,gexp) \
83  Tpetra::RTI::binary_pre_transform_reduce( *out, *in, \
84  Tpetra::RTI::reductionGlob<Tpetra::RTI::ZeroOp<decltype((out)->meanValue())>>( \
85  [=]( decltype((out)->meanValue()) out, \
86  decltype((in)->meanValue()) in ) { return texp; }, \
87  [=]( decltype((out)->meanValue()) out, \
88  decltype((in)->meanValue()) in ) { return gexp; }, \
89  std::plus<decltype((out)->meanValue())>() ) )
90 
91 #define XFORM3RED(out,in2,in3, texp, gexp) \
92  Tpetra::RTI::tertiary_pre_transform_reduce( *out, *in2, *in3, \
93  Tpetra::RTI::reductionGlob<Tpetra::RTI::ZeroOp<decltype((out)->meanValue())>>( \
94  [=]( decltype((out)->meanValue()) out, \
95  decltype((in2)->meanValue()) in2, \
96  decltype((in3)->meanValue()) in3 ) \
97  { return texp; }, \
98  [=]( decltype((out)->meanValue()) out, \
99  decltype((in2)->meanValue()) in2, \
100  decltype((in3)->meanValue()) in3 ) \
101  { return gexp; }, \
102  std::plus<decltype((out)->meanValue())>() ) )
103 
104 namespace TpetraExamples {
105 
106  using Teuchos::RCP;
107  using Tpetra::createVector;
108  using Teuchos::ParameterList;
109 
111  template <class Tout, class Tin, class LO, class GO, class Node>
112  struct convertHelp {
113  static RCP<const Tpetra::CrsMatrix<Tout,LO,GO,Node>> doit(const RCP<const Tpetra::CrsMatrix<Tin,LO,GO,Node>> &A)
114  {
115  return A->template convert<Tout>();
116  }
117  };
118 
120  template <class T, class LO, class GO, class Node>
121  struct convertHelp<T,T,LO,GO,Node> {
122  static RCP<const Tpetra::CrsMatrix<T,LO,GO,Node>> doit(const RCP<const Tpetra::CrsMatrix<T,LO,GO,Node>> &A)
123  {
124  return A;
125  }
126  };
127 
128 
129  /***************************************************
130  * Implicit Riemannian Trust-Region Eigensolver
131  * Baker, Absil, Gallivan 2008
132  ***************************************************/
133 
134  template <class S, class Souter, class LO, class GO, class Node>
135  S diagPrecond(const RCP<const Tpetra::Vector<S,LO,GO,Node> > &D,
136  const RCP<const Tpetra::Vector<S,LO,GO,Node> > &x,
137  const RCP<const Tpetra::Vector<S,LO,GO,Node> > &iDx,
138  const S &xiDx,
139  const RCP<const Tpetra::Vector<S,LO,GO,Node> > &r,
140  const RCP< Tpetra::Vector<S,LO,GO,Node> > &z)
141  {
142  /*
143  Solve
144  P D P z = r
145  for solution
146  r = P_{u,x} inv(D) r
147  = (I - u inv(x'*u) x') inv(D) r
148  = z - u inv(x'*u) x'*z
149  for u = inv(D) x = iDx
150  z = inv(D) r
151 
152  for our purposes,
153  1) z = r
154  2) fuse z \= D
155  and xz = x'*z
156  3) fuse z = z - iDx ( xt / xiDx )
157  and return z'*r
158  */
159  XFORM2(z,r, r);
160  const S alpha = XFORM3RED(z,D,x, z/D, x*z ) / xiDx;
161  return XFORM3RED(z,iDx,r, z - iDx*alpha, z*r );
162  }
163 
164  template <class S, class LO, class GO, class Node>
165  struct tCG_workspace {
166  RCP<Tpetra::Vector<S,LO,GO,Node>> r, z, iDx, d, Hd;
167  };
168 
169  /***************************************************
170  * Trust-region Model Subproblem CG Solver
171  * Given x, compute eta that minimizes the
172  * quadratic Taylor expansion of f around x,
173  * subject to rho_x(eta) >= rho_prime,
174  * or, equiv., eta'*eta <= ONE/rho_prime - ONE
175  ***************************************************/
177  template <class S, class Souter, class LO, class GO, class Node>
178  void truncateCG(const RCP<Teuchos::FancyOStream> &out, int verbose,
179  const RCP<const Tpetra::Operator<S,LO,GO,Node> > &A,
180  const RCP<const Tpetra::Vector<S,LO,GO,Node> > &diag,
181  const RCP<const Tpetra::Vector<Souter,LO,GO,Node> > &x_outer,
182  const RCP<const Tpetra::Vector<Souter,LO,GO,Node> > &grad,
183  const Souter &lx_outer,
184  const RCP<Tpetra::Vector<S,LO,GO,Node> > &eta,
185  const tCG_workspace<S,LO,GO,Node> &workspace,
186  double rho_prime, double kappa, double theta, int maxItersCG, double outertol)
187  {
188  using Teuchos::as;
189  using Teuchos::NO_TRANS;
190  typedef Teuchos::ScalarTraits<S> ST;
191  typedef Teuchos::ScalarTraits<S> STO;
192  Teuchos::OSTab tab(out,2);
193  const S ZERO = ST::zero();
194  const S ONE = ST::one();
195  const S D2 = ONE/rho_prime - ONE;
196  const S lx = as<S>(lx_outer);
197  decltype(eta) r = workspace.r,
198  z = workspace.z,
199  d = workspace.d,
200  iDx = workspace.iDx,
201  Hd = workspace.Hd;
202  static RCP<Teuchos::Time> timer;
203  if (timer == Teuchos::null) {
204  std::string methName("truncatedCG<"+Teuchos::TypeNameTraits<S>::name()+">");
205  timer = Teuchos::TimeMonitor::getNewTimer(methName);
206  }
207  timer->start();
208  RCP<const Tpetra::Vector<S,LO,GO,Node>> x;
209  {
210  auto xinit = createVector<S>(r->getMap());
211  XFORM2(xinit,x_outer, as<S>(x_outer));
212  x = xinit;
213  }
215  // init precond. compute:
216  // iDx = inv(D)*x
217  // xiDx = x'*iDx
218  const S xiDx = XFORM3RED(iDx,diag,x, x/diag, x*iDx );
220  // init solver
221  XFORM1( eta, ZERO ); // eta = 0
222  S r_r = XFORM2RED( r,grad, as<S>(grad), r*r ); // r = grad
223  S e_e = ZERO;
224  S z_r = diagPrecond<S,Souter,LO,GO,Node>(diag,x,iDx,xiDx,r,z);
225  XFORM2( d,z, -z ); // d = -z
226  const S rnrm0 = ST::squareroot(r_r);
227  const S kconv = rnrm0*kappa;
228  const S tconv = ST::pow(rnrm0, (theta+1));
229  const S futile_tol = TEUCHOS_MAX(outertol, 100*rnrm0*ST::eps());
230  const S convtol = TEUCHOS_MAX(TEUCHOS_MIN(kconv,tconv), futile_tol);
231  std::string convstr;
232  if (kconv < tconv) convstr = "non-local convergence";
233  else convstr = "local convergence";
235  // iterate
236  if (verbose > 2) *out << "starting tCG with |res| = " << rnrm0 << std::endl;
237  if (verbose > 2) *out << "targeting tol = " << convtol << std::endl;
238  int k = 0;
239  std::string reason;
240  while (true)
241  {
242  // apply Hessian Hd = A*d - lx*d
243  A->apply(*d,*Hd);
244  const S xHd = XFORM3RED(Hd,x,d, Hd - d*lx, x*Hd );
245  const S dHd = XFORM3RED(Hd,x,d, Hd - x*xHd, d*Hd );
246  if (verbose > 19) *out << "curvature: " << dHd << std::endl;
247 
248  /*
249  m_x(e + alpha * d)
250  == (e + alpha * d)'*r + 1/2 * (e + alpha * d)' * H * (e + alpha * d)
251  == e'*r + alpha*d'*r + 1/2*e'*H*e + 1/2*alpha^2*d'*H*d
252  ---------- ------------------
253  derivative w.r.t. alpha, set to zero:
254  0 = d'*r + alpha*d'*H*d
255  so that
256  alpha = -d'*r / d'*H*d
257  substituting d = (gram-schmidt) -z
258  alpha = z'*r / d'*H*d
259  */
260  // compute step size
261  const S alpha = z_r / dHd;
262  if (verbose > 19) *out << "alpha: " << alpha << std::endl;
263  if (verbose > 19) *out << "z_r: " << z_r << std::endl;
264 
265  // anticipate e'*e for this step size
266  const S e_d = REDUCE2(eta,d, eta*d),
267  d_d = REDUCE1(d, d*d );
268  const S new_e_e = e_e + 2.0*alpha*e_d + alpha*alpha*d_d;
269 
270  // check for truncation: positive curvature or implicit trust-region boundary
271  if (dHd <= ZERO || new_e_e > D2)
272  {
273  // find truncated step to boundary
274  // find alpha_prime
275  // eta_new'*eta_new = (eta + alpha_prime*d)'*(eta + alpha_prime*d)
276  // = e_e + 2*alpha_prime*e_d + alpha_prime^2*d_d
277  // choose alpha_prime > 0 such that eta_new'*eta_new == D2
278  // solve for alpha_prime
279  //
280  const S alpha_prime = (-e_d + ST::squareroot(e_d*e_d + d_d*(D2-e_e))) / d_d;
281  if (verbose > 19) *out << "alpha_prime: " << alpha_prime << std::endl;
282  XFORM2(eta,d, eta + alpha_prime*d );
283  if (dHd <= ZERO) reason="negative curvature";
284  else reason="exceeded trust-region";
285  //
286  break;
287  }
288 
289  // compute new optimal point
290  XFORM2(eta,d, eta + alpha*d );
291  e_e = new_e_e;
292 
293  // update the residual
294  const S x_r = XFORM3RED(r,Hd,x, r + alpha*Hd, x*r );
295  // re-tangentialize r
296  r_r = XFORM2RED(r,x, r - x*x_r, r*r );
297  // compute norm
298  S rnrm = ST::squareroot(r_r);
299  if (verbose > 9) *out << "|r| = " << rnrm << std::endl;
300 
301  // check stopping criteria
302  if (rnrm <= convtol) {reason = convstr; break;}
303 
304  // save the old z'*r
305  const S zold_rold = z_r;
306  // z = diagPrec(r)
307  z_r = diagPrecond<S,Souter,LO,GO,Node>(diag,x,iDx,xiDx,r,z);
308  // compute new search direction
309  const S beta = z_r / zold_rold;
310  XFORM2(d,z, -z + beta*d );
311 
312  k += 1;
313  if (k >= maxItersCG) {reason="maximum number of inner iterations";break;}
314  }
315  timer->stop();
316  if (verbose > 1) {
317  *out << "leaving tCG after " << k << " iterations: " << reason << std::endl;
318  }
319  }
320 
322  template <class Sinner, class S, class LO, class GO, class Node>
323  S IRTR(const RCP<Teuchos::FancyOStream> &out, ParameterList &params,
324  const RCP<const Tpetra::CrsMatrix<S,LO,GO,Node> > &A,
325  const RCP<Tpetra::Vector<S,LO,GO,Node> > &x)
326  {
327  using Teuchos::NO_TRANS;
328  Teuchos::OSTab tab(out,2);
329  std::string methName("IRTR<"+Teuchos::TypeNameTraits<S>::name()+","+Teuchos::TypeNameTraits<Sinner>::name()+">");
330  typedef Tpetra::Vector<S,LO,GO,Node> Vec;
331  typedef Tpetra::CrsMatrix<Sinner,LO,GO,Node> MatInner;
332  typedef Teuchos::ScalarTraits<S> ST;
333  const Sinner ONE = Teuchos::ScalarTraits<Sinner>::one();
334  // get objects from level database
335  const int maxIters = params.get<int >("maxIters", 100);
336  const int maxItersCG = params.get<int >("maxItersCG",A->getDomainMap()->getGlobalNumElements());
337  const int verbose = params.get<int >("verbose",0);
338  const double tolerance = params.get<double>("tolerance");
339  const double kappa = params.get<double>("kappa",0.1);
340  const double theta = params.get<double>("theta",2.0);
341  const double rho_prime = params.get<double>("rho_prime",.1);
342  const bool precond = params.get<int> ("precond",1);
343  if (verbose > 10) *out << params << std::endl;
344  if (verbose > 10) *out << "maxIters: " << maxIters << std::endl;
345  TEUCHOS_TEST_FOR_EXCEPTION(rho_prime >= 1.0, std::runtime_error, "IRTR: rho_prime must be less than 1");
346  RCP<Teuchos::Time> timer = Teuchos::TimeMonitor::getNewTimer(methName);
347  // x, ax, gradfx, eta
348  auto map = A->getDomainMap();
349  auto Ax = createVector<S>(map),
350  r = createVector<S>(map),
351  eta = createVector<Sinner>(map),
352  diag = createVector<Sinner>(map);
353  tCG_workspace<Sinner,LO,GO,Node> workspace;
354  workspace.r = createVector<Sinner>(map);
355  workspace.z = createVector<Sinner>(map);
356  workspace.iDx = createVector<Sinner>(map);
357  workspace.d = createVector<Sinner>(map);
358  workspace.Hd = createVector<Sinner>(map);
359  RCP<const MatInner> Ainner = convertHelp<Sinner,S,LO,GO,Node>::doit(A);
360  if (precond) {
361  Ainner->getLocalDiagCopy(*diag);
362  }
363  else {
364  XFORM1(diag, ONE);
365  }
366  timer->start();
368  // init the solver
369  S x_x = REDUCE1(x, x*x ); // x'*x
370  S xnrm = ST::squareroot(x_x);
371  XFORM1( x, x/xnrm); // normalize x
372  A->apply(*x,*Ax); // Ax = A*x
373  S lambda = REDUCE2(x,Ax, x*Ax ); // x'*A*x
374  S rr = XFORM3RED(r,x,Ax, Ax - x*lambda, r*r ); // r = (I - x*x')Ax = Ax - x*lambda and compute its norm
375  S rnrm = ST::squareroot(rr);
376  if (verbose) {
377  *out << "Beginning " << methName << " with λ = " << lambda << std::endl;
378  }
380  // iterate
381  int k=0;
382  while (k < maxIters && rnrm > tolerance) {
384  // solve the trust-region subproblem for update eta
385  truncateCG<Sinner,S,LO,GO,Node>(out,verbose,Ainner,diag,
386  x,r,lambda,
387  eta, workspace,
388  rho_prime,kappa,theta,maxItersCG,tolerance);
390  // update iterate, compute new eigenvalue
391  x_x = XFORM2RED(x,eta, x + eta, x*x ); // x = x+eta and x'*x
392  xnrm = ST::squareroot(x_x);
393  XFORM1(x, x/xnrm); // normalize x
394  A->apply(*x,*Ax); // Ax = A*x
395  lambda = REDUCE2(x,Ax, x*Ax ); // lambda = x'*A*x
396  rr = XFORM3RED(r,x,Ax, Ax - x*lambda, r*r ); // r = A*x - x*lambda and r'*r
397  rnrm = ST::squareroot(rr) / ST::magnitude(lambda);
398  k += 1;
399  if (verbose) {
400  *out << "After iteration " << k << ", λ = " << std::setprecision(2) << std::scientific << lambda << ", |Ax-xλ|/|λ| = " << rnrm << std::endl;
401  }
402  }
403  timer->stop();
404  if (verbose) {
405  *out << "Leaving " << methName << " after " << k << " iterations." << std::endl;
406  }
407  return lambda;
408  }
409 
410 } // end of namespace TpetraExamples
411 
412 #endif // MULTIPRECCG_HPP_
Sparse matrix that presents a compressed sparse row interface.
S IRTR(const RCP< Teuchos::FancyOStream > &out, ParameterList &params, const RCP< const Tpetra::CrsMatrix< S, LO, GO, Node > > &A, const RCP< Tpetra::Vector< S, LO, GO, Node > > &x)
Templated IRTR solver.
RCP< Vector< Scalar, LocalOrdinal, GlobalOrdinal, Node > > createVector(const RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > &map)
Non-member function to create a Vector from a specified Map.
void truncateCG(const RCP< Teuchos::FancyOStream > &out, int verbose, const RCP< const Tpetra::Operator< S, LO, GO, Node > > &A, const RCP< const Tpetra::Vector< S, LO, GO, Node > > &diag, const RCP< const Tpetra::Vector< Souter, LO, GO, Node > > &x_outer, const RCP< const Tpetra::Vector< Souter, LO, GO, Node > > &grad, const Souter &lx_outer, const RCP< Tpetra::Vector< S, LO, GO, Node > > &eta, const tCG_workspace< S, LO, GO, Node > &workspace, double rho_prime, double kappa, double theta, int maxItersCG, double outertol)
Model trust-region subproblem CG solver.
Helper function to call CrsMatrix&lt;T1&gt;::convert&lt;T2&gt; if T1 != T2, and return the original matrix otherw...
A distributed dense vector.