Tpetra Matrix/Vector Services  Version of the Day
MatrixMarket_Tpetra.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 __MatrixMarket_Tpetra_hpp
43 #define __MatrixMarket_Tpetra_hpp
44 
56 #include "Tpetra_CrsMatrix.hpp"
57 #include "Teuchos_MatrixMarket_Raw_Adder.hpp"
58 #include "Teuchos_MatrixMarket_SymmetrizingAdder.hpp"
59 #include "Teuchos_MatrixMarket_assignScalar.hpp"
60 #include "Teuchos_MatrixMarket_Banner.hpp"
61 #include "Teuchos_MatrixMarket_CoordDataReader.hpp"
62 #include "Teuchos_MatrixMarket_SetScientific.hpp"
63 
64 #include <algorithm>
65 #include <fstream>
66 #include <iostream>
67 #include <iterator>
68 #include <vector>
69 #include <stdexcept>
70 
71 namespace Tpetra {
100  namespace MatrixMarket {
101 
102  namespace {
103 #ifdef HAVE_MPI
104  // We're communicating integers of type IntType. Figure
105  // out the right MPI_Datatype for IntType. Usually it
106  // is int or long, so these are good enough for now.
107  template<class IntType> MPI_Datatype getMpiDatatype () {
108  TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Not implemented for IntType != int or long");
109  }
110  template<> MPI_Datatype getMpiDatatype<int> () { return MPI_INT; }
111  template<> MPI_Datatype getMpiDatatype<long> () { return MPI_LONG; }
112 #endif // HAVE_MPI
113 
114  template<class IntType>
115  void
116  reduceSum (const IntType sendbuf[],
117  IntType recvbuf[],
118  const int count,
119  const int root,
120  const Teuchos::RCP<const Teuchos::Comm<int> >& comm)
121  {
122 #ifdef HAVE_MPI
123  using Teuchos::RCP;
124  using Teuchos::rcp_dynamic_cast;
125  using Teuchos::MpiComm;
126 
127  // Get the raw MPI communicator, so we don't have to wrap MPI_Reduce in Teuchos.
128  RCP<const MpiComm<int> > mpiComm = rcp_dynamic_cast<const MpiComm<int> > (comm);
129  if (! mpiComm.is_null ()) {
130  MPI_Datatype rawMpiType = getMpiDatatype<IntType> ();
131  MPI_Comm rawMpiComm = * (mpiComm->getRawMpiComm ());
132  const int err =
133  MPI_Reduce (reinterpret_cast<void*> (const_cast<IntType*> (sendbuf)),
134  reinterpret_cast<void*> (const_cast<IntType*> (recvbuf)),
135  count, rawMpiType, MPI_SUM, root, rawMpiComm);
136  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error, "MPI_Reduce failed");
137  return;
138  }
139 #endif // HAVE_MPI
140  // Serial communicator case: just copy. count is the
141  // amount to receive, so it's the amount to copy.
142  std::copy (sendbuf, sendbuf + count, recvbuf);
143  }
144 
145  template<class IntType>
146  void
147  gather (const IntType sendbuf[], const int sendcnt,
148  IntType recvbuf[], const int recvcnt,
149  const int root, const Teuchos::RCP<const Teuchos::Comm<int> >& comm)
150  {
151  using Teuchos::RCP;
152  using Teuchos::rcp_dynamic_cast;
153 #ifdef HAVE_MPI
154  using Teuchos::MpiComm;
155 
156  // Get the raw MPI communicator, so we don't have to wrap MPI_Gather in Teuchos.
157  RCP<const MpiComm<int> > mpiComm = rcp_dynamic_cast<const MpiComm<int> > (comm);
158  if (! mpiComm.is_null ()) {
159  MPI_Datatype sendtype = getMpiDatatype<IntType> ();
160  MPI_Datatype recvtype = sendtype;
161  MPI_Comm rawMpiComm = * (mpiComm->getRawMpiComm ());
162  const int err = MPI_Gather (reinterpret_cast<void*> (const_cast<IntType*> (sendbuf)),
163  sendcnt,
164  sendtype,
165  reinterpret_cast<void*> (recvbuf),
166  recvcnt,
167  recvtype,
168  root,
169  rawMpiComm);
171  err != MPI_SUCCESS, std::runtime_error, "MPI_Gather failed");
172  return;
173  }
174 #endif // HAVE_MPI
175 
177  recvcnt > sendcnt, std::invalid_argument,
178  "gather: If the input communicator contains only one process, "
179  "then you cannot receive more entries than you send. "
180  "You aim to receive " << recvcnt << " entries, "
181  "but to send " << sendcnt << ".");
182  // Serial communicator case: just copy. recvcnt is the
183  // amount to receive, so it's the amount to copy.
184  std::copy (sendbuf, sendbuf + recvcnt, recvbuf);
185  }
186 
187  template<class IntType>
188  void
189  gatherv (const IntType sendbuf[], const int sendcnt,
190  IntType recvbuf[], const int recvcnts[], const int displs[],
191  const int root, const Teuchos::RCP<const Teuchos::Comm<int> >& comm)
192  {
193  using Teuchos::RCP;
194  using Teuchos::rcp_dynamic_cast;
195 #ifdef HAVE_MPI
196  using Teuchos::MpiComm;
197 
198  // Get the raw MPI communicator, so we don't have to wrap
199  // MPI_Gather in Teuchos.
200  RCP<const MpiComm<int> > mpiComm =
201  rcp_dynamic_cast<const MpiComm<int> > (comm);
202  if (! mpiComm.is_null ()) {
203  MPI_Datatype sendtype = getMpiDatatype<IntType> ();
204  MPI_Datatype recvtype = sendtype;
205  MPI_Comm rawMpiComm = * (mpiComm->getRawMpiComm ());
206  const int err = MPI_Gatherv (reinterpret_cast<void*> (const_cast<IntType*> (sendbuf)),
207  sendcnt,
208  sendtype,
209  reinterpret_cast<void*> (recvbuf),
210  const_cast<int*> (recvcnts),
211  const_cast<int*> (displs),
212  recvtype,
213  root,
214  rawMpiComm);
216  err != MPI_SUCCESS, std::runtime_error, "MPI_Gatherv failed");
217  return;
218  }
219 #endif // HAVE_MPI
221  recvcnts[0] > sendcnt,
222  std::invalid_argument,
223  "gatherv: If the input communicator contains only one process, "
224  "then you cannot receive more entries than you send. "
225  "You aim to receive " << recvcnts[0] << " entries, "
226  "but to send " << sendcnt << ".");
227  // Serial communicator case: just copy. recvcnts[0] is the
228  // amount to receive, so it's the amount to copy. Start
229  // writing to recvbuf at the offset displs[0].
230  std::copy (sendbuf, sendbuf + recvcnts[0], recvbuf + displs[0]);
231  }
232 
233  // Given an arbitrary Map, compute a Map containing all the GIDs
234  // in the same order as in (the one-to-one version of) map, but
235  // all owned exclusively by Proc 0.
236  template<class MapType>
238  computeGatherMap (Teuchos::RCP<const MapType> map,
240  const bool debug=false)
241  {
243  using Tpetra::global_size_t;
244  using Teuchos::Array;
245  using Teuchos::ArrayRCP;
246  using Teuchos::ArrayView;
247  using Teuchos::as;
248  using Teuchos::Comm;
249  using Teuchos::RCP;
250  using std::endl;
251  typedef typename MapType::local_ordinal_type LO;
252  typedef typename MapType::global_ordinal_type GO;
253  typedef typename MapType::node_type NT;
254 
255  RCP<const Comm<int> > comm = map->getComm ();
256  const int numProcs = comm->getSize ();
257  const int myRank = comm->getRank ();
258 
259  if (! err.is_null ()) {
260  err->pushTab ();
261  }
262  if (debug) {
263  *err << myRank << ": computeGatherMap:" << endl;
264  }
265  if (! err.is_null ()) {
266  err->pushTab ();
267  }
268 
269  RCP<const MapType> oneToOneMap;
270  if (map->isContiguous ()) {
271  oneToOneMap = map; // contiguous Maps are always 1-to-1
272  } else {
273  if (debug) {
274  *err << myRank << ": computeGatherMap: Calling createOneToOne" << endl;
275  }
276  // It could be that Map is one-to-one, but the class doesn't
277  // give us a way to test this, other than to create the
278  // one-to-one Map.
279  oneToOneMap = createOneToOne<LO, GO, NT> (map);
280  }
281 
282  RCP<const MapType> gatherMap;
283  if (numProcs == 1) {
284  gatherMap = oneToOneMap;
285  } else {
286  if (debug) {
287  *err << myRank << ": computeGatherMap: Gathering Map counts" << endl;
288  }
289  // Gather each process' count of Map elements to Proc 0,
290  // into the recvCounts array. This will tell Proc 0 how
291  // many GIDs to expect from each process when calling
292  // MPI_Gatherv. Counts and offsets are all int, because
293  // that's what MPI uses. Teuchos::as will at least prevent
294  // bad casts to int in a debug build.
295  //
296  // Yeah, it's not memory scalable. Guess what: We're going
297  // to bring ALL the data to Proc 0, not just the receive
298  // counts. The first MPI_Gather is only the beginning...
299  // Seriously, if you want to make this memory scalable, the
300  // right thing to do (after the Export to the one-to-one
301  // Map) is to go round robin through the processes, having
302  // each send a chunk of data (with its GIDs, to get the
303  // order of rows right) at a time, and overlapping writing
304  // to the file (resp. reading from it) with receiving (resp.
305  // sending) the next chunk.
306  const int myEltCount = as<int> (oneToOneMap->getNodeNumElements ());
307  Array<int> recvCounts (numProcs);
308  const int rootProc = 0;
309  gather<int> (&myEltCount, 1, recvCounts.getRawPtr (), 1, rootProc, comm);
310 
311  ArrayView<const GO> myGlobalElts = oneToOneMap->getNodeElementList ();
312  const int numMyGlobalElts = as<int> (myGlobalElts.size ());
313  // Only Proc 0 needs to receive and store all the GIDs (from
314  // all processes).
315  ArrayRCP<GO> allGlobalElts;
316  if (myRank == 0) {
317  allGlobalElts = arcp<GO> (oneToOneMap->getGlobalNumElements ());
318  std::fill (allGlobalElts.begin (), allGlobalElts.end (), 0);
319  }
320 
321  if (debug) {
322  *err << myRank << ": computeGatherMap: Computing MPI_Gatherv "
323  "displacements" << endl;
324  }
325  // Displacements for gatherv() in this case (where we are
326  // gathering into a contiguous array) are an exclusive
327  // partial sum (first entry is zero, second starts the
328  // partial sum) of recvCounts.
329  Array<int> displs (numProcs, 0);
330  std::partial_sum (recvCounts.begin (), recvCounts.end () - 1,
331  displs.begin () + 1);
332  if (debug) {
333  *err << myRank << ": computeGatherMap: Calling MPI_Gatherv" << endl;
334  }
335  gatherv<GO> (myGlobalElts.getRawPtr (), numMyGlobalElts,
336  allGlobalElts.getRawPtr (), recvCounts.getRawPtr (),
337  displs.getRawPtr (), rootProc, comm);
338 
339  if (debug) {
340  *err << myRank << ": computeGatherMap: Creating gather Map" << endl;
341  }
342  // Create a Map with all the GIDs, in the same order as in
343  // the one-to-one Map, but owned by Proc 0.
344  ArrayView<const GO> allElts (NULL, 0);
345  if (myRank == 0) {
346  allElts = allGlobalElts ();
347  }
349  gatherMap = rcp (new MapType (INVALID, allElts,
350  oneToOneMap->getIndexBase (),
351  comm, map->getNode ()));
352  }
353  if (! err.is_null ()) {
354  err->popTab ();
355  }
356  if (debug) {
357  *err << myRank << ": computeGatherMap: done" << endl;
358  }
359  if (! err.is_null ()) {
360  err->popTab ();
361  }
362  return gatherMap;
363  }
364  } // namespace (anonymous)
365 
429  template<class SparseMatrixType>
430  class Reader {
431  public:
433  typedef SparseMatrixType sparse_matrix_type;
435 
438  typedef typename SparseMatrixType::scalar_type scalar_type;
441  typedef typename SparseMatrixType::local_ordinal_type local_ordinal_type;
449  typedef typename SparseMatrixType::global_ordinal_type
453  typedef typename SparseMatrixType::node_type node_type;
454 
456  typedef MultiVector<scalar_type,
459  node_type> multivector_type;
460 
461  typedef RCP<node_type> node_ptr;
462  typedef Comm<int> comm_type;
466 
467  private:
470  typedef typename ArrayRCP<global_ordinal_type>::size_type size_type;
471 
483  static RCP<const map_type>
484  makeRangeMap (const RCP<const comm_type>& pComm,
485  const RCP<node_type>& pNode,
486  const global_ordinal_type numRows)
487  {
488  // A conventional, uniformly partitioned, contiguous map.
489  return rcp (new map_type (static_cast<global_size_t> (numRows),
490  static_cast<global_ordinal_type> (0),
491  pComm, GloballyDistributed, pNode));
492  }
493 
522  static RCP<const map_type>
523  makeRowMap (const RCP<const map_type>& pRowMap,
524  const RCP<const comm_type>& pComm,
525  const RCP<node_type>& pNode,
526  const global_ordinal_type numRows)
527  {
528  // If the caller didn't provide a map, return a conventional,
529  // uniformly partitioned, contiguous map.
530  if (pRowMap.is_null()) {
531  return rcp (new map_type (static_cast<global_size_t> (numRows),
532  static_cast<global_ordinal_type> (0),
533  pComm, GloballyDistributed, pNode));
534  } else {
535  TEUCHOS_TEST_FOR_EXCEPTION(! pRowMap->isDistributed() && pComm->getSize() > 1,
536  std::invalid_argument,
537  "The specified row map is not distributed, but "
538  "the given communicator includes more than one "
539  "rank (in fact, there are " << pComm->getSize()
540  << " ranks).");
541  TEUCHOS_TEST_FOR_EXCEPTION(pRowMap->getComm() != pComm,
542  std::invalid_argument,
543  "The specified row map's communicator (pRowMap->"
544  "getComm()) is different than the given separately "
545  "supplied communicator pComm.");
546  TEUCHOS_TEST_FOR_EXCEPTION(pRowMap->getNode() != pNode,
547  std::invalid_argument,
548  "The specified row map's node (pRowMap->getNode()) "
549  "is different than the given separately supplied "
550  "node pNode.");
551  return pRowMap;
552  }
553  }
554 
570  makeDomainMap (const Teuchos::RCP<const map_type>& pRangeMap,
571  const global_ordinal_type numRows,
572  const global_ordinal_type numCols)
573  {
574  // Abbreviations so that the map creation call isn't too long.
575  typedef local_ordinal_type LO;
576  typedef global_ordinal_type GO;
577  typedef node_type Node;
578 
579  if (numRows == numCols) {
580  return pRangeMap;
581  } else {
582  return createUniformContigMapWithNode<LO,GO,Node> (numCols,
583  pRangeMap->getComm (),
584  pRangeMap->getNode ());
585  }
586  }
587 
660  static void
661  distribute (ArrayRCP<size_t>& myNumEntriesPerRow,
662  ArrayRCP<size_t>& myRowPtr,
664  ArrayRCP<scalar_type>& myValues,
665  const RCP<const map_type>& pRowMap,
666  ArrayRCP<size_t>& numEntriesPerRow,
667  ArrayRCP<size_t>& rowPtr,
669  ArrayRCP<scalar_type>& values,
670  const bool debug=false)
671  {
672  using Teuchos::as;
673  using Teuchos::CommRequest;
674  using Teuchos::receive;
675  using Teuchos::send;
676  using std::cerr;
677  using std::endl;
678 
679  const bool extraDebug = false;
680  comm_ptr pComm = pRowMap->getComm();
681  const int numProcs = pComm->getSize ();
682  const int myRank = pComm->getRank ();
683  const int rootRank = 0;
684 
685  // Type abbreviations to make the code more concise.
686  typedef global_ordinal_type GO;
687 
688  // List of the global indices of my rows. They may or may
689  // not be contiguous, and the row map need not be one-to-one.
690  ArrayView<const GO> myRows = pRowMap->getNodeElementList();
691  const size_type myNumRows = myRows.size();
692  TEUCHOS_TEST_FOR_EXCEPTION(static_cast<size_t>(myNumRows) !=
693  pRowMap->getNodeNumElements(),
694  std::logic_error,
695  "pRowMap->getNodeElementList().size() = "
696  << myNumRows
697  << " != pRowMap->getNodeNumElements() = "
698  << pRowMap->getNodeNumElements() << ". "
699  "Please report this bug to the Tpetra developers.");
700  TEUCHOS_TEST_FOR_EXCEPTION(myRank == 0 && numEntriesPerRow.size() < myNumRows,
701  std::logic_error,
702  "On Proc 0: numEntriesPerRow.size() = "
703  << numEntriesPerRow.size()
704  << " != pRowMap->getNodeElementList().size() = "
705  << myNumRows << ". Please report this bug to the "
706  "Tpetra developers.");
707 
708  // Space for my proc's number of entries per row. Will be
709  // filled in below.
710  myNumEntriesPerRow = arcp<size_t> (myNumRows);
711 
712  if (myRank != rootRank) {
713  // Tell the root how many rows we have. If we're sending
714  // none, then we don't have anything else to send, nor does
715  // the root have to receive anything else.
716  send (*pComm, myNumRows, rootRank);
717  if (myNumRows != 0) {
718  // Now send my rows' global indices. Hopefully the cast
719  // to int doesn't overflow. This is unlikely, since it
720  // should fit in a LO, even though it is a GO.
721  send (*pComm, static_cast<int> (myNumRows),
722  myRows.getRawPtr(), rootRank);
723 
724  // I (this proc) don't care if my global row indices are
725  // contiguous, though the root proc does (since otherwise
726  // it needs to pack noncontiguous data into contiguous
727  // storage before sending). That's why we don't check
728  // for contiguousness here.
729 
730  // Ask the root process for my part of the array of the
731  // number of entries per row.
732  receive (*pComm, rootRank,
733  static_cast<int> (myNumRows),
734  myNumEntriesPerRow.getRawPtr());
735 
736  // Use the resulting array to figure out how many column
737  // indices and values I should ask from the root process.
738  const local_ordinal_type myNumEntries =
739  std::accumulate (myNumEntriesPerRow.begin(),
740  myNumEntriesPerRow.end(), 0);
741 
742  // Make space for my entries of the sparse matrix. Note
743  // that they don't have to be sorted by row index.
744  // Iterating through all my rows requires computing a
745  // running sum over myNumEntriesPerRow.
746  myColInd = arcp<GO> (myNumEntries);
747  myValues = arcp<scalar_type> (myNumEntries);
748  if (myNumEntries > 0) {
749  // Ask for that many column indices and values, if
750  // there are any.
751  receive (*pComm, rootRank,
752  static_cast<int> (myNumEntries),
753  myColInd.getRawPtr());
754  receive (*pComm, rootRank,
755  static_cast<int> (myNumEntries),
756  myValues.getRawPtr());
757  }
758  } // If I own at least one row
759  } // If I am not the root processor
760  else { // I _am_ the root processor
761  if (debug) {
762  cerr << "-- Proc 0: Copying my data from global arrays" << endl;
763  }
764  // Proc 0 still needs to (allocate, if not done already)
765  // and fill its part of the matrix (my*).
766  for (size_type k = 0; k < myNumRows; ++k) {
767  const GO myCurRow = myRows[k];
768  const local_ordinal_type numEntriesInThisRow = numEntriesPerRow[myCurRow];
769  myNumEntriesPerRow[k] = numEntriesInThisRow;
770  }
771  if (extraDebug && debug) {
772  cerr << "Proc " << pRowMap->getComm ()->getRank ()
773  << ": myNumEntriesPerRow[0.." << (myNumRows-1) << "] = [";
774  for (size_type k = 0; k < myNumRows; ++k) {
775  cerr << myNumEntriesPerRow[k];
776  if (k < myNumRows-1) {
777  cerr << " ";
778  }
779  }
780  cerr << "]" << endl;
781  }
782  // The total number of matrix entries that my proc owns.
783  const local_ordinal_type myNumEntries =
784  std::accumulate (myNumEntriesPerRow.begin(),
785  myNumEntriesPerRow.end(), 0);
786  if (debug) {
787  cerr << "-- Proc 0: I own " << myNumRows << " rows and "
788  << myNumEntries << " entries" << endl;
789  }
790  myColInd = arcp<GO> (myNumEntries);
791  myValues = arcp<scalar_type> (myNumEntries);
792 
793  // Copy Proc 0's part of the matrix into the my* arrays.
794  // It's important that myCurPos be updated _before_ k,
795  // otherwise myCurPos will get the wrong number of entries
796  // per row (it should be for the row in the just-completed
797  // iteration, not for the next iteration's row).
798  local_ordinal_type myCurPos = 0;
799  for (size_type k = 0; k < myNumRows;
800  myCurPos += myNumEntriesPerRow[k], ++k) {
801  const local_ordinal_type curNumEntries = myNumEntriesPerRow[k];
802  const GO myRow = myRows[k];
803  const size_t curPos = rowPtr[myRow];
804  // Only copy if there are entries to copy, in order not
805  // to construct empty ranges for the ArrayRCP views.
806  if (curNumEntries > 0) {
807  ArrayView<GO> colIndView = colInd (curPos, curNumEntries);
808  ArrayView<GO> myColIndView = myColInd (myCurPos, curNumEntries);
809  std::copy (colIndView.begin(), colIndView.end(),
810  myColIndView.begin());
811 
812  ArrayView<scalar_type> valuesView =
813  values (curPos, curNumEntries);
814  ArrayView<scalar_type> myValuesView =
815  myValues (myCurPos, curNumEntries);
816  std::copy (valuesView.begin(), valuesView.end(),
817  myValuesView.begin());
818  }
819  }
820 
821  // Proc 0 processes each other proc p in turn.
822  for (int p = 1; p < numProcs; ++p) {
823  if (debug) {
824  cerr << "-- Proc 0: Processing proc " << p << endl;
825  }
826 
827  size_type theirNumRows = 0;
828  // Ask Proc p how many rows it has. If it doesn't
829  // have any, we can move on to the next proc. This
830  // has to be a standard receive so that we can avoid
831  // the degenerate case of sending zero data.
832  receive (*pComm, p, &theirNumRows);
833  if (debug) {
834  cerr << "-- Proc 0: Proc " << p << " owns "
835  << theirNumRows << " rows" << endl;
836  }
837  if (theirNumRows != 0) {
838  // Ask Proc p which rows it owns. The resulting global
839  // row indices are not guaranteed to be contiguous or
840  // sorted. Global row indices are themselves indices
841  // into the numEntriesPerRow array.
842  ArrayRCP<GO> theirRows = arcp<GO> (theirNumRows);
843  receive (*pComm, p, as<int> (theirNumRows),
844  theirRows.getRawPtr ());
845  // Extra test to make sure that the rows we received
846  // are all sensible. This is a good idea since we are
847  // going to use the global row indices we've received
848  // to index into the numEntriesPerRow array. Better to
849  // catch any bugs here and print a sensible error
850  // message, rather than segfault and print a cryptic
851  // error message.
852  {
853  const global_size_t numRows = pRowMap->getGlobalNumElements ();
854  const GO indexBase = pRowMap->getIndexBase ();
855  bool theirRowsValid = true;
856  for (size_type k = 0; k < theirNumRows; ++k) {
857  if (theirRows[k] < indexBase ||
858  as<global_size_t> (theirRows[k] - indexBase) >= numRows) {
859  theirRowsValid = false;
860  }
861  }
862  if (! theirRowsValid) {
864  ! theirRowsValid, std::logic_error,
865  "Proc " << p << " has at least one invalid row index. "
866  "Here are all of them: " <<
867  Teuchos::toString (theirRows ()) << ". Valid row index "
868  "range (zero-based): [0, " << (numRows - 1) << "].");
869  }
870  }
871 
872  // Perhaps we could save a little work if we check
873  // whether Proc p's row indices are contiguous. That
874  // would make lookups in the global data arrays
875  // faster. For now, we just implement the general
876  // case and don't prematurely optimize. (Remember
877  // that you're making Proc 0 read the whole file, so
878  // you've already lost scalability.)
879 
880  // Compute the number of entries in each of Proc p's
881  // rows. (Proc p will compute its row pointer array
882  // on its own, after it gets the data from Proc 0.)
883  ArrayRCP<size_t> theirNumEntriesPerRow;
884  theirNumEntriesPerRow = arcp<size_t> (theirNumRows);
885  for (size_type k = 0; k < theirNumRows; ++k) {
886  theirNumEntriesPerRow[k] = numEntriesPerRow[theirRows[k]];
887  }
888 
889  // Tell Proc p the number of entries in each of its
890  // rows. Hopefully the cast to int doesn't overflow.
891  // This is unlikely, since it should fit in a LO,
892  // even though it is a GO.
893  send (*pComm, static_cast<int> (theirNumRows),
894  theirNumEntriesPerRow.getRawPtr(), p);
895 
896  // Figure out how many entries Proc p owns.
897  const local_ordinal_type theirNumEntries =
898  std::accumulate (theirNumEntriesPerRow.begin(),
899  theirNumEntriesPerRow.end(), 0);
900 
901  if (debug) {
902  cerr << "-- Proc 0: Proc " << p << " owns "
903  << theirNumEntries << " entries" << endl;
904  }
905 
906  // If there are no entries to send, then we're done
907  // with Proc p.
908  if (theirNumEntries == 0) {
909  continue;
910  }
911 
912  // Construct (views of) proc p's column indices and
913  // values. Later, we might like to optimize for the
914  // (common) contiguous case, for which we don't need to
915  // copy data into separate "their*" arrays (we can just
916  // use contiguous views of the global arrays).
917  ArrayRCP<GO> theirColInd (theirNumEntries);
918  ArrayRCP<scalar_type> theirValues (theirNumEntries);
919  // Copy Proc p's part of the matrix into the their*
920  // arrays. It's important that theirCurPos be updated
921  // _before_ k, otherwise theirCurPos will get the wrong
922  // number of entries per row (it should be for the row
923  // in the just-completed iteration, not for the next
924  // iteration's row).
925  local_ordinal_type theirCurPos = 0;
926  for (size_type k = 0; k < theirNumRows;
927  theirCurPos += theirNumEntriesPerRow[k], k++) {
928  const local_ordinal_type curNumEntries = theirNumEntriesPerRow[k];
929  const GO theirRow = theirRows[k];
930  const local_ordinal_type curPos = rowPtr[theirRow];
931 
932  // Only copy if there are entries to copy, in order
933  // not to construct empty ranges for the ArrayRCP
934  // views.
935  if (curNumEntries > 0) {
936  ArrayView<GO> colIndView =
937  colInd (curPos, curNumEntries);
938  ArrayView<GO> theirColIndView =
939  theirColInd (theirCurPos, curNumEntries);
940  std::copy (colIndView.begin(), colIndView.end(),
941  theirColIndView.begin());
942 
943  ArrayView<scalar_type> valuesView =
944  values (curPos, curNumEntries);
945  ArrayView<scalar_type> theirValuesView =
946  theirValues (theirCurPos, curNumEntries);
947  std::copy (valuesView.begin(), valuesView.end(),
948  theirValuesView.begin());
949  }
950  }
951  // Send Proc p its column indices and values.
952  // Hopefully the cast to int doesn't overflow. This
953  // is unlikely, since it should fit in a LO, even
954  // though it is a GO.
955  send (*pComm, static_cast<int> (theirNumEntries),
956  theirColInd.getRawPtr(), p);
957  send (*pComm, static_cast<int> (theirNumEntries),
958  theirValues.getRawPtr(), p);
959 
960  if (debug) {
961  cerr << "-- Proc 0: Finished with proc " << p << endl;
962  }
963  } // If proc p owns at least one row
964  } // For each proc p not the root proc 0
965  } // If I'm (not) the root proc 0
966 
967  // Invalidate the input data to save space, since we don't
968  // need it anymore.
969  numEntriesPerRow = null;
970  rowPtr = null;
971  colInd = null;
972  values = null;
973 
974  if (debug && myRank == 0) {
975  cerr << "-- Proc 0: About to fill in myRowPtr" << endl;
976  }
977 
978  // Allocate and fill in myRowPtr (the row pointer array for
979  // my rank's rows). We delay this until the end because we
980  // don't need it to compute anything else in distribute().
981  // Each proc can do this work for itself, since it only needs
982  // myNumEntriesPerRow to do so.
983  myRowPtr = arcp<size_t> (myNumRows+1);
984  myRowPtr[0] = 0;
985  for (size_type k = 1; k < myNumRows+1; ++k) {
986  myRowPtr[k] = myRowPtr[k-1] + myNumEntriesPerRow[k-1];
987  }
988  if (extraDebug && debug) {
989  cerr << "Proc " << Teuchos::rank (*(pRowMap->getComm()))
990  << ": myRowPtr[0.." << myNumRows << "] = [";
991  for (size_type k = 0; k < myNumRows+1; ++k) {
992  cerr << myRowPtr[k];
993  if (k < myNumRows) {
994  cerr << " ";
995  }
996  }
997  cerr << "]" << endl << endl;
998  }
999 
1000  if (debug && myRank == 0) {
1001  cerr << "-- Proc 0: Done with distribute" << endl;
1002  }
1003  }
1004 
1018  static sparse_matrix_ptr
1019  makeMatrix (ArrayRCP<size_t>& myNumEntriesPerRow,
1020  ArrayRCP<size_t>& myRowPtr,
1022  ArrayRCP<scalar_type>& myValues,
1023  const map_ptr& pRowMap,
1024  const map_ptr& pRangeMap,
1025  const map_ptr& pDomainMap,
1026  const bool callFillComplete = true)
1027  {
1028  using std::cerr;
1029  using std::endl;
1030  // Typedef to make certain type declarations shorter.
1031  typedef global_ordinal_type GO;
1032 
1033  // The row pointer array always has at least one entry, even
1034  // if the matrix has zero rows. myNumEntriesPerRow, myColInd,
1035  // and myValues would all be empty arrays in that degenerate
1036  // case, but the row and domain maps would still be nonnull
1037  // (though they would be trivial maps).
1038  TEUCHOS_TEST_FOR_EXCEPTION(myRowPtr.is_null(), std::logic_error,
1039  "makeMatrix: myRowPtr array is null. "
1040  "Please report this bug to the Tpetra developers.");
1041  TEUCHOS_TEST_FOR_EXCEPTION(pDomainMap.is_null(), std::logic_error,
1042  "makeMatrix: domain map is null. "
1043  "Please report this bug to the Tpetra developers.");
1044  TEUCHOS_TEST_FOR_EXCEPTION(pRangeMap.is_null(), std::logic_error,
1045  "makeMatrix: range map is null. "
1046  "Please report this bug to the Tpetra developers.");
1047  TEUCHOS_TEST_FOR_EXCEPTION(pRowMap.is_null(), std::logic_error,
1048  "makeMatrix: row map is null. "
1049  "Please report this bug to the Tpetra developers.");
1050 
1051  // Construct the CrsMatrix, using the row map, with the
1052  // constructor specifying the number of nonzeros for each row.
1053  // Create with DynamicProfile, so that the fillComplete() can
1054  // do first-touch reallocation (a NUMA (Non-Uniform Memory
1055  // Access) optimization on multicore CPUs).
1056  sparse_matrix_ptr A =
1057  rcp (new sparse_matrix_type (pRowMap, myNumEntriesPerRow,
1058  DynamicProfile));
1059 
1060  // List of the global indices of my rows.
1061  // They may or may not be contiguous.
1062  ArrayView<const GO> myRows = pRowMap->getNodeElementList ();
1063  const size_type myNumRows = myRows.size ();
1064 
1065  // Add this processor's matrix entries to the CrsMatrix.
1066  const GO indexBase = pRowMap->getIndexBase ();
1067  for (size_type i = 0; i < myNumRows; ++i) {
1068  const size_type myCurPos = myRowPtr[i];
1069  const local_ordinal_type curNumEntries = myNumEntriesPerRow[i];
1070  ArrayView<GO> curColInd = myColInd.view (myCurPos, curNumEntries);
1071  ArrayView<scalar_type> curValues = myValues.view (myCurPos, curNumEntries);
1072 
1073  // Modify the column indices in place to have the right index base.
1074  for (size_type k = 0; k < curNumEntries; ++k) {
1075  curColInd[k] += indexBase;
1076  }
1077  // Avoid constructing empty views of ArrayRCP objects.
1078  if (curNumEntries > 0) {
1079  A->insertGlobalValues (myRows[i], curColInd, curValues);
1080  }
1081  }
1082  // We've entered in all our matrix entries, so we can delete
1083  // the original data. This will save memory when we call
1084  // fillComplete(), so that we never keep more than two copies
1085  // of the matrix's data in memory at once.
1086  myNumEntriesPerRow = null;
1087  myRowPtr = null;
1088  myColInd = null;
1089  myValues = null;
1090 
1091  if (callFillComplete) {
1092  A->fillComplete (pDomainMap, pRangeMap);
1093  }
1094  return A;
1095  }
1096 
1102  static sparse_matrix_ptr
1103  makeMatrix (ArrayRCP<size_t>& myNumEntriesPerRow,
1104  ArrayRCP<size_t>& myRowPtr,
1106  ArrayRCP<scalar_type>& myValues,
1107  const map_ptr& pRowMap,
1108  const map_ptr& pRangeMap,
1109  const map_ptr& pDomainMap,
1110  const RCP<Teuchos::ParameterList>& constructorParams,
1111  const RCP<Teuchos::ParameterList>& fillCompleteParams)
1112  {
1113  using std::cerr;
1114  using std::endl;
1115  // Typedef to make certain type declarations shorter.
1116  typedef global_ordinal_type GO;
1117 
1118  // The row pointer array always has at least one entry, even
1119  // if the matrix has zero rows. myNumEntriesPerRow, myColInd,
1120  // and myValues would all be empty arrays in that degenerate
1121  // case, but the row and domain maps would still be nonnull
1122  // (though they would be trivial maps).
1124  myRowPtr.is_null(), std::logic_error,
1125  "makeMatrix: myRowPtr array is null. "
1126  "Please report this bug to the Tpetra developers.");
1128  pDomainMap.is_null(), std::logic_error,
1129  "makeMatrix: domain map is null. "
1130  "Please report this bug to the Tpetra developers.");
1132  pRangeMap.is_null(), std::logic_error,
1133  "makeMatrix: range map is null. "
1134  "Please report this bug to the Tpetra developers.");
1136  pRowMap.is_null(), std::logic_error,
1137  "makeMatrix: row map is null. "
1138  "Please report this bug to the Tpetra developers.");
1139 
1140  // Construct the CrsMatrix, using the row map, with the
1141  // constructor specifying the number of nonzeros for each row.
1142  // Create with DynamicProfile, so that the fillComplete() can
1143  // do first-touch reallocation (a NUMA (Non-Uniform Memory
1144  // Access) optimization on multicore CPUs).
1145  sparse_matrix_ptr A =
1146  rcp (new sparse_matrix_type (pRowMap, myNumEntriesPerRow,
1147  DynamicProfile, constructorParams));
1148 
1149  // List of the global indices of my rows.
1150  // They may or may not be contiguous.
1151  ArrayView<const GO> myRows = pRowMap->getNodeElementList();
1152  const size_type myNumRows = myRows.size();
1153 
1154  // Add this processor's matrix entries to the CrsMatrix.
1155  const GO indexBase = pRowMap->getIndexBase ();
1156  for (size_type i = 0; i < myNumRows; ++i) {
1157  const size_type myCurPos = myRowPtr[i];
1158  const local_ordinal_type curNumEntries = myNumEntriesPerRow[i];
1159  ArrayView<GO> curColInd = myColInd.view (myCurPos, curNumEntries);
1160  ArrayView<scalar_type> curValues = myValues.view (myCurPos, curNumEntries);
1161 
1162  // Modify the column indices in place to have the right index base.
1163  for (size_type k = 0; k < curNumEntries; ++k) {
1164  curColInd[k] += indexBase;
1165  }
1166  if (curNumEntries > 0) {
1167  A->insertGlobalValues (myRows[i], curColInd, curValues);
1168  }
1169  }
1170  // We've entered in all our matrix entries, so we can delete
1171  // the original data. This will save memory when we call
1172  // fillComplete(), so that we never keep more than two copies
1173  // of the matrix's data in memory at once.
1174  myNumEntriesPerRow = null;
1175  myRowPtr = null;
1176  myColInd = null;
1177  myValues = null;
1178 
1179  A->fillComplete (pDomainMap, pRangeMap, fillCompleteParams);
1180  return A;
1181  }
1182 
1187  static sparse_matrix_ptr
1188  makeMatrix (Teuchos::ArrayRCP<size_t>& myNumEntriesPerRow,
1189  Teuchos::ArrayRCP<size_t>& myRowPtr,
1192  const Teuchos::RCP<const map_type>& rowMap,
1194  const Teuchos::RCP<const map_type>& domainMap,
1195  const Teuchos::RCP<const map_type>& rangeMap,
1196  const bool callFillComplete = true)
1197  {
1198  using Teuchos::ArrayView;
1199  using Teuchos::as;
1200  using Teuchos::null;
1201  using Teuchos::RCP;
1202  using Teuchos::rcp;
1203  typedef global_ordinal_type GO;
1204  typedef typename ArrayView<const GO>::size_type size_type;
1205 
1206  // Construct the CrsMatrix.
1207  //
1208  // Create with DynamicProfile, so that the fillComplete() can
1209  // do first-touch reallocation.
1210  RCP<sparse_matrix_type> A; // the matrix to return.
1211  if (colMap.is_null ()) { // the user didn't provide a column Map
1212  A = rcp (new sparse_matrix_type (rowMap, myNumEntriesPerRow, DynamicProfile));
1213  } else { // the user provided a column Map
1214  A = rcp (new sparse_matrix_type (rowMap, colMap, myNumEntriesPerRow, DynamicProfile));
1215  }
1216 
1217  // List of the global indices of my rows.
1218  // They may or may not be contiguous.
1219  ArrayView<const GO> myRows = rowMap->getNodeElementList ();
1220  const size_type myNumRows = myRows.size ();
1221 
1222  // Add this process' matrix entries to the CrsMatrix.
1223  const GO indexBase = rowMap->getIndexBase ();
1224  for (size_type i = 0; i < myNumRows; ++i) {
1225  const size_type myCurPos = myRowPtr[i];
1226  const size_type curNumEntries = as<size_type> (myNumEntriesPerRow[i]);
1227  ArrayView<GO> curColInd = myColInd.view (myCurPos, curNumEntries);
1228  ArrayView<scalar_type> curValues = myValues.view (myCurPos, curNumEntries);
1229 
1230  // Modify the column indices in place to have the right index base.
1231  for (size_type k = 0; k < curNumEntries; ++k) {
1232  curColInd[k] += indexBase;
1233  }
1234  if (curNumEntries > 0) {
1235  A->insertGlobalValues (myRows[i], curColInd, curValues);
1236  }
1237  }
1238  // We've entered in all our matrix entries, so we can delete
1239  // the original data. This will save memory when we call
1240  // fillComplete(), so that we never keep more than two copies
1241  // of the matrix's data in memory at once.
1242  myNumEntriesPerRow = null;
1243  myRowPtr = null;
1244  myColInd = null;
1245  myValues = null;
1246 
1247  if (callFillComplete) {
1248  A->fillComplete (domainMap, rangeMap);
1249  if (colMap.is_null ()) {
1250  colMap = A->getColMap ();
1251  }
1252  }
1253  return A;
1254  }
1255 
1256  private:
1257 
1275  readBanner (std::istream& in,
1276  size_t& lineNumber,
1277  const bool tolerant=false,
1278  const bool debug=false)
1279  {
1281  using std::cerr;
1282  using std::endl;
1284 
1285  RCP<Banner> pBanner; // On output, if successful: the read-in Banner.
1286  std::string line; // If read from stream successful: the Banner line
1287 
1288  // Try to read a line from the input stream.
1289  const bool readFailed = ! getline(in, line);
1290  TEUCHOS_TEST_FOR_EXCEPTION(readFailed, std::invalid_argument,
1291  "Failed to get Matrix Market banner line from input.");
1292 
1293  // We read a line from the input stream.
1294  lineNumber++;
1295 
1296  // Assume that the line we found is the Banner line.
1297  try {
1298  pBanner = rcp (new Banner (line, tolerant));
1299  } catch (std::exception& e) {
1300  TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument,
1301  "Matrix Market banner line contains syntax error(s): "
1302  << e.what());
1303  }
1304  TEUCHOS_TEST_FOR_EXCEPTION(pBanner->objectType() != "matrix",
1305  std::invalid_argument, "The Matrix Market file does not contain "
1306  "matrix data. Its Banner (first) line says that its object type is \""
1307  << pBanner->matrixType() << "\", rather than the required \"matrix\".");
1308 
1309  // Validate the data type of the matrix, with respect to the
1310  // Scalar type of the CrsMatrix entries.
1312  ! STS::isComplex && pBanner->dataType() == "complex",
1313  std::invalid_argument,
1314  "The Matrix Market file contains complex-valued data, but you are "
1315  "trying to read it into a matrix containing entries of the real-"
1316  "valued Scalar type \""
1319  pBanner->dataType() != "real" &&
1320  pBanner->dataType() != "complex" &&
1321  pBanner->dataType() != "integer",
1322  std::invalid_argument,
1323  "When reading Matrix Market data into a Tpetra::CrsMatrix, the "
1324  "Matrix Market file may not contain a \"pattern\" matrix. A "
1325  "pattern matrix is really just a graph with no weights. It "
1326  "should be stored in a CrsGraph, not a CrsMatrix.");
1327 
1328  return pBanner;
1329  }
1330 
1354  readCoordDims (std::istream& in,
1355  size_t& lineNumber,
1357  const comm_ptr& pComm,
1358  const bool tolerant = false,
1359  const bool debug = false)
1360  {
1361  using Teuchos::MatrixMarket::readCoordinateDimensions;
1362 
1363  // Packed coordinate matrix dimensions (numRows, numCols,
1364  // numNonzeros); computed on Rank 0 and broadcasted to all MPI
1365  // ranks.
1367 
1368  // Read in the coordinate matrix dimensions from the input
1369  // stream. "success" tells us whether reading in the
1370  // coordinate matrix dimensions succeeded ("Guilty unless
1371  // proven innocent").
1372  bool success = false;
1373  if (pComm->getRank() == 0) {
1374  TEUCHOS_TEST_FOR_EXCEPTION(pBanner->matrixType() != "coordinate",
1375  std::invalid_argument, "The Tpetra::CrsMatrix Matrix Market reader "
1376  "only accepts \"coordinate\" (sparse) matrix data.");
1377  // Unpacked coordinate matrix dimensions
1378  global_ordinal_type numRows, numCols, numNonzeros;
1379  // Only MPI Rank 0 reads from the input stream
1380  success = readCoordinateDimensions (in, numRows, numCols,
1381  numNonzeros, lineNumber,
1382  tolerant);
1383  // Pack up the data into a Tuple so we can send them with
1384  // one broadcast instead of three.
1385  dims[0] = numRows;
1386  dims[1] = numCols;
1387  dims[2] = numNonzeros;
1388  }
1389  // Only Rank 0 did the reading, so it decides success.
1390  //
1391  // FIXME (mfh 02 Feb 2011) Teuchos::broadcast doesn't know how
1392  // to send bools. For now, we convert to/from int instead,
1393  // using the usual "true is 1, false is 0" encoding.
1394  {
1395  int the_success = success ? 1 : 0; // only matters on MPI Rank 0
1396  Teuchos::broadcast (*pComm, 0, &the_success);
1397  success = (the_success == 1);
1398  }
1399  if (success) {
1400  // Broadcast (numRows, numCols, numNonzeros) from Rank 0
1401  // to all the other MPI ranks.
1402  Teuchos::broadcast (*pComm, 0, dims);
1403  }
1404  else {
1405  // Perhaps in tolerant mode, we could set all the
1406  // dimensions to zero for now, and deduce correct
1407  // dimensions by reading all of the file's entries and
1408  // computing the max(row index) and max(column index).
1409  // However, for now we just error out in that case.
1410  TEUCHOS_TEST_FOR_EXCEPTION(true, std::invalid_argument,
1411  "Error reading Matrix Market sparse matrix: failed to read "
1412  "coordinate matrix dimensions.");
1413  }
1414  return dims;
1415  }
1416 
1428 
1454  static RCP<adder_type>
1455  makeAdder (const RCP<const Comm<int> >& pComm,
1457  const Tuple<global_ordinal_type, 3>& dims,
1458  const bool tolerant=false,
1459  const bool debug=false)
1460  {
1461  if (pComm->getRank() == 0) {
1463  RCP<raw_adder_type> pRaw =
1464  rcp (new raw_adder_type (dims[0], dims[1], dims[2], tolerant, debug));
1465  return rcp (new adder_type (pRaw, pBanner->symmType()));
1466  }
1467  else {
1468  return null;
1469  }
1470  }
1471 
1472  public:
1473 
1498  static sparse_matrix_ptr
1499  readSparseFile (const std::string& filename,
1500  const RCP<const Comm<int> >& pComm,
1501  const RCP<node_type>& pNode,
1502  const bool callFillComplete=true,
1503  const bool tolerant=false,
1504  const bool debug=false)
1505  {
1506  const int myRank = Teuchos::rank (*pComm);
1507  std::ifstream in;
1508 
1509  // Only open the file on Rank 0.
1510  if (myRank == 0)
1511  in.open (filename.c_str());
1512  return readSparse (in, pComm, pNode, callFillComplete, tolerant, debug);
1513  // We can rely on the destructor of the input stream to close
1514  // the file on scope exit, even if readSparse() throws an
1515  // exception.
1516  }
1517 
1547  static sparse_matrix_ptr
1548  readSparseFile (const std::string& filename,
1549  const RCP<const Comm<int> >& pComm,
1550  const RCP<node_type>& pNode,
1551  const RCP<Teuchos::ParameterList>& constructorParams,
1552  const RCP<Teuchos::ParameterList>& fillCompleteParams,
1553  const bool tolerant=false,
1554  const bool debug=false)
1555  {
1556  std::ifstream in;
1557  if (pComm->getRank () == 0) { // only open on Process 0
1558  in.open (filename.c_str());
1559  }
1560  return readSparse (in, pComm, pNode, constructorParams,
1561  fillCompleteParams, tolerant, debug);
1562  }
1563 
1601  static sparse_matrix_ptr
1602  readSparseFile (const std::string& filename,
1603  const RCP<const map_type>& rowMap,
1604  RCP<const map_type>& colMap,
1605  const RCP<const map_type>& domainMap,
1606  const RCP<const map_type>& rangeMap,
1607  const bool callFillComplete=true,
1608  const bool tolerant=false,
1609  const bool debug=false)
1610  {
1611  using Teuchos::broadcast;
1612  using Teuchos::outArg;
1614  rowMap.is_null (), std::invalid_argument,
1615  "Row Map must be nonnull.");
1616 
1617  RCP<const Comm<int> > comm = rowMap->getComm ();
1618  RCP<node_type> node = rowMap->getNode ();
1619  const int myRank = comm->getRank ();
1620 
1621  // Only open the file on Process 0. Test carefully to make
1622  // sure that the file opened successfully (and broadcast that
1623  // result to all processes to prevent a hang on exception
1624  // throw), since it's a common mistake to misspell a filename.
1625  std::ifstream in;
1626  int opened = 0;
1627  if (myRank == 0) {
1628  try {
1629  in.open (filename.c_str ());
1630  opened = 1;
1631  }
1632  catch (...) {
1633  opened = 0;
1634  }
1635  }
1636  broadcast<int, int> (*comm, 0, outArg (opened));
1638  opened == 0, std::runtime_error,
1639  "readSparseFile: Failed to open file \"" << filename << "\" on "
1640  "Process 0.");
1641  return readSparse (in, rowMap, colMap, domainMap, rangeMap,
1642  callFillComplete, tolerant, debug);
1643  }
1644 
1671  static sparse_matrix_ptr
1672  readSparse (std::istream& in,
1673  const RCP<const Comm<int> >& pComm,
1674  const RCP<node_type>& pNode,
1675  const bool callFillComplete=true,
1676  const bool tolerant=false,
1677  const bool debug=false)
1678  {
1680  using Teuchos::broadcast;
1681  using Teuchos::ptr;
1682  using Teuchos::reduceAll;
1683  using std::cerr;
1684  using std::endl;
1686 
1687  const bool extraDebug = false;
1688  const int myRank = pComm->getRank ();
1689  const int rootRank = 0;
1690 
1691  // Current line number in the input stream. Various calls
1692  // will modify this depending on the number of lines that are
1693  // read from the input stream. Only Rank 0 modifies this.
1694  size_t lineNumber = 1;
1695 
1696  if (debug && myRank == rootRank) {
1697  cerr << "Matrix Market reader: readSparse:" << endl
1698  << "-- Reading banner line" << endl;
1699  }
1700 
1701  // The "Banner" tells you whether the input stream represents
1702  // a sparse matrix, the symmetry type of the matrix, and the
1703  // type of the data it contains.
1704  //
1705  // pBanner will only be nonnull on MPI Rank 0. It will be
1706  // null on all other MPI processes.
1707  RCP<const Banner> pBanner;
1708  {
1709  // We read and validate the Banner on Proc 0, but broadcast
1710  // the validation result to all processes.
1711  // Teuchos::broadcast doesn't currently work with bool, so
1712  // we use int (true -> 1, false -> 0).
1713  int bannerIsCorrect = 1;
1714  std::ostringstream errMsg;
1715 
1716  if (myRank == rootRank) {
1717  // Read the Banner line from the input stream.
1718  try {
1719  pBanner = readBanner (in, lineNumber, tolerant, debug);
1720  }
1721  catch (std::exception& e) {
1722  errMsg << "Attempt to read the Matrix Market file's Banner line "
1723  "threw an exception: " << e.what();
1724  bannerIsCorrect = 0;
1725  }
1726 
1727  if (bannerIsCorrect) {
1728  // Validate the Banner for the case of a sparse matrix.
1729  // We validate on Proc 0, since it reads the Banner.
1730 
1731  // In intolerant mode, the matrix type must be "coordinate".
1732  if (! tolerant && pBanner->matrixType() != "coordinate") {
1733  bannerIsCorrect = 0;
1734  errMsg << "The Matrix Market input file must contain a "
1735  "\"coordinate\"-format sparse matrix in order to create a "
1736  "Tpetra::CrsMatrix object from it, but the file's matrix "
1737  "type is \"" << pBanner->matrixType() << "\" instead.";
1738  }
1739  // In tolerant mode, we allow the matrix type to be
1740  // anything other than "array" (which would mean that
1741  // the file contains a dense matrix).
1742  if (tolerant && pBanner->matrixType() == "array") {
1743  bannerIsCorrect = 0;
1744  errMsg << "Matrix Market file must contain a \"coordinate\"-"
1745  "format sparse matrix in order to create a Tpetra::CrsMatrix "
1746  "object from it, but the file's matrix type is \"array\" "
1747  "instead. That probably means the file contains dense matrix "
1748  "data.";
1749  }
1750  }
1751  } // Proc 0: Done reading the Banner, hopefully successfully.
1752 
1753  // Broadcast from Proc 0 whether the Banner was read correctly.
1754  broadcast (*pComm, rootRank, ptr (&bannerIsCorrect));
1755 
1756  // If the Banner is invalid, all processes throw an
1757  // exception. Only Proc 0 gets the exception message, but
1758  // that's OK, since the main point is to "stop the world"
1759  // (rather than throw an exception on one process and leave
1760  // the others hanging).
1761  TEUCHOS_TEST_FOR_EXCEPTION(bannerIsCorrect == 0,
1762  std::invalid_argument, errMsg.str ());
1763  } // Done reading the Banner line and broadcasting success.
1764  if (debug && myRank == rootRank) {
1765  cerr << "-- Reading dimensions line" << endl;
1766  }
1767 
1768  // Read the matrix dimensions from the Matrix Market metadata.
1769  // dims = (numRows, numCols, numEntries). Proc 0 does the
1770  // reading, but it broadcasts the results to all MPI
1771  // processes. Thus, readCoordDims() is a collective
1772  // operation. It does a collective check for correctness too.
1774  readCoordDims (in, lineNumber, pBanner, pComm, tolerant, debug);
1775 
1776  if (debug && myRank == rootRank) {
1777  cerr << "-- Making Adder for collecting matrix data" << endl;
1778  }
1779 
1780  // "Adder" object for collecting all the sparse matrix entries
1781  // from the input stream. This is only nonnull on Proc 0.
1782  RCP<adder_type> pAdder =
1783  makeAdder (pComm, pBanner, dims, tolerant, debug);
1784 
1785  if (debug && myRank == rootRank) {
1786  cerr << "-- Reading matrix data" << endl;
1787  }
1788  //
1789  // Read the matrix entries from the input stream on Proc 0.
1790  //
1791  {
1792  // We use readSuccess to broadcast the results of the read
1793  // (succeeded or not) to all MPI processes. Since
1794  // Teuchos::broadcast doesn't currently know how to send
1795  // bools, we convert to int (true -> 1, false -> 0).
1796  int readSuccess = 1;
1797  std::ostringstream errMsg; // Exception message (only valid on Proc 0)
1798  if (myRank == rootRank) {
1799  try {
1800  // Reader for "coordinate" format sparse matrix data.
1801  typedef Teuchos::MatrixMarket::CoordDataReader<adder_type,
1802  global_ordinal_type, scalar_type, STS::isComplex> reader_type;
1803  reader_type reader (pAdder);
1804 
1805  // Read the sparse matrix entries.
1806  std::pair<bool, std::vector<size_t> > results =
1807  reader.read (in, lineNumber, tolerant, debug);
1808  readSuccess = results.first ? 1 : 0;
1809  }
1810  catch (std::exception& e) {
1811  readSuccess = 0;
1812  errMsg << e.what();
1813  }
1814  }
1815  broadcast (*pComm, rootRank, ptr (&readSuccess));
1816 
1817  // It would be nice to add a "verbose" flag, so that in
1818  // tolerant mode, we could log any bad line number(s) on
1819  // Proc 0. For now, we just throw if the read fails to
1820  // succeed.
1821  //
1822  // Question: If we're in tolerant mode, and if the read did
1823  // not succeed, should we attempt to call fillComplete()?
1824  TEUCHOS_TEST_FOR_EXCEPTION(readSuccess == 0, std::runtime_error,
1825  "Failed to read the Matrix Market sparse matrix file: "
1826  << errMsg.str());
1827  } // Done reading the matrix entries (stored on Proc 0 for now)
1828 
1829  if (debug && myRank == rootRank) {
1830  cerr << "-- Successfully read the Matrix Market data" << endl;
1831  }
1832 
1833  // In tolerant mode, we need to rebroadcast the matrix
1834  // dimensions, since they may be different after reading the
1835  // actual matrix data. We only need to broadcast the number
1836  // of rows and columns. Only Rank 0 needs to know the actual
1837  // global number of entries, since (a) we need to merge
1838  // duplicates on Rank 0 first anyway, and (b) when we
1839  // distribute the entries, each rank other than Rank 0 will
1840  // only need to know how many entries it owns, not the total
1841  // number of entries.
1842  if (tolerant) {
1843  if (debug && myRank == rootRank) {
1844  cerr << "-- Tolerant mode: rebroadcasting matrix dimensions"
1845  << endl
1846  << "----- Dimensions before: "
1847  << dims[0] << " x " << dims[1]
1848  << endl;
1849  }
1850  // Packed coordinate matrix dimensions (numRows, numCols).
1851  Tuple<global_ordinal_type, 2> updatedDims;
1852  if (myRank == rootRank) {
1853  // If one or more bottom rows of the matrix contain no
1854  // entries, then the Adder will report that the number
1855  // of rows is less than that specified in the
1856  // metadata. We allow this case, and favor the
1857  // metadata so that the zero row(s) will be included.
1858  updatedDims[0] =
1859  std::max (dims[0], pAdder->getAdder()->numRows());
1860  updatedDims[1] = pAdder->getAdder()->numCols();
1861  }
1862  broadcast (*pComm, rootRank, updatedDims);
1863  dims[0] = updatedDims[0];
1864  dims[1] = updatedDims[1];
1865  if (debug && myRank == rootRank) {
1866  cerr << "----- Dimensions after: " << dims[0] << " x "
1867  << dims[1] << endl;
1868  }
1869  }
1870  else {
1871  // In strict mode, we require that the matrix's metadata and
1872  // its actual data agree, at least somewhat. In particular,
1873  // the number of rows must agree, since otherwise we cannot
1874  // distribute the matrix correctly.
1875 
1876  // Teuchos::broadcast() doesn't know how to broadcast bools,
1877  // so we use an int with the standard 1 == true, 0 == false
1878  // encoding.
1879  int dimsMatch = 1;
1880  if (myRank == rootRank) {
1881  // If one or more bottom rows of the matrix contain no
1882  // entries, then the Adder will report that the number of
1883  // rows is less than that specified in the metadata. We
1884  // allow this case, and favor the metadata, but do not
1885  // allow the Adder to think there are more rows in the
1886  // matrix than the metadata says.
1887  if (dims[0] < pAdder->getAdder ()->numRows ()) {
1888  dimsMatch = 0;
1889  }
1890  }
1891  broadcast (*pComm, 0, ptr (&dimsMatch));
1892  if (dimsMatch == 0) {
1893  // We're in an error state anyway, so we might as well
1894  // work a little harder to print an informative error
1895  // message.
1896  //
1897  // Broadcast the Adder's idea of the matrix dimensions
1898  // from Proc 0 to all processes.
1899  Tuple<global_ordinal_type, 2> addersDims;
1900  if (myRank == rootRank) {
1901  addersDims[0] = pAdder->getAdder()->numRows();
1902  addersDims[1] = pAdder->getAdder()->numCols();
1903  }
1904  broadcast (*pComm, 0, addersDims);
1906  dimsMatch == 0, std::runtime_error,
1907  "The matrix metadata says that the matrix is " << dims[0] << " x "
1908  << dims[1] << ", but the actual data says that the matrix is "
1909  << addersDims[0] << " x " << addersDims[1] << ". That means the "
1910  "data includes more rows than reported in the metadata. This "
1911  "is not allowed when parsing in strict mode. Parse the matrix in "
1912  "tolerant mode to ignore the metadata when it disagrees with the "
1913  "data.");
1914  }
1915  } // Matrix dimensions (# rows, # cols, # entries) agree.
1916 
1917  if (debug && myRank == rootRank) {
1918  cerr << "-- Converting matrix data into CSR format on Proc 0" << endl;
1919  }
1920 
1921  // Now that we've read in all the matrix entries from the
1922  // input stream into the adder on Proc 0, post-process them
1923  // into CSR format (still on Proc 0). This will facilitate
1924  // distributing them to all the processors.
1925  //
1926  // These arrays represent the global matrix data as a CSR
1927  // matrix (with numEntriesPerRow as redundant but convenient
1928  // metadata, since it's computable from rowPtr and vice
1929  // versa). They are valid only on Proc 0.
1930  ArrayRCP<size_t> numEntriesPerRow;
1931  ArrayRCP<size_t> rowPtr;
1933  ArrayRCP<scalar_type> values;
1934 
1935  // Proc 0 first merges duplicate entries, and then converts
1936  // the coordinate-format matrix data to CSR.
1937  {
1938  int mergeAndConvertSucceeded = 1;
1939  std::ostringstream errMsg;
1940 
1941  if (myRank == rootRank) {
1942  try {
1944  global_ordinal_type> element_type;
1945 
1946  // Number of rows in the matrix. If we are in tolerant
1947  // mode, we've already synchronized dims with the actual
1948  // matrix data. If in strict mode, we should use dims
1949  // (as read from the file's metadata) rather than the
1950  // matrix data to determine the dimensions. (The matrix
1951  // data will claim fewer rows than the metadata, if one
1952  // or more rows have no entries stored in the file.)
1953  const size_type numRows = dims[0];
1954 
1955  // Additively merge duplicate matrix entries.
1956  pAdder->getAdder()->merge ();
1957 
1958  // Get a temporary const view of the merged matrix entries.
1959  const std::vector<element_type>& entries =
1960  pAdder->getAdder()->getEntries();
1961 
1962  // Number of matrix entries (after merging).
1963  const size_t numEntries = (size_t)entries.size();
1964 
1965  if (debug) {
1966  cerr << "----- Proc 0: Matrix has numRows=" << numRows
1967  << " rows and numEntries=" << numEntries
1968  << " entries." << endl;
1969  }
1970 
1971  // Make space for the CSR matrix data. Converting to
1972  // CSR is easier if we fill numEntriesPerRow with zeros
1973  // at first.
1974  numEntriesPerRow = arcp<size_t> (numRows);
1975  std::fill (numEntriesPerRow.begin(), numEntriesPerRow.end(), 0);
1976  rowPtr = arcp<size_t> (numRows+1);
1977  std::fill (rowPtr.begin(), rowPtr.end(), 0);
1978  colInd = arcp<global_ordinal_type> (numEntries);
1979  values = arcp<scalar_type> (numEntries);
1980 
1981  // Convert from array-of-structs coordinate format to CSR
1982  // (compressed sparse row) format.
1983  global_ordinal_type prvRow = 0;
1984  size_t curPos = 0;
1985  rowPtr[0] = 0;
1986  for (curPos = 0; curPos < numEntries; ++curPos) {
1987  const element_type& curEntry = entries[curPos];
1988  const global_ordinal_type curRow = curEntry.rowIndex();
1990  curRow < prvRow, std::logic_error,
1991  "Row indices are out of order, even though they are supposed "
1992  "to be sorted. curRow = " << curRow << ", prvRow = "
1993  << prvRow << ", at curPos = " << curPos << ". Please report "
1994  "this bug to the Tpetra developers.");
1995  if (curRow > prvRow) {
1996  for (global_ordinal_type r = prvRow+1; r <= curRow; ++r) {
1997  rowPtr[r] = curPos;
1998  }
1999  prvRow = curRow;
2000  }
2001  numEntriesPerRow[curRow]++;
2002  colInd[curPos] = curEntry.colIndex();
2003  values[curPos] = curEntry.value();
2004  }
2005  // rowPtr has one more entry than numEntriesPerRow. The
2006  // last entry of rowPtr is the number of entries in
2007  // colInd and values.
2008  rowPtr[numRows] = numEntries;
2009  } // Finished conversion to CSR format
2010  catch (std::exception& e) {
2011  mergeAndConvertSucceeded = 0;
2012  errMsg << "Failed to merge sparse matrix entries and convert to "
2013  "CSR format: " << e.what();
2014  }
2015 
2016  if (debug && mergeAndConvertSucceeded) {
2017  // Number of rows in the matrix.
2018  const size_type numRows = dims[0];
2019  const size_type maxToDisplay = 100;
2020 
2021  cerr << "----- Proc 0: numEntriesPerRow[0.."
2022  << (numEntriesPerRow.size()-1) << "] ";
2023  if (numRows > maxToDisplay) {
2024  cerr << "(only showing first and last few entries) ";
2025  }
2026  cerr << "= [";
2027  if (numRows > 0) {
2028  if (numRows > maxToDisplay) {
2029  for (size_type k = 0; k < 2; ++k) {
2030  cerr << numEntriesPerRow[k] << " ";
2031  }
2032  cerr << "... ";
2033  for (size_type k = numRows-2; k < numRows-1; ++k) {
2034  cerr << numEntriesPerRow[k] << " ";
2035  }
2036  }
2037  else {
2038  for (size_type k = 0; k < numRows-1; ++k) {
2039  cerr << numEntriesPerRow[k] << " ";
2040  }
2041  }
2042  cerr << numEntriesPerRow[numRows-1];
2043  } // numRows > 0
2044  cerr << "]" << endl;
2045 
2046  cerr << "----- Proc 0: rowPtr ";
2047  if (numRows > maxToDisplay) {
2048  cerr << "(only showing first and last few entries) ";
2049  }
2050  cerr << "= [";
2051  if (numRows > maxToDisplay) {
2052  for (size_type k = 0; k < 2; ++k) {
2053  cerr << rowPtr[k] << " ";
2054  }
2055  cerr << "... ";
2056  for (size_type k = numRows-2; k < numRows; ++k) {
2057  cerr << rowPtr[k] << " ";
2058  }
2059  }
2060  else {
2061  for (size_type k = 0; k < numRows; ++k) {
2062  cerr << rowPtr[k] << " ";
2063  }
2064  }
2065  cerr << rowPtr[numRows] << "]" << endl;
2066  }
2067  } // if myRank == rootRank
2068  } // Done converting sparse matrix data to CSR format
2069 
2070  // Now we're done with the Adder, so we can release the
2071  // reference ("free" it) to save space. This only actually
2072  // does anything on Rank 0, since pAdder is null on all the
2073  // other MPI processes.
2074  pAdder = null;
2075 
2076  if (debug && myRank == rootRank) {
2077  cerr << "-- Making range, domain, and row maps" << endl;
2078  }
2079 
2080  // Make the maps that describe the matrix's range and domain,
2081  // and the distribution of its rows. Creating a Map is a
2082  // collective operation, so we don't have to do a broadcast of
2083  // a success Boolean.
2084  map_ptr pRangeMap = makeRangeMap (pComm, pNode, dims[0]);
2085  map_ptr pDomainMap = makeDomainMap (pRangeMap, dims[0], dims[1]);
2086  map_ptr pRowMap = makeRowMap (null, pComm, pNode, dims[0]);
2087 
2088  if (debug && myRank == rootRank) {
2089  cerr << "-- Distributing the matrix data" << endl;
2090  }
2091 
2092  // Distribute the matrix data. Each processor has to add the
2093  // rows that it owns. If you try to make Proc 0 call
2094  // insertGlobalValues() for _all_ the rows, not just those it
2095  // owns, then fillComplete() will compute the number of
2096  // columns incorrectly. That's why Proc 0 has to distribute
2097  // the matrix data and why we make all the processors (not
2098  // just Proc 0) call insertGlobalValues() on their own data.
2099  //
2100  // These arrays represent each processor's part of the matrix
2101  // data, in "CSR" format (sort of, since the row indices might
2102  // not be contiguous).
2103  ArrayRCP<size_t> myNumEntriesPerRow;
2104  ArrayRCP<size_t> myRowPtr;
2106  ArrayRCP<scalar_type> myValues;
2107  // Distribute the matrix data. This is a collective operation.
2108  distribute (myNumEntriesPerRow, myRowPtr, myColInd, myValues, pRowMap,
2109  numEntriesPerRow, rowPtr, colInd, values, debug);
2110 
2111  if (debug && myRank == rootRank) {
2112  cerr << "-- Inserting matrix entries on each processor";
2113  if (callFillComplete) {
2114  cerr << " and calling fillComplete()";
2115  }
2116  cerr << endl;
2117  }
2118  // Each processor inserts its part of the matrix data, and
2119  // then they all call fillComplete(). This method invalidates
2120  // the my* distributed matrix data before calling
2121  // fillComplete(), in order to save space. In general, we
2122  // never store more than two copies of the matrix's entries in
2123  // memory at once, which is no worse than what Tpetra
2124  // promises.
2125  sparse_matrix_ptr pMatrix =
2126  makeMatrix (myNumEntriesPerRow, myRowPtr, myColInd, myValues,
2127  pRowMap, pRangeMap, pDomainMap, callFillComplete);
2128  // Only use a reduce-all in debug mode to check if pMatrix is
2129  // null. Otherwise, just throw an exception. We never expect
2130  // a null pointer here, so we can save a communication.
2131  if (debug) {
2132  int localIsNull = pMatrix.is_null () ? 1 : 0;
2133  int globalIsNull = 0;
2134  reduceAll (*pComm, Teuchos::REDUCE_MAX, localIsNull, ptr (&globalIsNull));
2135  TEUCHOS_TEST_FOR_EXCEPTION(globalIsNull != 0, std::logic_error,
2136  "Reader::makeMatrix() returned a null pointer on at least one "
2137  "process. Please report this bug to the Tpetra developers.");
2138  }
2139  else {
2140  TEUCHOS_TEST_FOR_EXCEPTION(pMatrix.is_null(), std::logic_error,
2141  "Reader::makeMatrix() returned a null pointer. "
2142  "Please report this bug to the Tpetra developers.");
2143  }
2144 
2145  // We can't get the dimensions of the matrix until after
2146  // fillComplete() is called. Thus, we can't do the sanity
2147  // check (dimensions read from the Matrix Market data,
2148  // vs. dimensions reported by the CrsMatrix) unless the user
2149  // asked makeMatrix() to call fillComplete().
2150  //
2151  // Note that pMatrix->getGlobalNum{Rows,Cols}() does _not_ do
2152  // what one might think it does, so you have to ask the range
2153  // resp. domain map for the number of rows resp. columns.
2154  if (callFillComplete) {
2155  const int numProcs = pComm->getSize ();
2156 
2157  if (extraDebug && debug) {
2158  const global_size_t globalNumRows =
2159  pRangeMap->getGlobalNumElements();
2160  const global_size_t globalNumCols =
2161  pDomainMap->getGlobalNumElements();
2162  if (myRank == rootRank) {
2163  cerr << "-- Matrix is "
2164  << globalNumRows << " x " << globalNumCols
2165  << " with " << pMatrix->getGlobalNumEntries()
2166  << " entries, and index base "
2167  << pMatrix->getIndexBase() << "." << endl;
2168  }
2169  pComm->barrier ();
2170  for (int p = 0; p < numProcs; ++p) {
2171  if (myRank == p) {
2172  cerr << "-- Proc " << p << " owns "
2173  << pMatrix->getNodeNumCols() << " columns, and "
2174  << pMatrix->getNodeNumEntries() << " entries." << endl;
2175  }
2176  pComm->barrier ();
2177  }
2178  } // if (extraDebug && debug)
2179  } // if (callFillComplete)
2180 
2181  if (debug && myRank == rootRank) {
2182  cerr << "-- Done creating the CrsMatrix from the Matrix Market data"
2183  << endl;
2184  }
2185  return pMatrix;
2186  }
2187 
2188 
2218  static sparse_matrix_ptr
2219  readSparse (std::istream& in,
2220  const RCP<const Comm<int> >& pComm,
2221  const RCP<node_type>& pNode,
2222  const RCP<Teuchos::ParameterList>& constructorParams,
2223  const RCP<Teuchos::ParameterList>& fillCompleteParams,
2224  const bool tolerant=false,
2225  const bool debug=false)
2226  {
2228  using Teuchos::broadcast;
2229  using Teuchos::ptr;
2230  using Teuchos::reduceAll;
2231  using std::cerr;
2232  using std::endl;
2234 
2235  const bool extraDebug = false;
2236  const int myRank = pComm->getRank ();
2237  const int rootRank = 0;
2238 
2239  // Current line number in the input stream. Various calls
2240  // will modify this depending on the number of lines that are
2241  // read from the input stream. Only Rank 0 modifies this.
2242  size_t lineNumber = 1;
2243 
2244  if (debug && myRank == rootRank) {
2245  cerr << "Matrix Market reader: readSparse:" << endl
2246  << "-- Reading banner line" << endl;
2247  }
2248 
2249  // The "Banner" tells you whether the input stream represents
2250  // a sparse matrix, the symmetry type of the matrix, and the
2251  // type of the data it contains.
2252  //
2253  // pBanner will only be nonnull on MPI Rank 0. It will be
2254  // null on all other MPI processes.
2255  RCP<const Banner> pBanner;
2256  {
2257  // We read and validate the Banner on Proc 0, but broadcast
2258  // the validation result to all processes.
2259  // Teuchos::broadcast doesn't currently work with bool, so
2260  // we use int (true -> 1, false -> 0).
2261  int bannerIsCorrect = 1;
2262  std::ostringstream errMsg;
2263 
2264  if (myRank == rootRank) {
2265  // Read the Banner line from the input stream.
2266  try {
2267  pBanner = readBanner (in, lineNumber, tolerant, debug);
2268  }
2269  catch (std::exception& e) {
2270  errMsg << "Attempt to read the Matrix Market file's Banner line "
2271  "threw an exception: " << e.what();
2272  bannerIsCorrect = 0;
2273  }
2274 
2275  if (bannerIsCorrect) {
2276  // Validate the Banner for the case of a sparse matrix.
2277  // We validate on Proc 0, since it reads the Banner.
2278 
2279  // In intolerant mode, the matrix type must be "coordinate".
2280  if (! tolerant && pBanner->matrixType() != "coordinate") {
2281  bannerIsCorrect = 0;
2282  errMsg << "The Matrix Market input file must contain a "
2283  "\"coordinate\"-format sparse matrix in order to create a "
2284  "Tpetra::CrsMatrix object from it, but the file's matrix "
2285  "type is \"" << pBanner->matrixType() << "\" instead.";
2286  }
2287  // In tolerant mode, we allow the matrix type to be
2288  // anything other than "array" (which would mean that
2289  // the file contains a dense matrix).
2290  if (tolerant && pBanner->matrixType() == "array") {
2291  bannerIsCorrect = 0;
2292  errMsg << "Matrix Market file must contain a \"coordinate\"-"
2293  "format sparse matrix in order to create a Tpetra::CrsMatrix "
2294  "object from it, but the file's matrix type is \"array\" "
2295  "instead. That probably means the file contains dense matrix "
2296  "data.";
2297  }
2298  }
2299  } // Proc 0: Done reading the Banner, hopefully successfully.
2300 
2301  // Broadcast from Proc 0 whether the Banner was read correctly.
2302  broadcast (*pComm, rootRank, ptr (&bannerIsCorrect));
2303 
2304  // If the Banner is invalid, all processes throw an
2305  // exception. Only Proc 0 gets the exception message, but
2306  // that's OK, since the main point is to "stop the world"
2307  // (rather than throw an exception on one process and leave
2308  // the others hanging).
2309  TEUCHOS_TEST_FOR_EXCEPTION(bannerIsCorrect == 0,
2310  std::invalid_argument, errMsg.str ());
2311  } // Done reading the Banner line and broadcasting success.
2312  if (debug && myRank == rootRank) {
2313  cerr << "-- Reading dimensions line" << endl;
2314  }
2315 
2316  // Read the matrix dimensions from the Matrix Market metadata.
2317  // dims = (numRows, numCols, numEntries). Proc 0 does the
2318  // reading, but it broadcasts the results to all MPI
2319  // processes. Thus, readCoordDims() is a collective
2320  // operation. It does a collective check for correctness too.
2322  readCoordDims (in, lineNumber, pBanner, pComm, tolerant, debug);
2323 
2324  if (debug && myRank == rootRank) {
2325  cerr << "-- Making Adder for collecting matrix data" << endl;
2326  }
2327 
2328  // "Adder" object for collecting all the sparse matrix entries
2329  // from the input stream. This is only nonnull on Proc 0.
2330  RCP<adder_type> pAdder =
2331  makeAdder (pComm, pBanner, dims, tolerant, debug);
2332 
2333  if (debug && myRank == rootRank) {
2334  cerr << "-- Reading matrix data" << endl;
2335  }
2336  //
2337  // Read the matrix entries from the input stream on Proc 0.
2338  //
2339  {
2340  // We use readSuccess to broadcast the results of the read
2341  // (succeeded or not) to all MPI processes. Since
2342  // Teuchos::broadcast doesn't currently know how to send
2343  // bools, we convert to int (true -> 1, false -> 0).
2344  int readSuccess = 1;
2345  std::ostringstream errMsg; // Exception message (only valid on Proc 0)
2346  if (myRank == rootRank) {
2347  try {
2348  // Reader for "coordinate" format sparse matrix data.
2349  typedef Teuchos::MatrixMarket::CoordDataReader<adder_type,
2350  global_ordinal_type, scalar_type, STS::isComplex> reader_type;
2351  reader_type reader (pAdder);
2352 
2353  // Read the sparse matrix entries.
2354  std::pair<bool, std::vector<size_t> > results =
2355  reader.read (in, lineNumber, tolerant, debug);
2356  readSuccess = results.first ? 1 : 0;
2357  }
2358  catch (std::exception& e) {
2359  readSuccess = 0;
2360  errMsg << e.what();
2361  }
2362  }
2363  broadcast (*pComm, rootRank, ptr (&readSuccess));
2364 
2365  // It would be nice to add a "verbose" flag, so that in
2366  // tolerant mode, we could log any bad line number(s) on
2367  // Proc 0. For now, we just throw if the read fails to
2368  // succeed.
2369  //
2370  // Question: If we're in tolerant mode, and if the read did
2371  // not succeed, should we attempt to call fillComplete()?
2372  TEUCHOS_TEST_FOR_EXCEPTION(readSuccess == 0, std::runtime_error,
2373  "Failed to read the Matrix Market sparse matrix file: "
2374  << errMsg.str());
2375  } // Done reading the matrix entries (stored on Proc 0 for now)
2376 
2377  if (debug && myRank == rootRank) {
2378  cerr << "-- Successfully read the Matrix Market data" << endl;
2379  }
2380 
2381  // In tolerant mode, we need to rebroadcast the matrix
2382  // dimensions, since they may be different after reading the
2383  // actual matrix data. We only need to broadcast the number
2384  // of rows and columns. Only Rank 0 needs to know the actual
2385  // global number of entries, since (a) we need to merge
2386  // duplicates on Rank 0 first anyway, and (b) when we
2387  // distribute the entries, each rank other than Rank 0 will
2388  // only need to know how many entries it owns, not the total
2389  // number of entries.
2390  if (tolerant) {
2391  if (debug && myRank == rootRank) {
2392  cerr << "-- Tolerant mode: rebroadcasting matrix dimensions"
2393  << endl
2394  << "----- Dimensions before: "
2395  << dims[0] << " x " << dims[1]
2396  << endl;
2397  }
2398  // Packed coordinate matrix dimensions (numRows, numCols).
2399  Tuple<global_ordinal_type, 2> updatedDims;
2400  if (myRank == rootRank) {
2401  // If one or more bottom rows of the matrix contain no
2402  // entries, then the Adder will report that the number
2403  // of rows is less than that specified in the
2404  // metadata. We allow this case, and favor the
2405  // metadata so that the zero row(s) will be included.
2406  updatedDims[0] =
2407  std::max (dims[0], pAdder->getAdder()->numRows());
2408  updatedDims[1] = pAdder->getAdder()->numCols();
2409  }
2410  broadcast (*pComm, rootRank, updatedDims);
2411  dims[0] = updatedDims[0];
2412  dims[1] = updatedDims[1];
2413  if (debug && myRank == rootRank) {
2414  cerr << "----- Dimensions after: " << dims[0] << " x "
2415  << dims[1] << endl;
2416  }
2417  }
2418  else {
2419  // In strict mode, we require that the matrix's metadata and
2420  // its actual data agree, at least somewhat. In particular,
2421  // the number of rows must agree, since otherwise we cannot
2422  // distribute the matrix correctly.
2423 
2424  // Teuchos::broadcast() doesn't know how to broadcast bools,
2425  // so we use an int with the standard 1 == true, 0 == false
2426  // encoding.
2427  int dimsMatch = 1;
2428  if (myRank == rootRank) {
2429  // If one or more bottom rows of the matrix contain no
2430  // entries, then the Adder will report that the number of
2431  // rows is less than that specified in the metadata. We
2432  // allow this case, and favor the metadata, but do not
2433  // allow the Adder to think there are more rows in the
2434  // matrix than the metadata says.
2435  if (dims[0] < pAdder->getAdder ()->numRows ()) {
2436  dimsMatch = 0;
2437  }
2438  }
2439  broadcast (*pComm, 0, ptr (&dimsMatch));
2440  if (dimsMatch == 0) {
2441  // We're in an error state anyway, so we might as well
2442  // work a little harder to print an informative error
2443  // message.
2444  //
2445  // Broadcast the Adder's idea of the matrix dimensions
2446  // from Proc 0 to all processes.
2447  Tuple<global_ordinal_type, 2> addersDims;
2448  if (myRank == rootRank) {
2449  addersDims[0] = pAdder->getAdder()->numRows();
2450  addersDims[1] = pAdder->getAdder()->numCols();
2451  }
2452  broadcast (*pComm, 0, addersDims);
2454  dimsMatch == 0, std::runtime_error,
2455  "The matrix metadata says that the matrix is " << dims[0] << " x "
2456  << dims[1] << ", but the actual data says that the matrix is "
2457  << addersDims[0] << " x " << addersDims[1] << ". That means the "
2458  "data includes more rows than reported in the metadata. This "
2459  "is not allowed when parsing in strict mode. Parse the matrix in "
2460  "tolerant mode to ignore the metadata when it disagrees with the "
2461  "data.");
2462  }
2463  } // Matrix dimensions (# rows, # cols, # entries) agree.
2464 
2465  if (debug && myRank == rootRank) {
2466  cerr << "-- Converting matrix data into CSR format on Proc 0" << endl;
2467  }
2468 
2469  // Now that we've read in all the matrix entries from the
2470  // input stream into the adder on Proc 0, post-process them
2471  // into CSR format (still on Proc 0). This will facilitate
2472  // distributing them to all the processors.
2473  //
2474  // These arrays represent the global matrix data as a CSR
2475  // matrix (with numEntriesPerRow as redundant but convenient
2476  // metadata, since it's computable from rowPtr and vice
2477  // versa). They are valid only on Proc 0.
2478  ArrayRCP<size_t> numEntriesPerRow;
2479  ArrayRCP<size_t> rowPtr;
2481  ArrayRCP<scalar_type> values;
2482 
2483  // Proc 0 first merges duplicate entries, and then converts
2484  // the coordinate-format matrix data to CSR.
2485  {
2486  int mergeAndConvertSucceeded = 1;
2487  std::ostringstream errMsg;
2488 
2489  if (myRank == rootRank) {
2490  try {
2492  global_ordinal_type> element_type;
2493 
2494  // Number of rows in the matrix. If we are in tolerant
2495  // mode, we've already synchronized dims with the actual
2496  // matrix data. If in strict mode, we should use dims
2497  // (as read from the file's metadata) rather than the
2498  // matrix data to determine the dimensions. (The matrix
2499  // data will claim fewer rows than the metadata, if one
2500  // or more rows have no entries stored in the file.)
2501  const size_type numRows = dims[0];
2502 
2503  // Additively merge duplicate matrix entries.
2504  pAdder->getAdder()->merge ();
2505 
2506  // Get a temporary const view of the merged matrix entries.
2507  const std::vector<element_type>& entries =
2508  pAdder->getAdder()->getEntries();
2509 
2510  // Number of matrix entries (after merging).
2511  const size_t numEntries = (size_t)entries.size();
2512 
2513  if (debug) {
2514  cerr << "----- Proc 0: Matrix has numRows=" << numRows
2515  << " rows and numEntries=" << numEntries
2516  << " entries." << endl;
2517  }
2518 
2519  // Make space for the CSR matrix data. Converting to
2520  // CSR is easier if we fill numEntriesPerRow with zeros
2521  // at first.
2522  numEntriesPerRow = arcp<size_t> (numRows);
2523  std::fill (numEntriesPerRow.begin(), numEntriesPerRow.end(), 0);
2524  rowPtr = arcp<size_t> (numRows+1);
2525  std::fill (rowPtr.begin(), rowPtr.end(), 0);
2526  colInd = arcp<global_ordinal_type> (numEntries);
2527  values = arcp<scalar_type> (numEntries);
2528 
2529  // Convert from array-of-structs coordinate format to CSR
2530  // (compressed sparse row) format.
2531  global_ordinal_type prvRow = 0;
2532  size_t curPos = 0;
2533  rowPtr[0] = 0;
2534  for (curPos = 0; curPos < numEntries; ++curPos) {
2535  const element_type& curEntry = entries[curPos];
2536  const global_ordinal_type curRow = curEntry.rowIndex();
2538  curRow < prvRow, std::logic_error,
2539  "Row indices are out of order, even though they are supposed "
2540  "to be sorted. curRow = " << curRow << ", prvRow = "
2541  << prvRow << ", at curPos = " << curPos << ". Please report "
2542  "this bug to the Tpetra developers.");
2543  if (curRow > prvRow) {
2544  for (global_ordinal_type r = prvRow+1; r <= curRow; ++r) {
2545  rowPtr[r] = curPos;
2546  }
2547  prvRow = curRow;
2548  }
2549  numEntriesPerRow[curRow]++;
2550  colInd[curPos] = curEntry.colIndex();
2551  values[curPos] = curEntry.value();
2552  }
2553  // rowPtr has one more entry than numEntriesPerRow. The
2554  // last entry of rowPtr is the number of entries in
2555  // colInd and values.
2556  rowPtr[numRows] = numEntries;
2557  } // Finished conversion to CSR format
2558  catch (std::exception& e) {
2559  mergeAndConvertSucceeded = 0;
2560  errMsg << "Failed to merge sparse matrix entries and convert to "
2561  "CSR format: " << e.what();
2562  }
2563 
2564  if (debug && mergeAndConvertSucceeded) {
2565  // Number of rows in the matrix.
2566  const size_type numRows = dims[0];
2567  const size_type maxToDisplay = 100;
2568 
2569  cerr << "----- Proc 0: numEntriesPerRow[0.."
2570  << (numEntriesPerRow.size()-1) << "] ";
2571  if (numRows > maxToDisplay) {
2572  cerr << "(only showing first and last few entries) ";
2573  }
2574  cerr << "= [";
2575  if (numRows > 0) {
2576  if (numRows > maxToDisplay) {
2577  for (size_type k = 0; k < 2; ++k) {
2578  cerr << numEntriesPerRow[k] << " ";
2579  }
2580  cerr << "... ";
2581  for (size_type k = numRows-2; k < numRows-1; ++k) {
2582  cerr << numEntriesPerRow[k] << " ";
2583  }
2584  }
2585  else {
2586  for (size_type k = 0; k < numRows-1; ++k) {
2587  cerr << numEntriesPerRow[k] << " ";
2588  }
2589  }
2590  cerr << numEntriesPerRow[numRows-1];
2591  } // numRows > 0
2592  cerr << "]" << endl;
2593 
2594  cerr << "----- Proc 0: rowPtr ";
2595  if (numRows > maxToDisplay) {
2596  cerr << "(only showing first and last few entries) ";
2597  }
2598  cerr << "= [";
2599  if (numRows > maxToDisplay) {
2600  for (size_type k = 0; k < 2; ++k) {
2601  cerr << rowPtr[k] << " ";
2602  }
2603  cerr << "... ";
2604  for (size_type k = numRows-2; k < numRows; ++k) {
2605  cerr << rowPtr[k] << " ";
2606  }
2607  }
2608  else {
2609  for (size_type k = 0; k < numRows; ++k) {
2610  cerr << rowPtr[k] << " ";
2611  }
2612  }
2613  cerr << rowPtr[numRows] << "]" << endl;
2614  }
2615  } // if myRank == rootRank
2616  } // Done converting sparse matrix data to CSR format
2617 
2618  // Now we're done with the Adder, so we can release the
2619  // reference ("free" it) to save space. This only actually
2620  // does anything on Rank 0, since pAdder is null on all the
2621  // other MPI processes.
2622  pAdder = null;
2623 
2624  if (debug && myRank == rootRank) {
2625  cerr << "-- Making range, domain, and row maps" << endl;
2626  }
2627 
2628  // Make the maps that describe the matrix's range and domain,
2629  // and the distribution of its rows. Creating a Map is a
2630  // collective operation, so we don't have to do a broadcast of
2631  // a success Boolean.
2632  map_ptr pRangeMap = makeRangeMap (pComm, pNode, dims[0]);
2633  map_ptr pDomainMap = makeDomainMap (pRangeMap, dims[0], dims[1]);
2634  map_ptr pRowMap = makeRowMap (null, pComm, pNode, dims[0]);
2635 
2636  if (debug && myRank == rootRank) {
2637  cerr << "-- Distributing the matrix data" << endl;
2638  }
2639 
2640  // Distribute the matrix data. Each processor has to add the
2641  // rows that it owns. If you try to make Proc 0 call
2642  // insertGlobalValues() for _all_ the rows, not just those it
2643  // owns, then fillComplete() will compute the number of
2644  // columns incorrectly. That's why Proc 0 has to distribute
2645  // the matrix data and why we make all the processors (not
2646  // just Proc 0) call insertGlobalValues() on their own data.
2647  //
2648  // These arrays represent each processor's part of the matrix
2649  // data, in "CSR" format (sort of, since the row indices might
2650  // not be contiguous).
2651  ArrayRCP<size_t> myNumEntriesPerRow;
2652  ArrayRCP<size_t> myRowPtr;
2654  ArrayRCP<scalar_type> myValues;
2655  // Distribute the matrix data. This is a collective operation.
2656  distribute (myNumEntriesPerRow, myRowPtr, myColInd, myValues, pRowMap,
2657  numEntriesPerRow, rowPtr, colInd, values, debug);
2658 
2659  if (debug && myRank == rootRank) {
2660  cerr << "-- Inserting matrix entries on each process "
2661  "and calling fillComplete()" << endl;
2662  }
2663  // Each processor inserts its part of the matrix data, and
2664  // then they all call fillComplete(). This method invalidates
2665  // the my* distributed matrix data before calling
2666  // fillComplete(), in order to save space. In general, we
2667  // never store more than two copies of the matrix's entries in
2668  // memory at once, which is no worse than what Tpetra
2669  // promises.
2670  sparse_matrix_ptr pMatrix =
2671  makeMatrix (myNumEntriesPerRow, myRowPtr, myColInd, myValues,
2672  pRowMap, pRangeMap, pDomainMap, constructorParams,
2673  fillCompleteParams);
2674  // Only use a reduce-all in debug mode to check if pMatrix is
2675  // null. Otherwise, just throw an exception. We never expect
2676  // a null pointer here, so we can save a communication.
2677  if (debug) {
2678  int localIsNull = pMatrix.is_null () ? 1 : 0;
2679  int globalIsNull = 0;
2680  reduceAll (*pComm, Teuchos::REDUCE_MAX, localIsNull, ptr (&globalIsNull));
2681  TEUCHOS_TEST_FOR_EXCEPTION(globalIsNull != 0, std::logic_error,
2682  "Reader::makeMatrix() returned a null pointer on at least one "
2683  "process. Please report this bug to the Tpetra developers.");
2684  }
2685  else {
2686  TEUCHOS_TEST_FOR_EXCEPTION(pMatrix.is_null(), std::logic_error,
2687  "Reader::makeMatrix() returned a null pointer. "
2688  "Please report this bug to the Tpetra developers.");
2689  }
2690 
2691  // Sanity check for dimensions (read from the Matrix Market
2692  // data, vs. dimensions reported by the CrsMatrix).
2693  //
2694  // Note that pMatrix->getGlobalNum{Rows,Cols}() does _not_ do
2695  // what one might think it does, so you have to ask the range
2696  // resp. domain map for the number of rows resp. columns.
2697  if (extraDebug && debug) {
2698  const int numProcs = pComm->getSize ();
2699  const global_size_t globalNumRows =
2700  pRangeMap->getGlobalNumElements();
2701  const global_size_t globalNumCols =
2702  pDomainMap->getGlobalNumElements();
2703  if (myRank == rootRank) {
2704  cerr << "-- Matrix is "
2705  << globalNumRows << " x " << globalNumCols
2706  << " with " << pMatrix->getGlobalNumEntries()
2707  << " entries, and index base "
2708  << pMatrix->getIndexBase() << "." << endl;
2709  }
2710  pComm->barrier ();
2711  for (int p = 0; p < numProcs; ++p) {
2712  if (myRank == p) {
2713  cerr << "-- Proc " << p << " owns "
2714  << pMatrix->getNodeNumCols() << " columns, and "
2715  << pMatrix->getNodeNumEntries() << " entries." << endl;
2716  }
2717  pComm->barrier ();
2718  }
2719  } // if (extraDebug && debug)
2720 
2721  if (debug && myRank == rootRank) {
2722  cerr << "-- Done creating the CrsMatrix from the Matrix Market data"
2723  << endl;
2724  }
2725  return pMatrix;
2726  }
2727 
2768  static sparse_matrix_ptr
2769  readSparse (std::istream& in,
2770  const RCP<const map_type>& rowMap,
2771  RCP<const map_type>& colMap,
2772  const RCP<const map_type>& domainMap,
2773  const RCP<const map_type>& rangeMap,
2774  const bool callFillComplete=true,
2775  const bool tolerant=false,
2776  const bool debug=false)
2777  {
2779  using Teuchos::as;
2780  using Teuchos::broadcast;
2781  using Teuchos::ptr;
2782  using Teuchos::reduceAll;
2783  using std::cerr;
2784  using std::endl;
2786 
2787  RCP<const Comm<int> > pComm = rowMap->getComm ();
2788  RCP<node_type> pNode = rowMap->getNode ();
2789  const int myRank = pComm->getRank ();
2790  const int rootRank = 0;
2791  const bool extraDebug = false;
2792 
2793  // Fast checks for invalid input. We can't check other
2794  // attributes of the Maps until we've read in the matrix
2795  // dimensions.
2797  rowMap.is_null (), std::invalid_argument,
2798  "Row Map must be nonnull.");
2800  rangeMap.is_null (), std::invalid_argument,
2801  "Range Map must be nonnull.");
2803  domainMap.is_null (), std::invalid_argument,
2804  "Domain Map must be nonnull.");
2806  rowMap->getComm().getRawPtr() != pComm.getRawPtr(),
2807  std::invalid_argument,
2808  "The specified row Map's communicator (rowMap->getComm())"
2809  "differs from the given separately supplied communicator pComm.");
2811  rowMap->getNode().getRawPtr() != pNode.getRawPtr(),
2812  std::invalid_argument,
2813  "The specified row Map's Kokkos Node instance (rowMap->getNode())"
2814  "differs from the given separately supplied Node instance pNode.");
2816  domainMap->getComm().getRawPtr() != pComm.getRawPtr(),
2817  std::invalid_argument,
2818  "The specified domain Map's communicator (domainMap->getComm())"
2819  "differs from the given separately supplied communicator pComm.");
2821  domainMap->getNode().getRawPtr() != pNode.getRawPtr(),
2822  std::invalid_argument,
2823  "The specified domain Map's Kokkos Node instance (domainMap->getNode())"
2824  "differs from the given separately supplied Node instance pNode.");
2826  rangeMap->getComm().getRawPtr() != pComm.getRawPtr(),
2827  std::invalid_argument,
2828  "The specified range Map's communicator (rangeMap->getComm())"
2829  "differs from the given separately supplied communicator pComm.");
2831  rangeMap->getNode().getRawPtr() != pNode.getRawPtr(),
2832  std::invalid_argument,
2833  "The specified range Map's Kokkos Node instance (rangeMap->getNode())"
2834  "differs from the given separately supplied Node instance pNode.");
2835 
2836  // Current line number in the input stream. Various calls
2837  // will modify this depending on the number of lines that are
2838  // read from the input stream. Only Rank 0 modifies this.
2839  size_t lineNumber = 1;
2840 
2841  if (debug && myRank == rootRank) {
2842  cerr << "Matrix Market reader: readSparse:" << endl
2843  << "-- Reading banner line" << endl;
2844  }
2845 
2846  // The "Banner" tells you whether the input stream represents
2847  // a sparse matrix, the symmetry type of the matrix, and the
2848  // type of the data it contains.
2849  //
2850  // pBanner will only be nonnull on MPI Rank 0. It will be
2851  // null on all other MPI processes.
2852  RCP<const Banner> pBanner;
2853  {
2854  // We read and validate the Banner on Proc 0, but broadcast
2855  // the validation result to all processes.
2856  // Teuchos::broadcast doesn't currently work with bool, so
2857  // we use int (true -> 1, false -> 0).
2858  int bannerIsCorrect = 1;
2859  std::ostringstream errMsg;
2860 
2861  if (myRank == rootRank) {
2862  // Read the Banner line from the input stream.
2863  try {
2864  pBanner = readBanner (in, lineNumber, tolerant, debug);
2865  }
2866  catch (std::exception& e) {
2867  errMsg << "Attempt to read the Matrix Market file's Banner line "
2868  "threw an exception: " << e.what();
2869  bannerIsCorrect = 0;
2870  }
2871 
2872  if (bannerIsCorrect) {
2873  // Validate the Banner for the case of a sparse matrix.
2874  // We validate on Proc 0, since it reads the Banner.
2875 
2876  // In intolerant mode, the matrix type must be "coordinate".
2877  if (! tolerant && pBanner->matrixType() != "coordinate") {
2878  bannerIsCorrect = 0;
2879  errMsg << "The Matrix Market input file must contain a "
2880  "\"coordinate\"-format sparse matrix in order to create a "
2881  "Tpetra::CrsMatrix object from it, but the file's matrix "
2882  "type is \"" << pBanner->matrixType() << "\" instead.";
2883  }
2884  // In tolerant mode, we allow the matrix type to be
2885  // anything other than "array" (which would mean that
2886  // the file contains a dense matrix).
2887  if (tolerant && pBanner->matrixType() == "array") {
2888  bannerIsCorrect = 0;
2889  errMsg << "Matrix Market file must contain a \"coordinate\"-"
2890  "format sparse matrix in order to create a Tpetra::CrsMatrix "
2891  "object from it, but the file's matrix type is \"array\" "
2892  "instead. That probably means the file contains dense matrix "
2893  "data.";
2894  }
2895  }
2896  } // Proc 0: Done reading the Banner, hopefully successfully.
2897 
2898  // Broadcast from Proc 0 whether the Banner was read correctly.
2899  broadcast (*pComm, rootRank, ptr (&bannerIsCorrect));
2900 
2901  // If the Banner is invalid, all processes throw an
2902  // exception. Only Proc 0 gets the exception message, but
2903  // that's OK, since the main point is to "stop the world"
2904  // (rather than throw an exception on one process and leave
2905  // the others hanging).
2906  TEUCHOS_TEST_FOR_EXCEPTION(bannerIsCorrect == 0,
2907  std::invalid_argument, errMsg.str ());
2908  } // Done reading the Banner line and broadcasting success.
2909  if (debug && myRank == rootRank) {
2910  cerr << "-- Reading dimensions line" << endl;
2911  }
2912 
2913  // Read the matrix dimensions from the Matrix Market metadata.
2914  // dims = (numRows, numCols, numEntries). Proc 0 does the
2915  // reading, but it broadcasts the results to all MPI
2916  // processes. Thus, readCoordDims() is a collective
2917  // operation. It does a collective check for correctness too.
2919  readCoordDims (in, lineNumber, pBanner, pComm, tolerant, debug);
2920 
2921  if (debug && myRank == rootRank) {
2922  cerr << "-- Making Adder for collecting matrix data" << endl;
2923  }
2924 
2925  // "Adder" object for collecting all the sparse matrix entries
2926  // from the input stream. This is only nonnull on Proc 0.
2927  // The Adder internally converts the one-based indices (native
2928  // Matrix Market format) into zero-based indices.
2929  RCP<adder_type> pAdder =
2930  makeAdder (pComm, pBanner, dims, tolerant, debug);
2931 
2932  if (debug && myRank == rootRank) {
2933  cerr << "-- Reading matrix data" << endl;
2934  }
2935  //
2936  // Read the matrix entries from the input stream on Proc 0.
2937  //
2938  {
2939  // We use readSuccess to broadcast the results of the read
2940  // (succeeded or not) to all MPI processes. Since
2941  // Teuchos::broadcast doesn't currently know how to send
2942  // bools, we convert to int (true -> 1, false -> 0).
2943  int readSuccess = 1;
2944  std::ostringstream errMsg; // Exception message (only valid on Proc 0)
2945  if (myRank == rootRank) {
2946  try {
2947  // Reader for "coordinate" format sparse matrix data.
2948  typedef Teuchos::MatrixMarket::CoordDataReader<adder_type,
2949  global_ordinal_type, scalar_type, STS::isComplex> reader_type;
2950  reader_type reader (pAdder);
2951 
2952  // Read the sparse matrix entries.
2953  std::pair<bool, std::vector<size_t> > results =
2954  reader.read (in, lineNumber, tolerant, debug);
2955  readSuccess = results.first ? 1 : 0;
2956  }
2957  catch (std::exception& e) {
2958  readSuccess = 0;
2959  errMsg << e.what();
2960  }
2961  }
2962  broadcast (*pComm, rootRank, ptr (&readSuccess));
2963 
2964  // It would be nice to add a "verbose" flag, so that in
2965  // tolerant mode, we could log any bad line number(s) on
2966  // Proc 0. For now, we just throw if the read fails to
2967  // succeed.
2968  //
2969  // Question: If we're in tolerant mode, and if the read did
2970  // not succeed, should we attempt to call fillComplete()?
2971  TEUCHOS_TEST_FOR_EXCEPTION(readSuccess == 0, std::runtime_error,
2972  "Failed to read the Matrix Market sparse matrix file: "
2973  << errMsg.str());
2974  } // Done reading the matrix entries (stored on Proc 0 for now)
2975 
2976  if (debug && myRank == rootRank) {
2977  cerr << "-- Successfully read the Matrix Market data" << endl;
2978  }
2979 
2980  // In tolerant mode, we need to rebroadcast the matrix
2981  // dimensions, since they may be different after reading the
2982  // actual matrix data. We only need to broadcast the number
2983  // of rows and columns. Only Rank 0 needs to know the actual
2984  // global number of entries, since (a) we need to merge
2985  // duplicates on Rank 0 first anyway, and (b) when we
2986  // distribute the entries, each rank other than Rank 0 will
2987  // only need to know how many entries it owns, not the total
2988  // number of entries.
2989  if (tolerant) {
2990  if (debug && myRank == rootRank) {
2991  cerr << "-- Tolerant mode: rebroadcasting matrix dimensions"
2992  << endl
2993  << "----- Dimensions before: "
2994  << dims[0] << " x " << dims[1]
2995  << endl;
2996  }
2997  // Packed coordinate matrix dimensions (numRows, numCols).
2998  Tuple<global_ordinal_type, 2> updatedDims;
2999  if (myRank == rootRank) {
3000  // If one or more bottom rows of the matrix contain no
3001  // entries, then the Adder will report that the number
3002  // of rows is less than that specified in the
3003  // metadata. We allow this case, and favor the
3004  // metadata so that the zero row(s) will be included.
3005  updatedDims[0] =
3006  std::max (dims[0], pAdder->getAdder()->numRows());
3007  updatedDims[1] = pAdder->getAdder()->numCols();
3008  }
3009  broadcast (*pComm, rootRank, updatedDims);
3010  dims[0] = updatedDims[0];
3011  dims[1] = updatedDims[1];
3012  if (debug && myRank == rootRank) {
3013  cerr << "----- Dimensions after: " << dims[0] << " x "
3014  << dims[1] << endl;
3015  }
3016  }
3017  else {
3018  // In strict mode, we require that the matrix's metadata and
3019  // its actual data agree, at least somewhat. In particular,
3020  // the number of rows must agree, since otherwise we cannot
3021  // distribute the matrix correctly.
3022 
3023  // Teuchos::broadcast() doesn't know how to broadcast bools,
3024  // so we use an int with the standard 1 == true, 0 == false
3025  // encoding.
3026  int dimsMatch = 1;
3027  if (myRank == rootRank) {
3028  // If one or more bottom rows of the matrix contain no
3029  // entries, then the Adder will report that the number of
3030  // rows is less than that specified in the metadata. We
3031  // allow this case, and favor the metadata, but do not
3032  // allow the Adder to think there are more rows in the
3033  // matrix than the metadata says.
3034  if (dims[0] < pAdder->getAdder ()->numRows ()) {
3035  dimsMatch = 0;
3036  }
3037  }
3038  broadcast (*pComm, 0, ptr (&dimsMatch));
3039  if (dimsMatch == 0) {
3040  // We're in an error state anyway, so we might as well
3041  // work a little harder to print an informative error
3042  // message.
3043  //
3044  // Broadcast the Adder's idea of the matrix dimensions
3045  // from Proc 0 to all processes.
3046  Tuple<global_ordinal_type, 2> addersDims;
3047  if (myRank == rootRank) {
3048  addersDims[0] = pAdder->getAdder()->numRows();
3049  addersDims[1] = pAdder->getAdder()->numCols();
3050  }
3051  broadcast (*pComm, 0, addersDims);
3053  dimsMatch == 0, std::runtime_error,
3054  "The matrix metadata says that the matrix is " << dims[0] << " x "
3055  << dims[1] << ", but the actual data says that the matrix is "
3056  << addersDims[0] << " x " << addersDims[1] << ". That means the "
3057  "data includes more rows than reported in the metadata. This "
3058  "is not allowed when parsing in strict mode. Parse the matrix in "
3059  "tolerant mode to ignore the metadata when it disagrees with the "
3060  "data.");
3061  }
3062  } // Matrix dimensions (# rows, # cols, # entries) agree.
3063 
3064  if (debug && myRank == rootRank) {
3065  cerr << "-- Converting matrix data into CSR format on Proc 0" << endl;
3066  }
3067 
3068  // Now that we've read in all the matrix entries from the
3069  // input stream into the adder on Proc 0, post-process them
3070  // into CSR format (still on Proc 0). This will facilitate
3071  // distributing them to all the processors.
3072  //
3073  // These arrays represent the global matrix data as a CSR
3074  // matrix (with numEntriesPerRow as redundant but convenient
3075  // metadata, since it's computable from rowPtr and vice
3076  // versa). They are valid only on Proc 0.
3077  ArrayRCP<size_t> numEntriesPerRow;
3078  ArrayRCP<size_t> rowPtr;
3080  ArrayRCP<scalar_type> values;
3081 
3082  // Proc 0 first merges duplicate entries, and then converts
3083  // the coordinate-format matrix data to CSR.
3084  {
3085  int mergeAndConvertSucceeded = 1;
3086  std::ostringstream errMsg;
3087 
3088  if (myRank == rootRank) {
3089  try {
3091  global_ordinal_type> element_type;
3092 
3093  // Number of rows in the matrix. If we are in tolerant
3094  // mode, we've already synchronized dims with the actual
3095  // matrix data. If in strict mode, we should use dims
3096  // (as read from the file's metadata) rather than the
3097  // matrix data to determine the dimensions. (The matrix
3098  // data will claim fewer rows than the metadata, if one
3099  // or more rows have no entries stored in the file.)
3100  const size_type numRows = dims[0];
3101 
3102  // Additively merge duplicate matrix entries.
3103  pAdder->getAdder()->merge ();
3104 
3105  // Get a temporary const view of the merged matrix entries.
3106  const std::vector<element_type>& entries =
3107  pAdder->getAdder()->getEntries();
3108 
3109  // Number of matrix entries (after merging).
3110  const size_t numEntries = (size_t)entries.size();
3111 
3112  if (debug) {
3113  cerr << "----- Proc 0: Matrix has numRows=" << numRows
3114  << " rows and numEntries=" << numEntries
3115  << " entries." << endl;
3116  }
3117 
3118  // Make space for the CSR matrix data. Converting to
3119  // CSR is easier if we fill numEntriesPerRow with zeros
3120  // at first.
3121  numEntriesPerRow = arcp<size_t> (numRows);
3122  std::fill (numEntriesPerRow.begin(), numEntriesPerRow.end(), 0);
3123  rowPtr = arcp<size_t> (numRows+1);
3124  std::fill (rowPtr.begin(), rowPtr.end(), 0);
3125  colInd = arcp<global_ordinal_type> (numEntries);
3126  values = arcp<scalar_type> (numEntries);
3127 
3128  // Convert from array-of-structs coordinate format to CSR
3129  // (compressed sparse row) format.
3130  global_ordinal_type prvRow = 0;
3131  size_t curPos = 0;
3132  rowPtr[0] = 0;
3133  for (curPos = 0; curPos < numEntries; ++curPos) {
3134  const element_type& curEntry = entries[curPos];
3135  const global_ordinal_type curRow = curEntry.rowIndex();
3137  curRow < prvRow, std::logic_error,
3138  "Row indices are out of order, even though they are supposed "
3139  "to be sorted. curRow = " << curRow << ", prvRow = "
3140  << prvRow << ", at curPos = " << curPos << ". Please report "
3141  "this bug to the Tpetra developers.");
3142  if (curRow > prvRow) {
3143  for (global_ordinal_type r = prvRow+1; r <= curRow; ++r) {
3144  rowPtr[r] = curPos;
3145  }
3146  prvRow = curRow;
3147  }
3148  numEntriesPerRow[curRow]++;
3149  colInd[curPos] = curEntry.colIndex();
3150  values[curPos] = curEntry.value();
3151  }
3152  // rowPtr has one more entry than numEntriesPerRow. The
3153  // last entry of rowPtr is the number of entries in
3154  // colInd and values.
3155  rowPtr[numRows] = numEntries;
3156  } // Finished conversion to CSR format
3157  catch (std::exception& e) {
3158  mergeAndConvertSucceeded = 0;
3159  errMsg << "Failed to merge sparse matrix entries and convert to "
3160  "CSR format: " << e.what();
3161  }
3162 
3163  if (debug && mergeAndConvertSucceeded) {
3164  // Number of rows in the matrix.
3165  const size_type numRows = dims[0];
3166  const size_type maxToDisplay = 100;
3167 
3168  cerr << "----- Proc 0: numEntriesPerRow[0.."
3169  << (numEntriesPerRow.size()-1) << "] ";
3170  if (numRows > maxToDisplay) {
3171  cerr << "(only showing first and last few entries) ";
3172  }
3173  cerr << "= [";
3174  if (numRows > 0) {
3175  if (numRows > maxToDisplay) {
3176  for (size_type k = 0; k < 2; ++k) {
3177  cerr << numEntriesPerRow[k] << " ";
3178  }
3179  cerr << "... ";
3180  for (size_type k = numRows-2; k < numRows-1; ++k) {
3181  cerr << numEntriesPerRow[k] << " ";
3182  }
3183  }
3184  else {
3185  for (size_type k = 0; k < numRows-1; ++k) {
3186  cerr << numEntriesPerRow[k] << " ";
3187  }
3188  }
3189  cerr << numEntriesPerRow[numRows-1];
3190  } // numRows > 0
3191  cerr << "]" << endl;
3192 
3193  cerr << "----- Proc 0: rowPtr ";
3194  if (numRows > maxToDisplay) {
3195  cerr << "(only showing first and last few entries) ";
3196  }
3197  cerr << "= [";
3198  if (numRows > maxToDisplay) {
3199  for (size_type k = 0; k < 2; ++k) {
3200  cerr << rowPtr[k] << " ";
3201  }
3202  cerr << "... ";
3203  for (size_type k = numRows-2; k < numRows; ++k) {
3204  cerr << rowPtr[k] << " ";
3205  }
3206  }
3207  else {
3208  for (size_type k = 0; k < numRows; ++k) {
3209  cerr << rowPtr[k] << " ";
3210  }
3211  }
3212  cerr << rowPtr[numRows] << "]" << endl;
3213 
3214  cerr << "----- Proc 0: colInd = [";
3215  for (size_t k = 0; k < rowPtr[numRows]; ++k) {
3216  cerr << colInd[k] << " ";
3217  }
3218  cerr << "]" << endl;
3219  }
3220  } // if myRank == rootRank
3221  } // Done converting sparse matrix data to CSR format
3222 
3223  // Now we're done with the Adder, so we can release the
3224  // reference ("free" it) to save space. This only actually
3225  // does anything on Rank 0, since pAdder is null on all the
3226  // other MPI processes.
3227  pAdder = null;
3228 
3229  // Verify details of the Maps. Don't count the global number
3230  // of entries in the row Map, since that number doesn't
3231  // correctly count overlap.
3232  if (debug && myRank == rootRank) {
3233  cerr << "-- Verifying Maps" << endl;
3234  }
3236  as<global_size_t> (dims[0]) != rangeMap->getGlobalNumElements(),
3237  std::invalid_argument,
3238  "The range Map has " << rangeMap->getGlobalNumElements ()
3239  << " entries, but the matrix has a global number of rows " << dims[0]
3240  << ".");
3242  as<global_size_t> (dims[1]) != domainMap->getGlobalNumElements (),
3243  std::invalid_argument,
3244  "The domain Map has " << domainMap->getGlobalNumElements ()
3245  << " entries, but the matrix has a global number of columns "
3246  << dims[1] << ".");
3247 
3248  // Create a row Map which is entirely owned on Proc 0.
3249  RCP<Teuchos::FancyOStream> err = debug ?
3250  Teuchos::getFancyOStream (Teuchos::rcpFromRef (cerr)) : null;
3251  RCP<const map_type> gatherRowMap = computeGatherMap (rowMap, err, debug);
3252 
3253  // Create a matrix using this Map, and fill in on Proc 0. We
3254  // know how many entries there are in each row, so we can use
3255  // static profile.
3256  RCP<sparse_matrix_type> A_proc0 =
3257  rcp (new sparse_matrix_type (gatherRowMap, numEntriesPerRow,
3259  if (myRank == rootRank) {
3260  if (debug) {
3261  cerr << "-- Proc 0: Filling gather matrix" << endl;
3262  }
3264  gatherRowMap->getNodeElementList ();
3265  if (debug) {
3266  cerr << "---- Rows: " << Teuchos::toString (myRows) << endl;
3267  }
3268  const size_type myNumRows = myRows.size ();
3269 
3270  // Add Proc 0's matrix entries to the CrsMatrix.
3271  const global_ordinal_type indexBase = gatherRowMap->getIndexBase ();
3272  for (size_type i = 0; i < myNumRows; ++i) {
3273  const size_type curPos = as<size_type> (rowPtr[i]);
3274  const local_ordinal_type curNumEntries = numEntriesPerRow[i];
3275  ArrayView<global_ordinal_type> curColInd =
3276  colInd.view (curPos, curNumEntries);
3277  ArrayView<scalar_type> curValues =
3278  values.view (curPos, curNumEntries);
3279 
3280  // Modify the column indices in place to have the right index base.
3281  for (size_type k = 0; k < curNumEntries; ++k) {
3282  curColInd[k] += indexBase;
3283  }
3284  if (debug) {
3285  cerr << "------ Columns: " << Teuchos::toString (curColInd) << endl;
3286  cerr << "------ Values: " << Teuchos::toString (curValues) << endl;
3287  }
3288  // Avoid constructing empty views of ArrayRCP objects.
3289  if (curNumEntries > 0) {
3290  A_proc0->insertGlobalValues (myRows[i], curColInd, curValues);
3291  }
3292  }
3293  // Now we can save space by deallocating numEntriesPerRow,
3294  // rowPtr, colInd, and values, since we've already put those
3295  // data in the matrix.
3296  numEntriesPerRow = null;
3297  rowPtr = null;
3298  colInd = null;
3299  values = null;
3300  } // if myRank == rootRank
3301 
3303  if (colMap.is_null ()) {
3304  A = rcp (new sparse_matrix_type (rowMap, 0));
3305  } else {
3306  A = rcp (new sparse_matrix_type (rowMap, colMap, 0));
3307  }
3309  export_type exp (gatherRowMap, rowMap);
3310  A->doExport (*A_proc0, exp, INSERT);
3311 
3312  if (callFillComplete) {
3313  A->fillComplete (domainMap, rangeMap);
3314  }
3315 
3316  // We can't get the dimensions of the matrix until after
3317  // fillComplete() is called. Thus, we can't do the sanity
3318  // check (dimensions read from the Matrix Market data,
3319  // vs. dimensions reported by the CrsMatrix) unless the user
3320  // asked us to call fillComplete().
3321  //
3322  // Note that pMatrix->getGlobalNum{Rows,Cols}() does _not_ do
3323  // what one might think it does, so you have to ask the range
3324  // resp. domain map for the number of rows resp. columns.
3325  if (callFillComplete) {
3326  const int numProcs = pComm->getSize ();
3327 
3328  if (extraDebug && debug) {
3329  const global_size_t globalNumRows = rangeMap->getGlobalNumElements ();
3330  const global_size_t globalNumCols = domainMap->getGlobalNumElements ();
3331  if (myRank == rootRank) {
3332  cerr << "-- Matrix is "
3333  << globalNumRows << " x " << globalNumCols
3334  << " with " << A->getGlobalNumEntries()
3335  << " entries, and index base "
3336  << A->getIndexBase() << "." << endl;
3337  }
3338  pComm->barrier ();
3339  for (int p = 0; p < numProcs; ++p) {
3340  if (myRank == p) {
3341  cerr << "-- Proc " << p << " owns "
3342  << A->getNodeNumCols() << " columns, and "
3343  << A->getNodeNumEntries() << " entries." << endl;
3344  }
3345  pComm->barrier ();
3346  }
3347  } // if (extraDebug && debug)
3348  } // if (callFillComplete)
3349 
3350  if (debug && myRank == rootRank) {
3351  cerr << "-- Done creating the CrsMatrix from the Matrix Market data"
3352  << endl;
3353  }
3354  return A;
3355  }
3356 
3357 
3387  static RCP<multivector_type>
3388  readDenseFile (const std::string& filename,
3389  const RCP<const comm_type>& comm,
3390  const RCP<node_type>& node,
3391  RCP<const map_type>& map,
3392  const bool tolerant=false,
3393  const bool debug=false)
3394  {
3395  std::ifstream in;
3396  if (comm->getRank () == 0) { // Only open the file on Proc 0.
3397  in.open (filename.c_str ()); // Destructor closes safely
3398  }
3399  return readDense (in, comm, node, map, tolerant, debug);
3400  }
3401 
3469  static RCP<multivector_type>
3470  readDense (std::istream& in,
3471  const RCP<const comm_type>& comm,
3472  const RCP<node_type>& node,
3473  RCP<const map_type>& map,
3474  const bool tolerant=false,
3475  const bool debug=false)
3476  {
3478  Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr));
3479  return readDenseImpl<scalar_type> (in, comm, node, map,
3480  err, tolerant, debug);
3481  }
3482 
3504  static RCP<const map_type>
3505  readMapFile (const std::string& filename,
3506  const RCP<const comm_type>& comm,
3507  const RCP<node_type>& node,
3508  const bool tolerant=false,
3509  const bool debug=false)
3510  {
3511  using Teuchos::inOutArg;
3512  using Teuchos::broadcast;
3513  std::ifstream in;
3514 
3515  int success = 1;
3516  if (comm->getRank () == 0) { // Only open the file on Proc 0.
3517  in.open (filename.c_str ()); // Destructor closes safely
3518  if (! in) {
3519  success = 0;
3520  }
3521  }
3522  broadcast<int, int> (*comm, 0, inOutArg (success));
3524  success == 0, std::runtime_error,
3525  "Tpetra::MatrixMarket::Reader::readMapFile: "
3526  "Failed to read file \"" << filename << "\" on Process 0.");
3527  return readMap (in, comm, node, tolerant, debug);
3528  }
3529 
3530  private:
3531  template<class MultiVectorScalarType>
3532  static RCP<Tpetra::MultiVector<MultiVectorScalarType,
3535  node_type> >
3536  readDenseImpl (std::istream& in,
3537  const RCP<const comm_type>& comm,
3538  const RCP<node_type>& node,
3539  RCP<const map_type>& map,
3541  const bool tolerant=false,
3542  const bool debug=false)
3543  {
3545  using Teuchos::MatrixMarket::checkCommentLine;
3546  using Teuchos::as;
3547  using Teuchos::broadcast;
3548  using Teuchos::outArg;
3549  using std::endl;
3550  typedef MultiVectorScalarType ST;
3551  typedef local_ordinal_type LO;
3552  typedef global_ordinal_type GO;
3553  typedef node_type NT;
3554  typedef Teuchos::ScalarTraits<ST> STS;
3555  typedef typename STS::magnitudeType MT;
3556  typedef Teuchos::ScalarTraits<MT> STM;
3558 
3559  // Rank 0 is the only (MPI) process allowed to read from the
3560  // input stream.
3561  const int myRank = comm->getRank ();
3562 
3563  if (! err.is_null ()) {
3564  err->pushTab ();
3565  }
3566  if (debug) {
3567  *err << myRank << ": readDenseImpl" << endl;
3568  }
3569  if (! err.is_null ()) {
3570  err->pushTab ();
3571  }
3572 
3573  // mfh 17 Feb 2013: It's not strictly necessary that the Comm
3574  // instances be identical and that the Node instances be
3575  // identical. The essential condition is more complicated to
3576  // test and isn't the same for all Node types. Thus, we just
3577  // leave it up to the user.
3578 
3579  // // If map is nonnull, check the precondition that its
3580  // // communicator resp. node equal comm resp. node. Checking
3581  // // now avoids doing a lot of file reading before we detect the
3582  // // violated precondition.
3583  // TEUCHOS_TEST_FOR_EXCEPTION(
3584  // ! map.is_null() && (map->getComm() != comm || map->getNode () != node,
3585  // std::invalid_argument, "If you supply a nonnull Map, the Map's "
3586  // "communicator and node must equal the supplied communicator resp. "
3587  // "node.");
3588 
3589  // Process 0 will read in the matrix dimensions from the file,
3590  // and broadcast them to all ranks in the given communicator.
3591  // There are only 2 dimensions in the matrix, but we use the
3592  // third element of the Tuple to encode the banner's reported
3593  // data type: "real" == 0, "complex" == 1, and "integer" == 0
3594  // (same as "real"). We don't allow pattern matrices (i.e.,
3595  // graphs) since they only make sense for sparse data.
3596  Tuple<GO, 3> dims;
3597  dims[0] = 0;
3598  dims[1] = 0;
3599 
3600  // Current line number in the input stream. Only valid on
3601  // Proc 0. Various calls will modify this depending on the
3602  // number of lines that are read from the input stream.
3603  size_t lineNumber = 1;
3604 
3605  // Capture errors and their messages on Proc 0.
3606  std::ostringstream exMsg;
3607  int localBannerReadSuccess = 1;
3608  int localDimsReadSuccess = 1;
3609 
3610  // Only Proc 0 gets to read matrix data from the input stream.
3611  if (myRank == 0) {
3612  if (debug) {
3613  *err << myRank << ": readDenseImpl: Reading banner line (dense)" << endl;
3614  }
3615 
3616  // The "Banner" tells you whether the input stream
3617  // represents a dense matrix, the symmetry type of the
3618  // matrix, and the type of the data it contains.
3619  RCP<const Banner> pBanner;
3620  try {
3621  pBanner = readBanner (in, lineNumber, tolerant, debug);
3622  } catch (std::exception& e) {
3623  exMsg << e.what ();
3624  localBannerReadSuccess = 0;
3625  }
3626  // Make sure the input stream is the right kind of data.
3627  if (localBannerReadSuccess) {
3628  if (pBanner->matrixType () != "array") {
3629  exMsg << "The Matrix Market file does not contain dense matrix "
3630  "data. Its banner (first) line says that its matrix type is \""
3631  << pBanner->matrixType () << "\", rather that the required "
3632  "\"array\".";
3633  localBannerReadSuccess = 0;
3634  } else if (pBanner->dataType() == "pattern") {
3635  exMsg << "The Matrix Market file's banner (first) "
3636  "line claims that the matrix's data type is \"pattern\". This does "
3637  "not make sense for a dense matrix, yet the file reports the matrix "
3638  "as dense. The only valid data types for a dense matrix are "
3639  "\"real\", \"complex\", and \"integer\".";
3640  localBannerReadSuccess = 0;
3641  } else {
3642  // Encode the data type reported by the Banner as the
3643  // third element of the dimensions Tuple.
3644  dims[2] = encodeDataType (pBanner->dataType ());
3645  }
3646  } // if we successfully read the banner line
3647 
3648  // At this point, we've successfully read the banner line.
3649  // Now read the dimensions line.
3650  if (localBannerReadSuccess) {
3651  if (debug) {
3652  *err << myRank << ": readDenseImpl: Reading dimensions line (dense)" << endl;
3653  }
3654  // Keep reading lines from the input stream until we find
3655  // a non-comment line, or until we run out of lines. The
3656  // latter is an error, since every "array" format Matrix
3657  // Market file must have a dimensions line after the
3658  // banner (even if the matrix has zero rows or columns, or
3659  // zero entries).
3660  std::string line;
3661  bool commentLine = true;
3662 
3663  while (commentLine) {
3664  // Test whether it is even valid to read from the input
3665  // stream wrapping the line.
3666  if (in.eof () || in.fail ()) {
3667  exMsg << "Unable to get array dimensions line (at all) from line "
3668  << lineNumber << " of input stream. The input stream "
3669  << "claims that it is "
3670  << (in.eof() ? "at end-of-file." : "in a failed state.");
3671  localDimsReadSuccess = 0;
3672  } else {
3673  // Try to get the next line from the input stream.
3674  if (getline (in, line)) {
3675  ++lineNumber; // We did actually read a line.
3676  }
3677  // Is the current line a comment line? Ignore start
3678  // and size; they are only useful for reading the
3679  // actual matrix entries. (We could use them here as
3680  // an optimization, but we've chosen not to.)
3681  size_t start = 0, size = 0;
3682  commentLine = checkCommentLine (line, start, size, lineNumber, tolerant);
3683  } // whether we failed to read the line at all
3684  } // while the line we just read is a comment line
3685 
3686  //
3687  // Get <numRows> <numCols> from the line we just read.
3688  //
3689  std::istringstream istr (line);
3690 
3691  // Test whether it is even valid to read from the input
3692  // stream wrapping the line.
3693  if (istr.eof () || istr.fail ()) {
3694  exMsg << "Unable to read any data from line " << lineNumber
3695  << " of input; the line should contain the matrix dimensions "
3696  << "\"<numRows> <numCols>\".";
3697  localDimsReadSuccess = 0;
3698  } else { // It's valid to read from the line.
3699  GO theNumRows = 0;
3700  istr >> theNumRows; // Read in the number of rows.
3701  if (istr.fail ()) {
3702  exMsg << "Failed to get number of rows from line "
3703  << lineNumber << " of input; the line should contains the "
3704  << "matrix dimensions \"<numRows> <numCols>\".";
3705  localDimsReadSuccess = 0;
3706  } else { // We successfully read the number of rows
3707  dims[0] = theNumRows; // Save the number of rows
3708  if (istr.eof ()) { // Do we still have data to read?
3709  exMsg << "No more data after number of rows on line "
3710  << lineNumber << " of input; the line should contain the "
3711  << "matrix dimensions \"<numRows> <numCols>\".";
3712  localDimsReadSuccess = 0;
3713  } else { // Still data left to read; read in number of columns.
3714  GO theNumCols = 0;
3715  istr >> theNumCols; // Read in the number of columns
3716  if (istr.fail ()) {
3717  exMsg << "Failed to get number of columns from line "
3718  << lineNumber << " of input; the line should contain "
3719  << "the matrix dimensions \"<numRows> <numCols>\".";
3720  localDimsReadSuccess = 0;
3721  } else { // We successfully read the number of columns
3722  dims[1] = theNumCols; // Save the number of columns
3723  } // if istr.fail ()
3724  } // if istr.eof ()
3725  } // if we read the number of rows
3726  } // if the input stream wrapping the dims line was (in)valid
3727  } // if we successfully read the banner line
3728  } // if (myRank == 0)
3729 
3730  // Broadcast the matrix dimensions, the encoded data type, and
3731  // whether or not Proc 0 succeeded in reading the banner and
3732  // dimensions.
3733  Tuple<GO, 5> bannerDimsReadResult;
3734  if (myRank == 0) {
3735  bannerDimsReadResult[0] = dims[0]; // numRows
3736  bannerDimsReadResult[1] = dims[1]; // numCols
3737  bannerDimsReadResult[2] = dims[2]; // encoded data type
3738  bannerDimsReadResult[3] = localBannerReadSuccess;
3739  bannerDimsReadResult[4] = localDimsReadSuccess;
3740  }
3741  // Broadcast matrix dimensions and the encoded data type from
3742  // Proc 0 to all the MPI processes.
3743  broadcast (*comm, 0, bannerDimsReadResult);
3744 
3746  bannerDimsReadResult[3] == 0, std::runtime_error,
3747  "Failed to read banner line: " << exMsg.str ());
3749  bannerDimsReadResult[4] == 0, std::runtime_error,
3750  "Failed to read matrix dimensions line: " << exMsg.str ());
3751  if (myRank != 0) {
3752  dims[0] = bannerDimsReadResult[0];
3753  dims[1] = bannerDimsReadResult[1];
3754  dims[2] = bannerDimsReadResult[2];
3755  }
3756 
3757  // Tpetra objects want the matrix dimensions in these types.
3758  const global_size_t numRows = static_cast<global_size_t> (dims[0]);
3759  const size_t numCols = static_cast<size_t> (dims[1]);
3760 
3761  // Make a "Proc 0 owns everything" Map that we will use to
3762  // read in the multivector entries in the correct order on
3763  // Proc 0. This must be a collective
3764  RCP<const map_type> proc0Map; // "Proc 0 owns everything" Map
3765  if (map.is_null ()) {
3766  // The user didn't supply a Map. Make a contiguous
3767  // distributed Map for them, using the read-in multivector
3768  // dimensions.
3769  map = createUniformContigMapWithNode<LO, GO, NT> (numRows, comm, node);
3770  const size_t localNumRows = (myRank == 0) ? numRows : 0;
3771  proc0Map = createContigMapWithNode<LO, GO, NT> (numRows, localNumRows, comm, node);
3772  }
3773  else { // The user supplied a Map.
3774  proc0Map = computeGatherMap<map_type> (map, err, debug);
3775  }
3776 
3777  // Make a multivector X owned entirely by Proc 0.
3778  RCP<MV> X = createMultiVector<ST, LO, GO, NT> (proc0Map, numCols);
3779 
3780  //
3781  // On Proc 0, read the Matrix Market data from the input
3782  // stream into the multivector X.
3783  //
3784  int localReadDataSuccess = 1;
3785  if (myRank == 0) {
3786  try {
3787  if (debug) {
3788  *err << myRank << ": readDenseImpl: Reading matrix data (dense)"
3789  << endl;
3790  }
3791 
3792  // Make sure that we can get a 1-D view of X.
3794  ! X->isConstantStride (), std::logic_error,
3795  "Can't get a 1-D view of the entries of the MultiVector X on "
3796  "Process 0, because the stride between the columns of X is not "
3797  "constant. This shouldn't happen because we just created X and "
3798  "haven't filled it in yet. Please report this bug to the Tpetra "
3799  "developers.");
3800 
3801  // Get a writeable 1-D view of the entries of X. Rank 0
3802  // owns all of them. The view will expire at the end of
3803  // scope, so (if necessary) it will be written back to X
3804  // at this time.
3805  ArrayRCP<ST> X_view = X->get1dViewNonConst ();
3807  as<global_size_t> (X_view.size ()) < numRows * numCols,
3808  std::logic_error,
3809  "The view of X has size " << X_view << " which is not enough to "
3810  "accommodate the expected number of entries numRows*numCols = "
3811  << numRows << "*" << numCols << " = " << numRows*numCols << ". "
3812  "Please report this bug to the Tpetra developers.");
3813  const size_t stride = X->getStride ();
3814 
3815  // The third element of the dimensions Tuple encodes the data
3816  // type reported by the Banner: "real" == 0, "complex" == 1,
3817  // "integer" == 0 (same as "real"), "pattern" == 2. We do not
3818  // allow dense matrices to be pattern matrices, so dims[2] ==
3819  // 0 or 1. We've already checked for this above.
3820  const bool isComplex = (dims[2] == 1);
3821  size_type count = 0, curRow = 0, curCol = 0;
3822 
3823  std::string line;
3824  while (getline (in, line)) {
3825  ++lineNumber;
3826  // Is the current line a comment line? If it's not,
3827  // line.substr(start,size) contains the data.
3828  size_t start = 0, size = 0;
3829  const bool commentLine =
3830  checkCommentLine (line, start, size, lineNumber, tolerant);
3831  if (! commentLine) {
3832  // Make sure we have room in which to put the new matrix
3833  // entry. We check this only after checking for a
3834  // comment line, because there may be one or more
3835  // comment lines at the end of the file. In tolerant
3836  // mode, we simply ignore any extra data.
3837  if (count >= X_view.size()) {
3838  if (tolerant) {
3839  break;
3840  }
3841  else {
3843  count >= X_view.size(),
3844  std::runtime_error,
3845  "The Matrix Market input stream has more data in it than "
3846  "its metadata reported. Current line number is "
3847  << lineNumber << ".");
3848  }
3849  }
3850 
3851  // mfh 19 Dec 2012: Ignore everything up to the initial
3852  // colon. writeDense() has the option to print out the
3853  // global row index in front of each entry, followed by
3854  // a colon and space.
3855  {
3856  const size_t pos = line.substr (start, size).find (':');
3857  if (pos != std::string::npos) {
3858  start = pos+1;
3859  }
3860  }
3861  std::istringstream istr (line.substr (start, size));
3862  // Does the line contain anything at all? Can we
3863  // safely read from the input stream wrapping the
3864  // line?
3865  if (istr.eof() || istr.fail()) {
3866  // In tolerant mode, simply ignore the line.
3867  if (tolerant) {
3868  break;
3869  }
3870  // We repeat the full test here so the exception
3871  // message is more informative.
3873  ! tolerant && (istr.eof() || istr.fail()),
3874  std::runtime_error,
3875  "Line " << lineNumber << " of the Matrix Market file is "
3876  "empty, or we cannot read from it for some other reason.");
3877  }
3878  // Current matrix entry to read in.
3879  ST val = STS::zero();
3880  // Real and imaginary parts of the current matrix entry.
3881  // The imaginary part is zero if the matrix is real-valued.
3882  MT real = STM::zero(), imag = STM::zero();
3883 
3884  // isComplex refers to the input stream's data, not to
3885  // the scalar type S. It's OK to read real-valued
3886  // data into a matrix storing complex-valued data; in
3887  // that case, all entries' imaginary parts are zero.
3888  if (isComplex) {
3889  // STS::real() and STS::imag() return a copy of
3890  // their respective components, not a writeable
3891  // reference. Otherwise we could just assign to
3892  // them using the istream extraction operator (>>).
3893  // That's why we have separate magnitude type "real"
3894  // and "imag" variables.
3895 
3896  // Attempt to read the real part of the current entry.
3897  istr >> real;
3898  if (istr.fail()) {
3900  ! tolerant && istr.eof(), std::runtime_error,
3901  "Failed to get the real part of a complex-valued matrix "
3902  "entry from line " << lineNumber << " of the Matrix Market "
3903  "file.");
3904  // In tolerant mode, just skip bad lines.
3905  if (tolerant) {
3906  break;
3907  }
3908  } else if (istr.eof()) {
3910  ! tolerant && istr.eof(), std::runtime_error,
3911  "Missing imaginary part of a complex-valued matrix entry "
3912  "on line " << lineNumber << " of the Matrix Market file.");
3913  // In tolerant mode, let any missing imaginary part be 0.
3914  } else {
3915  // Attempt to read the imaginary part of the current
3916  // matrix entry.
3917  istr >> imag;
3919  ! tolerant && istr.fail(), std::runtime_error,
3920  "Failed to get the imaginary part of a complex-valued "
3921  "matrix entry from line " << lineNumber << " of the "
3922  "Matrix Market file.");
3923  // In tolerant mode, let any missing or corrupted
3924  // imaginary part be 0.
3925  }
3926  } else { // Matrix Market file contains real-valued data.
3927  // Attempt to read the current matrix entry.
3928  istr >> real;
3930  ! tolerant && istr.fail(), std::runtime_error,
3931  "Failed to get a real-valued matrix entry from line "
3932  << lineNumber << " of the Matrix Market file.");
3933  // In tolerant mode, simply ignore the line if
3934  // we failed to read a matrix entry.
3935  if (istr.fail() && tolerant) {
3936  break;
3937  }
3938  }
3939  // In tolerant mode, we simply let pass through whatever
3940  // data we got.
3942  ! tolerant && istr.fail(), std::runtime_error,
3943  "Failed to read matrix data from line " << lineNumber
3944  << " of the Matrix Market file.");
3945 
3946  // Assign val = ST(real, imag).
3947  Teuchos::MatrixMarket::details::assignScalar<ST> (val, real, imag);
3948 
3949  curRow = count % numRows;
3950  curCol = count / numRows;
3951  X_view[curRow + curCol*stride] = val;
3952  ++count;
3953  } // if not a comment line
3954  } // while there are still lines in the file, get the next one
3955 
3957  ! tolerant && static_cast<global_size_t> (count) < numRows * numCols,
3958  std::runtime_error,
3959  "The Matrix Market metadata reports that the dense matrix is "
3960  << numRows << " x " << numCols << ", and thus has "
3961  << numRows*numCols << " total entries, but we only found " << count
3962  << " entr" << (count == 1 ? "y" : "ies") << " in the file.");
3963  } catch (std::exception& e) {
3964  exMsg << e.what ();
3965  localReadDataSuccess = 0;
3966  }
3967  } // if (myRank == 0)
3968 
3969  if (debug) {
3970  *err << myRank << ": readDenseImpl: done reading data" << endl;
3971  }
3972 
3973  // Synchronize on whether Proc 0 successfully read the data.
3974  int globalReadDataSuccess = localReadDataSuccess;
3975  broadcast (*comm, 0, outArg (globalReadDataSuccess));
3977  globalReadDataSuccess == 0, std::runtime_error,
3978  "Failed to read the multivector's data: " << exMsg.str ());
3979 
3980  // If there's only one MPI process and the user didn't supply
3981  // a Map (i.e., pMap is null), we're done. Set pMap to the
3982  // Map used to distribute X, and return X.
3983  if (comm->getSize () == 1 && map.is_null ()) {
3984  map = proc0Map;
3985  if (! err.is_null ()) {
3986  err->popTab ();
3987  }
3988  if (debug) {
3989  *err << myRank << ": readDenseImpl: done" << endl;
3990  }
3991  if (! err.is_null ()) {
3992  err->popTab ();
3993  }
3994  return X;
3995  }
3996 
3997  if (debug) {
3998  *err << myRank << ": readDenseImpl: Creating target MV" << endl;
3999  }
4000 
4001  // Make a multivector Y with the distributed map pMap.
4002  RCP<MV> Y = createMultiVector<ST, LO, GO, NT> (map, numCols);
4003 
4004  if (debug) {
4005  *err << myRank << ": readDenseImpl: Creating Export" << endl;
4006  }
4007 
4008  // Make an Export object that will export X to Y. First
4009  // argument is the source map, second argument is the target
4010  // map.
4011  Export<LO, GO, NT> exporter (proc0Map, map, err);
4012 
4013  if (debug) {
4014  *err << myRank << ": readDenseImpl: Exporting" << endl;
4015  }
4016  // Export X into Y.
4017  Y->doExport (*X, exporter, INSERT);
4018 
4019  if (! err.is_null ()) {
4020  err->popTab ();
4021  }
4022  if (debug) {
4023  *err << myRank << ": readDenseImpl: done" << endl;
4024  }
4025  if (! err.is_null ()) {
4026  err->popTab ();
4027  }
4028 
4029  // Y is distributed over all process(es) in the communicator.
4030  return Y;
4031  }
4032 
4033  public:
4054  static RCP<const map_type>
4055  readMap (std::istream& in,
4056  const RCP<const comm_type>& comm,
4057  const RCP<node_type>& node,
4058  const bool tolerant=false,
4059  const bool debug=false)
4060  {
4062  Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr));
4063  return readMap (in, comm, node, err, tolerant, debug);
4064  }
4065 
4091  static RCP<const map_type>
4092  readMap (std::istream& in,
4093  const RCP<const comm_type>& comm,
4094  const RCP<node_type>& node,
4096  const bool tolerant=false,
4097  const bool debug=false)
4098  {
4099  using Tpetra::global_size_t;
4100  using Teuchos::Array;
4101  using Teuchos::ArrayRCP;
4102  using Teuchos::as;
4103  using Teuchos::broadcast;
4104  using Teuchos::Comm;
4105  using Teuchos::CommRequest;
4106  using Teuchos::inOutArg;
4107  using Teuchos::outArg;
4108  using Teuchos::reduceAll;
4109  using Teuchos::REDUCE_MIN;
4110  using Teuchos::SerialComm;
4111  using Teuchos::toString;
4112  using std::endl;
4113  typedef ptrdiff_t int_type; // Can hold int and GO
4114  typedef local_ordinal_type LO;
4115  typedef global_ordinal_type GO;
4116  typedef node_type NT;
4118 
4119  const int numProcs = comm->getSize ();
4120  const int myRank = comm->getRank ();
4121 
4122  if (err.is_null ()) {
4123  err->pushTab ();
4124  }
4125  if (debug) {
4126  *err << myRank << ": readMap: " << endl;
4127  }
4128  if (err.is_null ()) {
4129  err->pushTab ();
4130  }
4131 
4132  int readSuccess = 1;
4133  std::ostringstream exMsg;
4134  RCP<MV> data; // Will only be valid on Proc 0
4135  if (myRank == 0) {
4136  // If we want to reuse readDenseImpl, we have to make a
4137  // communicator that only contains Proc 0. Otherwise,
4138  // readDenseImpl will redistribute the data to all
4139  // processes. While we eventually want that, neither we nor
4140  // readDenseImpl know the correct Map to use at the moment.
4141  // That depends on the second column of the multivector.
4142  RCP<const Comm<int> > proc0Comm (new SerialComm<int> ());
4143  try {
4144  RCP<const map_type> dataMap;
4145  // This is currently the only place where we use
4146  // 'tolerant' and 'debug'. Later, if we want to be
4147  // clever, we could have tolerant mode allow PIDs out of
4148  // order.
4149  data = readDenseImpl<int_type> (in, proc0Comm, node, dataMap,
4150  err, tolerant, debug);
4151  (void) dataMap; // Silence "unused" warnings
4152  } catch (std::exception& e) {
4153  readSuccess = 0;
4154  exMsg << e.what ();
4155  }
4156  }
4157  broadcast<int, int> (*comm, 0, inOutArg (readSuccess));
4159  readSuccess == 0, std::runtime_error,
4160  "Tpetra::MatrixMarket::readMap: "
4161  "Reading the Map failed with the following exception message: "
4162  << exMsg.str ());
4163 
4164  if (debug) {
4165  *err << myRank << ": readMap: Successfully read data" << endl;
4166  }
4167 
4168  ArrayRCP<const GO> myGids;
4169  GO indexBase = 0; // must be global min GID
4170 
4171  ArrayRCP<size_type> gidsPerProcess;
4172  ArrayRCP<const int_type> GIDs, PIDs;
4173  ArrayRCP<size_type> startIndices;
4174  if (myRank == 0) {
4175  try {
4176  // Assume that the Map's data are ordered by PID (2nd column).
4177  GIDs = data->getData (0);
4178  PIDs = data->getData (1);
4180  GIDs.size () != PIDs.size (), std::logic_error,
4181  "GIDs.size() = " << GIDs.size() << " != PIDs.size() = "
4182  << PIDs.size() << ". This should never happen. "
4183  "Please report this bug to the Tpetra developers.");
4184  // Count of data in each process.
4185  const size_type globalNumGIDs = GIDs.size ();
4186  gidsPerProcess = arcp<size_type> (numProcs);
4187  std::fill (gidsPerProcess.begin (), gidsPerProcess.end (), 0);
4188 
4189  // Error conditions. If any are nonzero, there was an
4190  // error. We use int, not bool, because bool doesn't have
4191  // an MPI_Datatype.
4192  int numNegPids = 0;
4193  int numTooBigPids = 0;
4194  int pidsOutOfOrder = 0;
4195  Array<size_type> badRows;
4196  startIndices = arcp<size_type> (numProcs+1);
4197  std::fill (startIndices.begin (), startIndices.end (), 0);
4198  //startIndices[0] = 0;
4199  int lastPid = 0;
4200  for (size_type k = 0; k < globalNumGIDs; ++k) {
4201  const GO gid = as<GO> (GIDs[k]);
4202  const int pid = as<int> (PIDs[k]);
4203  if (debug) {
4204  std::ostringstream os;
4205  os << "0: readMap: "
4206  << "{k: " << k
4207  << ", gid: " << gid
4208  << ", pid: " << pid
4209  << ", lastPid: " << lastPid << "}" << endl;
4210  *err << os.str ();
4211  }
4212  if (pid < 0) {
4213  ++numNegPids;
4214  badRows.push_back (k);
4215  }
4216  else if (pid >= numProcs) {
4217  ++numTooBigPids;
4218  badRows.push_back (k);
4219  }
4220  else if (pid < lastPid) {
4221  // Did the PID occur out of order?
4222  // We allow PIDs to have zero GIDs.
4223  ++pidsOutOfOrder;
4224  badRows.push_back (k);
4225  }
4226  else { // We know now that pid is valid.
4227  ++gidsPerProcess[pid];
4228  if (k == 0 || GIDs[k] < indexBase) {
4229  indexBase = GIDs[k]; // indexBase must be the global min GID
4230  }
4231  // It could be that Proc 0 owns no GIDs. In that case,
4232  // PID[0] will be > 0 and the code below will fill in
4233  // startIndices[p] = 0 for p = 1, 2, ..., PIDs[0].
4234  if (pid > lastPid) {
4235  // startIndices is analogous to the 'ptr' array in CSR.
4236  // Fill in offsets for processes with no GIDs.
4237  for (int p = lastPid+1; p <= pid; ++p) {
4238  startIndices[p] = k;
4239  }
4240  }
4241  lastPid = PIDs[k];
4242  }
4243  } // for each GID
4244  startIndices[numProcs] = globalNumGIDs;
4245 
4246  readSuccess =
4247  (numNegPids == 0 && numTooBigPids == 0 && pidsOutOfOrder == 0) ?
4248  1 : 0;
4249  if (debug) {
4250  if (readSuccess) {
4251  *err << "0: readMap: The Map's data are valid" << endl;
4252  } else {
4253  *err << "0: readMap: The Map's data are INVALID" << endl;
4254  }
4255  Teuchos::OSTab tab (err);
4256  std::ostringstream os;
4257  os << "startIndices: " << toString (startIndices) << endl
4258  << "gidsPerProcess: " << toString (gidsPerProcess ()) << endl;
4259  *err << os.str ();
4260  }
4261  if (readSuccess == 0) {
4262  // Construct an informative error message and throw.
4263  exMsg << "We found the following errors in the Map's data:" << endl;
4264  if (numNegPids > 0) {
4265  exMsg << " - There were " << numNegPids << " negative process "
4266  "ranks (PIDs)" << endl;
4267  }
4268  if (numTooBigPids > 0) {
4269  exMsg << " - There were " << numTooBigPids << " PIDs that "
4270  << "were out of the valid range [0, " << (numProcs-1)
4271  << "]. This probably means that the communicator with "
4272  << "which you saved the Map had a different number of "
4273  << "processes than the communicator with which you are "
4274  << "reading in the Map." << endl;
4275  }
4276  if (pidsOutOfOrder > 0) {
4277  exMsg << " - There were " << pidsOutOfOrder << " PIDs that "
4278  "occurred out of order. We require that PIDs occur in "
4279  "consecutive increasing order in the file or input stream."
4280  << endl;
4281  }
4282  exMsg << "List of bad lines in the file or input stream:" << endl;
4283  if (badRows.size () > 50) {
4284  exMsg << " - (Over 50 bad lines, so not showing all; first is "
4285  << badRows[0] << ")" << endl;
4286  } else {
4287  exMsg << " - " << toString (badRows) << endl;
4288  }
4289  TEUCHOS_TEST_FOR_EXCEPTION(true, std::runtime_error, exMsg.str ());
4290  }
4291 
4292  // convert GIDs from int_type to GO.
4293  //
4294  // We read in GIDs as int_type, which may differ from GO.
4295  // (For example, on 64-bit Mac or Linux, int_type is long;
4296  // GO might be int or long, or even an unsigned integer
4297  // type.) If GO == int_type, we can just make myGids a
4298  // view of the relevant section of GIDs. However, the
4299  // code still has to compile when GO != int_type. Since
4300  // we know that GIDs will be valid until the end of this
4301  // method, we can use a raw pointer in that case to avoid
4302  // the copy.
4303  if (typeid (GO) == typeid (int_type)) {
4304  ArrayRCP<const int_type> myGidsAsIntType =
4305  GIDs.persistingView (startIndices[0], gidsPerProcess[0]);
4306  const int_type* myGidsRaw = myGidsAsIntType.getRawPtr ();
4307  myGids = arcp<const GO> (reinterpret_cast<const GO*> (myGidsRaw),
4308  0, gidsPerProcess[0], false);
4309  } else {
4310  ArrayRCP<const int_type> myGidsAsIntType =
4311  GIDs.persistingView (startIndices[0], gidsPerProcess[0]);
4312  ArrayRCP<GO> myGidsAsGO (myGidsAsIntType.size ());
4313  for (size_type k = 0; k < myGidsAsIntType.size (); ++k) {
4314  myGidsAsGO[k] = as<GO> (myGidsAsIntType[k]);
4315  }
4316  myGids = myGidsAsGO.getConst ();
4317  }
4318  } catch (std::exception& e) {
4319  readSuccess = 0;
4320  exMsg << e.what ();
4321  }
4322  } // if myRank == 0
4323 
4324  broadcast<int, int> (*comm, 0, inOutArg (readSuccess));
4326  readSuccess == 0, std::runtime_error,
4327  "Tpetra::MatrixMarket::readMap: The Map's data were invalid: "
4328  << exMsg.str ());
4329 
4330  // If we get this far, every process knows that the read-in
4331  // data are valid. That means we can distribute them without
4332  // any more fuss for error conditions.
4333  if (myRank == 0) {
4334  // Distribute the GIDs from Process 0 to the processes to
4335  // which they belong. Also tell the GIDs the index base
4336  // while we're at it, so we don't have to do an all-reduce
4337  // to compute it later.
4338  //
4339  // MPI guarantees ordering of messages, so we can use
4340  // nonblocking sends for both (count, indexBase) and the
4341  // content (the GIDs). We don't send the GIDs if that
4342  // process will own zero of them.
4343  //
4344  // We could avoid the broadcast above by using a count of -1
4345  // as a flag that something went wrong while reading.
4346  // However, broadcasts are generally inexpensive compared
4347  // with this data redistribution.
4348  Array<RCP<CommRequest<int> > > countRequests (numProcs-1);
4349  for (int p = 1; p < numProcs; ++p) {
4350  ArrayRCP<size_type> sendBuf (2);
4351  sendBuf[0] = gidsPerProcess[p];
4352  sendBuf[1] = as<size_type> (indexBase);
4353  countRequests[p-1] = isend (*comm, sendBuf.getConst (), p);
4354  }
4355 
4356  Array<RCP<CommRequest<int> > > dataRequests;
4357  ArrayRCP<GO> gidsToSend;
4358  for (int p = 1; p < numProcs; ++p) {
4359  if (gidsPerProcess[p] > 0) {
4360  gidsToSend.resize (gidsPerProcess[p]);
4361  for (size_type k = 0; k < gidsPerProcess[p]; ++k) {
4362  gidsToSend[k] = as<GO> (GIDs[startIndices[p] + k]);
4363  }
4364  dataRequests.push_back (isend (*comm, gidsToSend.getConst (), p));
4365  }
4366  }
4367 
4368  if (debug) {
4369  *err << "0: readMap: waiting on count sends" << endl;
4370  }
4371  waitAll (*comm, countRequests ());
4372 
4373  if (debug) {
4374  *err << "0: readMap: waiting on GID sends" << endl;
4375  }
4376  waitAll (*comm, dataRequests ());
4377  }
4378  else { // if (myRank != 0)
4379  const int rootRank = 0;
4380  if (debug) {
4381  *err << myRank <<": readMap: receiving GID count" << endl;
4382  }
4383 
4384  // Receive the count of GIDs to receive. If 0, don't do a
4385  // second receive. We use blocking receives here because
4386  // there's nothing we can do in the meantime while waiting.
4387  Tuple<size_type, 2> gidCountAndMinAllGid;
4388  gidCountAndMinAllGid[0] = 0; // gidCount
4389  receive (*comm, rootRank, 2, gidCountAndMinAllGid.getRawPtr ());
4390  indexBase = as<GO> (gidCountAndMinAllGid[1]);
4391  const size_type gidCount = gidCountAndMinAllGid[0];
4392  indexBase = as<GO> (gidCountAndMinAllGid[1]);
4393  if (gidCount > 0) { // there are actual data to receive
4394  if (debug) {
4395  *err << myRank << ": readMap: receiving GID list" << endl;
4396  }
4397  ArrayRCP<GO> myGidsCopy (gidCount);
4398  receive (*comm, rootRank, as<int> (gidCount), myGidsCopy.getRawPtr ());
4399  myGids = myGidsCopy.getConst ();
4400  }
4401  } // if myRank == 0
4402 
4403  if (debug) {
4404  *err << myRank << ": readMap: Done distributing GID list" << endl;
4405  Teuchos::OSTab tab (err);
4406  comm->barrier (); // let output finish
4407  for (int p = 0; p < numProcs; ++p) {
4408  if (myRank == p) {
4409  std::ostringstream os;
4410  os << "Proc " << myRank << ": GIDs: " << toString (myGids ())
4411  << endl;
4412  *err << os.str ();
4413  }
4414  comm->barrier (); // let output finish
4415  comm->barrier ();
4416  comm->barrier ();
4417  }
4418  }
4419 
4420  if (debug) {
4421  *err << myRank << ": readMap: creating Map" << endl;
4422  }
4424  RCP<const map_type> newMap (new map_type (INVALID, myGids (), indexBase, comm, node));
4425 
4426  if (err.is_null ()) {
4427  err->popTab ();
4428  }
4429  if (debug) {
4430  *err << myRank << ": readMap: done" << endl;
4431  }
4432  if (err.is_null ()) {
4433  err->popTab ();
4434  }
4435  return newMap;
4436  }
4437 
4438  private:
4439 
4450  static int
4451  encodeDataType (const std::string& dataType)
4452  {
4453  if (dataType == "real" || dataType == "integer") {
4454  return 0;
4455  } else if (dataType == "complex") {
4456  return 1;
4457  } else if (dataType == "pattern") {
4458  return 2;
4459  } else {
4460  // We should never get here, since Banner validates the
4461  // reported data type and ensures it is one of the accepted
4462  // values.
4463  TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error,
4464  "Unrecognized Matrix Market data type \"" << dataType
4465  << "\". We should never get here. "
4466  "Please report this bug to the Tpetra developers.");
4467  }
4468  }
4469  };
4470 
4510  template<class SparseMatrixType>
4511  class Writer {
4512  public:
4513  typedef SparseMatrixType sparse_matrix_type;
4515 
4518  typedef typename SparseMatrixType::scalar_type scalar_type;
4521  typedef typename SparseMatrixType::local_ordinal_type local_ordinal_type;
4528  typedef typename SparseMatrixType::global_ordinal_type global_ordinal_type;
4531  typedef typename SparseMatrixType::node_type node_type;
4532 
4535  typedef MultiVector<scalar_type,
4538  node_type> multivector_type;
4542 
4574  static void
4575  writeSparseFile (const std::string& filename,
4576  const RCP<const sparse_matrix_type>& pMatrix,
4577  const std::string& matrixName,
4578  const std::string& matrixDescription,
4579  const bool debug=false)
4580  {
4581  const int myRank = Teuchos::rank (*(pMatrix->getComm()));
4582  std::ofstream out;
4583 
4584  // Only open the file on Rank 0.
4585  if (myRank == 0) out.open (filename.c_str());
4586  writeSparse (out, pMatrix, matrixName, matrixDescription, debug);
4587  // We can rely on the destructor of the output stream to close
4588  // the file on scope exit, even if writeSparse() throws an
4589  // exception.
4590  }
4591 
4612  static void
4613  writeSparseFile (const std::string& filename,
4614  const RCP<const sparse_matrix_type>& pMatrix,
4615  const bool debug=false)
4616  {
4617  writeSparseFile (filename, pMatrix, "", "", debug);
4618  }
4619 
4620  public:
4621 
4652  static void
4653  writeSparse (std::ostream& out,
4654  const RCP<const sparse_matrix_type>& pMatrix,
4655  const std::string& matrixName,
4656  const std::string& matrixDescription,
4657  const bool debug=false)
4658  {
4659  using Teuchos::Comm;
4660  using Teuchos::FancyOStream;
4661  using Teuchos::getFancyOStream;
4662  using Teuchos::null;
4663  using Teuchos::RCP;
4664  using Teuchos::rcpFromRef;
4665  using std::cerr;
4666  using std::endl;
4667  typedef scalar_type ST;
4668  typedef local_ordinal_type LO;
4669  typedef global_ordinal_type GO;
4670  typedef typename Teuchos::ScalarTraits<ST> STS;
4671  typedef typename ArrayView<const LO>::const_iterator lo_iter;
4672  typedef typename ArrayView<const GO>::const_iterator go_iter;
4673  typedef typename ArrayView<const ST>::const_iterator st_iter;
4674 
4675  // Make the output stream write floating-point numbers in
4676  // scientific notation. It will politely put the output
4677  // stream back to its state on input, when this scope
4678  // terminates.
4680 
4681  RCP<const Comm<int> > comm = pMatrix->getComm();
4682  const int myRank = comm->getRank ();
4683 
4684  RCP<FancyOStream> err =
4685  debug ? getFancyOStream (rcpFromRef (std::cerr)) : null;
4686  if (debug) {
4687  std::ostringstream os;
4688  os << myRank << ": writeSparse" << endl;
4689  *err << os.str ();
4690  comm->barrier ();
4691  os << "-- " << myRank << ": past barrier" << endl;
4692  *err << os.str ();
4693  }
4694 
4695  // Whether to print debugging output to stderr.
4696  const bool debugPrint = debug && myRank == 0;
4697 
4698  RCP<const map_type> rowMap = pMatrix->getRowMap ();
4699  RCP<const map_type> colMap = pMatrix->getColMap ();
4700  RCP<const map_type> domainMap = pMatrix->getDomainMap ();
4701  RCP<const map_type> rangeMap = pMatrix->getRangeMap ();
4702 
4703  const global_size_t numRows = rangeMap->getGlobalNumElements ();
4704  const global_size_t numCols = domainMap->getGlobalNumElements ();
4705 
4706  if (debug && myRank == 0) {
4707  std::ostringstream os;
4708  os << "-- Input sparse matrix is:"
4709  << "---- " << numRows << " x " << numCols << " with "
4710  << pMatrix->getGlobalNumEntries() << " entries;" << endl
4711  << "---- "
4712  << (pMatrix->isGloballyIndexed() ? "Globally" : "Locally")
4713  << " indexed." << endl
4714  << "---- Its row map has " << rowMap->getGlobalNumElements ()
4715  << " elements." << endl
4716  << "---- Its col map has " << colMap->getGlobalNumElements ()
4717  << " elements." << endl;
4718  *err << os.str ();
4719  }
4720  // Make the "gather" row map, where Proc 0 owns all rows and
4721  // the other procs own no rows.
4722  const size_t localNumRows = (myRank == 0) ? numRows : 0;
4723  RCP<node_type> node = rowMap->getNode();
4724  if (debug) {
4725  std::ostringstream os;
4726  os << "-- " << myRank << ": making gatherRowMap" << endl;
4727  *err << os.str ();
4728  }
4729  RCP<const map_type> gatherRowMap =
4730  computeGatherMap (rowMap, err, debug);
4731 
4732  // Since the matrix may in general be non-square, we need to
4733  // make a column map as well. In this case, the column map
4734  // contains all the columns of the original matrix, because we
4735  // are gathering the whole matrix onto Proc 0. We call
4736  // computeGatherMap to preserve the original order of column
4737  // indices over all the processes.
4738  const size_t localNumCols = (myRank == 0) ? numCols : 0;
4739  RCP<const map_type> gatherColMap =
4740  computeGatherMap (colMap, err, debug);
4741 
4742  // Current map is the source map, gather map is the target map.
4743  typedef Import<LO, GO, node_type> import_type;
4744  import_type importer (rowMap, gatherRowMap);
4745 
4746  // Create a new CrsMatrix to hold the result of the import.
4747  // The constructor needs a column map as well as a row map,
4748  // for the case that the matrix is not square.
4749  RCP<sparse_matrix_type> newMatrix =
4750  rcp (new sparse_matrix_type (gatherRowMap, gatherColMap,
4751  static_cast<size_t> (0)));
4752  // Import the sparse matrix onto Proc 0.
4753  newMatrix->doImport (*pMatrix, importer, INSERT);
4754 
4755  // fillComplete() needs the domain and range maps for the case
4756  // that the matrix is not square.
4757  {
4758  RCP<const map_type> gatherDomainMap =
4759  rcp (new map_type (numCols, localNumCols,
4760  domainMap->getIndexBase (),
4761  comm, node));
4762  RCP<const map_type> gatherRangeMap =
4763  rcp (new map_type (numRows, localNumRows,
4764  rangeMap->getIndexBase (),
4765  comm, node));
4766  newMatrix->fillComplete (gatherDomainMap, gatherRangeMap);
4767  }
4768 
4769  if (debugPrint) {
4770  cerr << "-- Output sparse matrix is:"
4771  << "---- " << newMatrix->getRangeMap ()->getGlobalNumElements ()
4772  << " x "
4773  << newMatrix->getDomainMap ()->getGlobalNumElements ()
4774  << " with "
4775  << newMatrix->getGlobalNumEntries () << " entries;" << endl
4776  << "---- "
4777  << (newMatrix->isGloballyIndexed () ? "Globally" : "Locally")
4778  << " indexed." << endl
4779  << "---- Its row map has "
4780  << newMatrix->getRowMap ()->getGlobalNumElements ()
4781  << " elements, with index base "
4782  << newMatrix->getRowMap ()->getIndexBase () << "." << endl
4783  << "---- Its col map has "
4784  << newMatrix->getColMap ()->getGlobalNumElements ()
4785  << " elements, with index base "
4786  << newMatrix->getColMap ()->getIndexBase () << "." << endl
4787  << "---- Element count of output matrix's column Map may differ "
4788  << "from that of the input matrix's column Map, if some columns "
4789  << "of the matrix contain no entries." << endl;
4790  }
4791 
4792  //
4793  // Print the metadata and the matrix entries on Rank 0.
4794  //
4795  if (myRank == 0) {
4796  // Print the Matrix Market banner line. CrsMatrix stores
4797  // data nonsymmetrically ("general"). This implies that
4798  // readSparse() on a symmetrically stored input file,
4799  // followed by writeSparse() on the resulting sparse matrix,
4800  // will result in an output file with a different banner
4801  // line than the original input file.
4802  out << "%%MatrixMarket matrix coordinate "
4803  << (STS::isComplex ? "complex" : "real")
4804  << " general" << endl;
4805 
4806  // Print comments (the matrix name and / or description).
4807  if (matrixName != "") {
4808  printAsComment (out, matrixName);
4809  }
4810  if (matrixDescription != "") {
4811  printAsComment (out, matrixDescription);
4812  }
4813 
4814  // Print the Matrix Market header (# rows, # columns, #
4815  // nonzeros). Use the range resp. domain map for the number
4816  // of rows resp. columns, since Tpetra::CrsMatrix uses the
4817  // column map for the number of columns. That only
4818  // corresponds to the "linear-algebraic" number of columns
4819  // when the column map is uniquely owned (a.k.a. one-to-one),
4820  // which only happens if the matrix is (block) diagonal.
4821  out << newMatrix->getRangeMap ()->getGlobalNumElements () << " "
4822  << newMatrix->getDomainMap ()->getGlobalNumElements () << " "
4823  << newMatrix->getGlobalNumEntries () << endl;
4824 
4825  // The Matrix Market format expects one-based row and column
4826  // indices. We'll convert the indices on output from
4827  // whatever index base they use to one-based indices.
4828  const GO rowIndexBase = gatherRowMap->getIndexBase ();
4829  const GO colIndexBase = newMatrix->getColMap()->getIndexBase ();
4830  //
4831  // Print the entries of the matrix.
4832  //
4833  // newMatrix can never be globally indexed, since we called
4834  // fillComplete() on it. We include code for both cases
4835  // (globally or locally indexed) just in case that ever
4836  // changes.
4837  if (newMatrix->isGloballyIndexed()) {
4838  // We know that the "gather" row Map is contiguous, so we
4839  // don't need to get the list of GIDs.
4840  const GO minAllGlobalIndex = gatherRowMap->getMinAllGlobalIndex ();
4841  const GO maxAllGlobalIndex = gatherRowMap->getMaxAllGlobalIndex ();
4842  for (GO globalRowIndex = minAllGlobalIndex;
4843  globalRowIndex <= maxAllGlobalIndex; // inclusive range
4844  ++globalRowIndex) {
4845  ArrayView<const GO> ind;
4846  ArrayView<const ST> val;
4847  newMatrix->getGlobalRowView (globalRowIndex, ind, val);
4848  go_iter indIter = ind.begin ();
4849  st_iter valIter = val.begin ();
4850  for (; indIter != ind.end() && valIter != val.end();
4851  ++indIter, ++valIter) {
4852  const GO globalColIndex = *indIter;
4853  // Convert row and column indices to 1-based.
4854  // This works because the global index type is signed.
4855  out << (globalRowIndex + 1 - rowIndexBase) << " "
4856  << (globalColIndex + 1 - colIndexBase) << " ";
4857  if (STS::isComplex) {
4858  out << STS::real (*valIter) << " " << STS::imag (*valIter);
4859  } else {
4860  out << *valIter;
4861  }
4862  out << endl;
4863  } // For each entry in the current row
4864  } // For each row of the "gather" matrix
4865  } else { // newMatrix is locally indexed
4866  typedef OrdinalTraits<GO> OTG;
4867  for (LO localRowIndex = gatherRowMap->getMinLocalIndex();
4868  localRowIndex <= gatherRowMap->getMaxLocalIndex();
4869  ++localRowIndex) {
4870  // Convert from local to global row index.
4871  const GO globalRowIndex =
4872  gatherRowMap->getGlobalElement (localRowIndex);
4874  globalRowIndex == OTG::invalid(), std::logic_error,
4875  "Failed to convert the supposed local row index "
4876  << localRowIndex << " into a global row index. "
4877  "Please report this bug to the Tpetra developers.");
4878  ArrayView<const LO> ind;
4879  ArrayView<const ST> val;
4880  newMatrix->getLocalRowView (localRowIndex, ind, val);
4881  lo_iter indIter = ind.begin ();
4882  st_iter valIter = val.begin ();
4883  for (; indIter != ind.end() && valIter != val.end();
4884  ++indIter, ++valIter) {
4885  // Convert the column index from local to global.
4886  const GO globalColIndex =
4887  newMatrix->getColMap()->getGlobalElement (*indIter);
4889  globalColIndex == OTG::invalid(), std::logic_error,
4890  "On local row " << localRowIndex << " of the sparse matrix: "
4891  "Failed to convert the supposed local column index "
4892  << *indIter << " into a global column index. Please report "
4893  "this bug to the Tpetra developers.");
4894  // Convert row and column indices to 1-based.
4895  // This works because the global index type is signed.
4896  out << (globalRowIndex + 1 - rowIndexBase) << " "
4897  << (globalColIndex + 1 - colIndexBase) << " ";
4898  if (STS::isComplex) {
4899  out << STS::real (*valIter) << " " << STS::imag (*valIter);
4900  } else {
4901  out << *valIter;
4902  }
4903  out << endl;
4904  } // For each entry in the current row
4905  } // For each row of the "gather" matrix
4906  } // Whether the "gather" matrix is locally or globally indexed
4907  } // If my process' rank is 0
4908  }
4909 
4932  static void
4933  writeSparse (std::ostream& out,
4934  const RCP<const sparse_matrix_type>& pMatrix,
4935  const bool debug=false)
4936  {
4937  writeSparse (out, pMatrix, "", "", debug);
4938  }
4939 
4966  static void
4967  writeDenseFile (const std::string& filename,
4968  const RCP<const multivector_type>& X,
4969  const std::string& matrixName,
4970  const std::string& matrixDescription)
4971  {
4972  const int myRank = Teuchos::rank (*(X->getMap()->getComm()));
4973  std::ofstream out;
4974 
4975  if (myRank == 0) // Only open the file on Rank 0.
4976  out.open (filename.c_str());
4977 
4978  writeDense (out, X, matrixName, matrixDescription);
4979  // We can rely on the destructor of the output stream to close
4980  // the file on scope exit, even if writeDense() throws an
4981  // exception.
4982  }
4983 
5002  static void
5003  writeDenseFile (const std::string& filename,
5004  const RCP<const multivector_type>& X)
5005  {
5006  writeDenseFile (filename, X, "", "");
5007  }
5008 
5035  static void
5036  writeDense (std::ostream& out,
5037  const RCP<const multivector_type>& X,
5038  const std::string& matrixName,
5039  const std::string& matrixDescription)
5040  {
5041  writeDenseImpl<scalar_type> (out, *X, matrixName, matrixDescription);
5042  }
5043 
5062  static void
5063  writeDense (std::ostream& out,
5064  const RCP<const multivector_type>& X)
5065  {
5066  writeDense (out, X, "", "");
5067  }
5068 
5070  static void
5071  writeMap (std::ostream& out, const map_type& map, const bool debug=false)
5072  {
5074  Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr));
5075  writeMap (out, map, err, debug);
5076  }
5077 
5086  static void
5087  writeMap (std::ostream& out,
5088  const map_type& map,
5090  const bool debug=false)
5091  {
5092  using Teuchos::ArrayRCP;
5093  using Teuchos::ArrayView;
5094  using Teuchos::as;
5095  using Teuchos::rcp_const_cast;
5096  using Teuchos::rcpFromRef;
5098  using std::cerr;
5099  using std::endl;
5100  typedef local_ordinal_type LO;
5101  typedef global_ordinal_type GO;
5102  typedef node_type NT;
5103  typedef int pid_type;
5104 
5105  // ptrdiff_t should be the biggest signed built-in integer
5106  // type that can hold any GO or pid_type (= int) quantity
5107  // without overflow. Nevertheless, we'll test this.
5108  typedef ptrdiff_t int_type;
5110  sizeof(GO) > sizeof(int_type), std::logic_error,
5111  "The global ordinal type GO=" << TypeNameTraits<GO>::name ()
5112  << " is too big for ptrdiff_t. sizeof(GO) = " << sizeof (GO)
5113  << " > sizeof(ptrdiff_t) = " << sizeof (ptrdiff_t) << ".");
5115  sizeof(pid_type) > sizeof(int_type), std::logic_error,
5116  "The process rank type pid_type=" << TypeNameTraits<pid_type>::name ()
5117  << " is too big for ptrdiff_t. sizeof(pid_type) = " << sizeof (pid_type)
5118  << " > sizeof(ptrdiff_t) = " << sizeof (ptrdiff_t) << ".");
5119 
5120  const int myRank = map.getComm ()->getRank ();
5121 
5122  if (! err.is_null ()) {
5123  err->pushTab ();
5124  }
5125  if (debug) {
5126  *err << myRank << ": writeMap" << endl;
5127  }
5128  if (! err.is_null ()) {
5129  err->pushTab ();
5130  }
5131 
5132  // We pack the Map into a 2-column MultiVector. Column 0
5133  // holds the GIDs, and Column 1 holds the PIDs.
5135  MV data (rcpFromRef (map), 2);
5136 
5137  // Column 0: GIDs for each process in sequence (by their
5138  // process ranks), in their original order on that process.
5139  // We put the GIDs first because the ordering of GIDs defines
5140  // the permutation that the Map represents, no matter how the
5141  // GIDs are distributed over processes.
5142  ArrayView<const GO> gidList = map.getNodeElementList ();
5143  {
5144  ArrayRCP<int_type> V0 = data.getDataNonConst (0);
5145  for (int_type k = 0; k < gidList.size (); ++k) {
5146  V0[k] = as<int_type> (gidList[k]);
5147  }
5148  }
5149 
5150  if (debug) {
5151  *err << myRank << ": writeMap: Done with column 0" << endl;
5152  }
5153 
5154  // Column 1: PID (process rank) that owns the GID in the same
5155  // row. The same GID might be owned by multiple processes; in
5156  // that case, it will appear multiple times in the first
5157  // column, with a different PID each time.
5158  {
5159  ArrayRCP<int_type> V1 = data.getDataNonConst (1);
5160  for (int_type k = 0; k < gidList.size (); ++k) {
5161  V1[k] = as<int_type> (myRank);
5162  }
5163  }
5164 
5165  if (debug) {
5166  *err << myRank << ": writeMap: Done with column 1" << endl;
5167  }
5168 
5169  // Map description explains each column.
5170  std::ostringstream desc;
5171  desc << "This file encodes a Tpetra::Map." << endl
5172  << "It is stored as a dense matrix with 2 columns:" << endl
5173  << " - Column 1: GID (global index)" << endl
5174  << " - Column 2: PID (rank) of process owning that GID" << endl;
5175  writeDenseImpl<int_type> (out, data, map.getObjectLabel (),
5176  desc.str (), err, debug);
5177 
5178  if (! err.is_null ()) {
5179  err->popTab ();
5180  }
5181  if (debug) {
5182  *err << myRank << ": writeMap: Done" << endl;
5183  }
5184  if (! err.is_null ()) {
5185  err->popTab ();
5186  }
5187  }
5188 
5190  static void
5191  writeMapFile (const std::string& filename,
5192  const map_type& map)
5193  {
5194  const int myRank = map.getComm ()->getRank ();
5195  std::ofstream out;
5196  if (myRank == 0) { // Only open the file on Proc 0.
5197  out.open (filename.c_str());
5198  }
5199  writeMap (out, map);
5200  // We can rely on the destructor of the output stream to close
5201  // the file on scope exit, even if writeDense() throws an
5202  // exception.
5203  }
5204 
5205  private:
5237  template<class MultiVectorScalarType>
5238  static void
5239  writeDenseImpl (std::ostream& out,
5241  const std::string& matrixName,
5242  const std::string& matrixDescription,
5243  const Teuchos::RCP<Teuchos::FancyOStream>& err=Teuchos::null,
5244  const bool debug=false)
5245  {
5246  using Tpetra::createOneToOne;
5248  using Teuchos::as;
5249  using Teuchos::rcp;
5250  using Teuchos::rcp_const_cast;
5251  using Teuchos::rcp_dynamic_cast;
5252  using std::endl;
5253 
5254  typedef MultiVectorScalarType ST;
5255  typedef local_ordinal_type LO;
5256  typedef global_ordinal_type GO;
5257  typedef node_type NT;
5258 
5259  typedef typename Teuchos::ScalarTraits<ST> STS;
5261 
5262  RCP<const map_type> map = X.getMap ();
5263  RCP<const Comm<int> > comm = map->getComm ();
5264  const int myRank = comm->getRank ();
5265 
5266  if (! err.is_null ()) {
5267  err->pushTab ();
5268  }
5269  if (debug) {
5270  std::ostringstream os;
5271  os << myRank << ": writeDenseImpl" << endl;
5272  *err << os.str ();
5273  }
5274  if (! err.is_null ()) {
5275  err->pushTab ();
5276  }
5277 
5278  // Make the output stream write floating-point numbers in
5279  // scientific notation. It will politely put the output
5280  // stream back to its state on input, when this scope
5281  // terminates.
5283 
5284  const global_size_t numRows = map->getGlobalNumElements ();
5285  // Promote to global_size_t.
5286  const global_size_t numCols = as<global_size_t> (X.getNumVectors ());
5287 
5288  if (debug) {
5289  std::ostringstream os;
5290  os << myRank << ": writeDenseImpl: Computing gather Map" << endl;
5291  *err << os.str ();
5292  }
5293 
5294  // Make the "gather" map, where Proc 0 owns all rows of X, and
5295  // the other procs own no rows.
5296  RCP<NT> node = map->getNode();
5297  RCP<const map_type> gatherMap =
5298  computeGatherMap<map_type> (map, err, debug);
5299 
5300  if (debug) {
5301  std::ostringstream os;
5302  os << myRank << ": writeDenseImpl: Computing Import" << endl;
5303  *err << os.str ();
5304  }
5305 
5306  // Create an Import object to import X's data into a
5307  // multivector Y owned entirely by Proc 0. In the Import
5308  // constructor, X's map is the source map, and the "gather
5309  // map" is the target map.
5310  Import<LO, GO, NT> importer (map, gatherMap, err);
5311 
5312  if (debug) {
5313  std::ostringstream os;
5314  os << myRank << ": writeDenseImpl: Creating target MultiVector" << endl;
5315  *err << os.str ();
5316  }
5317 
5318  // Create a new multivector Y to hold the result of the import.
5319  RCP<MV> Y = createMultiVector<ST, LO, GO, NT> (gatherMap, numCols);
5320 
5321  if (debug) {
5322  std::ostringstream os;
5323  os << myRank << ": writeDenseImpl: Doing Import" << endl;
5324  *err << os.str ();
5325  }
5326 
5327  // Import the multivector onto Proc 0.
5328  Y->doImport (X, importer, INSERT);
5329 
5330  if (debug) {
5331  std::ostringstream os;
5332  os << myRank << ": writeDenseImpl: Writing data to out" << endl;
5333  *err << os.str ();
5334  }
5335 
5336  //
5337  // Print the matrix in Matrix Market format on Proc 0.
5338  //
5339  std::ostringstream exMsg; // for exception messages on Proc 0
5340  int localWriteSuccess = 1; // whether the write succeeded on Proc 0
5341  if (myRank == 0) {
5342  try {
5343  std::string dataType;
5344  if (STS::isComplex) {
5345  dataType = "complex";
5346  } else if (STS::isOrdinal) {
5347  dataType = "integer";
5348  } else {
5349  dataType = "real";
5350  }
5351 
5352  // Print the Matrix Market banner line. MultiVector
5353  // stores data nonsymmetrically, hence "general".
5354  out << "%%MatrixMarket matrix array "
5355  << dataType << " general" << endl;
5356 
5357  // Print comments (the matrix name and / or description).
5358  if (matrixName != "") {
5359  printAsComment (out, matrixName);
5360  }
5361  if (matrixDescription != "") {
5362  printAsComment (out, matrixDescription);
5363  }
5364  // Print the Matrix Market dimensions header for dense matrices.
5365  out << numRows << " " << numCols << endl;
5366 
5367  // Get a read-only view of the entries of Y.
5368  // Rank 0 owns all of the entries of Y.
5369  ArrayRCP<ArrayRCP<const ST> > Y_view = Y->get2dView ();
5371  as<global_size_t> (Y_view.size ()) < numCols, std::logic_error,
5372  "Y_view has size " << Y_view.size () << " < numCols = "
5373  << numCols << ".");
5374 
5375  // Print the entries of the matrix, in column-major order.
5376  for (global_size_t j = 0; j < numCols; ++j) {
5377  ArrayRCP<const ST> Y_j = Y_view[j];
5379  as<global_size_t> (Y_j.size ()) < numRows, std::logic_error,
5380  "The current column's data has length " << Y_j.size ()
5381  << " < numRows=" << numRows << ".");
5382  for (global_size_t i = 0; i < numRows; ++i) {
5383  const ST Y_ij = Y_j[i];
5384  if (STS::isComplex) {
5385  out << STS::real (Y_ij) << " " << STS::imag (Y_ij) << endl;
5386  } else {
5387  out << Y_ij << endl;
5388  }
5389  }
5390  }
5391  } catch (std::exception& e) {
5392  exMsg << e.what ();
5393  localWriteSuccess = 0;
5394  }
5395  } // if (myRank == 0)
5396 
5397  // Synchronize on error. This is not necessary here, but it
5398  // will prevent later code from hanging in Proc 0 threw an
5399  // exception above.
5400  int globalWriteSuccess = localWriteSuccess;
5401  broadcast (*comm, 0, outArg (globalWriteSuccess));
5403  globalWriteSuccess == 0, std::runtime_error,
5404  "Failed to write data: " << exMsg.str ());
5405 
5406  if (! err.is_null ()) {
5407  err->popTab ();
5408  }
5409  if (debug) {
5410  *err << myRank << ": writeDenseImpl: done" << endl;
5411  }
5412  if (! err.is_null ()) {
5413  err->popTab ();
5414  }
5415  }
5416 
5440  static void
5441  printAsComment (std::ostream& out, const std::string& str)
5442  {
5443  using std::endl;
5444  std::istringstream istream (str);
5445  std::string line;
5446 
5447  while (getline (istream, line)) {
5448  if (! line.empty()) {
5449  // Note that getline() doesn't store '\n', so we have to
5450  // append the endline ourselves.
5451  if (line[0] == '%') { // Line starts with a comment character.
5452  out << line << endl;
5453  }
5454  else { // Line doesn't start with a comment character.
5455  out << "%% " << line << endl;
5456  }
5457  }
5458  }
5459  }
5460  }; // class Writer
5461 
5462  } // namespace MatrixMarket
5463 } // namespace Tpetra
5464 
5465 #endif // __MatrixMarket_Tpetra_hpp
Communication plan for data redistribution from a uniquely-owned to a (possibly) multiply-owned distr...
Namespace Tpetra contains the class and methods constituting the Tpetra library.
virtual std::string getObjectLabel() const
SparseMatrixType::node_type node_type
ArrayRCP< T > persistingView(size_type lowerOffset, size_type size) const
SparseMatrixType::scalar_type scalar_type
Type of the entries of the sparse matrix.
static sparse_matrix_ptr readSparse(std::istream &in, const RCP< const Comm< int > > &pComm, const RCP< node_type > &pNode, const bool callFillComplete=true, const bool tolerant=false, const bool debug=false)
Read sparse matrix from the given Matrix Market input stream.
static RCP< multivector_type > readDense(std::istream &in, const RCP< const comm_type > &comm, const RCP< node_type > &node, RCP< const map_type > &map, const bool tolerant=false, const bool debug=false)
Read dense matrix (as a MultiVector) from the given Matrix Market input stream.
const Teuchos::RCP< const Teuchos::Comm< int > > & getComm() const
Accessors for the Teuchos::Comm and Kokkos Node objects.
static sparse_matrix_ptr readSparseFile(const std::string &filename, const RCP< const map_type > &rowMap, RCP< const map_type > &colMap, const RCP< const map_type > &domainMap, const RCP< const map_type > &rangeMap, const bool callFillComplete=true, const bool tolerant=false, const bool debug=false)
Read sparse matrix from the given Matrix Market file, with provided Maps.
iterator begin() const
size_t getNumVectors() const
Number of columns in the multivector.
Map< local_ordinal_type, global_ordinal_type, node_type > map_type
Tpetra::Map specialization associated with SparseMatrixType.
SparseMatrixType::local_ordinal_type local_ordinal_type
const std::string & matrixType() const
SparseMatrixType::global_ordinal_type global_ordinal_type
One or more distributed dense vectors.
basic_FancyOStream< char > FancyOStream
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
static void writeDenseFile(const std::string &filename, const RCP< const multivector_type > &X)
Print the multivector in Matrix Market format.
const_pointer const_iterator
T * getRawPtr() const
Teuchos::RCP< AdderType > getAdder() const
SparseMatrixType::local_ordinal_type local_ordinal_type
Only used to define map_type.
size_type size() const
GlobalOrdinal getIndexBase() const
The index base for this Map.
SparseMatrixType::scalar_type scalar_type
bool isDistributed() const
Whether this Map is globally distributed or locally replicated.
virtual int getRank() const =0
ArrayRCP< const T > getConst() const
static RCP< const map_type > readMapFile(const std::string &filename, const RCP< const comm_type > &comm, const RCP< node_type > &node, const bool tolerant=false, const bool debug=false)
Read Map (as a MultiVector) from the given Matrix Market file.
void pushTab(const int tabs=1)
size_type size() const
static void writeMap(std::ostream &out, const map_type &map, const bool debug=false)
Print the Map to the given output stream.
void resize(const size_type n, const T &val=T())
size_t global_size_t
Global size_t object.
T * getRawPtr() const
static void writeMapFile(const std::string &filename, const map_type &map)
Write the Map to the given file.
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
static sparse_matrix_ptr readSparse(std::istream &in, const RCP< const map_type > &rowMap, RCP< const map_type > &colMap, const RCP< const map_type > &domainMap, const RCP< const map_type > &rangeMap, const bool callFillComplete=true, const bool tolerant=false, const bool debug=false)
Read sparse matrix from the given Matrix Market input stream, with provided Maps. ...
static sparse_matrix_ptr readSparseFile(const std::string &filename, const RCP< const Comm< int > > &pComm, const RCP< node_type > &pNode, const RCP< Teuchos::ParameterList > &constructorParams, const RCP< Teuchos::ParameterList > &fillCompleteParams, const bool tolerant=false, const bool debug=false)
Read sparse matrix from the given Matrix Market file.
Communication plan for data redistribution from a (possibly) multiply-owned to a uniquely-owned distr...
static RCP< multivector_type > readDenseFile(const std::string &filename, const RCP< const comm_type > &comm, const RCP< node_type > &node, RCP< const map_type > &map, const bool tolerant=false, const bool debug=false)
Read dense matrix (as a MultiVector) from the given Matrix Market file.
static void writeSparse(std::ostream &out, const RCP< const sparse_matrix_type > &pMatrix, const std::string &matrixName, const std::string &matrixDescription, const bool debug=false)
Print the sparse matrix in Matrix Market format, with comments.
static sparse_matrix_ptr readSparseFile(const std::string &filename, const RCP< const Comm< int > > &pComm, const RCP< node_type > &pNode, const bool callFillComplete=true, const bool tolerant=false, const bool debug=false)
Read sparse matrix from the given Matrix Market file.
static void writeSparseFile(const std::string &filename, const RCP< const sparse_matrix_type > &pMatrix, const std::string &matrixName, const std::string &matrixDescription, const bool debug=false)
Print the sparse matrix in Matrix Market format, with comments.
const Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > & getMap() const
The Map describing the parallel distribution of this object.
TEUCHOSCORE_LIB_DLL_EXPORT std::string toString(const EVerbosityLevel verbLevel)
static void writeDenseFile(const std::string &filename, const RCP< const multivector_type > &X, const std::string &matrixName, const std::string &matrixDescription)
Print the multivector in Matrix Market format, with comments.
static void writeMap(std::ostream &out, const map_type &map, const Teuchos::RCP< Teuchos::FancyOStream > &err, const bool debug=false)
Print the Map to the given output stream out.
const std::string & symmType() const
TEUCHOS_DEPRECATED void reduceAll(const Comm< Ordinal > &comm, const EReductionType reductType, const Packet &send, Packet *globalReduct)
void send(const Packet sendBuffer[], const Ordinal count, const int destRank, const int tag, const Comm< Ordinal > &comm)
static void writeDense(std::ostream &out, const RCP< const multivector_type > &X)
Print the multivector in Matrix Market format.
T * getRawPtr() const
SparseMatrixType::node_type node_type
The Kokkos Node type.
Teuchos::ArrayView< const GlobalOrdinal > getNodeElementList() const
Return a view of the global indices owned by this process.
static void writeSparseFile(const std::string &filename, const RCP< const sparse_matrix_type > &pMatrix, const bool debug=false)
Print the sparse matrix in Matrix Market format.
SparseMatrixType::global_ordinal_type global_ordinal_type
Type of indices as read from the Matrix Market file.
MultiVector< scalar_type, local_ordinal_type, global_ordinal_type, node_type > multivector_type
The MultiVector specialization associated with SparseMatrixType.
static sparse_matrix_ptr readSparse(std::istream &in, const RCP< const Comm< int > > &pComm, const RCP< node_type > &pNode, const RCP< Teuchos::ParameterList > &constructorParams, const RCP< Teuchos::ParameterList > &fillCompleteParams, const bool tolerant=false, const bool debug=false)
Read sparse matrix from the given Matrix Market input stream.
void push_back(const value_type &x)
MultiVector< scalar_type, local_ordinal_type, global_ordinal_type, node_type > multivector_type
The MultiVector type associated with SparseMatrixType.
size_t getNodeNumElements() const
The number of elements belonging to the calling process.
virtual int getSize() const =0
Describes a parallel distribution of objects over processes.
iterator end() const
size_type size() const
TypeTo as(const TypeFrom &t)
static RCP< const map_type > readMap(std::istream &in, const RCP< const comm_type > &comm, const RCP< node_type > &node, const bool tolerant=false, const bool debug=false)
Read Map (as a MultiVector) from the given input stream.
static void writeDense(std::ostream &out, const RCP< const multivector_type > &X, const std::string &matrixName, const std::string &matrixDescription)
Print the multivector in Matrix Market format.
Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > createNonContigMapWithNode(const ArrayView< const GlobalOrdinal > &elementList, const RCP< const Teuchos::Comm< int > > &comm, const RCP< Node > &node)
Non-member constructor for a non-contiguous Map with a user-specified Kokkos Node.
SparseMatrixType sparse_matrix_type
This class&#39; template parameter; a specialization of CrsMatrix.
static void writeSparse(std::ostream &out, const RCP< const sparse_matrix_type > &pMatrix, const bool debug=false)
Print the sparse matrix in Matrix Market format.
iterator end() const
Matrix Market file reader for CrsMatrix and MultiVector.
static RCP< const map_type > readMap(std::istream &in, const RCP< const comm_type > &comm, const RCP< node_type > &node, const Teuchos::RCP< Teuchos::FancyOStream > &err, const bool tolerant=false, const bool debug=false)
Read Map (as a MultiVector) from the given input stream, with optional debugging output stream...
Matrix Market file writer for CrsMatrix and MultiVector.
bool is_null() const
const Teuchos::RCP< Node > & getNode() const
Get this Map&#39;s Node object.
iterator begin() const
Matrix Market file readers and writers for sparse and dense matrices (as CrsMatrix resp...
global_size_t getGlobalNumElements() const
The number of elements in this Map.
static std::string name()
Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > createOneToOne(Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > &M)
Creates a one-to-one version of the given Map where each GID is owned by only one process...
std::string toString(const T &t)
bool is_null() const
ArrayView< T > view(size_type lowerOffset, size_type size) const