Debian Codegraph @

packages/belos/epetra/example/LSQR/PrecLSQREpetraExFile.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 // This driver reads a problem from a file, which can be in Harwell-Boeing (*.hb),
11 // Matrix Market (*.mtx), or triplet format (*.triU, *.triS). The right-hand side
12 // from the problem, if it exists, will be used instead of multiple random
13 // right-hand-sides. The initial guesses are all set to zero. An ILU preconditioner
14 // is constructed using the Ifpack factory.
15 //
16 #include "BelosConfigDefs.hpp"
17 #include "BelosLinearProblem.hpp"
18 #include "BelosEpetraAdapter.hpp"
19 #include "BelosLSQRSolMgr.hpp"
20
21 #include "EpetraExt_readEpetraLinearSystem.h"
22 #include "Epetra_Map.h"
23 #ifdef EPETRA_MPI
24 #include "Epetra_MpiComm.h"
25 #else
26 #include "Epetra_SerialComm.h"
27 #endif
28 #include "Epetra_CrsMatrix.h"
29
30 #include "Ifpack.h"
31
32 #include "Teuchos_CommandLineProcessor.hpp"
33 #include "Teuchos_ParameterList.hpp"
34 #include "Teuchos_StandardCatchMacros.hpp"
35
36 int main(int argc, char *argv[]) {
37 //
38 int MyPID = 0;
39 #ifdef EPETRA_MPI
40 // Initialize MPI
41 MPI_Init(&argc,&argv);
42 Epetra_MpiComm Comm(MPI_COMM_WORLD);
43 MyPID = Comm.MyPID();
44 #else
45 Epetra_SerialComm Comm;
46 #endif
47 //
48 typedef double ST;
49 typedef Teuchos::ScalarTraits<ST> SCT;
50 typedef SCT::magnitudeType MT;
51 typedef Epetra_MultiVector MV;
52 typedef Epetra_Operator OP;
53 typedef Belos::MultiVecTraits<ST,MV> MVT;
54 typedef Belos::OperatorTraits<ST,MV,OP> OPT;
55
56 using Teuchos::ParameterList;
57 using Teuchos::RCP;
58 using Teuchos::rcp;
59
60 bool verbose = false;
61 bool success = true;
62 try {
63 bool proc_verbose = false;
64 bool leftprec = true; // left preconditioning or right.
65 // LSQR applies the operator and the transposed operator.
66 // A preconditioner must support transpose multiply.
67 int frequency = -1; // frequency of status test output.
68 int blocksize = 1; // blocksize
69 // LSQR as currently implemented is a single vector algorithm.
70 // However some of the parameters that would be used by a block version
71 // have not been removed from this file.
72 int numrhs = 1; // number of right-hand sides to solve for
73 int maxiters = -1; // maximum number of iterations allowed per linear system
74 std::string filename("orsirr1_scaled.hb");
75 MT relResTol = 1.0e-5; // relative residual tolerance for the preconditioned linear system
76 MT resGrowthFactor = 1.0; // In this example, warn if |resid| > resGrowthFactor * relResTol
77
78 MT relMatTol = 1.e-10; // relative Matrix error, default value sqrt(eps)
79 MT maxCond = 1.e+5; // maximum condition number default value 1/eps
80 MT damp = 0.; // regularization (or damping) parameter
81
82 Teuchos::CommandLineProcessor cmdp(false,true);
83 cmdp.setOption("verbose","quiet",&verbose,"Print messages and results.");
84 cmdp.setOption("left-prec","right-prec",&leftprec,"Left preconditioning or right.");
85 cmdp.setOption("frequency",&frequency,"Solvers frequency for printing residuals (#iters).");
86 cmdp.setOption("filename",&filename,"Filename for test matrix. Acceptable file extensions: *.hb,*.mtx,*.triU,*.triS");
87 cmdp.setOption("lambda",&damp,"Regularization parameter");
88 cmdp.setOption("tol",&relResTol,"Relative residual tolerance");
89 cmdp.setOption("matrixTol",&relMatTol,"Relative error in Matrix");
90 cmdp.setOption("max-cond",&maxCond,"Maximum condition number");
91 cmdp.setOption("num-rhs",&numrhs,"Number of right-hand sides to be solved for.");
92 cmdp.setOption("block-size",&blocksize,"Block size used by LSQR.");
93 cmdp.setOption("max-iters",&maxiters,"Maximum number of iterations per linear system (-1 = adapted to problem/block size).");
94 if (cmdp.parse(argc,argv) != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL) {
95 return -1;
96 }
97 if (!verbose)
98 frequency = -1; // reset frequency if test is not verbose
99
100 //
101 // *************Get the problem*********************
102 //
103 RCP<Epetra_Map> Map;
104 RCP<Epetra_CrsMatrix> A;
105 RCP<Epetra_MultiVector> B, X;
106 RCP<Epetra_Vector> vecB, vecX;
107 EpetraExt::readEpetraLinearSystem(filename, Comm, &A, &Map, &vecX, &vecB);
108 A->OptimizeStorage();
109 proc_verbose = verbose && (MyPID==0); /* Only print on the zero processor */
110
111 // Check to see if the number of right-hand sides is the same as requested.
112 if (numrhs>1) {
113 X = rcp( new Epetra_MultiVector( *Map, numrhs ) );
114 B = rcp( new Epetra_MultiVector( *Map, numrhs ) );
115 X->Random();
116 OPT::Apply( *A, *X, *B );
117 X->PutScalar( 0.0 );
118 }
119 else {
120 int locNumCol = Map->MaxLID() + 1; // Create a known solution
121 int globNumCol = Map->MaxAllGID() + 1;
122 for( int li = 0; li < locNumCol; li++){ // assume consecutive lid
123 int gid = Map->GID(li);
124 double value = (double) ( globNumCol -1 - gid );
125 int numEntries = 1;
126 vecX->ReplaceGlobalValues( numEntries, &value, &gid );
127 }
128 bool Trans = false;
129 A->Multiply( Trans, *vecX, *vecB ); // Create a consistent linear system
130 // At this point, the initial guess is exact.
131 bool zeroInitGuess = false; // annihilate initial guess
132 bool goodInitGuess = true; // initial guess near solution
133 if( zeroInitGuess )
134 {
135 vecX->PutScalar( 0.0 );
136 }
137 else
138 {
139 if( goodInitGuess )
140 {
141 double value = 1.e-2; // "Rel RHS Err" and "Rel Mat Err" apply to the residual equation,
142 int numEntries = 1; // norm( b - A x_k ) ?<? relResTol norm( b- Axo).
143 int index = 0; // norm(b) is inaccessible to LSQR.
144 vecX->SumIntoMyValues( numEntries, &value, &index);
145 }
146 }
147 X = Teuchos::rcp_implicit_cast<Epetra_MultiVector>(vecX);
148 B = Teuchos::rcp_implicit_cast<Epetra_MultiVector>(vecB);
149 }
150 //
151 // ************Construct preconditioner*************
152 //
153 ParameterList ifpackList;
154
155 // allocates an IFPACK factory. No data is associated
156 // to this object (only method Create()).
157 Ifpack Factory; // do support transpose multiply
158
159 // create the preconditioner. For valid PrecType values,
160 // please check the documentation
161 std::string PrecType = "ILU"; // incomplete LU
162 int OverlapLevel = 1; // nonnegative
163
164 RCP<Ifpack_Preconditioner> Prec = Teuchos::rcp( Factory.Create(PrecType, &*A, OverlapLevel) );
165 assert(Prec != Teuchos::null);
166
167 // specify parameters for ILU
168 ifpackList.set("fact: level-of-fill", 1);
169 // the combine mode is on the following:
170 // "Add", "Zero", "Insert", "InsertAdd", "Average", "AbsMax"
171 // Their meaning is as defined in file Epetra_CombineMode.h
172 ifpackList.set("schwarz: combine mode", "Add");
173 // sets the parameters
174 IFPACK_CHK_ERR(Prec->SetParameters(ifpackList));
175
176 // initialize the preconditioner. At this point the matrix must
177 // have been FillComplete()'d, but actual values are ignored.
178 IFPACK_CHK_ERR(Prec->Initialize());
179
180 // Builds the preconditioners, by looking for the values of
181 // the matrix.
182 IFPACK_CHK_ERR(Prec->Compute());
183
184 {
185 const int errcode = Prec->SetUseTranspose (true);
186 if (errcode != 0) {
187 throw std::logic_error ("Oh hai! Ifpack_Preconditioner doesn't know how to apply its transpose.");
188 } else {
189 (void) Prec->SetUseTranspose (false);
190 }
191 }
192
193 // Create the Belos preconditioned operator from the Ifpack preconditioner.
194 // NOTE: This is necessary because Belos expects an operator to apply the
195 // preconditioner with Apply() NOT ApplyInverse().
196 RCP<Belos::EpetraPrecOp> belosPrec = rcp( new Belos::EpetraPrecOp( Prec ) );
197
198 //
199 // *****Create parameter list for the LSQR solver manager*****
200 //
201 const int NumGlobalElements = B->GlobalLength();
202 if (maxiters == -1)
203 maxiters = NumGlobalElements/blocksize - 1; // maximum number of iterations to run
204 //
205 ParameterList belosList;
206 belosList.set( "Block Size", blocksize ); // Blocksize to be used by iterative solver
207 belosList.set( "Lambda", damp ); // Regularization parameter
208 belosList.set( "Rel RHS Err", relResTol ); // Relative convergence tolerance requested
209 belosList.set( "Rel Mat Err", relMatTol ); // Maximum number of restarts allowed
210 belosList.set( "Condition Limit", maxCond); // upper bound for cond(A)
211 belosList.set( "Maximum Iterations", maxiters );// Maximum number of iterations allowed
212 if (numrhs > 1) {
213 belosList.set( "Show Maximum Residual Norm Only", true ); // Show only the maximum residual norm
214 }
215 if (verbose) {
216 belosList.set( "Verbosity", Belos::Errors + Belos::Warnings +
217 Belos::TimingDetails + Belos::StatusTestDetails );
218 if (frequency > 0)
219 belosList.set( "Output Frequency", frequency );
220 }
221 else
222 belosList.set( "Verbosity", Belos::Errors + Belos::Warnings );
223 //
224 // *******Construct a preconditioned linear problem********
225 //
226 RCP<Belos::LinearProblem<double,MV,OP> > problem
227 = rcp( new Belos::LinearProblem<double,MV,OP>( A, X, B ) );
228 if (leftprec) {
229 problem->setLeftPrec( belosPrec );
230 }
231 else {
232 problem->setRightPrec( belosPrec );
233 }
234 bool set = problem->setProblem();
235 if (set == false) {
236 if (proc_verbose)
237 std::cout << std::endl << "ERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
238 return -1;
239 }
240
241 // Create an iterative solver manager.
242 RCP< Belos::LSQRSolMgr<double,MV,OP> > solver
243 = rcp( new Belos::LSQRSolMgr<double,MV,OP>(problem, rcp(&belosList,false)));
244
245 //
246 // *******************************************************************
247 // ******************Start the LSQR iteration*************************
248 // *******************************************************************
249 //
250 if (proc_verbose) {
251 std::cout << std::endl << std::endl;
252 std::cout << "Dimension of matrix: " << NumGlobalElements << std::endl;
253 std::cout << "Number of right-hand sides: " << numrhs << std::endl;
254 std::cout << "Block size used by solver: " << blocksize << std::endl;
255 std::cout << "Max number of Gmres iterations per restart cycle: " << maxiters << std::endl;
256 std::cout << "Relative residual tolerance: " << relResTol << std::endl;
257 std::cout << std::endl;
258 std::cout << "Solver's Description: " << std::endl;
259 std::cout << solver->description() << std::endl; // visually verify the parameter list
260 }
261 //
262 // Perform solve
263 //
264 Belos::ReturnType ret = solver->solve();
265 //
266 // Get the number of iterations for this solve.
267 //
268 std::vector<double> solNorm( numrhs ); // get solution norm
269 MVT::MvNorm( *X, solNorm );
270 int numIters = solver->getNumIters();
271 MT condNum = solver->getMatCondNum();
272 MT matrixNorm= solver->getMatNorm();
273 MT resNorm = solver->getResNorm();
274 MT lsResNorm = solver->getMatResNorm();
275 if (proc_verbose)
276 std::cout << "Number of iterations performed for this solve: " << numIters << std::endl
277 << "matrix condition number: " << condNum << std::endl
278 << "matrix norm: " << matrixNorm << std::endl
279 << "residual norm: " << resNorm << std::endl
280 << "solution norm: " << solNorm[0] << std::endl
281 << "least squares residual Norm: " << lsResNorm << std::endl;
282 //
283 // Compute actual residuals.
284 //
285 bool badRes = false;
286 std::vector<double> actual_resids( numrhs );
287 std::vector<double> rhs_norm( numrhs );
288 Epetra_MultiVector resid(*Map, numrhs);
289 OPT::Apply( *A, *X, resid );
290 MVT::MvAddMv( -1.0, resid, 1.0, *B, resid );
291 MVT::MvNorm( resid, actual_resids );
292 MVT::MvNorm( *B, rhs_norm );
293 if (proc_verbose) {
294 std::cout<< "---------- Actual Residuals (normalized) ----------"<<std::endl<<std::endl;
295 for ( int i=0; i<numrhs; i++) {
296 double actRes = actual_resids[i]/rhs_norm[i];
297 std::cout<<"Problem "<<i<<" : \t"<< actRes <<std::endl;
298 if (actRes > relResTol * resGrowthFactor ) badRes = true;
299 }
300 }
301
302 if (ret!=Belos::Converged || badRes) {
303 success = false;
304 if (proc_verbose)
305 std::cout << std::endl << "ERROR: Belos did not converge!" << std::endl;
306 } else {
307 success = true;
308 if (proc_verbose)
309 std::cout << std::endl << "SUCCESS: Belos converged!" << std::endl;
310 }
311 }
312 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
313
314 #ifdef EPETRA_MPI
315 MPI_Finalize();
316 #endif
317
318 return success ? EXIT_SUCCESS : EXIT_FAILURE;
319 }