Tpetra Matrix/Vector Services  Version of the Day
Tpetra_RowMatrix_def.hpp
1 // @HEADER
2 // ***********************************************************************
3 //
4 // Tpetra: Templated Linear Algebra Services Package
5 // Copyright (2008) Sandia Corporation
6 //
7 // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
8 // the U.S. Government retains certain rights in this software.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
38 //
39 // ************************************************************************
40 // @HEADER
41 
42 #ifndef TPETRA_ROWMATRIX_DEF_HPP
43 #define TPETRA_ROWMATRIX_DEF_HPP
44 
45 #include <Tpetra_ConfigDefs.hpp>
46 #include <Tpetra_CrsMatrix.hpp>
47 #include <Tpetra_Map.hpp>
48 
49 namespace Tpetra {
50 
51  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
53 
54  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
57  add (const Scalar& alpha,
59  const Scalar& beta,
62  const Teuchos::RCP<Teuchos::ParameterList>& params) const
63  {
64  using Teuchos::Array;
65  using Teuchos::ArrayRCP;
66  using Teuchos::as;
68  using Teuchos::RCP;
69  using Teuchos::rcp;
70  using Teuchos::rcp_implicit_cast;
71  using Teuchos::sublist;
72  typedef LocalOrdinal LO;
73  typedef GlobalOrdinal GO;
75  typedef Map<LO, GO, Node> map_type;
78 
79  const this_type& B = *this; // a convenient abbreviation
80 
81  // If the user didn't supply a domain or range Map, then try to
82  // get one from B first (if it has them), then from A (if it has
83  // them). If we don't have any domain or range Maps, scold the
84  // user.
85  RCP<const map_type> A_domainMap = A.getDomainMap ();
86  RCP<const map_type> A_rangeMap = A.getRangeMap ();
87  RCP<const map_type> B_domainMap = B.getDomainMap ();
88  RCP<const map_type> B_rangeMap = B.getRangeMap ();
89 
90  RCP<const map_type> theDomainMap = domainMap;
91  RCP<const map_type> theRangeMap = rangeMap;
92 
93  if (domainMap.is_null ()) {
94  if (B_domainMap.is_null ()) {
96  A_domainMap.is_null (), std::invalid_argument,
97  "Tpetra::RowMatrix::add: If neither A nor B have a domain Map, "
98  "then you must supply a nonnull domain Map to this method.");
99  theDomainMap = A_domainMap;
100  } else {
101  theDomainMap = B_domainMap;
102  }
103  }
104  if (rangeMap.is_null ()) {
105  if (B_rangeMap.is_null ()) {
107  A_rangeMap.is_null (), std::invalid_argument,
108  "Tpetra::RowMatrix::add: If neither A nor B have a range Map, "
109  "then you must supply a nonnull range Map to this method.");
110  theRangeMap = A_rangeMap;
111  } else {
112  theRangeMap = B_rangeMap;
113  }
114  }
115 
116 #ifdef HAVE_TPETRA_DEBUG
117  // In a debug build, check that A and B have matching domain and
118  // range Maps, if they have domain and range Maps at all. (If
119  // they aren't fill complete, then they may not yet have them.)
120  if (! A_domainMap.is_null () && ! A_rangeMap.is_null ()) {
121  if (! B_domainMap.is_null () && ! B_rangeMap.is_null ()) {
123  ! B_domainMap->isSameAs (*A_domainMap), std::invalid_argument,
124  "Tpetra::RowMatrix::add: The input RowMatrix A must have a domain Map "
125  "which is the same as (isSameAs) this RowMatrix's domain Map.");
127  ! B_rangeMap->isSameAs (*A_rangeMap), std::invalid_argument,
128  "Tpetra::RowMatrix::add: The input RowMatrix A must have a range Map "
129  "which is the same as (isSameAs) this RowMatrix's range Map.");
131  ! domainMap.is_null () && ! domainMap->isSameAs (*B_domainMap),
132  std::invalid_argument,
133  "Tpetra::RowMatrix::add: The input domain Map must be the same as "
134  "(isSameAs) this RowMatrix's domain Map.");
136  ! rangeMap.is_null () && ! rangeMap->isSameAs (*B_rangeMap),
137  std::invalid_argument,
138  "Tpetra::RowMatrix::add: The input range Map must be the same as "
139  "(isSameAs) this RowMatrix's range Map.");
140  }
141  }
142  else if (! B_domainMap.is_null () && ! B_rangeMap.is_null ()) {
144  ! domainMap.is_null () && ! domainMap->isSameAs (*B_domainMap),
145  std::invalid_argument,
146  "Tpetra::RowMatrix::add: The input domain Map must be the same as "
147  "(isSameAs) this RowMatrix's domain Map.");
149  ! rangeMap.is_null () && ! rangeMap->isSameAs (*B_rangeMap),
150  std::invalid_argument,
151  "Tpetra::RowMatrix::add: The input range Map must be the same as "
152  "(isSameAs) this RowMatrix's range Map.");
153  }
154  else {
156  domainMap.is_null () || rangeMap.is_null (), std::invalid_argument,
157  "Tpetra::RowMatrix::add: If neither A nor B have a domain and range "
158  "Map, then you must supply a nonnull domain and range Map to this "
159  "method.");
160  }
161 #endif // HAVE_TPETRA_DEBUG
162 
163  // What parameters do we pass to C's constructor? Do we call
164  // fillComplete on C after filling it? And if so, what parameters
165  // do we pass to C's fillComplete call?
166  bool callFillComplete = true;
167  RCP<ParameterList> constructorSublist;
168  RCP<ParameterList> fillCompleteSublist;
169  if (! params.is_null ()) {
170  callFillComplete = params->get ("Call fillComplete", callFillComplete);
171  constructorSublist = sublist (params, "Constructor parameters");
172  fillCompleteSublist = sublist (params, "fillComplete parameters");
173  }
174 
175  RCP<const map_type> A_rowMap = A.getRowMap ();
176  RCP<const map_type> B_rowMap = B.getRowMap ();
177  RCP<const map_type> C_rowMap = B_rowMap; // see discussion in documentation
178  RCP<crs_matrix_type> C; // The result matrix.
179 
180  // If A and B's row Maps are the same, we can compute an upper
181  // bound on the number of entries in each row of C, before
182  // actually computing the sum. A reasonable upper bound is the
183  // sum of the two entry counts in each row. If we choose this as
184  // the actual per-row upper bound, we can use static profile.
185  if (A_rowMap->isSameAs (*B_rowMap)) {
186  const LO localNumRows = as<LO> (A_rowMap->getNodeNumElements ());
187  ArrayRCP<size_t> C_maxNumEntriesPerRow (localNumRows, 0);
188 
189  // Get the number of entries in each row of A.
190  if (alpha != STS::zero ()) {
191  for (LO localRow = 0; localRow < localNumRows; ++localRow) {
192  const size_t A_numEntries = A.getNumEntriesInLocalRow (localRow);
193  C_maxNumEntriesPerRow[localRow] += A_numEntries;
194  }
195  }
196  // Get the number of entries in each row of B.
197  if (beta != STS::zero ()) {
198  for (LO localRow = 0; localRow < localNumRows; ++localRow) {
199  const size_t B_numEntries = B.getNumEntriesInLocalRow (localRow);
200  C_maxNumEntriesPerRow[localRow] += B_numEntries;
201  }
202  }
203  // Construct the result matrix C.
204  if (constructorSublist.is_null ()) {
205  C = rcp (new crs_matrix_type (C_rowMap, C_maxNumEntriesPerRow,
206  StaticProfile));
207  } else {
208  C = rcp (new crs_matrix_type (C_rowMap, C_maxNumEntriesPerRow,
209  StaticProfile, constructorSublist));
210  }
211  // Since A and B have the same row Maps, we could add them
212  // together all at once and merge values before we call
213  // insertGlobalValues. However, we don't really need to, since
214  // we've already allocated enough space in each row of C for C
215  // to do the merge itself.
216  }
217  else { // the row Maps of A and B are not the same
218  // Construct the result matrix C.
219  if (constructorSublist.is_null ()) {
220  C = rcp (new crs_matrix_type (C_rowMap, 0, DynamicProfile));
221  } else {
222  C = rcp (new crs_matrix_type (C_rowMap, 0, DynamicProfile,
223  constructorSublist));
224  }
225  }
226 
227 #ifdef HAVE_TPETRA_DEBUG
228  TEUCHOS_TEST_FOR_EXCEPTION(C.is_null (), std::logic_error,
229  "Tpetra::RowMatrix::add: C should not be null at this point. "
230  "Please report this bug to the Tpetra developers.");
231 #endif // HAVE_TPETRA_DEBUG
232  //
233  // Compute C = alpha*A + beta*B.
234  //
235  Array<GO> ind;
236  Array<Scalar> val;
237 
238  if (alpha != STS::zero ()) {
239  const LO A_localNumRows = as<LO> (A_rowMap->getNodeNumElements ());
240  for (LO localRow = 0; localRow < A_localNumRows; ++localRow) {
241  size_t A_numEntries = A.getNumEntriesInLocalRow (localRow);
242  const GO globalRow = A_rowMap->getGlobalElement (localRow);
243  if (A_numEntries > as<size_t> (ind.size ())) {
244  ind.resize (A_numEntries);
245  val.resize (A_numEntries);
246  }
247  ArrayView<GO> indView = ind (0, A_numEntries);
248  ArrayView<Scalar> valView = val (0, A_numEntries);
249  A.getGlobalRowCopy (globalRow, indView, valView, A_numEntries);
250 
251  if (alpha != STS::one ()) {
252  for (size_t k = 0; k < A_numEntries; ++k) {
253  valView[k] *= alpha;
254  }
255  }
256  C->insertGlobalValues (globalRow, indView, valView);
257  }
258  }
259 
260  if (beta != STS::zero ()) {
261  const LO B_localNumRows = as<LO> (B_rowMap->getNodeNumElements ());
262  for (LO localRow = 0; localRow < B_localNumRows; ++localRow) {
263  size_t B_numEntries = B.getNumEntriesInLocalRow (localRow);
264  const GO globalRow = B_rowMap->getGlobalElement (localRow);
265  if (B_numEntries > as<size_t> (ind.size ())) {
266  ind.resize (B_numEntries);
267  val.resize (B_numEntries);
268  }
269  ArrayView<GO> indView = ind (0, B_numEntries);
270  ArrayView<Scalar> valView = val (0, B_numEntries);
271  B.getGlobalRowCopy (globalRow, indView, valView, B_numEntries);
272 
273  if (beta != STS::one ()) {
274  for (size_t k = 0; k < B_numEntries; ++k) {
275  valView[k] *= beta;
276  }
277  }
278  C->insertGlobalValues (globalRow, indView, valView);
279  }
280  }
281 
282  if (callFillComplete) {
283  if (fillCompleteSublist.is_null ()) {
284  C->fillComplete (theDomainMap, theRangeMap);
285  } else {
286  C->fillComplete (theDomainMap, theRangeMap, fillCompleteSublist);
287  }
288  }
289 
290  return rcp_implicit_cast<this_type> (C);
291  }
292 
293 
294  template <class Scalar, class LocalOrdinal, class GlobalOrdinal, class Node>
295  void
298  Teuchos::Array<char>& exports,
299  const Teuchos::ArrayView<size_t>& numPacketsPerLID,
300  size_t& constantNumPackets,
301  Distributor &distor) const
302  {
303  using Teuchos::Array;
304  using Teuchos::ArrayView;
305  using Teuchos::as;
306  using Teuchos::av_reinterpret_cast;
307  using Teuchos::RCP;
308  typedef LocalOrdinal LO;
309  typedef GlobalOrdinal GO;
310  typedef typename ArrayView<const LO>::size_type size_type;
311  typedef Map<LO, GO, Node> map_type;
312  const char tfecfFuncName[] = "pack";
313 
315  exportLIDs.size() != numPacketsPerLID.size(),
316  std::invalid_argument, "exportLIDs.size() = " << exportLIDs.size()
317  << "!= numPacketsPerLID.size() = " << numPacketsPerLID.size() << ".");
318 
319  // Row Map of the source matrix.
320  RCP<const map_type> rowMapPtr = this->getRowMap ();
322  rowMapPtr.is_null (), std::runtime_error,
323  "The source object's row Map is null.");
324  const map_type& rowMap = *rowMapPtr;
325 
326  // Each input LID corresponds to a different row of the sparse
327  // matrix. In general, a RowMatrix doesn't have the same number
328  // of entries in each row.
329  constantNumPackets = 0;
330 
331  // Get the GIDs of the rows we want to pack.
332  Array<GO> exportGIDs (exportLIDs.size ());
333  const size_type numExportGIDs = exportGIDs.size ();
334  for (size_type i = 0; i < numExportGIDs; ++i) {
335  exportGIDs[i] = rowMap.getGlobalElement (exportLIDs[i]);
336  }
337 
338  // We say "Packet" is char (really a "byte"), but the actual unit
339  // of packing is a (GID, value) pair. The GID is the column index
340  // in that row of the sparse matrix, and the value is the value at
341  // that entry of the sparse matrix. Thus, we have to scale
342  // numPacketsPerLID by the number of bytes in a _packed_ (GID,
343  // value) pair. (We pack the GID and value in each pair
344  // separately, so the number of bytes in a packed pair is actually
345  // sizeof(GO) + sizeof(Scalar).)
346  //
347  // FIXME (mfh 24 Feb 2013) This code is only correct if
348  // sizeof(Scalar) is a meaningful representation of the amount of
349  // data in a Scalar instance. (GO is always a built-in integer
350  // type.)
351  //
352  // Compute the number of packets per export LID, and accumulate
353  // the total number of packages. While doing so, find the max
354  // number of entries in each row owned by this process; we will
355  // use that to size temporary arrays below.
356  const size_t sizeOfOrdValPair = sizeof (GO) + sizeof (Scalar);
357  size_t totalNumEntries = 0;
358  size_t maxRowLength = 0;
359  for (size_type i = 0; i < exportGIDs.size(); ++i) {
360  const size_t curNumEntries =
361  this->getNumEntriesInGlobalRow (exportGIDs[i]);
362  numPacketsPerLID[i] = curNumEntries * sizeOfOrdValPair;
363  totalNumEntries += curNumEntries;
364  maxRowLength = std::max (curNumEntries, maxRowLength);
365  }
366 
367  // Pack export data by interleaving rows' indices and values in
368  // the following way:
369  //
370  // [inds_row0 vals_row0 inds_row1 vals_row1 ... ]
371  if (totalNumEntries > 0) {
372  // exports is an array of char (bytes), so scale the total
373  // number of entries by the number of bytes per entry (where
374  // "entry" includes both the column index and the value).
375  const size_t totalNumBytes = totalNumEntries * sizeOfOrdValPair;
376  exports.resize (totalNumBytes);
377 
378  // Temporary buffers for a copy of the entries in each row.
379  Array<GO> inds (as<size_type> (maxRowLength));
380  Array<Scalar> vals (as<size_type> (maxRowLength));
381  // Current position in the 'exports' output array.
382  size_t curOffsetInBytes = 0;
383 
384  // For each row of the matrix owned by the calling process, pack
385  // that row's column indices and values into the exports array.
386  // We'll use getGlobalRowCopy, since it will always work, no
387  // matter how the subclass stores its data. Subclasses (like
388  // CrsMatrix) should reimplement this method to use (e.g.,)
389  // getGlobalRowView if appropriate, since that will likely be
390  // more efficient.
391  //
392  // FIXME (mfh 28 Jun 2013) This could be made a (shared-memory)
393  // parallel kernel, by using the CSR data layout to calculate
394  // positions in the output buffer.
395  for (size_type i = 0; i < exportGIDs.size(); ++i) {
396  // Get a copy of the current row's data.
397  size_t curNumEntries = 0;
398  this->getGlobalRowCopy (exportGIDs[i], inds (), vals (), curNumEntries);
399  // inds and vals arrays might have more entries than the row.
400  // curNumEntries is the number of valid entries of these arrays.
401  ArrayView<const GO> curInds = inds (0, as<size_type> (curNumEntries));
402  ArrayView<const Scalar> curVals = vals (0, as<size_type> (curNumEntries));
403 
404  // Get views of the spots in the exports array in which to
405  // put the indices resp. values. See notes and FIXME above.
406  ArrayView<char> outIndsChar =
407  exports (curOffsetInBytes, curNumEntries * sizeof (GO));
408  ArrayView<char> outValsChar =
409  exports (curOffsetInBytes + curNumEntries * sizeof (GO),
410  curNumEntries * sizeof (Scalar));
411 
412  // Cast the above views of char as views of GO resp. Scalar.
413  ArrayView<GO> outInds = av_reinterpret_cast<GO> (outIndsChar);
414  ArrayView<Scalar> outVals = av_reinterpret_cast<Scalar> (outValsChar);
415 
416  // Copy the source matrix's row data into the views of the
417  // exports array for indices resp. values.
418  std::copy (curInds.begin(), curInds.end(), outInds.begin());
419  std::copy (curVals.begin(), curVals.end(), outVals.begin());
420  curOffsetInBytes += sizeOfOrdValPair * curNumEntries;
421  }
422 
423 #ifdef HAVE_TPETRA_DEBUG
424  TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(curOffsetInBytes != totalNumBytes,
425  std::logic_error, ": At end of method, the final offset bytes count "
426  "curOffsetInBytes=" << curOffsetInBytes << " does not equal the total "
427  "number of bytes packed totalNumBytes=" << totalNumBytes << ". Please "
428  "report this bug to the Tpetra developers.");
429 #endif // HAVE_TPETRA_DEBUG
430  }
431  }
432 
433 } // namespace Tpetra
434 
435 //
436 // Explicit instantiation macro
437 //
438 // Must be expanded from within the Tpetra namespace!
439 //
440 
441 #define TPETRA_ROWMATRIX_INSTANT(SCALAR,LO,GO,NODE) \
442  \
443  template class RowMatrix< SCALAR , LO , GO , NODE >;
444 
445 
446 #endif // TPETRA_ROWMATRIX_DEF_HPP
447 
Namespace Tpetra contains the class and methods constituting the Tpetra library.
Sparse matrix that presents a compressed sparse row interface.
virtual void getGlobalRowCopy(GlobalOrdinal GlobalRow, const Teuchos::ArrayView< GlobalOrdinal > &Indices, const Teuchos::ArrayView< Scalar > &Values, size_t &NumEntries) const =0
Get a copy of the given global row&#39;s entries.
iterator begin() const
virtual const Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > & getRangeMap() const =0
Returns the Map associated with the range of this operator, which must be compatible with Y...
T & get(const std::string &name, T def_value)
#define TEUCHOS_TEST_FOR_EXCEPTION_CLASS_FUNC(throw_exception_test, Exception, msg)
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
size_type size() const
virtual const Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > & getRowMap() const =0
The Map that describes the distribution of rows over processes.
virtual const Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > & getDomainMap() const =0
Returns the Map associated with the domain of this operator, which must be compatible with X...
virtual ~RowMatrix()
Destructor (virtual for memory safety of derived classes).
virtual size_t getNumEntriesInLocalRow(LocalOrdinal localRow) const =0
The current number of entries on the calling process in the specified local row.
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
Sets up and executes a communication plan for a Tpetra DistObject.
virtual void pack(const Teuchos::ArrayView< const LocalOrdinal > &exportLIDs, Teuchos::Array< char > &exports, const Teuchos::ArrayView< size_t > &numPacketsPerLID, size_t &constantNumPackets, Distributor &distor) const
Implementation of SrcDistObjectWithPack.
void resize(size_type new_size, const value_type &x=value_type())
virtual Teuchos::RCP< RowMatrix< Scalar, LocalOrdinal, GlobalOrdinal, Node > > add(const Scalar &alpha, const RowMatrix< Scalar, LocalOrdinal, GlobalOrdinal, Node > &A, const Scalar &beta, const Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > &domainMap=Teuchos::null, const Teuchos::RCP< const Map< LocalOrdinal, GlobalOrdinal, Node > > &rangeMap=Teuchos::null, const Teuchos::RCP< Teuchos::ParameterList > &params=Teuchos::null) const
Return a new RowMatrix which is the result of beta*this + alpha*A.
Describes a parallel distribution of objects over processes.
A read-only, row-oriented interface to a sparse matrix.
iterator end() const
size_type size() const
TypeTo as(const TypeFrom &t)
bool is_null() const