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"
100 namespace MatrixMarket {
107 template<
class IntType> MPI_Datatype getMpiDatatype () {
108 TEUCHOS_TEST_FOR_EXCEPTION(
true, std::logic_error,
"Not implemented for IntType != int or long");
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[],
120 const Teuchos::RCP<
const Teuchos::Comm<int> >& comm)
124 using Teuchos::rcp_dynamic_cast;
125 using Teuchos::MpiComm;
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);
136 TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
"MPI_Reduce failed");
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,
149 const int root,
const Teuchos::RCP<
const Teuchos::Comm<int> >& comm)
152 using Teuchos::rcp_dynamic_cast;
154 using Teuchos::MpiComm;
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),
170 TEUCHOS_TEST_FOR_EXCEPTION(
171 err != MPI_SUCCESS, std::runtime_error,
"MPI_Gather failed");
176 TEUCHOS_TEST_FOR_EXCEPTION(
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[],
191 const int root,
const Teuchos::RCP<
const Teuchos::Comm<int> >& comm)
194 using Teuchos::rcp_dynamic_cast;
196 using Teuchos::MpiComm;
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),
215 TEUCHOS_TEST_FOR_EXCEPTION(
216 err != MPI_SUCCESS, std::runtime_error,
"MPI_Gatherv failed");
220 TEUCHOS_TEST_FOR_EXCEPTION(
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>
237 Teuchos::RCP<const MapType>
238 computeGatherMap (Teuchos::RCP<const MapType> map,
239 const Teuchos::RCP<Teuchos::FancyOStream>& err,
240 const bool debug=
false)
244 using Teuchos::Array;
245 using Teuchos::ArrayRCP;
246 using Teuchos::ArrayView;
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 ();
259 if (! err.is_null ()) {
263 *err << myRank <<
": computeGatherMap:" << endl;
265 if (! err.is_null ()) {
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 ());
307 Array<int> recvCounts (numProcs);
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;
329 Array<int> displs (numProcs, 0);
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 ();
348 const global_size_t INVALID = Teuchos::OrdinalTraits<global_size_t>::invalid ();
349 gatherMap = rcp (
new MapType (INVALID, allElts,
350 oneToOneMap->getIndexBase (),
351 comm, map->getNode ()));
353 if (! err.is_null ()) {
357 *err << myRank <<
": computeGatherMap: done" << endl;
359 if (! err.is_null ()) {
429 template<
class SparseMatrixType>
434 typedef RCP<sparse_matrix_type> sparse_matrix_ptr;
449 typedef typename SparseMatrixType::global_ordinal_type
461 typedef RCP<node_type> node_ptr;
462 typedef Comm<int> comm_type;
463 typedef RCP<const comm_type> comm_ptr;
465 typedef RCP<const map_type> map_ptr;
470 typedef typename ArrayRCP<global_ordinal_type>::size_type size_type;
483 static RCP<const map_type>
484 makeRangeMap (
const RCP<const comm_type>& pComm,
485 const RCP<node_type>& pNode,
489 return rcp (
new map_type (static_cast<global_size_t> (numRows),
490 static_cast<global_ordinal_type> (0),
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,
530 if (pRowMap.is_null()) {
531 return rcp (
new map_type (static_cast<global_size_t> (numRows),
532 static_cast<global_ordinal_type> (0),
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()
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 "
569 static Teuchos::RCP<const map_type>
570 makeDomainMap (
const Teuchos::RCP<const map_type>& pRangeMap,
579 if (numRows == numCols) {
582 return createUniformContigMapWithNode<LO,GO,Node> (numCols,
583 pRangeMap->getComm (),
584 pRangeMap->getNode ());
661 distribute (ArrayRCP<size_t>& myNumEntriesPerRow,
662 ArrayRCP<size_t>& myRowPtr,
663 ArrayRCP<global_ordinal_type>& myColInd,
664 ArrayRCP<scalar_type>& myValues,
665 const RCP<const map_type>& pRowMap,
666 ArrayRCP<size_t>& numEntriesPerRow,
667 ArrayRCP<size_t>& rowPtr,
668 ArrayRCP<global_ordinal_type>& colInd,
669 ArrayRCP<scalar_type>& values,
670 const bool debug=
false)
673 using Teuchos::CommRequest;
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;
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(),
695 "pRowMap->getNodeElementList().size() = "
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,
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),
722 myRows.getRawPtr(), rootRank);
732 receive (*pComm, rootRank,
733 static_cast<int> (myNumRows),
734 myNumEntriesPerRow.getRawPtr());
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),
753 myColInd.getRawPtr());
754 receive (*pComm, rootRank,
755 static_cast<int> (myNumEntries),
756 myValues.getRawPtr());
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];
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) {
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);
799 for (size_type k = 0; k < myNumRows;
800 myCurPos += myNumEntriesPerRow[k], ++k) {
802 const GO myRow = myRows[k];
803 const size_t curPos = rowPtr[myRow];
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());
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());
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) {
842 ArrayRCP<GO> theirRows = arcp<GO> (theirNumRows);
843 receive (*pComm, p, as<int> (theirNumRows),
844 theirRows.getRawPtr ());
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;
862 if (! theirRowsValid) {
863 TEUCHOS_TEST_FOR_EXCEPTION(
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) <<
"].");
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]];
893 send (*pComm, static_cast<int> (theirNumRows),
894 theirNumEntriesPerRow.getRawPtr(), p);
898 std::accumulate (theirNumEntriesPerRow.begin(),
899 theirNumEntriesPerRow.end(), 0);
902 cerr <<
"-- Proc 0: Proc " << p <<
" owns "
903 << theirNumEntries <<
" entries" << endl;
908 if (theirNumEntries == 0) {
917 ArrayRCP<GO> theirColInd (theirNumEntries);
918 ArrayRCP<scalar_type> theirValues (theirNumEntries);
926 for (size_type k = 0; k < theirNumRows;
927 theirCurPos += theirNumEntriesPerRow[k], k++) {
929 const GO theirRow = theirRows[k];
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());
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());
955 send (*pComm, static_cast<int> (theirNumEntries),
956 theirColInd.getRawPtr(), p);
957 send (*pComm, static_cast<int> (theirNumEntries),
958 theirValues.getRawPtr(), p);
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
1019 makeMatrix (ArrayRCP<size_t>& myNumEntriesPerRow,
1020 ArrayRCP<size_t>& myRowPtr,
1021 ArrayRCP<global_ordinal_type>& myColInd,
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)
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.");
1056 sparse_matrix_ptr A =
1062 ArrayView<const GO> myRows = pRowMap->getNodeElementList ();
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];
1070 ArrayView<GO> curColInd = myColInd.view (myCurPos, curNumEntries);
1071 ArrayView<scalar_type> curValues = myValues.view (myCurPos, curNumEntries);
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
1103 makeMatrix (ArrayRCP<size_t>& myNumEntriesPerRow,
1104 ArrayRCP<size_t>& myRowPtr,
1105 ArrayRCP<global_ordinal_type>& myColInd,
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)
1123 TEUCHOS_TEST_FOR_EXCEPTION(
1124 myRowPtr.is_null(), std::logic_error,
1125 "makeMatrix: myRowPtr array is null. "
1126 "Please report this bug to the Tpetra developers.");
1127 TEUCHOS_TEST_FOR_EXCEPTION(
1128 pDomainMap.is_null(), std::logic_error,
1129 "makeMatrix: domain map is null. "
1130 "Please report this bug to the Tpetra developers.");
1131 TEUCHOS_TEST_FOR_EXCEPTION(
1132 pRangeMap.is_null(), std::logic_error,
1133 "makeMatrix: range map is null. "
1134 "Please report this bug to the Tpetra developers.");
1135 TEUCHOS_TEST_FOR_EXCEPTION(
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 =
1151 ArrayView<const GO> myRows = pRowMap->getNodeElementList();
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];
1159 ArrayView<GO> curColInd = myColInd.view (myCurPos, curNumEntries);
1160 ArrayView<scalar_type> curValues = myValues.view (myCurPos, curNumEntries);
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
1188 makeMatrix (Teuchos::ArrayRCP<size_t>& myNumEntriesPerRow,
1189 Teuchos::ArrayRCP<size_t>& myRowPtr,
1190 Teuchos::ArrayRCP<global_ordinal_type>& myColInd,
1191 Teuchos::ArrayRCP<scalar_type>& myValues,
1192 const Teuchos::RCP<const map_type>& rowMap,
1193 Teuchos::RCP<const map_type>& colMap,
1194 const Teuchos::RCP<const map_type>& domainMap,
1195 const Teuchos::RCP<const map_type>& rangeMap,
1196 const bool callFillComplete =
true)
1198 using Teuchos::ArrayView;
1200 using Teuchos::null;
1204 typedef typename ArrayView<const GO>::size_type size_type;
1210 RCP<sparse_matrix_type> A;
1211 if (colMap.is_null ()) {
1219 ArrayView<const GO> myRows = rowMap->getNodeElementList ();
1220 const size_type myNumRows = myRows.size ();
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);
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);
1249 if (colMap.is_null ()) {
1250 colMap = A->getColMap ();
1274 static RCP<const Teuchos::MatrixMarket::Banner>
1275 readBanner (std::istream& in,
1277 const bool tolerant=
false,
1278 const bool debug=
false)
1280 using Teuchos::MatrixMarket::Banner;
1283 typedef Teuchos::ScalarTraits<scalar_type> STS;
1285 RCP<Banner> pBanner;
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.");
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): "
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\".");
1311 TEUCHOS_TEST_FOR_EXCEPTION(
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 \""
1317 << Teuchos::TypeNameTraits<scalar_type>::name() <<
"\".");
1318 TEUCHOS_TEST_FOR_EXCEPTION(
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.");
1353 static Tuple<global_ordinal_type, 3>
1354 readCoordDims (std::istream& in,
1356 const RCP<const Teuchos::MatrixMarket::Banner>& pBanner,
1357 const comm_ptr& pComm,
1358 const bool tolerant =
false,
1359 const bool debug =
false)
1361 using Teuchos::MatrixMarket::readCoordinateDimensions;
1366 Tuple<global_ordinal_type, 3> dims;
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.");
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);
1410 TEUCHOS_TEST_FOR_EXCEPTION(
true, std::invalid_argument,
1411 "Error reading Matrix Market sparse matrix: failed to read "
1412 "coordinate matrix dimensions.");
1427 typedef Teuchos::MatrixMarket::SymmetrizingAdder<Teuchos::MatrixMarket::Raw::Adder<scalar_type, global_ordinal_type> > adder_type;
1454 static RCP<adder_type>
1455 makeAdder (
const RCP<
const Comm<int> >& pComm,
1456 RCP<const Teuchos::MatrixMarket::Banner>& pBanner,
1457 const Tuple<global_ordinal_type, 3>& dims,
1458 const bool tolerant=
false,
1459 const bool debug=
false)
1461 if (pComm->getRank() == 0) {
1462 typedef Teuchos::MatrixMarket::Raw::Adder<scalar_type, global_ordinal_type> raw_adder_type;
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()));
1498 static sparse_matrix_ptr
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)
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
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)
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
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)
1611 using Teuchos::broadcast;
1612 using Teuchos::outArg;
1613 TEUCHOS_TEST_FOR_EXCEPTION(
1614 rowMap.is_null (), std::invalid_argument,
1615 "Row Map must be nonnull.");
1617 RCP<const Comm<int> > comm = rowMap->getComm ();
1618 RCP<node_type> node = rowMap->getNode ();
1619 const int myRank = comm->getRank ();
1629 in.open (filename.c_str ());
1636 broadcast<int, int> (*comm, 0, outArg (opened));
1637 TEUCHOS_TEST_FOR_EXCEPTION(
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
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)
1679 using Teuchos::MatrixMarket::Banner;
1680 using Teuchos::broadcast;
1682 using Teuchos::reduceAll;
1685 typedef Teuchos::ScalarTraits<scalar_type> STS;
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;
1707 RCP<const Banner> pBanner;
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));
1761 TEUCHOS_TEST_FOR_EXCEPTION(bannerIsCorrect == 0,
1762 std::invalid_argument, errMsg.str ());
1764 if (debug && myRank == rootRank) {
1765 cerr <<
"-- Reading dimensions line" << endl;
1773 Tuple<global_ordinal_type, 3> dims =
1774 readCoordDims (in, lineNumber, pBanner, pComm, tolerant, debug);
1776 if (debug && myRank == rootRank) {
1777 cerr <<
"-- Making Adder for collecting matrix data" << endl;
1782 RCP<adder_type> pAdder =
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) {
1801 typedef Teuchos::MatrixMarket::CoordDataReader<adder_type,
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));
1824 TEUCHOS_TEST_FOR_EXCEPTION(readSuccess == 0, std::runtime_error,
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]
1851 Tuple<global_ordinal_type, 2> updatedDims;
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) {
1899 Tuple<global_ordinal_type, 2> addersDims;
1900 if (myRank == rootRank) {
1901 addersDims[0] = pAdder->getAdder()->numRows();
1902 addersDims[1] = pAdder->getAdder()->numCols();
1904 broadcast (*pComm, 0, addersDims);
1905 TEUCHOS_TEST_FOR_EXCEPTION(
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;
1930 ArrayRCP<size_t> numEntriesPerRow;
1931 ArrayRCP<size_t> rowPtr;
1932 ArrayRCP<global_ordinal_type> colInd;
1933 ArrayRCP<scalar_type> values;
1938 int mergeAndConvertSucceeded = 1;
1939 std::ostringstream errMsg;
1941 if (myRank == rootRank) {
1943 typedef Teuchos::MatrixMarket::Raw::Element<
scalar_type,
1953 const size_type numRows = dims[0];
1956 pAdder->getAdder()->merge ();
1959 const std::vector<element_type>& entries =
1960 pAdder->getAdder()->getEntries();
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);
1986 for (curPos = 0; curPos < numEntries; ++curPos) {
1987 const element_type& curEntry = entries[curPos];
1989 TEUCHOS_TEST_FOR_EXCEPTION(
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) {
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;
2103 ArrayRCP<size_t> myNumEntriesPerRow;
2104 ArrayRCP<size_t> myRowPtr;
2105 ArrayRCP<global_ordinal_type> myColInd;
2106 ArrayRCP<scalar_type> myValues;
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));
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.");
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.");
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
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)
2227 using Teuchos::MatrixMarket::Banner;
2228 using Teuchos::broadcast;
2230 using Teuchos::reduceAll;
2233 typedef Teuchos::ScalarTraits<scalar_type> STS;
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;
2255 RCP<const Banner> pBanner;
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));
2309 TEUCHOS_TEST_FOR_EXCEPTION(bannerIsCorrect == 0,
2310 std::invalid_argument, errMsg.str ());
2312 if (debug && myRank == rootRank) {
2313 cerr <<
"-- Reading dimensions line" << endl;
2321 Tuple<global_ordinal_type, 3> dims =
2322 readCoordDims (in, lineNumber, pBanner, pComm, tolerant, debug);
2324 if (debug && myRank == rootRank) {
2325 cerr <<
"-- Making Adder for collecting matrix data" << endl;
2330 RCP<adder_type> pAdder =
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) {
2349 typedef Teuchos::MatrixMarket::CoordDataReader<adder_type,
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));
2372 TEUCHOS_TEST_FOR_EXCEPTION(readSuccess == 0, std::runtime_error,
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]
2399 Tuple<global_ordinal_type, 2> updatedDims;
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) {
2447 Tuple<global_ordinal_type, 2> addersDims;
2448 if (myRank == rootRank) {
2449 addersDims[0] = pAdder->getAdder()->numRows();
2450 addersDims[1] = pAdder->getAdder()->numCols();
2452 broadcast (*pComm, 0, addersDims);
2453 TEUCHOS_TEST_FOR_EXCEPTION(
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;
2478 ArrayRCP<size_t> numEntriesPerRow;
2479 ArrayRCP<size_t> rowPtr;
2480 ArrayRCP<global_ordinal_type> colInd;
2481 ArrayRCP<scalar_type> values;
2486 int mergeAndConvertSucceeded = 1;
2487 std::ostringstream errMsg;
2489 if (myRank == rootRank) {
2491 typedef Teuchos::MatrixMarket::Raw::Element<
scalar_type,
2501 const size_type numRows = dims[0];
2504 pAdder->getAdder()->merge ();
2507 const std::vector<element_type>& entries =
2508 pAdder->getAdder()->getEntries();
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);
2534 for (curPos = 0; curPos < numEntries; ++curPos) {
2535 const element_type& curEntry = entries[curPos];
2537 TEUCHOS_TEST_FOR_EXCEPTION(
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) {
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;
2651 ArrayRCP<size_t> myNumEntriesPerRow;
2652 ArrayRCP<size_t> myRowPtr;
2653 ArrayRCP<global_ordinal_type> myColInd;
2654 ArrayRCP<scalar_type> myValues;
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));
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.");
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.");
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
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)
2778 using Teuchos::MatrixMarket::Banner;
2780 using Teuchos::broadcast;
2782 using Teuchos::reduceAll;
2785 typedef Teuchos::ScalarTraits<scalar_type> STS;
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;
2796 TEUCHOS_TEST_FOR_EXCEPTION(
2797 rowMap.is_null (), std::invalid_argument,
2798 "Row Map must be nonnull.");
2799 TEUCHOS_TEST_FOR_EXCEPTION(
2800 rangeMap.is_null (), std::invalid_argument,
2801 "Range Map must be nonnull.");
2802 TEUCHOS_TEST_FOR_EXCEPTION(
2803 domainMap.is_null (), std::invalid_argument,
2804 "Domain Map must be nonnull.");
2805 TEUCHOS_TEST_FOR_EXCEPTION(
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.");
2810 TEUCHOS_TEST_FOR_EXCEPTION(
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.");
2815 TEUCHOS_TEST_FOR_EXCEPTION(
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.");
2820 TEUCHOS_TEST_FOR_EXCEPTION(
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.");
2825 TEUCHOS_TEST_FOR_EXCEPTION(
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.");
2830 TEUCHOS_TEST_FOR_EXCEPTION(
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.");
2839 size_t lineNumber = 1;
2841 if (debug && myRank == rootRank) {
2842 cerr <<
"Matrix Market reader: readSparse:" << endl
2843 <<
"-- Reading banner line" << endl;
2852 RCP<const Banner> pBanner;
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));
2906 TEUCHOS_TEST_FOR_EXCEPTION(bannerIsCorrect == 0,
2907 std::invalid_argument, errMsg.str ());
2909 if (debug && myRank == rootRank) {
2910 cerr <<
"-- Reading dimensions line" << endl;
2918 Tuple<global_ordinal_type, 3> dims =
2919 readCoordDims (in, lineNumber, pBanner, pComm, tolerant, debug);
2921 if (debug && myRank == rootRank) {
2922 cerr <<
"-- Making Adder for collecting matrix data" << endl;
2929 RCP<adder_type> pAdder =
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) {
2948 typedef Teuchos::MatrixMarket::CoordDataReader<adder_type,
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));
2971 TEUCHOS_TEST_FOR_EXCEPTION(readSuccess == 0, std::runtime_error,
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]
2998 Tuple<global_ordinal_type, 2> updatedDims;
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) {
3046 Tuple<global_ordinal_type, 2> addersDims;
3047 if (myRank == rootRank) {
3048 addersDims[0] = pAdder->getAdder()->numRows();
3049 addersDims[1] = pAdder->getAdder()->numCols();
3051 broadcast (*pComm, 0, addersDims);
3052 TEUCHOS_TEST_FOR_EXCEPTION(
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;
3077 ArrayRCP<size_t> numEntriesPerRow;
3078 ArrayRCP<size_t> rowPtr;
3079 ArrayRCP<global_ordinal_type> colInd;
3080 ArrayRCP<scalar_type> values;
3085 int mergeAndConvertSucceeded = 1;
3086 std::ostringstream errMsg;
3088 if (myRank == rootRank) {
3090 typedef Teuchos::MatrixMarket::Raw::Element<
scalar_type,
3100 const size_type numRows = dims[0];
3103 pAdder->getAdder()->merge ();
3106 const std::vector<element_type>& entries =
3107 pAdder->getAdder()->getEntries();
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);
3133 for (curPos = 0; curPos < numEntries; ++curPos) {
3134 const element_type& curEntry = entries[curPos];
3136 TEUCHOS_TEST_FOR_EXCEPTION(
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) {
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;
3235 TEUCHOS_TEST_FOR_EXCEPTION(
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]
3241 TEUCHOS_TEST_FOR_EXCEPTION(
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 "
3249 RCP<Teuchos::FancyOStream> err = debug ?
3250 Teuchos::getFancyOStream (Teuchos::rcpFromRef (cerr)) : null;
3251 RCP<const map_type> gatherRowMap = computeGatherMap (rowMap, err, debug);
3256 RCP<sparse_matrix_type> A_proc0 =
3259 if (myRank == rootRank) {
3261 cerr <<
"-- Proc 0: Filling gather matrix" << endl;
3263 ArrayView<const global_ordinal_type> myRows =
3264 gatherRowMap->getNodeElementList ();
3266 cerr <<
"---- Rows: " << Teuchos::toString (myRows) << endl;
3268 const size_type myNumRows = myRows.size ();
3272 for (size_type i = 0; i < myNumRows; ++i) {
3273 const size_type curPos = as<size_type> (rowPtr[i]);
3275 ArrayView<global_ordinal_type> curColInd =
3276 colInd.view (curPos, curNumEntries);
3277 ArrayView<scalar_type> curValues =
3278 values.view (curPos, curNumEntries);
3281 for (size_type k = 0; k < curNumEntries; ++k) {
3282 curColInd[k] += indexBase;
3285 cerr <<
"------ Columns: " << Teuchos::toString (curColInd) << endl;
3286 cerr <<
"------ Values: " << Teuchos::toString (curValues) << endl;
3289 if (curNumEntries > 0) {
3290 A_proc0->insertGlobalValues (myRows[i], curColInd, curValues);
3296 numEntriesPerRow = null;
3302 RCP<sparse_matrix_type> A;
3303 if (colMap.is_null ()) {
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) {
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;
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"
3387 static RCP<multivector_type>
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)
3396 if (comm->getRank () == 0) {
3397 in.open (filename.c_str ());
3399 return readDense (in, comm, node, map, tolerant, debug);
3469 static RCP<multivector_type>
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)
3477 Teuchos::RCP<Teuchos::FancyOStream> err =
3478 Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr));
3479 return readDenseImpl<scalar_type> (in, comm, node, map,
3480 err, tolerant, debug);
3504 static RCP<const map_type>
3506 const RCP<const comm_type>& comm,
3507 const RCP<node_type>& node,
3508 const bool tolerant=
false,
3509 const bool debug=
false)
3511 using Teuchos::inOutArg;
3512 using Teuchos::broadcast;
3516 if (comm->getRank () == 0) {
3517 in.open (filename.c_str ());
3522 broadcast<int, int> (*comm, 0, inOutArg (success));
3523 TEUCHOS_TEST_FOR_EXCEPTION(
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,
3537 const RCP<const comm_type>& comm,
3538 const RCP<node_type>& node,
3539 RCP<const map_type>& map,
3540 const Teuchos::RCP<Teuchos::FancyOStream>& err,
3541 const bool tolerant=
false,
3542 const bool debug=
false)
3544 using Teuchos::MatrixMarket::Banner;
3545 using Teuchos::MatrixMarket::checkCommentLine;
3547 using Teuchos::broadcast;
3548 using Teuchos::outArg;
3550 typedef MultiVectorScalarType ST;
3554 typedef Teuchos::ScalarTraits<ST> STS;
3555 typedef typename STS::magnitudeType MT;
3556 typedef Teuchos::ScalarTraits<MT> STM;
3561 const int myRank = comm->getRank ();
3563 if (! err.is_null ()) {
3567 *err << myRank <<
": readDenseImpl" << endl;
3569 if (! err.is_null ()) {
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;
3619 RCP<const Banner> pBanner;
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;
3733 Tuple<GO, 5> bannerDimsReadResult;
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);
3745 TEUCHOS_TEST_FOR_EXCEPTION(
3746 bannerDimsReadResult[3] == 0, std::runtime_error,
3747 "Failed to read banner line: " << exMsg.str ());
3748 TEUCHOS_TEST_FOR_EXCEPTION(
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]);
3764 RCP<const map_type> proc0Map;
3765 if (map.is_null ()) {
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)"
3793 TEUCHOS_TEST_FOR_EXCEPTION(
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 "
3805 ArrayRCP<ST> X_view = X->get1dViewNonConst ();
3806 TEUCHOS_TEST_FOR_EXCEPTION(
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()) {
3842 TEUCHOS_TEST_FOR_EXCEPTION(
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()) {
3872 TEUCHOS_TEST_FOR_EXCEPTION(
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();
3899 TEUCHOS_TEST_FOR_EXCEPTION(
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()) {
3909 TEUCHOS_TEST_FOR_EXCEPTION(
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.");
3918 TEUCHOS_TEST_FOR_EXCEPTION(
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.");
3929 TEUCHOS_TEST_FOR_EXCEPTION(
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) {
3941 TEUCHOS_TEST_FOR_EXCEPTION(
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;
3956 TEUCHOS_TEST_FOR_EXCEPTION(
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));
3976 TEUCHOS_TEST_FOR_EXCEPTION(
3977 globalReadDataSuccess == 0, std::runtime_error,
3978 "Failed to read the multivector's data: " << exMsg.str ());
3983 if (comm->getSize () == 1 && map.is_null ()) {
3985 if (! err.is_null ()) {
3989 *err << myRank <<
": readDenseImpl: done" << endl;
3991 if (! err.is_null ()) {
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;
4011 Export<LO, GO, NT> exporter (proc0Map, map, err);
4014 *err << myRank <<
": readDenseImpl: Exporting" << endl;
4017 Y->doExport (*X, exporter,
INSERT);
4019 if (! err.is_null ()) {
4023 *err << myRank <<
": readDenseImpl: done" << endl;
4025 if (! err.is_null ()) {
4054 static RCP<const map_type>
4056 const RCP<const comm_type>& comm,
4057 const RCP<node_type>& node,
4058 const bool tolerant=
false,
4059 const bool debug=
false)
4061 Teuchos::RCP<Teuchos::FancyOStream> err =
4062 Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr));
4063 return readMap (in, comm, node, err, tolerant, debug);
4091 static RCP<const map_type>
4093 const RCP<const comm_type>& comm,
4094 const RCP<node_type>& node,
4095 const Teuchos::RCP<Teuchos::FancyOStream>& err,
4096 const bool tolerant=
false,
4097 const bool debug=
false)
4100 using Teuchos::Array;
4101 using Teuchos::ArrayRCP;
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;
4113 typedef ptrdiff_t int_type;
4119 const int numProcs = comm->getSize ();
4120 const int myRank = comm->getRank ();
4122 if (err.is_null ()) {
4126 *err << myRank <<
": readMap: " << endl;
4128 if (err.is_null ()) {
4132 int readSuccess = 1;
4133 std::ostringstream exMsg;
4142 RCP<const Comm<int> > proc0Comm (
new SerialComm<int> ());
4144 RCP<const map_type> dataMap;
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));
4158 TEUCHOS_TEST_FOR_EXCEPTION(
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;
4168 ArrayRCP<const GO> myGids;
4171 ArrayRCP<size_type> gidsPerProcess;
4172 ArrayRCP<const int_type> GIDs, PIDs;
4173 ArrayRCP<size_type> startIndices;
4177 GIDs = data->getData (0);
4178 PIDs = data->getData (1);
4179 TEUCHOS_TEST_FOR_EXCEPTION(
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;
4195 Array<size_type> badRows;
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;
4214 badRows.push_back (k);
4216 else if (pid >= numProcs) {
4218 badRows.push_back (k);
4220 else if (pid < lastPid) {
4224 badRows.push_back (k);
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;
4255 Teuchos::OSTab tab (err);
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;
4289 TEUCHOS_TEST_FOR_EXCEPTION(
true, std::runtime_error, exMsg.str ());
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);
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]);
4316 myGids = myGidsAsGO.getConst ();
4318 }
catch (std::exception& e) {
4324 broadcast<int, int> (*comm, 0, inOutArg (readSuccess));
4325 TEUCHOS_TEST_FOR_EXCEPTION(
4326 readSuccess == 0, std::runtime_error,
4327 "Tpetra::MatrixMarket::readMap: The Map's data were invalid: "
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);
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]);
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;
4387 Tuple<size_type, 2> gidCountAndMinAllGid;
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;
4397 ArrayRCP<GO> myGidsCopy (gidCount);
4398 receive (*comm, rootRank, as<int> (gidCount), myGidsCopy.getRawPtr ());
4399 myGids = myGidsCopy.getConst ();
4404 *err << myRank <<
": readMap: Done distributing GID list" << endl;
4405 Teuchos::OSTab tab (err);
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;
4423 const global_size_t INVALID = Teuchos::OrdinalTraits<global_size_t>::invalid ();
4424 RCP<const map_type> newMap (
new map_type (INVALID, myGids (), indexBase, comm, node));
4426 if (err.is_null ()) {
4430 *err << myRank <<
": readMap: done" << endl;
4432 if (err.is_null ()) {
4451 encodeDataType (
const std::string& dataType)
4453 if (dataType ==
"real" || dataType ==
"integer") {
4455 }
else if (dataType ==
"complex") {
4457 }
else if (dataType ==
"pattern") {
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.");
4510 template<
class SparseMatrixType>
4513 typedef SparseMatrixType sparse_matrix_type;
4514 typedef RCP<sparse_matrix_type> sparse_matrix_ptr;
4576 const RCP<const sparse_matrix_type>& pMatrix,
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);
4614 const RCP<const sparse_matrix_type>& pMatrix,
4615 const bool debug=
false)
4654 const RCP<const sparse_matrix_type>& pMatrix,
4655 const std::string& matrixName,
4656 const std::string& matrixDescription,
4657 const bool debug=
false)
4659 using Teuchos::Comm;
4660 using Teuchos::FancyOStream;
4661 using Teuchos::getFancyOStream;
4662 using Teuchos::null;
4664 using Teuchos::rcpFromRef;
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;
4679 Teuchos::MatrixMarket::details::SetScientific<ST> sci (out);
4681 RCP<const Comm<int> > comm = pMatrix->getComm();
4682 const int myRank = comm->getRank ();
4684 RCP<FancyOStream> err =
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;
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 ();
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;
4723 RCP<node_type> node = rowMap->getNode();
4725 std::ostringstream os;
4726 os <<
"-- " << myRank <<
": making gatherRowMap" << endl;
4729 RCP<const map_type> gatherRowMap =
4730 computeGatherMap (rowMap, err, debug);
4738 const size_t localNumCols = (myRank == 0) ? numCols : 0;
4739 RCP<const map_type> gatherColMap =
4740 computeGatherMap (colMap, err, debug);
4744 import_type importer (rowMap, gatherRowMap);
4749 RCP<sparse_matrix_type> newMatrix =
4750 rcp (
new sparse_matrix_type (gatherRowMap, gatherColMap,
4751 static_cast<size_t> (0)));
4753 newMatrix->doImport (*pMatrix, importer,
INSERT);
4758 RCP<const map_type> gatherDomainMap =
4759 rcp (
new map_type (numCols, localNumCols,
4760 domainMap->getIndexBase (),
4762 RCP<const map_type> gatherRangeMap =
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;
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;
4855 out << (globalRowIndex + 1 - rowIndexBase) <<
" "
4856 << (globalColIndex + 1 - colIndexBase) <<
" ";
4857 if (STS::isComplex) {
4858 out << STS::real (*valIter) <<
" " << STS::imag (*valIter);
4866 typedef OrdinalTraits<GO> OTG;
4867 for (LO localRowIndex = gatherRowMap->getMinLocalIndex();
4868 localRowIndex <= gatherRowMap->getMaxLocalIndex();
4871 const GO globalRowIndex =
4872 gatherRowMap->getGlobalElement (localRowIndex);
4873 TEUCHOS_TEST_FOR_EXCEPTION(
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) {
4886 const GO globalColIndex =
4887 newMatrix->getColMap()->getGlobalElement (*indIter);
4888 TEUCHOS_TEST_FOR_EXCEPTION(
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);
4934 const RCP<const sparse_matrix_type>& pMatrix,
4935 const bool debug=
false)
4968 const RCP<const multivector_type>& X,
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);
5004 const RCP<const multivector_type>& X)
5037 const RCP<const multivector_type>& X,
5038 const std::string& matrixName,
5039 const std::string& matrixDescription)
5041 writeDenseImpl<scalar_type> (out, *X, matrixName, matrixDescription);
5064 const RCP<const multivector_type>& X)
5073 Teuchos::RCP<Teuchos::FancyOStream> err =
5074 Teuchos::getFancyOStream (Teuchos::rcpFromRef (std::cerr));
5089 const Teuchos::RCP<Teuchos::FancyOStream>& err,
5090 const bool debug=
false)
5092 using Teuchos::ArrayRCP;
5093 using Teuchos::ArrayView;
5095 using Teuchos::rcp_const_cast;
5096 using Teuchos::rcpFromRef;
5097 using Teuchos::TypeNameTraits;
5103 typedef int pid_type;
5108 typedef ptrdiff_t int_type;
5109 TEUCHOS_TEST_FOR_EXCEPTION(
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) <<
".");
5114 TEUCHOS_TEST_FOR_EXCEPTION(
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 ();
5122 if (! err.is_null ()) {
5126 *err << myRank <<
": writeMap" << endl;
5128 if (! err.is_null ()) {
5135 MV data (rcpFromRef (map), 2);
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]);
5151 *err << myRank <<
": writeMap: Done with column 0" << endl;
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);
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;
5175 writeDenseImpl<int_type> (out, data, map.getObjectLabel (),
5176 desc.str (), err, debug);
5178 if (! err.is_null ()) {
5182 *err << myRank <<
": writeMap: Done" << endl;
5184 if (! err.is_null ()) {
5194 const int myRank = map.
getComm ()->getRank ();
5197 out.open (filename.c_str());
5237 template<
class MultiVectorScalarType>
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)
5250 using Teuchos::rcp_const_cast;
5251 using Teuchos::rcp_dynamic_cast;
5254 typedef MultiVectorScalarType ST;
5259 typedef typename Teuchos::ScalarTraits<ST> STS;
5262 RCP<const map_type> map = X.
getMap ();
5263 RCP<const Comm<int> > comm = map->getComm ();
5264 const int myRank = comm->getRank ();
5266 if (! err.is_null ()) {
5270 std::ostringstream os;
5271 os << myRank <<
": writeDenseImpl" << endl;
5274 if (! err.is_null ()) {
5282 Teuchos::MatrixMarket::details::SetScientific<ST> sci (out);
5289 std::ostringstream os;
5290 os << myRank <<
": writeDenseImpl: Computing gather Map" << endl;
5296 RCP<NT> node = map->getNode();
5297 RCP<const map_type> gatherMap =
5298 computeGatherMap<map_type> (map, err, debug);
5301 std::ostringstream os;
5302 os << myRank <<
": writeDenseImpl: Computing Import" << endl;
5310 Import<LO, GO, NT> importer (map, gatherMap, err);
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;
5369 ArrayRCP<ArrayRCP<const ST> > Y_view = Y->get2dView ();
5370 TEUCHOS_TEST_FOR_EXCEPTION(
5371 as<global_size_t> (Y_view.size ()) < numCols, std::logic_error,
5372 "Y_view has size " << Y_view.size () <<
" < numCols = "
5377 ArrayRCP<const ST> Y_j = Y_view[j];
5378 TEUCHOS_TEST_FOR_EXCEPTION(
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));
5402 TEUCHOS_TEST_FOR_EXCEPTION(
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...
SparseMatrixType::node_type node_type
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
SparseMatrixType::global_ordinal_type global_ordinal_type
One or more distributed dense vectors.
static void writeDenseFile(const std::string &filename, const RCP< const multivector_type > &X)
Print the multivector in Matrix Market format.
SparseMatrixType::local_ordinal_type local_ordinal_type
Only used to define map_type.
SparseMatrixType::scalar_type scalar_type
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.
static void writeMap(std::ostream &out, const map_type &map, const bool debug=false)
Print the Map to the given output stream.
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.
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.
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.
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.
MultiVector< scalar_type, local_ordinal_type, global_ordinal_type, node_type > multivector_type
The MultiVector type associated with SparseMatrixType.
Describes a parallel distribution of objects over processes.
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.
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...