Debian Codegraph @

packages/muelu/research/regionMG/src/SolveRegionHierarchy_def.hpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // MueLu: A package for multigrid based preconditioning
4 //
5 // Copyright 2012 NTESS and the MueLu contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 #ifndef MUELU_SOLVEREGIONHIERARCHY_DEF_HPP
11 #define MUELU_SOLVEREGIONHIERARCHY_DEF_HPP
12
13 #include "SetupRegionHierarchy_def.hpp"
14
15 using Teuchos::Array;
16 using Teuchos::RCP;
17 using Teuchos::rcp;
18
19 //! Recursive multigrid cycle (V or W) in region fashion
20 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
21 void MgCycle(const int levelID, ///< ID of current level
22 const std::string cycleType,
23 RCP<MueLu::Hierarchy<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& regHierarchy,
24 RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& fineRegX, ///< solution
25 RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>> fineRegB, ///< right hand side
26 Array<RCP<Teuchos::ParameterList>> smootherParams, ///< region smoother parameter list
27 bool& zeroInitGuess,
28 RCP<ParameterList> coarseSolverData = Teuchos::null,
29 RCP<ParameterList> hierarchyData = Teuchos::null) {
30 #include "MueLu_UseShortNames.hpp"
31 using Teuchos::TimeMonitor;
32 const Scalar SC_ZERO = Teuchos::ScalarTraits<Scalar>::zero();
33 const Scalar SC_ONE = Teuchos::ScalarTraits<Scalar>::one();
34
35 RCP<Level> level = regHierarchy->GetLevel(levelID);
36 RCP<Matrix> regMatrix = level->Get<RCP<Matrix>>("A", MueLu::NoFactory::get());
37 RCP<const Map> regRowMap = regMatrix->getRowMap();
38 RCP<Xpetra::Import<LocalOrdinal, GlobalOrdinal, Node>> regRowImporter = level->Get<RCP<Xpetra::Import<LocalOrdinal, GlobalOrdinal, Node>>>("rowImport");
39 RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>> regInterfaceScalings = level->Get<RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>>>("regInterfaceScalings");
40
41 // Setup recursive cycling to represent either V- or W-cycles
42 int cycleCount = 1;
43 if (cycleType == "W" && levelID > 0) { // W cycle and not on finest level.
44 const std::string coarseSolverType = coarseSolverData->get<std::string>("coarse solver type");
45 if (coarseSolverType == "direct" && levelID == regHierarchy->GetNumLevels() - 2) // Only call coarse level solve once if direct solve
46 cycleCount = 1;
47 else
48 cycleCount = 2;
49 }
50
51 if (levelID < regHierarchy->GetNumLevels() - 1) // fine or intermediate levels
52 {
53 // extract data from hierarchy parameterlist
54 std::string levelName("level" + std::to_string(levelID));
55 ParameterList levelList;
56 bool useCachedVectors = false;
57 // if(Teuchos::nonnull(hierarchyData) && hierarchyData->isSublist(levelName)) {
58 // levelList = hierarchyData->sublist(levelName);
59 // if(levelList.isParameter("residual") && levelList.isParameter("solution")) {
60 // useCachedVectors = true;
61 // }
62 // }
63
64 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("MgCycle: 1 - pre-smoother")));
65
66 // pre-smoothing
67 smootherApply(smootherParams[levelID], fineRegX, fineRegB, regMatrix,
68 regRowMap, regRowImporter, zeroInitGuess);
69
70 tm = Teuchos::null;
71 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("MgCycle: 2 - compute residual")));
72
73 RCP<Vector> regRes;
74 if (useCachedVectors) {
75 regRes = levelList.get<RCP<Vector>>("residual");
76 } else {
77 regRes = VectorFactory::Build(regRowMap, true);
78 }
79 computeResidual(regRes, fineRegX, fineRegB, regMatrix, *smootherParams[levelID]);
80
81 tm = Teuchos::null;
82 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("MgCycle: 3 - scale interface")));
83
84 scaleInterfaceDOFs(regRes, regInterfaceScalings, true);
85
86 tm = Teuchos::null;
87 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("MgCycle: 4 - create coarse vectors")));
88
89 // Transfer to coarse level
90 RCP<Vector> coarseRegX;
91 RCP<Vector> coarseRegB;
92
93 {
94 RCP<Level> levelCoarse = regHierarchy->GetLevel(levelID + 1);
95 RCP<Matrix> regProlongCoarse = levelCoarse->Get<RCP<Matrix>>("P", MueLu::NoFactory::get());
96 RCP<const Xpetra::Map<LocalOrdinal, GlobalOrdinal, Node>> regRowMapCoarse = regProlongCoarse->getColMap();
97 // Get pre-communicated communication patterns for the fast MatVec
98 const ArrayRCP<LocalOrdinal> regionInterfaceLIDs = smootherParams[levelID + 1]->get<ArrayRCP<LO>>("Fast MatVec: interface LIDs");
99 const RCP<Import> regionInterfaceImporter = smootherParams[levelID + 1]->get<RCP<Import>>("Fast MatVec: interface importer");
100
101 coarseRegX = VectorFactory::Build(regRowMapCoarse, true);
102 coarseRegB = VectorFactory::Build(regRowMapCoarse, true);
103
104 regProlongCoarse->apply(*regRes, *coarseRegB, Teuchos::TRANS, SC_ONE, SC_ZERO, true, regionInterfaceImporter, regionInterfaceLIDs);
105 // TEUCHOS_ASSERT(regProlong[l+1][j]->getRangeMap()->isSameAs(*regRes[j]->getMap()));
106 // TEUCHOS_ASSERT(regProlong[l+1][j]->getDomainMap()->isSameAs(*coarseRegB[j]->getMap()));
107 }
108
109 tm = Teuchos::null;
110 bool coarseZeroInitGuess = true;
111
112 for (int cycle = 0; cycle < cycleCount; cycle++) {
113 // Call V-cycle recursively
114 MgCycle(levelID + 1, cycleType, regHierarchy,
115 coarseRegX, coarseRegB,
116 smootherParams, coarseZeroInitGuess, coarseSolverData, hierarchyData);
117
118 } // cycleCount
119
120 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("MgCycle: 6 - transfer coarse to fine")));
121
122 // Transfer coarse level correction to fine level
123 RCP<Vector> regCorrection;
124 {
125 RCP<Level> levelCoarse = regHierarchy->GetLevel(levelID + 1);
126 RCP<Matrix> regProlongCoarse = levelCoarse->Get<RCP<Matrix>>("P", MueLu::NoFactory::get());
127 // Get pre-communicated communication patterns for the fast MatVec
128 const ArrayRCP<LocalOrdinal> regionInterfaceLIDs = smootherParams[levelID]->get<ArrayRCP<LO>>("Fast MatVec: interface LIDs");
129 const RCP<Import> regionInterfaceImporter = smootherParams[levelID]->get<RCP<Import>>("Fast MatVec: interface importer");
130
131 regCorrection = VectorFactory::Build(regRowMap, true);
132 regProlongCoarse->apply(*coarseRegX, *regCorrection, Teuchos::NO_TRANS, SC_ONE, SC_ZERO, false, regionInterfaceImporter, regionInterfaceLIDs);
133 // TEUCHOS_ASSERT(regProlong[l+1][j]->getDomainMap()->isSameAs(*coarseRegX[j]->getMap()));
134 // TEUCHOS_ASSERT(regProlong[l+1][j]->getRangeMap()->isSameAs(*regCorrection[j]->getMap()));
135 }
136
137 tm = Teuchos::null;
138 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("MgCycle: 7 - add coarse grid correction")));
139
140 // apply coarse grid correction
141 fineRegX->update(SC_ONE, *regCorrection, SC_ONE);
142 if (coarseZeroInitGuess) zeroInitGuess = true;
143
144 tm = Teuchos::null;
145 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("MgCycle: 8 - post-smoother")));
146
147 // post-smoothing
148 smootherApply(smootherParams[levelID], fineRegX, fineRegB, regMatrix,
149 regRowMap, regRowImporter, zeroInitGuess);
150
151 tm = Teuchos::null;
152
153 } else {
154 // Coarsest grid solve
155
156 RCP<Teuchos::FancyOStream> fos = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
157 fos->setOutputToRootOnly(0);
158
159 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("MgCycle: * - coarsest grid solve")));
160
161 // std::cout << "Applying coarse colver" << std::endl;
162
163 const std::string coarseSolverType = coarseSolverData->get<std::string>("coarse solver type");
164 if (coarseSolverType == "smoother") {
165 smootherApply(smootherParams[levelID], fineRegX, fineRegB, regMatrix,
166 regRowMap, regRowImporter, zeroInitGuess);
167 } else {
168 zeroInitGuess = false;
169 // First get the Xpetra vectors from region to composite format
170 RCP<const Map> coarseRowMap = coarseSolverData->get<RCP<const Map>>("compCoarseRowMap");
171 RCP<Vector> compX = VectorFactory::Build(coarseRowMap, true);
172 RCP<Vector> compRhs = VectorFactory::Build(coarseRowMap, true);
173 {
174 RCP<Vector> inverseInterfaceScaling = VectorFactory::Build(regInterfaceScalings->getMap());
175 inverseInterfaceScaling->reciprocal(*regInterfaceScalings);
176 fineRegB->elementWiseMultiply(SC_ONE, *fineRegB, *inverseInterfaceScaling, SC_ZERO);
177
178 regionalToComposite(fineRegB, compRhs, regRowImporter);
179 }
180
181 if (coarseSolverType == "direct") {
182 #if defined(HAVE_MUELU_AMESOS2)
183
184 using DirectCoarseSolver = Amesos2::Solver<Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>, Tpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node>>;
185 RCP<DirectCoarseSolver> coarseSolver = coarseSolverData->get<RCP<DirectCoarseSolver>>("direct solver object");
186
187 TEUCHOS_TEST_FOR_EXCEPT_MSG(coarseRowMap->lib() != Xpetra::UseTpetra,
188 "Coarse solver requires Tpetra/Amesos2 stack.");
189 TEUCHOS_ASSERT(!coarseSolver.is_null());
190
191 // using Utilities = MueLu::Utilities<Scalar, LocalOrdinal, GlobalOrdinal, Node>;
192
193 // From here on we switch to Tpetra for simplicity
194 // we could also implement a similar Epetra branch
195 using Tpetra_Vector = Tpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>;
196
197 // *fos << "Attempting to use Amesos2 to solve the coarse grid problem" << std::endl;
198 RCP<Tpetra_Vector> tX = toTpetra(compX);
199 RCP<const Tpetra_Vector> tB = toTpetra(compRhs);
200
201 /* Solve!
202 *
203 * Calling solve() on the coarseSolver should just do a triangular solve, since symbolic
204 * and numeric factorization are supposed to have happened during hierarchy setup.
205 * Here, we just check if they're done and print message if not.
206 *
207 * We don't have to change the map of tX and tB since we have configured the Amesos2 solver
208 * during its construction to work with non-continuous maps.
209 */
210 if (not coarseSolver->getStatus().symbolicFactorizationDone())
211 *fos << "Symbolic factorization should have been done during hierarchy setup, "
212 "but actually is missing. Anyway ... just do it right now."
213 << std::endl;
214 if (not coarseSolver->getStatus().numericFactorizationDone())
215 *fos << "Numeric factorization should have been done during hierarchy setup, "
216 "but actually is missing. Anyway ... just do it right now."
217 << std::endl;
218 coarseSolver->solve(tX.ptr(), tB.ptr());
219 #else
220 *fos << "+++++++++++++++++++++++++++ WARNING +++++++++++++++++++++++++\n"
221 << "+ Coarse level direct solver requires Tpetra and Amesos2. +\n"
222 << "+ Skipping the coarse level solve. +\n"
223 << "+++++++++++++++++++++++++++ WARNING +++++++++++++++++++++++++"
224 << std::endl;
225 #endif
226 } else if (coarseSolverType == "amg") // use AMG as coarse level solver
227 {
228 const bool coarseSolverRebalance = coarseSolverData->get<bool>("coarse solver rebalance");
229
230 // Extract the hierarchy from the coarseSolverData
231 RCP<Hierarchy> amgHierarchy = coarseSolverData->get<RCP<Hierarchy>>("amg hierarchy object");
232
233 // Run a single V-cycle
234 if (coarseSolverRebalance == false) {
235 amgHierarchy->Iterate(*compRhs, *compX, 1, true);
236
237 } else {
238 #if defined(HAVE_MUELU_ZOLTAN2) && defined(HAVE_MPI)
239 RCP<const Import> rebalanceImporter = coarseSolverData->get<RCP<const Import>>("rebalanceImporter");
240
241 // TODO: These vectors could be cached to improve performance
242 RCP<Vector> rebalancedRhs = VectorFactory::Build(rebalanceImporter->getTargetMap());
243 RCP<Vector> rebalancedX = VectorFactory::Build(rebalanceImporter->getTargetMap(), true);
244 rebalancedRhs->doImport(*compRhs, *rebalanceImporter, Xpetra::INSERT);
245
246 rebalancedRhs->replaceMap(rebalancedRhs->getMap()->removeEmptyProcesses());
247 rebalancedX->replaceMap(rebalancedX->getMap()->removeEmptyProcesses());
248
249 if (!amgHierarchy.is_null()) {
250 amgHierarchy->Iterate(*rebalancedRhs, *rebalancedX, 1, true);
251 }
252
253 rebalancedX->replaceMap(rebalanceImporter->getTargetMap());
254 compX->doExport(*rebalancedX, *rebalanceImporter, Xpetra::INSERT);
255 #else
256 amgHierarchy->Iterate(*compRhs, *compX, 1, true);
257 #endif
258 }
259 } else {
260 TEUCHOS_TEST_FOR_EXCEPT_MSG(false, "Unknown coarse solver type.");
261 }
262
263 // Transform back to region format
264 RCP<Vector> quasiRegX;
265 compositeToRegional(compX, quasiRegX, fineRegX,
266 regRowMap,
267 regRowImporter);
268
269 tm = Teuchos::null;
270 }
271 }
272
273 return;
274 } // MgCycle
275
276 //! Adapter that uses composite vectors and a region hierarchy
277 // and performs a region MG cycle on them.
278 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
279 void RegionMgCycleAdapter(const std::string cycleType,
280 RCP<MueLu::Hierarchy<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& regHierarchy,
281 RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& X, ///< solution
282 RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>> B, ///< right hand side
283 Array<RCP<Teuchos::ParameterList>> smootherParams, ///< region smoother parameter list
284 bool& zeroInitGuess,
285 RCP<ParameterList> coarseSolverData = Teuchos::null,
286 RCP<ParameterList> hierarchyData = Teuchos::null) {
287 using LO = LocalOrdinal;
288 using GO = GlobalOrdinal;
289 using NO = Node;
290 using SC = Scalar;
291
292 using Level = MueLu::Level;
293 using Map = Xpetra::Map<LO, GO, NO>;
294 using Import = Xpetra::Import<LO, GO, NO>;
295 using Matrix = Xpetra::Matrix<SC, LO, GO, NO>;
296 using Vector = Xpetra::Vector<SC, LO, GO, NO>;
297 using VectorFactory = Xpetra::VectorFactory<SC, LO, GO, NO>;
298
299 // Extract some info from the hierarchy
300 // to convert vectors from composite to regional and back
301 RCP<Level> level0 = regHierarchy->GetLevel(0);
302 RCP<Import> rowImport = level0->Get<RCP<Import>>("rowImport");
303 RCP<Vector> regInterfaceScalings = level0->Get<RCP<Vector>>("regInterfaceScalings");
304 RCP<Matrix> regMat = level0->Get<RCP<Matrix>>("A");
305 RCP<const Map> revisedRowMap = regMat->getRowMap();
306
307 // Compute region vectors for B and X
308 RCP<Vector> quasiRegB;
309 RCP<Vector> regB;
310 compositeToRegional(B, quasiRegB, regB,
311 revisedRowMap, rowImport);
312
313 RCP<Vector> quasiRegX;
314 RCP<Vector> regX;
315 compositeToRegional(X, quasiRegX, regX,
316 revisedRowMap, rowImport);
317
318 MgCycle(0, cycleType, regHierarchy,
319 regX, regB,
320 smootherParams, zeroInitGuess, coarseSolverData, hierarchyData);
321
322 // Bring solution back to composite format
323 scaleInterfaceDOFs(regX, regInterfaceScalings, true);
324 regionalToComposite(regX, X, rowImport);
325 } // RegionMgCycleAdapter
326
327 // Solve via Richardson iteration with region MG preconditioning, hand in matrix in region format
328 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
329 void solveRegionProblemRichardson(const double tol, const bool scaleResidualHist, const int maxIts,
330 const std::string cycleType, const std::string convergenceLog,
331 RCP<Teuchos::ParameterList>& coarseSolverData,
332 Array<RCP<Teuchos::ParameterList>>& smootherParams,
333 RCP<Teuchos::ParameterList> hierarchyData,
334 RCP<MueLu::Hierarchy<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& regHierarchy,
335 RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& X,
336 RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& B) {
337 using LO = LocalOrdinal;
338 using GO = GlobalOrdinal;
339 using NO = Node;
340 using SC = Scalar;
341
342 using Map = Xpetra::Map<LO, GO, NO>;
343 using Import = Xpetra::Import<LO, GO, NO>;
344 using Matrix = Xpetra::Matrix<SC, LO, GO, NO>;
345 using Vector = Xpetra::Vector<SC, LO, GO, NO>;
346 using VectorFactory = Xpetra::VectorFactory<SC, LO, GO, NO>;
347
348 using Level = MueLu::Level;
349
350 using STS = Teuchos::ScalarTraits<Scalar>;
351 using magnitude_type = typename STS::magnitudeType;
352 const Scalar SC_zero = STS::zero();
353 const Scalar SC_one = STS::one();
354
355 // we start by extracting some basic data from the hierarchy
356 RCP<Level> level0 = regHierarchy->GetLevel(0);
357 RCP<Matrix> regMat = level0->Get<RCP<Matrix>>("A");
358 RCP<const Map> revisedRowMap = regMat->getRowMap();
359 RCP<Import> rowImport = level0->Get<RCP<Import>>("rowImport");
360 RCP<const Map> dofMap = X->getMap();
361 const int myRank = dofMap->getComm()->getRank();
362
363 // Instead of checking each time for rank, create a rank 0 stream
364 RCP<Teuchos::FancyOStream> fancy = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
365 Teuchos::FancyOStream& out = *fancy;
366 out.setOutputToRootOnly(0);
367
368 // Prepare output of residual norm to file
369 RCP<std::ofstream> log;
370 if (myRank == 0) {
371 log = rcp(new std::ofstream(convergenceLog.c_str()));
372 (*log) << "# num procs = " << dofMap->getComm()->getSize() << "\n"
373 << "# iteration | res-norm (scaled=" << scaleResidualHist << ")\n"
374 << "#\n";
375 *log << std::setprecision(16) << std::scientific;
376 }
377
378 // Print type of residual norm to the screen
379 out << "Using region solver" << std::endl;
380 if (scaleResidualHist)
381 out << "Using scaled residual norm." << std::endl;
382 else
383 out << "Using unscaled residual norm." << std::endl;
384
385 TEUCHOS_TEST_FOR_EXCEPT_MSG(!(regHierarchy->GetNumLevels() > 0), "We require numLevel > 0. Probably, numLevel has not been set, yet.");
386
387 // We first use the non-level container variables to setup the fine grid problem.
388 // This is ok since the initial setup just mimics the application and the outer
389 // Krylov method.
390 //
391 // We switch to using the level container variables as soon as we enter the
392 // recursive part of the algorithm.
393 //
394
395 // Composite residual vector
396 RCP<Vector> compRes = VectorFactory::Build(dofMap, true);
397 compRes = VectorFactory::Build(dofMap, true);
398
399 // transform composite vectors to regional layout
400 Teuchos::RCP<Vector> quasiRegX;
401 Teuchos::RCP<Vector> regX;
402 compositeToRegional(X, quasiRegX, regX,
403 revisedRowMap, rowImport);
404
405 RCP<Vector> quasiRegB;
406 RCP<Vector> regB;
407 compositeToRegional(B, quasiRegB, regB,
408 revisedRowMap, rowImport);
409
410 RCP<Vector> regRes;
411 regRes = VectorFactory::Build(revisedRowMap, true);
412
413 Teuchos::RCP<Vector> regCorrect;
414 regCorrect = VectorFactory::Build(revisedRowMap, true);
415
416 /////////////////////////////////////////////////////////////////////////
417 // SWITCH TO RECURSIVE STYLE --> USE LEVEL CONTAINER VARIABLES
418 /////////////////////////////////////////////////////////////////////////
419
420 // Richardson iterations
421 magnitude_type normResIni = Teuchos::ScalarTraits<magnitude_type>::zero();
422 const int old_precision = std::cout.precision();
423 std::cout << std::setprecision(8) << std::scientific;
424 int cycle = 0;
425
426 // Get Stuff out of Hierarchy
427 RCP<Level> level = regHierarchy->GetLevel(0);
428 RCP<Vector> regInterfaceScalings = level->Get<RCP<Vector>>("regInterfaceScalings");
429 bool zeroInitGuess = true;
430 for (cycle = 0; cycle < maxIts; ++cycle) {
431 regCorrect->putScalar(SC_zero);
432 // check for convergence
433 {
434 ////////////////////////////////////////////////////////////////////////
435 // SWITCH BACK TO NON-LEVEL VARIABLES
436 ////////////////////////////////////////////////////////////////////////
437 computeResidual(regRes, regX, regB, regMat, *smootherParams[0]);
438 scaleInterfaceDOFs(regRes, regInterfaceScalings, true);
439 regionalToComposite(regRes, compRes, rowImport);
440
441 typename Teuchos::ScalarTraits<Scalar>::magnitudeType normRes = compRes->norm2();
442 if (cycle == 0) {
443 normResIni = normRes;
444 } // out << "NormResIni = " << normResIni << std::endl; }
445 if (scaleResidualHist) {
446 normRes /= normResIni;
447 }
448
449 // Output current residual norm to screen (on proc 0 only)
450 out << cycle << "\t" << normRes << std::endl;
451 if (myRank == 0)
452 (*log) << cycle << "\t" << normRes << "\n";
453
454 if (normRes < tol)
455 break;
456 }
457
458 /////////////////////////////////////////////////////////////////////////
459 // SWITCH TO RECURSIVE STYLE --> USE LEVEL CONTAINER VARIABLES
460 /////////////////////////////////////////////////////////////////////////
461
462 scaleInterfaceDOFs(regRes, regInterfaceScalings, false);
463
464 // std::cout << "regB->norm2() " << regRes->norm2() << std::endl;
465 MgCycle(0, cycleType, regHierarchy,
466 regCorrect, regRes,
467 smootherParams, zeroInitGuess, coarseSolverData, hierarchyData);
468
469 // std::cout << "regX->norm2() " << regCorrect->norm2() << std::endl;
470
471 regX->update(SC_one, *regCorrect, SC_one);
472 }
473 out << "Number of iterations performed for this solve: " << cycle << std::endl;
474
475 std::cout << std::setprecision(old_precision);
476 std::cout.unsetf(std::ios::fixed | std::ios::scientific);
477 } // solveRegionProblemRichardson
478
479 // Solve via Conjugate Gradient with region MG preconditioning, hand in matrix in composite format
480 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
481 void solveCompositeProblemPCG(const double tol, const bool scaleResidualHist, const int maxIts,
482 const std::string cycleType, const std::string convergenceLog,
483 RCP<Teuchos::ParameterList>& coarseSolverData,
484 Array<RCP<Teuchos::ParameterList>>& smootherParams,
485 RCP<Teuchos::ParameterList> hierarchyData,
486 RCP<MueLu::Hierarchy<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& regHierarchy,
487 RCP<Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& A,
488 RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& X,
489 RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& B) {
490 using LO = LocalOrdinal;
491 using GO = GlobalOrdinal;
492 using NO = Node;
493 using SC = Scalar;
494
495 using Map = Xpetra::Map<LO, GO, NO>;
496 using Import = Xpetra::Import<LO, GO, NO>;
497 using Matrix = Xpetra::Matrix<SC, LO, GO, NO>;
498 using Vector = Xpetra::Vector<SC, LO, GO, NO>;
499 using VectorFactory = Xpetra::VectorFactory<SC, LO, GO, NO>;
500
501 using Level = MueLu::Level;
502
503 using STS = Teuchos::ScalarTraits<Scalar>;
504 using magnitude_type = typename STS::magnitudeType;
505 const Scalar SC_zero = STS::zero();
506 const Scalar SC_one = STS::one();
507
508 // we start by extracting some basic data from the hierarchy
509 RCP<Level> level0 = regHierarchy->GetLevel(0);
510 RCP<const Map> dofMap = X->getMap();
511 const int myRank = dofMap->getComm()->getRank();
512
513 // Instead of checking each time for rank, create a rank 0 stream
514 RCP<Teuchos::FancyOStream> fancy = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
515 Teuchos::FancyOStream& out = *fancy;
516 out.setOutputToRootOnly(0);
517
518 // Prepare output of residual norm to file
519 RCP<std::ofstream> log;
520 if (myRank == 0) {
521 log = rcp(new std::ofstream(convergenceLog.c_str()));
522 (*log) << "# num procs = " << dofMap->getComm()->getSize() << "\n"
523 << "# iteration | res-norm (scaled=" << scaleResidualHist << ")\n"
524 << "#\n";
525 *log << std::setprecision(16) << std::scientific;
526 }
527
528 // Print type of residual norm to the screen
529 out << "Using CG solver" << std::endl;
530 if (scaleResidualHist)
531 out << "Using scaled residual norm." << std::endl;
532 else
533 out << "Using unscaled residual norm." << std::endl;
534
535 TEUCHOS_TEST_FOR_EXCEPT_MSG(!(regHierarchy->GetNumLevels() > 0), "We require numLevel > 0. Probably, numLevel has not been set, yet.");
536
537 // PCG iterations
538 const int old_precision = std::cout.precision();
539 std::cout << std::setprecision(8) << std::scientific;
540
541 // Get Stuff out of Hierarchy
542 RCP<Level> level = regHierarchy->GetLevel(0);
543 RCP<Vector> regInterfaceScalings = level->Get<RCP<Vector>>("regInterfaceScalings");
544 bool zeroInitGuess = true;
545
546 // Set variables for iterations
547 int cycle = 0;
548 RCP<Vector> Res = VectorFactory::Build(dofMap, true);
549 RCP<Vector> Z = VectorFactory::Build(dofMap, true);
550 RCP<Vector> P = VectorFactory::Build(dofMap, true);
551 RCP<Vector> AP = VectorFactory::Build(dofMap, true);
552 magnitude_type normResIni = Teuchos::ScalarTraits<magnitude_type>::zero();
553 magnitude_type normRes = Teuchos::ScalarTraits<magnitude_type>::zero();
554
555 A->apply(*X, *Res, Teuchos::NO_TRANS, -SC_one, SC_zero);
556 Res->update(SC_one, *B, SC_one);
557 normResIni = Res->norm2();
558 Z->putScalar(SC_zero);
559
560 RegionMgCycleAdapter(cycleType, regHierarchy,
561 Z, Res,
562 smootherParams, zeroInitGuess, coarseSolverData, hierarchyData);
563 P->update(SC_one, *Z, SC_zero); // deep copy values of Z into P
564
565 Scalar alpha = SC_zero, beta_old = SC_zero, beta_new = SC_zero, PAP = SC_zero;
566 for (cycle = 0; cycle < maxIts; ++cycle) {
567 A->apply(*P, *AP, Teuchos::NO_TRANS, SC_one, SC_zero);
568 PAP = P->dot(*AP);
569
570 TEUCHOS_TEST_FOR_EXCEPTION(PAP <= SC_zero, std::runtime_error,
571 "At iteration " << (cycle) << " out of " << maxIts
572 << ", P.dot(AP) = " << PAP << " <= 0. This usually means that "
573 "the matrix A is not symmetric (Hermitian) positive definite.");
574
575 beta_old = Res->dot(*Z);
576 alpha = beta_old / PAP;
577 X->update(alpha, *P, SC_one);
578 Res->update(-alpha, *AP, SC_one);
579
580 // check for convergence
581 {
582 normRes = Res->norm2();
583 if (scaleResidualHist) {
584 normRes /= normResIni;
585 }
586
587 // Output current residual norm to screen (on proc 0 only)
588 out << cycle << "\t" << normRes << std::endl;
589 if (myRank == 0)
590 (*log) << cycle << "\t" << normRes << "\n";
591
592 if (normRes < tol)
593 break;
594 }
595
596 Z->putScalar(SC_zero);
597 RegionMgCycleAdapter(cycleType, regHierarchy,
598 Z, Res,
599 smootherParams, zeroInitGuess, coarseSolverData, hierarchyData);
600
601 beta_new = Res->dot(*Z);
602 P->update(SC_one, *Z, (beta_new / beta_old));
603 beta_old = beta_new;
604 }
605 out << "Number of iterations performed for this solve: " << cycle << std::endl;
606
607 std::cout << std::setprecision(old_precision);
608 std::cout.unsetf(std::ios::fixed | std::ios::scientific);
609 } // solveCompositeProblemPCG
610
611 // Solve via Richardson iteration with region MG preconditioning, hand in matrix in composite format
612 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
613 void solveCompositeProblemRichardson(const double tol, const bool scaleResidualHist, const int maxIts,
614 const std::string cycleType, const std::string convergenceLog,
615 RCP<Teuchos::ParameterList>& coarseSolverData,
616 Array<RCP<Teuchos::ParameterList>>& smootherParams,
617 RCP<Teuchos::ParameterList> hierarchyData,
618 RCP<MueLu::Hierarchy<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& regHierarchy,
619 RCP<Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& A,
620 RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& X,
621 RCP<Xpetra::Vector<Scalar, LocalOrdinal, GlobalOrdinal, Node>>& B) {
622 using LO = LocalOrdinal;
623 using GO = GlobalOrdinal;
624 using NO = Node;
625 using SC = Scalar;
626
627 using Map = Xpetra::Map<LO, GO, NO>;
628 using Import = Xpetra::Import<LO, GO, NO>;
629 using Matrix = Xpetra::Matrix<SC, LO, GO, NO>;
630 using Vector = Xpetra::Vector<SC, LO, GO, NO>;
631 using VectorFactory = Xpetra::VectorFactory<SC, LO, GO, NO>;
632
633 using Level = MueLu::Level;
634
635 using STS = Teuchos::ScalarTraits<Scalar>;
636 using magnitude_type = typename STS::magnitudeType;
637 const Scalar SC_zero = STS::zero();
638 const Scalar SC_one = STS::one();
639
640 // we start by extracting some basic data from the hierarchy
641 RCP<Level> level0 = regHierarchy->GetLevel(0);
642 RCP<const Map> dofMap = X->getMap();
643 const int myRank = dofMap->getComm()->getRank();
644
645 // Instead of checking each time for rank, create a rank 0 stream
646 RCP<Teuchos::FancyOStream> fancy = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
647 Teuchos::FancyOStream& out = *fancy;
648 out.setOutputToRootOnly(0);
649
650 // Prepare output of residual norm to file
651 RCP<std::ofstream> log;
652 if (myRank == 0) {
653 log = rcp(new std::ofstream(convergenceLog.c_str()));
654 (*log) << "# num procs = " << dofMap->getComm()->getSize() << "\n"
655 << "# iteration | res-norm (scaled=" << scaleResidualHist << ")\n"
656 << "#\n";
657 *log << std::setprecision(16) << std::scientific;
658 }
659
660 // Print type of residual norm to the screen
661 out << "Using Richardson solver" << std::endl;
662 if (scaleResidualHist)
663 out << "Using scaled residual norm." << std::endl;
664 else
665 out << "Using unscaled residual norm." << std::endl;
666
667 TEUCHOS_TEST_FOR_EXCEPT_MSG(!(regHierarchy->GetNumLevels() > 0), "We require numLevel > 0. Probably, numLevel has not been set, yet.");
668
669 // Richardson iterations
670 const int old_precision = std::cout.precision();
671 std::cout << std::setprecision(8) << std::scientific;
672
673 // Set variables for iterations
674 int cycle = 0;
675 RCP<Vector> Correct = VectorFactory::Build(dofMap, true);
676 RCP<Vector> Res = VectorFactory::Build(dofMap, true);
677 magnitude_type normResIni = Teuchos::ScalarTraits<magnitude_type>::zero();
678 magnitude_type normRes = Teuchos::ScalarTraits<magnitude_type>::zero();
679
680 // out << "X->norm2() " << X->norm2() << std::endl;
681
682 // Get Stuff out of Hierarchy
683 RCP<Level> level = regHierarchy->GetLevel(0);
684 RCP<Vector> regInterfaceScalings = level->Get<RCP<Vector>>("regInterfaceScalings");
685 bool zeroInitGuess = true;
686 for (cycle = 0; cycle < maxIts; ++cycle) {
687 Correct->putScalar(SC_zero);
688 // check for convergence
689 {
690 A->apply(*X, *Res, Teuchos::NO_TRANS, -SC_one, SC_zero);
691 Res->update(SC_one, *B, SC_one);
692 normRes = Res->norm2();
693
694 if (cycle == 0) {
695 normResIni = normRes;
696 } // out << "NormResIni = " << normResIni << std::endl;}
697 if (scaleResidualHist) {
698 normRes /= normResIni;
699 }
700
701 // Output current residual norm to screen (on proc 0 only)
702 out << cycle << "\t" << normRes << std::endl;
703 if (myRank == 0)
704 (*log) << cycle << "\t" << normRes << "\n";
705
706 if (normRes < tol)
707 break;
708 }
709
710 RegionMgCycleAdapter(cycleType, regHierarchy,
711 Correct, Res,
712 smootherParams, zeroInitGuess, coarseSolverData, hierarchyData);
713
714 X->update(SC_one, *Correct, SC_one);
715 }
716 out << "Number of iterations performed for this solve: " << cycle << std::endl;
717
718 std::cout << std::setprecision(old_precision);
719 std::cout.unsetf(std::ios::fixed | std::ios::scientific);
720 } // solveCompositeProblemRichardson
721
722 #endif // MUELU_SOLVEREGIONHIERARCHY_DEF_HPP