| 1 |
// @HEADER |
| 2 |
// ***************************************************************************** |
| 3 |
// Belos: Block Linear Solvers Package |
| 4 |
// |
| 5 |
// Copyright 2004-2016 NTESS and the Belos contributors. |
| 6 |
// SPDX-License-Identifier: BSD-3-Clause |
| 7 |
// ***************************************************************************** |
| 8 |
// @HEADER |
| 9 |
|
| 10 |
#include "BelosSolverManager.hpp" |
| 11 |
#include "BelosTpetraAdapter.hpp" |
| 12 |
#include "BelosPseudoBlockCGSolMgr.hpp" |
| 13 |
#include "Tpetra_Core.hpp" |
| 14 |
#include "Tpetra_Map.hpp" |
| 15 |
#include "Tpetra_Vector.hpp" |
| 16 |
#include "KokkosBlas1_mult.hpp" |
| 17 |
#include "Teuchos_FancyOStream.hpp" |
| 18 |
#include "Teuchos_oblackholestream.hpp" |
| 19 |
#include "Teuchos_ParameterList.hpp" |
| 20 |
#include <cstdlib> // EXIT_SUCCESS |
| 21 |
#include <iostream> |
| 22 |
|
| 23 |
/// \file wrapTpetraSolver.cpp |
| 24 |
/// \brief Example of how to wrap a "native" solver as a Belos solver |
| 25 |
/// |
| 26 |
/// By a "native" solver, I mean a solver written for a particular |
| 27 |
/// linear algebra implementation. This corresponds to a particular |
| 28 |
/// (ScalarType, MV, and OP) Belos template parameter combination. |
| 29 |
/// "Wrap as a Belos solver" means to make available as a |
| 30 |
/// Belos::SolverManager subclass. |
| 31 |
/// |
| 32 |
/// This example includes a "stub" generic implementation of the |
| 33 |
/// Belos::SolverManager subclass, as well as the actual non-generic |
| 34 |
/// implementation specifically for our linear algebra of choice |
| 35 |
/// (Tpetra in this case). In order to make this example shorter, |
| 36 |
/// I've chosen a linear algebra implementation for which Belos has |
| 37 |
/// MultiVecTraits and OperatorTraits specializations already |
| 38 |
/// implemented. |
| 39 |
|
| 40 |
template<class SC, class LO, class GO, class NT> |
| 41 |
class SolverInput { |
| 42 |
private: |
| 43 |
typedef typename Teuchos::ScalarTraits<SC>::magnitudeType mag_type; |
| 44 |
|
| 45 |
public: |
| 46 |
mag_type r_norm_orig; |
| 47 |
mag_type tol; |
| 48 |
int maxNumIters; |
| 49 |
bool needToScale; |
| 50 |
}; |
| 51 |
|
| 52 |
|
| 53 |
/// \brief Result of a linear solve. |
| 54 |
/// |
| 55 |
/// "A linear solve" refers either to a solve Ax=b with a single |
| 56 |
/// right-hand side b, or to an aggregation of results of two such |
| 57 |
/// solves with the same matrix, but different right-hand sides. |
| 58 |
/// "Aggregation" here just means reporting a single group of metrics. |
| 59 |
/// For example, for two solves, we report the max of the two |
| 60 |
/// iteration counts, and the max of the two residual norms. |
| 61 |
template<class SC, class LO, class GO, class NT> |
| 62 |
class SolverOutput { |
| 63 |
public: |
| 64 |
typedef typename Teuchos::ScalarTraits<SC>::magnitudeType mag_type; |
| 65 |
|
| 66 |
private: |
| 67 |
typedef Teuchos::ScalarTraits<mag_type> STM; |
| 68 |
|
| 69 |
public: |
| 70 |
//! Absolute residual norm. |
| 71 |
mag_type absResid; |
| 72 |
//! Relative residual norm (if applicable). |
| 73 |
mag_type relResid; |
| 74 |
//! Number of iterations executed. |
| 75 |
int numIters; |
| 76 |
//! Whether the solve converged. |
| 77 |
bool converged; |
| 78 |
|
| 79 |
/// \brief Default constructor. |
| 80 |
/// |
| 81 |
/// The default constructor creates output corresponding to "solving |
| 82 |
/// a linear system with zero right-hand sides." This means that |
| 83 |
/// the solve succeeded trivially (converged == true), in zero |
| 84 |
/// iterations, with zero residual norm. |
| 85 |
SolverOutput () : |
| 86 |
absResid (STM::zero ()), |
| 87 |
relResid (STM::zero ()), |
| 88 |
numIters (0), |
| 89 |
converged (true) |
| 90 |
{} |
| 91 |
|
| 92 |
/// \brief Combine two solver outputs. |
| 93 |
/// |
| 94 |
/// "Combining" two solver outputs means aggregating the results of |
| 95 |
/// solving A x_1 = b_1 and A x_2 = b_2, that is, two solves with |
| 96 |
/// the same matrix, but different right-hand sides. Combining is |
| 97 |
/// associative and commutative. |
| 98 |
void |
| 99 |
combine (const SolverOutput<SC, LO, GO, NT>& src) |
| 100 |
{ |
| 101 |
// max of the residuals and iteration counts |
| 102 |
relResid = relResid > src.relResid ? relResid : src.relResid; |
| 103 |
absResid = absResid > src.absResid ? absResid : src.absResid; |
| 104 |
numIters = numIters > src.numIters ? numIters : src.numIters; |
| 105 |
// "converged" if all converged |
| 106 |
converged = converged && src.converged; |
| 107 |
} |
| 108 |
}; |
| 109 |
|
| 110 |
template<class SC, class LO, class GO, class NT> |
| 111 |
std::ostream& |
| 112 |
operator<< (std::ostream& out, |
| 113 |
const SolverOutput<SC, LO, GO, NT>& so) |
| 114 |
{ |
| 115 |
using std::endl; |
| 116 |
|
| 117 |
out << "Solver output:" << endl |
| 118 |
<< " Absolute residual norm: " << so.absResid << endl |
| 119 |
<< " Relative residual norm: " << so.relResid << endl |
| 120 |
<< " Number of iterations: " << so.numIters << endl |
| 121 |
<< " Converged: " << (so.converged ? "true" : "false"); |
| 122 |
return out; |
| 123 |
} |
| 124 |
|
| 125 |
/// \brief Tpetra implementation of CG |
| 126 |
/// |
| 127 |
/// This CG implementation can solve linear systems with multiple |
| 128 |
/// right-hand sides, but it solves them one right-hand side at a |
| 129 |
/// time. The reported convergence results in the case of multiple |
| 130 |
/// right-hand sides is the max of the residuals and iteration counts, |
| 131 |
/// and the AND of the "did it converge" Boolean values. |
| 132 |
template<class SC = Tpetra::Operator<>::scalar_type, |
| 133 |
class LO = typename Tpetra::Operator<SC>::local_ordinal_type, |
| 134 |
class GO = typename Tpetra::Operator<SC, LO>::global_ordinal_type, |
| 135 |
class NT = typename Tpetra::Operator<SC, LO, GO>::node_type> |
| 136 |
class CG { |
| 137 |
public: |
| 138 |
typedef Tpetra::Operator<SC, LO, GO, NT> op_type; |
| 139 |
typedef Tpetra::MultiVector<SC, LO, GO, NT> mv_type; |
| 140 |
|
| 141 |
private: |
| 142 |
typedef Tpetra::Vector<SC, LO, GO, NT> vec_type; |
| 143 |
typedef Teuchos::ScalarTraits<SC> STS; |
| 144 |
typedef typename STS::magnitudeType mag_type; |
| 145 |
typedef Teuchos::ScalarTraits<mag_type> STM; |
| 146 |
typedef typename NT::device_type device_type; |
| 147 |
|
| 148 |
public: |
| 149 |
CG () : |
| 150 |
tol_ (STM::squareroot (STS::eps ())), |
| 151 |
maxNumIters_ (100), |
| 152 |
verbosity_ (0), |
| 153 |
needToScale_ (true), |
| 154 |
relResid_ (STM::zero ()), |
| 155 |
absResid_ (STM::zero ()), |
| 156 |
numIters_ (0), |
| 157 |
converged_ (false) |
| 158 |
{} |
| 159 |
|
| 160 |
CG (const Teuchos::RCP<const op_type>& A) : |
| 161 |
A_ (A), |
| 162 |
tol_ (STM::squareroot (STS::eps ())), |
| 163 |
maxNumIters_ (100), |
| 164 |
verbosity_ (0), |
| 165 |
needToScale_ (true), |
| 166 |
relResid_ (STM::zero ()), |
| 167 |
absResid_ (STM::zero ()), |
| 168 |
numIters_ (0), |
| 169 |
converged_ (false) |
| 170 |
{} |
| 171 |
|
| 172 |
//! Set the matrix A in the linear system to solve. |
| 173 |
void setMatrix (const Teuchos::RCP<const op_type>& A) { |
| 174 |
if (A_.getRawPtr () != A.getRawPtr ()) { |
| 175 |
A_ = A; |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
Teuchos::RCP<const op_type> getMatrix () const { |
| 180 |
return A_; |
| 181 |
} |
| 182 |
|
| 183 |
/// \brief Fill \c params with all parameters this solver |
| 184 |
/// understands, and either their current values, or their default |
| 185 |
/// values. |
| 186 |
/// |
| 187 |
/// \param params [out] To be filled with this solver's parameters. |
| 188 |
/// \param defaultValues [in] Whether to use default values (true) |
| 189 |
/// or current values (false). |
| 190 |
void |
| 191 |
getParameters (Teuchos::ParameterList& params, |
| 192 |
const bool defaultValues) const |
| 193 |
{ |
| 194 |
// Yes, the inner STS is supposed to be STS. STS::eps() returns |
| 195 |
// mag_type. It's SC's machine epsilon. |
| 196 |
const mag_type tol = |
| 197 |
defaultValues ? STM::squareroot (STS::eps ()) : tol_; |
| 198 |
const int maxNumIters = defaultValues ? 100 : maxNumIters_; |
| 199 |
const int verbosity = defaultValues ? 0 : verbosity_; |
| 200 |
const bool needToScale = defaultValues ? true : needToScale_; |
| 201 |
const std::string implResScal = needToScale ? |
| 202 |
"Norm of Preconditioned Initial Residual" : |
| 203 |
"None"; |
| 204 |
|
| 205 |
params.set ("Convergence Tolerance", tol); |
| 206 |
params.set ("Implicit Residual Scaling", implResScal); |
| 207 |
params.set ("Maximum Iterations", maxNumIters); |
| 208 |
params.set ("Verbosity", verbosity); |
| 209 |
} |
| 210 |
|
| 211 |
/// \brief Set the solver's parameters. |
| 212 |
/// |
| 213 |
/// This solver takes a subset of the parameters that |
| 214 |
/// Belos::PseudoBlockCGSolMgr (Belos' CG implementation) takes, and |
| 215 |
/// ignores the rest. If it takes a parameter but doesn't implement |
| 216 |
/// all that parameter's options, it throws an exception if it |
| 217 |
/// encounters an option that it does not implement. The point is |
| 218 |
/// compatibility with Belos. |
| 219 |
void setParameters (Teuchos::ParameterList& params) { |
| 220 |
mag_type tol = tol_; |
| 221 |
bool needToScale = needToScale_; |
| 222 |
if (params.isParameter ("Convergence Tolerance")) { |
| 223 |
tol = params.get<mag_type> ("Convergence Tolerance"); |
| 224 |
TEUCHOS_TEST_FOR_EXCEPTION |
| 225 |
(tol < STM::zero (), std::invalid_argument, |
| 226 |
"\"Convergence tolerance\" = " << tol << " < 0."); |
| 227 |
} |
| 228 |
if (params.isParameter ("Implicit Residual Scaling")) { |
| 229 |
const std::string implScal = |
| 230 |
params.get<std::string> ("Implicit Residual Scaling"); |
| 231 |
if (implScal == "Norm of Initial Residual") { |
| 232 |
// FIXME (mfh 26 Oct 2016) Once we implement left |
| 233 |
// preconditioning, we'll have to keep separate preconditioned |
| 234 |
// and unpreconditioned absolute residuals. |
| 235 |
needToScale = true; |
| 236 |
} |
| 237 |
else if (implScal == "Norm of Preconditioned Initial Residual") { |
| 238 |
needToScale = true; |
| 239 |
} |
| 240 |
else if (implScal == "Norm of RHS") { |
| 241 |
// FIXME (mfh 26 Oct 2016) If we want to implement this, it |
| 242 |
// would make sense to combine that all-reduce with the |
| 243 |
// all-reduce for computing the initial residual norms. We |
| 244 |
// could modify computeResiduals to have an option to do this. |
| 245 |
TEUCHOS_TEST_FOR_EXCEPTION |
| 246 |
(true, std::logic_error, |
| 247 |
"\"Norm of RHS\" scaling option not implemented"); |
| 248 |
} |
| 249 |
else if (implScal == "None") { |
| 250 |
needToScale = false; |
| 251 |
} |
| 252 |
else { |
| 253 |
TEUCHOS_TEST_FOR_EXCEPTION |
| 254 |
(true, std::invalid_argument, "\"Implicit Residual Scaling\"" |
| 255 |
" has an invalid value \"" << implScal << "\"."); |
| 256 |
} |
| 257 |
} |
| 258 |
|
| 259 |
int maxNumIters = maxNumIters_; |
| 260 |
if (params.isParameter ("Maximum Iterations")) { |
| 261 |
maxNumIters = params.get<int> ("Maximum Iterations"); |
| 262 |
TEUCHOS_TEST_FOR_EXCEPTION |
| 263 |
(maxNumIters < 0, std::invalid_argument, |
| 264 |
"\"Maximum Iterations\" = " << maxNumIters << " < 0."); |
| 265 |
} |
| 266 |
|
| 267 |
int verbosity = verbosity_; |
| 268 |
if (params.isType<int> ("Verbosity")) { |
| 269 |
verbosity = params.get<int> ("Verbosity"); |
| 270 |
} |
| 271 |
else if (params.isType<bool> ("Verbosity")) { |
| 272 |
const bool verbBool = params.get<bool> ("Verbosity"); |
| 273 |
verbosity = verbBool ? 1 : 0; |
| 274 |
} |
| 275 |
|
| 276 |
tol_ = tol; |
| 277 |
maxNumIters_ = maxNumIters; |
| 278 |
verbosity_ = verbosity; |
| 279 |
needToScale_ = needToScale; |
| 280 |
} |
| 281 |
|
| 282 |
private: |
| 283 |
static void |
| 284 |
computeResiduals (Kokkos::DualView<mag_type*, device_type>& norms, |
| 285 |
mv_type& R, |
| 286 |
const op_type& A, |
| 287 |
const mv_type& X, |
| 288 |
const mv_type& B) |
| 289 |
{ |
| 290 |
typedef typename device_type::memory_space dev_mem_space; |
| 291 |
|
| 292 |
const SC ONE = STS::one (); |
| 293 |
A.apply (X, R); |
| 294 |
R.update (ONE, B, -ONE); // R := B - A*X |
| 295 |
|
| 296 |
norms.template modify<dev_mem_space> (); |
| 297 |
Kokkos::View<mag_type*, device_type> norms_d = |
| 298 |
norms.template view<dev_mem_space> (); |
| 299 |
R.norm2 (norms_d); |
| 300 |
} |
| 301 |
|
| 302 |
static mag_type |
| 303 |
computeResidual (vec_type& R, |
| 304 |
const op_type& A, |
| 305 |
const vec_type& X, |
| 306 |
const vec_type& B) |
| 307 |
{ |
| 308 |
const SC ONE = STS::one (); |
| 309 |
A.apply (X, R); |
| 310 |
R.update (ONE, B, -ONE); // R := B - A*X |
| 311 |
const mag_type r_norm = R.norm2 (); |
| 312 |
return r_norm; |
| 313 |
} |
| 314 |
|
| 315 |
public: |
| 316 |
//! Solve the linear system(s) AX=B. |
| 317 |
SolverOutput<SC, LO, GO, NT> |
| 318 |
solve (mv_type& X, const mv_type& B) |
| 319 |
{ |
| 320 |
using Teuchos::FancyOStream; |
| 321 |
using Teuchos::getFancyOStream; |
| 322 |
using Teuchos::oblackholestream; |
| 323 |
using Teuchos::RCP; |
| 324 |
using Teuchos::rcp; |
| 325 |
using Teuchos::rcpFromRef; |
| 326 |
|
| 327 |
TEUCHOS_TEST_FOR_EXCEPTION |
| 328 |
(A_.is_null (), std::runtime_error, "Matrix A is null. Please call " |
| 329 |
"setMatrix() with a nonnull argument before calling solve()."); |
| 330 |
TEUCHOS_TEST_FOR_EXCEPTION |
| 331 |
(X.getNumVectors () != B.getNumVectors (), std::runtime_error, |
| 332 |
"X.getNumVectors() = " << X.getNumVectors () << |
| 333 |
" != B.getNumVectors() = " << B.getNumVectors () << "."); |
| 334 |
|
| 335 |
RCP<FancyOStream> outPtr; |
| 336 |
if (verbosity_) { |
| 337 |
const int myRank = A_->getDomainMap ()->getComm ()->getRank (); |
| 338 |
if (myRank == 0) { |
| 339 |
outPtr = getFancyOStream (rcpFromRef (std::cout)); |
| 340 |
} |
| 341 |
else { |
| 342 |
outPtr = getFancyOStream (rcp (new oblackholestream ())); |
| 343 |
} |
| 344 |
} |
| 345 |
return solveImpl (outPtr.getRawPtr (), X, B); |
| 346 |
} |
| 347 |
|
| 348 |
private: |
| 349 |
//! Solve the linear system(s) AX=B. |
| 350 |
SolverOutput<SC, LO, GO, NT> |
| 351 |
solveImpl (Teuchos::FancyOStream* outPtr, mv_type& X, const mv_type& B) |
| 352 |
{ |
| 353 |
using Teuchos::RCP; |
| 354 |
using std::endl; |
| 355 |
|
| 356 |
const size_t numVecs = B.getNumVectors (); |
| 357 |
Kokkos::DualView<mag_type*, device_type> norms ("norms", numVecs); |
| 358 |
mv_type R (B.getMap (), numVecs); |
| 359 |
|
| 360 |
computeResiduals (norms, R, *A_, X, B); |
| 361 |
norms.sync_host (); |
| 362 |
auto norms_h = norms.view_host (); |
| 363 |
|
| 364 |
SolverInput<SC, LO, GO, NT> input; |
| 365 |
input.tol = tol_; |
| 366 |
input.maxNumIters = maxNumIters_; |
| 367 |
input.needToScale = needToScale_; |
| 368 |
SolverOutput<SC, LO, GO, NT> allOutput; |
| 369 |
|
| 370 |
for (size_t j = 0; j < numVecs; ++j) { |
| 371 |
if (outPtr != NULL) { |
| 372 |
*outPtr << "Solve for column " << (j+1) << " of " << numVecs << ":" << endl; |
| 373 |
outPtr->pushTab (); |
| 374 |
} |
| 375 |
RCP<vec_type> R_j = R.getVectorNonConst (j); |
| 376 |
RCP<vec_type> X_j = X.getVectorNonConst (j); |
| 377 |
input.r_norm_orig = norms_h(j); |
| 378 |
SolverOutput<SC, LO, GO, NT> curOutput; |
| 379 |
solveOneVec (outPtr, curOutput, *X_j, *R_j, *A_, input); |
| 380 |
allOutput.combine (curOutput); |
| 381 |
if (outPtr != NULL) { |
| 382 |
outPtr->popTab (); |
| 383 |
} |
| 384 |
} |
| 385 |
return allOutput; |
| 386 |
} |
| 387 |
|
| 388 |
static mag_type |
| 389 |
getConvergenceMetric (const mag_type r_norm_new, |
| 390 |
const SolverInput<SC, LO, GO, NT>& input) |
| 391 |
{ |
| 392 |
if (input.needToScale) { |
| 393 |
return input.r_norm_orig == STM::zero () ? |
| 394 |
r_norm_new : |
| 395 |
(r_norm_new / input.r_norm_orig); |
| 396 |
} |
| 397 |
else { |
| 398 |
return r_norm_new; |
| 399 |
} |
| 400 |
} |
| 401 |
|
| 402 |
static void |
| 403 |
solveOneVec (Teuchos::FancyOStream* outPtr, |
| 404 |
SolverOutput<SC, LO, GO, NT>& output, |
| 405 |
vec_type& X, // in/out |
| 406 |
vec_type& R, // in/out |
| 407 |
const op_type& A, |
| 408 |
const SolverInput<SC, LO, GO, NT>& input) |
| 409 |
{ |
| 410 |
using std::endl; |
| 411 |
|
| 412 |
const SC ONE = STS::one (); |
| 413 |
|
| 414 |
vec_type P (R, Teuchos::Copy); |
| 415 |
vec_type AP (R.getMap ()); |
| 416 |
mag_type r_norm_old = input.r_norm_orig; // R.norm2 () |
| 417 |
|
| 418 |
if (r_norm_old == STM::zero () || r_norm_old <= input.tol) { |
| 419 |
if (outPtr != NULL) { |
| 420 |
*outPtr << "Initial guess' residual norm " << r_norm_old |
| 421 |
<< " meets tolerance " << input.tol << endl; |
| 422 |
} |
| 423 |
output.absResid = r_norm_old; |
| 424 |
output.relResid = r_norm_old; |
| 425 |
output.numIters = 0; |
| 426 |
output.converged = true; |
| 427 |
return; |
| 428 |
} |
| 429 |
|
| 430 |
mag_type r_norm_new = STM::zero (); |
| 431 |
for (int iter = 0; iter < input.maxNumIters; ++iter) { |
| 432 |
if (outPtr != NULL) { |
| 433 |
*outPtr << "Iteration " << (iter+1) << " of " << input.maxNumIters << ":" << endl; |
| 434 |
outPtr->pushTab (); |
| 435 |
*outPtr << "r_norm_old: " << r_norm_old << endl; |
| 436 |
} |
| 437 |
|
| 438 |
A.apply (P, AP); |
| 439 |
const mag_type PAP = P.dot (AP); |
| 440 |
if (outPtr != NULL) { |
| 441 |
*outPtr << "PAP: " << PAP << endl; |
| 442 |
} |
| 443 |
TEUCHOS_TEST_FOR_EXCEPTION |
| 444 |
(PAP <= STM::zero (), std::runtime_error, "At iteration " << (iter+1) |
| 445 |
<< " out of " << input.maxNumIters << ", P.dot(AP) = " << PAP << |
| 446 |
" <= 0. This usually means that the matrix A is not symmetric " |
| 447 |
"(Hermitian) positive definite."); |
| 448 |
|
| 449 |
const mag_type alpha = (r_norm_old * r_norm_old) / PAP; |
| 450 |
if (outPtr != NULL) { |
| 451 |
*outPtr << "alpha: " << alpha << endl; |
| 452 |
} |
| 453 |
X.update (static_cast<SC> (alpha), P, ONE); |
| 454 |
R.update (static_cast<SC> (-alpha), AP, ONE); |
| 455 |
|
| 456 |
r_norm_new = R.norm2 (); |
| 457 |
if (outPtr != NULL) { |
| 458 |
*outPtr << "r_norm_new: " << r_norm_new << endl; |
| 459 |
} |
| 460 |
const mag_type metric = getConvergenceMetric (r_norm_new, input); |
| 461 |
if (outPtr != NULL) { |
| 462 |
*outPtr << "metric: " << metric << endl; |
| 463 |
} |
| 464 |
if (metric <= input.tol) { |
| 465 |
output.absResid = r_norm_new; |
| 466 |
output.relResid = input.r_norm_orig == STM::zero () ? |
| 467 |
r_norm_new : |
| 468 |
(r_norm_new / input.r_norm_orig); |
| 469 |
output.numIters = iter + 1; |
| 470 |
output.converged = true; |
| 471 |
return; |
| 472 |
} |
| 473 |
else if (iter + 1 < input.maxNumIters) { // not last iteration |
| 474 |
const mag_type beta = (r_norm_new * r_norm_new) / |
| 475 |
(r_norm_old * r_norm_old); |
| 476 |
P.update (ONE, R, static_cast<SC> (beta)); |
| 477 |
r_norm_old = r_norm_new; |
| 478 |
} |
| 479 |
|
| 480 |
if (outPtr != NULL) { |
| 481 |
outPtr->popTab (); |
| 482 |
} |
| 483 |
} |
| 484 |
|
| 485 |
// Reached max iteration count without converging |
| 486 |
output.absResid = r_norm_new; |
| 487 |
output.relResid = input.r_norm_orig == STM::zero () ? |
| 488 |
r_norm_new : |
| 489 |
(r_norm_new / input.r_norm_orig); |
| 490 |
output.numIters = input.maxNumIters; |
| 491 |
output.converged = false; |
| 492 |
} |
| 493 |
|
| 494 |
private: |
| 495 |
Teuchos::RCP<const op_type> A_; |
| 496 |
|
| 497 |
mag_type tol_; |
| 498 |
int maxNumIters_; |
| 499 |
int verbosity_; |
| 500 |
// FIXME (mfh 26 Oct 2016) Once we implement left preconditioning, |
| 501 |
// we'll have to keep separate preconditioned and unpreconditioned |
| 502 |
// absolute residuals. |
| 503 |
bool needToScale_; |
| 504 |
|
| 505 |
mag_type relResid_; |
| 506 |
mag_type absResid_; |
| 507 |
int numIters_; |
| 508 |
bool converged_; |
| 509 |
}; |
| 510 |
|
| 511 |
|
| 512 |
template<class ScalarType, class MV, class OP> |
| 513 |
class CgWrapper : |
| 514 |
public Belos::SolverManager<ScalarType, MV, OP> |
| 515 |
{ |
| 516 |
public: |
| 517 |
virtual ~CgWrapper () { |
| 518 |
TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Not implemented"); |
| 519 |
} |
| 520 |
|
| 521 |
const Belos::LinearProblem<ScalarType,MV,OP>& getProblem () const override { |
| 522 |
TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Not implemented"); |
| 523 |
} |
| 524 |
|
| 525 |
Teuchos::RCP<const Teuchos::ParameterList> getValidParameters () const override { |
| 526 |
TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Not implemented"); |
| 527 |
} |
| 528 |
|
| 529 |
Teuchos::RCP<const Teuchos::ParameterList> getCurrentParameters () const override { |
| 530 |
TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Not implemented"); |
| 531 |
} |
| 532 |
|
| 533 |
int getNumIters () const override { |
| 534 |
TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Not implemented"); |
| 535 |
} |
| 536 |
|
| 537 |
bool isLOADetected () const override { |
| 538 |
TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Not implemented"); |
| 539 |
} |
| 540 |
|
| 541 |
void setProblem (const Teuchos::RCP<Belos::LinearProblem<ScalarType,MV,OP> >& problem) override { |
| 542 |
TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Not implemented"); |
| 543 |
} |
| 544 |
|
| 545 |
void setParameters (const Teuchos::RCP<Teuchos::ParameterList>& params) override { |
| 546 |
TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Not implemented"); |
| 547 |
} |
| 548 |
|
| 549 |
void reset (const Belos::ResetType type) override { |
| 550 |
TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Not implemented"); |
| 551 |
} |
| 552 |
|
| 553 |
Belos::ReturnType solve () override { |
| 554 |
TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Not implemented"); |
| 555 |
} |
| 556 |
|
| 557 |
Teuchos::RCP<Belos::SolverManager<ScalarType, MV, OP> > clone () const override { |
| 558 |
return rcp(new CgWrapper<ScalarType, MV, OP>); |
| 559 |
} |
| 560 |
}; |
| 561 |
|
| 562 |
template<class SC, class LO, class GO, class NT> |
| 563 |
class CgWrapper<SC, |
| 564 |
Tpetra::MultiVector<SC, LO, GO, NT>, |
| 565 |
Tpetra::Operator<SC, LO, GO, NT> > : |
| 566 |
public Belos::SolverManager<SC, |
| 567 |
Tpetra::MultiVector<SC, LO, GO, NT>, |
| 568 |
Tpetra::Operator<SC, LO, GO, NT> > |
| 569 |
{ |
| 570 |
public: |
| 571 |
typedef Tpetra::MultiVector<SC, LO, GO, NT> MV; |
| 572 |
typedef Tpetra::Operator<SC, LO, GO, NT> OP; |
| 573 |
typedef Belos::LinearProblem<SC, MV, OP> belos_problem_type; |
| 574 |
|
| 575 |
virtual ~CgWrapper () {} |
| 576 |
|
| 577 |
const Belos::LinearProblem<SC,MV,OP>& getProblem () const override { |
| 578 |
TEUCHOS_TEST_FOR_EXCEPTION |
| 579 |
(problem_.is_null (), std::runtime_error, "The linear problem has not " |
| 580 |
"yet been set. Please call setProblem with a nonnull argument before " |
| 581 |
"calling this method."); |
| 582 |
return *problem_; |
| 583 |
} |
| 584 |
|
| 585 |
Teuchos::RCP<const Teuchos::ParameterList> getValidParameters () const override { |
| 586 |
using Teuchos::ParameterList; |
| 587 |
using Teuchos::RCP; |
| 588 |
|
| 589 |
RCP<ParameterList> params (new ParameterList ("CG")); |
| 590 |
const bool defaultValues = true; |
| 591 |
solver_.getParameters (*params, defaultValues); |
| 592 |
return params; |
| 593 |
} |
| 594 |
|
| 595 |
Teuchos::RCP<const Teuchos::ParameterList> getCurrentParameters () const override { |
| 596 |
using Teuchos::ParameterList; |
| 597 |
using Teuchos::RCP; |
| 598 |
|
| 599 |
RCP<ParameterList> params (new ParameterList ("CG")); |
| 600 |
const bool defaultValues = false; |
| 601 |
solver_.getParameters (*params, defaultValues); |
| 602 |
return params; |
| 603 |
} |
| 604 |
|
| 605 |
int getNumIters () const override { |
| 606 |
return lastSolverOutput_.numIters; |
| 607 |
} |
| 608 |
|
| 609 |
bool isLOADetected () const override { |
| 610 |
return false; // this solver doesn't attempt to detect loss of accuracy |
| 611 |
} |
| 612 |
|
| 613 |
void |
| 614 |
setProblem (const Teuchos::RCP<belos_problem_type>& problem) override |
| 615 |
{ |
| 616 |
if (problem.is_null ()) { |
| 617 |
solver_.setMatrix (Teuchos::null); |
| 618 |
} |
| 619 |
else if (solver_.getMatrix ().getRawPtr () != |
| 620 |
problem->getOperator ().getRawPtr ()) { |
| 621 |
// setMatrix resets state, so only call if necessary. |
| 622 |
solver_.setMatrix (problem->getOperator ()); |
| 623 |
} |
| 624 |
problem_ = problem; |
| 625 |
} |
| 626 |
|
| 627 |
void setParameters (const Teuchos::RCP<Teuchos::ParameterList>& params) override { |
| 628 |
if (! params.is_null ()) { |
| 629 |
solver_.setParameters (*params); |
| 630 |
} |
| 631 |
} |
| 632 |
|
| 633 |
void reset (const Belos::ResetType /* type */ ) override { |
| 634 |
TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Not implemented"); |
| 635 |
} |
| 636 |
|
| 637 |
Belos::ReturnType solve () override { |
| 638 |
using Teuchos::RCP; |
| 639 |
TEUCHOS_TEST_FOR_EXCEPTION |
| 640 |
(problem_.is_null (), std::runtime_error, "The linear problem has not " |
| 641 |
"yet been set. Please call setProblem with a nonnull argument before " |
| 642 |
"calling this method."); |
| 643 |
RCP<const MV> B = problem_->getRHS (); |
| 644 |
TEUCHOS_TEST_FOR_EXCEPTION |
| 645 |
(B.is_null (), std::runtime_error, "The linear problem's right-hand " |
| 646 |
"side(s) B has/have not yet been set. Please call setProblem with " |
| 647 |
"a nonnull argument before calling this method."); |
| 648 |
RCP<MV> X = problem_->getLHS (); |
| 649 |
TEUCHOS_TEST_FOR_EXCEPTION |
| 650 |
(X.is_null (), std::runtime_error, "The linear problem's left-hand " |
| 651 |
"side(s) X has/have not yet been set. Please call setProblem with " |
| 652 |
"a nonnull argument before calling this method."); |
| 653 |
SolverOutput<SC, LO, GO, NT> result = solver_.solve (*X, *B); |
| 654 |
lastSolverOutput_ = result; |
| 655 |
return result.converged ? Belos::Converged : Belos::Unconverged; |
| 656 |
} |
| 657 |
|
| 658 |
Teuchos::RCP<Belos::SolverManager<SC, MV, OP> > clone () const override { |
| 659 |
TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "clone() not implemented"); |
| 660 |
} |
| 661 |
|
| 662 |
private: |
| 663 |
typedef SolverOutput<SC, LO, GO, NT> output_type; |
| 664 |
|
| 665 |
CG<SC, LO, GO, NT> solver_; |
| 666 |
//! Output of the last solve. |
| 667 |
/// |
| 668 |
/// This does not include the solution (multi)vector, just things |
| 669 |
/// like the residual nor, the iteration count, and whether the |
| 670 |
/// solve converged. See SolverOutput documentation above for |
| 671 |
/// details. |
| 672 |
output_type lastSolverOutput_; |
| 673 |
Teuchos::RCP<belos_problem_type> problem_; |
| 674 |
}; |
| 675 |
|
| 676 |
|
| 677 |
template<class SC = Tpetra::Operator<>::scalar_type, |
| 678 |
class LO = typename Tpetra::Operator<SC>::local_ordinal_type, |
| 679 |
class GO = typename Tpetra::Operator<SC, LO>::global_ordinal_type, |
| 680 |
class NT = typename Tpetra::Operator<SC, LO, GO>::node_type> |
| 681 |
class TestDiagonalOperator : public Tpetra::Operator<SC, LO, GO, NT> { |
| 682 |
private: |
| 683 |
typedef typename NT::device_type device_type; |
| 684 |
|
| 685 |
public: |
| 686 |
typedef typename Teuchos::ScalarTraits<SC>::magnitudeType mag_type; |
| 687 |
typedef Tpetra::Map<LO, GO, NT> map_type; |
| 688 |
|
| 689 |
TestDiagonalOperator (const Teuchos::RCP<const map_type>& map, |
| 690 |
const mag_type minSingularValue) : |
| 691 |
map_ (map) |
| 692 |
{ |
| 693 |
typedef Kokkos::View<mag_type*, device_type> dev_view_type; |
| 694 |
typedef typename dev_view_type::HostMirror host_view_type; |
| 695 |
typedef Teuchos::ScalarTraits<SC> STS; |
| 696 |
|
| 697 |
const LO lclNumRows = map_.is_null () ? |
| 698 |
static_cast<LO> (0) : |
| 699 |
static_cast<LO> (map_->getLocalNumElements ()); |
| 700 |
dev_view_type diag_d ("diag", lclNumRows); |
| 701 |
host_view_type diag_h = Kokkos::create_mirror_view (diag_d); |
| 702 |
|
| 703 |
if (lclNumRows != 0) { |
| 704 |
const SC ONE = STS::one (); |
| 705 |
const SC exponent = ONE / static_cast<mag_type> (lclNumRows - 1); |
| 706 |
const SC scalingFactor = ::pow (minSingularValue, exponent); |
| 707 |
diag_h(0) = ONE; |
| 708 |
for (LO lclRow = 1; lclRow < lclNumRows; ++lclRow) { |
| 709 |
diag_h(lclRow) = diag_h(lclRow-1) * scalingFactor; |
| 710 |
} |
| 711 |
} |
| 712 |
Kokkos::deep_copy (diag_d, diag_h); |
| 713 |
diag_ = diag_d; |
| 714 |
} |
| 715 |
|
| 716 |
Teuchos::RCP<const map_type> getDomainMap () const { |
| 717 |
return map_; |
| 718 |
} |
| 719 |
|
| 720 |
Teuchos::RCP<const map_type> getRangeMap () const { |
| 721 |
return map_; |
| 722 |
} |
| 723 |
|
| 724 |
void |
| 725 |
apply (const Tpetra::MultiVector<SC, LO, GO, NT>& X, |
| 726 |
Tpetra::MultiVector<SC, LO, GO, NT>& Y, |
| 727 |
Teuchos::ETransp mode = Teuchos::NO_TRANS, |
| 728 |
SC alpha = Teuchos::ScalarTraits<SC>::one (), |
| 729 |
SC beta = Teuchos::ScalarTraits<SC>::zero ()) const |
| 730 |
{ |
| 731 |
using Teuchos::RCP; |
| 732 |
typedef Tpetra::MultiVector<SC, LO, GO, NT> MV; |
| 733 |
typedef typename MV::impl_scalar_type ISC; |
| 734 |
|
| 735 |
TEUCHOS_TEST_FOR_EXCEPTION |
| 736 |
(mode == Teuchos::CONJ_TRANS && Teuchos::ScalarTraits<SC>::isComplex, |
| 737 |
std::logic_error, "Conjugate transpose case not implemented."); |
| 738 |
|
| 739 |
const size_t numVecs = X.getNumVectors (); |
| 740 |
for (size_t j = 0; j < numVecs; ++j) { |
| 741 |
RCP<const MV> X_j = X.getVector (j); |
| 742 |
RCP<MV> Y_j = Y.getVectorNonConst (j); |
| 743 |
|
| 744 |
auto X_j_lcl_2d = X_j->template getLocalView<device_type> (Tpetra::Access::ReadOnly); |
| 745 |
auto X_j_lcl = Kokkos::subview (X_j_lcl_2d, Kokkos::ALL (), 0); |
| 746 |
auto Y_j_lcl_2d = Y_j->template getLocalView<device_type> (Tpetra::Access::ReadWrite); |
| 747 |
auto Y_j_lcl = Kokkos::subview (Y_j_lcl_2d, Kokkos::ALL (), 0); |
| 748 |
|
| 749 |
KokkosBlas::mult (static_cast<ISC> (beta), Y_j_lcl, |
| 750 |
static_cast<ISC> (alpha), X_j_lcl, diag_); |
| 751 |
} |
| 752 |
} |
| 753 |
|
| 754 |
private: |
| 755 |
Teuchos::RCP<const map_type> map_; |
| 756 |
Kokkos::View<const mag_type*, device_type> diag_; |
| 757 |
}; |
| 758 |
|
| 759 |
|
| 760 |
int |
| 761 |
main (int argc, char* argv[]) |
| 762 |
{ |
| 763 |
using Teuchos::RCP; |
| 764 |
using Teuchos::rcp; |
| 765 |
using std::cout; |
| 766 |
using std::endl; |
| 767 |
typedef Tpetra::Map<> map_type; |
| 768 |
typedef Tpetra::MultiVector<> mv_type; |
| 769 |
typedef Tpetra::Operator<> op_type; |
| 770 |
typedef mv_type::scalar_type SC; |
| 771 |
typedef map_type::global_ordinal_type GO; |
| 772 |
typedef mv_type::mag_type mag_type; |
| 773 |
typedef Teuchos::ScalarTraits<SC> STS; |
| 774 |
typedef Teuchos::ScalarTraits<mag_type> STM; |
| 775 |
const SC ZERO = STS::zero (); |
| 776 |
const SC ONE = STS::one (); |
| 777 |
|
| 778 |
Tpetra::initialize (&argc, &argv); |
| 779 |
auto comm = Tpetra::getDefaultComm (); |
| 780 |
|
| 781 |
const int myRank = comm->getRank (); |
| 782 |
|
| 783 |
const GO gblNumRows = 10000; |
| 784 |
const GO indexBase = 0; |
| 785 |
RCP<const map_type> map (new map_type (gblNumRows, indexBase, comm)); |
| 786 |
const mag_type minSingVal = 0.1; |
| 787 |
RCP<TestDiagonalOperator<> > A = |
| 788 |
rcp (new TestDiagonalOperator<> (map, minSingVal)); |
| 789 |
|
| 790 |
mv_type X (A->getDomainMap (), 1); |
| 791 |
mv_type B (A->getRangeMap (), 1); |
| 792 |
|
| 793 |
B.randomize (); |
| 794 |
|
| 795 |
CG<> solver (A); |
| 796 |
auto out = solver.solve (X, B); |
| 797 |
if (myRank == 0) { |
| 798 |
cout << out << endl; |
| 799 |
} |
| 800 |
|
| 801 |
{ |
| 802 |
// Check the residual. |
| 803 |
mv_type X_copy (X, Teuchos::Copy); |
| 804 |
mv_type R (B.getMap (), B.getNumVectors ()); |
| 805 |
A->apply (X_copy, R); |
| 806 |
R.update (ONE, B, -ONE); |
| 807 |
Teuchos::Array<mag_type> R_norms (R.getNumVectors ()); |
| 808 |
R.norm2 (R_norms ()); |
| 809 |
Teuchos::Array<mag_type> B_norms (B.getNumVectors ()); |
| 810 |
B.norm2 (B_norms ()); |
| 811 |
if (myRank == 0) { |
| 812 |
for (size_t j = 0; j < R.getNumVectors (); ++j) { |
| 813 |
const mag_type relResNorm = (B_norms[j] == STM::zero ()) ? |
| 814 |
R_norms[j] : |
| 815 |
R_norms[j] / B_norms[j]; |
| 816 |
cout << "Column " << (j+1) << " of " << R.getNumVectors () |
| 817 |
<< ": Absolute residual norm: " << R_norms[j] |
| 818 |
<< ", Relative residual norm: " << relResNorm |
| 819 |
<< endl; |
| 820 |
} |
| 821 |
cout << endl; |
| 822 |
} |
| 823 |
} |
| 824 |
|
| 825 |
// Get ready for next solve by resetting initial guess to zero. |
| 826 |
X.putScalar (ZERO); |
| 827 |
|
| 828 |
typedef Belos::LinearProblem<SC, mv_type, op_type> belos_problem_type; |
| 829 |
{ |
| 830 |
RCP<Belos::LinearProblem<SC, mv_type, op_type> > lp = |
| 831 |
rcp (new belos_problem_type (A, rcpFromRef (X), rcpFromRef (B))); |
| 832 |
// Our CG implementation bypasses this, but we call it anyway, just |
| 833 |
// for interface consistency with Belos' other solvers. |
| 834 |
lp->setProblem (); |
| 835 |
|
| 836 |
CgWrapper<SC, mv_type, op_type> solverWrapper; |
| 837 |
solverWrapper.setProblem (lp); |
| 838 |
const Belos::ReturnType belosResult = solverWrapper.solve (); |
| 839 |
if (myRank == 0) { |
| 840 |
cout << "Belos solver wrapper result: " |
| 841 |
<< (belosResult == Belos::Converged ? "Converged" : "Unconverged") |
| 842 |
<< endl |
| 843 |
<< "Number of iterations: " << solverWrapper.getNumIters () |
| 844 |
<< endl; |
| 845 |
} |
| 846 |
} |
| 847 |
|
| 848 |
{ |
| 849 |
// Check the residual. |
| 850 |
mv_type X_copy (X, Teuchos::Copy); |
| 851 |
mv_type R (B.getMap (), B.getNumVectors ()); |
| 852 |
A->apply (X_copy, R); |
| 853 |
R.update (ONE, B, -ONE); |
| 854 |
Teuchos::Array<mag_type> R_norms (R.getNumVectors ()); |
| 855 |
R.norm2 (R_norms ()); |
| 856 |
Teuchos::Array<mag_type> B_norms (B.getNumVectors ()); |
| 857 |
B.norm2 (B_norms ()); |
| 858 |
if (myRank == 0) { |
| 859 |
for (size_t j = 0; j < R.getNumVectors (); ++j) { |
| 860 |
const mag_type relResNorm = (B_norms[j] == STM::zero ()) ? |
| 861 |
R_norms[j] : |
| 862 |
R_norms[j] / B_norms[j]; |
| 863 |
cout << "Column " << (j+1) << " of " << R.getNumVectors () |
| 864 |
<< ": Absolute residual norm: " << R_norms[j] |
| 865 |
<< ", Relative residual norm: " << relResNorm |
| 866 |
<< endl; |
| 867 |
} |
| 868 |
cout << endl; |
| 869 |
} |
| 870 |
} |
| 871 |
|
| 872 |
// Prepare for next linear solve by resetting initial guess to zero. |
| 873 |
X.putScalar (ZERO); |
| 874 |
|
| 875 |
Belos::PseudoBlockCGSolMgr<SC, mv_type, op_type> belosSolver; |
| 876 |
{ |
| 877 |
RCP<Belos::LinearProblem<SC, mv_type, op_type> > lp = |
| 878 |
rcp (new belos_problem_type (A, rcpFromRef (X), rcpFromRef (B))); |
| 879 |
// Our CG implementation bypasses this, but we call it anyway, just |
| 880 |
// for interface consistency with Belos' other solvers. |
| 881 |
lp->setProblem (); |
| 882 |
|
| 883 |
belosSolver.setProblem (lp); |
| 884 |
const Belos::ReturnType belosResult = belosSolver.solve (); |
| 885 |
if (myRank == 0) { |
| 886 |
cout << "Belos solver (PseudoBlockCGSolMgr) result: " |
| 887 |
<< (belosResult == Belos::Converged ? "Converged" : "Unconverged") |
| 888 |
<< endl |
| 889 |
<< "Number of iterations: " << belosSolver.getNumIters () |
| 890 |
<< endl; |
| 891 |
} |
| 892 |
|
| 893 |
// Check the residual. |
| 894 |
mv_type X_copy (X, Teuchos::Copy); |
| 895 |
mv_type R (B.getMap (), B.getNumVectors ()); |
| 896 |
A->apply (X_copy, R); |
| 897 |
R.update (ONE, B, -ONE); |
| 898 |
Teuchos::Array<mag_type> R_norms (R.getNumVectors ()); |
| 899 |
R.norm2 (R_norms ()); |
| 900 |
Teuchos::Array<mag_type> B_norms (B.getNumVectors ()); |
| 901 |
B.norm2 (B_norms ()); |
| 902 |
if (myRank == 0) { |
| 903 |
for (size_t j = 0; j < R.getNumVectors (); ++j) { |
| 904 |
const mag_type relResNorm = (B_norms[j] == STM::zero ()) ? |
| 905 |
R_norms[j] : |
| 906 |
R_norms[j] / B_norms[j]; |
| 907 |
cout << "Column " << (j+1) << " of " << R.getNumVectors () |
| 908 |
<< ": Absolute residual norm: " << R_norms[j] |
| 909 |
<< ", Relative residual norm: " << relResNorm |
| 910 |
<< endl; |
| 911 |
} |
| 912 |
} |
| 913 |
} |
| 914 |
|
| 915 |
Tpetra::finalize (); |
| 916 |
return EXIT_SUCCESS; |
| 917 |
} |