Tpetra Matrix/Vector Services  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
Tpetra_MatrixIO_def.hpp
1 /*
2 // @HEADER
3 // ***********************************************************************
4 //
5 // Tpetra: Templated Linear Algebra Services Package
6 // Copyright (2008) Sandia Corporation
7 //
8 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
9 // the U.S. Government retains certain rights in this software.
10 //
11 // Redistribution and use in source and binary forms, with or without
12 // modification, are permitted provided that the following conditions are
13 // met:
14 //
15 // 1. Redistributions of source code must retain the above copyright
16 // notice, this list of conditions and the following disclaimer.
17 //
18 // 2. Redistributions in binary form must reproduce the above copyright
19 // notice, this list of conditions and the following disclaimer in the
20 // documentation and/or other materials provided with the distribution.
21 //
22 // 3. Neither the name of the Corporation nor the names of the
23 // contributors may be used to endorse or promote products derived from
24 // this software without specific prior written permission.
25 //
26 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
27 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
30 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
31 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
32 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
33 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
34 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
35 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
36 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 //
38 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
39 //
40 // ************************************************************************
41 // @HEADER
42 */
43 
44 #ifndef TPETRA_MATRIX_IO_DEF
45 #define TPETRA_MATRIX_IO_DEF
46 
47 #include "Tpetra_CrsMatrix.hpp"
48 #include "Tpetra_MatrixIO.hpp"
49 #include <iostream>
50 
51 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
52 void
53 Tpetra::Utils::generateMatrix(const Teuchos::RCP<Teuchos::ParameterList> &plist,
54  const Teuchos::RCP<const Teuchos::Comm<int> > &comm,
55  const Teuchos::RCP<Node> &node,
57 {
58  typedef Teuchos::ScalarTraits<Scalar> ST;
59  using Teuchos::as;
60  TEUCHOS_TEST_FOR_EXCEPTION( plist == Teuchos::null, std::runtime_error,
61  "Tpetra::Utils::generateMatrix(): ParameterList is null.");
62  TEUCHOS_TEST_FOR_EXCEPTION( Teuchos::isParameterType<std::string>(*plist,"mat_type") == false, std::runtime_error,
63  "Tpetra::Utils::generateMatrix(): ParameterList did not contain string parameter ""mat_type"".");
64  std::string mat_type = plist->get<std::string>("mat_type");
65  if (mat_type == "Lap3D") {
66  // 3D Laplacian, grid is a cube with dimension gridSize x gridSize x gridSize
67  const GlobalOrdinal gridSize = as<GlobalOrdinal>(plist->get<int>("gridSize",100));
68  const GlobalOrdinal gS2 = gridSize*gridSize;
69  const GlobalOrdinal numRows = gS2*gridSize;
70  Teuchos::RCP<Tpetra::Map<LocalOrdinal,GlobalOrdinal,Node> > rowMap;
71  rowMap = Teuchos::rcp(new Tpetra::Map<LocalOrdinal,GlobalOrdinal,Node>(as<global_size_t>(numRows),as<GlobalOrdinal>(0),comm,GloballyDistributed,node));
73  // fill matrix, one row at a time
74  Teuchos::Array<GlobalOrdinal> neighbors;
75  Teuchos::Array<Scalar> values(7, -ST::one());
76  values[0] = (Scalar)6;
77  for (GlobalOrdinal r = rowMap->getMinGlobalIndex(); r <= rowMap->getMaxGlobalIndex(); ++r) {
78  neighbors.clear();
79  neighbors.push_back(r); // add diagonal
80  GlobalOrdinal ixy, iz, ix, iy; // (x,y,z) coords and index in xy plane
81  ixy = r%gS2;
82  iz = (r - ixy)/gS2;
83  ix = ixy%gridSize;
84  iy = (ixy - ix)/gridSize;
85  //
86  if ( ix != 0 ) neighbors.push_back( r-1 );
87  if ( ix != gridSize-1 ) neighbors.push_back( r+1 );
88  if ( iy != 0 ) neighbors.push_back( r-gridSize );
89  if ( iy != gridSize-1 ) neighbors.push_back( r+gridSize );
90  if ( iz != 0 ) neighbors.push_back( r-gS2 );
91  if ( iz != gridSize-1 ) neighbors.push_back( r+gS2 );
92  A->insertGlobalValues( r, neighbors(), values(0,neighbors.size()) );
93  }
94  A->fillComplete();
95  }
96  else {
97  TEUCHOS_TEST_FOR_EXCEPTION( true, std::runtime_error,
98  "Tpetra::Utils::generateMatrix(): ParameterList specified unsupported ""mat_type"".");
99  }
100 }
101 
102 
103 template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node, class LocalMatOps>
104 void
105 Tpetra::Utils::readHBMatrix(const std::string &filename,
106  const Teuchos::RCP<const Teuchos::Comm<int> > &comm,
107  const Teuchos::RCP<Node> &node,
109  Teuchos::RCP< const Tpetra::Map<LocalOrdinal,GlobalOrdinal,Node> > rowMap,
110  const Teuchos::RCP<ParameterList> &params)
111 {
112  const int myRank = comm->getRank();
113  int numRows,numCols,numNZ;
114  Teuchos::ArrayRCP<Scalar> svals;
115  Teuchos::ArrayRCP<GlobalOrdinal> colinds;
116  Teuchos::ArrayRCP<int> rowptrs;
117  Teuchos::ArrayRCP<size_t> nnzPerRow;
118  int fail = 0;
119  if (myRank == 0) {
120  bool isSymmetric=false;
121  Teuchos::ArrayRCP<double> dvals;
122  Teuchos::ArrayRCP<int> colptrs, rowinds;
123  std::string type;
124  Tpetra::Utils::readHBMatDouble(filename,numRows,numCols,numNZ,type,colptrs,rowinds,dvals);
125  TEUCHOS_TEST_FOR_EXCEPT(type.size() != 3);
126  if (type[0] != 'R' && type[0] != 'r') {
127  // only real matrices right now
128  fail = 1;
129  }
130  if (fail == 0 && numNZ > 0) {
131  if (type[1] == 'S' || type[1] == 's') {
132  isSymmetric = true;
133  }
134  else {
135  isSymmetric = false;
136  }
137  }
138  if (fail == 0 && numNZ > 0) {
139  // find num non-zero per row
140  nnzPerRow = Teuchos::arcp<size_t>(numRows);
141  std::fill(nnzPerRow.begin(), nnzPerRow.end(), 0);
142  for (Teuchos::ArrayRCP<int>::const_iterator ri=rowinds.begin(); ri != rowinds.end(); ++ri) {
143  // count each row index towards its row
144  ++nnzPerRow[*ri-1];
145  }
146  if (isSymmetric) {
147  // count each column toward the corresponding row as well
148  for (int c=0; c < numCols; ++c) {
149  // the diagonal was already counted; neglect it, if it exists
150  for (int i=colptrs[c]-1; i != colptrs[c+1]-1; ++i) {
151  if (rowinds[i] != c+1) {
152  ++nnzPerRow[c];
153  ++numNZ;
154  }
155  }
156  }
157  }
158  // allocate/set new matrix data
159  svals = Teuchos::arcp<Scalar>(numNZ);
160  colinds = Teuchos::arcp<GlobalOrdinal>(numNZ);
161  rowptrs = Teuchos::arcp<int>(numRows+1);
162  rowptrs[0] = 0;
163 #ifdef HAVE_TPETRA_DEBUG
164  Teuchos::ArrayRCP<size_t> nnzPerRow_debug(nnzPerRow.size());
165  std::copy(nnzPerRow.begin(), nnzPerRow.end(), nnzPerRow_debug.begin());
166 #endif
167  for (int j=1; j <= numRows; ++j) {
168  rowptrs[j] = rowptrs[j-1] + nnzPerRow[j-1];
169  nnzPerRow[j-1] = 0;
170  }
171  // translate from column-oriented to row-oriented
172  for (int col=0; col<numCols; ++col) {
173  for (int i=colptrs[col]-1; i != colptrs[col+1]-1; ++i) {
174  const int row = rowinds[i]-1;
175  // add entry to (row,col), with value dvals[i]
176  const size_t entry = rowptrs[row] + nnzPerRow[row];
177  svals[entry] = Teuchos::as<Scalar>(dvals[i]);
178  colinds[entry] = Teuchos::as<GlobalOrdinal>(col);
179  ++nnzPerRow[row];
180  if (isSymmetric && row != col) {
181  // add entry to (col,row), with value dvals[i]
182  const size_t symentry = rowptrs[col] + nnzPerRow[col];
183  svals[symentry] = Teuchos::as<Scalar>(dvals[i]);
184  colinds[symentry] = Teuchos::as<GlobalOrdinal>(row);
185  ++nnzPerRow[col];
186  }
187  }
188  }
189 #ifdef HAVE_TPETRA_DEBUG
190  {
191  bool isequal = true;
192  typename Teuchos::ArrayRCP<size_t>::const_iterator it1, it2;
193  for (it1 = nnzPerRow.begin(), it2 = nnzPerRow_debug.begin(); it1 != nnzPerRow.end(); ++it1, ++it2) {
194  if (*it1 != *it2) {
195  isequal = false;
196  break;
197  }
198  }
199  TEUCHOS_TEST_FOR_EXCEPTION(!isequal || nnzPerRow.size() != nnzPerRow_debug.size(), std::logic_error,
200  "Tpetra::Utils::readHBMatrix(): Logic error.");
201  }
202 #endif
203  }
204  // std::cout << "Matrix " << filename << " of type " << type << ": " << numRows << " by " << numCols << ", " << numNZ << " nonzeros" << std::endl;
205  }
206  // check for read errors
207  broadcast(*comm,0,&fail);
208  TEUCHOS_TEST_FOR_EXCEPTION(fail == 1, std::runtime_error, "Tpetra::Utils::readHBMatrix() can only read Real matrices.");
209  // distribute global matrix info
210  broadcast(*comm,0,&numRows);
211  broadcast(*comm,0,&numCols);
212  // create map with uniform partitioning
213  if (rowMap == Teuchos::null) {
214  rowMap = Teuchos::rcp(new Tpetra::Map<LocalOrdinal,GlobalOrdinal,Node>((global_size_t)numRows,(GlobalOrdinal)0,comm,GloballyDistributed,node));
215  }
216  else {
217  TEUCHOS_TEST_FOR_EXCEPTION( rowMap->getGlobalNumElements() != (global_size_t)numRows, std::runtime_error,
218  "Tpetra::Utils::readHBMatrix(): specified map has incorrect number of elements.");
219  TEUCHOS_TEST_FOR_EXCEPTION( rowMap->isDistributed() == false && comm->getSize() > 1, std::runtime_error,
220  "Tpetra::Utils::readHBMatrix(): specified map is not distributed.");
221  }
222  Teuchos::ArrayRCP<size_t> myNNZ;
223  if (rowMap->getNodeNumElements()) {
224  myNNZ = Teuchos::arcp<size_t>(rowMap->getNodeNumElements());
225  }
226  if (myRank == 0) {
227  LocalOrdinal numRowsAlreadyDistributed = rowMap->getNodeNumElements();
228  std::copy(nnzPerRow.begin(), nnzPerRow.begin()+numRowsAlreadyDistributed,myNNZ);
229  for (int p=1; p < Teuchos::size(*comm); ++p) {
230  size_t numRowsForP;
231  Teuchos::receive(*comm,p,&numRowsForP);
232  if (numRowsForP) {
233  Teuchos::send<int,size_t>(*comm,numRowsForP,nnzPerRow(numRowsAlreadyDistributed,numRowsForP).getRawPtr(),p);
234  numRowsAlreadyDistributed += numRowsForP;
235  }
236  }
237  }
238  else {
239  const size_t numMyRows = rowMap->getNodeNumElements();
240  Teuchos::send(*comm,numMyRows,0);
241  if (numMyRows) {
242  Teuchos::receive<int,size_t>(*comm,0,numMyRows,myNNZ(0,numMyRows).getRawPtr());
243  }
244  }
245  nnzPerRow = Teuchos::null;
246  // create column map
247  Teuchos::RCP<const Tpetra::Map<LocalOrdinal,GlobalOrdinal,Node> > domMap;
248  if (numRows == numCols) {
249  domMap = rowMap;
250  }
251  else {
252  domMap = createUniformContigMapWithNode<LocalOrdinal,GlobalOrdinal,Node>(numCols,comm,node);
253  }
255  // free this locally, A will keep it allocated as long as it is needed by A (up until allocation of nonzeros)
256  myNNZ = Teuchos::null;
257  if (myRank == 0 && numNZ > 0) {
258  for (int r=0; r < numRows; ++r) {
259  const LocalOrdinal nnz = rowptrs[r+1] - rowptrs[r];
260  if (nnz > 0) {
261  Teuchos::ArrayView<const GlobalOrdinal> inds = colinds(rowptrs[r],nnz);
262  Teuchos::ArrayView<const Scalar> vals = svals( rowptrs[r],nnz);
263  A->insertGlobalValues(r, inds, vals);
264  }
265  }
266  }
267  // don't need these anymore
268  colinds = Teuchos::null;
269  svals = Teuchos::null;
270  rowptrs = Teuchos::null;
271  A->fillComplete(domMap,rowMap,params);
272 }
273 
274 
275 
276 //
277 // Explicit instantiation macro
278 //
279 // Must be expanded from within the Tpetra::Utils namespace!
280 //
281 
282 #define TPETRA_MATRIXIO_INSTANT(SCALAR,LO,GO,NODE) \
283  template \
284  void \
285  readHBMatrix<SCALAR,LO,GO,NODE,Kokkos::DefaultKernels<SCALAR,LO,NODE>::SparseOps>( \
286  const std::string &, const Teuchos::RCP<const Teuchos::Comm<int> > &, const Teuchos::RCP<NODE > &, \
287  Teuchos::RCP< CrsMatrix<SCALAR,LO,GO,NODE,Kokkos::DefaultKernels<SCALAR,LO,NODE>::SparseOps > > &, \
288  Teuchos::RCP< const Tpetra::Map<LO,GO,NODE> >, \
289  const Teuchos::RCP< Teuchos::ParameterList > & ); \
290  \
291  template \
292  void \
293  generateMatrix<SCALAR,LO,GO,NODE,Kokkos::DefaultKernels<SCALAR,LO,NODE>::SparseOps>( \
294  const Teuchos::RCP<Teuchos::ParameterList> &plist, const Teuchos::RCP<const Teuchos::Comm<int> > &, const Teuchos::RCP<NODE > &, \
295  Teuchos::RCP< CrsMatrix<SCALAR,LO,GO,NODE,Kokkos::DefaultKernels<SCALAR,LO,NODE>::SparseOps > > &);
296 
297 #endif
Sparse matrix that presents a compressed sparse row interface.
size_t global_size_t
Global size_t object.
Describes a parallel distribution of objects over processes.