Debian Codegraph @

packages/belos/epetra/test/PCPG/test_pcpg_epetraex.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 // Purpose
11 // The example tests the successive right-hand sides capabilities of ML
12 // and Belos on a heat flow u_t = u_xx problem.
13 //
14 // A sequence of linear systems with the same coefficient matrix and
15 // different right-hand sides is solved. A seed space is generated dynamically,
16 // and a deflated linear system is solved. After each solves, the first
17 // few Krylov vectors are saved, and used to reduce the number of iterations
18 // for later solves.
19 // The optimal numbers of vectors to deflate and save are not known.
20 // Presently, the maximum number of vectors to deflate (seed space dimension)
21 // and to save are user paraemters.
22 // The seed space dimension is less than or equal to total number of vectors saved.
23 // The difference between the seed space dimension and the total number of vectors,
24 // is the number of vectors used to update the seed space after each solve.
25 // I guess that a seed space whose dimension is a small fraction of the total space
26 // will be best.
27 //
28 // maxSave=1 and maxDeflate=0 uses no recycling (not tested ).
29 //
30 // TODO: Instrument with timers, so that we can tell what is going on besides
31 // by counting the numbers of iterations.
32 //
33 //
34 // \author David M. Day
35 //
36 // \data Last modified 2007 December 11
37
38 #include "ml_include.h" //--enable-epetra --enable-teuchos.
39 #include "Epetra_Map.h"
40 #ifdef EPETRA_MPI
41 #include "Epetra_MpiComm.h"
42 #else
43 #include "Epetra_SerialComm.h"
44 #endif
45 #include "Epetra_Vector.h"
46 #include "Epetra_CrsMatrix.h"
47 #include "EpetraExt_MatrixMatrix.h" // build the example
48 #include "ml_MultiLevelPreconditioner.h" // ML
49
50 #include "BelosConfigDefs.hpp"
51 #include "BelosLinearProblem.hpp"
52 #include "BelosEpetraAdapter.hpp"
53 //#include "BelosBlockCGSolMgr.hpp"
54 #include "BelosPCPGSolMgr.hpp"
55
56 #include "Teuchos_CommandLineProcessor.hpp"
57 #include "Teuchos_ParameterList.hpp"
58 #include "Teuchos_StandardCatchMacros.hpp"
59
60 int main(int argc, char *argv[]) {
61 //
62 int MyPID = 0;
63 int numProc = 1;
64 #ifdef EPETRA_MPI
65 MPI_Init(&argc,&argv); // Initialize MPI
66 Epetra_MpiComm Comm(MPI_COMM_WORLD);
67 MyPID = Comm.MyPID();
68 numProc = Comm.NumProc();
69 #else
70 Epetra_SerialComm Comm;
71 #endif
72 //
73 // Laplace's equation, homogeneous Dirichlet boundary conditions, [0,1]^2
74 // regular mesh, Q1 finite elements
75 //
76 typedef double ST;
77 typedef Teuchos::ScalarTraits<ST> SCT;
78 typedef SCT::magnitudeType MT;
79 typedef Epetra_MultiVector MV;
80 typedef Epetra_Operator OP;
81 typedef Belos::MultiVecTraits<ST,MV> MVT;
82 typedef Belos::OperatorTraits<ST,MV,OP> OPT;
83
84 using Teuchos::ParameterList; // all of this may look fine but do not be fooled ...
85 using Teuchos::RCP; // it is not so clear what any of this does
86 using Teuchos::rcp;
87
88 bool success = false;
89 bool verbose = false;
90 try {
91 bool proc_verbose = false;
92 int frequency = -1; // frequency of status test output.
93 int blocksize = 1; // blocksize, PCPGIter
94 int numrhs = 1; // number of right-hand sides to solve for
95 int maxiters = 30; // maximum number of iterations allowed per linear system
96
97 int maxDeflate = 4; // maximum number of vectors deflated from the linear system;
98 // There is no overhead cost assoc with changing maxDeflate between solves
99 int maxSave = 8; // maximum number of vectors saved from current and previous .");
100 // If maxSave changes between solves, then re-initialize (setSize).
101
102 // Hypothesis: seed vectors are conjugate.
103 // Initial versions allowed users to supply a seed space et cetera, but no longer.
104
105 // The documentation it suitable for certain tasks, like defining a modules grammar,
106 std::string ortho("ICGS"); // The Belos documentation obscures the fact that
107 // IMGS is Iterated Modified Gram Schmidt,
108 // ICGS is Iterated Classical Gram Schmidt, and
109 // DKGS is another Iterated Classical Gram Schmidt.
110 // Mathematical issues, such as the difference between ICGS and DKGS, are not documented at all.
111 // UH tells me that Anasazi::SVQBOrthoManager is available; I need it for Belos
112 MT tol = 1.0e-8; // relative residual tolerance
113
114 // How do command line parsers work?
115 Teuchos::CommandLineProcessor cmdp(false,true);
116 cmdp.setOption("verbose","quiet",&verbose,"Print messages and results");
117 cmdp.setOption("frequency",&frequency,"Solvers frequency for printing residuals (#iters)");
118 cmdp.setOption("tol",&tol,"Relative residual tolerance used by PCPG solver");
119 cmdp.setOption("num-rhs",&numrhs,"Number of right-hand sides to be solved for");
120 cmdp.setOption("max-iters",&maxiters,"Maximum number of iterations per linear system (-1 = adapted to problem/block size)");
121 cmdp.setOption("num-deflate",&maxDeflate,"Number of vectors deflated from the linear system");
122 cmdp.setOption("num-save",&maxSave,"Number of vectors saved from old Krylov subspaces");
123 cmdp.setOption("ortho-type",&ortho,"Orthogonalization type, either DGKS, ICGS or IMGS");
124 if (cmdp.parse(argc,argv) != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL) {
125 return -1;
126 }
127 if (!verbose)
128 frequency = -1; // reset frequency if test is not verbose
129
130 //
131 // *************Form the problem*********************
132 //
133 int numElePerDirection = 14*numProc;
134 int num_time_step = 4;
135 int numNodes = (numElePerDirection - 1)*(numElePerDirection - 1);
136 //By the way, either matrix has (3*numElePerDirection - 2)^2 nonzeros.
137 RCP<Epetra_Map> Map = rcp(new Epetra_Map(numNodes, 0, Comm) );
138 RCP<Epetra_CrsMatrix> Stiff = rcp(new Epetra_CrsMatrix(Epetra_DataAccess::Copy, *Map, 0) );
139 RCP<Epetra_CrsMatrix> Mass = rcp(new Epetra_CrsMatrix(Epetra_DataAccess::Copy, *Map, 0) );
140 RCP<Epetra_Vector> vecLHS = rcp( new Epetra_Vector(*Map) );
141 RCP<Epetra_Vector> vecRHS = rcp( new Epetra_Vector(*Map) );
142
143 RCP<Epetra_MultiVector> LHS, RHS;
144 double ko = 8.0/3.0, k1 = -1.0/3.0;
145 double h = 1.0/(double) numElePerDirection; // x=(iX,iY)h
146 double mo = h*h*4.0/9.0, m1 = h*h/9.0, m2 = h*h/36.0;
147 double pi = 4.0*atan(1.0), valueLHS;
148 int lid, node, pos, iX, iY;
149 for(lid = Map->MinLID(); lid <= Map->MaxLID(); lid++){
150 node = Map->GID(lid);
151 iX = node % (numElePerDirection-1);
152 iY = ( node - iX )/(numElePerDirection-1);
153 pos = node;
154 Stiff->InsertGlobalValues(node, 1, &ko, &pos);
155 Mass->InsertGlobalValues(node, 1, &mo, &pos); // init guess violates hom Dir bc
156 valueLHS = sin( pi*h*((double) iX+1) )*cos( 2.0 * pi*h*((double) iY+1) );
157 vecLHS->ReplaceGlobalValues( 1, &valueLHS, &node);
158 if (iY > 0) {
159 pos = iX + (iY-1)*(numElePerDirection-1);
160 Stiff->InsertGlobalValues(node, 1, &k1, &pos); //North
161 Mass->InsertGlobalValues(node, 1, &m1, &pos);
162 }
163 if (iY < numElePerDirection-2) {
164 pos = iX + (iY+1)*(numElePerDirection-1);
165 Stiff->InsertGlobalValues(node, 1, &k1, &pos); //South
166 Mass->InsertGlobalValues(node, 1, &m1, &pos);
167 }
168
169 if (iX > 0) {
170 pos = iX-1 + iY*(numElePerDirection-1);
171 Stiff->InsertGlobalValues(node, 1, &k1, &pos); // West
172 Mass->InsertGlobalValues(node, 1, &m1, &pos);
173 if (iY > 0) {
174 pos = iX-1 + (iY-1)*(numElePerDirection-1);
175 Stiff->InsertGlobalValues(node, 1, &k1, &pos); // North West
176 Mass->InsertGlobalValues(node, 1, &m2, &pos);
177 }
178 if (iY < numElePerDirection-2) {
179 pos = iX-1 + (iY+1)*(numElePerDirection-1);
180 Stiff->InsertGlobalValues(node, 1, &k1, &pos); // South West
181 Mass->InsertGlobalValues(node, 1, &m2, &pos);
182 }
183 }
184
185 if (iX < numElePerDirection - 2) {
186 pos = iX+1 + iY*(numElePerDirection-1);
187 Stiff->InsertGlobalValues(node, 1, &k1, &pos); // East
188 Mass->InsertGlobalValues(node, 1, &m1, &pos);
189 if (iY > 0) {
190 pos = iX+1 + (iY-1)*(numElePerDirection-1);
191 Stiff->InsertGlobalValues(node, 1, &k1, &pos); // North East
192 Mass->InsertGlobalValues(node, 1, &m2, &pos);
193 }
194 if (iY < numElePerDirection-2) {
195 pos = iX+1 + (iY+1)*(numElePerDirection-1);
196 Stiff->InsertGlobalValues(node, 1, &k1, &pos); // South East
197 Mass->InsertGlobalValues(node, 1, &m2, &pos);
198 }
199 }
200 }
201 Stiff->FillComplete();
202 Stiff->OptimizeStorage();
203
204 Mass->FillComplete();
205 Mass->OptimizeStorage();
206
207 double one = 1.0, hdt = .00005; // half time step
208
209 RCP<Epetra_CrsMatrix> A = rcp(new Epetra_CrsMatrix(*Stiff) );// A = Mass+Stiff*dt/2
210 int err = EpetraExt::MatrixMatrix::Add(*Mass, false, one,*A,hdt);
211
212 if (err != 0) {
213 std::cout << "err "<<err<<" from MatrixMatrix::Add "<<std::endl;
214 return(err);
215 }
216
217 A->FillComplete();
218 A->OptimizeStorage();
219
220 hdt = -hdt;
221 RCP<Epetra_CrsMatrix> B = rcp(new Epetra_CrsMatrix(*Stiff) );// B = Mass-Stiff*dt/2
222 EpetraExt::MatrixMatrix::Add(*Mass, false, one,*B,hdt);
223 if (err != 0) {
224 std::cout << "err "<<err<<" from MatrixMatrix::Add "<<std::endl;
225 return(err);
226 }
227
228 B->FillComplete();
229 B->OptimizeStorage();
230 B->Multiply(false, *vecLHS, *vecRHS); // rhs_new := B*lhs_old,
231
232 proc_verbose = verbose && (MyPID==0); /* Only print on the zero processor */
233
234 LHS = Teuchos::rcp_implicit_cast<Epetra_MultiVector>(vecLHS);
235 RHS = Teuchos::rcp_implicit_cast<Epetra_MultiVector>(vecRHS);
236
237 //
238 // ************Construct preconditioner*************
239 //
240 ParameterList MLList; // Set MLList for Smoothed Aggregation
241
242 ML_Epetra::SetDefaults("SA",MLList); // reset parameters ML User's Guide
243 MLList.set("smoother: type","Chebyshev"); // Chebyshev smoother ... aztec??
244 MLList.set("smoother: sweeps",3);
245 MLList.set("smoother: pre or post", "both"); // both pre- and post-smoothing
246
247 #ifdef HAVE_ML_AMESOS
248 MLList.set("coarse: type","Amesos-KLU"); // solve with serial direct solver KLU
249 #else
250 MLList.set("coarse: type","Jacobi"); // not recommended
251 puts("Warning: Iterative coarse grid solve");
252 #endif
253
254 RCP<Epetra_Operator> Prec = rcp( new ML_Epetra::MultiLevelPreconditioner(*A, MLList) );
255 assert(Prec != Teuchos::null);
256
257 // Create the Belos preconditioned operator from the preconditioner.
258 // NOTE: This is necessary because Belos expects an operator to apply the
259 // preconditioner with Apply() NOT ApplyInverse().
260 RCP<Belos::EpetraPrecOp> belosPrec = rcp( new Belos::EpetraPrecOp( Prec ) );
261
262 //
263 // *****Create parameter list for the PCPG solver manager*****
264 //
265 const int NumGlobalElements = RHS->GlobalLength();
266 if (maxiters == -1)
267 maxiters = NumGlobalElements/blocksize - 1; // maximum number of iterations to run
268 //
269 ParameterList belosList;
270 belosList.set( "Block Size", blocksize ); // Blocksize to be used by iterative solver
271 belosList.set( "Maximum Iterations", maxiters ); // Maximum number of iterations allowed
272 belosList.set( "Convergence Tolerance", tol ); // Relative convergence tolerance requested
273 belosList.set( "Num Deflated Blocks", maxDeflate ); // Number of vectors in seed space
274 belosList.set( "Num Saved Blocks", maxSave ); // Number of vectors saved from old spaces
275 belosList.set( "Orthogonalization", ortho ); // Orthogonalization type
276
277 if (numrhs > 1) {
278 belosList.set( "Show Maximum Residual Norm Only", true ); // although numrhs = 1.
279 }
280 if (verbose) {
281 belosList.set( "Verbosity", Belos::Errors + Belos::Warnings +
282 Belos::TimingDetails + Belos::FinalSummary + Belos::StatusTestDetails );
283 if (frequency > 0)
284 belosList.set( "Output Frequency", frequency );
285 }
286 else
287 belosList.set( "Verbosity", Belos::Errors + Belos::Warnings + Belos::FinalSummary );
288 //
289 // *******Construct a preconditioned linear problem********
290 //
291 RCP<Belos::LinearProblem<double,MV,OP> > problem
292 = rcp( new Belos::LinearProblem<double,MV,OP>( A, LHS, RHS ) );
293 problem->setLeftPrec( belosPrec );
294
295 bool set = problem->setProblem();
296 if (set == false) {
297 if (proc_verbose)
298 std::cout << std::endl << "ERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
299 return -1;
300 }
301
302 // Create an iterative solver manager.
303 RCP< Belos::SolverManager<double,MV,OP> > solver
304 = rcp( new Belos::PCPGSolMgr<double,MV,OP>(problem, rcp(&belosList,false)) );
305
306 // std::cout << LHS.Values() << std::endl
307
308 //
309 // *******************************************************************
310 // ************************* Iterate PCPG ****************************
311 // *******************************************************************
312 //
313 if (proc_verbose) {
314 std::cout << std::endl << std::endl;
315 std::cout << "Dimension of matrix: " << NumGlobalElements << std::endl;
316 std::cout << "Number of right-hand sides: " << numrhs << std::endl;
317 std::cout << "Block size used by solver: " << blocksize << std::endl;
318 std::cout << "Maximum number of iterations allowed: " << maxiters << std::endl;
319 std::cout << "Relative residual tolerance: " << tol << std::endl;
320 std::cout << std::endl;
321 }
322 bool badRes;
323 for( int time_step = 0; time_step < num_time_step; time_step++){
324 if( time_step ){
325 B->Multiply(false, *LHS, *RHS); // rhs_new := B*lhs_old,
326 set = problem->setProblem(LHS,RHS);
327 if (set == false) {
328 if (proc_verbose)
329 std::cout << std::endl << "ERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
330 return -1;
331 }
332 } // if time_step
333 std::vector<double> rhs_norm( numrhs );
334 MVT::MvNorm( *RHS, rhs_norm );
335 std::cout << " RHS norm is ... " << rhs_norm[0] << std::endl;
336 //
337 // Perform solve
338 //
339 Belos::ReturnType ret = solver->solve();
340 //
341 // Compute actual residuals.
342 //
343 badRes = false;
344 std::vector<double> actual_resids( numrhs );
345 //std::vector<double> rhs_norm( numrhs );
346 Epetra_MultiVector resid(*Map, numrhs);
347 OPT::Apply( *A, *LHS, resid );
348 MVT::MvAddMv( -1.0, resid, 1.0, *RHS, resid );
349 MVT::MvNorm( resid, actual_resids );
350 MVT::MvNorm( *RHS, rhs_norm );
351 std::cout << " RHS norm is ... " << rhs_norm[0] << std::endl;
352
353 if (proc_verbose) {
354 std::cout<< "---------- Actual Residuals (normalized) ----------"<<std::endl<<std::endl;
355 for ( int i=0; i<numrhs; i++) {
356 double actRes = actual_resids[i]/rhs_norm[i];
357 std::cout<<"Problem "<<i<<" : \t"<< actRes <<std::endl;
358 if (actRes > tol) badRes = true;
359 }
360 }
361
362 success = ret==Belos::Converged && !badRes;
363 if (!success)
364 break;
365 } // for time_step
366
367 if (success) {
368 if (proc_verbose)
369 std::cout << "End Result: TEST PASSED" << std::endl;
370 } else {
371 if (proc_verbose)
372 std::cout << "End Result: TEST FAILED" << std::endl;
373 }
374 }
375 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
376
377 #ifdef EPETRA_MPI
378 MPI_Finalize();
379 #endif
380
381 return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
382 }