Debian Codegraph @

packages/muelu/research/regionMG/test/structured/Driver_Structured_Regions.cpp

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 #include <cstdio>
11 #include <iomanip>
12 #include <iostream>
13 #include <sstream>
14 #include <unistd.h>
15
16 // Teuchos
17 #include <Teuchos_XMLParameterListHelpers.hpp>
18 #include <Teuchos_YamlParameterListHelpers.hpp>
19 #include <Teuchos_StandardCatchMacros.hpp>
20
21 // Xpetra
22 #include <Xpetra_MultiVectorFactory.hpp>
23 #include <Xpetra_ImportFactory.hpp>
24 #include <Xpetra_Operator.hpp>
25 #include <Xpetra_Map.hpp>
26 #include <Xpetra_MultiVector.hpp>
27 #include <Xpetra_IO.hpp>
28
29 // Galeri
30 #include <Galeri_XpetraParameters.hpp>
31 #include <Galeri_XpetraProblemFactory.hpp>
32 #include <Galeri_XpetraUtils.hpp>
33 #include <Galeri_XpetraMaps.hpp>
34
35 // MueLu
36 #include <MueLu.hpp>
37
38 #include <MueLu_BaseClass.hpp>
39 #ifdef HAVE_MUELU_EXPLICIT_INSTANTIATION
40 #include <MueLu_ExplicitInstantiation.hpp>
41 #endif
42 #include <MueLu_Level.hpp>
43 #include <MueLu_MutuallyExclusiveTime.hpp>
44 #include <MueLu_ParameterListInterpreter.hpp>
45 #include <MueLu_Utilities.hpp>
46
47 // Belos
48 #ifdef HAVE_MUELU_BELOS
49 #include <BelosConfigDefs.hpp>
50 #include <BelosBiCGStabSolMgr.hpp>
51 #include <BelosBlockCGSolMgr.hpp>
52 #include <BelosBlockGmresSolMgr.hpp>
53 #include <BelosLinearProblem.hpp>
54 #include <BelosPseudoBlockCGSolMgr.hpp>
55 #include <BelosXpetraAdapter.hpp> // => This header defines Belos::XpetraOp
56 #include <BelosMueLuAdapter.hpp> // => This header defines Belos::MueLuOp
57 #include <BelosTpetraAdapter.hpp> // => This header defines Belos::TpetraOp
58 #endif
59
60 #ifdef HAVE_MUELU_CUDA
61 #include "cuda_profiler_api.h"
62 #endif
63
64 // MueLu and Xpetra Tpetra stack
65 #include <MueLu_TpetraOperator.hpp>
66 #include <MueLu_CreateTpetraPreconditioner.hpp>
67 #include <Xpetra_TpetraOperator.hpp>
68 #include "Xpetra_TpetraMultiVector.hpp"
69 #include <KokkosBlas1_abs.hpp>
70 #include <Tpetra_leftAndOrRightScaleCrsMatrix.hpp>
71 #include <Tpetra_computeRowAndColumnOneNorms.hpp>
72
73 // Xpetra Epetra stack
74 #ifdef HAVE_MUELU_EPETRA
75 #include "Xpetra_EpetraMultiVector.hpp"
76 #endif
77
78 #include <MueLu_CreateXpetraPreconditioner.hpp>
79
80 #if defined(HAVE_MUELU_AMESOS2)
81 #include <Amesos2_config.h>
82 #include <Amesos2.hpp>
83 #endif
84
85 // Region MG headers
86 #include "SetupRegionUtilities.hpp"
87 #include "SetupRegionVector_def.hpp"
88 #include "SetupRegionMatrix_def.hpp"
89 #include "SetupRegionHierarchy_def.hpp"
90 #include "SolveRegionHierarchy_def.hpp"
91
92 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
93 int main_(Teuchos::CommandLineProcessor &clp, Xpetra::UnderlyingLib &lib, int argc, char *argv[]) {
94 #include <MueLu_UseShortNames.hpp>
95 using Teuchos::ArrayRCP;
96 using Teuchos::ParameterList;
97 using Teuchos::RCP;
98 using Teuchos::rcp;
99 using Teuchos::TimeMonitor;
100
101 // =========================================================================
102 // MPI initialization using Teuchos
103 // =========================================================================
104 RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();
105 // const int numRanks = comm->getSize();
106 const int myRank = comm->getRank();
107
108 // =========================================================================
109 // Convenient definitions
110 // =========================================================================
111 using STS = Teuchos::ScalarTraits<SC>;
112 SC zero = STS::zero(), one = STS::one();
113 using magnitude_type = typename Teuchos::ScalarTraits<Scalar>::magnitudeType;
114 using real_type = typename STS::coordinateType;
115 using RealValuedMultiVector = Xpetra::MultiVector<real_type, LO, GO, NO>;
116
117 // =========================================================================
118 // Parameters initialization
119 // =========================================================================
120 GO nx = 10, ny = 10, nz = 10;
121 Galeri::Xpetra::Parameters<GO> galeriParameters(clp, nx, ny, nz, "Laplace2D"); // manage parameters of the test case
122 Xpetra::Parameters xpetraParameters(clp); // manage parameters of Xpetra
123
124 std::string xmlFileName = "";
125 clp.setOption("xml", &xmlFileName, "read parameters from an xml file");
126 std::string yamlFileName = "";
127 clp.setOption("yaml", &yamlFileName, "read parameters from a yaml file");
128 std::string solverType = "region";
129 clp.setOption("solverType", &solverType, "iterative solver to be used: (region | Richardson | CG)");
130 std::string convergenceLog = "residual_norm.txt";
131 clp.setOption("convergence-log", &convergenceLog, "file in which the convergence history of the linear solver is stored");
132 int maxIts = 200;
133 clp.setOption("its", &maxIts, "maximum number of solver iterations");
134 double tol = 1e-12;
135 clp.setOption("tol", &tol, "solver convergence tolerance");
136 bool scaleResidualHist = true;
137 clp.setOption("scale", "noscale", &scaleResidualHist, "scaled Krylov residual history");
138 bool serialRandom = false;
139 clp.setOption("use-serial-random", "no-use-serial-random", &serialRandom, "generate the random vector serially and then broadcast it");
140 std::string cycleType = "V";
141 clp.setOption("cycleType", &cycleType, "{Multigrid cycle type. Possible values: V, W.");
142 std::string smootherType = "Jacobi";
143 clp.setOption("smootherType", &smootherType, "smoother to be used: (None | Jacobi | Gauss | Chebyshev)");
144 int smootherIts = 2;
145 clp.setOption("smootherIts", &smootherIts, "number of smoother iterations");
146 double smootherDamp = 0.67;
147 clp.setOption("smootherDamp", &smootherDamp, "damping parameter for the level smoother");
148 double smootherChebyEigRatio = 2.0;
149 clp.setOption("smootherChebyEigRatio", &smootherChebyEigRatio, "eigenvalue ratio max/min used to approximate the smallest eigenvalue for Chebyshev relaxation");
150 double smootherChebyBoostFactor = 1.1;
151 clp.setOption("smootherChebyBoostFactor", &smootherChebyBoostFactor, "boost factor for Chebyshev smoother");
152 bool keepCoarseCoords = false;
153 clp.setOption("keep-coarse-coords", "no-keep-coarse-coords", &keepCoarseCoords, "keep coordinates on coarsest level of region hierarchy");
154 bool coarseSolverRebalance = false;
155 clp.setOption("rebalance-coarse", "no-rebalance-coarse", &coarseSolverRebalance, "rebalance before AMG coarse grid solve");
156 int rebalanceNumPartitions = -1;
157 clp.setOption("numPartitions", &rebalanceNumPartitions, "number of partitions for rebalancing the coarse grid AMG solve");
158 std::string coarseSolverType = "direct";
159 clp.setOption("coarseSolverType", &coarseSolverType, "Type of solver for (composite) coarse level operator (smoother | direct | amg)");
160 std::string unstructured = "{}";
161 clp.setOption("unstructured", &unstructured, "List of ranks to be treated as unstructured, e.g. {0, 2, 5}");
162 std::string coarseAmgXmlFile = "";
163 clp.setOption("coarseAmgXml", &coarseAmgXmlFile, "Read parameters for AMG as coarse level solve from this xml file.");
164 std::string coarseSmootherXMLFile = "";
165 clp.setOption("coarseSmootherXML", &coarseSmootherXMLFile, "File containing the parameters to use with the coarse level smoother.");
166 std::string equilibrate = "no";
167 clp.setOption("equilibrate", &equilibrate, "equilibrate the system (no | diag | 1-norm)");
168 #ifdef HAVE_MUELU_CUDA
169 bool profileSetup = false;
170 clp.setOption("cuda-profile-setup", "no-cuda-profile-setup", &profileSetup, "enable CUDA profiling for setup");
171 bool profileSolve = false;
172 clp.setOption("cuda-profile-solve", "no-cuda-profile-solve", &profileSolve, "enable CUDA profiling for solve");
173 #endif
174 int cacheSize = 0;
175 clp.setOption("cachesize", &cacheSize, "cache size (in KB)");
176 bool useStackedTimer = false;
177 clp.setOption("stacked-timer", "no-stacked-timer", &useStackedTimer, "use stacked timer");
178 bool showTimerSummary = true;
179 clp.setOption("show-timer-summary", "no-show-timer-summary", &showTimerSummary, "Switch on/off the timer summary at the end of the run.");
180
181 clp.recogniseAllOptions(true);
182 switch (clp.parse(argc, argv)) {
183 case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED: return EXIT_SUCCESS;
184 case Teuchos::CommandLineProcessor::PARSE_ERROR:
185 case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE;
186 case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL: break;
187 }
188
189 TEUCHOS_TEST_FOR_EXCEPTION(xmlFileName != "" && yamlFileName != "", std::runtime_error,
190 "Cannot provide both xml and yaml input files");
191
192 // Instead of checking each time for rank, create a rank 0 stream
193 RCP<Teuchos::FancyOStream> fancy = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
194 Teuchos::FancyOStream &out = *fancy;
195 out.setOutputToRootOnly(0);
196
197 ParameterList paramList;
198 auto inst = xpetraParameters.GetInstantiation();
199
200 if (yamlFileName != "") {
201 Teuchos::updateParametersFromYamlFileAndBroadcast(yamlFileName, Teuchos::Ptr<ParameterList>(&paramList), *comm);
202 } else {
203 if (inst == Xpetra::COMPLEX_INT_INT)
204 xmlFileName = (xmlFileName != "" ? xmlFileName : "structured_1dof-complex.xml");
205 else
206 xmlFileName = (xmlFileName != "" ? xmlFileName : "structured_1dof.xml");
207 Teuchos::updateParametersFromXmlFileAndBroadcast(xmlFileName, Teuchos::Ptr<ParameterList>(&paramList), *comm);
208 }
209
210 Array<RCP<Teuchos::ParameterList> > smootherParams(1); // TODO: this is good, resized to numlevel
211 smootherParams[0] = rcp(new Teuchos::ParameterList());
212 smootherParams[0]->set("smoother: type", smootherType);
213 smootherParams[0]->set("smoother: sweeps", smootherIts);
214 smootherParams[0]->set("smoother: damping", smootherDamp);
215 smootherParams[0]->set("smoother: Chebyshev eigRatio", smootherChebyEigRatio);
216 smootherParams[0]->set("smoother: Chebyshev boost factor", smootherChebyBoostFactor);
217
218 bool useUnstructured = false;
219 Array<LO> unstructuredRanks = Teuchos::fromStringToArray<LO>(unstructured);
220 for (int idx = 0; idx < unstructuredRanks.size(); ++idx) {
221 if (unstructuredRanks[idx] == myRank) {
222 useUnstructured = true;
223 }
224 }
225
226 // Retrieve matrix parameters (they may have been changed on the command line)
227 // [for instance, if we changed matrix type from 2D to 3D we need to update nz]
228 ParameterList galeriList = galeriParameters.GetParameterList();
229
230 // =========================================================================
231 // Problem construction
232 // =========================================================================
233 std::ostringstream galeriStream;
234 #ifdef HAVE_MUELU_OPENMP
235 std::string node_name = Node::name();
236 if (!comm->getRank() && !node_name.compare("OpenMP/Wrapper"))
237 galeriStream << "OpenMP Max Threads = " << omp_get_max_threads() << std::endl;
238 #endif
239
240 comm->barrier();
241 Teuchos::RCP<Teuchos::StackedTimer> stacked_timer;
242 if (useStackedTimer)
243 stacked_timer = rcp(new Teuchos::StackedTimer("MueLu_Driver"));
244 Teuchos::TimeMonitor::setStackedTimer(stacked_timer);
245 RCP<TimeMonitor> globalTimeMonitor = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: S - Global Time")));
246 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 1 - Build Composite Matrix")));
247
248 RCP<Matrix> A;
249 RCP<Map> nodeMap, dofMap;
250 RCP<Vector> X, B;
251 RCP<MultiVector> nullspace;
252 RCP<RealValuedMultiVector> coordinates;
253
254 galeriStream << "========================================================\n"
255 << xpetraParameters << galeriParameters;
256
257 // Galeri will attempt to create a square-as-possible distribution of subdomains di, e.g.,
258 // d1 d2 d3
259 // d4 d5 d6
260 // d7 d8 d9
261 // d10 d11 d12
262 // A perfect distribution is only possible when the #processors is a perfect square.
263 // This *will* result in "strip" distribution if the #processors is a prime number or if the factors are very different in
264 // size. For example, np=14 will give a 7-by-2 distribution.
265 // If you don't want Galeri to do this, specify mx or my on the galeriList.
266 std::string matrixType = galeriParameters.GetMatrixType();
267 int numDimensions = 0;
268 int numDofsPerNode = 0;
269 Teuchos::Array<GO> procsPerDim(3);
270 Teuchos::Array<GO> gNodesPerDim(3);
271 Teuchos::Array<LO> lNodesPerDim(3);
272
273 // Create map and coordinates
274 // In the future, we hope to be able to first create a Galeri problem, and then request map and coordinates from it
275 // At the moment, however, things are fragile as we hope that the Problem uses same map and coordinates inside
276 if (matrixType == "Laplace1D") {
277 numDimensions = 1;
278 nodeMap = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian1D", comm, galeriList);
279 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<double, LO, GO, Map, RealValuedMultiVector>("1D", nodeMap, galeriList);
280
281 } else if (matrixType == "Laplace2D" || matrixType == "Star2D" ||
282 matrixType == "BigStar2D" || matrixType == "Elasticity2D") {
283 numDimensions = 2;
284 nodeMap = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian2D", comm, galeriList);
285 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<double, LO, GO, Map, RealValuedMultiVector>("2D", nodeMap, galeriList);
286
287 } else if (matrixType == "Laplace3D" || matrixType == "Brick3D" || matrixType == "Elasticity3D") {
288 numDimensions = 3;
289 nodeMap = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian3D", comm, galeriList);
290 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<double, LO, GO, Map, RealValuedMultiVector>("3D", nodeMap, galeriList);
291 }
292
293 // Expand map to do multiple DOF per node for block problems
294 if (matrixType == "Elasticity2D") {
295 numDofsPerNode = 2;
296 } else if (matrixType == "Elasticity3D") {
297 numDofsPerNode = 3;
298 } else {
299 numDofsPerNode = 1;
300 }
301 dofMap = Xpetra::MapFactory<LO, GO, Node>::Build(nodeMap, numDofsPerNode);
302
303 galeriStream << "Processor subdomains in x direction: " << galeriList.get<GO>("mx") << std::endl
304 << "Processor subdomains in y direction: " << galeriList.get<GO>("my") << std::endl
305 << "Processor subdomains in z direction: " << galeriList.get<GO>("mz") << std::endl
306 << "========================================================" << std::endl;
307
308 if (matrixType == "Elasticity2D" || matrixType == "Elasticity3D") {
309 // Our default test case for elasticity: all boundaries of a square/cube have Neumann b.c. except left which has Dirichlet
310 galeriList.set("right boundary", "Neumann");
311 galeriList.set("bottom boundary", "Neumann");
312 galeriList.set("top boundary", "Neumann");
313 galeriList.set("front boundary", "Neumann");
314 galeriList.set("back boundary", "Neumann");
315 }
316
317 RCP<Galeri::Xpetra::Problem<Map, CrsMatrixWrap, MultiVector> > Pr =
318 Galeri::Xpetra::BuildProblem<SC, LO, GO, Map, CrsMatrixWrap, MultiVector>(galeriParameters.GetMatrixType(), dofMap, galeriList);
319 A = Pr->BuildMatrix();
320
321 A->SetFixedBlockSize(numDofsPerNode);
322
323 nullspace = Pr->BuildNullspace();
324
325 X = VectorFactory::Build(dofMap);
326 B = VectorFactory::Build(dofMap);
327
328 if (serialRandom) {
329 // Build the seed on rank zero and broadcast it.
330 size_t localNumElements = 0;
331 if (comm->getRank() == 0) {
332 localNumElements = static_cast<size_t>(dofMap->getGlobalNumElements());
333 }
334 RCP<Map> serialMap = MapFactory::Build(dofMap->lib(),
335 dofMap->getGlobalNumElements(),
336 localNumElements,
337 0,
338 comm);
339 RCP<Vector> Xserial = VectorFactory::Build(serialMap);
340 Xserial->setSeed(251743369);
341 Xserial->randomize(true); // using xpetra's randomize. Otherwise random vector is only consistent for first 128 entries
342 RCP<Import> randomnessImporter = ImportFactory::Build(serialMap, dofMap);
343 X->doImport(*Xserial, *randomnessImporter, Xpetra::INSERT);
344 } else {
345 // we set seed for reproducibility
346 Utilities::SetRandomSeed(*comm);
347 X->randomize(true); // using xpetra's randomize. Otherwise random vector is only consistent for first 128 entries
348 }
349 A->apply(*X, *B, Teuchos::NO_TRANS, one, zero);
350
351 Teuchos::Array<typename STS::magnitudeType> norms(1);
352 B->norm2(norms);
353 B->scale(one / norms[0]);
354 galeriStream << "Galeri complete.\n========================================================" << std::endl;
355
356 #ifdef MATLAB_COMPARE
357 Xpetra::IO<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Write("Ax.mm", *B);
358 Xpetra::IO<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Write("A.mm", *A);
359 B->putScalar(zero);
360 Xpetra::IO<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Write("rhs.mm", *B);
361 Xpetra::IO<Scalar, LocalOrdinal, GlobalOrdinal, Node>::Write("x.mm", *X);
362 #endif
363 out << galeriStream.str();
364
365 comm->barrier();
366 tm = Teuchos::null;
367
368 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 2 - Compute region data")));
369
370 // Set aggregation type for each region
371 std::string aggregationRegionType;
372 RCP<ParameterList> interfaceParams = rcp(new ParameterList());
373 if (useUnstructured) {
374 aggregationRegionType = "uncoupled";
375 } else {
376 aggregationRegionType = "structured";
377 }
378
379 // Loading geometric info from galeri
380 if (numDimensions == 1) {
381 gNodesPerDim[0] = galeriList.get<GO>("nx");
382 gNodesPerDim[1] = 1;
383 gNodesPerDim[2] = 1;
384
385 lNodesPerDim[0] = galeriList.get<LO>("lnx");
386 lNodesPerDim[1] = 1;
387 lNodesPerDim[2] = 1;
388
389 procsPerDim[0] = galeriList.get<GO>("mx");
390 procsPerDim[1] = 1;
391 procsPerDim[2] = 1;
392 } else if (numDimensions == 2) {
393 gNodesPerDim[0] = galeriList.get<GO>("nx");
394 gNodesPerDim[1] = galeriList.get<GO>("ny");
395 gNodesPerDim[2] = 1;
396
397 lNodesPerDim[0] = galeriList.get<LO>("lnx");
398 lNodesPerDim[1] = galeriList.get<LO>("lny");
399 lNodesPerDim[2] = 1;
400
401 procsPerDim[0] = galeriList.get<GO>("mx");
402 procsPerDim[1] = galeriList.get<GO>("my");
403 procsPerDim[2] = 1;
404 } else if (numDimensions == 3) {
405 gNodesPerDim[0] = galeriList.get<GO>("nx");
406 gNodesPerDim[1] = galeriList.get<GO>("ny");
407 gNodesPerDim[2] = galeriList.get<GO>("nz");
408
409 lNodesPerDim[0] = galeriList.get<LO>("lnx");
410 lNodesPerDim[1] = galeriList.get<LO>("lny");
411 lNodesPerDim[2] = galeriList.get<LO>("lnz");
412
413 procsPerDim[0] = galeriList.get<GO>("mx");
414 procsPerDim[1] = galeriList.get<GO>("my");
415 procsPerDim[2] = galeriList.get<GO>("mz");
416 }
417
418 // Rule for boundary duplication
419 // For any two ranks that share an interface:
420 // the lowest rank owns the interface and the highest rank gets extra nodes
421
422 // 1D example of the relation between Composite, Quasi Region, and Region formats
423 //
424 // Composite:
425 // Rank 0 Rank 1
426 // [0 1 2] [3 4]
427 //
428 // Quasi Region:
429 // Rank 0 Rank 1
430 // [0 1 2] [2 3 4]
431 //
432 // Region:
433 // Rank 0 Rank 1
434 // [0 1 2] [5 3 4]
435
436 // First we count how many nodes the region needs to send and receive
437 // and allocate arrays accordingly
438 Array<int> boundaryConditions;
439 int maxRegPerGID = 0;
440 int numInterfaces = 0;
441 LO numLocalRegionNodes = 0;
442 Array<GO> sendGIDs;
443 Array<int> sendPIDs;
444 Array<LO> rNodesPerDim(3);
445 Array<LO> compositeToRegionLIDs(nodeMap->getLocalNumElements() * numDofsPerNode);
446 Array<GO> quasiRegionGIDs;
447 Array<GO> quasiRegionCoordGIDs;
448 Array<GO> interfaceGIDs;
449 Array<LO> interfaceLIDsData;
450
451 createRegionData(numDimensions, useUnstructured, numDofsPerNode,
452 gNodesPerDim(), lNodesPerDim(), procsPerDim(), nodeMap, dofMap,
453 maxRegPerGID, numLocalRegionNodes, boundaryConditions,
454 sendGIDs, sendPIDs, numInterfaces, rNodesPerDim,
455 quasiRegionGIDs, quasiRegionCoordGIDs, compositeToRegionLIDs,
456 interfaceGIDs, interfaceLIDsData);
457
458 // std::cout << "p=" << myRank << " | numSend=" << numSend << std::endl;
459 // << ", numReceive=" << numReceive << std::endl;
460 // std::cout << "p=" << myRank << " | receiveGIDs: " << receiveGIDs << std::endl;
461 // std::cout << "p=" << myRank << " | receivePIDs: " << receivePIDs << std::endl;
462 // std::cout << "p=" << myRank << " | sendGIDs: " << sendGIDs << std::endl;
463 // std::cout << "p=" << myRank << " | sendPIDs: " << sendPIDs << std::endl;
464
465 // Second we actually fill the send and receive arrays with appropriate data
466 // which will allow us to compute the region and composite maps.
467 // Now we can construct a list of GIDs that corresponds to rowMap
468 Array<LO> interfacesDimensions, interfacesLIDs;
469 if (useUnstructured) {
470 findInterface(numDimensions, rNodesPerDim, boundaryConditions,
471 interfacesDimensions, interfacesLIDs);
472
473 // std::cout << "p=" << myRank << " | numLocalRegionNodes=" << numLocalRegionNodes
474 // << ", rNodesPerDim: " << rNodesPerDim << std::endl;
475 // std::cout << "p=" << myRank << " | boundaryConditions: " << boundaryConditions << std::endl
476 // << "p=" << myRank << " | rNodesPerDim: " << rNodesPerDim << std::endl
477 // << "p=" << myRank << " | interfacesDimensions: " << interfacesDimensions << std::endl
478 // << "p=" << myRank << " | interfacesLIDs: " << interfacesLIDs << std::endl;
479 }
480
481 interfaceParams->set<Array<LO> >("interfaces: nodes per dimensions", interfacesDimensions); // nodesPerDimensions);
482 interfaceParams->set<Array<LO> >("interfaces: interface nodes", interfacesLIDs); // interfaceLIDs);
483
484 // std::cout << "p=" << myRank << " | compositeToRegionLIDs: " << compositeToRegionLIDs << std::endl;
485 // std::cout << "p=" << myRank << " | quasiRegionGIDs: " << quasiRegionGIDs << std::endl;
486 // std::cout << "p=" << myRank << " | interfaceGIDs: " << interfaceGIDs << std::endl;
487 // std::cout << "p=" << myRank << " | interfaceLIDsData: " << interfaceLIDsData << std::endl;
488 // std::cout << "p=" << myRank << " | interfaceLIDs: " << interfaceLIDs << std::endl;
489 // std::cout << "p=" << myRank << " | quasiRegionCoordGIDs: " << quasiRegionCoordGIDs() << std::endl;
490
491 // In our very particular case we know that a node is at most shared by 4 (8) regions in 2D (3D) problems.
492 // Other geometries will certainly have different constrains and a parallel reduction using MAX
493 // would be appropriate.
494
495 comm->barrier();
496 tm = Teuchos::null;
497
498 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 3 - Build Region Matrix")));
499
500 RCP<TimeMonitor> tmLocal = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 3.1 - Build Region Maps")));
501
502 Teuchos::RCP<const Xpetra::Map<LO, GO, NO> > rowMap, colMap;
503 Teuchos::RCP<const Xpetra::Map<LO, GO, NO> > revisedRowMap, revisedColMap;
504 rowMap = Xpetra::MapFactory<LO, GO, Node>::Build(dofMap->lib(),
505 Teuchos::OrdinalTraits<GO>::invalid(),
506 quasiRegionGIDs(),
507 dofMap->getIndexBase(),
508 dofMap->getComm());
509 colMap = rowMap;
510 revisedRowMap = Xpetra::MapFactory<LO, GO, Node>::Build(dofMap->lib(),
511 Teuchos::OrdinalTraits<GO>::invalid(),
512 numLocalRegionNodes * numDofsPerNode,
513 dofMap->getIndexBase(),
514 dofMap->getComm());
515 revisedColMap = revisedRowMap;
516
517 // Build objects needed to construct the region coordinates
518 Teuchos::RCP<Xpetra::Map<LO, GO, NO> > quasiRegCoordMap = Xpetra::MapFactory<LO, GO, Node>::
519 Build(nodeMap->lib(),
520 Teuchos::OrdinalTraits<GO>::invalid(),
521 quasiRegionCoordGIDs(),
522 nodeMap->getIndexBase(),
523 nodeMap->getComm());
524 Teuchos::RCP<Xpetra::Map<LO, GO, NO> > regCoordMap = Xpetra::MapFactory<LO, GO, Node>::
525 Build(nodeMap->lib(),
526 Teuchos::OrdinalTraits<GO>::invalid(),
527 numLocalRegionNodes,
528 nodeMap->getIndexBase(),
529 nodeMap->getComm());
530
531 comm->barrier();
532 tmLocal = Teuchos::null;
533 tmLocal = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 3.2 - Build Region Importers")));
534
535 // Setup importers
536 RCP<Import> rowImport;
537 RCP<Import> colImport;
538 rowImport = ImportFactory::Build(dofMap, rowMap);
539 colImport = ImportFactory::Build(dofMap, colMap);
540 RCP<Import> coordImporter = ImportFactory::Build(nodeMap, quasiRegCoordMap);
541
542 comm->barrier();
543 tmLocal = Teuchos::null;
544 tmLocal = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 3.3 - Import ghost GIDs")));
545
546 Array<GO> interfaceCompositeGIDs, interfaceRegionGIDs;
547 ExtractListOfInterfaceRegionGIDs(revisedRowMap, interfaceLIDsData, interfaceRegionGIDs);
548
549 RCP<Xpetra::MultiVector<LO, LO, GO, NO> > regionsPerGIDWithGhosts;
550 RCP<Xpetra::MultiVector<GO, LO, GO, NO> > interfaceGIDsMV;
551 MakeRegionPerGIDWithGhosts(nodeMap, revisedRowMap, rowImport,
552 maxRegPerGID, numDofsPerNode,
553 lNodesPerDim, sendGIDs, sendPIDs, interfaceLIDsData,
554 regionsPerGIDWithGhosts, interfaceGIDsMV);
555
556 Teuchos::ArrayRCP<LO> regionMatVecLIDs;
557 RCP<Import> regionInterfaceImporter;
558 SetupMatVec(interfaceGIDsMV, regionsPerGIDWithGhosts, revisedRowMap, rowImport,
559 regionMatVecLIDs, regionInterfaceImporter);
560
561 comm->barrier();
562 tmLocal = Teuchos::null;
563 tmLocal = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 3.4 - Build QuasiRegion Matrix")));
564
565 std::cout << "About to create quasi region matrix" << std::endl;
566 RCP<Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> > quasiRegionMats;
567 MakeQuasiregionMatrices(Teuchos::rcp_dynamic_cast<CrsMatrixWrap>(A),
568 regionsPerGIDWithGhosts, rowMap, colMap, rowImport,
569 quasiRegionMats, regionMatVecLIDs);
570 std::cout << "Done creating quasi region matrix" << std::endl;
571
572 comm->barrier();
573 tmLocal = Teuchos::null;
574 tmLocal = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 3.5 - Build Region Matrix")));
575
576 RCP<Xpetra::Matrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> > regionMats;
577 MakeRegionMatrices(Teuchos::rcp_dynamic_cast<CrsMatrixWrap>(A), A->getRowMap(), rowMap,
578 revisedRowMap, revisedColMap,
579 rowImport, quasiRegionMats, regionMats);
580
581 // If we don't need the composite operator on the fine level anymore, free it!
582 if (solverType == "region") A = Teuchos::null;
583
584 comm->barrier();
585 tmLocal = Teuchos::null;
586
587 comm->barrier();
588 tm = Teuchos::null;
589
590 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 4 - Build Region Hierarchy")));
591
592 // Setting up parameters before hierarchy construction
593 // These need to stay in the driver as they would be provide by an app
594 Array<int> regionNodesPerDim;
595 RCP<MultiVector> regionNullspace;
596 RCP<RealValuedMultiVector> regionCoordinates;
597
598 // Set mesh structure data
599 regionNodesPerDim = rNodesPerDim;
600
601 // create nullspace vector
602 regionNullspace = MultiVectorFactory::Build(rowMap, nullspace->getNumVectors());
603 regionNullspace->doImport(*nullspace, *rowImport, Xpetra::INSERT);
604 regionNullspace->replaceMap(revisedRowMap);
605
606 // create region coordinates vector
607 regionCoordinates = Xpetra::MultiVectorFactory<real_type, LO, GO, NO>::Build(quasiRegCoordMap,
608 coordinates->getNumVectors());
609 regionCoordinates->doImport(*coordinates, *coordImporter, Xpetra::INSERT);
610 regionCoordinates->replaceMap(regCoordMap);
611
612 using Tpetra_CrsMatrix = Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>;
613 using Tpetra_MultiVector = Tpetra::MultiVector<Scalar, LocalOrdinal, GlobalOrdinal, Node>;
614
615 /* Stuff for multi-level algorithm
616 *
617 * To allow for multi-level schemes with more than two levels, we need to store
618 * maps, matrices, vectors, and stuff like that on each level. Since we call the
619 * multi-level scheme recursively, this should be reflected in the design of
620 * variables.
621 *
622 * We use MueLu::Hierarchy and MueLu:Level to store each quantity on each level.
623 */
624 RCP<ParameterList> coarseSolverData = rcp(new ParameterList());
625 coarseSolverData->set<std::string>("coarse solver type", coarseSolverType);
626 coarseSolverData->set<bool>("coarse solver rebalance", coarseSolverRebalance);
627 coarseSolverData->set<int>("coarse rebalance num partitions", rebalanceNumPartitions);
628 coarseSolverData->set<std::string>("amg xml file", coarseAmgXmlFile);
629 coarseSolverData->set<std::string>("smoother xml file", coarseSmootherXMLFile);
630 RCP<ParameterList> hierarchyData = rcp(new ParameterList());
631
632 // Create MueLu Hierarchy Initially...
633 // Read MueLu parameter list form xml file
634 RCP<ParameterList> mueluParams = Teuchos::rcp(new ParameterList());
635 Teuchos::updateParametersFromXmlFileAndBroadcast(xmlFileName, mueluParams.ptr(), *dofMap->getComm());
636
637 // Insert region-specific data into parameter list
638 const std::string userName = "user data";
639 Teuchos::ParameterList &userParamList = mueluParams->sublist(userName);
640 userParamList.set<int>("int numDimensions", numDimensions);
641 userParamList.set<Array<LO> >("Array<LO> lNodesPerDim", regionNodesPerDim);
642 userParamList.set<std::string>("string aggregationRegionType", aggregationRegionType);
643 userParamList.set<Array<LO> >("Array<LO> nodeOnInterface", interfaceParams->get<Array<LO> >("interfaces: interface nodes"));
644 userParamList.set<Array<LO> >("Array<LO> interfacesDimensions", interfaceParams->get<Array<LO> >("interfaces: nodes per dimensions"));
645 if (Teuchos::nonnull(regionCoordinates)) {
646 userParamList.set("Coordinates", regionCoordinates);
647 }
648 if (Teuchos::nonnull(regionNullspace)) {
649 userParamList.set("Nullspace", regionNullspace);
650 }
651
652 tmLocal = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("CreateXpetraPreconditioner: Hierarchy")));
653
654 // Create multigrid hierarchy part 1
655 RCP<Hierarchy> regHierarchy = MueLu::CreateXpetraPreconditioner(regionMats, *mueluParams);
656
657 {
658 RCP<MueLu::Level> level = regHierarchy->GetLevel(0);
659 level->Set<RCP<Xpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > >("rowImport", rowImport);
660 level->Set<ArrayView<LocalOrdinal> >("compositeToRegionLIDs", compositeToRegionLIDs());
661 level->Set<RCP<Xpetra::MultiVector<GlobalOrdinal, LocalOrdinal, GlobalOrdinal, Node> > >("interfaceGIDs", interfaceGIDsMV);
662 level->Set<RCP<Xpetra::MultiVector<LocalOrdinal, LocalOrdinal, GlobalOrdinal, Node> > >("regionsPerGIDWithGhosts", regionsPerGIDWithGhosts);
663 level->Set<Teuchos::ArrayRCP<LocalOrdinal> >("regionMatVecLIDs", regionMatVecLIDs);
664 level->Set<RCP<Xpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > >("regionInterfaceImporter", regionInterfaceImporter);
665 level->print(std::cout, MueLu::Extreme);
666 }
667
668 tmLocal = Teuchos::null;
669
670 // Create multigrid hierarchy part 2
671 createRegionHierarchy(numDimensions,
672 regionNodesPerDim,
673 aggregationRegionType,
674 interfaceParams,
675 maxRegPerGID,
676 coarseSolverData,
677 smootherParams,
678 hierarchyData,
679 regHierarchy,
680 keepCoarseCoords);
681
682 hierarchyData->print();
683
684 comm->barrier();
685 tm = Teuchos::null;
686
687 // Extract the number of levels from the prolongator data structure
688 const int numLevels = regHierarchy->GetNumLevels();
689
690 // Set data for fast MatVec
691 for (LO levelIdx = 0; levelIdx < numLevels; ++levelIdx) {
692 RCP<MueLu::Level> level = regHierarchy->GetLevel(levelIdx);
693 RCP<Xpetra::Import<LO, GO, NO> > regionInterfaceImport = level->Get<RCP<Xpetra::Import<LocalOrdinal, GlobalOrdinal, Node> > >("regionInterfaceImporter");
694 Teuchos::ArrayRCP<LO> regionMatVecLIDs1 = level->Get<Teuchos::ArrayRCP<LO> >("regionMatVecLIDs");
695 smootherParams[levelIdx]->set("Fast MatVec: interface LIDs",
696 regionMatVecLIDs1);
697 smootherParams[levelIdx]->set("Fast MatVec: interface importer",
698 regionInterfaceImport);
699 }
700
701 // RCP<Teuchos::FancyOStream> fancy2 = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
702 // Teuchos::FancyOStream& out2 = *fancy2;
703 // for(LO levelIdx = 0; levelIdx < numLevels; ++levelIdx) {
704 // out2 << "p=" << myRank << " | regionMatVecLIDs on level " << levelIdx << std::endl;
705 // regionMatVecLIDsPerLevel[levelIdx]->describe(out2, Teuchos::VERB_EXTREME);
706 // }
707
708 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("Driver: 5 - Solve with V-cycle")));
709
710 #ifdef DUMP_LOCALX_AND_A
711 FILE *fp;
712 char str[80];
713 sprintf(str, "theMatrix.%d", myRank);
714 fp = fopen(str, "w");
715 fprintf(fp, "%%%%MatrixMarket matrix coordinate real general\n");
716 LO numNzs = 0;
717 for (size_t kkk = 0; kkk < regionMats->getLocalNumRows(); kkk++) {
718 ArrayView<const LO> AAcols;
719 ArrayView<const SC> AAvals;
720 regionMats->getLocalRowView(kkk, AAcols, AAvals);
721 const int *Acols = AAcols.getRawPtr();
722 const SC *Avals = AAvals.getRawPtr();
723 numNzs += AAvals.size();
724 }
725 fprintf(fp, "%d %d %d\n", regionMats->getLocalNumRows(), regionMats->getLocalNumRows(), numNzs);
726
727 for (size_t kkk = 0; kkk < regionMats->getLocalNumRows(); kkk++) {
728 ArrayView<const LO> AAcols;
729 ArrayView<const SC> AAvals;
730 regionMats->getLocalRowView(kkk, AAcols, AAvals);
731 const int *Acols = AAcols.getRawPtr();
732 const SC *Avals = AAvals.getRawPtr();
733 LO RowLeng = AAvals.size();
734 for (LO kk = 0; kk < RowLeng; kk++) {
735 fprintf(fp, "%d %d %22.16e\n", kkk + 1, Acols[kk] + 1, Avals[kk]);
736 }
737 }
738 fclose(fp);
739 // sprintf(str,"theX.%d",myRank);
740 // fp = fopen(str,"w");
741 // ArrayRCP<SC> lX= regX->getDataNonConst(0);
742 // for (size_t kkk = 0; kkk < regionMats->getLocalNumRows(); kkk++) fprintf(fp, "%22.16e\n",lX[kkk]);
743 // fclose(fp);
744 #endif
745
746 if (solverType == "region") {
747 solveRegionProblemRichardson(tol, scaleResidualHist, maxIts,
748 cycleType, convergenceLog,
749 coarseSolverData, smootherParams, hierarchyData,
750 regHierarchy, X, B);
751 } else if (solverType == "Richardson") {
752 solveCompositeProblemRichardson(tol, scaleResidualHist, maxIts,
753 cycleType, convergenceLog,
754 coarseSolverData, smootherParams, hierarchyData,
755 regHierarchy, A, X, B);
756 } else if (solverType == "CG") {
757 solveCompositeProblemPCG(tol, scaleResidualHist, maxIts,
758 cycleType, convergenceLog,
759 coarseSolverData, smootherParams, hierarchyData,
760 regHierarchy, A, X, B);
761 } else {
762 throw std::runtime_error("Unknown solverType: " + solverType);
763 }
764
765 comm->barrier();
766 tm = Teuchos::null;
767 globalTimeMonitor = Teuchos::null;
768
769 if (showTimerSummary) {
770 RCP<ParameterList> reportParams = rcp(new ParameterList);
771 const std::string filter = "";
772 if (useStackedTimer) {
773 Teuchos::StackedTimer::OutputOptions options;
774 options.output_fraction = options.output_histogram = options.output_minmax = true;
775 stacked_timer->report(out, comm, options);
776 } else {
777 std::ios_base::fmtflags ff(out.flags());
778 TimeMonitor::report(comm.ptr(), out, filter, reportParams);
779 out << std::setiosflags(ff);
780 }
781 }
782
783 TimeMonitor::clearCounters();
784
785 return EXIT_SUCCESS;
786 }
787
788 //- -- --------------------------------------------------------
789 #define MUELU_AUTOMATIC_TEST_ETI_NAME main_
790 #include "MueLu_Test_ETI.hpp"
791
792 int main(int argc, char *argv[]) {
793 return Automatic_Test_ETI(argc, argv);
794 }