Ifpack2 Templated Preconditioning Package Version 1.0
Loading...
Searching...
No Matches
Ifpack2_AdditiveSchwarz_def.hpp
Go to the documentation of this file.
1// @HEADER
2// *****************************************************************************
3// Ifpack2: Templated Object-Oriented Algebraic Preconditioner Package
4//
5// Copyright 2009 NTESS and the Ifpack2 contributors.
6// SPDX-License-Identifier: BSD-3-Clause
7// *****************************************************************************
8// @HEADER
9
21
22#ifndef IFPACK2_ADDITIVESCHWARZ_DEF_HPP
23#define IFPACK2_ADDITIVESCHWARZ_DEF_HPP
24
26#include "Trilinos_Details_LinearSolverFactory.hpp"
27// We need Ifpack2's implementation of LinearSolver, because we use it
28// to wrap the user-provided Ifpack2::Preconditioner in
29// Ifpack2::AdditiveSchwarz::setInnerPreconditioner.
30#include "Ifpack2_Details_LinearSolver.hpp"
31#include "Ifpack2_Details_getParamTryingTypes.hpp"
32
33#if defined(HAVE_IFPACK2_XPETRA) && defined(HAVE_IFPACK2_ZOLTAN2)
34#include "Zoltan2_TpetraRowGraphAdapter.hpp"
35#include "Zoltan2_OrderingProblem.hpp"
36#include "Zoltan2_OrderingSolution.hpp"
37#endif
38
40#include "Ifpack2_Parameters.hpp"
41#include "Ifpack2_LocalFilter.hpp"
42#include "Ifpack2_ReorderFilter.hpp"
43#include "Ifpack2_SingletonFilter.hpp"
44#include "Ifpack2_Details_AdditiveSchwarzFilter.hpp"
46
47#ifdef HAVE_MPI
48#include "Teuchos_DefaultMpiComm.hpp"
49#endif
50
51#include "Teuchos_StandardParameterEntryValidators.hpp"
52#include <locale> // std::toupper
53#include <fstream>
54#include <sstream>
55#include <string>
56
57#include <Tpetra_BlockMultiVector.hpp>
58
59// FIXME (mfh 25 Aug 2015) Work-around for Bug 6392. This doesn't
60// need to be a weak symbol because it only refers to a function in
61// the Ifpack2 package.
62namespace Ifpack2 {
63namespace Details {
64extern void registerLinearSolverFactory();
65} // namespace Details
66} // namespace Ifpack2
67
68namespace { // (anonymous)
69
70template <class MV>
71bool anyBad(const MV& X) {
72 using STS = Teuchos::ScalarTraits<typename MV::scalar_type>;
73 using magnitude_type = typename STS::magnitudeType;
74 using STM = Teuchos::ScalarTraits<magnitude_type>;
75
76 Teuchos::Array<magnitude_type> norms(X.getNumVectors());
77 X.norm2(norms());
78 bool good = true;
79 for (size_t j = 0; j < X.getNumVectors(); ++j) {
80 if (STM::isnaninf(norms[j])) {
81 good = false;
82 break;
83 }
84 }
85 return !good;
86}
87
88template <class RowMatrixType>
89void writeLocalMatrixMarketPerRank(const Teuchos::RCP<RowMatrixType>& A_local,
90 const int rank,
91 const std::string& basePath) {
92 typedef typename RowMatrixType::local_ordinal_type local_ordinal_type;
93 typedef typename RowMatrixType::scalar_type scalar_type;
94 typedef typename RowMatrixType::nonconst_local_inds_host_view_type nonconst_local_inds_host_view_type;
95 typedef typename RowMatrixType::nonconst_values_host_view_type nonconst_values_host_view_type;
96 typedef Teuchos::ScalarTraits<scalar_type> STS;
97
98 std::ostringstream fname;
99 fname << basePath << ".rank_" << rank << ".mtx";
100
101 std::ofstream out(fname.str().c_str());
102 TEUCHOS_TEST_FOR_EXCEPTION(
103 !out.is_open(), std::runtime_error,
104 "Ifpack2::AdditiveSchwarz: Failed to open debug MatrixMarket file \""
105 << fname.str() << "\".");
106
107 const auto numRows = A_local->getLocalNumRows();
108 const auto numCols = A_local->getLocalNumCols();
109 const auto nnz = A_local->getLocalNumEntries();
110
111 if (STS::isComplex) {
112 out << "%%MatrixMarket matrix coordinate complex general\n";
113 } else {
114 out << "%%MatrixMarket matrix coordinate real general\n";
115 }
116 out << numRows << " " << numCols << " " << nnz << "\n";
117
118 nonconst_local_inds_host_view_type indices("indices", A_local->getLocalMaxNumRowEntries());
119 nonconst_values_host_view_type values("values", A_local->getLocalMaxNumRowEntries());
120
121 for (local_ordinal_type i = 0; i < static_cast<local_ordinal_type>(numRows); ++i) {
122 size_t numEntries = 0;
123 A_local->getLocalRowCopy(i, indices, values, numEntries);
124 for (size_t k = 0; k < numEntries; ++k) {
125 out << (i + 1) << " " << (indices[k] + 1);
126 if (STS::isComplex) {
127 out << " " << STS::real(values[k]) << " " << STS::imag(values[k]) << "\n";
128 } else {
129 out << " " << values[k] << "\n";
130 }
131 }
132 }
133}
134
135} // namespace
136
137namespace Ifpack2 {
138
139template <class MatrixType, class LocalInverseType>
140bool AdditiveSchwarz<MatrixType, LocalInverseType>::hasInnerPrecName() const {
141 const char* options[4] = {
142 "inner preconditioner name",
143 "subdomain solver name",
144 "schwarz: inner preconditioner name",
145 "schwarz: subdomain solver name"};
146 const int numOptions = 4;
147 bool match = false;
148 for (int k = 0; k < numOptions && !match; ++k) {
149 if (List_.isParameter(options[k])) {
150 return true;
151 }
152 }
153 return false;
154}
155
156template <class MatrixType, class LocalInverseType>
157void AdditiveSchwarz<MatrixType, LocalInverseType>::removeInnerPrecName() {
158 const char* options[4] = {
159 "inner preconditioner name",
160 "subdomain solver name",
161 "schwarz: inner preconditioner name",
162 "schwarz: subdomain solver name"};
163 const int numOptions = 4;
164 for (int k = 0; k < numOptions; ++k) {
165 List_.remove(options[k], false);
166 }
167}
168
169template <class MatrixType, class LocalInverseType>
170std::string
171AdditiveSchwarz<MatrixType, LocalInverseType>::innerPrecName() const {
172 const char* options[4] = {
173 "inner preconditioner name",
174 "subdomain solver name",
175 "schwarz: inner preconditioner name",
176 "schwarz: subdomain solver name"};
177 const int numOptions = 4;
178 std::string newName;
179 bool match = false;
180
181 // As soon as one parameter option matches, ignore all others.
182 for (int k = 0; k < numOptions && !match; ++k) {
183 const Teuchos::ParameterEntry* paramEnt =
184 List_.getEntryPtr(options[k]);
185 if (paramEnt != nullptr && paramEnt->isType<std::string>()) {
186 newName = Teuchos::getValue<std::string>(*paramEnt);
187 match = true;
188 }
189 }
190 return match ? newName : defaultInnerPrecName();
191}
192
193template <class MatrixType, class LocalInverseType>
194void AdditiveSchwarz<MatrixType, LocalInverseType>::removeInnerPrecParams() {
195 const char* options[4] = {
196 "inner preconditioner parameters",
197 "subdomain solver parameters",
198 "schwarz: inner preconditioner parameters",
199 "schwarz: subdomain solver parameters"};
200 const int numOptions = 4;
201
202 // As soon as one parameter option matches, ignore all others.
203 for (int k = 0; k < numOptions; ++k) {
204 List_.remove(options[k], false);
205 }
206}
207
208template <class MatrixType, class LocalInverseType>
209std::pair<Teuchos::ParameterList, bool>
210AdditiveSchwarz<MatrixType, LocalInverseType>::innerPrecParams() const {
211 const char* options[4] = {
212 "inner preconditioner parameters",
213 "subdomain solver parameters",
214 "schwarz: inner preconditioner parameters",
215 "schwarz: subdomain solver parameters"};
216 const int numOptions = 4;
217 Teuchos::ParameterList params;
218
219 // As soon as one parameter option matches, ignore all others.
220 bool match = false;
221 for (int k = 0; k < numOptions && !match; ++k) {
222 if (List_.isSublist(options[k])) {
223 params = List_.sublist(options[k]);
224 match = true;
225 }
226 }
227 // Default is an empty list of parameters.
228 return std::make_pair(params, match);
229}
230
231template <class MatrixType, class LocalInverseType>
232std::string
233AdditiveSchwarz<MatrixType, LocalInverseType>::defaultInnerPrecName() {
234 // The default inner preconditioner is "ILUT", for backwards
235 // compatibility with the original AdditiveSchwarz implementation.
236 return "ILUT";
237}
238
239template <class MatrixType, class LocalInverseType>
241 AdditiveSchwarz(const Teuchos::RCP<const row_matrix_type>& A)
242 : Matrix_(A) {}
243
244template <class MatrixType, class LocalInverseType>
246 AdditiveSchwarz(const Teuchos::RCP<const row_matrix_type>& A,
247 const Teuchos::RCP<const coord_type>& coordinates)
248 : Matrix_(A)
249 , Coordinates_(coordinates) {}
250
251template <class MatrixType, class LocalInverseType>
253 AdditiveSchwarz(const Teuchos::RCP<const row_matrix_type>& A,
254 const int overlapLevel)
255 : Matrix_(A)
256 , OverlapLevel_(overlapLevel) {}
257
258template <class MatrixType, class LocalInverseType>
259Teuchos::RCP<const Tpetra::Map<typename MatrixType::local_ordinal_type, typename MatrixType::global_ordinal_type, typename MatrixType::node_type>>
261 getDomainMap() const {
262 TEUCHOS_TEST_FOR_EXCEPTION(
263 Matrix_.is_null(), std::runtime_error,
264 "Ifpack2::AdditiveSchwarz::"
265 "getDomainMap: The matrix to precondition is null. You must either pass "
266 "a nonnull matrix to the constructor, or call setMatrix() with a nonnull "
267 "input, before you may call this method.");
268 return Matrix_->getDomainMap();
269}
270
271template <class MatrixType, class LocalInverseType>
272Teuchos::RCP<const Tpetra::Map<typename MatrixType::local_ordinal_type, typename MatrixType::global_ordinal_type, typename MatrixType::node_type>>
274 TEUCHOS_TEST_FOR_EXCEPTION(
275 Matrix_.is_null(), std::runtime_error,
276 "Ifpack2::AdditiveSchwarz::"
277 "getRangeMap: The matrix to precondition is null. You must either pass "
278 "a nonnull matrix to the constructor, or call setMatrix() with a nonnull "
279 "input, before you may call this method.");
280 return Matrix_->getRangeMap();
281}
282
283template <class MatrixType, class LocalInverseType>
284Teuchos::RCP<const Tpetra::RowMatrix<typename MatrixType::scalar_type, typename MatrixType::local_ordinal_type, typename MatrixType::global_ordinal_type, typename MatrixType::node_type>> AdditiveSchwarz<MatrixType, LocalInverseType>::getMatrix() const {
285 return Matrix_;
286}
287
288template <class MatrixType, class LocalInverseType>
289Teuchos::RCP<const Tpetra::MultiVector<typename Teuchos::ScalarTraits<typename MatrixType::scalar_type>::magnitudeType, typename MatrixType::local_ordinal_type, typename MatrixType::global_ordinal_type, typename MatrixType::node_type>> AdditiveSchwarz<MatrixType, LocalInverseType>::getCoord() const {
290 return Coordinates_;
291}
292
293namespace {
294
295template <class MatrixType, class map_type>
296Teuchos::RCP<const map_type>
297pointMapFromMeshMap(const Teuchos::RCP<const map_type>& meshMap, const typename MatrixType::local_ordinal_type blockSize) {
298 using BMV = Tpetra::BlockMultiVector<
299 typename MatrixType::scalar_type,
300 typename MatrixType::local_ordinal_type,
301 typename MatrixType::global_ordinal_type,
302 typename MatrixType::node_type>;
303
304 if (blockSize == 1) return meshMap;
305
306 return Teuchos::RCP<const map_type>(new map_type(BMV::makePointMap(*meshMap, blockSize)));
307}
308
309template <typename MV, typename Map>
310void resetMultiVecIfNeeded(std::unique_ptr<MV>& mv_ptr, const Map& map, const size_t numVectors, bool initialize) {
311 if (!mv_ptr || mv_ptr->getNumVectors() != numVectors) {
312 mv_ptr.reset(new MV(map, numVectors, initialize));
313 }
314}
315
316} // namespace
317
318template <class MatrixType, class LocalInverseType>
320 apply(const Tpetra::MultiVector<scalar_type, local_ordinal_type, global_ordinal_type, node_type>& B,
321 Tpetra::MultiVector<scalar_type, local_ordinal_type, global_ordinal_type, node_type>& Y,
322 Teuchos::ETransp mode,
323 scalar_type alpha,
324 scalar_type beta) const {
325 using Teuchos::RCP;
326 using Teuchos::rcp;
327 using Teuchos::rcp_dynamic_cast;
328 using Teuchos::Time;
329 using Teuchos::TimeMonitor;
330 typedef Teuchos::ScalarTraits<scalar_type> STS;
331 const char prefix[] = "Ifpack2::AdditiveSchwarz::apply: ";
332
333 TEUCHOS_TEST_FOR_EXCEPTION(!IsComputed_, std::runtime_error,
334 prefix << "isComputed() must be true before you may call apply().");
335 TEUCHOS_TEST_FOR_EXCEPTION(Matrix_.is_null(), std::logic_error, prefix << "The input matrix A is null, but the preconditioner says that it has "
336 "been computed (isComputed() is true). This should never happen, since "
337 "setMatrix() should always mark the preconditioner as not computed if "
338 "its argument is null. "
339 "Please report this bug to the Ifpack2 developers.");
340 TEUCHOS_TEST_FOR_EXCEPTION(Inverse_.is_null(), std::runtime_error,
341 prefix << "The subdomain solver is null. "
342 "This can only happen if you called setInnerPreconditioner() with a null "
343 "input, after calling initialize() or compute(). If you choose to call "
344 "setInnerPreconditioner() with a null input, you must then call it with "
345 "a nonnull input before you may call initialize() or compute().");
346 TEUCHOS_TEST_FOR_EXCEPTION(B.getNumVectors() != Y.getNumVectors(), std::invalid_argument,
347 prefix << "B and Y must have the same number of columns. B has " << B.getNumVectors() << " columns, but Y has " << Y.getNumVectors() << ".");
348 TEUCHOS_TEST_FOR_EXCEPTION(IsOverlapping_ && OverlappingMatrix_.is_null(), std::logic_error,
349 prefix << "The overlapping matrix is null. "
350 "This should never happen if IsOverlapping_ is true. "
351 "Please report this bug to the Ifpack2 developers.");
352 TEUCHOS_TEST_FOR_EXCEPTION(!IsOverlapping_ && localMap_.is_null(), std::logic_error,
353 prefix << "localMap_ is null. "
354 "This should never happen if IsOverlapping_ is false. "
355 "Please report this bug to the Ifpack2 developers.");
356 TEUCHOS_TEST_FOR_EXCEPTION(alpha != STS::one(), std::logic_error,
357 prefix << "Not implemented for alpha != 1.");
358 TEUCHOS_TEST_FOR_EXCEPTION(beta != STS::zero(), std::logic_error,
359 prefix << "Not implemented for beta != 0.");
360
362 const bool bad = anyBad(B);
363 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
364 "Ifpack2::AdditiveSchwarz::apply: "
365 "The 2-norm of the input B is NaN or Inf.");
366 }
367
369 if (!ZeroStartingSolution_) {
370 const bool bad = anyBad(Y);
371 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
372 "Ifpack2::AdditiveSchwarz::apply: "
373 "On input, the initial guess Y has 2-norm NaN or Inf "
374 "(ZeroStartingSolution_ is false).");
375 }
376 }
377
378 const std::string timerName("Ifpack2::AdditiveSchwarz::apply");
379 RCP<Time> timer = TimeMonitor::lookupCounter(timerName);
380 if (timer.is_null()) {
381 timer = TimeMonitor::getNewCounter(timerName);
382 }
383 double startTime = timer->wallTime();
384
385 { // Start timing here.
386 TimeMonitor timeMon(*timer);
387
388 const scalar_type ZERO = Teuchos::ScalarTraits<scalar_type>::zero();
389 const size_t numVectors = B.getNumVectors();
390
391 // mfh 25 Apr 2015: Fix for currently failing
392 // Ifpack2_AdditiveSchwarz_RILUK test.
393 if (ZeroStartingSolution_) {
394 Y.putScalar(ZERO);
395 }
396
397 // set up for overlap communication
398 MV* OverlappingB = nullptr;
399 MV* OverlappingY = nullptr;
400 {
401 RCP<const map_type> B_and_Y_map = pointMapFromMeshMap<MatrixType>(IsOverlapping_ ? OverlappingMatrix_->getRowMap() : localMap_, Matrix_->getBlockSize());
402 resetMultiVecIfNeeded(overlapping_B_, B_and_Y_map, numVectors, false);
403 resetMultiVecIfNeeded(overlapping_Y_, B_and_Y_map, numVectors, false);
404 OverlappingB = overlapping_B_.get();
405 OverlappingY = overlapping_Y_.get();
406 // FIXME (mfh 25 Jun 2019) It's not clear whether we really need
407 // to fill with zeros here, but that's what was happening before.
408 OverlappingB->putScalar(ZERO);
409 OverlappingY->putScalar(ZERO);
410 }
411
412 RCP<MV> globalOverlappingB;
413 if (!IsOverlapping_) {
414 auto matrixPointRowMap = pointMapFromMeshMap<MatrixType>(Matrix_->getRowMap(), Matrix_->getBlockSize());
415
416 globalOverlappingB =
417 OverlappingB->offsetViewNonConst(matrixPointRowMap, 0);
418
419 // Create Import object on demand, if necessary.
420 if (DistributedImporter_.is_null()) {
421 // FIXME (mfh 15 Apr 2014) Why can't we just ask the Matrix
422 // for its Import object? Of course a general RowMatrix might
423 // not necessarily have one.
424 DistributedImporter_ =
425 rcp(new import_type(matrixPointRowMap,
426 Matrix_->getDomainMap()));
427 }
428 }
429
430 resetMultiVecIfNeeded(R_, B.getMap(), numVectors, false);
431 resetMultiVecIfNeeded(C_, Y.getMap(), numVectors, false);
432 // If taking averages in overlap region, we need to compute
433 // the number of procs who have a copy of each overlap dof
434 Teuchos::ArrayRCP<scalar_type> dataNumOverlapCopies;
435 if (IsOverlapping_ && AvgOverlap_) {
436 if (num_overlap_copies_.get() == nullptr) {
437 num_overlap_copies_.reset(new MV(Y.getMap(), 1, false));
438 RCP<MV> onesVec(new MV(OverlappingMatrix_->getRowMap(), 1, false));
439 onesVec->putScalar(Teuchos::ScalarTraits<scalar_type>::one());
440 rcp_dynamic_cast<OverlappingRowMatrix<row_matrix_type>>(OverlappingMatrix_)->exportMultiVector(*onesVec, *(num_overlap_copies_.get()), CombineMode_);
441 }
442 dataNumOverlapCopies = num_overlap_copies_.get()->getDataNonConst(0);
443 }
444
445 MV* R = R_.get();
446 MV* C = C_.get();
447
448 // FIXME (mfh 25 Jun 2019) It was never clear whether C had to be
449 // initialized to zero. R definitely should not need this.
450 C->putScalar(ZERO);
451
452 for (int ni = 0; ni < NumIterations_; ++ni) {
454 const bool bad = anyBad(Y);
455 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
456 "Ifpack2::AdditiveSchwarz::apply: "
457 "At top of iteration "
458 << ni << ", the 2-norm of Y is NaN or Inf.");
459 }
460
461 Tpetra::deep_copy(*R, B);
462
463 // if (ZeroStartingSolution_ && ni == 0) {
464 // Y.putScalar (STS::zero ());
465 // }
466 if (!ZeroStartingSolution_ || ni > 0) {
467 // calculate residual
468 Matrix_->apply(Y, *R, mode, -STS::one(), STS::one());
469
471 const bool bad = anyBad(*R);
472 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
473 "Ifpack2::AdditiveSchwarz::apply: "
474 "At iteration "
475 << ni << ", the 2-norm of R (result of computing "
476 "residual with Y) is NaN or Inf.");
477 }
478 }
479
480 // do communication if necessary
481 if (IsOverlapping_) {
482 TEUCHOS_TEST_FOR_EXCEPTION(OverlappingMatrix_.is_null(), std::logic_error, prefix << "IsOverlapping_ is true, but OverlappingMatrix_, while nonnull, is "
483 "not an OverlappingRowMatrix<row_matrix_type>. Please report this "
484 "bug to the Ifpack2 developers.");
485 OverlappingMatrix_->importMultiVector(*R, *OverlappingB, Tpetra::INSERT);
486
487 // JJH We don't need to import the solution Y we are always solving AY=R with initial guess zero
488 // if (ZeroStartingSolution_ == false)
489 // overlapMatrix->importMultiVector (Y, *OverlappingY, Tpetra::INSERT);
490 /*
491 FIXME from Ifpack1: Will not work with non-zero starting solutions.
492 TODO JJH 3/20/15 I don't know whether this comment is still valid.
493
494 Here is the log for the associated commit 720b2fa4 to Ifpack1:
495
496 "Added a note to recall that the nonzero starting solution will not
497 work properly if reordering, filtering or wider overlaps are used. This only
498 applied to methods like Jacobi, Gauss-Seidel, and SGS (in both point and block
499 version), and not to ILU-type preconditioners."
500 */
501
503 const bool bad = anyBad(*OverlappingB);
504 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
505 "Ifpack2::AdditiveSchwarz::apply: "
506 "At iteration "
507 << ni << ", result of importMultiVector from R "
508 "to OverlappingB, has 2-norm NaN or Inf.");
509 }
510 } else {
511 globalOverlappingB->doImport(*R, *DistributedImporter_, Tpetra::INSERT);
512
514 const bool bad = anyBad(*globalOverlappingB);
515 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
516 "Ifpack2::AdditiveSchwarz::apply: "
517 "At iteration "
518 << ni << ", result of doImport from R, has 2-norm "
519 "NaN or Inf.");
520 }
521 }
522
524 const bool bad = anyBad(*OverlappingB);
525 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
526 "Ifpack2::AdditiveSchwarz::apply: "
527 "At iteration "
528 << ni << ", right before localApply, the 2-norm of "
529 "OverlappingB is NaN or Inf.");
530 }
531
532 // local solve
533 localApply(*OverlappingB, *OverlappingY);
534
536 const bool bad = anyBad(*OverlappingY);
537 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
538 "Ifpack2::AdditiveSchwarz::apply: "
539 "At iteration "
540 << ni << ", after localApply and before export / "
541 "copy, the 2-norm of OverlappingY is NaN or Inf.");
542 }
543
545 const bool bad = anyBad(*C);
546 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
547 "Ifpack2::AdditiveSchwarz::apply: "
548 "At iteration "
549 << ni << ", before export / copy, the 2-norm of C "
550 "is NaN or Inf.");
551 }
552
553 // do communication if necessary
554 if (IsOverlapping_) {
555 TEUCHOS_TEST_FOR_EXCEPTION(OverlappingMatrix_.is_null(), std::logic_error, prefix << "OverlappingMatrix_ is null when it shouldn't be. "
556 "Please report this bug to the Ifpack2 developers.");
557 OverlappingMatrix_->exportMultiVector(*OverlappingY, *C, CombineMode_);
558
559 // average solution in overlap regions if requested via "schwarz: combine mode" "AVG"
560 if (AvgOverlap_) {
561 Teuchos::ArrayRCP<scalar_type> dataC = C->getDataNonConst(0);
562 for (int i = 0; i < (int)C->getMap()->getLocalNumElements(); i++) {
563 dataC[i] = dataC[i] / dataNumOverlapCopies[i];
564 }
565 }
566 } else {
567 // mfh 16 Apr 2014: Make a view of Y with the same Map as
568 // OverlappingY, so that we can copy OverlappingY into Y. This
569 // replaces code that iterates over all entries of OverlappingY,
570 // copying them one at a time into Y. That code assumed that
571 // the rows of Y and the rows of OverlappingY have the same
572 // global indices in the same order; see Bug 5992.
573 RCP<MV> C_view = C->offsetViewNonConst(OverlappingY->getMap(), 0);
574 Tpetra::deep_copy(*C_view, *OverlappingY);
575 }
576
578 const bool bad = anyBad(*C);
579 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
580 "Ifpack2::AdditiveSchwarz::apply: "
581 "At iteration "
582 << ni << ", before Y := C + Y, the 2-norm of C "
583 "is NaN or Inf.");
584 }
585
587 const bool bad = anyBad(Y);
588 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
589 "Ifpack2::AdditiveSchwarz::apply: "
590 "Before Y := C + Y, at iteration "
591 << ni << ", the 2-norm of Y "
592 "is NaN or Inf.");
593 }
594
595 Y.update(UpdateDamping_, *C, STS::one());
596
598 const bool bad = anyBad(Y);
599 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
600 "Ifpack2::AdditiveSchwarz::apply: "
601 "At iteration "
602 << ni << ", after Y := C + Y, the 2-norm of Y "
603 "is NaN or Inf.");
604 }
605 } // for each iteration
606
607 } // Stop timing here
608
610 const bool bad = anyBad(Y);
611 TEUCHOS_TEST_FOR_EXCEPTION(bad, std::runtime_error,
612 "Ifpack2::AdditiveSchwarz::apply: "
613 "The 2-norm of the output Y is NaN or Inf.");
614 }
615
616 ++NumApply_;
617
618 ApplyTime_ += (timer->wallTime() - startTime);
619}
620
621template <class MatrixType, class LocalInverseType>
623 localApply(MV& OverlappingB, MV& OverlappingY) const {
624 using Teuchos::RCP;
625 using Teuchos::rcp_dynamic_cast;
626
627 const size_t numVectors = OverlappingB.getNumVectors();
628
629 auto additiveSchwarzFilter = rcp_dynamic_cast<Details::AdditiveSchwarzFilter<MatrixType>>(innerMatrix_);
630 if (additiveSchwarzFilter) {
631 // Create the reduced system innerMatrix_ * ReducedY = ReducedB.
632 // This effectively fuses 3 tasks:
633 // -SingletonFilter::SolveSingletons (solve entries of OverlappingY corresponding to singletons)
634 // -SingletonFilter::CreateReducedRHS (fill ReducedReorderedB from OverlappingB, with entries in singleton columns eliminated)
635 // -ReorderFilter::permuteOriginalToReordered (apply permutation to ReducedReorderedB)
636 resetMultiVecIfNeeded(reduced_reordered_B_, additiveSchwarzFilter->getRowMap(), numVectors, true);
637 resetMultiVecIfNeeded(reduced_reordered_Y_, additiveSchwarzFilter->getRowMap(), numVectors, true);
638 additiveSchwarzFilter->CreateReducedProblem(OverlappingB, OverlappingY, *reduced_reordered_B_);
639 // Apply inner solver
640 Inverse_->solve(*reduced_reordered_Y_, *reduced_reordered_B_);
641 // Scatter ReducedY back to non-singleton rows of OverlappingY, according to the reordering.
642 additiveSchwarzFilter->UpdateLHS(*reduced_reordered_Y_, OverlappingY);
643 } else {
644 if (FilterSingletons_) {
645 // process singleton filter
646 resetMultiVecIfNeeded(reduced_B_, SingletonMatrix_->getRowMap(), numVectors, true);
647 resetMultiVecIfNeeded(reduced_Y_, SingletonMatrix_->getRowMap(), numVectors, true);
648
649 RCP<SingletonFilter<row_matrix_type>> singletonFilter =
650 rcp_dynamic_cast<SingletonFilter<row_matrix_type>>(SingletonMatrix_);
651 TEUCHOS_TEST_FOR_EXCEPTION(!SingletonMatrix_.is_null() && singletonFilter.is_null(),
652 std::logic_error,
653 "Ifpack2::AdditiveSchwarz::localApply: "
654 "SingletonFilter_ is nonnull but is not a SingletonFilter"
655 "<row_matrix_type>. This should never happen. Please report this bug "
656 "to the Ifpack2 developers.");
657 singletonFilter->SolveSingletons(OverlappingB, OverlappingY);
658 singletonFilter->CreateReducedRHS(OverlappingY, OverlappingB, *reduced_B_);
659
660 // process reordering
661 if (!UseReordering_) {
662 Inverse_->solve(*reduced_Y_, *reduced_B_);
663 } else {
664 RCP<ReorderFilter<row_matrix_type>> rf =
665 rcp_dynamic_cast<ReorderFilter<row_matrix_type>>(ReorderedLocalizedMatrix_);
666 TEUCHOS_TEST_FOR_EXCEPTION(!ReorderedLocalizedMatrix_.is_null() && rf.is_null(), std::logic_error,
667 "Ifpack2::AdditiveSchwarz::localApply: ReorderedLocalizedMatrix_ is "
668 "nonnull but is not a ReorderFilter<row_matrix_type>. This should "
669 "never happen. Please report this bug to the Ifpack2 developers.");
670 resetMultiVecIfNeeded(reordered_B_, reduced_B_->getMap(), numVectors, false);
671 resetMultiVecIfNeeded(reordered_Y_, reduced_Y_->getMap(), numVectors, false);
672 rf->permuteOriginalToReordered(*reduced_B_, *reordered_B_);
673 Inverse_->solve(*reordered_Y_, *reordered_B_);
674 rf->permuteReorderedToOriginal(*reordered_Y_, *reduced_Y_);
675 }
676
677 // finish up with singletons
678 singletonFilter->UpdateLHS(*reduced_Y_, OverlappingY);
679 } else {
680 // process reordering
681 if (!UseReordering_) {
682 Inverse_->solve(OverlappingY, OverlappingB);
683 } else {
684 resetMultiVecIfNeeded(reordered_B_, OverlappingB.getMap(), numVectors, false);
685 resetMultiVecIfNeeded(reordered_Y_, OverlappingY.getMap(), numVectors, false);
686
687 RCP<ReorderFilter<row_matrix_type>> rf =
688 rcp_dynamic_cast<ReorderFilter<row_matrix_type>>(ReorderedLocalizedMatrix_);
689 TEUCHOS_TEST_FOR_EXCEPTION(!ReorderedLocalizedMatrix_.is_null() && rf.is_null(), std::logic_error,
690 "Ifpack2::AdditiveSchwarz::localApply: ReorderedLocalizedMatrix_ is "
691 "nonnull but is not a ReorderFilter<row_matrix_type>. This should "
692 "never happen. Please report this bug to the Ifpack2 developers.");
693 rf->permuteOriginalToReordered(OverlappingB, *reordered_B_);
694 Inverse_->solve(*reordered_Y_, *reordered_B_);
695 rf->permuteReorderedToOriginal(*reordered_Y_, OverlappingY);
696 }
697 }
698 }
699}
700
701template <class MatrixType, class LocalInverseType>
703 setParameters(const Teuchos::ParameterList& plist) {
704 // mfh 18 Nov 2013: Ifpack2's setParameters() method passes in the
705 // input list as const. This means that we have to copy it before
706 // validation or passing into setParameterList().
707 List_ = plist;
708 this->setParameterList(Teuchos::rcpFromRef(List_));
709}
710
711template <class MatrixType, class LocalInverseType>
713 setParameterList(const Teuchos::RCP<Teuchos::ParameterList>& plist) {
714 using Details::getParamTryingTypes;
715 using Teuchos::ParameterEntry;
716 using Teuchos::ParameterEntryValidator;
717 using Teuchos::ParameterList;
718 using Teuchos::RCP;
719 using Teuchos::rcp;
720 using Teuchos::rcp_dynamic_cast;
721 using Teuchos::StringToIntegralParameterEntryValidator;
722 using Tpetra::CombineMode;
723 const char prefix[] = "Ifpack2::AdditiveSchwarz: ";
724
725 if (plist.is_null()) {
726 // Assume that the user meant to set default parameters by passing
727 // in an empty list.
728 this->setParameterList(rcp(new ParameterList()));
729 }
730 // FIXME (mfh 26 Aug 2015) It's not necessarily true that plist is
731 // nonnull at this point.
732
733 // At this point, plist should be nonnull.
734 TEUCHOS_TEST_FOR_EXCEPTION(
735 plist.is_null(), std::logic_error,
736 "Ifpack2::AdditiveSchwarz::"
737 "setParameterList: plist is null. This should never happen, since the "
738 "method should have replaced a null input list with a nonnull empty list "
739 "by this point. Please report this bug to the Ifpack2 developers.");
740
741 // TODO JJH 24March2015 The list needs to be validated. Not sure why this is commented out.
742 // try {
743 // List_.validateParameters (* getValidParameters ());
744 // }
745 // catch (std::exception& e) {
746 // std::cerr << "Ifpack2::AdditiveSchwarz::setParameterList: Validation failed with the following error message: " << e.what () << std::endl;
747 // throw e;
748 // }
749
750 // mfh 18 Nov 2013: Supplying the current value as the default value
751 // when calling ParameterList::get() ensures "delta" behavior when
752 // users pass in new parameters: any unspecified parameters in the
753 // new list retain their values in the old list. This preserves
754 // backwards compatiblity with this class' previous behavior. Note
755 // that validateParametersAndSetDefaults() would have different
756 // behavior: any parameters not in the new list would get default
757 // values, which could be different than their values in the
758 // original list.
759
760 const std::string cmParamName("schwarz: combine mode");
761 const ParameterEntry* cmEnt = plist->getEntryPtr(cmParamName);
762 if (cmEnt != nullptr) {
763 if (cmEnt->isType<CombineMode>()) {
764 CombineMode_ = Teuchos::getValue<CombineMode>(*cmEnt);
765 } else if (cmEnt->isType<int>()) {
766 const int cm = Teuchos::getValue<int>(*cmEnt);
767 CombineMode_ = static_cast<CombineMode>(cm);
768 } else if (cmEnt->isType<std::string>()) {
769 // Try to get the combine mode as a string. If this works, use
770 // the validator to convert to int. This is painful, but
771 // necessary in order to do validation, since the input list may
772 // not necessarily come with a validator.
773 const ParameterEntry& validEntry =
774 getValidParameters()->getEntry(cmParamName);
775 RCP<const ParameterEntryValidator> v = validEntry.validator();
776 using vs2e_type = StringToIntegralParameterEntryValidator<CombineMode>;
777 RCP<const vs2e_type> vs2e = rcp_dynamic_cast<const vs2e_type>(v, true);
778
779 ParameterEntry& inputEntry = plist->getEntry(cmParamName);
780 // As AVG is only a Schwarz option and does not exist in Tpetra's
781 // version of CombineMode, we use a separate boolean local to
782 // Schwarz in conjunction with CombineMode_ == ADD to handle
783 // averaging. Here, we change input entry to ADD and set the boolean.
784 if (strncmp(Teuchos::getValue<std::string>(inputEntry).c_str(), "AVG", 3) == 0) {
785 inputEntry.template setValue<std::string>("ADD");
786 AvgOverlap_ = true;
787 }
788 CombineMode_ = vs2e->getIntegralValue(inputEntry, cmParamName);
789 }
790 }
791 // If doing user partitioning with Block Jacobi relaxation and overlapping blocks, we might
792 // later need to know whether or not the overlapping Schwarz scheme is "ADD" or "ZERO" (which
793 // is really RAS Schwarz. If it is "ADD", communication will be necessary when computing the
794 // proper weights needed to combine solution values in overlap regions
795 if (plist->isParameter("subdomain solver name")) {
796 if (plist->get<std::string>("subdomain solver name") == "BLOCK_RELAXATION") {
797 if (plist->isSublist("subdomain solver parameters")) {
798 if (plist->sublist("subdomain solver parameters").isParameter("relaxation: type")) {
799 if (plist->sublist("subdomain solver parameters").get<std::string>("relaxation: type") == "Jacobi") {
800 if (plist->sublist("subdomain solver parameters").isParameter("partitioner: type")) {
801 if (plist->sublist("subdomain solver parameters").get<std::string>("partitioner: type") == "user") {
802 if (CombineMode_ == Tpetra::ADD) plist->sublist("subdomain solver parameters").set("partitioner: combine mode", "ADD");
803 if (CombineMode_ == Tpetra::ZERO) plist->sublist("subdomain solver parameters").set("partitioner: combine mode", "ZERO");
804 AvgOverlap_ = false; // averaging already taken care of by the partitioner: nonsymmetric overlap combine option
805 }
806 }
807 }
808 }
809 }
810 }
811 }
812
813 OverlapLevel_ = plist->get("schwarz: overlap level", OverlapLevel_);
814
815 // We set IsOverlapping_ in initialize(), once we know that Matrix_ is nonnull.
816
817 // Will we be doing reordering? Unlike Ifpack, we'll use a
818 // "schwarz: reordering list" to give to Zoltan2.
819 UseReordering_ = plist->get("schwarz: use reordering", UseReordering_);
820
821#if !defined(HAVE_IFPACK2_XPETRA) || !defined(HAVE_IFPACK2_ZOLTAN2)
822 TEUCHOS_TEST_FOR_EXCEPTION(
823 UseReordering_, std::invalid_argument,
824 "Ifpack2::AdditiveSchwarz::"
825 "setParameters: You specified \"schwarz: use reordering\" = true. "
826 "This is only valid when Trilinos was built with Ifpack2, Xpetra, and "
827 "Zoltan2 enabled. Either Xpetra or Zoltan2 was not enabled in your build "
828 "of Trilinos.");
829#endif
830
831 // FIXME (mfh 18 Nov 2013) Now would be a good time to validate the
832 // "schwarz: reordering list" parameter list. Currently, that list
833 // gets extracted in setup().
834
835 // if true, filter singletons. NOTE: the filtered matrix can still have
836 // singletons! A simple example: upper triangular matrix, if I remove
837 // the lower node, I still get a matrix with a singleton! However, filter
838 // singletons should help for PDE problems with Dirichlet BCs.
839 FilterSingletons_ = plist->get("schwarz: filter singletons", FilterSingletons_);
840
841 // Allow for damped Schwarz updates
842 getParamTryingTypes<scalar_type, scalar_type, double>(UpdateDamping_, *plist, "schwarz: update damping", prefix);
843
844 // If the inner solver doesn't exist yet, don't create it.
845 // initialize() creates it.
846 //
847 // If the inner solver _does_ exist, there are three cases,
848 // depending on what the user put in the input ParameterList.
849 //
850 // 1. The user did /not/ provide a parameter specifying the inner
851 // solver's type, nor did the user specify a sublist of
852 // parameters for the inner solver
853 // 2. The user did /not/ provide a parameter specifying the inner
854 // solver's type, but /did/ specify a sublist of parameters for
855 // the inner solver
856 // 3. The user provided a parameter specifying the inner solver's
857 // type (it does not matter in this case whether the user gave
858 // a sublist of parameters for the inner solver)
859 //
860 // AdditiveSchwarz has "delta" (relative) semantics for setting
861 // parameters. This means that if the user did not specify the
862 // inner solver's type, we presume that the type has not changed.
863 // Thus, if the inner solver exists, we don't need to recreate it.
864 //
865 // In Case 3, if the user bothered to specify the inner solver's
866 // type, then we must assume it may differ than the current inner
867 // solver's type. Thus, we have to recreate the inner solver. We
868 // achieve this here by assigning null to Inverse_; initialize()
869 // will recreate the solver when it is needed. Our assumption here
870 // is necessary because Ifpack2::Preconditioner does not have a
871 // method for querying a preconditioner's "type" (i.e., name) as a
872 // string. Remember that the user may have previously set an
873 // arbitrary inner solver by calling setInnerPreconditioner().
874 //
875 // See note at the end of setInnerPreconditioner().
876
877 if (!Inverse_.is_null()) {
878 // "CUSTOM" explicitly indicates that the user called or plans to
879 // call setInnerPreconditioner.
880 if (hasInnerPrecName() && innerPrecName() != "CUSTOM") {
881 // Wipe out the current inner solver. initialize() will
882 // recreate it with the correct type.
883 Inverse_ = Teuchos::null;
884 } else {
885 // Extract and apply the sublist of parameters to give to the
886 // inner solver, if there is such a sublist of parameters.
887 std::pair<ParameterList, bool> result = innerPrecParams();
888 if (result.second) {
889 // FIXME (mfh 26 Aug 2015) Rewrite innerPrecParams() so this
890 // isn't another deep copy.
891 Inverse_->setParameters(rcp(new ParameterList(result.first)));
892 }
893 }
894 }
895
896 NumIterations_ = plist->get("schwarz: num iterations", NumIterations_);
897 ZeroStartingSolution_ =
898 plist->get("schwarz: zero starting solution", ZeroStartingSolution_);
899}
900
901template <class MatrixType, class LocalInverseType>
902Teuchos::RCP<const Teuchos::ParameterList>
904 getValidParameters() const {
905 using Teuchos::ParameterList;
906 using Teuchos::parameterList;
907 using Teuchos::RCP;
908 using Teuchos::rcp_const_cast;
909
910 if (validParams_.is_null()) {
911 const int overlapLevel = 0;
912 const bool useReordering = false;
913 const bool filterSingletons = false;
914 const int numIterations = 1;
915 const bool zeroStartingSolution = true;
916 const scalar_type updateDamping = Teuchos::ScalarTraits<scalar_type>::one();
917 ParameterList reorderingSublist;
918 reorderingSublist.set("order_method", std::string("rcm"));
919
920 RCP<ParameterList> plist = parameterList("Ifpack2::AdditiveSchwarz");
921
922 Tpetra::setCombineModeParameter(*plist, "schwarz: combine mode");
923 plist->set("schwarz: overlap level", overlapLevel);
924 plist->set("schwarz: use reordering", useReordering);
925 plist->set("schwarz: reordering list", reorderingSublist);
926 // mfh 24 Mar 2015: We accept this for backwards compatibility
927 // ONLY. It is IGNORED.
928 plist->set("schwarz: compute condest", false);
929 plist->set("schwarz: filter singletons", filterSingletons);
930 plist->set("schwarz: num iterations", numIterations);
931 plist->set("schwarz: zero starting solution", zeroStartingSolution);
932 plist->set("schwarz: update damping", updateDamping);
933
934 // FIXME (mfh 18 Nov 2013) Get valid parameters from inner solver.
935 // JJH The inner solver should handle its own validation.
936 //
937 // FIXME (mfh 18 Nov 2013) Get valid parameters from Zoltan2, if
938 // Zoltan2 was enabled in the build.
939 // JJH Zoltan2 should handle its own validation.
940 //
941
942 validParams_ = rcp_const_cast<const ParameterList>(plist);
943 }
944 return validParams_;
945}
946
947template <class MatrixType, class LocalInverseType>
949 using Teuchos::RCP;
950 using Teuchos::rcp;
951 using Teuchos::SerialComm;
952 using Teuchos::Time;
953 using Teuchos::TimeMonitor;
954 using Tpetra::global_size_t;
955
956 const std::string timerName("Ifpack2::AdditiveSchwarz::initialize");
957 RCP<Time> timer = TimeMonitor::lookupCounter(timerName);
958 if (timer.is_null()) {
959 timer = TimeMonitor::getNewCounter(timerName);
960 }
961 double startTime = timer->wallTime();
962
963 { // Start timing here.
964 TimeMonitor timeMon(*timer);
965
966 TEUCHOS_TEST_FOR_EXCEPTION(
967 Matrix_.is_null(), std::runtime_error,
968 "Ifpack2::AdditiveSchwarz::"
969 "initialize: The matrix to precondition is null. You must either pass "
970 "a nonnull matrix to the constructor, or call setMatrix() with a nonnull "
971 "input, before you may call this method.");
972
973 IsInitialized_ = false;
974 IsComputed_ = false;
975 overlapping_B_.reset(nullptr);
976 overlapping_Y_.reset(nullptr);
977 R_.reset(nullptr);
978 C_.reset(nullptr);
979 reduced_reordered_B_.reset(nullptr);
980 reduced_reordered_Y_.reset(nullptr);
981 reduced_B_.reset(nullptr);
982 reduced_Y_.reset(nullptr);
983 reordered_B_.reset(nullptr);
984 reordered_Y_.reset(nullptr);
985
986 RCP<const Teuchos::Comm<int>> comm = Matrix_->getComm();
987 RCP<const map_type> rowMap = Matrix_->getRowMap();
988 const global_size_t INVALID =
989 Teuchos::OrdinalTraits<global_size_t>::invalid();
990
991 // If there's only one process in the matrix's communicator,
992 // then there's no need to compute overlap.
993 if (comm->getSize() == 1) {
994 OverlapLevel_ = 0;
995 IsOverlapping_ = false;
996 } else if (OverlapLevel_ != 0) {
997 IsOverlapping_ = true;
998 }
999
1000 if (OverlapLevel_ == 0) {
1001 const global_ordinal_type indexBase = rowMap->getIndexBase();
1002 RCP<const SerialComm<int>> localComm(new SerialComm<int>());
1003 // FIXME (mfh 15 Apr 2014) What if indexBase isn't the least
1004 // global index in the list of GIDs on this process?
1005 localMap_ =
1006 rcp(new map_type(INVALID, rowMap->getLocalNumElements(),
1007 indexBase, localComm));
1008 }
1009
1010 // compute the overlapping matrix if necessary
1011 if (IsOverlapping_) {
1012 Teuchos::TimeMonitor t(*Teuchos::TimeMonitor::getNewTimer("OverlappingRowMatrix construction"));
1013 OverlappingMatrix_ = rcp(new OverlappingRowMatrix<row_matrix_type>(Matrix_, OverlapLevel_));
1014 }
1015
1016 setup(); // This does a lot of the initialization work.
1017
1018 [&]() {
1019 if (Inverse_.is_null()) return;
1020 const std::string innerName = innerPrecName();
1021 if (innerName.compare("RILUK") != 0) return;
1022 if (Coordinates_ == Teuchos::null) return;
1023
1024 // a user may provide coordinates that do not match the row map
1025 if (rowMap->getGlobalNumElements() != Coordinates_->getMap()->getGlobalNumElements()) return;
1026
1027 auto ifpack2_Inverse = Teuchos::rcp_dynamic_cast<Ifpack2::Details::LinearSolver<scalar_type, local_ordinal_type, global_ordinal_type, node_type>>(Inverse_);
1028 if (!IsOverlapping_ && !UseReordering_) {
1029 ifpack2_Inverse->setCoord(Coordinates_);
1030 return;
1031 }
1032
1033 RCP<coord_type> tmp_Coordinates_;
1034 if (IsOverlapping_) {
1035 tmp_Coordinates_ = rcp(new coord_type(OverlappingMatrix_->getRowMap(), Coordinates_->getNumVectors(), false));
1036 Tpetra::Import<local_ordinal_type, global_ordinal_type, node_type> importer(Coordinates_->getMap(), tmp_Coordinates_->getMap());
1037 tmp_Coordinates_->doImport(*Coordinates_, importer, Tpetra::INSERT);
1038 } else {
1039 tmp_Coordinates_ = rcp(new coord_type(*Coordinates_, Teuchos::Copy));
1040 }
1041 if (UseReordering_) {
1042 auto coorDevice = tmp_Coordinates_->getLocalViewDevice(Tpetra::Access::ReadWrite);
1043 auto permDevice = perm_coors.view_device();
1044 Kokkos::View<magnitude_type**, Kokkos::LayoutLeft> tmp_coor(Kokkos::view_alloc(Kokkos::WithoutInitializing, "tmp_coor"), coorDevice.extent(0), coorDevice.extent(1));
1045 Kokkos::parallel_for(
1046 Kokkos::RangePolicy<typename crs_matrix_type::execution_space>(0, static_cast<int>(coorDevice.extent(0))), KOKKOS_LAMBDA(const int& i) {
1047 for (int j = 0; j < static_cast<int>(coorDevice.extent(1)); j++) {
1048 tmp_coor(permDevice(i), j) = coorDevice(i, j);
1049 }
1050 });
1051 Kokkos::deep_copy(coorDevice, tmp_coor);
1052 }
1053 ifpack2_Inverse->setCoord(tmp_Coordinates_);
1054 }();
1055
1056 if (!Inverse_.is_null()) {
1057 Inverse_->symbolic(); // Initialize subdomain solver.
1058 }
1059
1060 } // Stop timing here.
1061
1062 IsInitialized_ = true;
1063 ++NumInitialize_;
1064
1065 InitializeTime_ += (timer->wallTime() - startTime);
1066}
1067
1068template <class MatrixType, class LocalInverseType>
1070 return IsInitialized_;
1071}
1072
1073template <class MatrixType, class LocalInverseType>
1075 using Teuchos::RCP;
1076 using Teuchos::Time;
1077 using Teuchos::TimeMonitor;
1078
1079 if (!IsInitialized_) {
1080 initialize();
1081 }
1082
1083 TEUCHOS_TEST_FOR_EXCEPTION(
1084 !isInitialized(), std::logic_error,
1085 "Ifpack2::AdditiveSchwarz::compute: "
1086 "The preconditioner is not yet initialized, "
1087 "even though initialize() supposedly has been called. "
1088 "This should never happen. "
1089 "Please report this bug to the Ifpack2 developers.");
1090
1091 TEUCHOS_TEST_FOR_EXCEPTION(
1092 Inverse_.is_null(), std::runtime_error,
1093 "Ifpack2::AdditiveSchwarz::compute: The subdomain solver is null. "
1094 "This can only happen if you called setInnerPreconditioner() with a null "
1095 "input, after calling initialize() or compute(). If you choose to call "
1096 "setInnerPreconditioner() with a null input, you must then call it with a "
1097 "nonnull input before you may call initialize() or compute().");
1098
1099 const std::string timerName("Ifpack2::AdditiveSchwarz::compute");
1100 RCP<Time> timer = TimeMonitor::lookupCounter(timerName);
1101 if (timer.is_null()) {
1102 timer = TimeMonitor::getNewCounter(timerName);
1103 }
1104 TimeMonitor timeMon(*timer);
1105 double startTime = timer->wallTime();
1106
1107 // compute () assumes that the values of Matrix_ (aka A) have changed.
1108 // If this has overlap, do an import from the input matrix to the halo.
1109 if (IsOverlapping_) {
1110 Teuchos::TimeMonitor t(*Teuchos::TimeMonitor::getNewTimer("Halo Import"));
1111 OverlappingMatrix_->doExtImport();
1112 }
1113 // At this point, either Matrix_ or OverlappingMatrix_ (depending on whether this is overlapping)
1114 // has new values and unchanged structure. If we are using AdditiveSchwarzFilter, update the local matrix.
1115 //
1116 if (auto asf = Teuchos::rcp_dynamic_cast<Details::AdditiveSchwarzFilter<MatrixType>>(innerMatrix_)) {
1117 Teuchos::TimeMonitor t(*Teuchos::TimeMonitor::getNewTimer("Fill Local Matrix"));
1118 // NOTE: if this compute() call comes right after the initialize() with no intervening matrix changes, this call is redundant.
1119 // initialize() already filled the local matrix. However, we have no way to tell if this is the case.
1120 asf->updateMatrixValues();
1121 }
1122 // Now, whether the Inverse_'s matrix is the AdditiveSchwarzFilter's local matrix or simply Matrix_/OverlappingMatrix_,
1123 // it will be able to see the new values and update itself accordingly.
1124
1126 const int rank = Matrix_->getComm()->getRank();
1127 writeLocalMatrixMarketPerRank(innerMatrix_, rank, "Ifpack2_AdditiveSchwarz_innerMatrix");
1128 }
1129
1130 { // Start timing here.
1131
1132 IsComputed_ = false;
1133 Inverse_->numeric();
1134 } // Stop timing here.
1135
1136 IsComputed_ = true;
1137 ++NumCompute_;
1138
1139 ComputeTime_ += (timer->wallTime() - startTime);
1140}
1141
1142//==============================================================================
1143// Returns true if the preconditioner has been successfully computed, false otherwise.
1144template <class MatrixType, class LocalInverseType>
1146 return IsComputed_;
1147}
1148
1149template <class MatrixType, class LocalInverseType>
1151 return NumInitialize_;
1152}
1153
1154template <class MatrixType, class LocalInverseType>
1156 return NumCompute_;
1157}
1158
1159template <class MatrixType, class LocalInverseType>
1161 return NumApply_;
1162}
1163
1164template <class MatrixType, class LocalInverseType>
1166 return InitializeTime_;
1167}
1168
1169template <class MatrixType, class LocalInverseType>
1171 return ComputeTime_;
1172}
1173
1174template <class MatrixType, class LocalInverseType>
1176 return ApplyTime_;
1177}
1178
1179template <class MatrixType, class LocalInverseType>
1181 std::ostringstream out;
1182
1183 out << "\"Ifpack2::AdditiveSchwarz\": {";
1184 if (this->getObjectLabel() != "") {
1185 out << "Label: \"" << this->getObjectLabel() << "\", ";
1186 }
1187 out << "Initialized: " << (isInitialized() ? "true" : "false")
1188 << ", Computed: " << (isComputed() ? "true" : "false")
1189 << ", Iterations: " << NumIterations_
1190 << ", Overlap level: " << OverlapLevel_
1191 << ", Subdomain reordering: \"" << ReorderingAlgorithm_ << "\"";
1192 out << ", Combine mode: \"";
1193 if (CombineMode_ == Tpetra::INSERT) {
1194 out << "INSERT";
1195 } else if (CombineMode_ == Tpetra::ADD) {
1196 out << "ADD";
1197 } else if (CombineMode_ == Tpetra::REPLACE) {
1198 out << "REPLACE";
1199 } else if (CombineMode_ == Tpetra::ABSMAX) {
1200 out << "ABSMAX";
1201 } else if (CombineMode_ == Tpetra::ZERO) {
1202 out << "ZERO";
1203 }
1204 out << "\"";
1205 if (Matrix_.is_null()) {
1206 out << ", Matrix: null";
1207 } else {
1208 out << ", Global matrix dimensions: ["
1209 << Matrix_->getGlobalNumRows() << ", "
1210 << Matrix_->getGlobalNumCols() << "]";
1211 }
1212 out << ", Inner solver: ";
1213 if (!Inverse_.is_null()) {
1214 Teuchos::RCP<Teuchos::Describable> inv =
1215 Teuchos::rcp_dynamic_cast<Teuchos::Describable>(Inverse_);
1216 if (!inv.is_null()) {
1217 out << "{" << inv->description() << "}";
1218 } else {
1219 out << "{"
1220 << "Some inner solver"
1221 << "}";
1222 }
1223 } else {
1224 out << "null";
1225 }
1226
1227 out << "}";
1228 return out.str();
1229}
1230
1231template <class MatrixType, class LocalInverseType>
1233 describe(Teuchos::FancyOStream& out,
1234 const Teuchos::EVerbosityLevel verbLevel) const {
1235 using std::endl;
1236 using Teuchos::OSTab;
1237 using Teuchos::TypeNameTraits;
1238
1239 const int myRank = Matrix_->getComm()->getRank();
1240 const int numProcs = Matrix_->getComm()->getSize();
1241 const Teuchos::EVerbosityLevel vl =
1242 (verbLevel == Teuchos::VERB_DEFAULT) ? Teuchos::VERB_LOW : verbLevel;
1243
1244 if (vl > Teuchos::VERB_NONE) {
1245 // describe() starts with a tab, by convention.
1246 OSTab tab0(out);
1247 if (myRank == 0) {
1248 out << "\"Ifpack2::AdditiveSchwarz\":";
1249 }
1250 OSTab tab1(out);
1251 if (myRank == 0) {
1252 out << "MatrixType: " << TypeNameTraits<MatrixType>::name() << endl;
1253 out << "LocalInverseType: " << TypeNameTraits<LocalInverseType>::name() << endl;
1254 if (this->getObjectLabel() != "") {
1255 out << "Label: \"" << this->getObjectLabel() << "\"" << endl;
1256 }
1257
1258 out << "Overlap level: " << OverlapLevel_ << endl
1259 << "Combine mode: \"";
1260 if (CombineMode_ == Tpetra::INSERT) {
1261 out << "INSERT";
1262 } else if (CombineMode_ == Tpetra::ADD) {
1263 out << "ADD";
1264 } else if (CombineMode_ == Tpetra::REPLACE) {
1265 out << "REPLACE";
1266 } else if (CombineMode_ == Tpetra::ABSMAX) {
1267 out << "ABSMAX";
1268 } else if (CombineMode_ == Tpetra::ZERO) {
1269 out << "ZERO";
1270 }
1271 out << "\"" << endl
1272 << "Subdomain reordering: \"" << ReorderingAlgorithm_ << "\"" << endl;
1273 }
1274
1275 if (Matrix_.is_null()) {
1276 if (myRank == 0) {
1277 out << "Matrix: null" << endl;
1278 }
1279 } else {
1280 if (myRank == 0) {
1281 out << "Matrix:" << endl;
1282 std::flush(out);
1283 }
1284 Matrix_->getComm()->barrier(); // wait for output to finish
1285 Matrix_->describe(out, Teuchos::VERB_LOW);
1286 }
1287
1288 if (myRank == 0) {
1289 out << "Number of initialize calls: " << getNumInitialize() << endl
1290 << "Number of compute calls: " << getNumCompute() << endl
1291 << "Number of apply calls: " << getNumApply() << endl
1292 << "Total time in seconds for initialize: " << getInitializeTime() << endl
1293 << "Total time in seconds for compute: " << getComputeTime() << endl
1294 << "Total time in seconds for apply: " << getApplyTime() << endl;
1295 }
1296
1297 if (Inverse_.is_null()) {
1298 if (myRank == 0) {
1299 out << "Subdomain solver: null" << endl;
1300 }
1301 } else {
1302 if (vl < Teuchos::VERB_EXTREME) {
1303 if (myRank == 0) {
1304 auto ifpack2_inverse = Teuchos::rcp_dynamic_cast<Ifpack2::Details::LinearSolver<scalar_type, local_ordinal_type, global_ordinal_type, node_type>>(Inverse_);
1305 if (ifpack2_inverse.is_null())
1306 out << "Subdomain solver: not null" << endl;
1307 else {
1308 out << "Subdomain solver: ";
1309 ifpack2_inverse->describe(out, Teuchos::VERB_LOW);
1310 }
1311 }
1312 } else { // vl >= Teuchos::VERB_EXTREME
1313 for (int p = 0; p < numProcs; ++p) {
1314 if (p == myRank) {
1315 out << "Subdomain solver on Process " << myRank << ":";
1316 if (Inverse_.is_null()) {
1317 out << "null" << endl;
1318 } else {
1319 Teuchos::RCP<Teuchos::Describable> inv =
1320 Teuchos::rcp_dynamic_cast<Teuchos::Describable>(Inverse_);
1321 if (!inv.is_null()) {
1322 out << endl;
1323 inv->describe(out, vl);
1324 } else {
1325 out << "null" << endl;
1326 }
1327 }
1328 }
1329 Matrix_->getComm()->barrier();
1330 Matrix_->getComm()->barrier();
1331 Matrix_->getComm()->barrier(); // wait for output to finish
1332 }
1333 }
1334 }
1335
1336 Matrix_->getComm()->barrier(); // wait for output to finish
1337 }
1338}
1339
1340template <class MatrixType, class LocalInverseType>
1341std::ostream& AdditiveSchwarz<MatrixType, LocalInverseType>::print(std::ostream& os) const {
1342 Teuchos::FancyOStream fos(Teuchos::rcp(&os, false));
1343 fos.setOutputToRootOnly(0);
1344 describe(fos);
1345 return (os);
1346}
1347
1348template <class MatrixType, class LocalInverseType>
1350 return OverlapLevel_;
1351}
1352
1353template <class MatrixType, class LocalInverseType>
1355#ifdef HAVE_MPI
1356 using Teuchos::MpiComm;
1357#endif // HAVE_MPI
1358 using Teuchos::ArrayRCP;
1359 using Teuchos::ParameterList;
1360 using Teuchos::RCP;
1361 using Teuchos::rcp;
1362 using Teuchos::rcp_dynamic_cast;
1363 using Teuchos::rcpFromRef;
1364
1365 TEUCHOS_TEST_FOR_EXCEPTION(
1366 Matrix_.is_null(), std::runtime_error,
1367 "Ifpack2::AdditiveSchwarz::"
1368 "initialize: The matrix to precondition is null. You must either pass "
1369 "a nonnull matrix to the constructor, or call setMatrix() with a nonnull "
1370 "input, before you may call this method.");
1371
1372 // If the matrix is a CrsMatrix or OverlappingRowMatrix, use the high-performance
1373 // AdditiveSchwarzFilter. Otherwise, use composition of Reordered/Singleton/LocalFilter.
1374 auto matrixCrs = rcp_dynamic_cast<const crs_matrix_type>(Matrix_);
1375 if (!OverlappingMatrix_.is_null() || !matrixCrs.is_null()) {
1376 ArrayRCP<local_ordinal_type> perm;
1377 ArrayRCP<local_ordinal_type> revperm;
1378 if (UseReordering_) {
1379 Teuchos::TimeMonitor t(*Teuchos::TimeMonitor::getNewTimer("Reordering"));
1380#if defined(HAVE_IFPACK2_XPETRA) && defined(HAVE_IFPACK2_ZOLTAN2)
1381 // Unlike Ifpack, Zoltan2 does all the dirty work here.
1382 Teuchos::ParameterList zlist = List_.sublist("schwarz: reordering list");
1383 ReorderingAlgorithm_ = zlist.get<std::string>("order_method", "rcm");
1384
1385 if (ReorderingAlgorithm_ == "user") {
1386 // User-provided reordering
1387 perm = zlist.get<Teuchos::ArrayRCP<local_ordinal_type>>("user ordering");
1388 revperm = zlist.get<Teuchos::ArrayRCP<local_ordinal_type>>("user reverse ordering");
1389 } else {
1390 // Zoltan2 reordering
1391 typedef Tpetra::RowGraph<local_ordinal_type, global_ordinal_type, node_type> row_graph_type;
1392 typedef Zoltan2::TpetraRowGraphAdapter<row_graph_type> z2_adapter_type;
1393 auto constActiveGraph = Teuchos::rcp_const_cast<const row_graph_type>(
1394 IsOverlapping_ ? OverlappingMatrix_->getGraph() : Matrix_->getGraph());
1395 z2_adapter_type Zoltan2Graph(constActiveGraph);
1396
1397 typedef Zoltan2::OrderingProblem<z2_adapter_type> ordering_problem_type;
1398#ifdef HAVE_MPI
1399 // Grab the MPI Communicator and build the ordering problem with that
1400 MPI_Comm myRawComm;
1401
1402 RCP<const MpiComm<int>> mpicomm =
1403 rcp_dynamic_cast<const MpiComm<int>>(Matrix_->getComm());
1404 if (mpicomm == Teuchos::null) {
1405 myRawComm = MPI_COMM_SELF;
1406 } else {
1407 myRawComm = *(mpicomm->getRawMpiComm());
1408 }
1409 ordering_problem_type MyOrderingProblem(&Zoltan2Graph, &zlist, myRawComm);
1410#else
1411 ordering_problem_type MyOrderingProblem(&Zoltan2Graph, &zlist);
1412#endif
1413 MyOrderingProblem.solve();
1414
1415 {
1416 typedef Zoltan2::LocalOrderingSolution<local_ordinal_type>
1417 ordering_solution_type;
1418
1419 ordering_solution_type sol(*MyOrderingProblem.getLocalOrderingSolution());
1420
1421 // perm[i] gives the where OLD index i shows up in the NEW
1422 // ordering. revperm[i] gives the where NEW index i shows
1423 // up in the OLD ordering. Note that perm is actually the
1424 // "inverse permutation," in Zoltan2 terms.
1425 perm = sol.getPermutationRCPConst(true);
1426 revperm = sol.getPermutationRCPConst();
1427 }
1428 }
1429#else
1430 // This is a logic_error, not a runtime_error, because
1431 // setParameters() should have excluded this case already.
1432 TEUCHOS_TEST_FOR_EXCEPTION(
1433 true, std::logic_error,
1434 "Ifpack2::AdditiveSchwarz::setup: "
1435 "The Zoltan2 and Xpetra packages must be enabled in order "
1436 "to support reordering.");
1437#endif
1438 } else {
1439 local_ordinal_type numLocalRows = OverlappingMatrix_.is_null() ? matrixCrs->getLocalNumRows() : OverlappingMatrix_->getLocalNumRows();
1440 // Use an identity ordering.
1441 // TODO: create a non-permuted code path in AdditiveSchwarzFilter, in the case that neither
1442 // reordering nor singleton filtering are enabled. In this situation it's like LocalFilter.
1443 perm = ArrayRCP<local_ordinal_type>(numLocalRows);
1444 revperm = ArrayRCP<local_ordinal_type>(numLocalRows);
1445 for (local_ordinal_type i = 0; i < numLocalRows; i++) {
1446 perm[i] = i;
1447 revperm[i] = i;
1448 }
1449 }
1450
1451 // Now, construct the filter
1452 {
1453 Teuchos::TimeMonitor t(*Teuchos::TimeMonitor::getNewTimer("Filter construction"));
1454 RCP<Details::AdditiveSchwarzFilter<MatrixType>> asf;
1455 if (OverlappingMatrix_.is_null())
1456 asf = rcp(new Details::AdditiveSchwarzFilter<MatrixType>(matrixCrs, perm, revperm, FilterSingletons_));
1457 else
1458 asf = rcp(new Details::AdditiveSchwarzFilter<MatrixType>(OverlappingMatrix_, perm, revperm, FilterSingletons_));
1459 innerMatrix_ = asf;
1460 }
1461
1462 if (UseReordering_ && (Coordinates_ != Teuchos::null)) {
1463 perm_coors = perm_dualview_type(Kokkos::view_alloc(Kokkos::WithoutInitializing, "perm_coors"), perm.size());
1464 perm_coors.modify_host();
1465 auto permHost = perm_coors.view_host();
1466 for (local_ordinal_type i = 0; i < static_cast<local_ordinal_type>(perm.size()); i++) {
1467 permHost(i) = perm[i];
1468 }
1469 perm_coors.sync_device();
1470 }
1471 } else {
1472 // Localized version of Matrix_ or OverlappingMatrix_.
1473 RCP<row_matrix_type> LocalizedMatrix;
1474
1475 // The "most current local matrix." At the end of this method, this
1476 // will be handed off to the inner solver.
1477 RCP<row_matrix_type> ActiveMatrix;
1478
1479 // Create localized matrix.
1480 if (!OverlappingMatrix_.is_null()) {
1481 LocalizedMatrix = rcp(new LocalFilter<row_matrix_type>(OverlappingMatrix_));
1482 } else {
1483 LocalizedMatrix = rcp(new LocalFilter<row_matrix_type>(Matrix_));
1484 }
1485
1486 // Sanity check; I don't trust the logic above to have created LocalizedMatrix.
1487 TEUCHOS_TEST_FOR_EXCEPTION(
1488 LocalizedMatrix.is_null(), std::logic_error,
1489 "Ifpack2::AdditiveSchwarz::setup: LocalizedMatrix is null, after the code "
1490 "that claimed to have created it. This should never be the case. Please "
1491 "report this bug to the Ifpack2 developers.");
1492
1493 // Mark localized matrix as active
1494 ActiveMatrix = LocalizedMatrix;
1495
1496 // Singleton Filtering
1497 if (FilterSingletons_) {
1498 SingletonMatrix_ = rcp(new SingletonFilter<row_matrix_type>(LocalizedMatrix));
1499 ActiveMatrix = SingletonMatrix_;
1500 }
1501
1502 // Do reordering
1503 if (UseReordering_) {
1504#if defined(HAVE_IFPACK2_XPETRA) && defined(HAVE_IFPACK2_ZOLTAN2)
1505 // Unlike Ifpack, Zoltan2 does all the dirty work here.
1506 typedef ReorderFilter<row_matrix_type> reorder_filter_type;
1507 Teuchos::ParameterList zlist = List_.sublist("schwarz: reordering list");
1508 ReorderingAlgorithm_ = zlist.get<std::string>("order_method", "rcm");
1509
1510 ArrayRCP<local_ordinal_type> perm;
1511 ArrayRCP<local_ordinal_type> revperm;
1512
1513 if (ReorderingAlgorithm_ == "user") {
1514 // User-provided reordering
1515 perm = zlist.get<Teuchos::ArrayRCP<local_ordinal_type>>("user ordering");
1516 revperm = zlist.get<Teuchos::ArrayRCP<local_ordinal_type>>("user reverse ordering");
1517 } else {
1518 // Zoltan2 reordering
1519 typedef Tpetra::RowGraph<local_ordinal_type, global_ordinal_type, node_type> row_graph_type;
1520 typedef Zoltan2::TpetraRowGraphAdapter<row_graph_type> z2_adapter_type;
1521 RCP<const row_graph_type> constActiveGraph =
1522 Teuchos::rcp_const_cast<const row_graph_type>(ActiveMatrix->getGraph());
1523 z2_adapter_type Zoltan2Graph(constActiveGraph);
1524
1525 typedef Zoltan2::OrderingProblem<z2_adapter_type> ordering_problem_type;
1526#ifdef HAVE_MPI
1527 // Grab the MPI Communicator and build the ordering problem with that
1528 MPI_Comm myRawComm;
1529
1530 RCP<const MpiComm<int>> mpicomm =
1531 rcp_dynamic_cast<const MpiComm<int>>(ActiveMatrix->getComm());
1532 if (mpicomm == Teuchos::null) {
1533 myRawComm = MPI_COMM_SELF;
1534 } else {
1535 myRawComm = *(mpicomm->getRawMpiComm());
1536 }
1537 ordering_problem_type MyOrderingProblem(&Zoltan2Graph, &zlist, myRawComm);
1538#else
1539 ordering_problem_type MyOrderingProblem(&Zoltan2Graph, &zlist);
1540#endif
1541 MyOrderingProblem.solve();
1542
1543 {
1544 typedef Zoltan2::LocalOrderingSolution<local_ordinal_type>
1545 ordering_solution_type;
1546
1547 ordering_solution_type sol(*MyOrderingProblem.getLocalOrderingSolution());
1548
1549 // perm[i] gives the where OLD index i shows up in the NEW
1550 // ordering. revperm[i] gives the where NEW index i shows
1551 // up in the OLD ordering. Note that perm is actually the
1552 // "inverse permutation," in Zoltan2 terms.
1553 perm = sol.getPermutationRCPConst(true);
1554 revperm = sol.getPermutationRCPConst();
1555 }
1556 }
1557 // All reorderings here...
1558 ReorderedLocalizedMatrix_ = rcp(new reorder_filter_type(ActiveMatrix, perm, revperm));
1559
1560 ActiveMatrix = ReorderedLocalizedMatrix_;
1561#else
1562 // This is a logic_error, not a runtime_error, because
1563 // setParameters() should have excluded this case already.
1564 TEUCHOS_TEST_FOR_EXCEPTION(
1565 true, std::logic_error,
1566 "Ifpack2::AdditiveSchwarz::setup: "
1567 "The Zoltan2 and Xpetra packages must be enabled in order "
1568 "to support reordering.");
1569#endif
1570 }
1571 innerMatrix_ = ActiveMatrix;
1572 }
1573
1574 TEUCHOS_TEST_FOR_EXCEPTION(
1575 innerMatrix_.is_null(), std::logic_error,
1576 "Ifpack2::AdditiveSchwarz::"
1577 "setup: Inner matrix is null right before constructing inner solver. "
1578 "Please report this bug to the Ifpack2 developers.");
1579
1580 // Construct the inner solver if necessary.
1581 if (Inverse_.is_null()) {
1582 const std::string innerName = innerPrecName();
1583 TEUCHOS_TEST_FOR_EXCEPTION(
1584 innerName == "INVALID", std::logic_error,
1585 "Ifpack2::AdditiveSchwarz::initialize: AdditiveSchwarz doesn't "
1586 "know how to create an instance of your LocalInverseType \""
1587 << Teuchos::TypeNameTraits<LocalInverseType>::name() << "\". "
1588 "Please talk to the Ifpack2 developers for details.");
1589
1590 TEUCHOS_TEST_FOR_EXCEPTION(
1591 innerName == "CUSTOM", std::runtime_error,
1592 "Ifpack2::AdditiveSchwarz::"
1593 "initialize: If the \"inner preconditioner name\" parameter (or any "
1594 "alias thereof) has the value \"CUSTOM\", then you must first call "
1595 "setInnerPreconditioner with a nonnull inner preconditioner input before "
1596 "you may call initialize().");
1597
1598 // FIXME (mfh 26 Aug 2015) Once we fix Bug 6392, the following
1599 // three lines of code can and SHOULD go away.
1600 if (!Trilinos::Details::Impl::registeredSomeLinearSolverFactory("Ifpack2")) {
1602 }
1603
1604 // FIXME (mfh 26 Aug 2015) Provide the capability to get inner
1605 // solvers from packages other than Ifpack2.
1606 typedef typename MV::mag_type MT;
1607 RCP<inner_solver_type> innerPrec =
1608 Trilinos::Details::getLinearSolver<MV, OP, MT>("Ifpack2", innerName);
1609 TEUCHOS_TEST_FOR_EXCEPTION(
1610 innerPrec.is_null(), std::logic_error,
1611 "Ifpack2::AdditiveSchwarz::setup: Failed to create inner preconditioner "
1612 "with name \""
1613 << innerName << "\".");
1614 innerPrec->setMatrix(innerMatrix_);
1615
1616 // Extract and apply the sublist of parameters to give to the
1617 // inner solver, if there is such a sublist of parameters.
1618 std::pair<Teuchos::ParameterList, bool> result = innerPrecParams();
1619 if (result.second) {
1620 // FIXME (mfh 26 Aug 2015) We don't really want to use yet
1621 // another deep copy of the ParameterList here.
1622 innerPrec->setParameters(rcp(new ParameterList(result.first)));
1623 }
1624 Inverse_ = innerPrec; // "Commit" the inner solver.
1625 } else if (Inverse_->getMatrix().getRawPtr() != innerMatrix_.getRawPtr()) {
1626 // The new inner matrix is different from the inner
1627 // preconditioner's current matrix, so give the inner
1628 // preconditioner the new inner matrix.
1629 Inverse_->setMatrix(innerMatrix_);
1630 }
1631 TEUCHOS_TEST_FOR_EXCEPTION(
1632 Inverse_.is_null(), std::logic_error,
1633 "Ifpack2::AdditiveSchwarz::"
1634 "setup: Inverse_ is null right after we were supposed to have created it."
1635 " Please report this bug to the Ifpack2 developers.");
1636
1637 // We don't have to call setInnerPreconditioner() here, because we
1638 // had the inner matrix (innerMatrix_) before creation of the inner
1639 // preconditioner. Calling setInnerPreconditioner here would be
1640 // legal, but it would require an unnecessary reset of the inner
1641 // preconditioner (i.e., calling initialize() and compute() again).
1642}
1643
1644template <class MatrixType, class LocalInverseType>
1649 node_type>>& innerPrec) {
1650 if (!innerPrec.is_null()) {
1651 // Make sure that the new inner solver knows how to have its matrix changed.
1652 typedef Details::CanChangeMatrix<row_matrix_type> can_change_type;
1653 can_change_type* innerSolver = dynamic_cast<can_change_type*>(&*innerPrec);
1654 TEUCHOS_TEST_FOR_EXCEPTION(
1655 innerSolver == NULL, std::invalid_argument,
1656 "Ifpack2::AdditiveSchwarz::"
1657 "setInnerPreconditioner: The input preconditioner does not implement the "
1658 "setMatrix() feature. Only input preconditioners that inherit from "
1659 "Ifpack2::Details::CanChangeMatrix implement this feature.");
1660
1661 // If users provide an inner solver, we assume that
1662 // AdditiveSchwarz's current inner solver parameters no longer
1663 // apply. (In fact, we will remove those parameters from
1664 // AdditiveSchwarz's current list below.) Thus, we do /not/ apply
1665 // the current sublist of inner solver parameters to the input
1666 // inner solver.
1667
1668 // mfh 03 Jan 2014: Thanks to Paul Tsuji for pointing out that
1669 // it's perfectly legal for innerMatrix_ to be null here. This
1670 // can happen if initialize() has not been called yet. For
1671 // example, when Ifpack2::Factory creates an AdditiveSchwarz
1672 // instance, it calls setInnerPreconditioner() without first
1673 // calling initialize().
1674
1675 // Give the local matrix to the new inner solver.
1676 if (auto asf = Teuchos::rcp_dynamic_cast<Details::AdditiveSchwarzFilter<MatrixType>>(innerMatrix_))
1677 innerSolver->setMatrix(asf->getFilteredMatrix());
1678 else
1679 innerSolver->setMatrix(innerMatrix_);
1680
1681 // If the user previously specified a parameter for the inner
1682 // preconditioner's type, then clear out that parameter and its
1683 // associated sublist. Replace the inner preconditioner's type with
1684 // "CUSTOM", to make it obvious that AdditiveSchwarz's ParameterList
1685 // does not necessarily describe the current inner preconditioner.
1686 // We have to remove all allowed aliases of "inner preconditioner
1687 // name" before we may set it to "CUSTOM". Users may also set this
1688 // parameter to "CUSTOM" themselves, but this is not required.
1689 removeInnerPrecName();
1690 removeInnerPrecParams();
1691 List_.set("inner preconditioner name", "CUSTOM");
1692
1693 // Bring the new inner solver's current status (initialized or
1694 // computed) in line with AdditiveSchwarz's current status.
1695 if (isInitialized()) {
1696 innerPrec->initialize();
1697 }
1698 if (isComputed()) {
1699 innerPrec->compute();
1700 }
1701 }
1702
1703 // If the new inner solver is null, we don't change the initialized
1704 // or computed status of AdditiveSchwarz. That way, AdditiveSchwarz
1705 // won't have to recompute innerMatrix_ if the inner solver changes.
1706 // This does introduce a new error condition in compute() and
1707 // apply(), but that's OK.
1708
1709 // Set the new inner solver.
1712 inner_solver_impl_type;
1713 Inverse_ = Teuchos::rcp(new inner_solver_impl_type(innerPrec, "CUSTOM"));
1714}
1715
1716template <class MatrixType, class LocalInverseType>
1718 setMatrix(const Teuchos::RCP<const row_matrix_type>& A) {
1719 // Don't set the matrix unless it is different from the current one.
1720 if (A.getRawPtr() != Matrix_.getRawPtr()) {
1721 IsInitialized_ = false;
1722 IsComputed_ = false;
1723
1724 // Reset all the state computed in initialize() and compute().
1725 OverlappingMatrix_ = Teuchos::null;
1726 ReorderedLocalizedMatrix_ = Teuchos::null;
1727 innerMatrix_ = Teuchos::null;
1728 SingletonMatrix_ = Teuchos::null;
1729 localMap_ = Teuchos::null;
1730 overlapping_B_.reset(nullptr);
1731 overlapping_Y_.reset(nullptr);
1732 R_.reset(nullptr);
1733 C_.reset(nullptr);
1734 DistributedImporter_ = Teuchos::null;
1735
1736 Matrix_ = A;
1737 }
1738}
1739
1740template <class MatrixType, class LocalInverseType>
1742 setCoord(const Teuchos::RCP<const coord_type>& Coordinates) {
1743 // Don't set unless it is different from the current one.
1744 if (Coordinates.getRawPtr() != Coordinates_.getRawPtr()) {
1745 Coordinates_ = Coordinates;
1746 }
1747}
1748
1749} // namespace Ifpack2
1750
1751// NOTE (mfh 26 Aug 2015) There's no need to instantiate for CrsMatrix
1752// too. All Ifpack2 preconditioners can and should do dynamic casts
1753// internally, if they need a type more specific than RowMatrix.
1754#define IFPACK2_ADDITIVESCHWARZ_INSTANT(S, LO, GO, N) \
1755 template class Ifpack2::AdditiveSchwarz<Tpetra::RowMatrix<S, LO, GO, N>>;
1756
1757#endif // IFPACK2_ADDITIVESCHWARZ_DECL_HPP
Declaration of Ifpack2::AdditiveSchwarz, which implements additive Schwarz preconditioning with an ar...
void registerLinearSolverFactory()
Register Ifpack2's LinearSolverFactory with the central repository, for all enabled combinations of t...
Definition Ifpack2_Details_registerLinearSolverFactory.cpp:33
Declaration of Ifpack2::Details::Behavior, a class that describes Ifpack2's run-time behavior.
Declaration of interface for preconditioners that can change their matrix after construction.
Additive Schwarz domain decomposition for Tpetra sparse matrices.
Definition Ifpack2_AdditiveSchwarz_decl.hpp:260
typename MatrixType::local_ordinal_type local_ordinal_type
The type of local indices in the input MatrixType.
Definition Ifpack2_AdditiveSchwarz_decl.hpp:283
std::string description() const
Return a simple one-line description of this object.
Definition Ifpack2_AdditiveSchwarz_def.hpp:1180
virtual bool isInitialized() const
Returns true if the preconditioner has been successfully initialized, false otherwise.
Definition Ifpack2_AdditiveSchwarz_def.hpp:1069
void setCoord(const Teuchos::RCP< const coord_type > &Coordinates)
Set the matrix rows' coordinates.
Definition Ifpack2_AdditiveSchwarz_def.hpp:1742
virtual int getOverlapLevel() const
Returns the level of overlap.
Definition Ifpack2_AdditiveSchwarz_def.hpp:1349
Teuchos::RCP< const Teuchos::ParameterList > getValidParameters() const
Get a list of the preconditioner's default parameters.
Definition Ifpack2_AdditiveSchwarz_def.hpp:904
typename MatrixType::global_ordinal_type global_ordinal_type
The type of global indices in the input MatrixType.
Definition Ifpack2_AdditiveSchwarz_decl.hpp:286
virtual int getNumCompute() const
Returns the number of calls to compute().
Definition Ifpack2_AdditiveSchwarz_def.hpp:1155
Teuchos::RCP< const coord_type > getCoord() const
Get the coordinates associated with the input matrix's rows.
Definition Ifpack2_AdditiveSchwarz_def.hpp:289
virtual int getNumApply() const
Returns the number of calls to apply().
Definition Ifpack2_AdditiveSchwarz_def.hpp:1160
virtual double getComputeTime() const
Returns the time spent in compute().
Definition Ifpack2_AdditiveSchwarz_def.hpp:1170
virtual double getApplyTime() const
Returns the time spent in apply().
Definition Ifpack2_AdditiveSchwarz_def.hpp:1175
virtual void setMatrix(const Teuchos::RCP< const row_matrix_type > &A)
Change the matrix to be preconditioned.
Definition Ifpack2_AdditiveSchwarz_def.hpp:1718
typename MatrixType::node_type node_type
The Node type used by the input MatrixType.
Definition Ifpack2_AdditiveSchwarz_decl.hpp:289
virtual void initialize()
Computes all (graph-related) data necessary to initialize the preconditioner.
Definition Ifpack2_AdditiveSchwarz_def.hpp:948
void setParameterList(const Teuchos::RCP< Teuchos::ParameterList > &plist)
Set the preconditioner's parameters.
Definition Ifpack2_AdditiveSchwarz_def.hpp:713
virtual void setInnerPreconditioner(const Teuchos::RCP< Preconditioner< scalar_type, local_ordinal_type, global_ordinal_type, node_type > > &innerPrec)
Set the inner preconditioner.
Definition Ifpack2_AdditiveSchwarz_def.hpp:1646
virtual double getInitializeTime() const
Returns the time spent in initialize().
Definition Ifpack2_AdditiveSchwarz_def.hpp:1165
virtual Teuchos::RCP< const Tpetra::Map< local_ordinal_type, global_ordinal_type, node_type > > getRangeMap() const
The range Map of this operator.
Definition Ifpack2_AdditiveSchwarz_def.hpp:273
virtual Teuchos::RCP< const Tpetra::Map< local_ordinal_type, global_ordinal_type, node_type > > getDomainMap() const
The domain Map of this operator.
Definition Ifpack2_AdditiveSchwarz_def.hpp:261
virtual void compute()
Computes all (coefficient) data necessary to apply the preconditioner.
Definition Ifpack2_AdditiveSchwarz_def.hpp:1074
Tpetra::MultiVector< magnitude_type, local_ordinal_type, global_ordinal_type, node_type > coord_type
The Tpetra::MultiVector specialization used for containing coordinates.
Definition Ifpack2_AdditiveSchwarz_decl.hpp:308
virtual std::ostream & print(std::ostream &os) const
Prints basic information on iostream. This function is used by operator<<.
Definition Ifpack2_AdditiveSchwarz_def.hpp:1341
typename MatrixType::scalar_type scalar_type
The type of the entries of the input MatrixType.
Definition Ifpack2_AdditiveSchwarz_decl.hpp:280
void describe(Teuchos::FancyOStream &out, const Teuchos::EVerbosityLevel verbLevel=Teuchos::Describable::verbLevel_default) const
Print the object with some verbosity level to an FancyOStream object.
Definition Ifpack2_AdditiveSchwarz_def.hpp:1233
virtual void setParameters(const Teuchos::ParameterList &plist)
Set the preconditioner's parameters.
Definition Ifpack2_AdditiveSchwarz_def.hpp:703
virtual Teuchos::RCP< const row_matrix_type > getMatrix() const
The input matrix.
Definition Ifpack2_AdditiveSchwarz_def.hpp:284
virtual 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, putting the result in Y.
Definition Ifpack2_AdditiveSchwarz_def.hpp:320
virtual bool isComputed() const
Returns true if the preconditioner has been successfully computed, false otherwise.
Definition Ifpack2_AdditiveSchwarz_def.hpp:1145
virtual int getNumInitialize() const
Returns the number of calls to initialize().
Definition Ifpack2_AdditiveSchwarz_def.hpp:1150
AdditiveSchwarz(const Teuchos::RCP< const row_matrix_type > &A)
Constructor that takes a matrix.
Definition Ifpack2_AdditiveSchwarz_def.hpp:241
static bool writeAdditiveSchwarzLocalMatrix()
Whether to write the AdditiveSchwarz local matrix.
Definition Ifpack2_Details_Behavior.cpp:40
static bool debug()
Whether Ifpack2 is in debug mode.
Definition Ifpack2_Details_Behavior.cpp:31
Ifpack2's implementation of Trilinos::Details::LinearSolver interface.
Definition Ifpack2_Details_LinearSolver_decl.hpp:75
Sparse matrix (Tpetra::RowMatrix subclass) with ghost rows.
Definition Ifpack2_OverlappingRowMatrix_decl.hpp:25
Interface for all Ifpack2 preconditioners.
Definition Ifpack2_Preconditioner.hpp:74
void registerLinearSolverFactory()
Ifpack2 implementation details.
Preconditioners and smoothers for Tpetra sparse matrices.
Definition Ifpack2_AdditiveSchwarz_decl.hpp:40
void getValidParameters(Teuchos::ParameterList &params)
Fills a list which contains all the parameters possibly used by Ifpack2.
Definition Ifpack2_Parameters.cpp:18