Debian Codegraph @

packages/trilinoscouplings/examples/scaling/IntrepidPoisson_Pamgen_Epetra_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_Epetra_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 Epetra 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 Epetra 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 and back-ported to Epetra for a fair comparison with
47 Tpetra.
48
49 \remark Use the "--help" command-line argument for usage info.
50
51 \remark Example driver has an option to use an input file (XML
52 serialization of a Teuchos::ParameterList) containing a
53 Pamgen mesh description. A version, Poisson.xml, is
54 included in the same directory as this driver. If not
55 included, this program will use a default mesh
56 description.
57
58 \remark The exact solution (u) and material tensor (A) are set in
59 the functions "exactSolution" and "materialTensor" and may
60 be modified by the user. We compute the source term f
61 from u using Sacado automatic differentiation, so that u
62 really is the exact solution. The current implementation
63 of exactSolution() has notes to guide your choice of
64 solution. For example, you might want to pick a solution
65 in the finite element space, so that the discrete solution
66 is exact if the solution of the linear system is exact
67 (modulo rounding error when constructing the linear
68 system).
69 */
70
71 #include "Teuchos_oblackholestream.hpp"
72 #include "Teuchos_GlobalMPISession.hpp"
73 #include "Teuchos_TimeMonitor.hpp"
74 #include "Teuchos_XMLParameterListHelpers.hpp"
75 #include "Teuchos_StandardCatchMacros.hpp"
76
77 #include "Epetra_Comm.h"
78 #ifdef EPETRA_MPI
79 # include "mpi.h"
80 # include "Epetra_MpiComm.h"
81 # include "Teuchos_DefaultMpiComm.hpp"
82 #else
83 # include "Epetra_SerialComm.h"
84 # include "Teuchos_DefaultSerialComm.hpp"
85 #endif // EPETRA_MPI
86
87 #include "TrilinosCouplings_config.h"
88 #include "TrilinosCouplings_EpetraIntrepidPoissonExample.hpp"
89 #include "TrilinosCouplings_IntrepidPoissonExampleHelpers.hpp"
90
91 #ifdef HAVE_TRILINOSCOUPLINGS_ML
92 # include "ml_include.h"
93 # include "ml_MultiLevelPreconditioner.h"
94 #endif // HAVE_TRILINOSCOUPLINGS_ML
95
96 #ifdef HAVE_TRILINOSCOUPLINGS_MUELU
97 # include "MueLu.hpp"
98 # include "MueLu_ParameterListInterpreter.hpp"
99 # include "MueLu_EpetraOperator.hpp"
100 #endif // HAVE_TRILINOSCOUPLINGS_MUELU
101
102 int
103 main (int argc, char *argv[])
104 {
105 using namespace TrilinosCouplings; // Yes, this means I'm lazy.
106
107 using EpetraIntrepidPoissonExample::exactResidualNorm;
108 using EpetraIntrepidPoissonExample::makeMatrixAndRightHandSide;
109 using EpetraIntrepidPoissonExample::solveWithBelos;
110 using IntrepidPoissonExample::makeMeshInput;
111 using IntrepidPoissonExample::parseCommandLineArguments;
112 using IntrepidPoissonExample::setCommandLineArgumentDefaults;
113 using IntrepidPoissonExample::setMaterialTensorOffDiagonalValue;
114 using IntrepidPoissonExample::setUpCommandLineArguments;
115 using Teuchos::outArg;
116 using Teuchos::ParameterList;
117 using Teuchos::parameterList;
118 using Teuchos::RCP;
119 using Teuchos::rcp;
120 using Teuchos::rcp_implicit_cast;
121 using Teuchos::rcpFromRef;
122 using Teuchos::getFancyOStream;
123 using Teuchos::FancyOStream;
124 using std::endl;
125 // Pull in typedefs from the example's namespace.
126 typedef EpetraIntrepidPoissonExample::ST ST;
127 //typedef EpetraIntrepidPoissonExample::Node Node;
128 typedef Teuchos::ScalarTraits<ST> STS;
129 typedef STS::magnitudeType MT;
130 typedef Teuchos::ScalarTraits<MT> STM;
131 typedef EpetraIntrepidPoissonExample::sparse_matrix_type sparse_matrix_type;
132 typedef EpetraIntrepidPoissonExample::vector_type vector_type;
133 typedef EpetraIntrepidPoissonExample::operator_type operator_type;
134
135 bool success = true;
136 try {
137 Epetra_Object::SetTracebackMode(2);
138
139 Teuchos::oblackholestream blackHole;
140 Teuchos::GlobalMPISession mpiSession (&argc, &argv, &blackHole);
141 const int myRank = mpiSession.getRank ();
142 //const int numProcs = mpiSession.getNProc ();
143
144 // Get the default communicator
145 RCP<Epetra_Comm> comm;
146 #ifdef EPETRA_MPI
147 comm = rcp_implicit_cast<Epetra_Comm> (rcp (new Epetra_MpiComm (MPI_COMM_WORLD)));
148 #else
149 comm = rcp_implicit_cast<Epetra_Comm> (rcp (new Epetra_SerialComm));
150 #endif // EPETRA_MPI
151
152 // Did the user specify --help at the command line to print help
153 // with command-line arguments?
154 bool printedHelp = false;
155 // Values of command-line arguments.
156 int nx, ny, nz;
157 std::string xmlInputParamsFile;
158 bool verbose, debug;
159 int maxNumItersFromCmdLine = -1; // -1 means "read from XML file"
160 double tolFromCmdLine = -1.0; // -1 means "read from XML file"
161 std::string solverName = "GMRES";
162 ST materialTensorOffDiagonalValue = 0.0;
163
164 // Set default values of command-line arguments.
165 setCommandLineArgumentDefaults (nx, ny, nz, xmlInputParamsFile,
166 solverName, verbose, debug);
167 // Parse and validate command-line arguments.
168 Teuchos::CommandLineProcessor cmdp (false, true);
169 setUpCommandLineArguments (cmdp, nx, ny, nz, xmlInputParamsFile,
170 solverName, tolFromCmdLine,
171 maxNumItersFromCmdLine,
172 verbose, debug);
173 cmdp.setOption ("materialTensorOffDiagonalValue",
174 &materialTensorOffDiagonalValue, "Off-diagonal value in "
175 "the material tensor. This controls the iteration count. "
176 "Be careful with this if you use CG, since you can easily "
177 "make the matrix indefinite.");
178
179 parseCommandLineArguments (cmdp, printedHelp, argc, argv, nx, ny, nz,
180 xmlInputParamsFile, solverName, verbose, debug);
181 if (printedHelp) {
182 // The user specified --help at the command line to print help
183 // with command-line arguments. We printed help already, so quit
184 // with a happy return code.
185 return EXIT_SUCCESS;
186 }
187
188 setMaterialTensorOffDiagonalValue (materialTensorOffDiagonalValue);
189
190 // Both streams only print on MPI Rank 0. "out" only prints if the
191 // user specified --verbose.
192 RCP<FancyOStream> out =
193 getFancyOStream (rcpFromRef ((myRank == 0 && verbose) ? std::cout : blackHole));
194 RCP<FancyOStream> err =
195 getFancyOStream (rcpFromRef ((myRank == 0 && debug) ? std::cerr : blackHole));
196
197 #ifdef HAVE_MPI
198 *out << "PARALLEL executable" << endl;
199 #else
200 *out << "SERIAL executable" << endl;
201 #endif
202
203 /**********************************************************************************/
204 /********************************** GET XML INPUTS ********************************/
205 /**********************************************************************************/
206 ParameterList inputList;
207 if (xmlInputParamsFile != "") {
208 *out << "Reading parameters from XML file \""
209 << xmlInputParamsFile << "\"..." << endl;
210 Teuchos::updateParametersFromXmlFile (xmlInputParamsFile,
211 outArg (inputList));
212 if (myRank == 0) {
213 inputList.print (*out, 2, true, true);
214 *out << endl;
215 }
216 }
217
218 // Get Pamgen mesh definition string, either from the input
219 // ParameterList or from our function that makes a cube and fills in
220 // the number of cells along each dimension.
221 std::string meshInput = inputList.get("meshInput", "");
222 if (meshInput == "") {
223 *out << "Generating mesh input string: nx = " << nx
224 << ", ny = " << ny
225 << ", nz = " << nz << endl;
226 meshInput = makeMeshInput (nx, ny, nz);
227 }
228
229 // Total application run time
230 {
231 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Time", total_time);
232
233 // Construct linear system
234 RCP<sparse_matrix_type> A;
235 RCP<vector_type> B, X_exact, X;
236 {
237 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Assembly", total_assembly);
238 makeMatrixAndRightHandSide (A, B, X_exact, X, comm, meshInput,
239 out, err, verbose, debug);
240 }
241
242 const std::vector<MT> norms = exactResidualNorm (A, B, X_exact);
243 // X_exact is the exact solution of the PDE, projected onto the
244 // discrete mesh. It may not necessarily equal the exact solution
245 // of the linear system.
246 *out << "||B - A*X_exact||_2 = " << norms[0] << endl
247 << "||B||_2 = " << norms[1] << endl
248 << "||A||_F = " << norms[2] << endl;
249
250 // Setup preconditioner
251 std::string prec_type = inputList.get ("Preconditioner", "None");
252 RCP<operator_type> M;
253 {
254 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Preconditioner Setup", total_prec);
255
256 if (prec_type == "ML") {
257 #ifdef HAVE_TRILINOSCOUPLINGS_ML
258 ParameterList mlParams;
259 if (inputList.isSublist("ML"))
260 mlParams = inputList.sublist("ML");
261 else {
262 ML_Epetra::SetDefaults("SA", mlParams);
263 mlParams.set("ML output", 0);
264 }
265 M = rcp(new ML_Epetra::MultiLevelPreconditioner(*A, mlParams));
266 #else // NOT HAVE_TRILINOSCOUPLINGS_ML
267 TEUCHOS_TEST_FOR_EXCEPTION(
268 prec_type == "ML", std::runtime_error, "Epetra scaling example: "
269 "In order to precondition with ML, you must have built Trilinos "
270 "with the ML package enabled.");
271 #endif // HAVE_TRILINOSCOUPLINGS_ML
272 }
273 else if (prec_type == "MueLu") {
274 #ifdef HAVE_TRILINOSCOUPLINGS_MUELU
275 // Turns a Epetra_CrsMatrix into a MueLu::Matrix
276 RCP<Xpetra::CrsMatrix<ST, int, int, Xpetra::EpetraNode> > mueluA_ =
277 rcp(new Xpetra::EpetraCrsMatrixT<int, Xpetra::EpetraNode>(A));
278 RCP<Xpetra::Matrix <ST, int, int, Xpetra::EpetraNode> > mueluA =
279 rcp(new Xpetra::CrsMatrixWrap<ST, int, int, Xpetra::EpetraNode>(mueluA_));
280
281 // Multigrid Hierarchy
282 ParameterList mueluParams;
283 if (inputList.isSublist("MueLu"))
284 mueluParams = inputList.sublist("MueLu");
285 MueLu::ParameterListInterpreter<ST, int, int, Xpetra::EpetraNode> mueLuFactory(mueluParams);
286 RCP<MueLu::Hierarchy<ST, int, int, Xpetra::EpetraNode> > H =
287 mueLuFactory.CreateHierarchy();
288 H->setVerbLevel(Teuchos::VERB_HIGH);
289 H->GetLevel(0)->Set("A", mueluA);
290
291 // Multigrid setup phase
292 H->Setup();
293
294 // Wrap MueLu Hierarchy as a Tpetra::Operator
295 M = rcp(new MueLu::EpetraOperator(H));
296 #else // NOT HAVE_TRILINOSCOUPLINGS_MUELU
297 TEUCHOS_TEST_FOR_EXCEPTION(
298 prec_type == "MueLu", std::runtime_error, "Epetra scaling example: "
299 "In order to precondition with MueLu, you must have built Trilinos "
300 "with the MueLu package enabled.");
301 #endif // HAVE_TRILINOSCOUPLINGS_MUELU
302 }
303 } // setup preconditioner
304
305 // Get the convergence tolerance for each linear solve.
306 // If the user provided a nonnegative value at the command
307 // line, it overrides any value in the input ParameterList.
308 MT tol = STM::squareroot (STM::eps ()); // default value
309 if (tolFromCmdLine < STM::zero ()) {
310 tol = inputList.get ("Convergence Tolerance", tol);
311 } else {
312 tol = tolFromCmdLine;
313 }
314
315 // Get the maximum number of iterations for each linear solve.
316 // If the user provided a value other than -1 at the command
317 // line, it overrides any value in the input ParameterList.
318 int maxNumIters = 200; // default value
319 if (maxNumItersFromCmdLine == -1) {
320 maxNumIters = inputList.get ("Maximum Iterations", maxNumIters);
321 } else {
322 maxNumIters = maxNumItersFromCmdLine;
323 }
324
325 // Get the number of "time steps." We imitate a time-dependent
326 // PDE by doing this many linear solves.
327 const int num_steps = inputList.get ("Number of Time Steps", 1);
328
329 // Do the linear solve(s).
330 bool converged = false;
331 int numItersPerformed = 0;
332 {
333 TEUCHOS_FUNC_TIME_MONITOR_DIFF("Total Solve", total_solve);
334 solveWithBelos (converged, numItersPerformed, solverName, tol,
335 maxNumIters, num_steps, X, A, B, Teuchos::null, M);
336 }
337
338 // Compute ||X-X_exact||_2
339 MT norm_x, norm_error;
340 X_exact->Norm2 (&norm_x);
341 X_exact->Update (-1.0, *X, 1.0);
342 X_exact->Norm2 (&norm_error);
343 *out << endl
344 << "||X - X_exact||_2 / ||X_exact||_2 = " << norm_error / norm_x
345 << endl;
346 } // total time block
347
348 // Summarize timings
349 {
350 // Make a Teuchos::Comm corresponding to the Epetra_Comm.
351 RCP<const Teuchos::Comm<int> > teuchosComm;
352 #ifdef EPETRA_MPI
353 teuchosComm = rcp (new Teuchos::MpiComm<int> (MPI_COMM_WORLD));
354 #else
355 teuchosComm = rcp (new Teuchos::SerialComm<int> ());
356 #endif // EPETRA_MPI
357
358 // Use the Teuchos::Comm to report timings.
359 Teuchos::TimeMonitor::report (teuchosComm.ptr (), std::cout);
360 }
361 } // try
362 TEUCHOS_STANDARD_CATCH_STATEMENTS(true, std::cerr, success);
363
364 if (success) {
365 return EXIT_SUCCESS;
366 } else {
367 return EXIT_FAILURE;
368 }
369 }
370