Teuchos Package Browser (Single Doxygen Collection)  Version of the Day
Teuchos_MatrixMarket_Raw_Adder.hpp
Go to the documentation of this file.
1 // @HEADER
2 // ***********************************************************************
3 //
4 // Tpetra: Templated Linear Algebra Services Package
5 // Copyright (2008) Sandia Corporation
6 //
7 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
8 // the U.S. Government retains certain rights in this software.
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 
42 #ifndef __Teuchos_MatrixMarket_Raw_Adder_hpp
43 #define __Teuchos_MatrixMarket_Raw_Adder_hpp
44 
45 #include "Teuchos_ConfigDefs.hpp"
46 #include "Teuchos_ArrayRCP.hpp"
47 #include "Teuchos_CommHelpers.hpp"
51 
52 #include <algorithm>
53 #include <fstream>
54 #include <iostream>
55 #include <iterator>
56 #include <vector>
57 #include <stdexcept>
58 
59 
60 namespace Teuchos {
61  namespace MatrixMarket {
62  namespace Raw {
86  template<class Scalar, class Ordinal>
87  class Element {
88  public:
96  Element () : rowIndex_ (-1), colIndex_ (-1), value_ (0) {}
97 
99  Element (const Ordinal i, const Ordinal j, const Scalar& Aij) :
100  rowIndex_ (i), colIndex_ (j), value_ (Aij) {}
101 
103  bool operator== (const Element& rhs) {
104  return rowIndex_ == rhs.rowIndex_ && colIndex_ == rhs.colIndex_;
105  }
106 
108  bool operator!= (const Element& rhs) {
109  return ! (*this == rhs);
110  }
111 
113  bool operator< (const Element& rhs) const {
114  if (rowIndex_ < rhs.rowIndex_)
115  return true;
116  else if (rowIndex_ > rhs.rowIndex_)
117  return false;
118  else { // equal
119  return colIndex_ < rhs.colIndex_;
120  }
121  }
122 
128  template<class BinaryFunction>
129  void merge (const Element& rhs, const BinaryFunction& f) {
131  rowIndex() != rhs.rowIndex() || colIndex() != rhs.colIndex(),
132  std::invalid_argument,
133  "Attempt to merge elements at different locations in the sparse "
134  "matrix. The current element is at (" << rowIndex() << ", "
135  << colIndex() << ") and the element you asked me to merge with it "
136  "is at (" << rhs.rowIndex() << ", " << rhs.colIndex() << "). This "
137  "probably indicates a bug in the sparse matrix reader.");
138 
139  value_ = f (rhs.value_, value_);
140  }
141 
148  void merge (const Element& rhs, const bool replace=false) {
150  rowIndex() != rhs.rowIndex() || colIndex() != rhs.colIndex(),
151  std::invalid_argument,
152  "Attempt to merge elements at different locations in the sparse "
153  "matrix. The current element is at (" << rowIndex() << ", "
154  << colIndex() << ") and the element you asked me to merge with it "
155  "is at (" << rhs.rowIndex() << ", " << rhs.colIndex() << "). This "
156  "probably indicates a bug in the sparse matrix reader.");
157 
158  if (replace) {
159  value_ = rhs.value_;
160  }
161  else {
162  value_ += rhs.value_;
163  }
164  }
165 
167  Ordinal rowIndex() const { return rowIndex_; }
168 
170  Ordinal colIndex() const { return colIndex_; }
171 
173  Scalar value() const { return value_; }
174 
175  private:
177  Scalar value_;
178  };
179 
190  template<class Scalar, class Ordinal>
191  std::ostream&
192  operator<< (std::ostream& out, const Element<Scalar, Ordinal>& elt)
193  {
194  typedef ScalarTraits<Scalar> STS;
195  // Non-Ordinal types are floating-point types. In order not to
196  // lose information when we print a floating-point type, we have
197  // to set the number of digits to print. C++ standard behavior
198  // in the default locale seems to be to print only five decimal
199  // digits after the decimal point; this does not suffice for
200  // double precision. We solve the problem of how many digits to
201  // print more generally below. It's a rough solution so please
202  // feel free to audit and revise it.
203  //
204  // FIXME (mfh 01 Feb 2011)
205  // This really calls for the following approach:
206  //
207  // Guy L. Steele and Jon L. White, "How to print floating-point
208  // numbers accurately", 20 Years of the ACM/SIGPLAN Conference
209  // on Programming Language Design and Implementation
210  // (1979-1999): A Selection, 2003.
211  if (! STS::isOrdinal) {
212  // std::scientific, std::fixed, and default are the three
213  // output states for floating-point numbers. A reasonable
214  // user-defined floating-point type should respect these
215  // flags; hopefully it does.
216  out << std::scientific;
217 
218  // Decimal output is standard for Matrix Market format.
219  out << std::setbase (10);
220 
221  // Compute the number of decimal digits required for expressing
222  // a Scalar, by comparing with IEEE 754 double precision (16
223  // decimal digits, 53 binary digits). This would be easier if
224  // Teuchos exposed std::numeric_limits<T>::digits10, alas.
225  const double numDigitsAsDouble =
226  16 * ((double) STS::t() / (double) ScalarTraits<double>::t());
227  // Adding 0.5 and truncating is a portable "floor".
228  const int numDigits = static_cast<int> (numDigitsAsDouble + 0.5);
229 
230  // Precision to which a Scalar should be written. Add one
231  // for good measure, since 17 is necessary for IEEE 754
232  // doubles.
233  out << std::setprecision (numDigits + 1);
234  }
235  out << elt.rowIndex () << " " << elt.colIndex () << " ";
236  if (STS::isComplex) {
237  out << STS::real (elt.value ()) << " " << STS::imag (elt.value ());
238  }
239  else {
240  out << elt.value ();
241  }
242  return out;
243  }
244 
281  template<class Scalar, class Ordinal>
282  class Adder {
283  public:
284  typedef Ordinal index_type;
285  typedef Scalar value_type;
287  typedef typename std::vector<element_type>::size_type size_type;
288 
299  Adder () :
300  expectedNumRows_(0),
301  expectedNumCols_(0),
302  expectedNumEntries_(0),
303  seenNumRows_(0),
304  seenNumCols_(0),
305  seenNumEntries_(0),
306  tolerant_ (true),
307  debug_ (false)
308  {}
309 
327  Adder (const Ordinal expectedNumRows,
328  const Ordinal expectedNumCols,
329  const Ordinal expectedNumEntries,
330  const bool tolerant=false,
331  const bool debug=false) :
332  expectedNumRows_(expectedNumRows),
333  expectedNumCols_(expectedNumCols),
334  expectedNumEntries_(expectedNumEntries),
335  seenNumRows_(0),
336  seenNumCols_(0),
337  seenNumEntries_(0),
338  tolerant_ (tolerant),
339  debug_ (debug)
340  {}
341 
362  void
363  operator() (const Ordinal i,
364  const Ordinal j,
365  const Scalar& Aij,
366  const bool countAgainstTotal=true)
367  {
368  if (! tolerant_) {
369  const bool indexPairOutOfRange = i < 1 || j < 1 ||
370  i > expectedNumRows_ || j > expectedNumCols_;
371 
372  TEUCHOS_TEST_FOR_EXCEPTION(indexPairOutOfRange,
373  std::invalid_argument, "Matrix is " << expectedNumRows_ << " x "
374  << expectedNumCols_ << ", so entry A(" << i << "," << j << ") = "
375  << Aij << " is out of range.");
376  if (countAgainstTotal) {
377  TEUCHOS_TEST_FOR_EXCEPTION(seenNumEntries_ >= expectedNumEntries_,
378  std::invalid_argument, "Cannot add entry A(" << i << "," << j
379  << ") = " << Aij << " to matrix; already have expected number "
380  "of entries " << expectedNumEntries_ << ".");
381  }
382  }
383  // i and j are 1-based indices, but we store them as 0-based.
384  elts_.push_back (element_type (i-1, j-1, Aij));
385 
386  // Keep track of the rightmost column containing a matrix
387  // entry, and the bottommost row containing a matrix entry.
388  // This gives us a lower bound for the dimensions of the
389  // matrix, and a check for the reported dimensions of the
390  // matrix in the Matrix Market file.
391  seenNumRows_ = std::max (seenNumRows_, i);
392  seenNumCols_ = std::max (seenNumCols_, j);
393  if (countAgainstTotal) {
394  ++seenNumEntries_;
395  }
396  }
397 
407  void
408  print (std::ostream& out, const bool doMerge, const bool replace=false)
409  {
410  if (doMerge) {
411  merge (replace);
412  } else {
413  std::sort (elts_.begin(), elts_.end());
414  }
415  // Print out the results, delimited by newlines.
416  typedef std::ostream_iterator<element_type> iter_type;
417  std::copy (elts_.begin(), elts_.end(), iter_type (out, "\n"));
418  }
419 
442  std::pair<size_type, size_type>
443  merge (const bool replace=false)
444  {
445  typedef typename std::vector<element_type>::iterator iter_type;
446 
447  // Start with a sorted container. Element objects sort in
448  // lexicographic order of their (row, column) indices, for
449  // easy conversion to CSR format. If you expect that the
450  // elements will usually be sorted in the desired order, you
451  // can check first whether they are already sorted. We have
452  // no such expectation, so we don't even bother to spend the
453  // extra O(# entries) operations to check.
454  std::sort (elts_.begin(), elts_.end());
455 
456  // Walk through the array of elements in place, merging
457  // duplicates and pushing unique elements up to the front of
458  // the array. We can't use std::unique for this because it
459  // doesn't let us merge duplicate elements; it only removes
460  // them from the sequence.
461  size_type numUnique = 0;
462  iter_type cur = elts_.begin();
463  if (cur == elts_.end()) { // No elements to merge
464  return std::make_pair (numUnique, size_type (0));
465  }
466  else {
467  iter_type next = cur;
468  ++next; // There is one unique element
469  ++numUnique;
470  while (next != elts_.end()) {
471  if (*cur == *next) {
472  // Merge in the duplicated element *next
473  cur->merge (*next, replace);
474  } else {
475  // *cur is already a unique element. Move over one to
476  // *make space for the new unique element.
477  ++cur;
478  *cur = *next; // Add the new unique element
479  ++numUnique;
480  }
481  // Look at the "next" not-yet-considered element
482  ++next;
483  }
484  // Remember how many elements we removed before resizing.
485  const size_type numRemoved = elts_.size() - numUnique;
486  elts_.resize (numUnique);
487  return std::make_pair (numUnique, numRemoved);
488  }
489  }
490 
533  void
534  mergeAndConvertToCSR (size_type& numUniqueElts,
535  size_type& numRemovedElts,
539  const bool replace=false)
540  {
541  using Teuchos::arcp;
542  using Teuchos::ArrayRCP;
543 
544  std::pair<size_type, size_type> mergeResult = merge (replace);
545 
546  // At this point, elts_ is already in CSR order.
547  // Now we can allocate and fill the ind and val arrays.
548  ArrayRCP<Ordinal> ind = arcp<Ordinal> (elts_.size ());
549  ArrayRCP<Scalar> val = arcp<Scalar> (elts_.size ());
550 
551  // Number of rows in the matrix.
552  const Ordinal nrows = tolerant_ ? seenNumRows_ : expectedNumRows_;
553  ArrayRCP<Ordinal> ptr = arcp<Ordinal> (nrows + 1);
554 
555  // Copy over the elements, and fill in the ptr array with
556  // offsets. Note that merge() sorted the entries by row
557  // index, so we can assume the row indices are increasing in
558  // the list of entries.
559  Ordinal curRow = 0;
560  Ordinal curInd = 0;
561  typedef typename std::vector<element_type>::const_iterator iter_type;
562  ptr[0] = 0; // ptr always has at least one entry.
563  for (iter_type it = elts_.begin(); it != elts_.end(); ++it) {
564  const Ordinal i = it->rowIndex ();
565  const Ordinal j = it->colIndex ();
566  const Scalar Aij = it->value ();
567 
568  TEUCHOS_TEST_FOR_EXCEPTION(i < curRow, std::logic_error, "The "
569  "current matrix entry's row index " << i << " is less then what "
570  "should be the current row index lower bound " << curRow << ".");
571  for (Ordinal k = curRow+1; k <= i; ++k) {
572  ptr[k] = curInd;
573  }
574  curRow = i;
575 
577  static_cast<size_t> (curInd) >= elts_.size (),
578  std::logic_error, "The current index " << curInd << " into ind "
579  "and val is >= the number of matrix entries " << elts_.size ()
580  << ".");
581  ind[curInd] = j;
582  val[curInd] = Aij;
583  ++curInd;
584  }
585  for (Ordinal k = curRow+1; k <= nrows; ++k) {
586  ptr[k] = curInd;
587  }
588 
589  // Assign to outputs here, to ensure the strong exception
590  // guarantee (assuming that ArrayRCP's operator= doesn't
591  // throw).
592  rowptr = ptr;
593  colind = ind;
594  values = val;
595  numUniqueElts = mergeResult.first;
596  numRemovedElts = mergeResult.second;
597  }
598 
600  const std::vector<element_type>& getEntries() const {
601  return elts_;
602  }
603 
605  void clear() {
606  seenNumRows_ = 0;
607  seenNumCols_ = 0;
608  seenNumEntries_ = 0;
609  elts_.resize (0);
610  }
611 
615  const Ordinal numRows() const { return seenNumRows_; }
616 
620  const Ordinal numCols() const { return seenNumCols_; }
621 
622  private:
623  Ordinal expectedNumRows_, expectedNumCols_, expectedNumEntries_;
624  Ordinal seenNumRows_, seenNumCols_, seenNumEntries_;
625  bool tolerant_;
626  bool debug_;
627 
629  std::vector<element_type> elts_;
630  };
631  } // namespace Raw
632  } // namespace MatrixMarket
633 } // namespace Teuchos
634 
635 #endif // #ifndef __Teuchos_MatrixMarket_Raw_Adder_hpp
std::pair< size_type, size_type > merge(const bool replace=false)
Merge duplicate elements.
std::vector< element_type > elts_
The actual matrix entries, stored as an array of structs.
const std::vector< element_type > & getEntries() const
A temporary const view of the entries of the matrix.
bool operator<(const Element &rhs) const
Lexicographic order first by row index, then by column index.
Element(const Ordinal i, const Ordinal j, const Scalar &Aij)
Create a sparse matrix entry at (i,j) with value Aij.
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Macro for throwing an exception with breakpointing to ease debugging.
"Raw" input of sparse matrices from Matrix Market files.
Scalar value() const
Value (A(rowIndex(), colIndex()) of this Element.
Teuchos header file which uses auto-configuration information to include necessary C++ headers...
void clear()
Clear all the added matrix entries and reset metadata.
void mergeAndConvertToCSR(size_type &numUniqueElts, size_type &numRemovedElts, Teuchos::ArrayRCP< Ordinal > &rowptr, Teuchos::ArrayRCP< Ordinal > &colind, Teuchos::ArrayRCP< Scalar > &values, const bool replace=false)
Merge duplicate elements and convert to zero-based CSR.
Element()
Default constructor: an invalid entry of the matrix.
This structure defines some basic traits for a scalar field type.
Templated Parameter List class.
Ordinal rowIndex() const
Row index (zero-based) of this Element.
bool operator==(const Element &rhs)
Ignore the matrix value for comparisons.
const Ordinal numRows() const
Computed number of rows.
void print(std::ostream &out, const bool doMerge, const bool replace=false)
Print the sparse matrix data.
Stores one entry of a sparse matrix.
const Ordinal numCols() const
Computed number of columns.
void merge(const Element &rhs, const BinaryFunction &f)
Merge rhs into this Element, using custom binary function.
bool operator!=(const Element &rhs)
Ignore the matrix value for comparisons.
void merge(const Element &rhs, const bool replace=false)
Merge rhs into this Element, either by addition or replacement.
Ordinal colIndex() const
Column index (zero-based) of this Element.
Adder(const Ordinal expectedNumRows, const Ordinal expectedNumCols, const Ordinal expectedNumEntries, const bool tolerant=false, const bool debug=false)
Standard constructor.
Matrix Market file utilities.
std::vector< element_type >::size_type size_type
Reference-counted smart pointer for managing arrays.
To be used with Checker for "raw" sparse matrix input.