42 #ifndef __MatrixMarket_Tpetra_hpp 43 #define __MatrixMarket_Tpetra_hpp 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" 107 template<
class IntType> MPI_Datatype getMpiDatatype () {
110 template<> MPI_Datatype getMpiDatatype<int> () {
return MPI_INT; }
111 template<> MPI_Datatype getMpiDatatype<long> () {
return MPI_LONG; }
114 template<
class IntType>
116 reduceSum (
const IntType sendbuf[],
124 using Teuchos::rcp_dynamic_cast;
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 ());
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);
142 std::copy (sendbuf, sendbuf + count, recvbuf);
145 template<
class IntType>
147 gather (
const IntType sendbuf[],
const int sendcnt,
148 IntType recvbuf[],
const int recvcnt,
152 using Teuchos::rcp_dynamic_cast;
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)),
165 reinterpret_cast<void*> (recvbuf),
171 err != MPI_SUCCESS, std::runtime_error,
"MPI_Gather failed");
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 <<
".");
184 std::copy (sendbuf, sendbuf + recvcnt, recvbuf);
187 template<
class IntType>
189 gatherv (
const IntType sendbuf[],
const int sendcnt,
190 IntType recvbuf[],
const int recvcnts[],
const int displs[],
194 using Teuchos::rcp_dynamic_cast;
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)),
209 reinterpret_cast<void*> (recvbuf),
210 const_cast<int*> (recvcnts),
211 const_cast<int*> (displs),
216 err != MPI_SUCCESS, std::runtime_error,
"MPI_Gatherv failed");
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 <<
".");
230 std::copy (sendbuf, sendbuf + recvcnts[0], recvbuf + displs[0]);
236 template<
class MapType>
240 const bool debug=
false)
251 typedef typename MapType::local_ordinal_type LO;
252 typedef typename MapType::global_ordinal_type GO;
253 typedef typename MapType::node_type NT;
255 RCP<const Comm<int> > comm = map->getComm ();
256 const int numProcs = comm->getSize ();
257 const int myRank = comm->getRank ();
263 *err << myRank <<
": computeGatherMap:" << endl;
269 RCP<const MapType> oneToOneMap;
270 if (map->isContiguous ()) {
274 *err << myRank <<
": computeGatherMap: Calling createOneToOne" << endl;
279 oneToOneMap = createOneToOne<LO, GO, NT> (map);
282 RCP<const MapType> gatherMap;
284 gatherMap = oneToOneMap;
287 *err << myRank <<
": computeGatherMap: Gathering Map counts" << endl;
306 const int myEltCount = as<int> (oneToOneMap->getNodeNumElements ());
308 const int rootProc = 0;
309 gather<int> (&myEltCount, 1, recvCounts.getRawPtr (), 1, rootProc, comm);
311 ArrayView<const GO> myGlobalElts = oneToOneMap->getNodeElementList ();
312 const int numMyGlobalElts = as<int> (myGlobalElts.size ());
315 ArrayRCP<GO> allGlobalElts;
317 allGlobalElts = arcp<GO> (oneToOneMap->getGlobalNumElements ());
318 std::fill (allGlobalElts.begin (), allGlobalElts.end (), 0);
322 *err << myRank <<
": computeGatherMap: Computing MPI_Gatherv " 323 "displacements" << endl;
330 std::partial_sum (recvCounts.begin (), recvCounts.end () - 1,
331 displs.begin () + 1);
333 *err << myRank <<
": computeGatherMap: Calling MPI_Gatherv" << endl;
335 gatherv<GO> (myGlobalElts.getRawPtr (), numMyGlobalElts,
336 allGlobalElts.getRawPtr (), recvCounts.getRawPtr (),
337 displs.getRawPtr (), rootProc, comm);
340 *err << myRank <<
": computeGatherMap: Creating gather Map" << endl;
344 ArrayView<const GO> allElts (NULL, 0);
346 allElts = allGlobalElts ();
349 gatherMap =
rcp (
new MapType (INVALID, allElts,
350 oneToOneMap->getIndexBase (),
351 comm, map->getNode ()));
357 *err << myRank <<
": computeGatherMap: done" << endl;
429 template<
class SparseMatrixType>
449 typedef typename SparseMatrixType::global_ordinal_type
486 const global_ordinal_type numRows)
489 return rcp (
new map_type (static_cast<global_size_t> (numRows),
490 static_cast<global_ordinal_type> (0),
526 const global_ordinal_type numRows)
531 return rcp (
new map_type (static_cast<global_size_t> (numRows),
532 static_cast<global_ordinal_type> (0),
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()
542 std::invalid_argument,
543 "The specified row map's communicator (pRowMap->" 544 "getComm()) is different than the given separately " 545 "supplied communicator pComm.");
547 std::invalid_argument,
548 "The specified row map's node (pRowMap->getNode()) " 549 "is different than the given separately supplied " 571 const global_ordinal_type numRows,
572 const global_ordinal_type numCols)
575 typedef local_ordinal_type LO;
576 typedef global_ordinal_type GO;
577 typedef node_type Node;
579 if (numRows == numCols) {
582 return createUniformContigMapWithNode<LO,GO,Node> (numCols,
670 const bool debug=
false)
674 using Teuchos::receive;
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;
686 typedef global_ordinal_type GO;
691 const size_type myNumRows = myRows.
size();
695 "pRowMap->getNodeElementList().size() = " 697 <<
" != pRowMap->getNodeNumElements() = " 699 "Please report this bug to the Tpetra developers.");
702 "On Proc 0: numEntriesPerRow.size() = " 703 << numEntriesPerRow.
size()
704 <<
" != pRowMap->getNodeElementList().size() = " 705 << myNumRows <<
". Please report this bug to the " 706 "Tpetra developers.");
710 myNumEntriesPerRow = arcp<size_t> (myNumRows);
712 if (myRank != rootRank) {
716 send (*pComm, myNumRows, rootRank);
717 if (myNumRows != 0) {
721 send (*pComm, static_cast<int> (myNumRows),
732 receive (*pComm, rootRank,
733 static_cast<int> (myNumRows),
738 const local_ordinal_type myNumEntries =
739 std::accumulate (myNumEntriesPerRow.begin(),
740 myNumEntriesPerRow.end(), 0);
746 myColInd = arcp<GO> (myNumEntries);
747 myValues = arcp<scalar_type> (myNumEntries);
748 if (myNumEntries > 0) {
751 receive (*pComm, rootRank,
752 static_cast<int> (myNumEntries),
754 receive (*pComm, rootRank,
755 static_cast<int> (myNumEntries),
762 cerr <<
"-- Proc 0: Copying my data from global arrays" << endl;
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;
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) {
783 const local_ordinal_type myNumEntries =
784 std::accumulate (myNumEntriesPerRow.begin(),
785 myNumEntriesPerRow.end(), 0);
787 cerr <<
"-- Proc 0: I own " << myNumRows <<
" rows and " 788 << myNumEntries <<
" entries" << endl;
790 myColInd = arcp<GO> (myNumEntries);
791 myValues = arcp<scalar_type> (myNumEntries);
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];
806 if (curNumEntries > 0) {
808 ArrayView<GO> myColIndView = myColInd (myCurPos, curNumEntries);
809 std::copy (colIndView.
begin(), colIndView.
end(),
810 myColIndView.
begin());
813 values (curPos, curNumEntries);
815 myValues (myCurPos, curNumEntries);
816 std::copy (valuesView.begin(), valuesView.end(),
817 myValuesView.
begin());
822 for (
int p = 1; p < numProcs; ++p) {
824 cerr <<
"-- Proc 0: Processing proc " << p << endl;
827 size_type theirNumRows = 0;
832 receive (*pComm, p, &theirNumRows);
834 cerr <<
"-- Proc 0: Proc " << p <<
" owns " 835 << theirNumRows <<
" rows" << endl;
837 if (theirNumRows != 0) {
843 receive (*pComm, p, as<int> (theirNumRows),
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;
862 if (! theirRowsValid) {
864 ! theirRowsValid, std::logic_error,
865 "Proc " << p <<
" has at least one invalid row index. " 866 "Here are all of them: " <<
868 "range (zero-based): [0, " << (numRows - 1) <<
"].");
884 theirNumEntriesPerRow = arcp<size_t> (theirNumRows);
885 for (size_type k = 0; k < theirNumRows; ++k) {
886 theirNumEntriesPerRow[k] = numEntriesPerRow[theirRows[k]];
893 send (*pComm, static_cast<int> (theirNumRows),
897 const local_ordinal_type theirNumEntries =
898 std::accumulate (theirNumEntriesPerRow.
begin(),
899 theirNumEntriesPerRow.
end(), 0);
902 cerr <<
"-- Proc 0: Proc " << p <<
" owns " 903 << theirNumEntries <<
" entries" << endl;
908 if (theirNumEntries == 0) {
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];
935 if (curNumEntries > 0) {
937 colInd (curPos, curNumEntries);
939 theirColInd (theirCurPos, curNumEntries);
940 std::copy (colIndView.
begin(), colIndView.
end(),
941 theirColIndView.
begin());
944 values (curPos, curNumEntries);
946 theirValues (theirCurPos, curNumEntries);
947 std::copy (valuesView.begin(), valuesView.end(),
948 theirValuesView.
begin());
955 send (*pComm, static_cast<int> (theirNumEntries),
957 send (*pComm, static_cast<int> (theirNumEntries),
961 cerr <<
"-- Proc 0: Finished with proc " << p << endl;
969 numEntriesPerRow = null;
974 if (debug && myRank == 0) {
975 cerr <<
"-- Proc 0: About to fill in myRowPtr" << endl;
983 myRowPtr = arcp<size_t> (myNumRows+1);
985 for (size_type k = 1; k < myNumRows+1; ++k) {
986 myRowPtr[k] = myRowPtr[k-1] + myNumEntriesPerRow[k-1];
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) {
997 cerr <<
"]" << endl << endl;
1000 if (debug && myRank == 0) {
1001 cerr <<
"-- Proc 0: Done with distribute" << endl;
1018 static sparse_matrix_ptr
1023 const map_ptr& pRowMap,
1024 const map_ptr& pRangeMap,
1025 const map_ptr& pDomainMap,
1026 const bool callFillComplete =
true)
1031 typedef global_ordinal_type GO;
1039 "makeMatrix: myRowPtr array is null. " 1040 "Please report this bug to the Tpetra developers.");
1042 "makeMatrix: domain map is null. " 1043 "Please report this bug to the Tpetra developers.");
1045 "makeMatrix: range map is null. " 1046 "Please report this bug to the Tpetra developers.");
1048 "makeMatrix: row map is null. " 1049 "Please report this bug to the Tpetra developers.");
1056 sparse_matrix_ptr A =
1057 rcp (
new sparse_matrix_type (pRowMap, myNumEntriesPerRow,
1063 const size_type myNumRows = myRows.
size ();
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];
1074 for (size_type k = 0; k < curNumEntries; ++k) {
1075 curColInd[k] += indexBase;
1078 if (curNumEntries > 0) {
1079 A->insertGlobalValues (myRows[i], curColInd, curValues);
1086 myNumEntriesPerRow = null;
1091 if (callFillComplete) {
1092 A->fillComplete (pDomainMap, pRangeMap);
1102 static sparse_matrix_ptr
1107 const map_ptr& pRowMap,
1108 const map_ptr& pRangeMap,
1109 const map_ptr& pDomainMap,
1116 typedef global_ordinal_type GO;
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.");
1145 sparse_matrix_ptr A =
1146 rcp (
new sparse_matrix_type (pRowMap, myNumEntriesPerRow,
1152 const size_type myNumRows = myRows.
size();
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];
1163 for (size_type k = 0; k < curNumEntries; ++k) {
1164 curColInd[k] += indexBase;
1166 if (curNumEntries > 0) {
1167 A->insertGlobalValues (myRows[i], curColInd, curValues);
1174 myNumEntriesPerRow = null;
1179 A->fillComplete (pDomainMap, pRangeMap, fillCompleteParams);
1187 static sparse_matrix_ptr
1196 const bool callFillComplete =
true)
1200 using Teuchos::null;
1203 typedef global_ordinal_type GO;
1214 A =
rcp (
new sparse_matrix_type (rowMap, colMap, myNumEntriesPerRow,
DynamicProfile));
1220 const size_type myNumRows = myRows.
size ();
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]);
1231 for (size_type k = 0; k < curNumEntries; ++k) {
1232 curColInd[k] += indexBase;
1234 if (curNumEntries > 0) {
1235 A->insertGlobalValues (myRows[i], curColInd, curValues);
1242 myNumEntriesPerRow = null;
1247 if (callFillComplete) {
1248 A->fillComplete (domainMap, rangeMap);
1250 colMap = A->getColMap ();
1275 readBanner (std::istream& in,
1277 const bool tolerant=
false,
1278 const bool debug=
false)
1289 const bool readFailed = ! getline(in, line);
1291 "Failed to get Matrix Market banner line from input.");
1298 pBanner =
rcp (
new Banner (line, tolerant));
1299 }
catch (std::exception& e) {
1301 "Matrix Market banner line contains syntax error(s): " 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\".");
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.");
1354 readCoordDims (std::istream& in,
1357 const comm_ptr& pComm,
1358 const bool tolerant =
false,
1359 const bool debug =
false)
1361 using Teuchos::MatrixMarket::readCoordinateDimensions;
1372 bool success =
false;
1373 if (pComm->getRank() == 0) {
1375 std::invalid_argument,
"The Tpetra::CrsMatrix Matrix Market reader " 1376 "only accepts \"coordinate\" (sparse) matrix data.");
1378 global_ordinal_type numRows, numCols, numNonzeros;
1380 success = readCoordinateDimensions (in, numRows, numCols,
1381 numNonzeros, lineNumber,
1387 dims[2] = numNonzeros;
1395 int the_success = success ? 1 : 0;
1396 Teuchos::broadcast (*pComm, 0, &the_success);
1397 success = (the_success == 1);
1402 Teuchos::broadcast (*pComm, 0, dims);
1411 "Error reading Matrix Market sparse matrix: failed to read " 1412 "coordinate matrix dimensions.");
1458 const bool tolerant=
false,
1459 const bool debug=
false)
1461 if (pComm->getRank() == 0) {
1464 rcp (
new raw_adder_type (dims[0], dims[1], dims[2], tolerant, debug));
1465 return rcp (
new adder_type (pRaw, pBanner->
symmType()));
1498 static sparse_matrix_ptr
1502 const bool callFillComplete=
true,
1503 const bool tolerant=
false,
1504 const bool debug=
false)
1506 const int myRank = Teuchos::rank (*pComm);
1511 in.open (filename.c_str());
1512 return readSparse (in, pComm, pNode, callFillComplete, tolerant, debug);
1547 static sparse_matrix_ptr
1553 const bool tolerant=
false,
1554 const bool debug=
false)
1557 if (pComm->getRank () == 0) {
1558 in.open (filename.c_str());
1560 return readSparse (in, pComm, pNode, constructorParams,
1561 fillCompleteParams, tolerant, debug);
1601 static sparse_matrix_ptr
1607 const bool callFillComplete=
true,
1608 const bool tolerant=
false,
1609 const bool debug=
false)
1611 using Teuchos::broadcast;
1612 using Teuchos::outArg;
1614 rowMap.
is_null (), std::invalid_argument,
1615 "Row Map must be nonnull.");
1619 const int myRank = comm->getRank ();
1629 in.open (filename.c_str ());
1636 broadcast<int, int> (*comm, 0, outArg (opened));
1638 opened == 0, std::runtime_error,
1639 "readSparseFile: Failed to open file \"" << filename <<
"\" on " 1641 return readSparse (in, rowMap, colMap, domainMap, rangeMap,
1642 callFillComplete, tolerant, debug);
1671 static sparse_matrix_ptr
1675 const bool callFillComplete=
true,
1676 const bool tolerant=
false,
1677 const bool debug=
false)
1680 using Teuchos::broadcast;
1687 const bool extraDebug =
false;
1688 const int myRank = pComm->getRank ();
1689 const int rootRank = 0;
1694 size_t lineNumber = 1;
1696 if (debug && myRank == rootRank) {
1697 cerr <<
"Matrix Market reader: readSparse:" << endl
1698 <<
"-- Reading banner line" << endl;
1713 int bannerIsCorrect = 1;
1714 std::ostringstream errMsg;
1716 if (myRank == rootRank) {
1719 pBanner = readBanner (in, lineNumber, tolerant, debug);
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;
1727 if (bannerIsCorrect) {
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.";
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 " 1754 broadcast (*pComm, rootRank, ptr (&bannerIsCorrect));
1762 std::invalid_argument, errMsg.str ());
1764 if (debug && myRank == rootRank) {
1765 cerr <<
"-- Reading dimensions line" << endl;
1774 readCoordDims (in, lineNumber, pBanner, pComm, tolerant, debug);
1776 if (debug && myRank == rootRank) {
1777 cerr <<
"-- Making Adder for collecting matrix data" << endl;
1783 makeAdder (pComm, pBanner, dims, tolerant, debug);
1785 if (debug && myRank == rootRank) {
1786 cerr <<
"-- Reading matrix data" << endl;
1796 int readSuccess = 1;
1797 std::ostringstream errMsg;
1798 if (myRank == rootRank) {
1803 reader_type reader (pAdder);
1806 std::pair<bool, std::vector<size_t> > results =
1807 reader.read (in, lineNumber, tolerant, debug);
1808 readSuccess = results.first ? 1 : 0;
1810 catch (std::exception& e) {
1815 broadcast (*pComm, rootRank, ptr (&readSuccess));
1825 "Failed to read the Matrix Market sparse matrix file: " 1829 if (debug && myRank == rootRank) {
1830 cerr <<
"-- Successfully read the Matrix Market data" << endl;
1843 if (debug && myRank == rootRank) {
1844 cerr <<
"-- Tolerant mode: rebroadcasting matrix dimensions" 1846 <<
"----- Dimensions before: " 1847 << dims[0] <<
" x " << dims[1]
1852 if (myRank == rootRank) {
1859 std::max (dims[0], pAdder->
getAdder()->numRows());
1860 updatedDims[1] = pAdder->
getAdder()->numCols();
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 " 1880 if (myRank == rootRank) {
1887 if (dims[0] < pAdder->
getAdder ()->numRows ()) {
1891 broadcast (*pComm, 0, ptr (&dimsMatch));
1892 if (dimsMatch == 0) {
1900 if (myRank == rootRank) {
1901 addersDims[0] = pAdder->
getAdder()->numRows();
1902 addersDims[1] = pAdder->
getAdder()->numCols();
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 " 1917 if (debug && myRank == rootRank) {
1918 cerr <<
"-- Converting matrix data into CSR format on Proc 0" << endl;
1938 int mergeAndConvertSucceeded = 1;
1939 std::ostringstream errMsg;
1941 if (myRank == rootRank) {
1944 global_ordinal_type> element_type;
1953 const size_type numRows = dims[0];
1959 const std::vector<element_type>& entries =
1963 const size_t numEntries = (size_t)entries.size();
1966 cerr <<
"----- Proc 0: Matrix has numRows=" << numRows
1967 <<
" rows and numEntries=" << numEntries
1968 <<
" entries." << endl;
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);
1983 global_ordinal_type prvRow = 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) {
2001 numEntriesPerRow[curRow]++;
2002 colInd[curPos] = curEntry.colIndex();
2003 values[curPos] = curEntry.value();
2008 rowPtr[numRows] = numEntries;
2010 catch (std::exception& e) {
2011 mergeAndConvertSucceeded = 0;
2012 errMsg <<
"Failed to merge sparse matrix entries and convert to " 2013 "CSR format: " << e.what();
2016 if (debug && mergeAndConvertSucceeded) {
2018 const size_type numRows = dims[0];
2019 const size_type maxToDisplay = 100;
2021 cerr <<
"----- Proc 0: numEntriesPerRow[0.." 2022 << (numEntriesPerRow.
size()-1) <<
"] ";
2023 if (numRows > maxToDisplay) {
2024 cerr <<
"(only showing first and last few entries) ";
2028 if (numRows > maxToDisplay) {
2029 for (size_type k = 0; k < 2; ++k) {
2030 cerr << numEntriesPerRow[k] <<
" ";
2033 for (size_type k = numRows-2; k < numRows-1; ++k) {
2034 cerr << numEntriesPerRow[k] <<
" ";
2038 for (size_type k = 0; k < numRows-1; ++k) {
2039 cerr << numEntriesPerRow[k] <<
" ";
2042 cerr << numEntriesPerRow[numRows-1];
2044 cerr <<
"]" << endl;
2046 cerr <<
"----- Proc 0: rowPtr ";
2047 if (numRows > maxToDisplay) {
2048 cerr <<
"(only showing first and last few entries) ";
2051 if (numRows > maxToDisplay) {
2052 for (size_type k = 0; k < 2; ++k) {
2053 cerr << rowPtr[k] <<
" ";
2056 for (size_type k = numRows-2; k < numRows; ++k) {
2057 cerr << rowPtr[k] <<
" ";
2061 for (size_type k = 0; k < numRows; ++k) {
2062 cerr << rowPtr[k] <<
" ";
2065 cerr << rowPtr[numRows] <<
"]" << endl;
2076 if (debug && myRank == rootRank) {
2077 cerr <<
"-- Making range, domain, and row maps" << endl;
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]);
2088 if (debug && myRank == rootRank) {
2089 cerr <<
"-- Distributing the matrix data" << endl;
2108 distribute (myNumEntriesPerRow, myRowPtr, myColInd, myValues, pRowMap,
2109 numEntriesPerRow, rowPtr, colInd, values, debug);
2111 if (debug && myRank == rootRank) {
2112 cerr <<
"-- Inserting matrix entries on each processor";
2113 if (callFillComplete) {
2114 cerr <<
" and calling fillComplete()";
2125 sparse_matrix_ptr pMatrix =
2126 makeMatrix (myNumEntriesPerRow, myRowPtr, myColInd, myValues,
2127 pRowMap, pRangeMap, pDomainMap, callFillComplete);
2132 int localIsNull = pMatrix.
is_null () ? 1 : 0;
2133 int globalIsNull = 0;
2134 reduceAll (*pComm, Teuchos::REDUCE_MAX, localIsNull, ptr (&globalIsNull));
2136 "Reader::makeMatrix() returned a null pointer on at least one " 2137 "process. Please report this bug to the Tpetra developers.");
2141 "Reader::makeMatrix() returned a null pointer. " 2142 "Please report this bug to the Tpetra developers.");
2154 if (callFillComplete) {
2155 const int numProcs = pComm->getSize ();
2157 if (extraDebug && debug) {
2159 pRangeMap->getGlobalNumElements();
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;
2170 for (
int p = 0; p < numProcs; ++p) {
2172 cerr <<
"-- Proc " << p <<
" owns " 2173 << pMatrix->getNodeNumCols() <<
" columns, and " 2174 << pMatrix->getNodeNumEntries() <<
" entries." << endl;
2181 if (debug && myRank == rootRank) {
2182 cerr <<
"-- Done creating the CrsMatrix from the Matrix Market data" 2218 static sparse_matrix_ptr
2224 const bool tolerant=
false,
2225 const bool debug=
false)
2228 using Teuchos::broadcast;
2235 const bool extraDebug =
false;
2236 const int myRank = pComm->getRank ();
2237 const int rootRank = 0;
2242 size_t lineNumber = 1;
2244 if (debug && myRank == rootRank) {
2245 cerr <<
"Matrix Market reader: readSparse:" << endl
2246 <<
"-- Reading banner line" << endl;
2261 int bannerIsCorrect = 1;
2262 std::ostringstream errMsg;
2264 if (myRank == rootRank) {
2267 pBanner = readBanner (in, lineNumber, tolerant, debug);
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;
2275 if (bannerIsCorrect) {
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.";
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 " 2302 broadcast (*pComm, rootRank, ptr (&bannerIsCorrect));
2310 std::invalid_argument, errMsg.str ());
2312 if (debug && myRank == rootRank) {
2313 cerr <<
"-- Reading dimensions line" << endl;
2322 readCoordDims (in, lineNumber, pBanner, pComm, tolerant, debug);
2324 if (debug && myRank == rootRank) {
2325 cerr <<
"-- Making Adder for collecting matrix data" << endl;
2331 makeAdder (pComm, pBanner, dims, tolerant, debug);
2333 if (debug && myRank == rootRank) {
2334 cerr <<
"-- Reading matrix data" << endl;
2344 int readSuccess = 1;
2345 std::ostringstream errMsg;
2346 if (myRank == rootRank) {
2351 reader_type reader (pAdder);
2354 std::pair<bool, std::vector<size_t> > results =
2355 reader.read (in, lineNumber, tolerant, debug);
2356 readSuccess = results.first ? 1 : 0;
2358 catch (std::exception& e) {
2363 broadcast (*pComm, rootRank, ptr (&readSuccess));
2373 "Failed to read the Matrix Market sparse matrix file: " 2377 if (debug && myRank == rootRank) {
2378 cerr <<
"-- Successfully read the Matrix Market data" << endl;
2391 if (debug && myRank == rootRank) {
2392 cerr <<
"-- Tolerant mode: rebroadcasting matrix dimensions" 2394 <<
"----- Dimensions before: " 2395 << dims[0] <<
" x " << dims[1]
2400 if (myRank == rootRank) {
2407 std::max (dims[0], pAdder->
getAdder()->numRows());
2408 updatedDims[1] = pAdder->
getAdder()->numCols();
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 " 2428 if (myRank == rootRank) {
2435 if (dims[0] < pAdder->
getAdder ()->numRows ()) {
2439 broadcast (*pComm, 0, ptr (&dimsMatch));
2440 if (dimsMatch == 0) {
2448 if (myRank == rootRank) {
2449 addersDims[0] = pAdder->
getAdder()->numRows();
2450 addersDims[1] = pAdder->
getAdder()->numCols();
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 " 2465 if (debug && myRank == rootRank) {
2466 cerr <<
"-- Converting matrix data into CSR format on Proc 0" << endl;
2486 int mergeAndConvertSucceeded = 1;
2487 std::ostringstream errMsg;
2489 if (myRank == rootRank) {
2492 global_ordinal_type> element_type;
2501 const size_type numRows = dims[0];
2507 const std::vector<element_type>& entries =
2511 const size_t numEntries = (size_t)entries.size();
2514 cerr <<
"----- Proc 0: Matrix has numRows=" << numRows
2515 <<
" rows and numEntries=" << numEntries
2516 <<
" entries." << endl;
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);
2531 global_ordinal_type prvRow = 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) {
2549 numEntriesPerRow[curRow]++;
2550 colInd[curPos] = curEntry.colIndex();
2551 values[curPos] = curEntry.value();
2556 rowPtr[numRows] = numEntries;
2558 catch (std::exception& e) {
2559 mergeAndConvertSucceeded = 0;
2560 errMsg <<
"Failed to merge sparse matrix entries and convert to " 2561 "CSR format: " << e.what();
2564 if (debug && mergeAndConvertSucceeded) {
2566 const size_type numRows = dims[0];
2567 const size_type maxToDisplay = 100;
2569 cerr <<
"----- Proc 0: numEntriesPerRow[0.." 2570 << (numEntriesPerRow.
size()-1) <<
"] ";
2571 if (numRows > maxToDisplay) {
2572 cerr <<
"(only showing first and last few entries) ";
2576 if (numRows > maxToDisplay) {
2577 for (size_type k = 0; k < 2; ++k) {
2578 cerr << numEntriesPerRow[k] <<
" ";
2581 for (size_type k = numRows-2; k < numRows-1; ++k) {
2582 cerr << numEntriesPerRow[k] <<
" ";
2586 for (size_type k = 0; k < numRows-1; ++k) {
2587 cerr << numEntriesPerRow[k] <<
" ";
2590 cerr << numEntriesPerRow[numRows-1];
2592 cerr <<
"]" << endl;
2594 cerr <<
"----- Proc 0: rowPtr ";
2595 if (numRows > maxToDisplay) {
2596 cerr <<
"(only showing first and last few entries) ";
2599 if (numRows > maxToDisplay) {
2600 for (size_type k = 0; k < 2; ++k) {
2601 cerr << rowPtr[k] <<
" ";
2604 for (size_type k = numRows-2; k < numRows; ++k) {
2605 cerr << rowPtr[k] <<
" ";
2609 for (size_type k = 0; k < numRows; ++k) {
2610 cerr << rowPtr[k] <<
" ";
2613 cerr << rowPtr[numRows] <<
"]" << endl;
2624 if (debug && myRank == rootRank) {
2625 cerr <<
"-- Making range, domain, and row maps" << endl;
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]);
2636 if (debug && myRank == rootRank) {
2637 cerr <<
"-- Distributing the matrix data" << endl;
2656 distribute (myNumEntriesPerRow, myRowPtr, myColInd, myValues, pRowMap,
2657 numEntriesPerRow, rowPtr, colInd, values, debug);
2659 if (debug && myRank == rootRank) {
2660 cerr <<
"-- Inserting matrix entries on each process " 2661 "and calling fillComplete()" << endl;
2670 sparse_matrix_ptr pMatrix =
2671 makeMatrix (myNumEntriesPerRow, myRowPtr, myColInd, myValues,
2672 pRowMap, pRangeMap, pDomainMap, constructorParams,
2673 fillCompleteParams);
2678 int localIsNull = pMatrix.
is_null () ? 1 : 0;
2679 int globalIsNull = 0;
2680 reduceAll (*pComm, Teuchos::REDUCE_MAX, localIsNull, ptr (&globalIsNull));
2682 "Reader::makeMatrix() returned a null pointer on at least one " 2683 "process. Please report this bug to the Tpetra developers.");
2687 "Reader::makeMatrix() returned a null pointer. " 2688 "Please report this bug to the Tpetra developers.");
2697 if (extraDebug && debug) {
2698 const int numProcs = pComm->getSize ();
2700 pRangeMap->getGlobalNumElements();
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;
2711 for (
int p = 0; p < numProcs; ++p) {
2713 cerr <<
"-- Proc " << p <<
" owns " 2714 << pMatrix->getNodeNumCols() <<
" columns, and " 2715 << pMatrix->getNodeNumEntries() <<
" entries." << endl;
2721 if (debug && myRank == rootRank) {
2722 cerr <<
"-- Done creating the CrsMatrix from the Matrix Market data" 2768 static sparse_matrix_ptr
2774 const bool callFillComplete=
true,
2775 const bool tolerant=
false,
2776 const bool debug=
false)
2780 using Teuchos::broadcast;
2789 const int myRank = pComm->getRank ();
2790 const int rootRank = 0;
2791 const bool extraDebug =
false;
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.");
2807 std::invalid_argument,
2808 "The specified row Map's communicator (rowMap->getComm())" 2809 "differs from the given separately supplied communicator pComm.");
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.");
2817 std::invalid_argument,
2818 "The specified domain Map's communicator (domainMap->getComm())" 2819 "differs from the given separately supplied communicator pComm.");
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.");
2827 std::invalid_argument,
2828 "The specified range Map's communicator (rangeMap->getComm())" 2829 "differs from the given separately supplied communicator pComm.");
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.");
2839 size_t lineNumber = 1;
2841 if (debug && myRank == rootRank) {
2842 cerr <<
"Matrix Market reader: readSparse:" << endl
2843 <<
"-- Reading banner line" << endl;
2858 int bannerIsCorrect = 1;
2859 std::ostringstream errMsg;
2861 if (myRank == rootRank) {
2864 pBanner = readBanner (in, lineNumber, tolerant, debug);
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;
2872 if (bannerIsCorrect) {
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.";
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 " 2899 broadcast (*pComm, rootRank, ptr (&bannerIsCorrect));
2907 std::invalid_argument, errMsg.str ());
2909 if (debug && myRank == rootRank) {
2910 cerr <<
"-- Reading dimensions line" << endl;
2919 readCoordDims (in, lineNumber, pBanner, pComm, tolerant, debug);
2921 if (debug && myRank == rootRank) {
2922 cerr <<
"-- Making Adder for collecting matrix data" << endl;
2930 makeAdder (pComm, pBanner, dims, tolerant, debug);
2932 if (debug && myRank == rootRank) {
2933 cerr <<
"-- Reading matrix data" << endl;
2943 int readSuccess = 1;
2944 std::ostringstream errMsg;
2945 if (myRank == rootRank) {
2950 reader_type reader (pAdder);
2953 std::pair<bool, std::vector<size_t> > results =
2954 reader.read (in, lineNumber, tolerant, debug);
2955 readSuccess = results.first ? 1 : 0;
2957 catch (std::exception& e) {
2962 broadcast (*pComm, rootRank, ptr (&readSuccess));
2972 "Failed to read the Matrix Market sparse matrix file: " 2976 if (debug && myRank == rootRank) {
2977 cerr <<
"-- Successfully read the Matrix Market data" << endl;
2990 if (debug && myRank == rootRank) {
2991 cerr <<
"-- Tolerant mode: rebroadcasting matrix dimensions" 2993 <<
"----- Dimensions before: " 2994 << dims[0] <<
" x " << dims[1]
2999 if (myRank == rootRank) {
3006 std::max (dims[0], pAdder->
getAdder()->numRows());
3007 updatedDims[1] = pAdder->
getAdder()->numCols();
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 " 3027 if (myRank == rootRank) {
3034 if (dims[0] < pAdder->
getAdder ()->numRows ()) {
3038 broadcast (*pComm, 0, ptr (&dimsMatch));
3039 if (dimsMatch == 0) {
3047 if (myRank == rootRank) {
3048 addersDims[0] = pAdder->
getAdder()->numRows();
3049 addersDims[1] = pAdder->
getAdder()->numCols();
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 " 3064 if (debug && myRank == rootRank) {
3065 cerr <<
"-- Converting matrix data into CSR format on Proc 0" << endl;
3085 int mergeAndConvertSucceeded = 1;
3086 std::ostringstream errMsg;
3088 if (myRank == rootRank) {
3091 global_ordinal_type> element_type;
3100 const size_type numRows = dims[0];
3106 const std::vector<element_type>& entries =
3110 const size_t numEntries = (size_t)entries.size();
3113 cerr <<
"----- Proc 0: Matrix has numRows=" << numRows
3114 <<
" rows and numEntries=" << numEntries
3115 <<
" entries." << endl;
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);
3130 global_ordinal_type prvRow = 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) {
3148 numEntriesPerRow[curRow]++;
3149 colInd[curPos] = curEntry.colIndex();
3150 values[curPos] = curEntry.value();
3155 rowPtr[numRows] = numEntries;
3157 catch (std::exception& e) {
3158 mergeAndConvertSucceeded = 0;
3159 errMsg <<
"Failed to merge sparse matrix entries and convert to " 3160 "CSR format: " << e.what();
3163 if (debug && mergeAndConvertSucceeded) {
3165 const size_type numRows = dims[0];
3166 const size_type maxToDisplay = 100;
3168 cerr <<
"----- Proc 0: numEntriesPerRow[0.." 3169 << (numEntriesPerRow.
size()-1) <<
"] ";
3170 if (numRows > maxToDisplay) {
3171 cerr <<
"(only showing first and last few entries) ";
3175 if (numRows > maxToDisplay) {
3176 for (size_type k = 0; k < 2; ++k) {
3177 cerr << numEntriesPerRow[k] <<
" ";
3180 for (size_type k = numRows-2; k < numRows-1; ++k) {
3181 cerr << numEntriesPerRow[k] <<
" ";
3185 for (size_type k = 0; k < numRows-1; ++k) {
3186 cerr << numEntriesPerRow[k] <<
" ";
3189 cerr << numEntriesPerRow[numRows-1];
3191 cerr <<
"]" << endl;
3193 cerr <<
"----- Proc 0: rowPtr ";
3194 if (numRows > maxToDisplay) {
3195 cerr <<
"(only showing first and last few entries) ";
3198 if (numRows > maxToDisplay) {
3199 for (size_type k = 0; k < 2; ++k) {
3200 cerr << rowPtr[k] <<
" ";
3203 for (size_type k = numRows-2; k < numRows; ++k) {
3204 cerr << rowPtr[k] <<
" ";
3208 for (size_type k = 0; k < numRows; ++k) {
3209 cerr << rowPtr[k] <<
" ";
3212 cerr << rowPtr[numRows] <<
"]" << endl;
3214 cerr <<
"----- Proc 0: colInd = [";
3215 for (
size_t k = 0; k < rowPtr[numRows]; ++k) {
3216 cerr << colInd[k] <<
" ";
3218 cerr <<
"]" << endl;
3232 if (debug && myRank == rootRank) {
3233 cerr <<
"-- Verifying Maps" << endl;
3237 std::invalid_argument,
3239 <<
" entries, but the matrix has a global number of rows " << dims[0]
3243 std::invalid_argument,
3245 <<
" entries, but the matrix has a global number of columns " 3250 Teuchos::getFancyOStream (Teuchos::rcpFromRef (cerr)) : null;
3257 rcp (
new sparse_matrix_type (gatherRowMap, numEntriesPerRow,
3259 if (myRank == rootRank) {
3261 cerr <<
"-- Proc 0: Filling gather matrix" << endl;
3268 const size_type myNumRows = myRows.
size ();
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];
3276 colInd.
view (curPos, curNumEntries);
3278 values.
view (curPos, curNumEntries);
3281 for (size_type k = 0; k < curNumEntries; ++k) {
3282 curColInd[k] += indexBase;
3289 if (curNumEntries > 0) {
3290 A_proc0->insertGlobalValues (myRows[i], curColInd, curValues);
3296 numEntriesPerRow = null;
3304 A =
rcp (
new sparse_matrix_type (rowMap, 0));
3306 A =
rcp (
new sparse_matrix_type (rowMap, colMap, 0));
3309 export_type exp (gatherRowMap, rowMap);
3310 A->doExport (*A_proc0, exp,
INSERT);
3312 if (callFillComplete) {
3313 A->fillComplete (domainMap, rangeMap);
3325 if (callFillComplete) {
3326 const int numProcs = pComm->getSize ();
3328 if (extraDebug && debug) {
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;
3339 for (
int p = 0; p < numProcs; ++p) {
3341 cerr <<
"-- Proc " << p <<
" owns " 3342 << A->getNodeNumCols() <<
" columns, and " 3343 << A->getNodeNumEntries() <<
" entries." << endl;
3350 if (debug && myRank == rootRank) {
3351 cerr <<
"-- Done creating the CrsMatrix from the Matrix Market data" 3392 const bool tolerant=
false,
3393 const bool debug=
false)
3397 in.open (filename.c_str ());
3399 return readDense (in, comm, node, map, tolerant, debug);
3474 const bool tolerant=
false,
3475 const bool debug=
false)
3478 Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr));
3479 return readDenseImpl<scalar_type> (in, comm, node, map,
3480 err, tolerant, debug);
3508 const bool tolerant=
false,
3509 const bool debug=
false)
3511 using Teuchos::inOutArg;
3512 using Teuchos::broadcast;
3517 in.open (filename.c_str ());
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);
3531 template<
class MultiVectorScalarType>
3536 readDenseImpl (std::istream& in,
3541 const bool tolerant=
false,
3542 const bool debug=
false)
3545 using Teuchos::MatrixMarket::checkCommentLine;
3547 using Teuchos::broadcast;
3548 using Teuchos::outArg;
3550 typedef MultiVectorScalarType ST;
3551 typedef local_ordinal_type LO;
3552 typedef global_ordinal_type GO;
3553 typedef node_type NT;
3555 typedef typename STS::magnitudeType MT;
3561 const int myRank = comm->
getRank ();
3567 *err << myRank <<
": readDenseImpl" << endl;
3603 size_t lineNumber = 1;
3606 std::ostringstream exMsg;
3607 int localBannerReadSuccess = 1;
3608 int localDimsReadSuccess = 1;
3613 *err << myRank <<
": readDenseImpl: Reading banner line (dense)" << endl;
3621 pBanner = readBanner (in, lineNumber, tolerant, debug);
3622 }
catch (std::exception& e) {
3624 localBannerReadSuccess = 0;
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 " 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;
3644 dims[2] = encodeDataType (pBanner->dataType ());
3650 if (localBannerReadSuccess) {
3652 *err << myRank <<
": readDenseImpl: Reading dimensions line (dense)" << endl;
3661 bool commentLine =
true;
3663 while (commentLine) {
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;
3674 if (getline (in, line)) {
3681 size_t start = 0, size = 0;
3682 commentLine = checkCommentLine (line, start, size, lineNumber, tolerant);
3689 std::istringstream istr (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;
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;
3707 dims[0] = theNumRows;
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;
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;
3722 dims[1] = theNumCols;
3735 bannerDimsReadResult[0] = dims[0];
3736 bannerDimsReadResult[1] = dims[1];
3737 bannerDimsReadResult[2] = dims[2];
3738 bannerDimsReadResult[3] = localBannerReadSuccess;
3739 bannerDimsReadResult[4] = localDimsReadSuccess;
3743 broadcast (*comm, 0, bannerDimsReadResult);
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 ());
3752 dims[0] = bannerDimsReadResult[0];
3753 dims[1] = bannerDimsReadResult[1];
3754 dims[2] = bannerDimsReadResult[2];
3759 const size_t numCols =
static_cast<size_t> (dims[1]);
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);
3774 proc0Map = computeGatherMap<map_type> (map, err, debug);
3778 RCP<MV> X = createMultiVector<ST, LO, GO, NT> (proc0Map, numCols);
3784 int localReadDataSuccess = 1;
3788 *err << myRank <<
": readDenseImpl: Reading matrix data (dense)" 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 " 3807 as<global_size_t> (X_view.size ()) < numRows * numCols,
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 ();
3820 const bool isComplex = (dims[2] == 1);
3821 size_type count = 0, curRow = 0, curCol = 0;
3824 while (getline (in, line)) {
3828 size_t start = 0, size = 0;
3829 const bool commentLine =
3830 checkCommentLine (line, start, size, lineNumber, tolerant);
3831 if (! commentLine) {
3837 if (count >= X_view.size()) {
3843 count >= X_view.size(),
3845 "The Matrix Market input stream has more data in it than " 3846 "its metadata reported. Current line number is " 3847 << lineNumber <<
".");
3856 const size_t pos = line.substr (start, size).find (
':');
3857 if (pos != std::string::npos) {
3861 std::istringstream istr (line.substr (start, size));
3865 if (istr.eof() || istr.fail()) {
3873 ! tolerant && (istr.eof() || istr.fail()),
3875 "Line " << lineNumber <<
" of the Matrix Market file is " 3876 "empty, or we cannot read from it for some other reason.");
3879 ST val = STS::zero();
3882 MT real = STM::zero(), imag = STM::zero();
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 " 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.");
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.");
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.");
3935 if (istr.fail() && tolerant) {
3942 ! tolerant && istr.fail(), std::runtime_error,
3943 "Failed to read matrix data from line " << lineNumber
3944 <<
" of the Matrix Market file.");
3947 Teuchos::MatrixMarket::details::assignScalar<ST> (val, real, imag);
3949 curRow = count % numRows;
3950 curCol = count / numRows;
3951 X_view[curRow + curCol*stride] = val;
3957 ! tolerant && static_cast<global_size_t> (count) < numRows * numCols,
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) {
3965 localReadDataSuccess = 0;
3970 *err << myRank <<
": readDenseImpl: done reading data" << endl;
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 ());
3989 *err << myRank <<
": readDenseImpl: done" << endl;
3998 *err << myRank <<
": readDenseImpl: Creating target MV" << endl;
4002 RCP<MV> Y = createMultiVector<ST, LO, GO, NT> (map, numCols);
4005 *err << myRank <<
": readDenseImpl: Creating Export" << endl;
4014 *err << myRank <<
": readDenseImpl: Exporting" << endl;
4017 Y->doExport (*X, exporter,
INSERT);
4023 *err << myRank <<
": readDenseImpl: done" << endl;
4058 const bool tolerant=
false,
4059 const bool debug=
false)
4062 Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr));
4063 return readMap (in, comm, node, err, tolerant, debug);
4096 const bool tolerant=
false,
4097 const bool debug=
false)
4103 using Teuchos::broadcast;
4106 using Teuchos::inOutArg;
4107 using Teuchos::outArg;
4109 using Teuchos::REDUCE_MIN;
4113 typedef ptrdiff_t int_type;
4114 typedef local_ordinal_type LO;
4115 typedef global_ordinal_type GO;
4116 typedef node_type NT;
4119 const int numProcs = comm->
getSize ();
4120 const int myRank = comm->
getRank ();
4126 *err << myRank <<
": readMap: " << endl;
4132 int readSuccess = 1;
4133 std::ostringstream exMsg;
4149 data = readDenseImpl<int_type> (in, proc0Comm, node, dataMap,
4150 err, tolerant, debug);
4152 }
catch (std::exception& e) {
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: " 4165 *err << myRank <<
": readMap: Successfully read data" << endl;
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.");
4185 const size_type globalNumGIDs = GIDs.
size ();
4186 gidsPerProcess = arcp<size_type> (numProcs);
4187 std::fill (gidsPerProcess.
begin (), gidsPerProcess.
end (), 0);
4193 int numTooBigPids = 0;
4194 int pidsOutOfOrder = 0;
4196 startIndices = arcp<size_type> (numProcs+1);
4197 std::fill (startIndices.
begin (), startIndices.
end (), 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]);
4204 std::ostringstream os;
4205 os <<
"0: readMap: " 4209 <<
", lastPid: " << lastPid <<
"}" << endl;
4216 else if (pid >= numProcs) {
4220 else if (pid < lastPid) {
4227 ++gidsPerProcess[pid];
4228 if (k == 0 || GIDs[k] < indexBase) {
4229 indexBase = GIDs[k];
4234 if (pid > lastPid) {
4237 for (
int p = lastPid+1; p <= pid; ++p) {
4238 startIndices[p] = k;
4244 startIndices[numProcs] = globalNumGIDs;
4247 (numNegPids == 0 && numTooBigPids == 0 && pidsOutOfOrder == 0) ?
4251 *err <<
"0: readMap: The Map's data are valid" << endl;
4253 *err <<
"0: readMap: The Map's data are INVALID" << endl;
4256 std::ostringstream os;
4257 os <<
"startIndices: " <<
toString (startIndices) << endl
4258 <<
"gidsPerProcess: " <<
toString (gidsPerProcess ()) << endl;
4261 if (readSuccess == 0) {
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;
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;
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." 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;
4287 exMsg <<
" - " <<
toString (badRows) << endl;
4303 if (
typeid (GO) ==
typeid (int_type)) {
4306 const int_type* myGidsRaw = myGidsAsIntType.
getRawPtr ();
4307 myGids = arcp<const GO> (
reinterpret_cast<const GO*
> (myGidsRaw),
4308 0, gidsPerProcess[0],
false);
4313 for (size_type k = 0; k < myGidsAsIntType.
size (); ++k) {
4314 myGidsAsGO[k] = as<GO> (myGidsAsIntType[k]);
4318 }
catch (std::exception& e) {
4324 broadcast<int, int> (*comm, 0, inOutArg (readSuccess));
4326 readSuccess == 0, std::runtime_error,
4327 "Tpetra::MatrixMarket::readMap: The Map's data were invalid: " 4349 for (
int p = 1; p < numProcs; ++p) {
4351 sendBuf[0] = gidsPerProcess[p];
4352 sendBuf[1] = as<size_type> (indexBase);
4353 countRequests[p-1] = isend (*comm, sendBuf.
getConst (), p);
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]);
4364 dataRequests.push_back (isend (*comm, gidsToSend.
getConst (), p));
4369 *err <<
"0: readMap: waiting on count sends" << endl;
4371 waitAll (*comm, countRequests ());
4374 *err <<
"0: readMap: waiting on GID sends" << endl;
4376 waitAll (*comm, dataRequests ());
4379 const int rootRank = 0;
4381 *err << myRank <<
": readMap: receiving GID count" << endl;
4388 gidCountAndMinAllGid[0] = 0;
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]);
4395 *err << myRank <<
": readMap: receiving GID list" << endl;
4398 receive (*comm, rootRank, as<int> (gidCount), myGidsCopy.
getRawPtr ());
4404 *err << myRank <<
": readMap: Done distributing GID list" << endl;
4407 for (
int p = 0; p < numProcs; ++p) {
4409 std::ostringstream os;
4410 os <<
"Proc " << myRank <<
": GIDs: " <<
toString (myGids ())
4421 *err << myRank <<
": readMap: creating Map" << endl;
4430 *err << myRank <<
": readMap: done" << endl;
4451 encodeDataType (
const std::string& dataType)
4453 if (dataType ==
"real" || dataType ==
"integer") {
4455 }
else if (dataType ==
"complex") {
4457 }
else if (dataType ==
"pattern") {
4464 "Unrecognized Matrix Market data type \"" << dataType
4465 <<
"\". We should never get here. " 4466 "Please report this bug to the Tpetra developers.");
4510 template<
class SparseMatrixType>
4577 const std::string& matrixName,
4578 const std::string& matrixDescription,
4579 const bool debug=
false)
4581 const int myRank = Teuchos::rank (*(pMatrix->getComm()));
4585 if (myRank == 0) out.open (filename.c_str());
4586 writeSparse (out, pMatrix, matrixName, matrixDescription, debug);
4615 const bool debug=
false)
4617 writeSparseFile (filename, pMatrix,
"",
"", debug);
4655 const std::string& matrixName,
4656 const std::string& matrixDescription,
4657 const bool debug=
false)
4661 using Teuchos::getFancyOStream;
4662 using Teuchos::null;
4664 using Teuchos::rcpFromRef;
4667 typedef scalar_type ST;
4668 typedef local_ordinal_type LO;
4669 typedef global_ordinal_type GO;
4682 const int myRank = comm->getRank ();
4685 debug ? getFancyOStream (rcpFromRef (std::cerr)) : null;
4687 std::ostringstream os;
4688 os << myRank <<
": writeSparse" << endl;
4691 os <<
"-- " << myRank <<
": past barrier" << endl;
4696 const bool debugPrint = debug && myRank == 0;
4703 const global_size_t numRows = rangeMap->getGlobalNumElements ();
4704 const global_size_t numCols = domainMap->getGlobalNumElements ();
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
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;
4722 const size_t localNumRows = (myRank == 0) ? numRows : 0;
4725 std::ostringstream os;
4726 os <<
"-- " << myRank <<
": making gatherRowMap" << endl;
4730 computeGatherMap (rowMap, err, debug);
4738 const size_t localNumCols = (myRank == 0) ? numCols : 0;
4740 computeGatherMap (colMap, err, debug);
4744 import_type importer (rowMap, gatherRowMap);
4750 rcp (
new sparse_matrix_type (gatherRowMap, gatherColMap,
4751 static_cast<size_t> (0)));
4753 newMatrix->doImport (*pMatrix, importer,
INSERT);
4759 rcp (
new map_type (numCols, localNumCols,
4760 domainMap->getIndexBase (),
4763 rcp (
new map_type (numRows, localNumRows,
4764 rangeMap->getIndexBase (),
4766 newMatrix->fillComplete (gatherDomainMap, gatherRangeMap);
4770 cerr <<
"-- Output sparse matrix is:" 4771 <<
"---- " << newMatrix->getRangeMap ()->getGlobalNumElements ()
4773 << newMatrix->getDomainMap ()->getGlobalNumElements ()
4775 << newMatrix->getGlobalNumEntries () <<
" entries;" << endl
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;
4802 out <<
"%%MatrixMarket matrix coordinate " 4803 << (STS::isComplex ?
"complex" :
"real")
4804 <<
" general" << endl;
4807 if (matrixName !=
"") {
4808 printAsComment (out, matrixName);
4810 if (matrixDescription !=
"") {
4811 printAsComment (out, matrixDescription);
4821 out << newMatrix->getRangeMap ()->getGlobalNumElements () <<
" " 4822 << newMatrix->getDomainMap ()->getGlobalNumElements () <<
" " 4823 << newMatrix->getGlobalNumEntries () << endl;
4828 const GO rowIndexBase = gatherRowMap->getIndexBase ();
4829 const GO colIndexBase = newMatrix->getColMap()->getIndexBase ();
4837 if (newMatrix->isGloballyIndexed()) {
4840 const GO minAllGlobalIndex = gatherRowMap->getMinAllGlobalIndex ();
4841 const GO maxAllGlobalIndex = gatherRowMap->getMaxAllGlobalIndex ();
4842 for (GO globalRowIndex = minAllGlobalIndex;
4843 globalRowIndex <= maxAllGlobalIndex;
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;
4855 out << (globalRowIndex + 1 - rowIndexBase) <<
" " 4856 << (globalColIndex + 1 - colIndexBase) <<
" ";
4857 if (STS::isComplex) {
4858 out << STS::real (*valIter) <<
" " << STS::imag (*valIter);
4867 for (LO localRowIndex = gatherRowMap->getMinLocalIndex();
4868 localRowIndex <= gatherRowMap->getMaxLocalIndex();
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.");
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) {
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.");
4896 out << (globalRowIndex + 1 - rowIndexBase) <<
" " 4897 << (globalColIndex + 1 - colIndexBase) <<
" ";
4898 if (STS::isComplex) {
4899 out << STS::real (*valIter) <<
" " << STS::imag (*valIter);
4935 const bool debug=
false)
4937 writeSparse (out, pMatrix,
"",
"", debug);
4969 const std::string& matrixName,
4970 const std::string& matrixDescription)
4972 const int myRank = Teuchos::rank (*(X->getMap()->getComm()));
4976 out.open (filename.c_str());
4978 writeDense (out, X, matrixName, matrixDescription);
5006 writeDenseFile (filename, X,
"",
"");
5038 const std::string& matrixName,
5039 const std::string& matrixDescription)
5041 writeDenseImpl<scalar_type> (out, *X, matrixName, matrixDescription);
5066 writeDense (out, X,
"",
"");
5071 writeMap (std::ostream& out,
const map_type& map,
const bool debug=
false)
5074 Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr));
5075 writeMap (out, map, err, debug);
5088 const map_type& map,
5090 const bool debug=
false)
5095 using Teuchos::rcp_const_cast;
5096 using Teuchos::rcpFromRef;
5100 typedef local_ordinal_type LO;
5101 typedef global_ordinal_type GO;
5102 typedef node_type NT;
5103 typedef int pid_type;
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) <<
".");
5120 const int myRank = map.
getComm ()->getRank ();
5126 *err << myRank <<
": writeMap" << endl;
5135 MV data (rcpFromRef (map), 2);
5145 for (int_type k = 0; k < gidList.
size (); ++k) {
5146 V0[k] = as<int_type> (gidList[k]);
5151 *err << myRank <<
": writeMap: Done with column 0" << endl;
5160 for (int_type k = 0; k < gidList.
size (); ++k) {
5161 V1[k] = as<int_type> (myRank);
5166 *err << myRank <<
": writeMap: Done with column 1" << endl;
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;
5176 desc.str (), err, debug);
5182 *err << myRank <<
": writeMap: Done" << endl;
5192 const map_type& map)
5194 const int myRank = map.
getComm ()->getRank ();
5197 out.open (filename.c_str());
5199 writeMap (out, map);
5237 template<
class MultiVectorScalarType>
5239 writeDenseImpl (std::ostream& out,
5241 const std::string& matrixName,
5242 const std::string& matrixDescription,
5244 const bool debug=
false)
5250 using Teuchos::rcp_const_cast;
5251 using Teuchos::rcp_dynamic_cast;
5254 typedef MultiVectorScalarType ST;
5255 typedef local_ordinal_type LO;
5256 typedef global_ordinal_type GO;
5257 typedef node_type NT;
5264 const int myRank = comm->getRank ();
5270 std::ostringstream os;
5271 os << myRank <<
": writeDenseImpl" << endl;
5289 std::ostringstream os;
5290 os << myRank <<
": writeDenseImpl: Computing gather Map" << endl;
5296 RCP<NT> node = map->getNode();
5298 computeGatherMap<map_type> (map, err, debug);
5301 std::ostringstream os;
5302 os << myRank <<
": writeDenseImpl: Computing Import" << endl;
5313 std::ostringstream os;
5314 os << myRank <<
": writeDenseImpl: Creating target MultiVector" << endl;
5319 RCP<MV> Y = createMultiVector<ST, LO, GO, NT> (gatherMap, numCols);
5322 std::ostringstream os;
5323 os << myRank <<
": writeDenseImpl: Doing Import" << endl;
5328 Y->doImport (X, importer,
INSERT);
5331 std::ostringstream os;
5332 os << myRank <<
": writeDenseImpl: Writing data to out" << endl;
5339 std::ostringstream exMsg;
5340 int localWriteSuccess = 1;
5343 std::string dataType;
5344 if (STS::isComplex) {
5345 dataType =
"complex";
5346 }
else if (STS::isOrdinal) {
5347 dataType =
"integer";
5354 out <<
"%%MatrixMarket matrix array " 5355 << dataType <<
" general" << endl;
5358 if (matrixName !=
"") {
5359 printAsComment (out, matrixName);
5361 if (matrixDescription !=
"") {
5362 printAsComment (out, matrixDescription);
5365 out << numRows <<
" " << numCols << endl;
5371 as<global_size_t> (Y_view.
size ()) < numCols, std::logic_error,
5372 "Y_view has size " << Y_view.
size () <<
" < numCols = " 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 <<
".");
5383 const ST Y_ij = Y_j[i];
5384 if (STS::isComplex) {
5385 out << STS::real (Y_ij) <<
" " << STS::imag (Y_ij) << endl;
5387 out << Y_ij << endl;
5391 }
catch (std::exception& e) {
5393 localWriteSuccess = 0;
5400 int globalWriteSuccess = localWriteSuccess;
5401 broadcast (*comm, 0, outArg (globalWriteSuccess));
5403 globalWriteSuccess == 0, std::runtime_error,
5404 "Failed to write data: " << exMsg.str ());
5406 if (! err.is_null ()) {
5410 *err << myRank <<
": writeDenseImpl: done" << endl;
5412 if (! err.is_null ()) {
5441 printAsComment (std::ostream& out,
const std::string& str)
5444 std::istringstream istream (str);
5447 while (getline (istream, line)) {
5448 if (! line.empty()) {
5451 if (line[0] ==
'%') {
5452 out << line << endl;
5455 out <<
"%% " << line << endl;
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.
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
Teuchos::RCP< AdderType > getAdder() const
SparseMatrixType::local_ordinal_type local_ordinal_type
Only used to define map_type.
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)
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.
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.
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.
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' 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.
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.
const Teuchos::RCP< Node > & getNode() const
Get this Map's Node object.
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)
ArrayView< T > view(size_type lowerOffset, size_type size) const