Debian Codegraph @

packages/muelu/research/semicoarsening/driver.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 /*!
11 \example tutorial.cpp
12 \brief Driver examples for an application that wants to use MueLu as a preconditioner.
13
14 This example shows how to create a problem, set up a MueLu hierarchy
15 with the help of an XML file, and to solve it using MueLu as a
16 preconditioner. It is meant to be used with one of the .xml files in
17 this directory.
18 */
19
20 //
21 // This example shows how to create a problem, set up a MueLu hierarchy with
22 // the help of an XML file, and to solve it using MueLu as a preconditioner.
23 //
24
25 #include <iostream>
26
27 // Define default data types
28 //#include <Tpetra_KokkosCompat_DefaultNode.hpp>
29
30 // typedef double Scalar;
31 // typedef int LocalOrdinal;
32 // typedef int GlobalOrdinal;
33 // typedef Tpetra::KokkosClassic::DefaultNode::DefaultNodeType Node;
34
35 #include <Xpetra_MultiVectorFactory.hpp>
36 #include <Xpetra_ImportFactory.hpp>
37 #include <Xpetra_IO.hpp>
38
39 #include <Galeri_XpetraParameters.hpp>
40 #include <Galeri_XpetraProblemFactory.hpp>
41 #include <Galeri_XpetraUtils.hpp>
42 #include <Galeri_XpetraMaps.hpp>
43
44 #include <MueLu.hpp>
45 #include <MueLu_Level.hpp>
46 #include <MueLu_ParameterListInterpreter.hpp>
47 #include <MueLu_Utilities.hpp>
48 #include <MueLu_SemiCoarsenPFactory_decl.hpp>
49 #include "Teuchos_ScalarTraits.hpp"
50
51 #ifdef HAVE_MUELU_BELOS
52 #include <BelosConfigDefs.hpp>
53 #include <BelosLinearProblem.hpp>
54 #include <BelosBlockCGSolMgr.hpp>
55 #include <BelosPseudoBlockCGSolMgr.hpp>
56 #include <BelosBlockGmresSolMgr.hpp>
57 #include <BelosXpetraAdapter.hpp>
58 #include <BelosMueLuAdapter.hpp>
59 #endif
60
61 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
62 int main_(Teuchos::CommandLineProcessor &clp, Xpetra::UnderlyingLib lib, int argc, char *argv[]) {
63 // Most MueLu and Xpetra classes are templated on some or all of the
64 // following template types: Scalar, LocalOrdinal, GlobalOrdinal,
65 // and Node. In order to make types more concise, MueLu has an
66 // option to let users refer to its classes by typedefs, which we
67 // call "short names." Thus, instead of writing, for instance,
68 //
69 // MueLu::Hierarchy<Scalar,LocalOrdinal,GlobalOrdinal,Node> H;
70 //
71 // one can simply write
72 //
73 // Hierarchy H;
74 //
75 // provided the MueLu_UseShortNames.hpp header and the appropriate
76 // class are included. If one wishes to use short names, one must
77 // include this header file before referring to any of the short
78 // names. One may include it anywhere in the program, but it is
79 // better to include it in the scope where one wants the typedefs
80 // defined. It's better not to include it at global scope, in order
81 // to avoid polluting the global scope with typedefs.
82 #include <MueLu_UseShortNames.hpp>
83
84 // These "using" declarations make the code more concise, in that
85 // you don't have to write the namespace along with the class or
86 // object name. This is especially helpful with commonly used things
87 // like std::endl or Teuchos::RCP.
88 using Teuchos::ParameterList;
89 using Teuchos::RCP;
90 using Teuchos::rcp;
91
92 // Start up MPI, if using MPI. Trilinos doesn't have to be built
93 // with MPI; it's called a "serial" build if you build without MPI.
94 // GlobalMPISession hides this implementation detail.
95 //
96 // Note the third argument. If you pass GlobalMPISession the
97 // address of an std::ostream, it will print a one-line status
98 // message with the rank on each MPI process. This may be
99 // undesirable if running with a large number of MPI processes.
100 // You can avoid printing anything here by passing in either
101 // NULL or the address of a Teuchos::oblackholestream.
102
103 // Get a pointer to the communicator object representing
104 // MPI_COMM_WORLD.
105 //
106 // If we didn't build with MPI, we'll get a serial "communicator",
107 // i.e. a communicator with size 1, whose only process has rank 0.
108 RCP<const Teuchos::Comm<int> > comm = Teuchos::DefaultComm<int>::getComm();
109
110 // Get my process' rank. Equivalent to MPI_Comm_rank.
111 const int myRank = comm->getRank();
112
113 // Teuchos::ScalarTraits provides a traits interface to general
114 // scalar types. This allows the same code to be valid for
115 // different scalar types, like double, complex, or high precision
116 // (i.e., double-double).
117 typedef Teuchos::ScalarTraits<SC> STS;
118 typedef typename STS::magnitudeType MT;
119 SC zero = STS::zero(), one = STS::one();
120
121 // Make an output stream (for verbose output) that only prints on
122 // Process 0 of the communicator.
123 Teuchos::oblackholestream blackHole;
124 std::ostream &out = (myRank == 0) ? std::cout : blackHole;
125
126 // Teuchos provides an interface to get arguments from the command
127 // line. The first argument indicates that we don't want any
128 // exceptions to be thrown during command line parsing.
129
130 // The list of valid parameters for the driver comes from three sources:
131 //
132 // - Galeri parameters: These are responsible for constructing the
133 // problem data (i.e., matrix and coordinates).
134 // - Xpetra parameters: Allow switching between Epetra and Tpetra.
135 // - Driver parameters: These are specified below.
136 GO nx = 6, ny = 5, nz = 163;
137 Galeri::Xpetra::Parameters<GO> galeriParameters(clp, nx, ny, nz, "Laplace3D"); // manage parameters of the test case
138 Xpetra::Parameters xpetraParameters(clp); // manage parameters of Xpetra
139
140 std::string xmlFileName = "driver1.xml";
141 clp.setOption("xml", &xmlFileName, "read parameters from a file [default = 'scalingTest.xml']");
142
143 std::string solveType = "cg";
144 clp.setOption("solver", &solveType, "solve type: (cg | gmres)");
145 double tol = 1e-12;
146 clp.setOption("tol", &tol, "solver convergence tolerance");
147 int maxIts = 200;
148 clp.setOption("its", &maxIts, "maximum number of solver iterations");
149
150 std::string mapFile;
151 clp.setOption("map", &mapFile, "map data file");
152 std::string matrixFile;
153 clp.setOption("matrix", &matrixFile, "matrix data file");
154 std::string coordFile;
155 clp.setOption("coords", &coordFile, "coordinates data file");
156
157 // Command line processor parsing stage
158 switch (clp.parse(argc, argv)) {
159 case Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED: return EXIT_SUCCESS;
160 case Teuchos::CommandLineProcessor::PARSE_ERROR:
161 case Teuchos::CommandLineProcessor::PARSE_UNRECOGNIZED_OPTION: return EXIT_FAILURE;
162 case Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL: break;
163 }
164
165 // Retrieve matrix parameters (they may have been changed on the
166 // command line).
167 ParameterList galeriList = galeriParameters.GetParameterList();
168 // galeriList.set("mx",6); galeriList.set("my",5); galeriList.set("mz",1);
169
170 // Construct the problem data. Typically, we construct the matrix,
171 // coordinates, and nullspace, though only the matrix is mandatory.
172 RCP<Matrix> A;
173 RCP<const Map> map;
174 RCP<MultiVector> coordinates;
175 if (matrixFile.empty()) {
176 // Use Galeri to construct the data
177 //
178 // Galeri provides several pre-defined problem types, including
179 // some stencil based ones (like Laplace matrices in 2D and 3D),
180 // and some others (like elasticity in 2D and 3D)
181 out << "========================================================\n"
182 << xpetraParameters << galeriParameters;
183
184 // Galeri will attempt to create a square-as-possible distribution of
185 // subdomains di, e.g.,
186 //
187 // d1 d2 d3
188 // d4 d5 d6
189 // d7 d8 d9
190 // d10 d11 d12
191 //
192 // A perfect distribution is only possible when the number of
193 // processes is a perfect square. This *will* result in "strip"
194 // distribution if the number of processes is a prime number or if
195 // the factors are very different in size. For example, np=14 will
196 // give a 7-by-2 distribution. If you don't want Galeri to do
197 // this, specify mx or my on the galeriList.
198 std::string matrixType = galeriParameters.GetMatrixType();
199
200 // Create map (Map) and coordinates (MultiVector). Xpetra's Map
201 // and MultiVector imitate Tpetra's interface.
202 if (matrixType == "Laplace1D") {
203 map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian1D", comm, galeriList);
204 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<SC, LO, GO, Map, MultiVector>("1D", map, galeriList);
205
206 } else if (matrixType == "Laplace2D") {
207 map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian2D", comm, galeriList);
208 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<SC, LO, GO, Map, MultiVector>("2D", map, galeriList);
209
210 } else if (matrixType == "Laplace3D") {
211 map = Galeri::Xpetra::CreateMap<LO, GO, Node>(xpetraParameters.GetLib(), "Cartesian3D", comm, galeriList);
212 coordinates = Galeri::Xpetra::Utils::CreateCartesianCoordinates<SC, LO, GO, Map, MultiVector>("3D", map, galeriList);
213 }
214
215 out << "Processor subdomains in x direction: " << galeriList.get<int>("mx") << std::endl
216 << "Processor subdomains in y direction: " << galeriList.get<int>("my") << std::endl
217 << "Processor subdomains in z direction: " << galeriList.get<int>("mz") << std::endl
218 << "========================================================" << std::endl;
219
220 // Construct the matrix based on the problem name and provided
221 // parameters.
222 RCP<Galeri::Xpetra::Problem<Map, CrsMatrixWrap, MultiVector> > Pr =
223 Galeri::Xpetra::BuildProblem<SC, LO, GO, Map, CrsMatrixWrap, MultiVector>(galeriParameters.GetMatrixType(), map, galeriList);
224 A = Pr->BuildMatrix();
225
226 } else {
227 // Read in data
228 //
229 // This is a convenient way to use the driver, provided you have
230 // some custom data you want to run. Typically, you need a Map
231 // (though you may avoid that in a serial run), a matrix (in a
232 // MatrixMarket format), and a file with coordinates.
233 if (!mapFile.empty())
234 map = Xpetra::IO<SC, LO, GO, Node>::ReadMap(mapFile, xpetraParameters.GetLib(), comm);
235
236 A = Xpetra::IO<SC, LO, GO, Node>::Read(matrixFile, map);
237
238 if (!coordFile.empty())
239 coordinates = Xpetra::IO<SC, LO, GO, Node>::ReadMultiVector(coordFile, map);
240 }
241
242 // For scalar equations, we assume that the constant vector is a
243 // good approximate nullspace. Note, though, that we may skip this
244 // step as this is also a default nullspace in MueLu, if user has
245 // not provided it.
246 RCP<MultiVector> nullspace = MultiVectorFactory::Build(map, 1);
247 nullspace->putScalar(one);
248
249 out << "Galeri complete.\n========================================================" << std::endl;
250 std::cout << coordinates << std::endl;
251
252 // Hierarchy is a key concept in MueLu. Once set up, it has all the
253 // data required to apply the preconditioner. MueLu provides
254 // multiple interfaces to construct a Hierarchy. The first one is a
255 // C++ interface, which is suitable for advanced users. The second
256 // one is a XML file interface, used in this driver. You may find
257 // the documentation for the interface and a list of parameter names
258 // in Trilinos/packages/muelu/doc/UsersGuide.
259 //
260 // HierarchyManager creates a Hierarchy object based on an XML file
261 // containing the parameters. Only Process 0 reads from this file.
262 // We additionally provide a communicator, so that Process 0 can
263 // broadcast the parameters to all other processes.
264 RCP<HierarchyManager> mueLuFactory =
265 rcp(new ParameterListInterpreter(xmlFileName, *comm));
266
267 // The CreateHierarchy() call creates a Hierarchy object. This
268 // object is not set up, though, so it cannot be used yet.
269 RCP<Hierarchy> H = mueLuFactory->CreateHierarchy();
270
271 // All hierarchies have at least one level: the finest level, which
272 // must contain the user's matrix. The finest level is level 0, and
273 // subsequent coarser levels have increasing indices. This way, if
274 // we have L levels, level 0 corresponds to the finest level, and
275 // level L-1 is the coarsest level.
276 RCP<Level> L = H->GetLevel(0);
277
278 // Setting the finest level matrix is mandatory in MueLu. However,
279 // setting the nullspace and coordinates is optional. If nullspace
280 // is not provided, it is automatically generated to be a constant
281 // vector. Coordinates are needed only in two cases: if one uses
282 // distance Laplacian filtering, or one uses repartitioning (which
283 // is based on geometric partitioning).
284 L->Set("A", A);
285 L->Set("Nullspace", nullspace);
286
287 /*
288 if (!coordinates.is_null())
289 L->Set("Coordinates", coordinates);
290 */
291
292 Teuchos::ArrayRCP<LO> SemiCoarsenInfo = Teuchos::arcp<LO>(3);
293 SemiCoarsenInfo[NUM_ZPTS] = nz;
294 SemiCoarsenInfo[ORIENTATION] = VERTICAL;
295 // L->Set("SemiCoarsenInfo",SemiCoarsenInfo, MueLu::NoFactory::get() );
296 L->Set("SemiCoarsenInfo", SemiCoarsenInfo);
297
298 printf("before level print\n");
299 L->print(std::cout, Teuchos::VERB_EXTREME);
300 printf("after level print\n");
301
302 // Now that we have set the mandatory data, we can construct the
303 // preconditioner. The result of this is a fully constructed
304 // hierarchy, which can be used to solve the linear system.
305 mueLuFactory->SetupHierarchy(*H);
306
307 // Multigrid methods can be used in a standalone fashion, or they
308 // can be used to precondition a Krylov method. Typically, the
309 // second method is preferred, which is indicated by the argument of
310 // IsPreconditioner function.
311 H->IsPreconditioner(true);
312
313 // To complete the problem description, we construct an initial
314 // guess X and a right-hand side B (of the linear system AX=B). Both
315 // have the same Map as A's row Map.
316 RCP<Vector> X = VectorFactory::Build(map);
317 RCP<Vector> B = VectorFactory::Build(map);
318
319 // For this test problem, we determine the exact solution first (as
320 // a random vector), and compute B so that AX=B exactly. We then
321 // make X an initial guess vector by filling it with zeros. You may
322 // use any initial guess you like.
323 {
324 // We set seed for reproducibility
325 Utilities::SetRandomSeed(*comm);
326 X->randomize();
327 A->apply(*X, *B, Teuchos::NO_TRANS, one, zero);
328
329 Teuchos::Array<MT> norms(1);
330 B->norm2(norms);
331 B->scale(one / norms[0]);
332 X->putScalar(zero);
333 }
334 #ifdef HAVE_MUELU_BELOS
335 typedef MultiVector MV;
336 typedef Belos::OperatorT<MV> OP;
337
338 // Internally, Belos uses its own types. We use special wrappers to
339 // wrap MueLu and Xpetra objects into Belos operators. This is only
340 // one of many different ways one could choose to wrap MueLu and
341 // Xpetra objects in order to get them to work with Belos.
342 RCP<OP> belosOp = rcp(new Belos::XpetraOp<SC, LO, GO, NO>(A));
343 RCP<OP> belosPrec = rcp(new Belos::MueLuOp<SC, LO, GO, NO>(H));
344
345 // Construct a Belos LinearProblem object. This is a complete
346 // problem formulation. All the data necessary to solve the system
347 // are now inside that problem.
348 RCP<Belos::LinearProblem<SC, MV, OP> > belosProblem =
349 rcp(new Belos::LinearProblem<SC, MV, OP>(belosOp, X, B));
350 belosProblem->setRightPrec(belosPrec);
351
352 // Prepare the linear problem to solve the linear system that was
353 // already passed in.
354 bool set = belosProblem->setProblem();
355 if (!set) {
356 out << "\nERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
357 return EXIT_FAILURE;
358 }
359
360 // As many packages in Trilinos, Belos provides a parameter list
361 // interface. This lets users easily change solver behavior, like
362 // the number of iterations or its verbosity. For a full list of
363 // Belos parameters, please consult the Belos package documentation.
364 ParameterList belosList;
365 belosList.set("Maximum Iterations", maxIts); // Maximum number of iterations allowed
366 belosList.set("Convergence Tolerance", tol); // Relative convergence tolerance requested
367 belosList.set("Verbosity", Belos::Errors + Belos::Warnings + Belos::StatusTestDetails);
368 belosList.set("Output Frequency", 1);
369 belosList.set("Output Style", Belos::Brief);
370
371 // Create a Belos iterative linear solver
372 //
373 // Belos provides multiple iterative linear solvers, with CG and
374 // GMRES being most popular. Based on a command line argument, we
375 // select the proper one. Note that the C++ objects are templated
376 // on scalar, multivector and operator. This is due to the traits
377 // interface in Belos.
378 RCP<Belos::SolverManager<SC, MV, OP> > solver;
379 if (solveType == "cg")
380 solver = rcp(new Belos::PseudoBlockCGSolMgr<SC, MV, OP>(belosProblem, rcp(&belosList, false)));
381 else if (solveType == "gmres")
382 solver = rcp(new Belos::BlockGmresSolMgr<SC, MV, OP>(belosProblem, rcp(&belosList, false)));
383
384 // Finally, perform the solve. We wrap it in a try-catch block,
385 // since Belos indicates erros by throwing exceptions.
386 Belos::ReturnType ret = Belos::Unconverged;
387 try {
388 ret = solver->solve();
389
390 // Get the number of iterations for this solve.
391 out << "Converged in " << solver->getNumIters() << " iterations" << std::endl;
392
393 } catch (...) {
394 out << std::endl
395 << "ERROR: Belos threw an error! " << std::endl;
396 }
397
398 // Check convergence
399 if (ret != Belos::Converged)
400 out << std::endl
401 << "ERROR: Belos did not converge! " << std::endl;
402 else
403 out << std::endl
404 << "SUCCESS: Belos converged!" << std::endl;
405 #else
406 out << std::endl
407 << "MueLu has been compiled without Belos support!" << std::endl;
408 #endif
409 // GlobalMPISession calls MPI_Finalize() in its destructor, if
410 // appropriate. You don't have to do anything here! Just return
411 // from main(). Isn't that helpful?
412 return 0;
413 }
414
415 //- -- --------------------------------------------------------
416 #define MUELU_AUTOMATIC_TEST_ETI_NAME main_
417 #include "MueLu_Test_ETI.hpp"
418
419 int main(int argc, char *argv[]) {
420 return Automatic_Test_ETI(argc, argv);
421 }