Debian Codegraph @

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