Debian Codegraph @

packages/trilinoscouplings/examples/scaling/StructuredIntrepidPoisson_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 "Teuchos_oblackholestream.hpp"
70 #include "Teuchos_TimeMonitor.hpp"
71 #include "Teuchos_XMLParameterListHelpers.hpp"
72 #include "Teuchos_StandardCatchMacros.hpp"
73
74 #include "TrilinosCouplings_config.h"
75 #include "TrilinosCouplings_TpetraIntrepidStructuredPoissonExample.hpp"
76 #include "TrilinosCouplings_IntrepidPoissonExampleHelpers.hpp"
77
78 #ifdef HAVE_TRILINOSCOUPLINGS_MUELU
79 # include "MueLu_CreateTpetraPreconditioner.hpp"
80 #endif // HAVE_TRILINOSCOUPLINGS_MUELU
81
82 #include "Tpetra_Core.hpp"
83 #include "MatrixMarket_Tpetra.hpp"
84
85 int
86 main (int argc, char *argv[])
87 {
88 using namespace TrilinosCouplings; // Yes, this means I'm lazy.
89
90 using TpetraIntrepidPoissonExample::exactResidualNorm;
91 using TpetraIntrepidPoissonExample::makeMatrixAndRightHandSide;
92 using TpetraIntrepidPoissonExample::solveWithBelos;
93 using TpetraIntrepidPoissonExample::solveWithBelosGPU;
94 using IntrepidPoissonExample::makeMeshInput;
95 using IntrepidPoissonExample::parseCommandLineArguments;
96 using IntrepidPoissonExample::setCommandLineArgumentDefaults;
97 using IntrepidPoissonExample::setMaterialTensorOffDiagonalValue;
98 using IntrepidPoissonExample::setUpCommandLineArguments;
99 using Teuchos::Comm;
100 using Teuchos::outArg;
101 using Teuchos::ParameterList;
102 using Teuchos::parameterList;
103 using Teuchos::RCP;
104 using Teuchos::rcp;
105 using Teuchos::rcpFromRef;
106 using Teuchos::getFancyOStream;
107 using Teuchos::FancyOStream;
108 using std::endl;
109 // Pull in typedefs from the example's namespace.
110 typedef TpetraIntrepidPoissonExample::ST ST;
111 #ifdef HAVE_TRILINOSCOUPLINGS_MUELU
112 typedef TpetraIntrepidPoissonExample::LO LO;
113 typedef TpetraIntrepidPoissonExample::GO GO;
114 #else
115 typedef TpetraIntrepidPoissonExample::sparse_matrix_type::local_ordinal_type LO;
116 typedef TpetraIntrepidPoissonExample::sparse_matrix_type::global_ordinal_type GO;
117 #endif // HAVE_TRILINOSCOUPLINGS_MUELU
118 typedef TpetraIntrepidPoissonExample::Node Node;
119 typedef TpetraIntrepidPoissonExample::MT 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::realmultivector_type realmultivector_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 = 0.0;
146
147 // Set default values of command-line arguments.
148 setCommandLineArgumentDefaults (nx, ny, nz, xmlInputParamsFile,
149 solverName, verbose, debug);
150 // Parse and validate command-line arguments.
151 Teuchos::CommandLineProcessor cmdp (false, true);
152 setUpCommandLineArguments (cmdp, nx, ny, nz, xmlInputParamsFile,
153 solverName, tolFromCmdLine,
154 maxNumItersFromCmdLine,
155 verbose, debug);
156 cmdp.setOption ("materialTensorOffDiagonalValue",
157 &materialTensorOffDiagonalValue, "Off-diagonal value in "
158 "the material tensor. This controls the iteration count. "
159 "Be careful with this if you use CG, since you can easily "
160 "make the matrix indefinite.");
161
162 // Additional command-line arguments for GPU experimentation.
163 bool gpu = false;
164 cmdp.setOption ("gpu", "no-gpu", &gpu,
165 "Run example using GPU node (if supported)");
166 int ranks_per_node = 1;
167 cmdp.setOption ("ranks_per_node", &ranks_per_node,
168 "Number of MPI ranks per node");
169 int gpu_ranks_per_node = 1;
170 cmdp.setOption ("gpu_ranks_per_node", &gpu_ranks_per_node,
171 "Number of MPI ranks per node for GPUs");
172 int device_offset = 0;
173 cmdp.setOption ("device_offset", &device_offset,
174 "Offset for attaching MPI ranks to CUDA devices");
175
176 // Additional command-line arguments for dumping the generated
177 // matrix or its row Map to output files.
178 //
179 // FIXME (mfh 09 Apr 2014) Need to port these command-line
180 // arguments to the Epetra version.
181
182 // If matrixFilename is nonempty, dump the matrix to that file
183 // in MatrixMarket format.
184 std::string matrixFilename;
185 cmdp.setOption ("matrixFilename", &matrixFilename, "If nonempty, dump the "
186 "generated matrix to that file in MatrixMarket format.");
187
188 // If rowMapFilename is nonempty, dump the matrix's row Map to
189 // that file in MatrixMarket format.
190 std::string rowMapFilename;
191 cmdp.setOption ("rowMapFilename", &rowMapFilename, "If nonempty, dump the "
192 "generated matrix's row Map to that file in a format that "
193 "Tpetra::MatrixMarket::Reader can read.");
194 // Option to exit after building A and b (and dumping stuff to
195 // files, if requested).
196 bool exitAfterAssembly = false;
197 cmdp.setOption ("exitAfterAssembly", "dontExitAfterAssembly",
198 &exitAfterAssembly, "If true, exit after building the "
199 "sparse matrix and dense right-hand side vector. If either"
200 " --matrixFilename or --rowMapFilename are nonempty strings"
201 ", dump the matrix resp. row Map to their respective files "
202 "before exiting.");
203
204 // Option to exit after building the preconditioner
205 bool exitAfterPrecond = false;
206 cmdp.setOption ("exitAfterPrecond", "dontExitAfterPrecond",
207 &exitAfterPrecond, "If true, exit after building the "
208 "preconditioner.");
209
210
211 // If matrixFilename is nonempty, dump the matrix to that file
212 // in MatrixMarket format.
213 int numMueluRebuilds=0;
214 cmdp.setOption ("rebuild", &numMueluRebuilds, "Number of times to rebuild the MueLu hierarchy.");
215
216 parseCommandLineArguments (cmdp, printedHelp, argc, argv, nx, ny, nz,
217 xmlInputParamsFile, solverName, verbose, debug);
218 if (printedHelp) {
219 // The user specified --help at the command line to print help
220 // with command-line arguments. We printed help already, so quit
221 // with a happy return code.
222 return EXIT_SUCCESS;
223 }
224
225 setMaterialTensorOffDiagonalValue (materialTensorOffDiagonalValue);
226
227 // Both streams only print on MPI Rank 0. "out" only prints if the
228 // user specified --verbose.
229 RCP<FancyOStream> out =
230 getFancyOStream (rcpFromRef ((myRank == 0 && verbose) ? std::cout : blackHole));
231 RCP<FancyOStream> err =
232 getFancyOStream (rcpFromRef ((myRank == 0 && debug) ? std::cerr : blackHole));
233
234 #ifdef HAVE_MPI
235 *out << "PARALLEL executable" << endl;
236 #else
237 *out << "SERIAL executable" << endl;
238 #endif
239
240 /**********************************************************************************/
241 /********************************** GET XML INPUTS ********************************/
242 /**********************************************************************************/
243 ParameterList inputList;
244 if (xmlInputParamsFile != "") {
245 *out << "Reading parameters from XML file \""
246 << xmlInputParamsFile << "\"..." << endl;
247 Teuchos::updateParametersFromXmlFile (xmlInputParamsFile,
248 outArg (inputList));
249 if (myRank == 0) {
250 inputList.print (*out, 2, true, true);
251 *out << endl;
252 }
253 }
254
255 // Get Pamgen mesh definition string, either from the input
256 // ParameterList or from our function that makes a cube and fills in
257 // the number of cells along each dimension.
258 std::string meshInput = inputList.get("meshInput", "");
259 if (meshInput == "") {
260 *out << "Generating mesh input string: nx = " << nx
261 << ", ny = " << ny
262 << ", nz = " << nz << endl;
263 meshInput = makeMeshInput (nx, ny, nz);
264 }
265
266 // Total application run time
267 {
268 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Time", total_time);
269
270 RCP<sparse_matrix_type> A;
271 RCP<vector_type> B, X_exact, X;
272 RCP<realmultivector_type> Coordinates;
273 Teuchos::Array<Teuchos::ArrayView<const MT> > coordArrayView(3);
274 Teuchos::Array<Teuchos::Array<MT> > coordsArray(3);
275 Teuchos::Array<LO> lNodesPerDim(3);
276 {
277 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Assembly", total_assembly);
278 makeMatrixAndRightHandSide (A, B, X_exact, X, coordsArray, lNodesPerDim,
279 comm, meshInput, out, err, verbose, debug);
280 }
281 for(int dim = 0; dim < 3; ++dim) {coordArrayView[dim] = coordsArray[dim]();}
282 Coordinates = Teuchos::rcp(new realmultivector_type(A->getRowMap(), coordArrayView(), 3));
283
284 // Optionally dump the matrix and/or its row Map to files.
285 {
286 typedef Tpetra::MatrixMarket::Writer<sparse_matrix_type> writer_type;
287 if (matrixFilename != "") {
288 writer_type::writeSparseFile (matrixFilename, A);
289 }
290 if (rowMapFilename != "") {
291 writer_type::writeMapFile (rowMapFilename, * (A->getRowMap ()));
292 }
293 }
294
295 if (exitAfterAssembly) {
296 // Users might still be interested in assembly time.
297 Teuchos::TimeMonitor::report (comm.ptr (), std::cout);
298 return EXIT_SUCCESS;
299 }
300
301 const std::vector<MT> norms = exactResidualNorm (A, B, X_exact);
302 // X_exact is the exact solution of the PDE, projected onto the
303 // discrete mesh. It may not necessarily equal the exact solution
304 // of the linear system.
305 *out << "||B - A*X_exact||_2 = " << norms[0] << endl
306 << "||B||_2 = " << norms[1] << endl
307 << "||A||_F = " << norms[2] << endl;
308
309 // Setup preconditioner
310 std::string prec_type = inputList.get ("Preconditioner", "None");
311 RCP<operator_type> M;
312 RCP<operator_type> opA(A);
313 {
314 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Preconditioner Setup", total_prec);
315
316 if (prec_type == "MueLu") {
317 #ifdef HAVE_TRILINOSCOUPLINGS_MUELU
318 for(int i=0; i<numMueluRebuilds+1; i++) {
319 if (inputList.isSublist("MueLu")) {
320 ParameterList mueluParams = inputList.sublist("MueLu");
321 const std::string userName = "user data";
322 Teuchos::ParameterList& userParamList = mueluParams.sublist(userName);
323 userParamList.set<RCP<realmultivector_type> >("Coordinates", Coordinates);
324 userParamList.set<Teuchos::Array<LO> >("Array<LO> lNodesPerDim", lNodesPerDim);
325 userParamList.set<int> ("int numDimensions", 3);//TODO: dont hardcode?
326 M = MueLu::CreateTpetraPreconditioner<ST,LO,GO,Node>(opA, mueluParams);
327 } else {
328 M = MueLu::CreateTpetraPreconditioner<ST,LO,GO,Node>(opA);
329 }
330 }
331 #else // NOT HAVE_TRILINOSCOUPLINGS_MUELU
332 TEUCHOS_TEST_FOR_EXCEPTION(
333 prec_type == "MueLu", std::runtime_error, "Tpetra scaling example: "
334 "In order to precondition with MueLu, you must have built Trilinos "
335 "with the MueLu package enabled.");
336 #endif // HAVE_TRILINOSCOUPLINGS_MUELU
337 }
338 } // setup preconditioner
339
340
341 // exit if we only wanted the preconditioner
342 if(exitAfterPrecond) {
343 Teuchos::TimeMonitor::report (comm.ptr (), std::cout);
344 return EXIT_SUCCESS;
345 }
346
347
348 // Get the convergence tolerance for each linear solve.
349 // If the user provided a nonnegative value at the command
350 // line, it overrides any value in the input ParameterList.
351 MT tol = STM::squareroot (STM::eps ()); // default value
352 if (tolFromCmdLine < STM::zero ()) {
353 tol = inputList.get ("Convergence Tolerance", tol);
354 } else {
355 tol = tolFromCmdLine;
356 }
357
358 // Get the maximum number of iterations for each linear solve.
359 // If the user provided a value other than -1 at the command
360 // line, it overrides any value in the input ParameterList.
361 int maxNumIters = 200; // default value
362 if (maxNumItersFromCmdLine == -1) {
363 maxNumIters = inputList.get ("Maximum Iterations", maxNumIters);
364 } else {
365 maxNumIters = maxNumItersFromCmdLine;
366 }
367
368 // Get the number of "time steps." We imitate a time-dependent
369 // PDE by doing this many linear solves.
370 const int num_steps = inputList.get ("Number of Time Steps", 1);
371
372 // Do the linear solve(s).
373 bool converged = false;
374 int numItersPerformed = 0;
375 if (gpu) {
376 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total GPU Solve", total_solve);
377 solveWithBelosGPU (converged, numItersPerformed, tol, maxNumIters,
378 num_steps, ranks_per_node, gpu_ranks_per_node,
379 device_offset, prec_type, X, A, B, Teuchos::null, M);
380 }
381 else {
382 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Solve", total_solve);
383 solveWithBelos (converged, numItersPerformed, solverName, tol,
384 maxNumIters, num_steps, X, A, B, Teuchos::null, M);
385 }
386
387 // Compute ||X-X_exact||_2
388 const MT norm_x = X_exact->norm2 ();
389 X_exact->update (-1.0, *X, 1.0);
390 const MT norm_error = X_exact->norm2 ();
391 *out << endl
392 << "||X - X_exact||_2 / ||X_exact||_2 = " << norm_error / norm_x
393 << endl;
394 } // total time block
395
396 // Summarize timings
397 Teuchos::TimeMonitor::report (comm.ptr (), std::cout);
398 } // try
399 TEUCHOS_STANDARD_CATCH_STATEMENTS(true, std::cerr, success);
400
401 if (success) {
402 return EXIT_SUCCESS;
403 } else {
404 return EXIT_FAILURE;
405 }
406 }