Debian Codegraph @

packages/belos/tpetra/src/BelosTpetraTestFramework.hpp

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 #ifndef __Belos_TpetraTestFramework_hpp
11 #define __Belos_TpetraTestFramework_hpp
12
13 /// \file BelosTpetraTestFramework.hpp
14 /// \brief A common test framework for Tpetra instantiations of Belos solvers.
15 /// \author Mark Hoemmen
16
17 #include "BelosTpetraAdapter.hpp"
18 #include "MatrixMarket_Tpetra.hpp"
19 #include "Teuchos_ArrayView.hpp"
20 #include "Teuchos_FancyOStream.hpp"
21 #include "Teuchos_oblackholestream.hpp"
22 #include "Teuchos_ParameterListAcceptorDefaultBase.hpp"
23 #include "Teuchos_TypeNameTraits.hpp"
24 #include "Trilinos_Util_iohb.h"
25
26 namespace Belos {
27 namespace Tpetra {
28
29 /// \function convertData
30 template<class scalar>
31 void convertData( const double* dPtr, const int nnz, scalar* retVals );
32
33 template<>
34 void convertData( const double* dPtr, const int nnz, double* retVals )
35 {
36 for ( int i=0; i<nnz; ++i )
37 retVals[i] = dPtr[i];
38 }
39
40 template<>
41 void convertData( const double* dPtr, const int nnz, float* retVals )
42 {
43 for ( int i=0; i<nnz; ++i )
44 retVals[i] = (float) dPtr[i];
45 }
46
47
48 template<>
49 void convertData( const double* dPtr, const int nnz, std::complex<double>* retVals )
50 {
51 for ( int i=0; i<nnz; ++i )
52 retVals[i] = std::complex<double>( dPtr[2*i], dPtr[2*i+1] );
53 }
54
55 /// \class HarwellBoeingReader
56 /// \brief Read a Harwell-Boeing format file into a Tpetra::CrsMatrix.
57 /// \author Mark Hoemmen
58 ///
59 /// \warning This reader is incomplete. It currently only handles
60 /// double-precision floating-point data and some of the possible
61 /// representations to create float, real, and complex-valued matrices.
62 template<class SparseMatrixType>
63 class HarwellBoeingReader {
64
65 typedef SparseMatrixType sparse_matrix_type;
66 typedef typename SparseMatrixType::scalar_type scalar_type;
67 typedef typename SparseMatrixType::local_ordinal_type local_ordinal_type;
68 typedef typename SparseMatrixType::global_ordinal_type global_ordinal_type;
69 typedef typename SparseMatrixType::node_type node_type;
70
71 public:
72 /// \typedef multivector_type
73 /// \brief Specialization of \c Tpetra::MultiVector.
74 ///
75 /// This class deduces the \c Tpeta::MultiVector specialization
76 /// from the \c Tpetra::CrsMatrix specialization. This ensures
77 /// compatibility of the sparse matrix type with the dense
78 /// multivector type.
79 typedef ::Tpetra::MultiVector<scalar_type,
80 local_ordinal_type,
81 global_ordinal_type,
82 node_type> multivector_type;
83 /// \typedef map_type
84 /// \brief Specialization of \c Tpetra::Map.
85 ///
86 /// This class deduces the \c Tpeta::Map specialization from the
87 /// \c Tpetra::CrsMatrix specialization. This ensures
88 /// compatibility of the sparse matrix type with the map type.
89 typedef ::Tpetra::Map<local_ordinal_type,
90 global_ordinal_type,
91 node_type> map_type;
92
93 /// \brief Constructor.
94 ///
95 /// \param comm [in] Communicator over which to distribute the
96 /// sparse matrices.
97 HarwellBoeingReader (const Teuchos::RCP<const Teuchos::Comm<int> >& comm) :
98 comm_ (comm)
99 {}
100
101 //! Read the sparse matrix from the file with the given name.
102 Teuchos::RCP<sparse_matrix_type>
103 readFromFile (const std::string& filename)
104 {
105 //
106 // Get the data from the HB file and build the Map,Matrix
107 //
108 int MyPID = rank(*comm_);
109 int info = 0;
110 int dim,dim2,nnz,rnnzmax;
111 double *dvals;
112 int *colptr,*rowind;
113 nnz = -1;
114 if (MyPID == 0) {
115 info = readHB_newmat_double(filename.c_str(),&dim,&dim2,&nnz,&colptr,&rowind,&dvals);
116 // find maximum NNZ over all rows
117 std::vector<int> rnnz(dim,0);
118 for (int *ri=rowind; ri<rowind+nnz; ++ri) {
119 ++rnnz[*ri-1];
120 }
121 rnnzmax = *std::max_element(rnnz.begin(),rnnz.end());
122 }
123 else {
124 // address uninitialized data warnings
125 dvals = NULL;
126 colptr = NULL;
127 rowind = NULL;
128 }
129 Teuchos::broadcast(*comm_,0,&info);
130 Teuchos::broadcast(*comm_,0,&nnz);
131 Teuchos::broadcast(*comm_,0,&dim);
132 Teuchos::broadcast(*comm_,0,&rnnzmax);
133
134 TEUCHOS_TEST_FOR_EXCEPTION((info == 0 || nnz < 0), std::runtime_error,
135 "HarwellBoeingReader::readFromFile: Failed to read Harwell-Boeing "
136 "sparse matrix file: readHB_newmat_double() returned INFO = "
137 << info << ".");
138
139 // create map
140 Teuchos::RCP<const ::Tpetra::Map<> > map = Teuchos::rcp (new ::Tpetra::Map<> (dim, 0, comm_));
141 Teuchos::RCP<sparse_matrix_type> A = Teuchos::rcp(new sparse_matrix_type(map, rnnzmax));
142 if (MyPID == 0) {
143 // HB format is compressed column. CrsMatrix is compressed row.
144 scalar_type* svals = new scalar_type[ nnz ];
145 convertData<scalar_type>( dvals, nnz, svals );
146 const scalar_type *sptr = svals;
147 const int *rptr = rowind;
148 for (int c=0; c<dim; ++c) {
149 for (int colnnz=0; colnnz < colptr[c+1]-colptr[c]; ++colnnz) {
150 A->insertGlobalValues (static_cast<global_ordinal_type> (*rptr++ - 1),
151 Teuchos::tuple<global_ordinal_type> (c),
152 Teuchos::tuple (sptr[0]));
153 sptr++;
154 }
155 }
156
157 // Clean up.
158 free( svals );
159 free( dvals );
160 free( colptr );
161 free( rowind );
162 }
163
164 A->fillComplete();
165 return A;
166 }
167
168 private:
169 //! Communicator over which to distribute the sparse matrices.
170 Teuchos::RCP<const Teuchos::Comm<int> > comm_;
171
172 /// \brief Convert the Harwell-Boeing data to a Tpetra::CrsMatrix.
173 ///
174 /// \note We allow the values and indices read from the file to
175 /// have different types than the types of the sparse matrix's
176 /// values resp. global indices. This is why this method is
177 /// templated on ValueType and IndexType, which are the types
178 /// of values resp. indices found in the file.
179 template<class ValueType>
180 void
181 insertValues (Teuchos::RCP<sparse_matrix_type>& A,
182 const double* dptr, const int *rind, const int *cptr );
183
184 };
185
186 /// \class ProblemMaker
187 /// \brief Make a test linear problem using Tpetra objects.
188 /// \author Mark Hoemmen
189 ///
190 /// \tparam SparseMatrixType A specialization of Tpetra::CrsMatrix.
191 ///
192 /// This class is useful for testing the Tpetra specialization of
193 /// Belos solvers. It is meant as a rudimentary version of Galeri
194 /// (which currently only creates Epetra objects) and avoids
195 /// duplicated code in the Tpetra tests.
196 ///
197 /// This class is templated on a specialization of \c
198 /// Tpetra::CrsMatrix. This saves users the trouble of needing to
199 /// know all five template arguments of their Tpetra::CrsMatrix
200 /// specialization in order to get the right sparse matrix type.
201 /// This class uses the typedefs of \c Tpetra::CrsMatrix to deduce
202 /// the \c Tpetra::MultiVector specialization to use.
203 ///
204 /// \note To Belos developers: using objects in the Tpetra
205 /// namespace in this class requires prefixing the Tpetra
206 /// namespace with ::, as in \c ::Tpetra::Map for example.
207 template<class SparseMatrixType>
208 class ProblemMaker : public Teuchos::ParameterListAcceptorDefaultBase {
209 public:
210 typedef SparseMatrixType sparse_matrix_type;
211 typedef typename SparseMatrixType::scalar_type scalar_type;
212 typedef typename SparseMatrixType::local_ordinal_type local_ordinal_type;
213 typedef typename SparseMatrixType::global_ordinal_type global_ordinal_type;
214 typedef typename SparseMatrixType::node_type node_type;
215 /// \typedef multivector_type
216 /// \brief Specialization of \c Tpetra::MultiVector.
217 ///
218 /// This class deduces the \c Tpeta::MultiVector specialization
219 /// from the \c Tpetra::CrsMatrix specialization. This ensures
220 /// compatibility of the sparse matrix type with the dense
221 /// multivector type.
222 typedef ::Tpetra::MultiVector<scalar_type,
223 local_ordinal_type,
224 global_ordinal_type,
225 node_type> multivector_type;
226
227 private:
228 typedef Teuchos::ScalarTraits<scalar_type> STS;
229 typedef ::Tpetra::Map<local_ordinal_type,
230 global_ordinal_type,
231 node_type> map_type;
232
233 public:
234 /// \brief Constructor.
235 ///
236 /// \param comm [in] Communicator over which to distribute the
237 /// sparse matrices and dense vectors created by this class
238 /// instance.
239 /// \param node [in] Kokkos Node instance with which to create
240 /// Tpetra objects.
241 /// \param out [out] Output stream that prints only on Rank 0
242 /// of the given communicator.
243 /// \param plist [in/out] On input: nonnull list of parameters.
244 /// On output, missing parameters will be filled in with their
245 /// default values.
246 ProblemMaker (const Teuchos::RCP<const Teuchos::Comm<int> >& comm,
247 const Teuchos::RCP<Teuchos::FancyOStream>& out,
248 const Teuchos::RCP<Teuchos::ParameterList> plist) :
249 comm_ (comm), out_ (out), tolerant_ (false), debug_ (false)
250 {
251 setParameterList (plist);
252 }
253
254 /// \brief Constructor.
255 ///
256 /// \param comm [in] Communicator over which to distribute the
257 /// sparse matrices and dense vectors created by this class
258 /// instance.
259 /// \param node [in] Kokkos Node instance with which to create
260 /// Tpetra objects.
261 /// \param out [out] Output stream that prints only on Rank 0
262 /// of the given communicator.
263 /// \param tolerant [in] Whether to parse files tolerantly.
264 /// \param debug [in] Whether to print copious debugging output.
265 ProblemMaker (const Teuchos::RCP<const Teuchos::Comm<int> >& comm,
266 const Teuchos::RCP<Teuchos::FancyOStream>& out,
267 const bool tolerant,
268 const bool debug) :
269 comm_ (comm),
270 out_ (out),
271 tolerant_ (tolerant),
272 debug_ (debug)
273 {
274 using Teuchos::ParameterList;
275 using Teuchos::parameterList;
276 using Teuchos::RCP;
277
278 RCP<ParameterList> plist = parameterList ();
279 plist->set ("Parse files tolerantly", tolerant);
280 plist->set ("Debug", debug);
281
282 this->setMyParamList (plist);
283 }
284
285 //! @name Implementation of Teuchos::ParameterListAcceptor
286 //@{
287
288 Teuchos::RCP<const Teuchos::ParameterList>
289 getValidParameters() const
290 {
291 using Teuchos::ParameterList;
292 using Teuchos::parameterList;
293 using Teuchos::RCP;
294
295 RCP<ParameterList> validParams = parameterList ();
296 const bool tolerant = false;
297 const bool debug = false;
298 validParams->set ("Parse files tolerantly", tolerant);
299 validParams->set ("Debug", debug);
300
301 return validParams;
302 }
303
304 void
305 setParameterList (const Teuchos::RCP<Teuchos::ParameterList>& plist)
306 {
307 using Teuchos::ParameterList;
308 using Teuchos::RCP;
309
310 RCP<const ParameterList> defaultParams = getValidParameters ();
311 tolerant_ = plist->get<bool> ("Parse files tolerantly");
312 debug_ = plist->get<bool> ("Debug");
313 this->setMyParamList (plist);
314 }
315
316 //@}
317
318 /// \brief Generate a sparse matrix using the given parameters.
319 ///
320 /// This function accepts the following parameters:
321 /// - "Input matrix filename" (std::string): If provided and not
322 /// "", then read the sparse matrix in from the file with the
323 /// given name. Currently, we assume that the file is in
324 /// Matrix Market format.
325 /// - "Output matrix filename" (std::string): If provided and
326 /// not "", write the sparse matrix (whether generated or
327 /// read) out in Matrix Market format to the file with the
328 /// given name.
329 /// - "Global number of rows" (global_ordinal_type): If provided
330 /// and if generating the matrix (rather than reading it from
331 /// a file), use this as the global number of rows (and
332 /// columns) in the matrix. Otherwise ignored. The type of
333 /// this parameter must be the same as \c
334 /// SparseMatrixType::global_ordinal_type.
335 /// - "Problem type" (std::string): If generating the matrix,
336 /// the type of matrix to generate. You should provide a
337 /// global number of rows if you provide this parameter.
338 /// "Symmetric" means generate a symmetric matrix. "GMRES
339 /// unfriendly" means generate a matrix for which GMRES
340 /// converges slowly. The default is "Nonsymmetric", which
341 /// generates a nonsymmetric matrix for which GMRES
342 /// convergence is not too slow.
343 Teuchos::RCP<sparse_matrix_type>
344 makeMatrix (const Teuchos::RCP<Teuchos::ParameterList>& params)
345 {
346 const std::string inputMatrixFilename =
347 params->isType<std::string> ("Input matrix filename") ?
348 params->get<std::string> ("Input matrix filename") : "";
349 const std::string outputMatrixFilename =
350 params->isType<std::string> ("Output matrix filename") ?
351 params->get<std::string> ("Output matrix filename") : "";
352 const global_ordinal_type globalNumRows =
353 params->isType<global_ordinal_type> ("Global number of rows") ?
354 params->get<global_ordinal_type> ("Global number of rows") :
355 comm_->getSize() * 100; // A sensible default
356 const bool generated = params->isType<bool> ("Generated") ?
357 params->get<bool> ("Generated") : inputMatrixFilename == "";
358 bool symmetric = false;
359 bool gmresUnfriendly = false;
360 if (params->isParameter ("Problem type")) {
361 const std::string probType = params->get<std::string> ("Problem type");
362 if (probType == "Symmetric") {
363 symmetric = true;
364 }
365 else if (probType == "GMRES unfriendly") {
366 gmresUnfriendly = true;
367 }
368 }
369
370 Teuchos::RCP<sparse_matrix_type> A;
371 if (inputMatrixFilename != "") {
372 A = readSparseMatrixFromFile (inputMatrixFilename);
373 } else if (generated) {
374 if (gmresUnfriendly) {
375 A = generateGmresUnfriendlyMatrix (globalNumRows);
376 } else {
377 A = generateTestMatrix (globalNumRows, symmetric);
378 }
379 } else {
380 TEUCHOS_TEST_FOR_EXCEPTION(! (inputMatrixFilename == "" || generated),
381 std::logic_error, "Should never get here!");
382 }
383
384 if (outputMatrixFilename != "") {
385 typedef ::Tpetra::MatrixMarket::Writer<sparse_matrix_type> writer_type;
386 writer_type::writeSparseFile (outputMatrixFilename, A, "", "", debug_);
387 }
388 return A;
389 }
390
391 /// \brief Read in a Tpetra sparse matrix from a Matrix Market file.
392 ///
393 /// \param matrixFilename [in] Name of the Matrix Market format
394 /// sparse matrix file to read (on Rank 0 of the communicator
395 /// only).
396 ///
397 /// \return Sparse matrix (represented as a Tpetra::CrsMatrix).
398 ///
399 /// You can access this functionality from \c makeMatrix(). We
400 /// merely provide it as a commonly used special case, so you
401 /// don't have to construct a parameter list just to read a
402 /// matrix from a file.
403 Teuchos::RCP<sparse_matrix_type>
404 readSparseMatrixFromFile (const std::string& filename)
405 {
406 using Teuchos::RCP;
407 using std::endl;
408 typedef ::Tpetra::MatrixMarket::Reader<sparse_matrix_type> reader_type;
409
410 RCP<Teuchos::FancyOStream> out = getDebugStream ();
411 Teuchos::OSTab tab (out); // Indent for debug output
412
413 // Read the sparse matrix A from the file.
414 *out << "Reading sparse matrix A from file \"" << filename
415 << "\"" << endl;
416 const bool callFillComplete = true;
417 RCP<sparse_matrix_type> A =
418 reader_type::readSparseFile (filename, comm_, callFillComplete,
419 tolerant_, debug_);
420 return A;
421 }
422
423 /// \brief Given a sparse matrix A, make corresponding linear system vectors.
424 ///
425 /// \param A [in] The sparse matrix. We require it as input
426 /// because we use its domain and range maps to create
427 /// right-hand side, exact solution, and initial guess
428 /// vectors.
429 /// \param X_guess [out] The initial guess for the linear system AX=B.
430 /// \param X_exact [out] The exact solution X of the linear system AX=B.
431 /// \param B [out] The right-hand side of the linear system AX=B.
432 /// \param params [in/out] List of parameters for generating the
433 /// vectors. This method accepts the following parameters:
434 /// - "Input RHS filename" (std::string): If provided and not
435 /// "", then read the right-hand side (RHS) in from the file
436 /// with the given name. Currently, we assume that the file
437 /// is in Matrix Market dense matrix format.
438 /// - "Output RHS filename" (std::string): If provided and not
439 /// "", write the right-hand side(s) (RHS) out in Matrix
440 /// Market format to the file with the given name.
441 /// - "Number of RHS" (size_t): If provided, and if no input
442 /// filename was specified, B, X_guess, and X_exact will all
443 /// have this number of columns. Defaults to 1.
444 /// - "Random solution" (bool): If true, pick a random (via
445 /// MultiVector::randomize()) exact solution, and compute
446 /// the right-hand side(s) accordingly.
447 /// - "Problem type" (std::string): Optional: The type of
448 /// problem to generate. Currently, the only value for
449 /// which this matters is "GMRES unfriendly", which means
450 /// generate a right-hand side corresponding to the linear
451 /// system for which GMRES converges slowly.
452 void
453 makeVectors (const Teuchos::RCP<const sparse_matrix_type>& A,
454 Teuchos::RCP<multivector_type>& X_guess,
455 Teuchos::RCP<multivector_type>& X_exact,
456 Teuchos::RCP<multivector_type>& B,
457 const Teuchos::RCP<Teuchos::ParameterList>& params)
458 {
459 using Teuchos::as;
460 using Teuchos::RCP;
461 using Teuchos::rcp;
462 using std::endl;
463
464 typedef global_ordinal_type GO;
465 typedef multivector_type MV;
466
467 RCP<Teuchos::FancyOStream> out = getDebugStream ();
468 Teuchos::OSTab tab (out); // Indent for verbose output
469
470 const std::string inRhsFilename =
471 params->isType<std::string> ("Input RHS filename") ?
472 params->get<std::string> ("Input RHS filename") : "";
473 const std::string outRhsFilename =
474 params->isType<std::string> ("Output RHS filename") ?
475 params->get<std::string> ("Output RHS filename") : "";
476
477 bool gmresUnfriendly = false;
478 if (params->isParameter ("Problem type")) {
479 const std::string probType = params->get<std::string> ("Problem type");
480 if (probType == "GMRES unfriendly") {
481 gmresUnfriendly = true;
482 }
483 }
484
485 // This applies only if generating the right-hand side(s), and
486 // if the problem type is not "GMRES unfriendly".
487 const bool randomSolution = ! gmresUnfriendly && inRhsFilename == "" &&
488 params->isParameter ("Random solution") &&
489 params->get<bool> ("Random solution");
490
491 // Number of right-hand side(s).
492 size_t numRHS = 1;
493 if (inRhsFilename == "") {
494 // Be liberal about the accepted type of this parameter.
495 if (params->isType<size_t> ("Number of RHS")) {
496 numRHS = params->get<size_t> ("Number of RHS");
497 }
498 else if (params->isType<long> ("Number of RHS")) {
499 numRHS = as<size_t> (params->get<long> ("Number of RHS"));
500 }
501 else if (params->isType<int> ("Number of RHS")) {
502 numRHS = as<size_t> (params->get<int> ("Number of RHS"));
503 }
504 // If reading the right-hand side(s) from a file, numRHS
505 // will be (re)set accordingly.
506 }
507
508 RCP<const map_type> domainMap = A->getDomainMap();
509 RCP<const map_type> rangeMap = A->getRangeMap();
510
511 if (inRhsFilename != "") {
512 // If reading the right-hand side(s) from a file, don't set
513 // the exact solution(s). Later we could try to read those
514 // from a file too.
515 *out << "Reading right-hand side(s) B from Matrix Market file" << endl;
516 Teuchos::OSTab tab2 (out);
517 typedef ::Tpetra::MatrixMarket::Reader<SparseMatrixType> reader_type;
518 B = reader_type::readDenseFile (inRhsFilename, comm_, rangeMap,
519 tolerant_, debug_);
520 TEUCHOS_TEST_FOR_EXCEPTION(B.is_null (), std::runtime_error, "Failed "
521 "to read right-hand side(s) B from Matrix Market file \""
522 << inRhsFilename << "\".");
523 numRHS = B->getNumVectors ();
524 }
525
526 // Construct X_guess (the initial guess for the solution of
527 // AX=B) from the domain of the matrix A, and fill it with
528 // zeros.
529 {
530 *out << "Constructing initial guess vector X_guess" << endl;
531 X_guess = rcp (new MV (domainMap, numRHS));
532 X_guess->putScalar (STS::zero());
533 }
534
535 // Compute the exact solution vector(s).
536 X_exact = rcp (new MV (domainMap, numRHS));
537 if (inRhsFilename != "") {
538 // FIXME (mfh 03 Apr 2012) We don't compute the exact
539 // solution vector(s) in this case. We could always fire up
540 // Amesos2 and do a direct solve, but instead, we just fill
541 // with zeros and be done with it.
542 X_exact->putScalar (STS::zero ());
543 }
544 else { // if (inRhsFilename == "")
545 // Our choice of exact solution and right-hand side depend
546 // on the test problem. If we generated the
547 // GMRES-unfriendly example, we need B = e_{globalNumRows}
548 // and therefore X_exact = e_{globalNumRows} as well.
549 // Otherwise, we pick X_exact first and compute B via the
550 // product B = A * X_exact.
551 X_exact = rcp (new MV (domainMap, numRHS));
552
553 // Construct the right-hand side B from the range of the
554 // matrix A. Don't just clone X_guess, since the range may
555 // differ from the domain.
556 B = rcp (new MV (rangeMap, numRHS));
557
558 if (gmresUnfriendly) {
559 *out << "Constructing B and X_exact for canonical \"GMRES-"
560 "unfriendly\" example" << endl;
561 X_exact->putScalar (STS::zero ());
562
563 // Only the owning process is allowed to call
564 // MV::replaceGlobalValue(). First check via the domain
565 // (for X_exact) resp. range (for B) Maps whether the
566 // calling process owns that row, and if so, make the
567 // change there. (Domain and range Maps of a CrsMatrix
568 // should never be overlapping, so we don't have to worry
569 // about multiple processes owning the row.)
570 const GO rowToChange = as<GO> (A->getGlobalNumRows() - 1);
571 if (domainMap->isNodeGlobalElement (rowToChange)) {
572 X_exact->replaceGlobalValue (rowToChange, 0, STS::one ());
573 }
574 B->putScalar (STS::zero());
575 if (rangeMap->isNodeGlobalElement (rowToChange)) {
576 B->replaceGlobalValue (rowToChange, 0, STS::one ());
577 }
578 } else {
579 if (randomSolution) {
580 *out << "Randomizing X_exact" << endl;
581 X_exact->randomize ();
582 }
583 else {
584 // Construct the exact solution vector and fill it with
585 // all ones. Tacky, but deterministic. Not good if we
586 // expect A to be singular with rigid body modes.
587 *out << "Setting X_exact = [1; ...; 1]" << endl;
588 X_exact->putScalar (STS::one ());
589 }
590
591 // Compute the right-hand side B := A*X_exact.
592 *out << "Computing B := A*X_exact" << endl;
593 A->apply (*X_exact, *B);
594 }
595 }
596 }
597
598 /// \brief Same as \c makeMatrix() followed by \c makeVectors().
599 ///
600 /// This method first uses \c makeMatrix() with the given
601 /// parameters to construct a sparse matrix A. It then uses \c
602 /// makeVectors() with the same parameter list to construct the
603 /// right-hand side, initial guess, and exact solution vectors.
604 ///
605 /// See the documentation of \c makeMatrix() and \c
606 /// makeVectors() for the parameters that this method accepts.
607 void
608 makeProblem (Teuchos::RCP<sparse_matrix_type>& A,
609 Teuchos::RCP<multivector_type>& X_guess,
610 Teuchos::RCP<multivector_type>& X_exact,
611 Teuchos::RCP<multivector_type>& B,
612 const Teuchos::RCP<Teuchos::ParameterList>& params)
613 {
614 A = makeMatrix (params);
615 makeVectors (A, X_guess, X_exact, B, params);
616 }
617
618 private:
619 //! Communicator over which to distribute sparse matrices and dense vectors.
620 Teuchos::RCP<const Teuchos::Comm<int> > comm_;
621 //! Output stream for indented verbose output.
622 Teuchos::RCP<Teuchos::FancyOStream> out_;
623 //! Whether to parse files tolerantly.
624 bool tolerant_;
625 //! Whether to print debug output.
626 bool debug_;
627
628 /// \brief Generate, distribute, and return a test sparse matrix.
629 ///
630 /// \param globalNumRows [in] Global (over all MPI process(es))
631 /// number of rows in the sparse matrix.
632 ///
633 /// \param symmetric [in] Whether to generate a symmetric test problem.
634 /// Storage is nonsymmetric regardless; symmetry here only applies to
635 /// the entries' locations and numerical values.
636 ///
637 /// \return The sparse matrix (global, distributed).
638 Teuchos::RCP<sparse_matrix_type>
639 generateTestMatrix (const global_ordinal_type globalNumRows,
640 const bool symmetric)
641 {
642 using Teuchos::RCP;
643 using Teuchos::rcp;
644 using Teuchos::tuple;
645 using ::Tpetra::createUniformContigMapWithNode;
646 using std::endl;
647 typedef local_ordinal_type LO;
648 typedef global_ordinal_type GO;
649 typedef node_type NT;
650
651 // For a square matrix, we only need a Map for the range of the matrix.
652 RCP<const map_type> pRangeMap =
653 createUniformContigMapWithNode<LO, GO, NT> (globalNumRows, comm_);
654 // The sparse matrix object to fill.
655 RCP<sparse_matrix_type> pMat = rcp (new sparse_matrix_type (pRangeMap, 0));
656
657 const int myRank = comm_->getRank();
658 if (myRank == 0) {
659 const scalar_type leftVal = -STS::one();
660 const scalar_type rightVal = symmetric ? -STS::one() : +2*STS::one();
661 // Boost the diagonal if nonsymmetric, hopefully to make
662 // convergence a little faster. The point isn't to make a
663 // difficult matrix, just an initial test of a solver.
664 const scalar_type centerVal = symmetric ? 2*STS::one() : 8*STS::one();
665
666 for (GO curRow = 0; curRow < globalNumRows; ++curRow) {
667 if (curRow > 0) {
668 pMat->insertGlobalValues (curRow, tuple(curRow-1), tuple(leftVal));
669 }
670 pMat->insertGlobalValues (curRow, tuple(curRow), tuple(centerVal));
671 if (curRow < globalNumRows-1) {
672 pMat->insertGlobalValues (curRow, tuple(curRow+1), tuple(rightVal));
673 }
674 }
675 }
676 // Make sure Rank 0 is done filling in the matrix.
677 Teuchos::barrier (*comm_);
678 // fillComplete() doesn't need any arguments if the domain and
679 // range maps are the same.
680 pMat->fillComplete ();
681 return pMat;
682 }
683
684 /// \brief Generate a sparse matrix for which GMRES converges slowly.
685 ///
686 /// \param globalNumRows [in] Global number of rows (and
687 /// columns) in the sparse matrix.
688 Teuchos::RCP<sparse_matrix_type>
689 generateGmresUnfriendlyMatrix (const global_ordinal_type globalNumRows)
690 {
691 using Teuchos::RCP;
692 using Teuchos::rcp;
693 using Teuchos::tuple;
694 using ::Tpetra::createUniformContigMapWithNode;
695 using std::endl;
696
697 typedef typename SparseMatrixType::local_ordinal_type LO;
698 typedef typename SparseMatrixType::global_ordinal_type GO;
699 typedef typename SparseMatrixType::node_type NT;
700
701 // For a square matrix, we only need a Map for the range of the matrix.
702 RCP<const map_type> pRangeMap =
703 createUniformContigMapWithNode<LO, GO, NT> (globalNumRows, comm_);
704
705 // The sparse matrix object to fill.
706 RCP<sparse_matrix_type> pMat = rcp (new sparse_matrix_type (pRangeMap, 0));
707
708 const int myRank = comm_->getRank();
709 if (myRank == 0) {
710 const scalar_type val = STS::one();
711 for (GO curRow = 0; curRow < globalNumRows; ++curRow) {
712 const GO curCol = (curRow == 0) ? (globalNumRows-1) : (curRow-1);
713 pMat->insertGlobalValues (curRow, tuple(curCol), tuple(val));
714 }
715 }
716 // Make sure Rank 0 is done filling in the matrix.
717 Teuchos::barrier (*comm_);
718 // fillComplete() doesn't need any arguments if the domain and
719 // range maps are the same.
720 pMat->fillComplete ();
721 return pMat;
722 }
723
724 //! Return an output stream that only prints in debug mode.
725 Teuchos::RCP<Teuchos::FancyOStream>
726 getDebugStream () const
727 {
728 using Teuchos::getFancyOStream;
729
730 if (debug_) {
731 return getFancyOStream (out_);
732 } else {
733 return getFancyOStream (Teuchos::rcp (new Teuchos::oblackholestream));
734 }
735 }
736 };
737
738 } // namespace Tpetra
739 } // namespace Belos
740
741 #endif // __Belos_TpetraTestFramework_hpp