Debian Codegraph @

packages/belos/epetra/test/BiCGStab/PrecBiCGStabExFile.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 "BelosBiCGStabSolMgr.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 #include "Ifpack.h"
30
31 #include "Teuchos_CommandLineProcessor.hpp"
32 #include "Teuchos_ParameterList.hpp"
33 #include "Teuchos_StandardCatchMacros.hpp"
34
35 int main (int argc, char *argv[])
36 {
37 using Teuchos::ParameterList;
38 using Teuchos::RCP;
39 using Teuchos::rcp;
40 using std::cout;
41 using std::endl;
42 typedef double ST;
43 typedef Teuchos::ScalarTraits<ST> SCT;
44 typedef SCT::magnitudeType MT;
45 typedef Epetra_MultiVector MV;
46 typedef Epetra_Operator OP;
47 typedef Belos::MultiVecTraits<ST,MV> MVT;
48 typedef Belos::OperatorTraits<ST,MV,OP> OPT;
49
50 int MyPID = 0;
51 #ifdef EPETRA_MPI
52 MPI_Init (&argc, &argv);
53 Epetra_MpiComm Comm (MPI_COMM_WORLD);
54 MyPID = Comm.MyPID ();
55 #else
56 Epetra_SerialComm Comm;
57 #endif
58
59 bool verbose = false;
60 bool success = true;
61
62 // This "try" relates to TEUCHOS_STANDARD_CATCH_STATEMENTS near the
63 // bottom of main(). That macro has the corresponding "catch".
64 try {
65 bool proc_verbose = false;
66 bool leftprec = false; // left preconditioning or right.
67 int frequency = -1; // frequency of status test output.
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 filename ("cage4.hb");
71 MT tol = 1.0e-5; // relative residual tolerance
72
73 Teuchos::CommandLineProcessor cmdp(false,true);
74 cmdp.setOption ("verbose", "quiet", &verbose, "Whether to print messages "
75 "and results.");
76 cmdp.setOption ("left-prec", "right-prec", &leftprec, "Left or right "
77 "preconditioning.");
78 cmdp.setOption ("frequency", &frequency, "Frequency of solver output "
79 "(1 means every iteration; -1 means never).");
80 cmdp.setOption ("filename", &filename, "Test matrix filename. "
81 "Allowed file extensions: *.hb, *.mtx, *.triU, *.triS");
82 cmdp.setOption ("tol", &tol, "Relative residual tolerance for solver.");
83 cmdp.setOption ("num-rhs", &numrhs, "Number of right-hand sides to solve.");
84 cmdp.setOption ("max-iters", &maxiters, "Maximum number of iterations per "
85 "linear system (-1 = adapted to problem/block size).");
86 if (cmdp.parse (argc,argv) != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL) {
87 return -1;
88 }
89 if (! verbose) {
90 frequency = -1; // reset frequency if test is not verbose
91 }
92
93 //
94 // *************Get the problem*********************
95 //
96 RCP<Epetra_Map> Map;
97 RCP<Epetra_CrsMatrix> A;
98 RCP<Epetra_MultiVector> B, X;
99 RCP<Epetra_Vector> vecB, vecX;
100 EpetraExt::readEpetraLinearSystem (filename, Comm, &A, &Map, &vecX, &vecB);
101 A->OptimizeStorage ();
102 proc_verbose = verbose && (MyPID==0); /* Only print on the zero processor */
103
104 // Check to see if the number of right-hand sides is the same as requested.
105 if (numrhs > 1) {
106 X = rcp (new Epetra_MultiVector (*Map, numrhs));
107 B = rcp (new Epetra_MultiVector (*Map, numrhs));
108 X->Random ();
109 OPT::Apply (*A, *X, *B);
110 X->PutScalar (0.0);
111 }
112 else {
113 X = Teuchos::rcp_implicit_cast<Epetra_MultiVector> (vecX);
114 B = Teuchos::rcp_implicit_cast<Epetra_MultiVector> (vecB);
115 }
116
117 // FIXME (mfh 05 Aug 2015) Doesn't this negate what we just did
118 // above with numrhs > 1 ?
119 B->PutScalar (1.0);
120
121 //
122 // Construct preconditioner
123 //
124
125 // allocates an IFPACK factory. No data is associated
126 // to this object (only method Create()).
127 Ifpack Factory;
128
129 // create the preconditioner. For valid PrecType values,
130 // please check the documentation
131 std::string PrecType = "point relaxation stand-alone"; // incomplete Cholesky
132 int OverlapLevel = 0; // must be >= 0. If Comm.NumProc() == 1,
133 // it is ignored.
134
135 RCP<Ifpack_Preconditioner> Prec;
136 try {
137 Prec = rcp (Factory.Create (PrecType, &*A, OverlapLevel));
138 } catch (std::exception& e) {
139 std::ostringstream os;
140 os << "Ifpack preconditioner construction threw an exception: "
141 << e.what ();
142 TEUCHOS_TEST_FOR_EXCEPTION(true, std::runtime_error, os.str ());
143 }
144 TEUCHOS_TEST_FOR_EXCEPTION
145 (Prec.is_null (), std::runtime_error, "Failed to create Ifpack "
146 "preconditioner!");
147
148 try {
149 ParameterList ifpackList;
150 ifpackList.set ("relaxation: type", "Jacobi");
151 IFPACK_CHK_ERR( Prec->SetParameters (ifpackList) );
152 IFPACK_CHK_ERR( Prec->Initialize () );
153 IFPACK_CHK_ERR( Prec->Compute () );
154 } catch (std::exception& e) {
155 std::ostringstream os;
156 os << "Ifpack preconditioner setup threw an exception: " << e.what ();
157 TEUCHOS_TEST_FOR_EXCEPTION(true, std::runtime_error, os.str ());
158 }
159
160 // Create the Belos preconditioned operator from the Ifpack
161 // preconditioner. This is necessary because Belos expects an
162 // operator to apply the preconditioner with Apply(), NOT with
163 // ApplyInverse().
164 RCP<Belos::EpetraPrecOp> belosPrec = rcp (new Belos::EpetraPrecOp (Prec));
165
166 //
167 // Create parameter list for the Belos solver
168 //
169 const int NumGlobalElements = B->GlobalLength ();
170 if (maxiters == -1) {
171 maxiters = NumGlobalElements - 1; // maximum number of iterations to run
172 }
173 RCP<ParameterList> belosList (new ParameterList ("Belos"));
174 belosList->set ("Maximum Iterations", maxiters);
175 belosList->set ("Convergence Tolerance", tol);
176 if (verbose) {
177 belosList->set ("Verbosity", Belos::Errors + Belos::Warnings +
178 Belos::TimingDetails + Belos::StatusTestDetails);
179 if (frequency > 0) {
180 belosList->set ("Output Frequency", frequency);
181 }
182 }
183 else {
184 belosList->set ("Verbosity", Belos::Errors + Belos::Warnings +
185 Belos::FinalSummary);
186 }
187 //
188 // Construct a preconditioned linear problem
189 //
190 RCP<Belos::LinearProblem<double,MV,OP> > problem
191 = rcp (new Belos::LinearProblem<double,MV,OP> (A, X, B));
192 if (leftprec) {
193 problem->setLeftPrec (belosPrec);
194 }
195 else {
196 problem->setRightPrec (belosPrec);
197 }
198 bool set = problem->setProblem ();
199 if (! set) {
200 if (proc_verbose) {
201 cout << endl << "ERROR: Belos::LinearProblem failed to set up correctly!" << endl;
202 }
203 return -1;
204 }
205
206 // Create a Belos solver.
207 RCP<Belos::SolverManager<double,MV,OP> > solver
208 = rcp (new Belos::BiCGStabSolMgr<double,MV,OP> (problem, belosList));
209
210 if (proc_verbose) {
211 cout << endl << endl;
212 cout << "Dimension of matrix: " << NumGlobalElements << endl;
213 cout << "Number of right-hand sides: " << numrhs << endl;
214 cout << "Max number of CG iterations: " << maxiters << endl;
215 cout << "Relative residual tolerance: " << tol << endl;
216 cout << endl;
217 }
218
219 // Ask Belos to solve the linear system.
220 Belos::ReturnType ret = solver->solve();
221
222 //
223 // Compute actual residuals.
224 //
225 bool badRes = false;
226 std::vector<double> actual_resids (numrhs);
227 std::vector<double> rhs_norm (numrhs);
228 Epetra_MultiVector resid (*Map, numrhs);
229 OPT::Apply (*A, *X, resid);
230 MVT::MvAddMv (-1.0, resid, 1.0, *B, resid);
231 MVT::MvNorm (resid, actual_resids);
232 MVT::MvNorm (*B, rhs_norm);
233 if (proc_verbose) {
234 cout << "---------- Actual Residuals (normalized) ----------" << endl << endl;
235 for (int i = 0; i < numrhs; ++i) {
236 double actRes = actual_resids[i] / rhs_norm[i];
237 cout <<"Problem " << i << " : \t" << actRes << endl;
238 if (actRes > tol) {
239 badRes = true;
240 }
241 }
242 }
243
244 if (ret != Belos::Converged || badRes) {
245 success = false;
246 if (proc_verbose) {
247 cout << endl << "ERROR: Belos did not converge!" << endl
248 << "End Result: TEST FAILED" << endl;
249 }
250 } else {
251 success = true;
252 if (proc_verbose) {
253 cout << endl << "SUCCESS: Belos converged!" << endl
254 << "End Result: TEST PASSED" << endl;
255 }
256 }
257 }
258 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
259
260 #ifdef EPETRA_MPI
261 MPI_Finalize();
262 #endif
263
264 return success ? EXIT_SUCCESS : EXIT_FAILURE;
265 }