Teuchos Package Browser (Single Doxygen Collection)  Version of the Day
MatrixMarket_Raw_InOutTest.cpp
Go to the documentation of this file.
1 // @HEADER
2 // ***********************************************************************
3 //
4 // Teuchos: Common Tools Package
5 // Copyright (2004) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
38 //
39 // ***********************************************************************
40 // @HEADER
41 
50 #include <algorithm>
51 
52 using std::endl;
53 
54 namespace {
55  // Sample Matrix Market sparse matrix file. We include this so we
56  // can test without needing to read in a file. Notice that all the
57  // decimal floating-point values in this example can be represented
58  // exactly in binary floating point. This example has correct
59  // syntax, so you won't need to use tolerant mode to parse it.
60  const char sampleMatrixMarketFile[] =
61  "%%MatrixMarket matrix coordinate real general\n"
62  "5 5 10\n"
63  "5 5 55.0\n"
64  "4 4 44.0\n"
65  "3 3 33.0\n"
66  "2 2 22.0\n"
67  "1 1 11.0\n"
68  "4 5 45.0\n"
69  "3 4 34.0\n"
70  "2 3 23.0\n"
71  "1 2 12.0\n"
72  "1 5 15.0\n";
73 
74  // Sample Matrix Market sparse matrix file for testing symmetric
75  // storage. Matrix Market format for symmetric, skew-symemtric,
76  // etc. specifies that only the lower triangle should be stored.
77  const char symmetricMatrixMarketFile[] =
78  "%%MatrixMarket matrix coordinate real symmetric\n"
79  "5 5 10\n"
80  "5 5 55.0\n"
81  "4 4 44.0\n"
82  "3 3 33.0\n"
83  "2 2 22.0\n"
84  "1 1 11.0\n"
85  "5 4 54.0\n"
86  "4 3 43.0\n"
87  "3 2 32.0\n"
88  "2 1 21.0\n"
89  "5 1 51.0\n";
90 
91 } // namespace (anonymous)
92 
93 // Benchmark driver
94 int
95 main (int argc, char *argv[])
96 {
99  using Teuchos::ArrayRCP;
100  using Teuchos::ArrayView;
101  using Teuchos::Comm;
104  using Teuchos::RCP;
105  using Teuchos::rcp;
106  using Teuchos::rcpFromRef;
107  using Teuchos::SerialComm;
108  using std::cout;
109  using std::cerr;
110  typedef double scalar_type;
111  typedef int ordinal_type;
112 
113  // Name of the Matrix Market sparse matrix file to read. If empty,
114  // use the Matrix Market example embedded as a string in this file.
115  std::string filename;
116  // If true, just check the sparse matrix file. Otherwise,
117  // do a full conversion to CSR (compressed sparse row) format.
118  bool checkOnly = false;
119  // Whether to echo the sparse matrix to stdout after reading it
120  // successfully.
121  bool echo = false;
122  // Whether to parse the Matrix Market file tolerantly.
123  bool tolerant = false;
124  // Verbosity of output
125  bool verbose = false;
126  // Whether to print debugging-level output
127  bool debug = false;
128 
129  CommandLineProcessor cmdp (false, true);
130  cmdp.setOption ("filename", &filename,
131  "Name of the Matrix Market sparse matrix file to read.");
132  cmdp.setOption ("checkOnly", "fullTest", &checkOnly,
133  "If true, just check the syntax of the input file. "
134  "Otherwise, do a full test.");
135  cmdp.setOption ("echo", "noecho", &echo,
136  "Whether to echo the sparse matrix contents to stdout "
137  "after reading it successfully.");
138  cmdp.setOption ("tolerant", "strict", &tolerant,
139  "Whether to tolerate syntax errors in the Matrix Market file.");
140  cmdp.setOption ("verbose", "quiet", &verbose,
141  "Print status output to stdout.");
142  cmdp.setOption ("debug", "nodebug", &debug,
143  "Print possibly copious debugging output to stderr.");
144  // Parse the command-line arguments.
145  {
146  const CommandLineProcessor::EParseCommandLineReturn parseResult =
147  cmdp.parse (argc,argv);
148  // If the caller asks us to print the documentation, or does not
149  // explicitly say to run the benchmark, we let this "test" pass
150  // trivially.
151  if (parseResult == CommandLineProcessor::PARSE_HELP_PRINTED) {
152  std::cout << "End Result: TEST PASSED" << endl;
153  return EXIT_SUCCESS;
154  }
156  parseResult != CommandLineProcessor::PARSE_SUCCESSFUL,
157  std::invalid_argument, "Failed to parse command-line arguments.");
158  }
159 
160  // Test reading in the sparse matrix. If no filename or an empty
161  // filename is specified, the test passes trivially.
162  bool success = true;
163  if (checkOnly) {
164  typedef Checker<scalar_type, ordinal_type> checker_type;
165  checker_type checker (echo, tolerant, debug);
166 
167  RCP<const Comm<int> > comm = rcp (new SerialComm<int>);
168  if (filename != "") {
169  if (verbose) {
170  cout << "Checking syntax of the Matrix Market file \"" << filename
171  << "\"" << endl;
172  }
173  success = success && checker.readFile (*comm, filename);
174  if (verbose) {
175  if (success) {
176  cout << "The given file is a valid Matrix Market file." << endl;
177  }
178  else {
179  cout << "The given file has syntax errors." << endl;
180  }
181  }
182  }
183  else {
184  if (verbose) {
185  cout << "Checking syntax of the first built-in Matrix Market example" << endl
186  << std::flush;// for debug output next
187  }
188  if (debug) {
189  cerr << "First built-in Matrix Market example: " << endl
190  << sampleMatrixMarketFile << endl;
191  }
192  std::istringstream in (sampleMatrixMarketFile);
193  RCP<std::istream> inStream = rcpFromRef (in);
194  success = success && checker.read (*comm, inStream);
195  if (verbose) {
196  if (success) {
197  cout << "The example has valid Matrix Market syntax." << endl;
198  }
199  else {
200  cout << "The example has syntax errors." << endl;
201  }
202  }
203  }
204  }
205  else {
206  typedef Reader<scalar_type, ordinal_type> reader_type;
207  reader_type reader (tolerant, debug);
208  ArrayRCP<ordinal_type> ptr, ind;
209  ArrayRCP<scalar_type> val;
210  ordinal_type numRows, numCols;
211  //
212  // Read the Matrix Market data, either from a file or from a
213  // built-in string.
214  //
215  if (filename != "") {
216  if (verbose) {
217  cout << "Reading the Matrix Market file \"" << filename << "\"" << endl;
218  }
219  success = success && reader.readFile (ptr, ind, val,
220  numRows, numCols, filename);
221  }
222  else {
223  if (verbose) {
224  cout << "Reading the first built-in Matrix Market example" << endl;
225  }
226  if (debug) {
227  cerr << "First built-in Matrix Market example:" << endl
228  << sampleMatrixMarketFile << endl;
229  }
230  std::istringstream inStr (sampleMatrixMarketFile);
231  success = success && reader.read (ptr, ind, val, numRows, numCols, inStr);
232  }
233  TEUCHOS_TEST_FOR_EXCEPTION(! success, std::runtime_error, "Matrix Market "
234  "reader failed to read the given file or input stream.");
235  if (success && verbose) {
236  cout << "Returned from reading the Matrix Market data" << endl
237  << std::flush; // for following debug output
238  }
239  if (debug) {
240  cerr << "CSR output info:" << endl
241  << " ptr.size() = " << ptr.size()
242  << ", ind.size() = " << ind.size()
243  << ", val.size() = " << val.size()
244  << ", numRows = " << numRows
245  << ", numCols = " << numCols
246  << endl;
247  }
248 
249  // Here's the fun part. Output the CSR data to an output stream.
250  // Then read in the output stream. The resulting matrix should be
251  // exactly the same (unless the original file had elements at the
252  // same location that were added together with rounding error).
253  // This is a test for both Writer and Reader.
254  std::ostringstream outStr;
255  if (success && verbose) {
256  cout << "Printing the CSR arrays to a Matrix Market output stream"
257  << endl << std::flush;
258  }
260  writer.write (outStr, ptr (), ind (), val (), numRows, numCols);
261 
262  if (debug && echo) {
263  cerr << "CSR data:" << endl
264  << "- ptr = [";
265  for (ordinal_type i = 0; i < ptr.size(); ++i) {
266  cerr << ptr[i];
267  if (i+1 != ptr.size()) { // don't subtract from zero if unsigned
268  cerr << ", ";
269  }
270  }
271  cerr << "]" << endl
272  << "- ind = [";
273  for (ordinal_type i = 0; i < ind.size(); ++i) {
274  cerr << ind[i];
275  if (i+1 != ind.size()) { // don't subtract from zero if unsigned
276  cerr << ", ";
277  }
278  }
279  cerr << "]" << endl
280  << "- val = [";
281  for (ordinal_type i = 0; i < val.size(); ++i) {
282  cerr << val[i];
283  if (i+1 != val.size()) { // don't subtract from zero if unsigned
284  cerr << ", ";
285  }
286  }
287  cerr << "]" << endl;
288 
289  cerr << "CSR data, converted back to Matrix Market format" << endl;
290  writer.write (cerr, ptr (), ind (), val (), numRows, numCols);
291  cerr << endl;
292  }
293 
294  ArrayRCP<ordinal_type> newptr, newind;
295  ArrayRCP<scalar_type> newval;
296  ordinal_type newNumRows, newNumCols;
297  if (success && verbose) {
298  cout << "Reading the Matrix Market output back into CSR arrays" << endl;
299  }
300  {
301  std::istringstream inStr (outStr.str ());
302  success = success && reader.read (newptr, newind, newval,
303  newNumRows, newNumCols, inStr);
304  }
305  TEUCHOS_TEST_FOR_EXCEPTION(! success, std::logic_error, "Matrix Market "
306  "reader failed to read the output back into CSR arrays.");
307  if (success && verbose) {
308  cout << "Successfully read the Matrix Market output back into CSR arrays"
309  << endl << std::flush;
310  }
311  if (debug) {
312  cerr << "CSR output info:" << endl
313  << " newptr.size() = " << newptr.size()
314  << ", newind.size() = " << newind.size()
315  << ", newval.size() = " << newval.size()
316  << ", newNumRows = " << newNumRows
317  << ", newNumCols = " << newNumCols
318  << endl;
319  }
320 
321  // The old arrays should equal the new arrays.
322  TEUCHOS_TEST_FOR_EXCEPTION(ptr.size () != newptr.size (), std::logic_error,
323  "New ptr array has a different length than old ptr array");
324  TEUCHOS_TEST_FOR_EXCEPTION(ind.size () != newind.size (), std::logic_error,
325  "New ind array has a different length than old ind array");
326  TEUCHOS_TEST_FOR_EXCEPTION(val.size () != newval.size (), std::logic_error,
327  "New val array has a different length than old val array");
328  TEUCHOS_TEST_FOR_EXCEPTION(newNumRows != numRows || newNumCols != numCols,
329  std::logic_error, "New dimensions differ from old dimensions");
330  TEUCHOS_TEST_FOR_EXCEPTION(ptr.size () != numRows+1, std::logic_error,
331  "ptr.size() != numRows+1");
332  TEUCHOS_TEST_FOR_EXCEPTION(newptr.size () != newNumRows+1, std::logic_error,
333  "newptr.size() != newNumRows+1");
334 
335  for (ordinal_type rowIndex = 0; rowIndex < numRows; ++rowIndex) {
336  TEUCHOS_TEST_FOR_EXCEPTION(ptr[rowIndex] != newptr[rowIndex],
337  std::logic_error, "At row index " << rowIndex << ", ptr[rowIndex] = "
338  << ptr[rowIndex] << " != newptr[rowIndex] = " << newptr[rowIndex]
339  << ".");
340  TEUCHOS_TEST_FOR_EXCEPTION(ptr[rowIndex+1] != newptr[rowIndex+1],
341  std::logic_error, "At row index " << rowIndex << ", ptr[rowIndex+1] = "
342  << ptr[rowIndex+1] << " != newptr[rowIndex+1] = " << newptr[rowIndex+1]
343  << ".");
344  for (ordinal_type k = ptr[rowIndex]; k < ptr[rowIndex+1]; ++k) {
345  TEUCHOS_TEST_FOR_EXCEPTION(ind[k] != newind[k], std::logic_error,
346  "At row index " << rowIndex << ", ind[k=" << k << "] = "
347  << ind[k] << " != newind[k] = " << newind[k] << ".");
348  // You may want to relax this inequality if the original
349  // Matrix Market file had multiple entries at the same
350  // location and if adding them together resulted in rounding
351  // error.
352  TEUCHOS_TEST_FOR_EXCEPTION(val[k] != newval[k], std::logic_error,
353  "At row index " << rowIndex << ", val[k=" << k << "] = "
354  << val[k] << " != newval[k] = " << newval[k] << ".");
355  }
356  }
357 
358  // Now test reading symmetric data, if no filename was specified.
359  if (filename == "") {
360  std::istringstream inStr (symmetricMatrixMarketFile);
361  success = success && reader.read (ptr, ind, val, numRows, numCols, inStr);
362  TEUCHOS_TEST_FOR_EXCEPTION(! success, std::logic_error,
363  "Matrix Market reader failed to read the given example string.");
364  if (success && verbose) {
365  cout << "Returned from reading the Matrix Market data" << endl
366  << std::flush; // for following debug output
367  }
368  if (debug) {
369  cerr << "CSR output info:" << endl
370  << " ptr.size() = " << ptr.size()
371  << ", ind.size() = " << ind.size()
372  << ", val.size() = " << val.size()
373  << ", numRows = " << numRows
374  << ", numCols = " << numCols
375  << endl;
376  }
377 
378  // This is a bit of a hack, since we know the contents of the
379  // example. Since we "symmetrize" when reading in symmetric
380  // data, there should be 15 entries in the resulting matrix.
381  const ordinal_type correctNumEntries = 15;
383  val.size() != correctNumEntries,
384  std::logic_error,
385  "Incorrect number of entries after symmetrization: There should be "
386  << correctNumEntries << ", but there are " << val.size() << " entries "
387  "instead.");
388  }
389  } // end of the file / string Reader tests
390 
391  if (success) {
392  std::cout << "End Result: TEST PASSED" << endl;
393  return EXIT_SUCCESS;
394  }
395  else {
396  std::cout << "End Result: TEST FAILED" << endl;
397  return EXIT_FAILURE;
398  }
399 }
400 
401 
402 
Read a sparse matrix from a Matrix Market file into raw CSR (compressed sparse row) storage...
RCP< T > rcp(const boost::shared_ptr< T > &sptr)
Conversion function that takes in a boost::shared_ptr object and spits out a Teuchos::RCP object...
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Macro for throwing an exception with breakpointing to ease debugging.
Concrete serial communicator subclass.
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
Deprecated.
void write(std::ostream &out, const ArrayView< const OrdinalType > &rowptr, const ArrayView< const OrdinalType > &colind, const ArrayView< const ScalarType > &values, const OrdinalType numRows, const OrdinalType numCols)
Write the sparse matrix to the given output stream.
A list of parameters of arbitrary type.
Ptr< T > ptr(T *p)
Create a pointer to an object from a raw pointer.
Abstract interface for distributed-memory communication.
Nonowning array view.
A MPI utilities class, providing methods for initializing, finalizing, and querying the global MPI se...
Basic command line parser for input from (argc,argv[])
RCP< T > rcpFromRef(T &r)
Return a non-owning weak RCP object from a raw object reference for a defined type.
Smart reference counting pointer class for automatic garbage collection.
int main(int argc, char *argv[])
Tool for debugging the syntax of a Matrix Market file containing a sparse matrix. ...
Write a sparse matrix from raw CSR (compressed sparse row) storage to a Matrix Market file...
Class that helps parse command line input arguments from (argc,argv[]) and set options.
Reference-counted smart pointer for managing arrays.