Debian Codegraph @

packages/belos/epetra/example/BlockGmres/BlockPrecGmresEpetraGaleriEx.cpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // Belos: Block Linear Solvers Package
4 //
5 // Copyright 2004-2016 NTESS and the Belos contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 #include "BelosBlockGmresSolMgr.hpp"
11 #include "BelosPseudoBlockGmresSolMgr.hpp"
12 #include "BelosEpetraAdapter.hpp"
13 #include "Epetra_CrsMatrix.h"
14 #include "Epetra_MultiVector.h"
15
16 // The Trilinos package Galeri has many example problems.
17 #include "Galeri_Maps.h"
18 #include "Galeri_CrsMatrices.h"
19
20 #include <Teuchos_CommandLineProcessor.hpp>
21 #include <Teuchos_GlobalMPISession.hpp>
22 #include <Teuchos_oblackholestream.hpp>
23 #include <Teuchos_TypeNameTraits.hpp>
24 #include <Teuchos_StandardCatchMacros.hpp>
25
26 #include "Ifpack.h"
27
28 // Include selected communicator class required by Epetra objects
29 #ifdef EPETRA_MPI
30 # include "Epetra_MpiComm.h"
31 #else
32 # include "Epetra_SerialComm.h"
33 #endif // EPETRA_MPI
34
35 // ****************************************************************************
36 // BEGIN MAIN ROUTINE
37 // ****************************************************************************
38
39 int
40 main (int argc, char *argv[])
41 {
42 int MyPID = 0;
43
44 // Belos solvers have the following template parameters:
45 //
46 // - Scalar: The type of dot product results.
47 // - MV: The type of (multi)vectors.
48 // - OP: The type of operators (functions from multivector to
49 // multivector). A matrix (like Epetra_CrsMatrix) is an example
50 // of an operator; an Ifpack preconditioner is another example.
51 //
52 // Here, Scalar is double, MV is Epetra_MultiVector, and OP is
53 // Epetra_Operator.
54 typedef double ST;
55 typedef Teuchos::ScalarTraits<ST> SCT;
56 typedef SCT::magnitudeType MT;
57 typedef Epetra_MultiVector MV;
58 typedef Epetra_Operator OP;
59 typedef Belos::MultiVecTraits<ST,MV> MVT;
60 typedef Belos::OperatorTraits<ST,MV,OP> OPT;
61
62 using Teuchos::ParameterList;
63 using Teuchos::RCP;
64 using Teuchos::rcp;
65
66 #ifdef EPETRA_MPI
67 MPI_Init (&argc, &argv);
68 Epetra_MpiComm Comm (MPI_COMM_WORLD);
69 #else
70 Epetra_SerialComm Comm;
71 #endif // EPETRA_MPI
72
73 bool verbose = false;
74 bool success = true;
75 try {
76 bool proc_verbose = false;
77 bool debug = false;
78 bool leftprec = true; // left preconditioning or right.
79 bool pseudo = false; // use pseudo-block or block gmres
80 int frequency = -1; // frequency of status test output
81 int blocksize = 1; // blocksize
82 int numrhs = 1; // number of right-hand sides to solve for
83 int maxiters = -1; // maximum number of iterations allowed per linear system
84 int maxsubspace = 50; // maximum number of blocks the solver can use for the subspace
85 int maxrestarts = 15; // number of restarts allowed
86 int nx = 10; // number of discretization points in each direction
87 MT tol = 1.0e-5; // relative residual tolerance
88 std::string ortho = "DGKS";// orthogonalization method
89
90 Teuchos::CommandLineProcessor cmdp(false,true);
91 cmdp.setOption("verbose","quiet",&verbose,"Print messages and results.");
92 cmdp.setOption("debug","nondebug",&debug,"Print debugging information from solver.");
93 cmdp.setOption("left-prec","right-prec",&leftprec,"Left preconditioning or right.");
94 cmdp.setOption("pseudo","block",&pseudo,"Use pseudo-block or block GMRES solver.");
95 cmdp.setOption("frequency",&frequency,"Solvers frequency for printing residuals (#iters).");
96 cmdp.setOption("tol",&tol,"Relative residual tolerance used by GMRES solver.");
97 cmdp.setOption("num-rhs",&numrhs,"Number of right-hand sides to be solved for.");
98 cmdp.setOption("block-size",&blocksize,"Block size used by GMRES.");
99 cmdp.setOption("max-iters",&maxiters,"Maximum number of iterations per linear system (-1 = adapted to problem/block size).");
100 cmdp.setOption("max-subspace",&maxsubspace,"Maximum number of blocks the solver can use for the subspace.");
101 cmdp.setOption("max-restarts",&maxrestarts,"Maximum number of restarts allowed for GMRES solver.");
102 cmdp.setOption("nx",&nx,"Number of discretization points in each direction of 3D Laplacian.");
103 cmdp.setOption("ortho",&ortho,"Orthogonalization being used by GMRES solver.");
104 if (cmdp.parse(argc,argv) != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL) {
105 return -1;
106 }
107 if (!verbose)
108 frequency = -1; // reset frequency if test is not verbose
109
110 //
111 // Set up the test problem.
112 //
113 // We use Trilinos' Galeri package to construct a test problem.
114 // Here, we use a discretization of the 2-D Laplacian operator.
115 // The global mesh size is nx * nx.
116 //
117 Teuchos::ParameterList GaleriList;
118 GaleriList.set ("n", nx * nx * nx);
119 GaleriList.set ("nx", nx);
120 GaleriList.set ("ny", nx);
121 GaleriList.set ("nz", nx);
122 RCP<Epetra_Map> Map = rcp (Galeri::CreateMap ("Linear", Comm, GaleriList));
123 RCP<Epetra_RowMatrix> A =
124 rcp (Galeri::CreateCrsMatrix ("Laplace3D", &*Map, GaleriList));
125
126 proc_verbose = verbose && (MyPID==0); /* Only print on the zero processor */
127
128 // Create RHS using random solution vector
129 RCP<MV> B = rcp (new MV (*Map, numrhs));
130 RCP<MV> X = rcp (new MV (*Map, numrhs));
131 RCP<MV> Xexact = rcp (new MV (*Map, numrhs));
132 Xexact->Random ();
133
134 A->Apply( *Xexact, *B );
135
136 //
137 // ************Construct preconditioner*************
138 //
139 ParameterList ifpackList;
140
141 // allocates an IFPACK factory. No data is associated
142 // to this object (only method Create()).
143 Ifpack Factory;
144
145 // create the preconditioner. For valid PrecType values,
146 // please check the documentation
147 std::string PrecType = "ILU"; // incomplete LU
148 int OverlapLevel = 1; // must be >= 0. If Comm.NumProc() == 1,
149 // it is ignored.
150
151 RCP<Ifpack_Preconditioner> Prec = Teuchos::rcp( Factory.Create(PrecType, &*A, OverlapLevel) );
152 assert(Prec != Teuchos::null);
153
154 // specify parameters for ILU
155 ifpackList.set("fact: level-of-fill", 1);
156 // the combine mode is on the following:
157 // "Add", "Zero", "Insert", "InsertAdd", "Average", "AbsMax"
158 // Their meaning is as defined in file Epetra_CombineMode.h
159 ifpackList.set("schwarz: combine mode", "Add");
160 // sets the parameters
161 IFPACK_CHK_ERR(Prec->SetParameters(ifpackList));
162
163 // initialize the preconditioner. At this point the matrix must
164 // have been FillComplete()'d, but actual values are ignored.
165 IFPACK_CHK_ERR(Prec->Initialize());
166
167 // Builds the preconditioners, by looking for the values of
168 // the matrix.
169 IFPACK_CHK_ERR(Prec->Compute());
170
171 // Create the Belos preconditioned operator from the Ifpack preconditioner.
172 // NOTE: This is necessary because Belos expects an operator to apply the
173 // preconditioner with Apply() NOT ApplyInverse().
174 RCP<Belos::EpetraPrecOp> belosPrec = rcp( new Belos::EpetraPrecOp( Prec ) );
175
176 //
177 // ********Other information used by block solver***********
178 // *****************(can be user specified)******************
179 //
180 const int NumGlobalElements = B->GlobalLength();
181 if (maxiters == -1)
182 maxiters = NumGlobalElements/blocksize - 1; // maximum number of iterations to run
183 //
184 ParameterList belosList;
185 belosList.set( "Num Blocks", maxsubspace); // Maximum number of blocks in Krylov factorization
186 belosList.set( "Block Size", blocksize ); // Blocksize to be used by iterative solver
187 belosList.set( "Maximum Iterations", maxiters ); // Maximum number of iterations allowed
188 belosList.set( "Maximum Restarts", maxrestarts ); // Maximum number of restarts allowed
189 belosList.set( "Convergence Tolerance", tol ); // Relative convergence tolerance requested
190 belosList.set( "Orthogonalization", ortho ); // Orthogonalization used by iterative solver
191 int verbosity = Belos::Errors + Belos::Warnings;
192 if (verbose) {
193 verbosity += Belos::TimingDetails + Belos::StatusTestDetails;
194 if (frequency > 0)
195 belosList.set( "Output Frequency", frequency );
196 }
197 if (debug) {
198 verbosity += Belos::Debug;
199 }
200 belosList.set( "Verbosity", verbosity );
201 //
202 // Construct an unpreconditioned linear problem instance.
203 //
204 Belos::LinearProblem<double,MV,OP> problem( A, X, B );
205 if (leftprec) {
206 problem.setLeftPrec( belosPrec );
207 }
208 else {
209 problem.setRightPrec( belosPrec );
210 }
211
212 bool set = problem.setProblem();
213 if (set == false) {
214 if (proc_verbose)
215 std::cout << std::endl << "ERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
216 return -1;
217 }
218 //
219 //
220 // *******************************************************************
221 // *************Start the block Gmres iteration*************************
222 // *******************************************************************
223 //
224 // Create an iterative solver manager.
225 RCP< Belos::SolverManager<double,MV,OP> > newSolver;
226 if (pseudo && (blocksize == 1))
227 newSolver = rcp( new Belos::PseudoBlockGmresSolMgr<double,MV,OP>(rcp(&problem,false), rcp(&belosList,false)));
228 else
229 newSolver = rcp( new Belos::BlockGmresSolMgr<double,MV,OP>(rcp(&problem,false), rcp(&belosList,false)));
230
231 //
232 // **********Print out information about problem*******************
233 //
234 if (proc_verbose) {
235 std::cout << std::endl << std::endl;
236 std::cout << "Dimension of matrix: " << NumGlobalElements << std::endl;
237 std::cout << "Number of right-hand sides: " << numrhs << std::endl;
238 std::cout << "Block size used by solver: " << blocksize << std::endl;
239 std::cout << "Max number of restarts allowed: " << maxrestarts << std::endl;
240 std::cout << "Max number of Gmres iterations per linear system: " << maxiters << std::endl;
241 std::cout << "Relative residual tolerance: " << tol << std::endl;
242 std::cout << std::endl;
243 }
244 //
245 // Perform solve
246 //
247 Belos::ReturnType ret = newSolver->solve();
248 //
249 // Get the number of iterations for this solve.
250 //
251 int numIters = newSolver->getNumIters();
252 if (proc_verbose)
253 std::cout << "Number of iterations performed for this solve: " << numIters << std::endl;
254 //
255 // Compute actual residuals.
256 //
257 bool badRes = false;
258 std::vector<double> actual_resids( numrhs );
259 std::vector<double> rhs_norm( numrhs );
260 Epetra_MultiVector resid(*Map, numrhs);
261 OPT::Apply( *A, *X, resid );
262 MVT::MvAddMv( -1.0, resid, 1.0, *B, resid );
263 MVT::MvNorm( resid, actual_resids );
264 MVT::MvNorm( *B, rhs_norm );
265 if (proc_verbose) {
266 std::cout<< "---------- Actual Residuals (normalized) ----------"<<std::endl<<std::endl;
267 for ( int i=0; i<numrhs; i++) {
268 double actRes = actual_resids[i]/rhs_norm[i];
269 std::cout<<"Problem "<<i<<" : \t"<< actRes <<std::endl;
270 if (actRes > tol) badRes = true;
271 }
272 }
273
274 if (ret!=Belos::Converged || badRes) {
275 success = false;
276 if (proc_verbose)
277 std::cout << "End Result: TEST FAILED" << std::endl;
278 } else {
279 if (proc_verbose)
280 std::cout << "End Result: TEST PASSED" << std::endl;
281 }
282 }
283 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
284
285 #ifdef EPETRA_MPI
286 MPI_Finalize();
287 #endif
288
289 return success ? EXIT_SUCCESS : EXIT_FAILURE;
290 }