Tpetra Matrix/Vector Services  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines
Tpetra_MatrixIO_def.hpp
00001 /*
00002 // @HEADER
00003 // ***********************************************************************
00004 //
00005 //          Tpetra: Templated Linear Algebra Services Package
00006 //                 Copyright (2008) Sandia Corporation
00007 //
00008 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
00009 // the U.S. Government retains certain rights in this software.
00010 //
00011 // Redistribution and use in source and binary forms, with or without
00012 // modification, are permitted provided that the following conditions are
00013 // met:
00014 //
00015 // 1. Redistributions of source code must retain the above copyright
00016 // notice, this list of conditions and the following disclaimer.
00017 //
00018 // 2. Redistributions in binary form must reproduce the above copyright
00019 // notice, this list of conditions and the following disclaimer in the
00020 // documentation and/or other materials provided with the distribution.
00021 //
00022 // 3. Neither the name of the Corporation nor the names of the
00023 // contributors may be used to endorse or promote products derived from
00024 // this software without specific prior written permission.
00025 //
00026 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
00027 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00028 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
00029 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
00030 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
00031 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
00032 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
00033 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
00034 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
00035 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
00036 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00037 //
00038 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
00039 //
00040 // ************************************************************************
00041 // @HEADER
00042 */
00043 
00044 #ifndef TPETRA_MATRIX_IO_DEF
00045 #define TPETRA_MATRIX_IO_DEF
00046 
00047 #include "Tpetra_CrsMatrix.hpp"
00048 #include "Tpetra_MatrixIO.hpp"
00049 #include <iostream>
00050 
00051 namespace Tpetra {
00052 namespace Utils {
00053 
00054 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
00055 void
00056 generateMatrix (const Teuchos::RCP<Teuchos::ParameterList> &plist,
00057                 const Teuchos::RCP<const Teuchos::Comm<int> > &comm,
00058                 const Teuchos::RCP<Node> &node,
00059                 Teuchos::RCP<Tpetra::CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> > &A)
00060 {
00061   typedef Teuchos::ScalarTraits<Scalar> ST;
00062   using Teuchos::as;
00063   TEUCHOS_TEST_FOR_EXCEPTION( plist == Teuchos::null, std::runtime_error,
00064       "Tpetra::Utils::generateMatrix(): ParameterList is null.");
00065   TEUCHOS_TEST_FOR_EXCEPTION( Teuchos::isParameterType<std::string>(*plist,"mat_type") == false, std::runtime_error,
00066       "Tpetra::Utils::generateMatrix(): ParameterList did not contain string parameter ""mat_type"".");
00067   std::string mat_type = plist->get<std::string>("mat_type");
00068   if (mat_type == "Lap3D") {
00069     // 3D Laplacian, grid is a cube with dimension gridSize x gridSize x gridSize
00070     const GlobalOrdinal gridSize = as<GlobalOrdinal>(plist->get<int>("gridSize",100));
00071     const GlobalOrdinal gS2 = gridSize*gridSize;
00072     const GlobalOrdinal numRows = gS2*gridSize;
00073     Teuchos::RCP<Tpetra::Map<LocalOrdinal,GlobalOrdinal,Node> > rowMap;
00074     rowMap = Teuchos::rcp(new Tpetra::Map<LocalOrdinal,GlobalOrdinal,Node>(as<global_size_t>(numRows),as<GlobalOrdinal>(0),comm,GloballyDistributed,node));
00075     A = rcp(new Tpetra::CrsMatrix<Scalar,LocalOrdinal,GlobalOrdinal,Node>(rowMap,7,Tpetra::StaticProfile));
00076     // fill matrix, one row at a time
00077     Teuchos::Array<GlobalOrdinal> neighbors;
00078     Teuchos::Array<Scalar> values(7, -ST::one());
00079     values[0] = (Scalar)6;
00080     for (GlobalOrdinal r = rowMap->getMinGlobalIndex(); r <= rowMap->getMaxGlobalIndex(); ++r) {
00081       neighbors.clear();
00082       neighbors.push_back(r); // add diagonal
00083       GlobalOrdinal ixy, iz, ix, iy;  // (x,y,z) coords and index in xy plane
00084       ixy = r%gS2;
00085       iz = (r - ixy)/gS2;
00086       ix = ixy%gridSize;
00087       iy = (ixy - ix)/gridSize;
00088       //
00089       if ( ix != 0 )          neighbors.push_back( r-1 );
00090       if ( ix != gridSize-1 ) neighbors.push_back( r+1 );
00091       if ( iy != 0 )          neighbors.push_back( r-gridSize );
00092       if ( iy != gridSize-1 ) neighbors.push_back( r+gridSize );
00093       if ( iz != 0 )          neighbors.push_back( r-gS2 );
00094       if ( iz != gridSize-1 ) neighbors.push_back( r+gS2 );
00095       A->insertGlobalValues( r, neighbors(), values(0,neighbors.size()) );
00096     }
00097     A->fillComplete();
00098   }
00099   else {
00100     TEUCHOS_TEST_FOR_EXCEPTION( true, std::runtime_error,
00101         "Tpetra::Utils::generateMatrix(): ParameterList specified unsupported ""mat_type"".");
00102   }
00103 }
00104 
00105 
00106 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
00107 void
00108 readHBMatrix (const std::string &filename,
00109               const Teuchos::RCP<const Teuchos::Comm<int> > &comm,
00110               const Teuchos::RCP<Node> &node,
00111               Teuchos::RCP< Tpetra::CrsMatrix<Scalar,LocalOrdinal,GlobalOrdinal,Node> > &A,
00112               Teuchos::RCP< const Tpetra::Map<LocalOrdinal,GlobalOrdinal,Node> > rowMap,
00113               const Teuchos::RCP<Teuchos::ParameterList> &params)
00114 {
00115   const int myRank = comm->getRank();
00116   int numRows,numCols,numNZ;
00117   Teuchos::ArrayRCP<Scalar> svals;
00118   Teuchos::ArrayRCP<GlobalOrdinal> colinds;
00119   Teuchos::ArrayRCP<int>           rowptrs;
00120   Teuchos::ArrayRCP<size_t>        nnzPerRow;
00121   int fail = 0;
00122   if (myRank == 0) {
00123     bool isSymmetric=false;
00124     Teuchos::ArrayRCP<double> dvals;
00125     Teuchos::ArrayRCP<int> colptrs, rowinds;
00126     std::string type;
00127     Tpetra::Utils::readHBMatDouble(filename,numRows,numCols,numNZ,type,colptrs,rowinds,dvals);
00128     TEUCHOS_TEST_FOR_EXCEPT(type.size() != 3);
00129     if (type[0] != 'R' && type[0] != 'r') {
00130       // only real matrices right now
00131       fail = 1;
00132     }
00133     if (fail == 0 && numNZ > 0) {
00134       if (type[1] == 'S' || type[1] == 's') {
00135         isSymmetric = true;
00136       }
00137       else {
00138         isSymmetric = false;
00139       }
00140     }
00141     if (fail == 0 && numNZ > 0) {
00142       // find num non-zero per row
00143       nnzPerRow = Teuchos::arcp<size_t>(numRows);
00144       std::fill(nnzPerRow.begin(), nnzPerRow.end(), 0);
00145       for (Teuchos::ArrayRCP<int>::const_iterator ri=rowinds.begin(); ri != rowinds.end(); ++ri) {
00146         // count each row index towards its row
00147         ++nnzPerRow[*ri-1];
00148       }
00149       if (isSymmetric) {
00150         // count each column toward the corresponding row as well
00151         for (int c=0; c < numCols; ++c) {
00152           // the diagonal was already counted; neglect it, if it exists
00153           for (int i=colptrs[c]-1; i != colptrs[c+1]-1; ++i) {
00154             if (rowinds[i] != c+1) {
00155               ++nnzPerRow[c];
00156               ++numNZ;
00157             }
00158           }
00159         }
00160       }
00161       // allocate/set new matrix data
00162       svals = Teuchos::arcp<Scalar>(numNZ);
00163       colinds = Teuchos::arcp<GlobalOrdinal>(numNZ);
00164       rowptrs = Teuchos::arcp<int>(numRows+1);
00165       rowptrs[0] = 0;
00166 #ifdef HAVE_TPETRA_DEBUG
00167       Teuchos::ArrayRCP<size_t> nnzPerRow_debug(nnzPerRow.size());
00168       std::copy(nnzPerRow.begin(), nnzPerRow.end(), nnzPerRow_debug.begin());
00169 #endif
00170       for (int j=1; j <= numRows; ++j) {
00171         rowptrs[j] = rowptrs[j-1] + nnzPerRow[j-1];
00172         nnzPerRow[j-1] = 0;
00173       }
00174       // translate from column-oriented to row-oriented
00175       for (int col=0; col<numCols; ++col) {
00176         for (int i=colptrs[col]-1; i != colptrs[col+1]-1; ++i) {
00177           const int row = rowinds[i]-1;
00178           // add entry to (row,col), with value dvals[i]
00179           const size_t entry = rowptrs[row] + nnzPerRow[row];
00180           svals[entry] = Teuchos::as<Scalar>(dvals[i]);
00181           colinds[entry] = Teuchos::as<GlobalOrdinal>(col);
00182           ++nnzPerRow[row];
00183           if (isSymmetric && row != col) {
00184             // add entry to (col,row), with value dvals[i]
00185             const size_t symentry = rowptrs[col] + nnzPerRow[col];
00186             svals[symentry] = Teuchos::as<Scalar>(dvals[i]);
00187             colinds[symentry] = Teuchos::as<GlobalOrdinal>(row);
00188             ++nnzPerRow[col];
00189           }
00190         }
00191       }
00192 #ifdef HAVE_TPETRA_DEBUG
00193       {
00194         bool isequal = true;
00195         typename Teuchos::ArrayRCP<size_t>::const_iterator it1, it2;
00196         for (it1 = nnzPerRow.begin(), it2 = nnzPerRow_debug.begin(); it1 != nnzPerRow.end(); ++it1, ++it2) {
00197           if (*it1 != *it2) {
00198             isequal = false;
00199             break;
00200           }
00201         }
00202         TEUCHOS_TEST_FOR_EXCEPTION(!isequal || nnzPerRow.size() != nnzPerRow_debug.size(), std::logic_error,
00203             "Tpetra::Utils::readHBMatrix(): Logic error.");
00204       }
00205 #endif
00206     }
00207     // std::cout << "Matrix " << filename << " of type " << type << ": " << numRows << " by " << numCols << ", " << numNZ << " nonzeros" << std::endl;
00208   }
00209   // check for read errors
00210   broadcast(*comm,0,&fail);
00211   TEUCHOS_TEST_FOR_EXCEPTION(fail == 1, std::runtime_error, "Tpetra::Utils::readHBMatrix() can only read Real matrices.");
00212   // distribute global matrix info
00213   broadcast(*comm,0,&numRows);
00214   broadcast(*comm,0,&numCols);
00215   // create map with uniform partitioning
00216   if (rowMap == Teuchos::null) {
00217     rowMap = Teuchos::rcp(new Tpetra::Map<LocalOrdinal,GlobalOrdinal,Node>((global_size_t)numRows,(GlobalOrdinal)0,comm,GloballyDistributed,node));
00218   }
00219   else {
00220     TEUCHOS_TEST_FOR_EXCEPTION( rowMap->getGlobalNumElements() != (global_size_t)numRows, std::runtime_error,
00221         "Tpetra::Utils::readHBMatrix(): specified map has incorrect number of elements.");
00222     TEUCHOS_TEST_FOR_EXCEPTION( rowMap->isDistributed() == false && comm->getSize() > 1, std::runtime_error,
00223         "Tpetra::Utils::readHBMatrix(): specified map is not distributed.");
00224   }
00225   Teuchos::ArrayRCP<size_t> myNNZ;
00226   if (rowMap->getNodeNumElements()) {
00227     myNNZ = Teuchos::arcp<size_t>(rowMap->getNodeNumElements());
00228   }
00229   if (myRank == 0) {
00230     LocalOrdinal numRowsAlreadyDistributed = rowMap->getNodeNumElements();
00231     std::copy(nnzPerRow.begin(), nnzPerRow.begin()+numRowsAlreadyDistributed,myNNZ);
00232     for (int p=1; p < Teuchos::size(*comm); ++p) {
00233       size_t numRowsForP;
00234       Teuchos::receive(*comm,p,&numRowsForP);
00235       if (numRowsForP) {
00236         Teuchos::send<int,size_t>(*comm,numRowsForP,nnzPerRow(numRowsAlreadyDistributed,numRowsForP).getRawPtr(),p);
00237         numRowsAlreadyDistributed += numRowsForP;
00238       }
00239     }
00240   }
00241   else {
00242     const size_t numMyRows = rowMap->getNodeNumElements();
00243     Teuchos::send(*comm,numMyRows,0);
00244     if (numMyRows) {
00245       Teuchos::receive<int,size_t>(*comm,0,numMyRows,myNNZ(0,numMyRows).getRawPtr());
00246     }
00247   }
00248   nnzPerRow = Teuchos::null;
00249   // create column map
00250   Teuchos::RCP<const Tpetra::Map<LocalOrdinal,GlobalOrdinal,Node> > domMap;
00251   if (numRows == numCols) {
00252     domMap = rowMap;
00253   }
00254   else {
00255     domMap = createUniformContigMapWithNode<LocalOrdinal,GlobalOrdinal,Node>(numCols,comm,node);
00256   }
00257   A = rcp(new Tpetra::CrsMatrix<Scalar,LocalOrdinal,GlobalOrdinal,Node>(rowMap,myNNZ,Tpetra::StaticProfile));
00258   // free this locally, A will keep it allocated as long as it is needed by A (up until allocation of nonzeros)
00259   myNNZ = Teuchos::null;
00260   if (myRank == 0 && numNZ > 0) {
00261     for (int r=0; r < numRows; ++r) {
00262       const LocalOrdinal nnz = rowptrs[r+1] - rowptrs[r];
00263       if (nnz > 0) {
00264         Teuchos::ArrayView<const GlobalOrdinal> inds = colinds(rowptrs[r],nnz);
00265         Teuchos::ArrayView<const        Scalar> vals = svals(  rowptrs[r],nnz);
00266         A->insertGlobalValues(r, inds, vals);
00267       }
00268     }
00269   }
00270   // don't need these anymore
00271   colinds = Teuchos::null;
00272   svals   = Teuchos::null;
00273   rowptrs = Teuchos::null;
00274   A->fillComplete(domMap,rowMap,params);
00275 }
00276 } // namespace Utils
00277 } // namespace Tpetra
00278 
00279 //
00280 // Explicit instantiation macro
00281 //
00282 // Must be expanded from within the Tpetra::Utils namespace!
00283 //
00284 
00285 #define TPETRA_MATRIXIO_INSTANT(SCALAR,LO,GO,NODE) \
00286   template void \
00287   readHBMatrix< SCALAR, LO, GO, NODE > (const std::string&, \
00288                                         const Teuchos::RCP<const Teuchos::Comm<int> > &, \
00289                                         const Teuchos::RCP< NODE > &, \
00290                                         Teuchos::RCP<CrsMatrix< SCALAR, LO, GO, NODE > >&, \
00291                                         Teuchos::RCP<const Tpetra::Map< LO, GO, NODE> >, \
00292                                         const Teuchos::RCP<Teuchos::ParameterList>& ); \
00293   \
00294   template void \
00295   generateMatrix< SCALAR, LO, GO, NODE> (const Teuchos::RCP<Teuchos::ParameterList>&, \
00296                                          const Teuchos::RCP<const Teuchos::Comm<int> > &, \
00297                                          const Teuchos::RCP< NODE > &,\
00298                                          Teuchos::RCP<CrsMatrix< SCALAR, LO, GO, NODE > >& );
00299 
00300 
00301 #endif
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines