Debian Codegraph @

packages/shylu/shylu_dd/core/test/shylu_belos_driver.cpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // ShyLU: Scalable Hybrid LU Preconditioner and Solver
4 //
5 // Copyright 2011 NTESS and the ShyLU contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 /** \file shylu_driver.cpp
11
12 \brief Factors and solves a sparse matrix using LU factorization.
13
14 \author Siva Rajamanickam
15
16 \remark Usage:
17 \code mpirun -n np shylu_driver.exe
18
19 */
20
21 #include <assert.h>
22 #include <iostream>
23 #include <sstream>
24
25 #include "Isorropia_config.h" // Just for HAVE_MPI
26
27 // Epetra includes
28 #ifdef HAVE_MPI
29 # include "Epetra_MpiComm.h"
30 #endif // HAVE_MPI
31 #include "Epetra_SerialComm.h"
32 #include "Epetra_CrsMatrix.h"
33 #include "Epetra_Map.h"
34 #include "Epetra_MultiVector.h"
35 #include "Epetra_LinearProblem.h"
36
37 // Teuchos includes
38 #include "Teuchos_GlobalMPISession.hpp"
39 #include "Teuchos_XMLParameterListHelpers.hpp"
40 #include "Teuchos_RCP.hpp"
41
42 // EpetraExt includes
43 #include "EpetraExt_RowMatrixOut.h"
44 #include "EpetraExt_MultiVectorOut.h"
45 #include "EpetraExt_CrsMatrixIn.h"
46 #include "EpetraExt_MultiVectorIn.h"
47
48 // Amesos includes
49 #include "Amesos.h"
50 #include "Amesos_BaseSolver.h"
51
52 // AztecOO includes
53 #include "AztecOO.h"
54
55 // ML includes
56 #include "ml_MultiLevelPreconditioner.h"
57 #include "ml_epetra_utils.h"
58
59 #include "Ifpack_ConfigDefs.h"
60 #include "shylu.h"
61 #include "shylu_util.h"
62 #include "Ifpack_ShyLU.h"
63 #include "Ifpack_ILUT.h"
64 #include "Ifpack_ILU.h"
65
66 #include "BelosConfigDefs.hpp"
67 #include "BelosLinearProblem.hpp"
68 #include "BelosEpetraAdapter.hpp"
69 #include "BelosBlockGmresSolMgr.hpp"
70
71 #include "EpetraExt_readEpetraLinearSystem.h"
72
73 //TODO Combine Belos driver and AztecOO driver into one driver.
74
75 int InitMatValues( const Epetra_CrsMatrix& newA, Epetra_CrsMatrix* A );
76 int InitMVValues( const Epetra_MultiVector& newb, Epetra_MultiVector* b );
77
78 using namespace std;
79
80 int main(int argc, char *argv[])
81 {
82 #ifdef HAVE_MPI
83 Teuchos::GlobalMPISession mpiSession(&argc, &argv, 0);
84 Epetra_MpiComm Comm(MPI_COMM_WORLD);
85 #else
86 Epetra_SerialComm Comm;
87 #endif
88 typedef double ST;
89 typedef Teuchos::ScalarTraits<ST> SCT;
90 typedef SCT::magnitudeType MT;
91 typedef Epetra_MultiVector MV;
92 typedef Epetra_Operator OP;
93 typedef Belos::MultiVecTraits<ST,MV> MVT;
94 typedef Belos::OperatorTraits<ST,MV,OP> OPT;
95 using Teuchos::RCP;
96 using Teuchos::rcp;
97
98
99 bool success = true;
100 string pass = "End Result: TEST PASSED";
101 string fail = "End Result: TEST FAILED";
102
103
104
105 bool verbose = false, proc_verbose = true;
106 bool leftprec = false; // left preconditioning or right.
107 int frequency = -1; // frequency of status test output.
108 int blocksize = 1; // blocksize
109 int numrhs = 1; // number of right-hand sides to solve for
110 int maxrestarts = 15; // maximum number of restarts allowed
111 int maxsubspace = 25; // maximum number of blocks the solver can use
112 // for the subspace
113 char file_name[100];
114
115 int nProcs, myPID ;
116 Teuchos::RCP <Teuchos::ParameterList> pLUList ; // ParaLU parameters
117 Teuchos::ParameterList isoList ; // Isorropia parameters
118 Teuchos::ParameterList shyLUList ; // ShyLU parameters
119 string ipFileName = "ShyLU.xml"; // TODO : Accept as i/p
120
121 #ifdef HAVE_MPI
122 nProcs = mpiSession.getNProc();
123 myPID = Comm.MyPID();
124 #else
125 nProcs = 1;
126 myPID = 0;
127 #endif
128
129 if (myPID == 0)
130 {
131 cout <<"Parallel execution: nProcs="<< nProcs << endl;
132 }
133
134 // =================== Read input xml file =============================
135 pLUList = Teuchos::getParametersFromXmlFile(ipFileName);
136 isoList = pLUList->sublist("Isorropia Input");
137 shyLUList = pLUList->sublist("ShyLU Input");
138 shyLUList.set("Outer Solver Library", "Belos");
139 // Get matrix market file name
140 string MMFileName = Teuchos::getParameter<string>(*pLUList, "mm_file");
141 string prec_type = Teuchos::getParameter<string>(*pLUList, "preconditioner");
142 int maxiters = Teuchos::getParameter<int>(*pLUList, "Outer Solver MaxIters");
143 MT tol = Teuchos::getParameter<double>(*pLUList, "Outer Solver Tolerance");
144 string rhsFileName = pLUList->get<string>("rhs_file", "");
145
146
147 int maxFiles = pLUList->get<int>("Maximum number of files to read in", 1);
148 int startFile = pLUList->get<int>("Number of initial file", 1);
149 int file_number = startFile;
150
151 if (myPID == 0)
152 {
153 cout << "Input :" << endl;
154 cout << "ParaLU params " << endl;
155 pLUList->print(std::cout, 2, true, true);
156 cout << "Matrix market file name: " << MMFileName << endl;
157 }
158
159 if (maxFiles > 1)
160 {
161 MMFileName += "%d.mm";
162 sprintf( file_name, MMFileName.c_str(), file_number );
163 }
164 else
165 {
166 strcpy( file_name, MMFileName.c_str());
167 }
168
169 // ==================== Read input Matrix ==============================
170 Epetra_CrsMatrix *A;
171 Epetra_MultiVector *b1;
172
173 int err = EpetraExt::MatrixMarketFileToCrsMatrix(file_name, Comm, A);
174 if (err != 0 && myPID == 0)
175 {
176 cout << "Matrix file could not be read in!!!, info = "<< err << endl;
177 success = false;
178 }
179
180 int n = A->NumGlobalRows();
181
182 // ==================== Read input rhs ==============================
183 if (rhsFileName != "" && maxFiles > 1)
184 {
185 rhsFileName += "%d.mm";
186 sprintf( file_name, rhsFileName.c_str(), file_number );
187 }
188 else
189 {
190 strcpy( file_name, rhsFileName.c_str());
191 }
192
193 Epetra_Map vecMap(n, 0, Comm);
194 bool allOneRHS = false;
195 if (rhsFileName != "")
196 {
197 err = EpetraExt::MatrixMarketFileToMultiVector(file_name, vecMap, b1);
198 }
199 else
200 {
201 b1 = new Epetra_MultiVector(vecMap, 1, false);
202 b1->Random();
203 allOneRHS = true;
204 }
205
206 Epetra_MultiVector x(vecMap, 1);
207
208 // Partition the matrix with hypergraph partitioning and redisstribute
209 Isorropia::Epetra::Partitioner *partitioner = new
210 Isorropia::Epetra::Partitioner(A, isoList, false);
211
212 Teuchos::Time ptime("Partition time");
213 ptime.start();
214 partitioner->partition();
215 ptime.stop();
216 if (myPID == 0)
217 {
218 cout << "Time to partition : " << ptime.totalElapsedTime() << endl << endl;
219 }
220
221 Teuchos::Time rtime("Redistribute time");
222 Isorropia::Epetra::Redistributor rd(partitioner);
223
224 Epetra_CrsMatrix *newA;
225 Epetra_MultiVector *newX, *newB;
226 rd.redistribute(*A, newA);
227 delete A;
228 A = newA;
229 RCP<Epetra_CrsMatrix> rcpA(A, false);
230
231 rtime.start();
232 rd.redistribute(x, newX);
233 rd.redistribute(*b1, newB);
234 rtime.stop();
235
236 delete b1;
237 RCP<Epetra_MultiVector> rcpx (newX, false);
238 RCP<Epetra_MultiVector> rcpb (newB, false);
239 //OPT::Apply(*rcpA, *rcpx, *rcpb );
240 if (myPID == 0)
241 {
242 cout << "Time to redistribute: " << rtime.totalElapsedTime() << endl << endl;
243 }
244
245 Epetra_CrsMatrix *iterA = 0;
246 Epetra_CrsMatrix *redistA = 0;
247 Epetra_MultiVector *iterb1 = 0;
248 Ifpack_Preconditioner *prec = nullptr;
249 ML_Epetra::MultiLevelPreconditioner *MLprec = nullptr;
250 while(file_number < maxFiles+startFile)
251 {
252
253 if (prec_type.compare("ShyLU") == 0)
254 {
255 if (file_number == startFile)
256 {
257 Teuchos::Time itime("Initialize time");
258 itime.start();
259 prec = new Ifpack_ShyLU(A);
260 #ifdef HAVE_IFPACK_DYNAMIC_FACTORY
261 Teuchos::ParameterList shyluParameters;
262 shyluParameters.set<Teuchos::ParameterList>("ShyLU list", shyLUList);
263 prec->SetParameters(shyluParameters);
264 #else
265 prec->SetParameters(shyLUList);
266 #endif
267 prec->Initialize();
268 itime.stop();
269 if (myPID == 0)
270 {
271 cout << "Time to initialiize : " << itime.totalElapsedTime() << endl << endl;
272 }
273 }
274 Teuchos::Time ftime("Compute time");
275 ftime.start();
276 prec->Compute();
277 ftime.stop();
278 if (myPID == 0)
279 {
280 cout << "Time to compute : " << ftime.totalElapsedTime() << endl << endl;
281 }
282 //cout << " Going to set it in solver" << endl ;
283 //solver.SetPrecOperator(prec);
284 //cout << " Done setting the solver" << endl ;
285 }
286 else if (prec_type.compare("ILU") == 0)
287 {
288 prec = new Ifpack_ILU(A);
289 prec->Initialize();
290 prec->Compute();
291 //solver.SetPrecOperator(prec);
292 }
293 else if (prec_type.compare("ILUT") == 0)
294 {
295 prec = new Ifpack_ILUT(A);
296 prec->Initialize();
297 prec->Compute();
298 //solver.SetPrecOperator(prec);
299 }
300 else if (prec_type.compare("ML") == 0)
301 {
302 Teuchos::ParameterList mlList; // TODO : Take it from i/p
303 MLprec = new ML_Epetra::MultiLevelPreconditioner(*A, mlList, true);
304 //solver.SetPrecOperator(MLprec);
305 }
306
307 RCP<Ifpack_Preconditioner> rcpPrec(prec, false);
308 RCP<Belos::EpetraPrecOp> belosPrec = rcp(new Belos::EpetraPrecOp(rcpPrec));
309
310 const int NumGlobalElements = rcpb->GlobalLength();
311 Teuchos::ParameterList belosList;
312 //belosList.set( "Flexible Gmres", true );
313 belosList.set( "Num Blocks", maxsubspace );// Maximum number of blocks in Krylov factorization
314 belosList.set( "Block Size", blocksize ); // Blocksize to be used by iterative solver
315 belosList.set( "Maximum Iterations", maxiters ); // Maximum number of iterations allowed
316 belosList.set( "Maximum Restarts", maxrestarts );// Maximum number of restarts allowed
317 belosList.set( "Convergence Tolerance", tol ); // Relative convergence tolerance requested
318 if (numrhs > 1) {
319 belosList.set( "Show Maximum Residual Norm Only", true ); // Show only the maximum residual norm
320 }
321 if (verbose) {
322 belosList.set( "Verbosity", Belos::Errors + Belos::Warnings +
323 Belos::TimingDetails + Belos::StatusTestDetails );
324 if (frequency > 0)
325 belosList.set( "Output Frequency", frequency );
326 }
327 else
328 belosList.set( "Verbosity", Belos::Errors + Belos::Warnings );
329 //
330 // *******Construct a preconditioned linear problem********
331 //
332
333 rcpx->PutScalar(0.0);
334 RCP<Belos::LinearProblem<double,MV,OP> > problem
335 = rcp( new Belos::LinearProblem<double,MV,OP>( rcpA, rcpx, rcpb ) );
336 if (leftprec) {
337 problem->setLeftPrec( belosPrec );
338 }
339 else {
340 problem->setRightPrec( belosPrec );
341 }
342 bool set = problem->setProblem();
343 if (set == false) {
344 if (proc_verbose)
345 {
346 cout << endl << "ERROR: Belos::LinearProblem failed to set up correctly!" << endl;
347 }
348 cout << fail << endl;
349 success = false;
350 return -1;
351 }
352
353 // Create an iterative solver manager.
354 RCP< Belos::SolverManager<double,MV,OP> > solver
355 = rcp( new Belos::BlockGmresSolMgr<double,MV,OP>(problem,
356 rcp(&belosList,false)));
357
358 //
359 // *******************************************************************
360 // *************Start the block Gmres iteration*************************
361 // *******************************************************************
362 //
363 if (proc_verbose && myPID == 0)
364 {
365 cout << std::endl << std::endl;
366 cout << "Dimension of matrix: " << NumGlobalElements << endl;
367 cout << "Number of right-hand sides: " << numrhs << endl;
368 cout << "Block size used by solver: " << blocksize << endl;
369 cout << "Number of restarts allowed: " << maxrestarts << endl;
370 cout << "Max number of Gmres iterations per restart cycle: " <<
371 maxiters << endl;
372 cout << "Relative residual tolerance: " << tol << endl;
373 cout << endl;
374 }
375
376 if(tol > 1e-5)
377 {
378 success = false;
379 }
380
381
382
383 //
384 // Perform solve
385 //
386 Teuchos::Time stime("Solve time");
387 stime.start();
388 solver->solve ();
389 stime.stop();
390 if (myPID == 0)
391 {
392 cout << "Time to solve : " << stime.totalElapsedTime() << endl << endl;
393 }
394
395 //
396 // Get the number of iterations for this solve.
397 //
398 int numIters = solver->getNumIters();
399 if (proc_verbose && myPID == 0)
400 {
401 cout << "Number of iterations performed for this solve: " <<
402 numIters << endl;
403 }
404 //
405 // Compute actual residuals.
406 //
407 //bool badRes = false; // unused
408 std::vector<double> actual_resids( numrhs );
409 std::vector<double> rhs_norm( numrhs );
410 Epetra_MultiVector resid((*rcpA).RowMap(), numrhs);
411 OPT::Apply( *rcpA, *rcpx, resid );
412 MVT::MvAddMv( -1.0, resid, 1.0, *rcpb, resid );
413 MVT::MvNorm( resid, actual_resids );
414 MVT::MvNorm( *rcpb, rhs_norm );
415 if (proc_verbose && myPID == 0)
416 {
417 cout<< "------ Actual Residuals (normalized) -------"<<endl;
418 for ( int i=0; i<numrhs; i++)
419 {
420 double actRes = actual_resids[i]/rhs_norm[i];
421 std::cout<<"Problem "<<i<<" : \t"<< actRes;
422 if (actRes > tol) {
423 //badRes = true; // unused
424 std::cout<<" (NOT CONVERGED)"<< std::endl;
425 success = false;
426 } else {
427 std::cout<<" (CONVERGED)"<< std::endl;
428 }
429 }
430 }
431
432 file_number++;
433 if (file_number >= maxFiles+startFile)
434 {
435 break;
436 }
437 else
438 {
439 sprintf(file_name, MMFileName.c_str(), file_number);
440
441 if (redistA != NULL) delete redistA;
442 // Load the new matrix
443 err = EpetraExt::MatrixMarketFileToCrsMatrix(file_name,
444 Comm, iterA);
445 if (err != 0)
446 {
447 if (myPID == 0)
448 {
449 cout << "Could not open file: "<< file_name << endl;
450
451 }
452 success = false;
453 }
454 else
455 {
456 rd.redistribute(*iterA, redistA);
457 delete iterA;
458 InitMatValues(*redistA, A);
459 }
460
461 // Load the new rhs
462 if (!allOneRHS)
463 {
464 sprintf(file_name, rhsFileName.c_str(), file_number);
465
466 if (iterb1 != NULL) delete iterb1;
467 err = EpetraExt::MatrixMarketFileToMultiVector(file_name,
468 vecMap, b1);
469 if (err != 0)
470 {
471 if (myPID==0)
472 {
473 cout << "Could not open file: "<< file_name << endl;
474 success = false;
475 }
476 }
477 else
478 {
479 rd.redistribute(*b1, iterb1);
480 delete b1;
481 InitMVValues( *iterb1, newB );
482 }
483 }
484 }
485 }
486 if (myPID == 0)
487 {
488 if(success)
489 {
490 cout << pass << endl;
491 }
492 else
493 {
494 cout << fail << endl;
495 }
496 }
497
498 if (redistA != NULL) delete redistA;
499 if (iterb1 != NULL) delete iterb1;
500
501
502 if (prec_type.compare("ML") == 0)
503 {
504 delete MLprec;
505 }
506 else
507 {
508 delete prec;
509 }
510 delete newX;
511 delete newB;
512 delete A;
513 delete partitioner;
514
515 return 0;
516 }
517
518 int InitMatValues( const Epetra_CrsMatrix& newA, Epetra_CrsMatrix* A )
519 {
520 int numMyRows = newA.NumMyRows();
521 int maxNum = newA.MaxNumEntries();
522 int numIn;
523 int *idx = 0;
524 double *vals = 0;
525
526 idx = new int[maxNum];
527 vals = new double[maxNum];
528
529 // For each row get the values and indices, and replace the values in A.
530 for (int i=0; i<numMyRows; ++i) {
531
532 // Get the values and indices from newA.
533 EPETRA_CHK_ERR( newA.ExtractMyRowCopy(i, maxNum, numIn, vals, idx) );
534
535 // Replace the values in A
536 EPETRA_CHK_ERR( A->ReplaceMyValues(i, numIn, vals, idx) );
537
538 }
539
540 // Clean up.
541 delete [] idx;
542 delete [] vals;
543
544 return 0;
545 }
546
547 int InitMVValues( const Epetra_MultiVector& newb, Epetra_MultiVector* b )
548 {
549 int length = newb.MyLength();
550 int numVecs = newb.NumVectors();
551 const Epetra_Vector *tempnewvec;
552 Epetra_Vector *tempvec = 0;
553
554 for (int i=0; i<numVecs; ++i) {
555 tempnewvec = newb(i);
556 tempvec = (*b)(i);
557 for (int j=0; j<length; ++j)
558 (*tempvec)[j] = (*tempnewvec)[j];
559 }
560
561 return 0;
562 }