Debian Codegraph @

packages/belos/epetra/test/OrthoManager/belos_orthomanager_epetra.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 /// \file belos_orthomanager_epetra.cpp
11 /// \brief Test (Mat)OrthoManager subclass(es) with Epetra
12 ///
13 /// Test various subclasses of (Mat)OrthoManager, using
14 /// Epetra_MultiVector as the multivector implementation,
15 /// and Epetra_Operator as the operator implementation.
16 ///
17 #include "BelosConfigDefs.hpp"
18 #include "BelosOutputManager.hpp"
19 #include "BelosOrthoManagerFactory.hpp"
20 #include "BelosOrthoManagerTest.hpp"
21 #include "BelosEpetraAdapter.hpp"
22
23 #include <Teuchos_CommandLineProcessor.hpp>
24 #include <Teuchos_GlobalMPISession.hpp>
25 #include <Teuchos_StandardCatchMacros.hpp>
26 #include <Teuchos_oblackholestream.hpp>
27
28 #ifdef EPETRA_MPI
29 # include <mpi.h>
30 # include <Epetra_MpiComm.h>
31 #else
32 # include <Epetra_SerialComm.h>
33 #endif
34 #include <Epetra_CrsMatrix.h>
35
36 // I/O for Harwell-Boeing files
37 #include <Trilinos_Util_iohb.h>
38
39 #include <algorithm>
40 #include <iostream>
41 #include <sstream>
42 #include <stdexcept>
43
44 using std::cout;
45 using std::endl;
46 using std::vector;
47
48 //
49 // These typedefs make main() as generic as possible.
50 //
51 typedef double scalar_type;
52 typedef int local_ordinal_type;
53 typedef int global_ordinal_type;
54
55 typedef Teuchos::ScalarTraits< scalar_type > SCT;
56 typedef SCT::magnitudeType magnitude_type;
57 typedef Epetra_MultiVector MV;
58 typedef Epetra_Operator OP;
59 typedef Belos::MultiVecTraits< scalar_type, MV > MVT;
60 typedef Belos::OperatorTraits< scalar_type, MV, OP > OPT;
61 typedef Teuchos::SerialDenseMatrix< int, scalar_type > serial_matrix_type;
62 typedef Epetra_Map map_type;
63 typedef Epetra_CrsMatrix sparse_matrix_type;
64
65 /* ******************************************************************* */
66
67 // The accepted way to restrict the scope of functions to their source
68 // file, is to use an anonymous namespace, rather than to declare the
69 // functions "static." Besides, "static" is a confusingly overloaded
70 // term in C++.
71 namespace {
72
73 void
74 printVersionInfo (std::ostream& debugOut)
75 {
76 using std::endl;
77
78 debugOut << "Belos version information:" << endl
79 << Belos::Belos_Version() << endl << endl;
80 }
81
82 int
83 selectVerbosity (const bool verbose, const bool debug)
84 {
85 // NOTE Calling this a "MsgType" (its correct type) or even an
86 // "enum MsgType" confuses the compiler.
87 int theType = Belos::Errors; // default (always print errors)
88 if (verbose)
89 {
90 // "Verbose" also means printing out Debug messages (as well
91 // as everything else).
92 theType = theType |
93 Belos::Warnings |
94 Belos::IterationDetails |
95 Belos::OrthoDetails |
96 Belos::FinalSummary |
97 Belos::TimingDetails |
98 Belos::StatusTestDetails |
99 Belos::Debug;
100 }
101 if (debug)
102 // "Debug" doesn't necessarily mean the same thing as
103 // "Verbose". We interpret "Debug" to mean printing out
104 // messages marked as Debug (as well as Error messages).
105 theType = theType | Belos::Debug;
106 return theType;
107 }
108
109 /// \fn loadSparseMatrix
110 /// \brief Load a sparse matrix from a Harwell-Boeing file
111 ///
112 /// Load a sparse matrix from a Harwell-Boeing file, distribute
113 /// it, and return RCPs to a map_type (the map object describing the
114 /// distribution of the sparse matrix: we distribute in a way such
115 /// that the domain, range, and row maps are the same) and a
116 /// sparse_matrix_type (the sparse matrix itself).
117 ///
118 std::pair< Teuchos::RCP< map_type >,
119 Teuchos::RCP< sparse_matrix_type > >
120 loadSparseMatrix (const Teuchos::RCP< const Epetra_Comm >& pComm,
121 const std::string& filename,
122 int& numRows,
123 std::ostream& debugOut)
124 {
125 using Teuchos::RCP;
126 using Teuchos::rcp;
127 using std::vector;
128
129 const int myRank = pComm->MyPID();
130 RCP< map_type > pMap;
131 RCP< sparse_matrix_type > pMatrix;
132
133 if (filename != "")
134 {
135 debugOut << "Loading sparse matrix file \"" << filename << "\"" << endl;
136
137 int loadedNumRows = 0;
138 int numCols = 0;
139 int nnz = -1;
140 int rnnzmax = 0;
141 double *dvals = NULL;
142 int *colptr = NULL;
143 int *rowind = NULL;
144
145 // The Harwell-Boeing routines use info == 0 to signal failure.
146 int info = 0;
147
148 if (myRank == 0)
149 {
150 // Proc 0 reads the sparse matrix (stored in Harwell-Boeing
151 // format) from the file into the tuple (loadedNumRows, numCols, nnz,
152 // colptr, rowind, dvals). The routine allocates memory for
153 // colptr, rowind, and dvals using malloc().
154 info = readHB_newmat_double (filename.c_str(), &loadedNumRows,
155 &numCols, &nnz, &colptr, &rowind,
156 &dvals);
157 // Make sure that loadedNumRows has a sensible value,
158 // since we'll need to allocate an std::vector with that
159 // many elements.
160 TEUCHOS_TEST_FOR_EXCEPTION(loadedNumRows < 0, std::runtime_error,
161 "Harwell-Boeing sparse matrix file reports that "
162 "the matrix has # rows = " << loadedNumRows
163 << " < 0.");
164
165 // The Harwell-Boeing routines use info == 0 to signal failure.
166 if (info != 0)
167 {
168 // rnnzmax := maximum number of nonzeros per row, over all
169 // rows of the sparse matrix.
170 std::vector<int> rnnz (loadedNumRows, 0);
171 for (int *ri = rowind; ri < rowind + nnz; ++ri) {
172 ++rnnz[*ri-1];
173 }
174 // This business with the iterator ensures that results
175 // are sensible even if the sequence is empty.
176 std::vector<int>::const_iterator iter =
177 std::max_element (rnnz.begin(),rnnz.end());
178 if (iter != rnnz.end())
179 rnnzmax = *iter;
180 else
181 // The matrix has zero rows, so the max number of
182 // nonzeros per row is trivially zero.
183 rnnzmax = 0;
184 }
185 }
186
187 // Proc 0 now broadcasts the sparse matrix data to the other
188 // process(es). First things broadcast are info and nnz, which
189 // tell the other process(es) whether reading the sparse matrix
190 // succeeded. (info should be nonzero if so. The
191 // Harwell-Boeing routines return "C boolean true" rather than
192 // the POSIX-standard "zero for success.")
193 pComm->Broadcast (&info, 1, 0);
194 pComm->Broadcast (&nnz, 1, 0);
195
196 TEUCHOS_TEST_FOR_EXCEPTION(info == 0, std::runtime_error,
197 "Error reading Harwell-Boeing sparse matrix file \""
198 << filename << "\"" << std::endl);
199
200 TEUCHOS_TEST_FOR_EXCEPTION(nnz < 0, std::runtime_error,
201 "Harwell-Boeing sparse matrix file \""
202 << filename << "\" reports having negative nnz "
203 << "(= " << nnz << ")"
204 << std::endl);
205
206 TEUCHOS_TEST_FOR_EXCEPTION(nnz == 0, std::runtime_error,
207 "Test matrix in Harwell-Boeing sparse matrix file '"
208 << filename << "' " << "has zero nonzero values, which "
209 << "means it does not define a valid inner product."
210 << std::endl);
211
212 pComm->Broadcast (&loadedNumRows, 1, 0);
213 pComm->Broadcast (&numCols, 1, 0);
214 pComm->Broadcast (&rnnzmax, 1, 0);
215
216 TEUCHOS_TEST_FOR_EXCEPTION(loadedNumRows != numCols, std::runtime_error,
217 "Test matrix in Harwell-Boeing sparse matrix file '"
218 << filename << "' " << "is not square: it is "
219 << loadedNumRows << " by " << numCols << std::endl);
220 // We've fully validated the number of rows, so set the
221 // appropriate output parameter.
222 numRows = loadedNumRows;
223
224 // Create Epetra_Map to represent multivectors in the range of
225 // the sparse matrix.
226 pMap = rcp (new map_type (numRows, 0, *pComm));
227
228 // Third argument: max number of nonzero entries per row.
229 pMatrix = rcp (new sparse_matrix_type (Epetra_DataAccess::Copy, *pMap, rnnzmax));
230
231 if (myRank == 0)
232 {
233 // Convert from Harwell-Boeing format (compressed sparse
234 // column, one-indexed) to CrsMatrix format (compressed
235 // sparse row, zero-index). We do this by iterating over
236 // all the columns of the matrix.
237 int curNonzeroIndex = 0;
238 for (int c = 0; c < numCols; ++c)
239 {
240 for (int colnnz = 0; colnnz < colptr[c+1] - colptr[c]; ++colnnz)
241 {
242 // Row index: *rptr - 1 (1-based -> 0-based indexing)
243 // Column index: c
244 // Value to insert there: *dptr
245 const int curGlobalRowIndex = rowind[curNonzeroIndex] - 1;
246 const scalar_type curValue = dvals[curNonzeroIndex];
247 pMatrix->InsertGlobalValues (curGlobalRowIndex,
248 1, &curValue, &c);
249 curNonzeroIndex++;
250 }
251 }
252 }
253 if (myRank == 0)
254 {
255 // Free memory allocated by the Harwell-Boeing input routine.
256 if (dvals != NULL)
257 {
258 free (dvals);
259 dvals = NULL;
260 }
261 if (colptr != NULL)
262 {
263 free (colptr);
264 colptr = NULL;
265 }
266 if (rowind != NULL)
267 {
268 free (rowind);
269 rowind = NULL;
270 }
271 }
272 // We're done reading in the sparse matrix. Now distribute it
273 // among the processes. The domain, range, and row maps are
274 // the same (the matrix must be square).
275 pMatrix->FillComplete();
276 debugOut << "Completed loading and distributing sparse matrix" << endl;
277 } // else M == null
278 else
279 {
280 debugOut << "Testing with Euclidean inner product" << endl;
281
282 // Let M remain null, and allocate map using the number of rows
283 // (numRows) specified on the command line.
284 pMap = rcp (new map_type (numRows, 0, *pComm));
285 }
286 return std::make_pair (pMap, pMatrix);
287 }
288 }
289
290
291 /// \fn main
292 /// \brief Test driver for (Mat)OrthoManager subclasses
293 int
294 main (int argc, char *argv[])
295 {
296 using Belos::OutputManager;
297 using Belos::OrthoManager;
298 using Teuchos::CommandLineProcessor;
299 using Teuchos::null;
300 using Teuchos::RCP;
301 using Teuchos::rcp;
302 using Teuchos::rcp_implicit_cast;
303 using Teuchos::ParameterList;
304
305 Teuchos::GlobalMPISession mpisess(&argc,&argv,&std::cout);
306
307 #ifdef EPETRA_MPI
308 RCP< Epetra_MpiComm > pCommSpecific (new Epetra_MpiComm (MPI_COMM_WORLD));
309 #else
310 RCP< Epetra_SerialComm > pCommSpecific (new Epetra_SerialComm);
311 #endif // EPETRA_MPI
312 RCP< Epetra_Comm > pComm = rcp_implicit_cast< Epetra_Comm > (pCommSpecific);
313
314 // This factory object knows how to make a (Mat)OrthoManager
315 // subclass, given a name for the subclass. The name is not the
316 // same as the class' syntactic name: e.g., "DKGS" is the name of
317 // DkgsOrthoManager.
318 Belos::OrthoManagerFactory< scalar_type, MV, OP > factory;
319 // The name of the (Mat)OrthoManager subclass to instantiate.
320 std::string ortho (factory.defaultName());
321
322 // Name of the Harwell-Boeing sparse matrix file from which to read
323 // the inner product operator matrix. If name is "" or not provided
324 // at the command line, use the standard Euclidean inner product.
325 std::string filename;
326
327 bool verbose = false;
328 bool success = false;
329
330 try {
331 bool debug = false;
332
333 // The OrthoManager is tested with three different multivectors: S,
334 // X1, and X2. sizeS is the number of columns in S, sizeX1 the
335 // number of columns in X1, and sizeX2 the number of columns in X2.
336 // The values below are defaults and may be changed by command-line
337 // arguments with corresponding names.
338 int sizeS = 5;
339 int sizeX1 = 11;
340 int sizeX2 = 13;
341
342 // Default global number of rows. The number of rows per MPI
343 // process must be no less than max(sizeS, sizeX1, sizeX2). To
344 // ensure that the test always passes with default parameters, we
345 // scale by the number of processes. The default value below may be
346 // changed by a command-line parameter with a corresponding name.
347 int numRows = 100 * pComm->NumProc();
348
349 CommandLineProcessor cmdp(false,true);
350 cmdp.setOption ("verbose", "quiet", &verbose,
351 "Print messages and results.");
352 cmdp.setOption ("debug", "nodebug", &debug,
353 "Print debugging information.");
354 cmdp.setOption ("filename", &filename,
355 "Filename of a Harwell-Boeing sparse matrix, used as the "
356 "inner product operator by the orthogonalization manager."
357 " If not provided, no matrix is read and the Euclidean "
358 "inner product is used.");
359 {
360 std::ostringstream os;
361 const int numValid = factory.numOrthoManagers();
362 const bool plural = numValid > 1 || numValid == 0;
363
364 os << "OrthoManager subclass to test. There ";
365 os << (plural ? "are " : "is ") << numValid << (plural ? "s: " : ": ");
366 factory.printValidNames (os);
367 os << ".";
368 cmdp.setOption ("ortho", &ortho, os.str().c_str());
369 }
370 cmdp.setOption ("numRows", &numRows,
371 "Controls the number of rows of the test "
372 "multivectors. If an input matrix is given, this "
373 "parameter\'s value is ignored, since the vectors must "
374 "be commensurate with the dimensions of the matrix.");
375 cmdp.setOption ("sizeS", &sizeS, "Controls the number of columns of the "
376 "input multivector.");
377 cmdp.setOption ("sizeX1", &sizeX1, "Controls the number of columns of the "
378 "first basis.");
379 cmdp.setOption ("sizeX2", &sizeX2, "Controls the number of columns of the "
380 "second basis. We require for simplicity of testing (the "
381 "routines do not require it) that sizeX1 >= sizeX2.");
382 // Parse the command-line arguments.
383 {
384 const CommandLineProcessor::EParseCommandLineReturn parseResult = cmdp.parse (argc,argv);
385 if (parseResult == CommandLineProcessor::PARSE_HELP_PRINTED)
386 {
387 if (pComm->MyPID() == 0)
388 std::cout << "End Result: TEST PASSED" << endl;
389 return EXIT_SUCCESS;
390 }
391 TEUCHOS_TEST_FOR_EXCEPTION(parseResult != CommandLineProcessor::PARSE_SUCCESSFUL,
392 std::invalid_argument,
393 "Failed to parse command-line arguments");
394 }
395 //
396 // Validate command-line arguments
397 //
398 TEUCHOS_TEST_FOR_EXCEPTION(numRows <= 0, std::invalid_argument, "numRows <= 0 is not allowed");
399 TEUCHOS_TEST_FOR_EXCEPTION(numRows <= sizeS + sizeX1 + sizeX2, std::invalid_argument,
400 "numRows <= sizeS + sizeX1 + sizeX2 is not allowed");
401
402 // Declare an output manager for handling local output. Initialize,
403 // using the caller's desired verbosity level.
404 //
405 // NOTE In Anasazi, this class is called BasicOutputManager. In
406 // Belos, this class is called OutputManager. We should eventually
407 // resolve this difference.
408 RCP<OutputManager<scalar_type> > outMan (new OutputManager<scalar_type> (selectVerbosity (verbose, debug)));
409
410 // Stream for debug output. If debug output is not enabled, then
411 // this stream doesn't print anything sent to it (it's a "black
412 // hole" stream).
413 std::ostream& debugOut = outMan->stream(Belos::Debug);
414 printVersionInfo (debugOut);
415
416 // Load the inner product operator matrix from the given filename.
417 // If filename == "", use the identity matrix as the inner product
418 // operator (the Euclidean inner product), and leave M as
419 // Teuchos::null. Also return an appropriate Map (which will
420 // always be initialized; it should never be Teuchos::null).
421 RCP< map_type > map;
422 RCP< sparse_matrix_type > M;
423 {
424 // If the sparse matrix is loaded successfully, this call will
425 // modify numRows to be the number of rows in the sparse matrix.
426 // Otherwise, it will leave numRows alone.
427 std::pair< RCP< map_type >, RCP< sparse_matrix_type > > results =
428 loadSparseMatrix (pComm, filename, numRows, debugOut);
429 map = results.first;
430 M = results.second;
431 }
432 TEUCHOS_TEST_FOR_EXCEPTION(map.is_null(), std::logic_error,
433 "Error: (Mat)OrthoManager test code failed to "
434 "initialize the Map");
435 {
436 // The maximum number of columns that will be passed to a
437 // MatOrthoManager's normalize() routine. Some MatOrthoManager
438 // subclasses (e.g., Tsqr(Mat)OrthoManager) need to have the
439 // number of columns no larger than the number of rows on any
440 // process. We check this _after_ attempting to load any sparse
441 // matrix to be used as the inner product matrix, because if a
442 // sparse matrix is successfully loaded, its number of rows will
443 // override the number of rows specified on the command line (if
444 // specified), and will also override the default number of rows.
445 const int maxNormalizeNumCols = std::max (sizeS, std::max (sizeX1, sizeX2));
446 if (map->NumMyElements() < maxNormalizeNumCols)
447 {
448 std::ostringstream os;
449 os << "The number of elements on this process " << pComm->MyPID()
450 << " is too small for the number of columns that you want to test."
451 << " There are " << map->NumMyElements() << " elements on "
452 "this process, but the normalize() method of the MatOrthoManager "
453 "subclass will need to process a multivector with "
454 << maxNormalizeNumCols << " columns. Not all MatOrthoManager "
455 "subclasses can handle a local row block with fewer rows than "
456 "columns.";
457 throw std::invalid_argument(os.str());
458 }
459 }
460
461 // Using the factory object, instantiate the specified
462 // OrthoManager subclass to be tested.
463 //
464 // TODO Read in a ParameterList for configuring the specific
465 // OrthoManager subclass.
466
467 std::string timingLabel ("Belos");
468 // Flush before computation, to ensure the message gets out
469 // before any possible errors.
470 debugOut << "Asking factory to create the OrthoManager subclass..."
471 << std::flush;
472 RCP<OrthoManager<scalar_type, MV> > OM =
473 factory.makeOrthoManager (ortho, M, outMan, timingLabel, null);
474 TEUCHOS_TEST_FOR_EXCEPTION(OM.is_null(), std::logic_error,
475 "The OrthoManager factory returned null, "
476 "for ortho=\"" << ortho << "\".");
477 debugOut << "done." << endl;
478
479 // Test the parameter get and set functions
480 debugOut << "Testing get and set paramenter functions..."
481 << std::flush;
482 RCP<const ParameterList> validOrthoParams = OM->getValidParameters();
483 TEUCHOS_TEST_FOR_EXCEPTION(validOrthoParams.is_null(), std::logic_error,
484 "The OrthoManager factory returned null "
485 "for getValidParameters.");
486 RCP<ParameterList> orthoParams= rcp(new ParameterList(*validOrthoParams));
487
488 // Try changing a parameter:
489 bool isNumPassesSet = false;
490 int newNumPasses = 7;
491 int defaultNumPasses;
492
493 if( orthoParams->isParameter("maxNumOrthogPasses") ) {
494 defaultNumPasses = validOrthoParams->get<int>("maxNumOrthogPasses");
495 orthoParams->set("maxNumOrthogPasses", newNumPasses);
496 isNumPassesSet = true;
497 }
498
499 OM->setParameterList(orthoParams);
500
501 // Change back to default:
502 if(isNumPassesSet){
503 orthoParams->set("maxNumOrthogPasses", defaultNumPasses);
504 OM->setParameterList(orthoParams);
505 }
506 debugOut << "done." << endl;
507
508 // Whether the specific OrthoManager subclass promises to compute
509 // rank-revealing orthogonalizations. If yes, then test it on
510 // rank-deficient multivectors, otherwise only test it on full-rank
511 // multivectors.
512 const bool isRankRevealing = factory.isRankRevealing (ortho);
513 if (isRankRevealing)
514 debugOut << "OrthoManager \"" << ortho << "\" claims to be "
515 "rank revealing." << endl;
516 else
517 debugOut << "OrthoManager \"" << ortho << "\" does not claim "
518 "to be rank revealing." << endl;
519
520 // "Prototype" multivector. The test code will use this (via
521 // Belos::MultiVecTraits) to clone other multivectors as necessary.
522 // (This means the test code doesn't need the Map, and it also makes
523 // the test code independent of the idea of a Map.)
524 RCP<MV> S = rcp (new MV (*map, sizeS));
525
526 // Test the OrthoManager subclass. Return the number of tests
527 // that failed. None of the tests should fail (this function
528 // should return zero).
529 int numFailed = 0;
530 {
531 typedef Belos::Test::OrthoManagerTester<scalar_type, MV> tester_type;
532 debugOut << "Running OrthoManager tests..." << endl;
533 numFailed = tester_type::runTests (OM, isRankRevealing, S,
534 sizeX1, sizeX2, outMan);
535 debugOut << "...done running OrthoManager tests." << endl;
536 }
537
538 // Only Rank 0 gets to write to cout. The other processes dump
539 // output to a black hole.
540 //std::ostream& finalOut = (pComm->MyPID() == 0) ? std::cout : Teuchos::oblackholestream;
541
542 if (numFailed != 0) // Oops, at least one test didn't pass
543 {
544 success = false;
545 outMan->stream(Belos::Errors) << numFailed << " errors." << endl;
546 // The Trilinos test framework depends on seeing this message,
547 // so don't rely on the OutputManager to report it correctly,
548 // since the verbosity setting of the OutputManager may cause it
549 // not to print something.
550 if (pComm->MyPID() == 0)
551 {
552 std::cout << "Total number of errors: " << numFailed << endl;
553 std::cout << "End Result: TEST FAILED" << endl;
554 }
555 }
556 else // All the tests passed, yay!
557 {
558 success = true;
559 // The Trilinos test framework depends on seeing this message to
560 // know that the test passed.
561 if (pComm->MyPID() == 0)
562 std::cout << "End Result: TEST PASSED" << endl;
563 }
564 }
565 TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success);
566
567 return ( success ? EXIT_SUCCESS : EXIT_FAILURE );
568 }