Debian Codegraph @

packages/belos/tpetra/test/BlockGmres/test_bl_gmres_hb_df.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 Harwell-Boeing (HB) file.
11 // The right-hand-side corresponds to a randomly generated solution.
12 // The initial guesses are all set to zero.
13 // The problem is solver for multiple scalar types, and timings are reported.
14 //
15 // NOTE: No preconditioner is used in this case.
16 //
17 #include "BelosConfigDefs.hpp"
18 #include "BelosLinearProblem.hpp"
19 #include "BelosTpetraAdapter.hpp"
20 #include "BelosBlockGmresSolMgr.hpp"
21
22 // I/O for Harwell-Boeing files
23 #include <Trilinos_Util_iohb.h>
24
25 #include <Teuchos_CommandLineProcessor.hpp>
26 #include <Teuchos_ScalarTraits.hpp>
27 #include <Tpetra_Core.hpp>
28 #include <Tpetra_CrsMatrix.hpp>
29 #include <Teuchos_TypeNameTraits.hpp>
30
31 #include <fstream>
32
33 using namespace Teuchos;
34 using namespace Belos;
35 using Tpetra::Operator;
36 using Tpetra::CrsMatrix;
37 using Tpetra::MultiVector;
38 using Tpetra::Vector;
39 using Tpetra::Map;
40 using std::endl;
41 using std::cout;
42 using std::string;
43 using std::setw;
44 using std::vector;
45 using Teuchos::tuple;
46
47 bool proc_verbose = false, reduce_tol = false, dumpdata = false;
48 ParameterList mptestpl;
49 int rnnzmax;
50 int mptestdim, numrhs;
51 double *dvals;
52 int *colptr, *rowind;
53 int mptestmypid = 0;
54 int mptestnumimages = 1;
55
56 ///////////////////////////////////////////////////////////////////////////
57 ///////////////////////////////////////////////////////////////////////////
58 template <class Scalar>
59 RCP<LinearProblem<Scalar,Tpetra::MultiVector<Scalar>,Tpetra::Operator<Scalar> > > buildProblem(const RCP<Map<> >& vmap)
60 {
61 typedef ScalarTraits<Scalar> SCT;
62 typedef Tpetra::Operator<Scalar> OP;
63 typedef Tpetra::MultiVector<Scalar> MV;
64 typedef OperatorTraits<Scalar,MV,OP> OPT;
65 typedef MultiVecTraits<Scalar,MV> MVT;
66 using GO = typename MV::global_ordinal_type;
67 RCP<CrsMatrix<Scalar> > A = rcp(new CrsMatrix<Scalar>(vmap,rnnzmax));
68 if (mptestmypid == 0) {
69 // HB format is compressed column. CrsMatrix is compressed row.
70 const double *dptr = dvals;
71 const int *rptr = rowind;
72 for (int c=0; c<mptestdim; ++c) {
73 for (int colnnz=0; colnnz < colptr[c+1]-colptr[c]; ++colnnz) {
74 A->insertGlobalValues(*rptr-1,tuple<GO>(c),tuple<Scalar>(*dptr));
75 if (c != *rptr -1) {
76 A->insertGlobalValues(c,tuple<GO>(*rptr-1),tuple<Scalar>(*dptr));
77 }
78 ++rptr;
79 ++dptr;
80 }
81 }
82 }
83 // distribute matrix data to other nodes
84 A->fillComplete();
85 // Create initial MV and solution MV
86 RCP<MV> B, X;
87 X = rcp( new MV(vmap,numrhs) );
88 MVT::MvRandom( *X );
89 B = rcp( new MV(vmap,numrhs) );
90 OPT::Apply( *A, *X, *B );
91 MVT::MvInit( *X, 0.0 );
92 // Construct a linear problem instance with zero initial MV
93 RCP<LinearProblem<Scalar,MV,OP> > problem = rcp( new LinearProblem<Scalar,MV,OP>(A,X,B) );
94 problem->setLabel(Teuchos::typeName(SCT::one()));
95 TEUCHOS_TEST_FOR_EXCEPT(problem->setProblem() == false);
96 return problem;
97 }
98
99
100 ///////////////////////////////////////////////////////////////////////////
101 ///////////////////////////////////////////////////////////////////////////
102 template <class Scalar>
103 bool runTest(double ltol, double times[], int &numIters, const RCP<Map<> >& vmap)
104 {
105 typedef ScalarTraits<Scalar> SCT;
106 typedef typename SCT::magnitudeType MT;
107 typedef Tpetra::Operator<Scalar> OP;
108 typedef Tpetra::MultiVector<Scalar> MV;
109 typedef OperatorTraits<Scalar,MV,OP> OPT;
110 typedef MultiVecTraits<Scalar,MV> MVT;
111
112 const Scalar ONE = SCT::one();
113 mptestpl.set<MT>( "Convergence Tolerance", ltol ); // Relative convergence tolerance requested
114 mptestpl.set( "Timer Label", typeName(ONE) ); // Set timer label to discern between the two solvers.
115
116 if (mptestmypid==0) cout << "Testing Scalar == " << typeName(ONE) << endl;
117
118 RCP<LinearProblem<Scalar,MV,OP> > problem;
119 Time btimer("Build Timer"), ctimer("Construct Timer"), stimer("Solve Timer");
120 ReturnType ret;
121 if (mptestmypid==0) cout << "Building problem..." << endl;
122 {
123 TimeMonitor localtimer(btimer);
124 problem = buildProblem<Scalar>(vmap);
125 }
126 RCP<SolverManager<Scalar,MV,OP> > solver;
127 if (mptestmypid==0) cout << "Constructing solver..." << endl;
128 {
129 TimeMonitor localtimer(ctimer);
130 solver = rcp(new BlockGmresSolMgr<Scalar,MV,OP>( problem, rcpFromRef(mptestpl) ));
131 }
132 if (mptestmypid==0) cout << "Solving problem..." << endl;
133 {
134 TimeMonitor localtimer(stimer);
135 try {
136 ret = solver->solve();
137 }
138 catch (std::exception &e) {
139 cout << "Caught exception: " << endl << e.what() << endl;
140 ret = Unconverged;
141 }
142 }
143 numIters = solver->getNumIters();
144 times[0] = btimer.totalElapsedTime();
145 times[1] = ctimer.totalElapsedTime();
146 times[2] = stimer.totalElapsedTime();
147
148 bool badRes = false;
149 if (ret == Converged) {
150 if (proc_verbose) cout << endl;
151 if (mptestmypid==0) cout << "Computing residuals..." << endl;
152 //
153 // Compute actual residuals.
154 //
155 RCP<const OP> A = problem->getOperator();
156 RCP<MV> X = problem->getLHS();
157 RCP<const MV> B = problem->getRHS();
158 std::vector<MT> actual_resids( numrhs );
159 std::vector<MT> rhs_norm( numrhs );
160 MV resid(vmap, numrhs);
161 OPT::Apply( *A, *X, resid );
162 MVT::MvAddMv( -ONE, resid, ONE, *B, resid );
163 MVT::MvNorm( resid, actual_resids );
164 MVT::MvNorm( *B, rhs_norm );
165 if (proc_verbose) cout << "Actual Residuals (normalized)" << endl;
166 for ( int i=0; i<numrhs; i++) {
167 MT actRes = actual_resids[i]/rhs_norm[i];
168 if (proc_verbose) cout << "Problem "<<i<<" : \t"<< actRes <<endl;
169 if (actRes > ltol) badRes = true;
170 }
171 if (proc_verbose) cout << endl;
172 }
173 if (ret != Converged || badRes) return false;
174 return true;
175 }
176
177
178 ///////////////////////////////////////////////////////////////////////////
179 ///////////////////////////////////////////////////////////////////////////
180 int main(int argc, char *argv[])
181 {
182 Tpetra::ScopeGuard tpetraScope(&argc, &argv);
183
184 RCP<const Comm<int> > comm = Tpetra::getDefaultComm();
185
186 //
187 // Get test parameters from command-line processor
188 //
189 bool verbose = false, debug = false;
190 int frequency = -1; // how often residuals are printed by solver
191 int maxiters = -1; // maximum number of iterations for solver to use
192 numrhs = 1; // total number of right-hand sides to solve for
193 int blocksize = 1; // blocksize used by solver
194 string filename("bcsstk14.hb");
195 double tol = 1.0e-5; // relative residual tolerance
196
197 CommandLineProcessor cmdp(false,true);
198 cmdp.setOption("verbose","quiet",&verbose,"Print messages and results.");
199 cmdp.setOption("debug","nodebug",&debug,"Run debugging checks.");
200 cmdp.setOption("frequency",&frequency,"Solvers frequency for printing residuals (#iters).");
201 cmdp.setOption("tol",&tol,"Relative residual tolerance used by solver.");
202 cmdp.setOption("filename",&filename,"Filename for Harwell-Boeing test matrix.");
203 cmdp.setOption("num-rhs",&numrhs,"Number of right-hand sides to be solved for.");
204 cmdp.setOption("block-size",&blocksize,"Block size to be used by the solver.");
205 cmdp.setOption("max-iters",&maxiters,"Maximum number of iterations per linear system (-1 := adapted to problem/block size).");
206 cmdp.setOption("reduce-tol","fixed-tol",&reduce_tol,"Require increased accuracy from higher precision scalar types.");
207 cmdp.setOption("dump-data","no-dump-data",&dumpdata,"Dump raw data to data.dat.");
208 if (cmdp.parse(argc,argv) != CommandLineProcessor::PARSE_SUCCESSFUL) {
209 return -1;
210 }
211 if (debug) {
212 verbose = true;
213 }
214 if (!verbose) {
215 frequency = -1; // reset frequency if test is not verbose
216 }
217
218 mptestnumimages = size(*comm);
219 mptestmypid = rank(*comm);
220 proc_verbose = ( verbose && (mptestmypid==0) );
221 if (proc_verbose) cout << Belos_Version() << endl << endl;
222 if (mptestmypid != 0) dumpdata = 0;
223
224 //
225 // Get the data (double) from the HB file and build the Map,Matrix
226 //
227 int nnz, info;
228 nnz = -1;
229 if (mptestmypid == 0) {
230 int dim2;
231 info = readHB_newmat_double(filename.c_str(),&mptestdim,&dim2,&nnz,&colptr,&rowind,&dvals);
232 // find maximum NNZ over all rows
233 vector<int> rnnz(mptestdim,0);
234 for (int *ri=rowind; ri<rowind+nnz; ++ri) {
235 ++rnnz[*ri-1];
236 }
237 for (int c=0; c<mptestdim; ++c) {
238 rnnz[c] += colptr[c+1]-colptr[c];
239 }
240 rnnzmax = *std::max_element(rnnz.begin(),rnnz.end());
241 }
242 else {
243 // address uninitialized data warnings
244 dvals = NULL;
245 colptr = NULL;
246 rowind = NULL;
247 }
248 broadcast(*comm,0,&info);
249 broadcast(*comm,0,&nnz);
250 broadcast(*comm,0,&mptestdim);
251 broadcast(*comm,0,&rnnzmax);
252 if (info == 0 || nnz < 0) {
253 if (mptestmypid == 0) {
254 cout << "Error reading '" << filename << "'" << endl
255 << "End Result: TEST FAILED" << endl;
256 }
257 return -1;
258 }
259
260 // Select maximum iterations
261 if (maxiters == -1) {
262 maxiters = mptestdim/blocksize - 1; // maximum number of iterations to run
263 }
264
265 // create map
266 RCP<Map<> > vmap = rcp(new Map<>(mptestdim,0,comm));
267 //
268 mptestpl.set( "Block Size", blocksize ); // Blocksize to be used by iterative solver
269 mptestpl.set( "Num Blocks", maxiters );
270 mptestpl.set( "Maximum Iterations", maxiters );
271 int verbLevel = Errors + Warnings;
272 if (debug) {
273 verbLevel |= Debug;
274 }
275 if (verbose) {
276 verbLevel |= TimingDetails + FinalSummary + StatusTestDetails;
277 }
278 mptestpl.set( "Verbosity", verbLevel );
279 if (verbose) {
280 if (frequency > 0) {
281 mptestpl.set( "Output Frequency", frequency );
282 }
283 }
284
285 //
286 // **********Print out information about problem*******************
287 //
288 if (mptestmypid==0) {
289 cout << "Filename: " << filename << endl;
290 cout << "Dimension of matrix: " << mptestdim << endl;
291 cout << "Number of nonzeros: " << nnz << endl;
292 cout << "Number of right-hand sides: " << numrhs << endl;
293 cout << "Block size used by solver: " << blocksize << endl;
294 cout << "Number of blocks used by solver: " << maxiters << endl;
295 cout << "Relative residual tolerance: " << tol << endl;
296 cout << endl;
297 }
298
299 // run tests for different scalar types
300 double ltol = tol;
301 double ftime[3] = {0,0,0}; int fiter=0;
302 bool fpass = true, dpass = true;
303 #ifdef HAVE_TPETRA_INST_FLOAT
304 fpass = runTest<float>(ltol,ftime,fiter,vmap);
305 #endif
306 ltol = (reduce_tol ? ltol*ltol : ltol);
307 double dtime[3] = {0,0,0}; int diter=0;
308 #ifdef HAVE_TPETRA_INST_DOUBLE
309 dpass = runTest<double>(ltol,dtime,diter,vmap);
310 #endif
311
312 // done with the matrix data now; delete it
313 if (mptestmypid == 0) {
314 free( dvals );
315 free( colptr );
316 free( rowind );
317 }
318
319 if (mptestmypid==0) {
320 cout << "Scalar field Build time Init time Solve time Num Iters Test Passsed" << endl;
321 cout << "---------------------------------------------------------------------------------------" << endl;
322 cout << setw(12) << "float" << " " << setw(10) << ftime[0] << " " << setw(9) << ftime[1] << " " << setw(10) << ftime[2] << " " << setw(9) << fiter << " " << ( fpass ? "pass" : "fail") << endl;
323 cout << setw(12) << "double" << " " << setw(10) << dtime[0] << " " << setw(9) << dtime[1] << " " << setw(10) << dtime[2] << " " << setw(9) << diter << " " << ( dpass ? "pass" : "fail") << endl;
324 }
325
326 if (dumpdata) {
327 std::ofstream fout("data.dat",std::ios_base::app | std::ios_base::out);
328 fout << setw(80) << "filename" << setw(14) << "numimages" << setw(14) << "blocksize" << setw(14) << "maxiters" << setw(14) << "dim" << setw(14) << "nnz" << setw(8) << "Scalar" << setw(12) << "build" << setw(12) << "init" << setw(12) << "solve" << setw(12) << "numiter" << endl;
329 fout << setw(80) << filename << setw(14) << mptestnumimages << setw(14) << blocksize << setw(14) << maxiters << setw(14) << mptestdim << setw(14) << nnz << setw(8) << "float" << setw(12) << ftime[0] << setw(12) << ftime[1] << setw(12) << ftime[2] << setw(12) << fiter << endl;
330 fout << setw(80) << filename << setw(14) << mptestnumimages << setw(14) << blocksize << setw(14) << maxiters << setw(14) << mptestdim << setw(14) << nnz << setw(8) << "double" << setw(12) << dtime[0] << setw(12) << dtime[1] << setw(12) << dtime[2] << setw(12) << diter << endl;
331 fout.close();
332 }
333
334 bool allpass = fpass && dpass;
335
336 if (!allpass) {
337 if (mptestmypid==0) cout << "\nEnd Result: TEST FAILED" << endl;
338 return -1;
339 }
340 //
341 // Default return value
342 //
343 if (mptestmypid==0) cout << "\nEnd Result: TEST PASSED" << endl;
344 return 0;
345 }