Debian Codegraph @

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