Debian Codegraph @

packages/muelu/test/viz/Viz.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 <unistd.h>
12 #include <iostream>
13
14 #include <Teuchos_XMLParameterListHelpers.hpp>
15 #include <Teuchos_StandardCatchMacros.hpp>
16
17 #include <Xpetra_MultiVectorFactory.hpp>
18 #include <Xpetra_ImportFactory.hpp>
19 #include <Xpetra_IO.hpp>
20
21 // Galeri
22 #include <Galeri_XpetraParameters.hpp>
23 #include <Galeri_XpetraProblemFactory.hpp>
24 #include <Galeri_XpetraUtils.hpp>
25 #include <Galeri_XpetraMaps.hpp>
26 //
27
28 #include <MueLu.hpp>
29 #include <MueLu_Level.hpp>
30 #include <MueLu_BaseClass.hpp>
31 #include <MueLu_ParameterListInterpreter.hpp> // TODO: move into MueLu.hpp
32
33 #include <MueLu_Utilities.hpp>
34
35 #include <MueLu_MutuallyExclusiveTime.hpp>
36
37 #ifdef HAVE_MUELU_BELOS
38 #include <BelosConfigDefs.hpp>
39 #include <BelosLinearProblem.hpp>
40 #include <BelosBlockCGSolMgr.hpp>
41 #include <BelosPseudoBlockCGSolMgr.hpp>
42 #include <BelosBlockGmresSolMgr.hpp>
43 #include <BelosXpetraAdapter.hpp> // => This header defines Belos::XpetraOp
44 #include <BelosMueLuAdapter.hpp> // => This header defines Belos::MueLuOp
45 #endif
46
47 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
48 int main_(Teuchos::CommandLineProcessor& clp, Xpetra::UnderlyingLib& lib, int argc, char* argv[]) {
49 #include <MueLu_UseShortNames.hpp>
50
51 using Teuchos::ArrayRCP;
52 using Teuchos::ParameterList;
53 using Teuchos::RCP;
54 using Teuchos::rcp;
55 using Teuchos::TimeMonitor;
56
57 // =========================================================================
58 // MPI initialization using Teuchos
59 // =========================================================================
60 bool success = false;
61 bool verbose = true;
62 try {
63 RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();
64
65 // =========================================================================
66 // Convenient definitions
67 // =========================================================================
68 typedef Teuchos::ScalarTraits<SC> STS;
69 SC zero = STS::zero(), one = STS::one();
70
71 // =========================================================================
72 // Parameters initialization
73 // =========================================================================
74 GO nx = 100, ny = 100, nz = 100;
75 Galeri::Xpetra::Parameters<GO> galeriParameters(clp, nx, ny, nz, "Laplace2D"); // manage parameters of the test case
76 Xpetra::Parameters xpetraParameters(clp); // manage parameters of Xpetra
77
78 std::string xmlFileName = "viztest.xml";
79 clp.setOption("xml", &xmlFileName, "read parameters from a file");
80 bool printTimings = true;
81 clp.setOption("timings", "notimings", &printTimings, "print timings to screen");
82 int writeMatricesOPT = -2;
83 clp.setOption("write", &writeMatricesOPT, "write matrices to file (-1 means all; i>=0 means level i)");
84 std::string dsolveType = "cg", solveType;
85 clp.setOption("solver", &dsolveType, "solve type: (none | cg | gmres | standalone)");
86 double dtol = 1e-12, tol;
87 clp.setOption("tol", &dtol, "solver convergence tolerance");
88
89 std::string mapFile;
90 clp.setOption("map", &mapFile, "map data file");
91 std::string colMapFile;
92 clp.setOption("colmap", &colMapFile, "colmap data file");
93 std::string domainMapFile;
94 clp.setOption("domainmap", &domainMapFile, "domainmap data file");
95 std::string rangeMapFile;
96 clp.setOption("rangemap", &rangeMapFile, "rangemap data file");
97 std::string matrixFile;
98 clp.setOption("matrix", &matrixFile, "matrix data file");
99 std::string coordFile;
100 clp.setOption("coords", &coordFile, "coordinates data file");
101 std::string nullFile;
102 clp.setOption("nullspace", &nullFile, "nullspace data file");
103 int numRebuilds = 0;
104 clp.setOption("rebuild", &numRebuilds, "#times to rebuild hierarchy");
105 int maxIts = 200;
106 clp.setOption("its", &maxIts, "maximum number of solver iterations");
107 bool scaleResidualHist = true;
108 clp.setOption("scale", "noscale", &scaleResidualHist, "scaled Krylov residual history");
109
110 switch (clp.parse(argc, argv)) {
111 case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED: return EXIT_SUCCESS;
112 case Teuchos::CommandLineProcessor::PARSE_ERROR:
113 case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE;
114 case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL: break;
115 }
116
117 ParameterList paramList;
118 Teuchos::updateParametersFromXmlFileAndBroadcast(xmlFileName, Teuchos::Ptr<ParameterList>(&paramList), *comm);
119 bool isDriver = paramList.isSublist("Run1");
120 if (isDriver) {
121 // update galeriParameters with the values from the XML file
122 ParameterList& realParams = galeriParameters.GetParameterList();
123
124 for (ParameterList::ConstIterator it = realParams.begin(); it != realParams.end(); it++) {
125 const std::string& name = realParams.name(it);
126 if (paramList.isParameter(name))
127 realParams.setEntry(name, paramList.getEntry(name));
128 }
129 }
130
131 // Retrieve matrix parameters (they may have been changed on the command line)
132 // [for instance, if we changed matrix type from 2D to 3D we need to update nz]
133 ParameterList galeriList = galeriParameters.GetParameterList();
134
135 // =========================================================================
136 // Problem construction
137 // =========================================================================
138 std::ostringstream galeriStream;
139 comm->barrier();
140 RCP<TimeMonitor> globalTimeMonitor = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: S - Global Time")));
141 RCP<TimeMonitor> tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 1 - Matrix Build")));
142
143 RCP<Matrix> A;
144 RCP<const Map> map;
145 RCP<MultiVector> coordinates;
146 RCP<MultiVector> nullspace;
147 int ndims = 2;
148 if (matrixFile.empty()) {
149 galeriStream << "========================================================\n"
150 << xpetraParameters << galeriParameters;
151
152 // Galeri will attempt to create a square-as-possible distribution of subdomains di, e.g.,
153 // d1 d2 d3
154 // d4 d5 d6
155 // d7 d8 d9
156 // d10 d11 d12
157 // A perfect distribution is only possible when the #processors is a perfect square.
158 // This *will* result in "strip" distribution if the #processors is a prime number or if the factors are very different in
159 // size. For example, np=14 will give a 7-by-2 distribution.
160 // If you don't want Galeri to do this, specify mx or my on the galeriList.
161 std::string matrixType = galeriParameters.GetMatrixType();
162
163 // Create map and coordinates
164 // In the future, we hope to be able to first create a Galeri problem, and then request map and coordinates from it
165 // At the moment, however, things are fragile as we hope that the Problem uses same map and coordinates inside
166 if (matrixType == "Laplace1D") {
167 map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian1D", comm, galeriList);
168 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<SC, LO, GO, Map, MultiVector>("1D", map, galeriList);
169
170 } else if (matrixType == "Laplace2D" || matrixType == "Star2D" ||
171 matrixType == "BigStar2D" || matrixType == "Elasticity2D") {
172 map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian2D", comm, galeriList);
173 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<SC, LO, GO, Map, MultiVector>("2D", map, galeriList);
174
175 } else if (matrixType == "Laplace3D" || matrixType == "Brick3D" || matrixType == "Elasticity3D") {
176 map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian3D", comm, galeriList);
177 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<SC, LO, GO, Map, MultiVector>("3D", map, galeriList);
178 ndims = 3;
179 }
180
181 // Expand map to do multiple DOF per node for block problems
182 if (matrixType == "Elasticity2D")
183 map = Xpetra::MapFactory<LO, GO, Node>::Build(map, 2);
184 if (matrixType == "Elasticity3D")
185 map = Xpetra::MapFactory<LO, GO, Node>::Build(map, 3);
186
187 galeriStream << "Processor subdomains in x direction: " << galeriList.get<GO>("mx") << std::endl
188 << "Processor subdomains in y direction: " << galeriList.get<GO>("my") << std::endl
189 << "Processor subdomains in z direction: " << galeriList.get<GO>("mz") << std::endl
190 << "========================================================" << std::endl;
191
192 if (matrixType == "Elasticity2D" || matrixType == "Elasticity3D") {
193 // Our default test case for elasticity: all boundaries of a square/cube have Neumann b.c. except left which has Dirichlet
194 galeriList.set("right boundary", "Neumann");
195 galeriList.set("bottom boundary", "Neumann");
196 galeriList.set("top boundary", "Neumann");
197 galeriList.set("front boundary", "Neumann");
198 galeriList.set("back boundary", "Neumann");
199 }
200
201 RCP<Galeri::Xpetra::Problem<Map, CrsMatrixWrap, MultiVector> > Pr =
202 Galeri::Xpetra::BuildProblem<SC, LO, GO, Map, CrsMatrixWrap, MultiVector>(galeriParameters.GetMatrixType(), map, galeriList);
203 A = Pr->BuildMatrix();
204
205 if (matrixType == "Elasticity2D" ||
206 matrixType == "Elasticity3D") {
207 nullspace = Pr->BuildNullspace();
208 A->SetFixedBlockSize((galeriParameters.GetMatrixType() == "Elasticity2D") ? 2 : 3);
209 }
210
211 } else {
212 if (!mapFile.empty())
213 map = Xpetra::IO<SC, LO, GO, Node>::ReadMap(mapFile, lib, comm);
214 comm->barrier();
215
216 const bool binaryFormat = false;
217
218 if (!binaryFormat && !map.is_null()) {
219 RCP<const Map> colMap = (!colMapFile.empty() ? Xpetra::IO<SC, LO, GO, Node>::ReadMap(colMapFile, lib, comm) : Teuchos::null);
220 RCP<const Map> domainMap = (!domainMapFile.empty() ? Xpetra::IO<SC, LO, GO, Node>::ReadMap(domainMapFile, lib, comm) : Teuchos::null);
221 RCP<const Map> rangeMap = (!rangeMapFile.empty() ? Xpetra::IO<SC, LO, GO, Node>::ReadMap(rangeMapFile, lib, comm) : Teuchos::null);
222 A = Xpetra::IO<SC, LO, GO, Node>::Read(matrixFile, map, colMap, domainMap, rangeMap);
223
224 } else {
225 A = Xpetra::IO<SC, LO, GO, Node>::Read(matrixFile, lib, comm, binaryFormat);
226
227 if (!map.is_null()) {
228 RCP<Matrix> newMatrix = MatrixFactory::Build(map, 1);
229 RCP<Import> importer = ImportFactory::Build(A->getRowMap(), map);
230 newMatrix->doImport(*A, *importer, Xpetra::INSERT);
231 newMatrix->fillComplete();
232
233 A.swap(newMatrix);
234 }
235 }
236 map = A->getMap();
237
238 comm->barrier();
239
240 if (!coordFile.empty()) {
241 // NOTE: currently we only allow reading scalar matrices, thus coordinate
242 // map is same as matrix map
243 coordinates = Xpetra::IO<SC, LO, GO, Node>::ReadMultiVector(coordFile, map);
244 }
245
246 if (!nullFile.empty())
247 nullspace = Xpetra::IO<SC, LO, GO, Node>::ReadMultiVector(nullFile, map);
248 }
249
250 comm->barrier();
251 tm = Teuchos::null;
252
253 galeriStream << "Galeri complete.\n========================================================" << std::endl;
254
255 if (ndims == 2)
256 paramList.set<std::string>("aggregation: output filename", "Output/MPI-Viz-Output-2D-Level%LEVELID-Proc%PROCID");
257 else if (ndims == 3)
258 paramList.set<std::string>("aggregation: output filename", "Output/MPI-Viz-Output-3D-Level%LEVELID-Proc%PROCID");
259 int numReruns = 1;
260 if (paramList.isParameter("number of reruns"))
261 numReruns = paramList.get<int>("number of reruns");
262
263 const bool mustAlreadyExist = true;
264 for (int rerunCount = 1; rerunCount <= numReruns; rerunCount++) {
265 ParameterList mueluList, runList;
266
267 bool stop = false;
268 if (isDriver) {
269 runList = paramList.sublist("Run1", mustAlreadyExist);
270 mueluList = runList.sublist("MueLu", mustAlreadyExist);
271 } else {
272 mueluList = paramList;
273 stop = true;
274 }
275
276 mueluList.set("use kokkos refactor", false);
277
278 if (nullspace.is_null()) {
279 int blkSize = 1;
280 if (mueluList.isSublist("Matrix")) {
281 // Factory style parameter list
282 const Teuchos::ParameterList& operatorList = paramList.sublist("Matrix");
283 if (operatorList.isParameter("PDE equations"))
284 blkSize = operatorList.get<int>("PDE equations");
285
286 } else if (paramList.isParameter("number of equations")) {
287 // Easy style parameter list
288 blkSize = paramList.get<int>("number of equations");
289 }
290
291 nullspace = MultiVectorFactory::Build(map, blkSize);
292 for (int i = 0; i < blkSize; i++) {
293 RCP<const Map> domainMap = A->getDomainMap();
294 GO indexBase = domainMap->getIndexBase();
295
296 ArrayRCP<SC> nsData = nullspace->getDataNonConst(i);
297 for (int j = 0; j < nsData.size(); j++) {
298 GO GID = domainMap->getGlobalElement(j) - indexBase;
299
300 if ((GID - i) % blkSize == 0)
301 nsData[j] = Teuchos::ScalarTraits<SC>::one();
302 }
303 }
304 }
305
306 int runCount = 1;
307 do {
308 solveType = dsolveType;
309 tol = dtol;
310
311 int savedOut = -1;
312 FILE* openedOut = NULL;
313 if (isDriver) {
314 if (runList.isParameter("filename")) {
315 // Redirect all output into a filename We have to redirect all output,
316 // including printf's, therefore we cannot simply replace C++ cout
317 // buffers, and have to use heavy machinary (dup2)
318 std::string filename = runList.get<std::string>("filename");
319 if (numReruns > 1)
320 filename += "_run" + MueLu::toString(rerunCount);
321 filename += (lib == Xpetra::UseEpetra ? ".epetra" : ".tpetra");
322
323 savedOut = dup(STDOUT_FILENO);
324 openedOut = fopen(filename.c_str(), "w");
325 dup2(fileno(openedOut), STDOUT_FILENO);
326 }
327 if (runList.isParameter("solver")) solveType = runList.get<std::string>("solver");
328 if (runList.isParameter("tol")) tol = runList.get<double>("tol");
329 }
330
331 // Instead of checking each time for rank, create a rank 0 stream
332 RCP<Teuchos::FancyOStream> fancy = Teuchos::fancyOStream(Teuchos::rcpFromRef(std::cout));
333 Teuchos::FancyOStream& out = *fancy;
334 out.setOutputToRootOnly(0);
335
336 out << galeriStream.str();
337
338 // =========================================================================
339 // Preconditioner construction
340 // =========================================================================
341 comm->barrier();
342 tm.reset();
343 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 1.5 - MueLu read XML")));
344
345 RCP<HierarchyManager> mueLuFactory = rcp(new ParameterListInterpreter(mueluList));
346
347 comm->barrier();
348 tm.reset();
349 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 2 - MueLu Setup")));
350
351 RCP<Hierarchy> H;
352 for (int i = 0; i <= numRebuilds; i++) {
353 A->SetMaxEigenvalueEstimate(-one);
354
355 H = mueLuFactory->CreateHierarchy();
356 H->GetLevel(0)->Set("A", A);
357 H->GetLevel(0)->Set("Nullspace", nullspace);
358 if (!coordinates.is_null())
359 H->GetLevel(0)->Set("Coordinates", coordinates);
360 mueLuFactory->SetupHierarchy(*H);
361 }
362
363 comm->barrier();
364 tm = Teuchos::null;
365
366 // =========================================================================
367 // System solution (Ax = b)
368 // =========================================================================
369 comm->barrier();
370 tm.reset();
371 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 3 - LHS and RHS initialization")));
372
373 RCP<Vector> X = VectorFactory::Build(map);
374 RCP<Vector> B = VectorFactory::Build(map);
375
376 {
377 // we set seed for reproducibility
378 Utilities::SetRandomSeed(*comm);
379 X->randomize();
380 A->apply(*X, *B, Teuchos::NO_TRANS, one, zero);
381
382 Teuchos::Array<typename STS::magnitudeType> norms(1);
383 B->norm2(norms);
384 B->scale(one / norms[0]);
385 X->putScalar(zero);
386 }
387 tm = Teuchos::null;
388
389 if (writeMatricesOPT > -2) {
390 tm.reset();
391 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 3.5 - Matrix output")));
392 H->Write(writeMatricesOPT, writeMatricesOPT);
393 tm = Teuchos::null;
394 }
395
396 comm->barrier();
397 if (solveType == "none") {
398 // Do not perform a solve
399
400 } else if (solveType == "standalone") {
401 tm.reset();
402 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 4 - Fixed Point Solve")));
403
404 H->IsPreconditioner(false);
405 H->Iterate(*B, *X, maxIts);
406
407 } else if (solveType == "cg" || solveType == "gmres") {
408 #ifdef HAVE_MUELU_BELOS
409 tm.reset();
410 tm = rcp(new TimeMonitor(*TimeMonitor::getNewTimer("ScalingTest: 5 - Belos Solve")));
411
412 // Operator and Multivector type that will be used with Belos
413 typedef MultiVector MV;
414 typedef Belos::OperatorT<MV> OP;
415
416 H->IsPreconditioner(true);
417
418 // Define Operator and Preconditioner
419 Teuchos::RCP<OP> belosOp = Teuchos::rcp(new Belos::XpetraOp<SC, LO, GO, NO>(A)); // Turns a Xpetra::Matrix object into a Belos operator
420 Teuchos::RCP<OP> belosPrec = Teuchos::rcp(new Belos::MueLuOp<SC, LO, GO, NO>(H)); // Turns a MueLu::Hierarchy object into a Belos operator
421
422 // Construct a Belos LinearProblem object
423 RCP<Belos::LinearProblem<SC, MV, OP> > belosProblem = rcp(new Belos::LinearProblem<SC, MV, OP>(belosOp, X, B));
424 belosProblem->setRightPrec(belosPrec);
425
426 bool set = belosProblem->setProblem();
427 if (set == false) {
428 out << "\nERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
429 return EXIT_FAILURE;
430 }
431
432 // Belos parameter list
433 Teuchos::ParameterList belosList;
434 belosList.set("Maximum Iterations", maxIts); // Maximum number of iterations allowed
435 belosList.set("Convergence Tolerance", tol); // Relative convergence tolerance requested
436 belosList.set("Verbosity", Belos::Errors + Belos::Warnings + Belos::StatusTestDetails);
437 belosList.set("Output Frequency", 1);
438 belosList.set("Output Style", Belos::Brief);
439 if (!scaleResidualHist)
440 belosList.set("Implicit Residual Scaling", "None");
441
442 // Create an iterative solver manager
443 RCP<Belos::SolverManager<SC, MV, OP> > solver;
444 if (solveType == "cg") {
445 solver = rcp(new Belos::PseudoBlockCGSolMgr<SC, MV, OP>(belosProblem, rcp(&belosList, false)));
446 } else if (solveType == "gmres") {
447 solver = rcp(new Belos::BlockGmresSolMgr<SC, MV, OP>(belosProblem, rcp(&belosList, false)));
448 }
449
450 // Perform solve
451 Belos::ReturnType ret = Belos::Unconverged;
452 ret = solver->solve();
453
454 // Get the number of iterations for this solve.
455 out << "Number of iterations performed for this solve: " << solver->getNumIters() << std::endl;
456
457 // Check convergence
458 if (ret != Belos::Converged)
459 out << std::endl
460 << "ERROR: Belos did not converge! " << std::endl;
461 else
462 out << std::endl
463 << "SUCCESS: Belos converged!" << std::endl;
464 #endif // ifdef HAVE_MUELU_BELOS
465 } else {
466 throw MueLu::Exceptions::RuntimeError("Unknown solver type: \"" + solveType + "\"");
467 }
468 comm->barrier();
469 tm = Teuchos::null;
470 globalTimeMonitor = Teuchos::null;
471
472 if (printTimings) {
473 const bool alwaysWriteLocal = false;
474 const bool writeGlobalStats = true;
475 const bool writeZeroTimers = false;
476 const bool ignoreZeroTimers = true;
477 const std::string filter = "";
478 TimeMonitor::summarize(A->getRowMap()->getComm().ptr(), std::cout, alwaysWriteLocal, writeGlobalStats,
479 writeZeroTimers, Teuchos::Union, filter, ignoreZeroTimers);
480 }
481
482 TimeMonitor::clearCounters();
483
484 if (isDriver) {
485 if (openedOut != NULL) {
486 TEUCHOS_ASSERT(savedOut >= 0);
487 dup2(savedOut, STDOUT_FILENO);
488 fclose(openedOut);
489 openedOut = NULL;
490 }
491 try {
492 runList = paramList.sublist("Run" + MueLu::toString(++runCount), mustAlreadyExist);
493 mueluList = runList.sublist("MueLu", mustAlreadyExist);
494 } catch (Teuchos::Exceptions::InvalidParameterName& e) {
495 stop = true;
496 }
497 }
498
499 } while (!stop);
500 }
501
502 success = true;
503 }
504 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
505
506 return (success ? EXIT_SUCCESS : EXIT_FAILURE);
507 }
508
509 //- -- --------------------------------------------------------
510 #define MUELU_AUTOMATIC_TEST_ETI_NAME main_
511 #include "MueLu_Test_ETI.hpp"
512
513 int main(int argc, char* argv[]) {
514 return Automatic_Test_ETI(argc, argv);
515 }