Debian Codegraph @

packages/belos/epetra/example/LSQR/LSQREpetraExFile.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
13 // random right-hand sides. The initial guesses are all set to zero.
14 //
15 // NOTE: No preconditioner is used in this example.
16 //
17 #include "BelosConfigDefs.hpp"
18 #include "BelosLinearProblem.hpp"
19 #include "BelosEpetraAdapter.hpp"
20 #include "BelosLSQRSolMgr.hpp"
21
22 #include "EpetraExt_readEpetraLinearSystem.h"
23 #include "EpetraExt_MultiVectorIn.h"
24
25 #include "Epetra_Map.h"
26 #ifdef EPETRA_MPI
27 #include "Epetra_MpiComm.h"
28 #else
29 #include "Epetra_SerialComm.h"
30 #endif
31 #include "Epetra_CrsMatrix.h"
32
33 #include "Teuchos_CommandLineProcessor.hpp"
34 #include "Teuchos_ParameterList.hpp"
35 #include "Teuchos_StandardCatchMacros.hpp"
36
37 int main(int argc, char *argv[]) {
38 //
39 int MyPID = 0;
40 #ifdef EPETRA_MPI
41 // Initialize MPI
42 MPI_Init(&argc,&argv);
43 Epetra_MpiComm Comm(MPI_COMM_WORLD);
44 MyPID = Comm.MyPID();
45 #else
46 Epetra_SerialComm Comm;
47 #endif
48 //
49 typedef double ST;
50 typedef Teuchos::ScalarTraits<ST> SCT;
51 typedef SCT::magnitudeType MT;
52 typedef Epetra_MultiVector MV;
53 typedef Epetra_Operator OP;
54 typedef Belos::MultiVecTraits<ST,MV> MVT;
55 typedef Belos::OperatorTraits<ST,MV,OP> OPT;
56
57 using Teuchos::ParameterList;
58 using Teuchos::RCP;
59 using Teuchos::rcp;
60
61 bool verbose = false;
62 bool success = true;
63 try {
64 bool proc_verbose = false;
65 bool debug = false;
66 int frequency = -1; // frequency of status test output.
67 int blocksize = 1; // blocksize
68 int numrhs = 1; // number of right-hand sides to solve for
69 int maxiters = -1; // maximum number of iterations allowed per linear system
70 std::string filenameMatrix("orsirr1_scaled.hb");
71 std::string filenameRHS; // blank mean unset
72 MT relResTol = 3.0e-4; // relative residual tolerance
73 // Like CG, LSQR is a short recurrence method that
74 // does not have the "n" step convergence property in finite precision arithmetic.
75 MT resGrowthFactor = 4.0; // In this example, warn if |resid| > resGrowthFactor * relResTol
76 // With no preconditioner, this is only the difference between the "implicit" and the "explict
77 // residual.
78
79 MT relMatTol = 1.e-4; // relative Matrix error, default value sqrt(eps)
80 MT maxCond = 1.e+8; // maximum condition number default value 1/eps
81 MT damp = 0.; // regularization (or damping) parameter
82
83 Teuchos::CommandLineProcessor cmdp(false,true); // e.g. ./a.out --tol=.1 --filename=foo.hb
84
85 cmdp.setOption("verbose","quiet",&verbose,"Print messages and results.");
86 cmdp.setOption("debug","nondebug",&debug,"Print debugging information from solver.");
87 cmdp.setOption("frequency",&frequency,"Solvers frequency for printing residuals (#iters).");
88 cmdp.setOption("filename",&filenameMatrix,"Filename for test matrix. Acceptable file extensions: *.hb,*.mtx,*.triU,*.triS");
89 cmdp.setOption("rhsFilename",&filenameRHS,"Filename for right-hand side. Acceptable file extension: *.mtx");
90 cmdp.setOption("lambda",&damp,"Regularization parameter");
91 cmdp.setOption("tol",&relResTol,"Relative residual tolerance");
92 cmdp.setOption("matrixTol",&relMatTol,"Relative error in Matrix");
93 cmdp.setOption("max-cond",&maxCond,"Maximum condition number");
94 cmdp.setOption("num-rhs",&numrhs,"Number of right-hand sides to be solved for.");
95 cmdp.setOption("block-size",&blocksize,"Block size used by LSQR."); // must be one at this point
96 cmdp.setOption("max-iters",&maxiters,"Maximum number of iterations per linear system (-1 = adapted to problem/block size).");
97
98 if (cmdp.parse(argc,argv) != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL) {
99 #ifdef EPETRA_MPI
100 MPI_Finalize();
101 #endif
102 return -1;
103 }
104 if (!verbose)
105 frequency = -1; // reset frequency if test is not verbose
106 //
107 // Get the problem
108 //
109 RCP<Epetra_Map> Map;
110 RCP<Epetra_CrsMatrix> A;
111 RCP<Epetra_MultiVector> B, X;
112 RCP<Epetra_Vector> vecB, vecX;
113 EpetraExt::readEpetraLinearSystem(filenameMatrix, Comm, &A, &Map, &vecX, &vecB);
114 // Rectangular matrices are embedded in square matrices. vecX := 0, vecB = A*randVec
115 A->OptimizeStorage();
116 proc_verbose = verbose && (MyPID==0); /* Only print on the zero processor */
117
118 bool isRHS = false;
119 if ( filenameRHS != "" )
120 {
121 isRHS = true;
122 }
123
124 // Check to see if the number of right-hand sides is the same as requested.
125 if (numrhs>1) {
126 isRHS = false; // numrhs > 1 not yet supported
127 X = rcp( new Epetra_MultiVector( *Map, numrhs ) );
128 B = rcp( new Epetra_MultiVector( *Map, numrhs ) );
129 X->Random();
130 OPT::Apply( *A, *X, *B ); // B := AX
131 X->PutScalar( 0.0 ); // annihilate X
132 }
133 else {
134 if ( isRHS )
135 {
136 Epetra_MultiVector * BmustDelete;
137 int mmRHSioflag = 0;
138 const char * charPtrRHSfn = filenameRHS.c_str();
139 mmRHSioflag = EpetraExt::MatrixMarketFileToMultiVector(charPtrRHSfn, *Map, BmustDelete);
140 //std::cout << "rhs from input file " << std::endl;
141 //BmustDelete->Print(std::cout);
142
143 if( mmRHSioflag )
144 {
145 if (proc_verbose)
146 std::cout << "Error " << mmRHSioflag << " occured while attempting to read file " << filenameRHS << std::endl;
147 #ifdef EPETRA_MPI
148 MPI_Finalize();
149 #endif
150 return -1;
151 }
152 X = rcp( new Epetra_MultiVector( *Map, numrhs ) );
153 X->Scale( 0.0 );
154 B = rcp( new MV(*BmustDelete));
155 delete BmustDelete;
156 }
157 else
158 {
159 int locNumCol = Map->MaxLID() + 1; // Create a known solution
160 int globNumCol = Map->MaxAllGID() + 1;
161 for( int li = 0; li < locNumCol; li++){ // assume consecutive lid
162 int gid = Map->GID(li);
163 double value = (double) ( globNumCol -1 - gid );
164 int numEntries = 1;
165 vecX->ReplaceGlobalValues( numEntries, &value, &gid );
166 }
167 bool Trans = false;
168 A->Multiply( Trans, *vecX, *vecB ); // Create a consistent linear system
169 // At this point, the initial guess is exact.
170 bool goodInitGuess = true; // perturb initial guess
171 bool zeroInitGuess = false; // annihilate initial guess
172 if( goodInitGuess )
173 {
174 double value = 1.e-2; // "Rel RHS Err" and "Rel Mat Err" apply to the residual equation,
175 int numEntries = 1; // norm( b - A x_k ) ?<? relResTol norm( b- Axo).
176 int index = 0; // norm(b) is inaccessible to LSQR.
177 vecX->SumIntoMyValues( numEntries, &value, &index);
178 }
179 if( zeroInitGuess )
180 {
181 vecX->PutScalar( 0.0 ); //
182 }
183 X = Teuchos::rcp_implicit_cast<Epetra_MultiVector>(vecX);
184 B = Teuchos::rcp_implicit_cast<Epetra_MultiVector>(vecB);
185 }
186 }
187 //
188 // ********Other information used by block solver***********
189 // *****************(can be user specified)******************
190 //
191 const int NumGlobalElements = B->GlobalLength();
192 if (maxiters == -1)
193 maxiters = NumGlobalElements/blocksize - 1; // maximum number of iterations to run
194 ParameterList belosList; // mechanism for configuring specific linear solver
195 belosList.set( "Block Size", blocksize ); // LSQR blocksize, must be one
196 belosList.set( "Lambda", damp ); // Regularization parameter
197 belosList.set( "Rel RHS Err", relResTol ); // Relative convergence tolerance requested
198 belosList.set( "Rel Mat Err", relMatTol ); // Maximum number of restarts allowed
199 belosList.set( "Condition Limit", maxCond); // upper bound for cond(A)
200 belosList.set( "Maximum Iterations", maxiters );// Maximum number of iterations allowed
201 int verbosity = Belos::Errors + Belos::Warnings;
202 if (verbose) {
203 verbosity += Belos::TimingDetails + Belos::StatusTestDetails;
204 if (frequency > 0)
205 belosList.set( "Output Frequency", frequency );
206 }
207 if (debug) {
208 verbosity += Belos::Debug;
209 }
210 belosList.set( "Verbosity", verbosity );
211 //
212 // Construct an unpreconditioned linear problem instance.
213 //
214 Belos::LinearProblem<double,MV,OP> problem( A, X, B );
215 bool set = problem.setProblem();
216 if (set == false) {
217 if (proc_verbose)
218 {
219 std::cout << std::endl << "ERROR: Belos::LinearProblem failed to set up correctly!" << std::endl;
220 }
221 #ifdef EPETRA_MPI
222 MPI_Finalize();
223 #endif
224 return -1;
225 }
226 // *******************************************************************
227 // ******************* Apply Single Vector LSQR **********************
228 // *******************************************************************
229 // Create an iterative solver manager.
230 RCP< Belos::LSQRSolMgr<double,MV,OP> > newSolver
231 = rcp( new Belos::LSQRSolMgr<double,MV,OP>(rcp(&problem,false), rcp(&belosList,false)));
232
233 if (proc_verbose) { // ******** Print a problem description *********
234 std::cout << std::endl << std::endl;
235 std::cout << "Dimension of matrix: " << NumGlobalElements << std::endl;
236 std::cout << "Number of right-hand sides: " << numrhs << std::endl;
237 std::cout << "Block size used by solver: " << blocksize << std::endl;
238 std::cout << "Max number of iterations for a linear system: " << maxiters << std::endl;
239 std::cout << "Relative residual tolerance: " << relResTol << std::endl;
240 std::cout << std::endl;
241 std::cout << "Solver's Description: " << std::endl;
242 std::cout << newSolver->description() << std::endl; // visually verify the parameter list
243 }
244 Belos::ReturnType ret = newSolver->solve(); // Perform solve
245 std::vector<double> solNorm( numrhs ); // get solution norm
246 MVT::MvNorm( *X, solNorm );
247 int numIters = newSolver->getNumIters(); // get number of solver iterations
248 MT condNum = newSolver->getMatCondNum();
249 MT matrixNorm= newSolver->getMatNorm();
250 MT resNorm = newSolver->getResNorm();
251 MT lsResNorm = newSolver->getMatResNorm();
252
253 if (proc_verbose)
254 std::cout << "Number of iterations performed for this solve: " << numIters << std::endl
255 << "matrix condition number: " << condNum << std::endl
256 << "matrix norm: " << matrixNorm << std::endl
257 << "residual norm: " << resNorm << std::endl
258 << "solution norm: " << solNorm[0] << std::endl
259 << "least squares residual Norm: " << lsResNorm << std::endl;
260 bool badRes = false; // Compute the actual residuals.
261 std::vector<double> actual_resids( numrhs );
262 std::vector<double> rhs_norm( numrhs );
263 Epetra_MultiVector resid(*Map, numrhs);
264 OPT::Apply( *A, *X, resid );
265 MVT::MvAddMv( -1.0, resid, 1.0, *B, resid );
266 MVT::MvNorm( resid, actual_resids );
267 MVT::MvNorm( *B, rhs_norm );
268 if (proc_verbose) {
269 std::cout<< "---------- Actual Residuals (normalized) ----------"<<std::endl<<std::endl;
270 for ( int i=0; i<numrhs; i++) {
271 double actRes = actual_resids[i]/rhs_norm[i];
272 std::cout<<"Problem "<<i<<" : \t"<< actRes <<std::endl;
273 if (actRes > relResTol * resGrowthFactor)
274 {
275 badRes = true;
276 if (verbose) std::cout << "residual norm > " << relResTol * resGrowthFactor << std::endl;
277 }
278 }
279 }
280
281 if (ret!=Belos::Converged || badRes) {
282 success = false;
283 if (proc_verbose)
284 std::cout << std::endl << "ERROR: Belos did not converge!" << std::endl;
285 } else {
286 success = true;
287 if (proc_verbose)
288 std::cout << std::endl << "SUCCESS: Belos converged!" << std::endl;
289 }
290 }
291 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
292
293 #ifdef EPETRA_MPI
294 MPI_Finalize();
295 #endif
296
297 return success ? EXIT_SUCCESS : EXIT_FAILURE;
298 }