Debian Codegraph @

packages/trilinoscouplings/examples/scaling/IntrepidPoisson_Pamgen_Tpetra_main.cpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // Trilinos: An Object-Oriented Solver Framework
4 //
5 // Copyright 2001-2024 NTESS and the Trilinos contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 /** \file IntrepidPoisson_Pamgen_Tpetra_main.cpp
11 \brief Example: Discretize Poisson's equation with Dirichlet
12 boundary conditions on a hexahedral mesh using nodal
13 (Hgrad) elements. The system is assembled into Tpetra data
14 structures, and optionally solved.
15
16 This example uses the following Trilinos packages:
17 \li Pamgen to generate a Hexahedral mesh.
18 \li Sacado to form the source term from user-specified manufactured solution.
19 \li Intrepid to build the discretization matrix and right-hand side.
20 \li Tpetra to handle the global sparse matrix and dense vector.
21
22 \verbatim
23
24 Poisson system:
25
26 div A grad u = f in Omega
27 u = g on Gamma
28
29 where
30 A is a material tensor (typically symmetric positive definite)
31 f is a given source term
32
33 Corresponding discrete linear system for nodal coefficients(x):
34
35 Kx = b
36
37 K - HGrad stiffness matrix
38 b - right hand side vector
39
40 \endverbatim
41
42 \author Created by P. Bochev, D. Ridzal, K. Peterson,
43 D. Hensinger, C. Siefert. Converted to Tpetra by
44 I. Kalashnikova ([email protected]). Modified by Mark
45 Hoemmen ([email protected]) and a bunch of other people.
46
47 \remark Use the "--help" command-line argument for usage info.
48
49 \remark Example driver has an option to use an input file (XML
50 serialization of a Teuchos::ParameterList) containing a
51 Pamgen mesh description. A version, Poisson.xml, is
52 included in the same directory as this driver. If not
53 included, this program will use a default mesh
54 description.
55
56 \remark The exact solution (u) and material tensor (A) are set in
57 the functions "exactSolution" and "materialTensor" and may
58 be modified by the user. We compute the source term f
59 from u using Sacado automatic differentiation, so that u
60 really is the exact solution. The current implementation
61 of exactSolution() has notes to guide your choice of
62 solution. For example, you might want to pick a solution
63 in the finite element space, so that the discrete solution
64 is exact if the solution of the linear system is exact
65 (modulo rounding error when constructing the linear
66 system).
67 */
68
69 #include <cstdlib>
70 #include "Teuchos_oblackholestream.hpp"
71 #include "Teuchos_TimeMonitor.hpp"
72 #include "Teuchos_XMLParameterListHelpers.hpp"
73 #include "Teuchos_StandardCatchMacros.hpp"
74
75 #include "TrilinosCouplings_config.h"
76 #include "TrilinosCouplings_TpetraIntrepidPoissonExample.hpp"
77 #include "TrilinosCouplings_IntrepidPoissonExampleHelpers.hpp"
78
79 #ifdef HAVE_TRILINOSCOUPLINGS_MUELU
80 # include "MueLu_CreateTpetraPreconditioner.hpp"
81
82 #ifdef HAVE_TRILINOSCOUPLINGS_AVATAR
83 # include "MueLu_AvatarInterface.hpp"
84 #endif //HAVE_TRILINOSCOUPLINGS_AVATAR
85
86 #endif // HAVE_TRILINOSCOUPLINGS_MUELU
87
88 #include "Tpetra_Core.hpp"
89 #include "MatrixMarket_Tpetra.hpp"
90
91 int
92 main (int argc, char *argv[])
93 {
94 using namespace TrilinosCouplings; // Yes, this means I'm lazy.
95
96 using TpetraIntrepidPoissonExample::exactResidualNorm;
97 using TpetraIntrepidPoissonExample::makeMatrixAndRightHandSide;
98 using TpetraIntrepidPoissonExample::solveWithBelos;
99 using TpetraIntrepidPoissonExample::solveWithBelosGPU;
100 using namespace IntrepidPoissonExample;
101 using Teuchos::Comm;
102 using Teuchos::outArg;
103 using Teuchos::ParameterList;
104 using Teuchos::parameterList;
105 using Teuchos::RCP;
106 using Teuchos::rcp;
107 using Teuchos::rcpFromRef;
108 using Teuchos::getFancyOStream;
109 using Teuchos::FancyOStream;
110 using std::endl;
111 // Pull in typedefs from the example's namespace.
112 typedef TpetraIntrepidPoissonExample::ST ST;
113 #ifdef HAVE_TRILINOSCOUPLINGS_MUELU
114 typedef TpetraIntrepidPoissonExample::LO LO;
115 typedef TpetraIntrepidPoissonExample::GO GO;
116 #endif // HAVE_TRILINOSCOUPLINGS_MUELU
117 typedef TpetraIntrepidPoissonExample::Node Node;
118 typedef Teuchos::ScalarTraits<ST> STS;
119 typedef STS::magnitudeType MT;
120 typedef Teuchos::ScalarTraits<MT> STM;
121 typedef TpetraIntrepidPoissonExample::sparse_matrix_type sparse_matrix_type;
122 typedef TpetraIntrepidPoissonExample::vector_type vector_type;
123 typedef TpetraIntrepidPoissonExample::multivector_type multivector_type;
124 typedef TpetraIntrepidPoissonExample::operator_type operator_type;
125
126 bool success = true;
127 try {
128 Teuchos::oblackholestream blackHole;
129 Tpetra::ScopeGuard mpiSession (&argc, &argv);
130 RCP<const Comm<int> > comm = Tpetra::getDefaultComm ();
131
132 const int myRank = comm->getRank ();
133 //const int numProcs = comm->getSize ();
134
135 // Did the user specify --help at the command line to print help
136 // with command-line arguments?
137 bool printedHelp = false;
138 // Values of command-line arguments.
139 int nx, ny, nz;
140 std::string xmlInputParamsFile;
141 bool verbose, debug;
142 int maxNumItersFromCmdLine = -1; // -1 means "read from XML file"
143 double tolFromCmdLine = -1.0; // -1 means "read from XML file"
144 std::string solverName = "GMRES";
145 ST materialTensorOffDiagonalValue = Teuchos::ScalarTraits<ST>::nan();
146 std::vector<double> diff_rotation_angle {0.0, 0.0, 0.0};
147 std::vector<double> diff_strength {1.0, 1.0, 1.0};
148 Teuchos::ParameterList problemStatistics;
149
150 // Set default values of command-line arguments.
151 setCommandLineArgumentDefaults (nx, ny, nz, xmlInputParamsFile,
152 solverName, verbose, debug);
153 // Parse and validate command-line arguments.
154 Teuchos::CommandLineProcessor cmdp (false, true);
155 setUpCommandLineArguments (cmdp, nx, ny, nz, xmlInputParamsFile,
156 solverName, tolFromCmdLine,
157 maxNumItersFromCmdLine,
158 verbose, debug);
159
160 // Diffusion tensor information (if we're using it)
161 cmdp.setOption ("materialTensorOffDiagonalValue",
162 &materialTensorOffDiagonalValue, "Off-diagonal value in "
163 "the material tensor. This controls the iteration count. "
164 "Be careful with this if you use CG, since you can easily "
165 "make the matrix indefinite.");
166 for(int i=0; i<3; i++) {
167 char letter[4] = "xyz";
168 char str1[80], str2[80];
169 // Rotation
170 sprintf(str1,"rot_%c_angle",letter[i]);
171 sprintf(str2,"Rotation around %c axis, in degrees",letter[i]);
172 cmdp.setOption(str1,&diff_rotation_angle[i],str2);
173
174 // Strength
175 sprintf(str1,"strength_%c",letter[i]);
176 sprintf(str2,"Strength of pre-rotation %c-diffusion",letter[i]);
177 cmdp.setOption(str1,&diff_strength[i],str2);
178 }
179
180 // Additional command-line arguments for GPU experimentation.
181 bool gpu = false;
182 cmdp.setOption ("gpu", "no-gpu", &gpu,
183 "Run example using GPU node (if supported)");
184 int ranks_per_node = 1;
185 cmdp.setOption ("ranks_per_node", &ranks_per_node,
186 "Number of MPI ranks per node");
187 int gpu_ranks_per_node = 1;
188 cmdp.setOption ("gpu_ranks_per_node", &gpu_ranks_per_node,
189 "Number of MPI ranks per node for GPUs");
190 int device_offset = 0;
191 cmdp.setOption ("device_offset", &device_offset,
192 "Offset for attaching MPI ranks to CUDA devices");
193
194 // Additional command-line arguments for dumping the generated
195 // matrix or its row Map to output files.
196 //
197 // FIXME (mfh 09 Apr 2014) Need to port these command-line
198 // arguments to the Epetra version.
199
200 // If matrixFilename is nonempty, dump the matrix to that file
201 // in MatrixMarket format.
202 std::string matrixFilename;
203 cmdp.setOption ("matrixFilename", &matrixFilename, "If nonempty, dump the "
204 "generated matrix to that file in MatrixMarket format.");
205
206 // If coordsFilename is nonempty, dump the coords to that file
207 // in MatrixMarket format.
208 std::string coordsFilename;
209 cmdp.setOption ("coordsFilename", &coordsFilename, "If nonempty, dump the "
210 "generated coordinates to that file in MatrixMarket format.");
211
212 // If rowMapFilename is nonempty, dump the matrix's row Map to
213 // that file in MatrixMarket format.
214 std::string rowMapFilename;
215 cmdp.setOption ("rowMapFilename", &rowMapFilename, "If nonempty, dump the "
216 "generated matrix's row Map to that file in a format that "
217 "Tpetra::MatrixMarket::Reader can read.");
218 // Option to exit after building A and b (and dumping stuff to
219 // files, if requested).
220 bool exitAfterAssembly = false;
221 cmdp.setOption ("exitAfterAssembly", "dontExitAfterAssembly",
222 &exitAfterAssembly, "If true, exit after building the "
223 "sparse matrix and dense right-hand side vector. If "
224 " --matrixFilename --coordsFilename or --rowMapFilename are nonempty strings"
225 ", dump the matrix resp. row Map to their respective files "
226 "before exiting.");
227
228 // Option to exit after building the preconditioner
229 bool exitAfterPrecond = false;
230 cmdp.setOption ("exitAfterPrecond", "dontExitAfterPrecond",
231 &exitAfterPrecond, "If true, exit after building the "
232 "preconditioner.");
233
234 // Number of rebuilds of the MueLu hierarchy
235 int numMueluRebuilds=0;
236 cmdp.setOption ("rebuild", &numMueluRebuilds, "Number of times to rebuild the MueLu hierarchy.");
237
238 // Random number seed
239 int randomSeed=24601;
240 cmdp.setOption ("seed", &randomSeed, "Random Seed.");
241
242 parseCommandLineArguments (cmdp, printedHelp, argc, argv, nx, ny, nz,
243 xmlInputParamsFile, solverName, verbose, debug);
244 if (printedHelp) {
245 // The user specified --help at the command line to print help
246 // with command-line arguments. We printed help already, so quit
247 // with a happy return code.
248 return EXIT_SUCCESS;
249 }
250
251 // Initialize RNG
252 srand(randomSeed);
253
254
255 // Set material information
256 if(Teuchos::ScalarTraits<ST>::isnaninf(materialTensorOffDiagonalValue))
257 setDiffusionRotationAndStrength(diff_rotation_angle, diff_strength);
258 else
259 setMaterialTensorOffDiagonalValue (materialTensorOffDiagonalValue);
260
261 // Both streams only print on MPI Rank 0. "out" only prints if the
262 // user specified --verbose.
263 RCP<FancyOStream> out =
264 getFancyOStream (rcpFromRef ((myRank == 0 && verbose) ? std::cout : blackHole));
265 RCP<FancyOStream> err =
266 getFancyOStream (rcpFromRef ((myRank == 0 && debug) ? std::cerr : blackHole));
267
268 #ifdef HAVE_MPI
269 *out << "PARALLEL executable" << endl;
270 #else
271 *out << "SERIAL executable" << endl;
272 #endif
273
274 if(useDiffusionMatrix()) {
275 const std::vector<double> & A = getDiffusionMatrix();
276 *out<<"[ "<<A[0]<<" "<<A[1]<<" "<<A[2]<<" ]\n"
277 <<"[ "<<A[3]<<" "<<A[4]<<" "<<A[5]<<" ]\n"
278 <<"[ "<<A[6]<<" "<<A[7]<<" "<<A[8]<<" ]"<<std::endl;
279 }
280 else {
281 *out<<"off diagonal value = "<<materialTensorOffDiagonalValue<<std::endl;
282 }
283
284 /**********************************************************************************/
285 /********************************** GET XML INPUTS ********************************/
286 /**********************************************************************************/
287 ParameterList inputList;
288 if (xmlInputParamsFile != "") {
289 *out << "Reading parameters from XML file \""
290 << xmlInputParamsFile << "\"..." << endl;
291 Teuchos::updateParametersFromXmlFile (xmlInputParamsFile,
292 outArg (inputList));
293 if (myRank == 0) {
294 inputList.print (*out, 2, true, true);
295 *out << endl;
296 }
297 }
298
299 // Get Pamgen mesh definition string, either from the input
300 // ParameterList or from our function that makes a cube and fills in
301 // the number of cells along each dimension.
302 std::string meshInput = inputList.get("meshInput", "");
303 if (meshInput == "") {
304 *out << "Generating mesh input string: nx = " << nx
305 << ", ny = " << ny
306 << ", nz = " << nz << endl;
307 meshInput = makeMeshInput (nx, ny, nz);
308 }
309
310 // Total application run time
311 {
312 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Time", total_time);
313
314 RCP<sparse_matrix_type> A;
315 RCP<vector_type> B, X_exact, X, node_sigma;
316 RCP<multivector_type> coords;
317 {
318 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Assembly", total_assembly);
319 makeMatrixAndRightHandSide (A, B, X_exact, X, coords, node_sigma, comm, meshInput, inputList, problemStatistics,
320 out, err, verbose, debug);
321 }
322
323 // Print Problem Statistics
324 *out<<"*** Problem Statistics ***\n"<<problemStatistics<<std::endl;
325
326 // Optionally dump the matrix and/or its row Map to files.
327 {
328 typedef Tpetra::MatrixMarket::Writer<sparse_matrix_type> writer_type;
329 if (matrixFilename != "") {
330 writer_type::writeSparseFile (matrixFilename, A);
331 }
332 if (coordsFilename != "") {
333 writer_type::writeDenseFile (coordsFilename, coords);
334 }
335 if (rowMapFilename != "") {
336 writer_type::writeMapFile (rowMapFilename, * (A->getRowMap ()));
337 }
338 }
339
340 if (exitAfterAssembly) {
341 // Users might still be interested in assembly time.
342 Teuchos::TimeMonitor::report (comm.ptr (), std::cout);
343 return EXIT_SUCCESS;
344 }
345
346 const std::vector<MT> norms = exactResidualNorm (A, B, X_exact);
347 // X_exact is the exact solution of the PDE, projected onto the
348 // discrete mesh. It may not necessarily equal the exact solution
349 // of the linear system.
350 *out << "||B - A*X_exact||_2 = " << norms[0] << endl
351 << "||B||_2 = " << norms[1] << endl
352 << "||A||_F = " << norms[2] << endl;
353
354
355 // Setup preconditioner
356 std::string prec_type = inputList.get ("Preconditioner", "None");
357 RCP<operator_type> M;
358 RCP<operator_type> opA(A);
359 {
360 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Preconditioner Setup", total_prec);
361
362 if (prec_type == "MueLu") {
363 #ifdef HAVE_TRILINOSCOUPLINGS_MUELU
364 #ifdef HAVE_TRILINOSCOUPLINGS_AVATAR
365 // If we have Avatar, then let's use it
366 if (inputList.isSublist("Avatar-MueLu")) {
367 // NOTE: User will need to make sure these are named consistently with the tree files specified
368 ParameterList problemFeatures = problemStatistics;
369 ParameterList avatarParams = inputList.sublist("Avatar-MueLu");
370 ParameterList & mueluParams = inputList.sublist("MueLu");
371
372 *out<<"*** Avatar Parameters ***\n"<<avatarParams<<std::endl;
373
374 MueLu::AvatarInterface avatar(comm,avatarParams);
375 *out<<"*** Avatar Setup ***"<<std::endl;
376 avatar.Setup();
377 avatar.SetMueLuParameters(problemFeatures,mueluParams, true);
378 // Do this twice to make sure this guy is re-callable.
379 avatar.SetMueLuParameters(problemFeatures,mueluParams, true);
380
381 *out<<"*** Updated MueLu Parameters ***\n"<<mueluParams<<std::endl;
382 avatar.Cleanup();
383 }
384 #endif
385 for(int i=0; i<numMueluRebuilds+1; i++) {
386 if (inputList.isSublist("MueLu")) {
387 ParameterList mueluParams = inputList.sublist("MueLu");
388 mueluParams.sublist("user data").set("Coordinates",coords);
389 M = MueLu::CreateTpetraPreconditioner<ST,LO,GO,Node>(opA,mueluParams);
390 } else {
391 M = MueLu::CreateTpetraPreconditioner<ST,LO,GO,Node>(opA);
392 }
393 }
394 #else // NOT HAVE_TRILINOSCOUPLINGS_MUELU
395 TEUCHOS_TEST_FOR_EXCEPTION(
396 prec_type == "MueLu", std::runtime_error, "Tpetra scaling example: "
397 "In order to precondition with MueLu, you must have built Trilinos "
398 "with the MueLu package enabled.");
399 #endif // HAVE_TRILINOSCOUPLINGS_MUELU
400 }
401 } // setup preconditioner
402
403
404 // exit if we only wanted the preconditioner
405 if(exitAfterPrecond) {
406 Teuchos::TimeMonitor::report (comm.ptr (), std::cout);
407 return EXIT_SUCCESS;
408 }
409
410
411 // Get the convergence tolerance for each linear solve.
412 // If the user provided a nonnegative value at the command
413 // line, it overrides any value in the input ParameterList.
414 MT tol = STM::squareroot (STM::eps ()); // default value
415 if (tolFromCmdLine < STM::zero ()) {
416 tol = inputList.get ("Convergence Tolerance", tol);
417 } else {
418 tol = tolFromCmdLine;
419 }
420
421 // Get the maximum number of iterations for each linear solve.
422 // If the user provided a value other than -1 at the command
423 // line, it overrides any value in the input ParameterList.
424 int maxNumIters = 200; // default value
425 if (maxNumItersFromCmdLine == -1) {
426 maxNumIters = inputList.get ("Maximum Iterations", maxNumIters);
427 } else {
428 maxNumIters = maxNumItersFromCmdLine;
429 }
430
431 // Get the number of "time steps." We imitate a time-dependent
432 // PDE by doing this many linear solves.
433 const int num_steps = inputList.get ("Number of Time Steps", 1);
434
435 // Do the linear solve(s).
436 bool converged = false;
437 int numItersPerformed = 0;
438 if (gpu) {
439 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total GPU Solve", total_solve);
440 solveWithBelosGPU (converged, numItersPerformed, tol, maxNumIters,
441 num_steps, ranks_per_node, gpu_ranks_per_node,
442 device_offset, prec_type, X, A, B, Teuchos::null, M);
443 }
444 else {
445 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Solve", total_solve);
446 solveWithBelos (converged, numItersPerformed, solverName, tol,
447 maxNumIters, num_steps, X, A, B, Teuchos::null, M);
448 }
449
450 *out<<"Total Iterations: "<<numItersPerformed<<std::endl;
451
452 // Compute ||X-X_exact||_2
453 const MT norm_x = X_exact->norm2 ();
454 X_exact->update (-1.0, *X, 1.0);
455 const MT norm_error = X_exact->norm2 ();
456 *out << endl
457 << "||X - X_exact||_2 / ||X_exact||_2 = " << norm_error / norm_x
458 << endl;
459 } // total time block
460
461 // Summarize timings
462 Teuchos::TimeMonitor::report (comm.ptr (), std::cout);
463 } // try
464 TEUCHOS_STANDARD_CATCH_STATEMENTS(true, std::cerr, success);
465
466 if (success) {
467 return EXIT_SUCCESS;
468 } else {
469 return EXIT_FAILURE;
470 }
471 }