Tpetra Matrix/Vector Services  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
TpetraExt_MatrixMatrix_def.hpp
Go to the documentation of this file.
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_MATRIXMATRIX_DEF_HPP
43 #define TPETRA_MATRIXMATRIX_DEF_HPP
44 
45 #include "TpetraExt_MatrixMatrix_decl.hpp"
46 #include "Teuchos_VerboseObject.hpp"
47 #include "Teuchos_Array.hpp"
48 #include "Tpetra_Util.hpp"
49 #include "Tpetra_ConfigDefs.hpp"
50 #include "Tpetra_CrsMatrix.hpp"
51 #include "TpetraExt_MMHelpers_def.hpp"
52 #include "Tpetra_RowMatrixTransposer.hpp"
53 #include "Tpetra_ConfigDefs.hpp"
54 #include "Tpetra_Map.hpp"
55 #include <algorithm>
56 #include "Teuchos_FancyOStream.hpp"
57 
58 
64 namespace Tpetra {
65 
66 
67 namespace MatrixMatrix{
68 
69 template <class Scalar,
70  class LocalOrdinal,
71  class GlobalOrdinal,
72  class Node,
73  class SpMatOps >
74 void Multiply(
75  const CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& A,
76  bool transposeA,
77  const CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& B,
78  bool transposeB,
79  CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& C,
80  bool call_FillComplete_on_result)
81 {
82  //TEUCHOS_FUNC_TIME_MONITOR_DIFF("My Matrix Mult", mmm_multiply);
83  typedef CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps> Matrix_t;
84  //
85  //This method forms the matrix-matrix product C = op(A) * op(B), where
86  //op(A) == A if transposeA is false,
87  //op(A) == A^T if transposeA is true,
88  //and similarly for op(B).
89  //
90 
91  //A and B should already be Filled.
92  //(Should we go ahead and call FillComplete() on them if necessary?
93  // or error out? For now, we choose to error out.)
94  TEUCHOS_TEST_FOR_EXCEPTION(!A.isFillComplete(), std::runtime_error,
95  "Uh oh. Looks like there's a bit of a problem here. No worries though. We'll help you figure it out. You're "
96  "a fantastic programer and this just a minor bump in the road! Maybe the information below can help you out a bit."
97  "\n\n MatrixMatrix::Multiply(): Matrix A is not fill complete.");
98  TEUCHOS_TEST_FOR_EXCEPTION(!B.isFillComplete(), std::runtime_error,
99  "Uh oh. Looks like there's a bit of a problem here. No worries though. We'll help you figure it out. You're "
100  "a fantastic programer and this just a minor bump in the road! Maybe the information below can help you out a bit."
101  "\n\n MatrixMatrix::Multiply(): Matrix B is not fill complete.");
102  TEUCHOS_TEST_FOR_EXCEPTION(C.isLocallyIndexed() , std::runtime_error,
103  "MatrixMatrix::Add ERROR, input matrix C must not be locally indexed!");
104 
105  //Convience typedefs
106  typedef CrsMatrixStruct<
107  Scalar,
108  LocalOrdinal,
109  GlobalOrdinal,
110  Node,
111  SpMatOps> CrsMatrixStruct_t;
112  typedef Map<LocalOrdinal, GlobalOrdinal, Node> Map_t;
113 
114  RCP<const Matrix_t > Aprime = null;
115  RCP<const Matrix_t > Bprime = null;
116  if(transposeA){
117  RowMatrixTransposer<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps> at (Teuchos::rcpFromRef (A));
118  Aprime = at.createTranspose();
119  }
120  else{
121  Aprime = rcpFromRef(A);
122  }
123  if(transposeB){
124  RowMatrixTransposer<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps> bt (Teuchos::rcpFromRef (B));
125  Bprime=bt.createTranspose();
126  }
127  else{
128  Bprime = rcpFromRef(B);
129  }
130 
131 
132  //now check size compatibility
133  global_size_t numACols = A.getDomainMap()->getGlobalNumElements();
134  global_size_t numBCols = B.getDomainMap()->getGlobalNumElements();
135  global_size_t Aouter = transposeA ? numACols : A.getGlobalNumRows();
136  global_size_t Bouter = transposeB ? B.getGlobalNumRows() : numBCols;
137  global_size_t Ainner = transposeA ? A.getGlobalNumRows() : numACols;
138  global_size_t Binner = transposeB ? numBCols : B.getGlobalNumRows();
139  TEUCHOS_TEST_FOR_EXCEPTION(!A.isFillComplete(), std::runtime_error,
140  "MatrixMatrix::Multiply: ERROR, inner dimensions of op(A) and op(B) "
141  "must match for matrix-matrix product. op(A) is "
142  <<Aouter<<"x"<<Ainner << ", op(B) is "<<Binner<<"x"<<Bouter<<std::endl);
143 
144  //The result matrix C must at least have a row-map that reflects the
145  //correct row-size. Don't check the number of columns because rectangular
146  //matrices which were constructed with only one map can still end up
147  //having the correct capacity and dimensions when filled.
148  TEUCHOS_TEST_FOR_EXCEPTION(Aouter > C.getGlobalNumRows(), std::runtime_error,
149  "MatrixMatrix::Multiply: ERROR, dimensions of result C must "
150  "match dimensions of op(A) * op(B). C has "<<C.getGlobalNumRows()
151  << " rows, should have at least "<<Aouter << std::endl);
152 
153  //It doesn't matter whether C is already Filled or not. If it is already
154  //Filled, it must have space allocated for the positions that will be
155  //referenced in forming C = op(A)*op(B). If it doesn't have enough space,
156  //we'll error out later when trying to store result values.
157 
158  // CGB: However, matrix must be in active-fill
159  TEUCHOS_TEST_FOR_EXCEPT( C.isFillActive() == false );
160 
161  //We're going to need to import remotely-owned sections of A and/or B
162  //if more than 1 processor is performing this run, depending on the scenario.
163  int numProcs = A.getComm()->getSize();
164 
165  //Declare a couple of structs that will be used to hold views of the data
166  //of A and B, to be used for fast access during the matrix-multiplication.
167  CrsMatrixStruct_t Aview;
168  CrsMatrixStruct_t Bview;
169 
170  RCP<const Map_t > targetMap_A = Aprime->getRowMap();
171  RCP<const Map_t > targetMap_B = Bprime->getRowMap();
172 
173  //Now import any needed remote rows and populate the Aview struct.
174  MMdetails::import_and_extract_views(*Aprime, targetMap_A, Aview);
175 
176 
177  //We will also need local access to all rows of B that correspond to the
178  //column-map of op(A).
179  if (numProcs > 1) {
180  targetMap_B = Aprime->getColMap(); //colmap_op_A;
181  }
182 
183  //Now import any needed remote rows and populate the Bview struct.
184  MMdetails::import_and_extract_views(*Bprime, targetMap_B, Bview);
185 
186 
187  //If the result matrix C is not already FillComplete'd, we will do a
188  //preprocessing step to create the nonzero structure,
189  /*
190  if (!C.isFillComplete()) {
191  CrsWrapper_GraphBuilder<Scalar, LocalOrdinal, GlobalOrdinal, Node> crsgraphbuilder(C.getRowMap());
192 
193  //pass the graph-builder object to the multiplication kernel to fill in all
194  //the nonzero positions that will be used in the result matrix.
195  MMdetails::mult_A_B(Aview, Bview, crsgraphbuilder, true);
196 
197  //now insert all of the nonzero positions into the result matrix.
198  insert_matrix_locations(crsgraphbuilder, C);
199 
200 
201  if (call_FillComplete_on_result) {
202  C.fillComplete(Bprime->getDomainMap(), Aprime->getRangeMap());
203  call_FillComplete_on_result = false;
204  }
205  }
206  */
207 
208  //Now call the appropriate method to perform the actual multiplication.
209 
210  CrsWrapper_CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> crsmat(C);
211 
212  MMdetails::mult_A_B(Aview, Bview, crsmat);
213 
214  if (call_FillComplete_on_result) {
215  //We'll call FillComplete on the C matrix before we exit, and give
216  //it a domain-map and a range-map.
217  //The domain-map will be the domain-map of B, unless
218  //op(B)==transpose(B), in which case the range-map of B will be used.
219  //The range-map will be the range-map of A, unless
220  //op(A)==transpose(A), in which case the domain-map of A will be used.
221  if (!C.isFillComplete()) {
222  C.fillComplete(Bprime->getDomainMap(), Aprime->getRangeMap());
223  }
224  }
225 
226 }
227 
228 
229 template <class Scalar,
230  class LocalOrdinal,
231  class GlobalOrdinal,
232  class Node,
233  class SpMatOps >
234 void Add(
235  const CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& A,
236  bool transposeA,
237  Scalar scalarA,
238  CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& B,
239  Scalar scalarB )
240 {
241  TEUCHOS_TEST_FOR_EXCEPTION(!A.isFillComplete(), std::runtime_error,
242  "MatrixMatrix::Add ERROR, input matrix A.isFillComplete() is false; it is required to be true. (Result matrix B is not required to be isFillComplete()).");
243  TEUCHOS_TEST_FOR_EXCEPTION(B.isFillComplete() , std::runtime_error,
244  "MatrixMatrix::Add ERROR, input matrix B must not be fill complete!");
245  TEUCHOS_TEST_FOR_EXCEPTION(B.isStaticGraph() , std::runtime_error,
246  "MatrixMatrix::Add ERROR, input matrix B must not have static graph!");
247  TEUCHOS_TEST_FOR_EXCEPTION(B.isLocallyIndexed() , std::runtime_error,
248  "MatrixMatrix::Add ERROR, input matrix B must not be locally indexed!");
249  TEUCHOS_TEST_FOR_EXCEPTION(B.getProfileType()!=DynamicProfile, std::runtime_error,
250  "MatrixMatrix::Add ERROR, input matrix B must have a dynamic profile!");
251  //Convience typedef
252  typedef CrsMatrix<
253  Scalar,
254  LocalOrdinal,
255  GlobalOrdinal,
256  Node,
257  SpMatOps> CrsMatrix_t;
258  RCP<const CrsMatrix_t> Aprime = null;
259  if( transposeA ){
260  RowMatrixTransposer<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps> theTransposer(Teuchos::rcpFromRef (A));
261  Aprime = theTransposer.createTranspose();
262  }
263  else{
264  Aprime = rcpFromRef(A);
265  }
266  size_t a_numEntries;
267  Array<GlobalOrdinal> a_inds(A.getNodeMaxNumRowEntries());
268  Array<Scalar> a_vals(A.getNodeMaxNumRowEntries());
269  GlobalOrdinal row;
270 
271  if(scalarB != ScalarTraits<Scalar>::one()){
272  B.scale(scalarB);
273  }
274 
275  bool bFilled = B.isFillComplete();
276  size_t numMyRows = B.getNodeNumRows();
277  if(scalarA != ScalarTraits<Scalar>::zero()){
278  for(LocalOrdinal i = 0; (size_t)i < numMyRows; ++i){
279  row = B.getRowMap()->getGlobalElement(i);
280  Aprime->getGlobalRowCopy(row, a_inds(), a_vals(), a_numEntries);
281  if(scalarA != ScalarTraits<Scalar>::one()){
282  for(size_t j =0; j<a_numEntries; ++j){
283  a_vals[j] *= scalarA;
284  }
285  }
286  if(bFilled){
287  B.sumIntoGlobalValues(row, a_inds(0,a_numEntries), a_vals(0,a_numEntries));
288  }
289  else{
290  B.insertGlobalValues(row, a_inds(0,a_numEntries), a_vals(0,a_numEntries));
291  }
292 
293  }
294  }
295 }
296 
297 
298 template <class Scalar,
299  class LocalOrdinal,
300  class GlobalOrdinal,
301  class Node,
302  class SpMatOps >
303 Teuchos::RCP<CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps> >
304 add (const Scalar& alpha,
305  const bool transposeA,
306  const CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& A,
307  const Scalar& beta,
308  const bool transposeB,
309  const CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& B,
310  const Teuchos::RCP<const Map<LocalOrdinal, GlobalOrdinal, Node> >& domainMap,
311  const Teuchos::RCP<const Map<LocalOrdinal, GlobalOrdinal, Node> >& rangeMap,
312  const Teuchos::RCP<Teuchos::ParameterList>& params)
313 {
314  using Teuchos::RCP;
315  using Teuchos::rcp;
316  using Teuchos::rcpFromRef;
317  using Teuchos::rcp_dynamic_cast;
318  using Teuchos::rcp_implicit_cast;
319  typedef RowMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> row_matrix_type;
320  typedef CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps> crs_matrix_type;
321  typedef RowMatrixTransposer<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps> transposer_type;
322 
323  TEUCHOS_TEST_FOR_EXCEPTION(
324  ! A.isFillComplete () || ! B.isFillComplete (), std::invalid_argument,
325  "Tpetra::MatrixMatrix::add: A and B must both be fill complete.");
326 
327 #ifdef HAVE_TPETRA_DEBUG
328  // The matrices don't have domain or range Maps unless they are fill complete.
329  if (A.isFillComplete () && B.isFillComplete ()) {
330  const bool domainMapsSame =
331  (! transposeA && ! transposeB && ! A.getDomainMap ()->isSameAs (* (B.getDomainMap ()))) ||
332  (! transposeA && transposeB && ! A.getDomainMap ()->isSameAs (* (B.getRangeMap ()))) ||
333  (transposeA && ! transposeB && ! A.getRangeMap ()->isSameAs (* (B.getDomainMap ())));
334  TEUCHOS_TEST_FOR_EXCEPTION(
335  domainMapsSame, std::invalid_argument,
336  "Tpetra::MatrixMatrix::add: The domain Maps of Op(A) and Op(B) are not the same.");
337 
338  const bool rangeMapsSame =
339  (! transposeA && ! transposeB && ! A.getRangeMap ()->isSameAs (* (B.getRangeMap ()))) ||
340  (! transposeA && transposeB && ! A.getRangeMap ()->isSameAs (* (B.getDomainMap ()))) ||
341  (transposeA && ! transposeB && ! A.getDomainMap ()->isSameAs (* (B.getRangeMap ())));
342  TEUCHOS_TEST_FOR_EXCEPTION(
343  rangeMapsSame, std::invalid_argument,
344  "Tpetra::MatrixMatrix::add: The range Maps of Op(A) and Op(B) are not the same.");
345  }
346 #endif // HAVE_TPETRA_DEBUG
347 
348  // Form the explicit transpose of A if necessary.
349  RCP<const crs_matrix_type> Aprime;
350  if (transposeA) {
351  transposer_type theTransposer (rcpFromRef (A));
352  Aprime = theTransposer.createTranspose ();
353  } else {
354  Aprime = rcpFromRef (A);
355  }
356 
357 #ifdef HAVE_TPETRA_DEBUG
358  TEUCHOS_TEST_FOR_EXCEPTION(Aprime.is_null (), std::logic_error,
359  "Tpetra::MatrixMatrix::Add: Failed to compute Op(A). "
360  "Please report this bug to the Tpetra developers.");
361 #endif // HAVE_TPETRA_DEBUG
362 
363  // Form the explicit transpose of B if necessary.
364  RCP<const crs_matrix_type> Bprime;
365  if (transposeB) {
366  transposer_type theTransposer (rcpFromRef (B));
367  Bprime = theTransposer.createTranspose ();
368  } else {
369  Bprime = rcpFromRef (B);
370  }
371 
372 #ifdef HAVE_TPETRA_DEBUG
373  TEUCHOS_TEST_FOR_EXCEPTION(Bprime.is_null (), std::logic_error,
374  "Tpetra::MatrixMatrix::Add: Failed to compute Op(B). "
375  "Please report this bug to the Tpetra developers.");
376 
377  TEUCHOS_TEST_FOR_EXCEPTION(
378  ! Aprime->isFillComplete () || ! Bprime->isFillComplete (), std::invalid_argument,
379  "Tpetra::MatrixMatrix::add: Aprime and Bprime must both be fill complete. "
380  "Please report this bug to the Tpetra developers.");
381 #endif // HAVE_TPETRA_DEBUG
382 
383 
384  RCP<row_matrix_type> C =
385  Bprime->add (alpha, *rcp_implicit_cast<const row_matrix_type> (Aprime),
386  beta, domainMap, rangeMap, params);
387  // FIXME (mfh 09 May 2013) This cast won't work if SpMatOps is not the default.
388  return rcp_dynamic_cast<crs_matrix_type> (C);
389 }
390 
391 
392 
393 
394 template <class Scalar,
395  class LocalOrdinal,
396  class GlobalOrdinal,
397  class Node,
398  class SpMatOps>
399 void Add(
400  const CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& A,
401  bool transposeA,
402  Scalar scalarA,
403  const CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& B,
404  bool transposeB,
405  Scalar scalarB,
406  RCP<CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps> > C)
407 {
408  using Teuchos::as;
409  using Teuchos::Array;
410  using Teuchos::ArrayRCP;
411  using Teuchos::ArrayView;
412  using Teuchos::RCP;
413  using Teuchos::rcp;
414  using Teuchos::rcp_dynamic_cast;
415  using Teuchos::rcpFromRef;
416  using Teuchos::tuple;
417  using std::endl;
418  typedef typename ArrayView<const Scalar>::size_type size_type;
419  typedef Teuchos::ScalarTraits<Scalar> STS;
420  typedef Map<LocalOrdinal, GlobalOrdinal, Node> map_type;
421  typedef Import<LocalOrdinal, GlobalOrdinal, Node> import_type;
422  typedef RowGraph<LocalOrdinal, GlobalOrdinal, Node> row_graph_type;
423  typedef CrsGraph<LocalOrdinal, GlobalOrdinal, Node, SpMatOps> crs_graph_type;
424  typedef CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps> crs_matrix_type;
425  typedef RowMatrixTransposer<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps> transposer_type;
426 
427  TEUCHOS_TEST_FOR_EXCEPTION(C.is_null (), std::logic_error,
428  "Tpetra::MatrixMatrix::Add: The case C == null does not actually work. "
429  "Fixing this will require an interface change.");
430 
431  TEUCHOS_TEST_FOR_EXCEPTION(
432  ! A.isFillComplete () || ! B.isFillComplete (), std::invalid_argument,
433  "Tpetra::MatrixMatrix::Add: Both input matrices must be fill complete "
434  "before calling this function.");
435 
436 #ifdef HAVE_TPETRA_DEBUG
437  {
438  const bool domainMapsSame =
439  (! transposeA && ! transposeB && ! A.getDomainMap ()->isSameAs (* (B.getDomainMap ()))) ||
440  (! transposeA && transposeB && ! A.getDomainMap ()->isSameAs (* (B.getRangeMap ()))) ||
441  (transposeA && ! transposeB && ! A.getRangeMap ()->isSameAs (* (B.getDomainMap ())));
442  TEUCHOS_TEST_FOR_EXCEPTION(
443  domainMapsSame, std::invalid_argument,
444  "Tpetra::MatrixMatrix::Add: The domain Maps of Op(A) and Op(B) are not the same.");
445 
446  const bool rangeMapsSame =
447  (! transposeA && ! transposeB && ! A.getRangeMap ()->isSameAs (* (B.getRangeMap ()))) ||
448  (! transposeA && transposeB && ! A.getRangeMap ()->isSameAs (* (B.getDomainMap ()))) ||
449  (transposeA && ! transposeB && ! A.getDomainMap ()->isSameAs (* (B.getRangeMap ())));
450  TEUCHOS_TEST_FOR_EXCEPTION(
451  rangeMapsSame, std::invalid_argument,
452  "Tpetra::MatrixMatrix::Add: The range Maps of Op(A) and Op(B) are not the same.");
453  }
454 #endif // HAVE_TPETRA_DEBUG
455 
456  // Form the explicit transpose of A if necessary.
457  RCP<const crs_matrix_type> Aprime;
458  if (transposeA) {
459  transposer_type theTransposer (rcpFromRef (A));
460  Aprime = theTransposer.createTranspose ();
461  } else {
462  Aprime = rcpFromRef (A);
463  }
464 
465 #ifdef HAVE_TPETRA_DEBUG
466  TEUCHOS_TEST_FOR_EXCEPTION(Aprime.is_null (), std::logic_error,
467  "Tpetra::MatrixMatrix::Add: Failed to compute Op(A). "
468  "Please report this bug to the Tpetra developers.");
469 #endif // HAVE_TPETRA_DEBUG
470 
471  // Form the explicit transpose of B if necessary.
472  RCP<const crs_matrix_type> Bprime;
473  if (transposeB) {
474  transposer_type theTransposer (rcpFromRef (B));
475  Bprime = theTransposer.createTranspose ();
476  } else {
477  Bprime = rcpFromRef (B);
478  }
479 
480 #ifdef HAVE_TPETRA_DEBUG
481  TEUCHOS_TEST_FOR_EXCEPTION(Bprime.is_null (), std::logic_error,
482  "Tpetra::MatrixMatrix::Add: Failed to compute Op(B). "
483  "Please report this bug to the Tpetra developers.");
484 #endif // HAVE_TPETRA_DEBUG
485 
486  // Allocate or zero the entries of the result matrix.
487  if (! C.is_null ()) {
488  C->setAllToScalar (STS::zero ());
489  } else {
490 #if 0
491  // If Aprime and Bprime have the same row Map, and if C is null,
492  // we can optimize construction and fillComplete of C. For now,
493  // we just check pointer equality, to avoid the all-reduce in
494  // isSameAs. It may be worth that all-reduce to check, however.
495  //if (Aprime->getRowMap ().getRawPtr () == Bprime->getRowMap ().getRawPtr ()) {
496  if (Aprime->getRowMap ()->isSameAs (* (Bprime->getRowMap ())) {
497  RCP<const map_type> rowMap = Aprime->getRowMap ();
498 
499  RCP<const crs_graph_type> A_graph =
500  rcp_dynamic_cast<const crs_graph_type> (Aprime->getGraph (), true);
501 #ifdef HAVE_TPETRA_DEBUG
502  TEUCHOS_TEST_FOR_EXCEPTION(A_graph.is_null (), std::logic_error,
503  "Tpetra::MatrixMatrix::Add: Graph of Op(A) is null. "
504  "Please report this bug to the Tpetra developers.");
505 #endif // HAVE_TPETRA_DEBUG
506  RCP<const crs_graph_type> B_graph =
507  rcp_dynamic_cast<const crs_graph_type> (Bprime->getGraph (), true);
508 #ifdef HAVE_TPETRA_DEBUG
509  TEUCHOS_TEST_FOR_EXCEPTION(B_graph.is_null (), std::logic_error,
510  "Tpetra::MatrixMatrix::Add: Graph of Op(B) is null. "
511  "Please report this bug to the Tpetra developers.");
512 #endif // HAVE_TPETRA_DEBUG
513  RCP<const map_type> A_colMap = A_graph->getColMap ();
514 #ifdef HAVE_TPETRA_DEBUG
515  TEUCHOS_TEST_FOR_EXCEPTION(A_colMap.is_null (), std::logic_error,
516  "Tpetra::MatrixMatrix::Add: Column Map of Op(A) is null. "
517  "Please report this bug to the Tpetra developers.");
518 #endif // HAVE_TPETRA_DEBUG
519  RCP<const map_type> B_colMap = B_graph->getColMap ();
520 #ifdef HAVE_TPETRA_DEBUG
521  TEUCHOS_TEST_FOR_EXCEPTION(B_colMap.is_null (), std::logic_error,
522  "Tpetra::MatrixMatrix::Add: Column Map of Op(B) is null. "
523  "Please report this bug to the Tpetra developers.");
524  TEUCHOS_TEST_FOR_EXCEPTION(A_graph->getImporter ().is_null (),
525  std::logic_error,
526  "Tpetra::MatrixMatrix::Add: Op(A)'s Import is null. "
527  "Please report this bug to the Tpetra developers.");
528  TEUCHOS_TEST_FOR_EXCEPTION(B_graph->getImporter ().is_null (),
529  std::logic_error,
530  "Tpetra::MatrixMatrix::Add: Op(B)'s Import is null. "
531  "Please report this bug to the Tpetra developers.");
532 #endif // HAVE_TPETRA_DEBUG
533 
534  // Compute the (column Map and) Import of the matrix sum.
535  RCP<const import_type> sumImport =
536  A_graph->getImporter ()->setUnion (* (B_graph->getImporter ()));
537  RCP<const map_type> C_colMap = sumImport->getTargetMap ();
538 
539  // First, count the number of entries in each row. Then, go
540  // back over the rows again, and compute the actual sum.
541  // Remember that C may have a different column Map than Aprime
542  // or Bprime, so its local indices may be different. That's why
543  // we have to convert from local to global indices.
544 
545  ArrayView<const LocalOrdinal> A_local_ind;
546  Array<GlobalOrdinal> A_global_ind;
547  ArrayView<const LocalOrdinal> B_local_ind;
548  Array<GlobalOrdinal> B_global_ind;
549 
550  const size_t localNumRows = rowMap->getNodeNumElements ();
551  ArrayRCP<size_t> numEntriesPerRow (localNumRows);
552  // Compute the max number of entries in any row of A+B on this
553  // process, so that we won't have to resize temporary arrays.
554  size_t maxNumEntriesPerRow = 0;
555  for (size_t localRow = 0; localRow < localNumRows; ++localRow) {
556  // Get view of current row of A_graph, in its local indices.
557  A_graph->getLocalRowView (as<LocalOrdinal> (localRow), A_local_ind);
558  const size_type A_numEnt = A_local_ind.size ();
559  if (A_numEnt > A_global_ind.size ()) {
560  A_global_ind.resize (A_numEnt);
561  }
562  // Convert A's local indices to global indices.
563  for (size_type k = 0; k < A_numEnt; ++k) {
564  A_global_ind[k] = A_colMap->getGlobalElement (A_local_ind[k]);
565  }
566 
567  // Get view of current row of B_graph, in its local indices.
568  B_graph->getLocalRowView (as<LocalOrdinal> (localRow), B_local_ind);
569  const size_type B_numEnt = B_local_ind.size ();
570  if (B_numEnt > B_global_ind.size ()) {
571  B_global_ind.resize (B_numEnt);
572  }
573  // Convert B's local indices to global indices.
574  for (size_type k = 0; k < B_numEnt; ++k) {
575  B_global_ind[k] = B_colMap->getGlobalElement (B_local_ind[k]);
576  }
577 
578  // Count the number of entries in the merged row of A + B.
579  const size_t curNumEntriesPerRow =
580  keyMergeCount (A_global_ind.begin (), A_global_ind.end (),
581  B_global_ind.begin (), B_global_ind.end ());
582  numEntriesPerRow[localRow] = curNumEntriesPerRow;
583  maxNumEntriesPerRow = std::max (maxNumEntriesPerRow, curNumEntriesPerRow);
584  }
585 
586  // Create C, using the sum column Map and number of entries per
587  // row that we computed above. Having the exact number of
588  // entries per row lets us use static profile, making it valid
589  // to call expertStaticFillComplete.
590  C = rcp (new crs_matrix_type (rowMap, C_colMap, numEntriesPerRow, StaticProfile));
591 
592  // Go back through the rows and actually compute the sum. We
593  // don't ever have to resize A_global_ind or B_global_ind below,
594  // since we've already done it above.
595  ArrayView<const Scalar> A_val;
596  ArrayView<const Scalar> B_val;
597 
598  Array<LocalOrdinal> AplusB_local_ind (maxNumEntriesPerRow);
599  Array<GlobalOrdinal> AplusB_global_ind (maxNumEntriesPerRow);
600  Array<Scalar> AplusB_val (maxNumEntriesPerRow);
601 
602  for (size_t localRow = 0; localRow < localNumRows; ++localRow) {
603  // Get view of current row of A, in A's local indices.
604  Aprime->getLocalRowView (as<LocalOrdinal> (localRow), A_local_ind, A_val);
605  // Convert A's local indices to global indices.
606  for (size_type k = 0; k < A_local_ind.size (); ++k) {
607  A_global_ind[k] = A_colMap->getGlobalElement (A_local_ind[k]);
608  }
609 
610  // Get view of current row of B, in B's local indices.
611  Bprime->getLocalRowView (as<LocalOrdinal> (localRow), B_local_ind, B_val);
612  // Convert B's local indices to global indices.
613  for (size_type k = 0; k < B_local_ind.size (); ++k) {
614  B_global_ind[k] = B_colMap->getGlobalElement (B_local_ind[k]);
615  }
616 
617  const size_t curNumEntries = numEntriesPerRow[localRow];
618  ArrayView<LocalOrdinal> C_local_ind = AplusB_local_ind (0, curNumEntries);
619  ArrayView<GlobalOrdinal> C_global_ind = AplusB_global_ind (0, curNumEntries);
620  ArrayView<Scalar> C_val = AplusB_val (0, curNumEntries);
621 
622  // Sum the entries in the current row of A plus B.
623  keyValueMerge (A_global_ind.begin (), A_global_ind.end (),
624  A_val.begin (), A_val.end (),
625  B_global_ind.begin (), B_global_ind.end (),
626  B_val.begin (), B_val.end (),
627  C_global_ind.begin (), C_val.begin (),
628  std::plus<Scalar> ());
629  // Convert the sum's global indices into C's local indices.
630  for (size_type k = 0; k < as<size_type> (numEntriesPerRow[localRow]); ++k) {
631  C_local_ind[k] = C_colMap->getLocalElement (C_global_ind[k]);
632  }
633  // Give the current row sum to C.
634  C->replaceLocalValues (localRow, C_local_ind, C_val);
635  }
636 
637  // Use "expert static fill complete" to bypass construction of
638  // the Import and Export (if applicable) object(s).
639  RCP<const map_type> domainMap = A_graph->getDomainMap ();
640  RCP<const map_type> rangeMap = A_graph->getRangeMap ();
641  C->expertStaticFillComplete (domainMap, rangeMap, sumImport, A_graph->getExporter ());
642 
643  return; // Now we're done!
644  }
645  else {
646  // FIXME (mfh 08 May 2013) When I first looked at this method, I
647  // noticed that C was being given the row Map of Aprime (the
648  // possibly transposed version of A). Is this what we want?
649  C = rcp (new crs_matrix_type (Aprime->getRowMap (), null));
650  }
651 
652 #else
653  // FIXME (mfh 08 May 2013) When I first looked at this method, I
654  // noticed that C was being given the row Map of Aprime (the
655  // possibly transposed version of A). Is this what we want?
656  C = rcp (new crs_matrix_type (Aprime->getRowMap (), 0));
657 #endif // 0
658  }
659 
660 #ifdef HAVE_TPETRA_DEBUG
661  TEUCHOS_TEST_FOR_EXCEPTION(Aprime.is_null (), std::logic_error,
662  "Tpetra::MatrixMatrix::Add: At this point, Aprime is null. "
663  "Please report this bug to the Tpetra developers.");
664  TEUCHOS_TEST_FOR_EXCEPTION(Bprime.is_null (), std::logic_error,
665  "Tpetra::MatrixMatrix::Add: At this point, Bprime is null. "
666  "Please report this bug to the Tpetra developers.");
667  TEUCHOS_TEST_FOR_EXCEPTION(C.is_null (), std::logic_error,
668  "Tpetra::MatrixMatrix::Add: At this point, C is null. "
669  "Please report this bug to the Tpetra developers.");
670 #endif // HAVE_TPETRA_DEBUG
671 
672  Array<RCP<const crs_matrix_type> > Mat =
673  tuple<RCP<const crs_matrix_type> > (Aprime, Bprime);
674  Array<Scalar> scalar = tuple<Scalar> (scalarA, scalarB);
675 
676  // do a loop over each matrix to add: A reordering might be more efficient
677  for (int k = 0; k < 2; ++k) {
678  Array<GlobalOrdinal> Indices;
679  Array<Scalar> Values;
680 
681  // Loop over each locally owned row of the current matrix (either
682  // Aprime or Bprime), and sum its entries into the corresponding
683  // row of C. This works regardless of whether Aprime or Bprime
684  // has the same row Map as C, because both sumIntoGlobalValues and
685  // insertGlobalValues allow summing resp. inserting into nonowned
686  // rows of C.
687 #ifdef HAVE_TPETRA_DEBUG
688  TEUCHOS_TEST_FOR_EXCEPTION(Mat[k].is_null (), std::logic_error,
689  "Tpetra::MatrixMatrix::Add: At this point, curRowMap is null. "
690  "Please report this bug to the Tpetra developers.");
691 #endif // HAVE_TPETRA_DEBUG
692  RCP<const map_type> curRowMap = Mat[k]->getRowMap ();
693 #ifdef HAVE_TPETRA_DEBUG
694  TEUCHOS_TEST_FOR_EXCEPTION(curRowMap.is_null (), std::logic_error,
695  "Tpetra::MatrixMatrix::Add: At this point, curRowMap is null. "
696  "Please report this bug to the Tpetra developers.");
697 #endif // HAVE_TPETRA_DEBUG
698 
699  const size_t localNumRows = Mat[k]->getNodeNumRows ();
700  for (size_t i = 0; i < localNumRows; ++i) {
701  const GlobalOrdinal globalRow = curRowMap->getGlobalElement (i);
702  size_t numEntries = Mat[k]->getNumEntriesInGlobalRow (globalRow);
703  if (numEntries > 0) {
704  Indices.resize (numEntries);
705  Values.resize (numEntries);
706  Mat[k]->getGlobalRowCopy (globalRow, Indices (), Values (), numEntries);
707 
708  if (scalar[k] != STS::one ()) {
709  for (size_t j = 0; j < numEntries; ++j) {
710  Values[j] *= scalar[k];
711  }
712  }
713 
714  if (C->isFillComplete ()) {
715  C->sumIntoGlobalValues (globalRow, Indices, Values);
716  } else {
717  C->insertGlobalValues (globalRow, Indices, Values);
718  }
719  }
720  }
721  }
722 }
723 
724 } //End namespace MatrixMatrix
725 
726 namespace MMdetails{
727 
728 
729 //kernel method for computing the local portion of C = A*B
730 template<class Scalar,
731  class LocalOrdinal,
732  class GlobalOrdinal,
733  class Node,
734  class SpMatOps>
735 void mult_A_B(
736  CrsMatrixStruct<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& Aview,
737  CrsMatrixStruct<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& Bview,
738  CrsWrapper<Scalar, LocalOrdinal, GlobalOrdinal, Node>& C,
739  bool onlyCalculateStructure)
740 {
741  //TEUCHOS_FUNC_TIME_MONITOR_DIFF("mult_A_B", mult_A_B);
742  LocalOrdinal C_firstCol = Bview.colMap->getMinLocalIndex();
743  LocalOrdinal C_lastCol = Bview.colMap->getMaxLocalIndex();
744 
745  LocalOrdinal C_firstCol_import = OrdinalTraits<LocalOrdinal>::zero();
746  LocalOrdinal C_lastCol_import = OrdinalTraits<LocalOrdinal>::invalid();
747 
748  ArrayView<const GlobalOrdinal> bcols = Bview.colMap->getNodeElementList();
749  ArrayView<const GlobalOrdinal> bcols_import = null;
750  if (Bview.importColMap != null) {
751  C_firstCol_import = Bview.importColMap->getMinLocalIndex();
752  C_lastCol_import = Bview.importColMap->getMaxLocalIndex();
753 
754  bcols_import = Bview.importColMap->getNodeElementList();
755  }
756 
757  size_t C_numCols = C_lastCol - C_firstCol +
758  OrdinalTraits<LocalOrdinal>::one();
759  size_t C_numCols_import = C_lastCol_import - C_firstCol_import +
760  OrdinalTraits<LocalOrdinal>::one();
761 
762  if (C_numCols_import > C_numCols) C_numCols = C_numCols_import;
763 
764  Array<Scalar> dwork = onlyCalculateStructure ? Array<Scalar>() : Array<Scalar>(C_numCols);
765  Array<GlobalOrdinal> iwork = Array<GlobalOrdinal>(C_numCols);
766  Array<size_t> iwork2 = Array<size_t>(C_numCols);
767 
768  Array<Scalar> C_row_i = dwork;
769  Array<GlobalOrdinal> C_cols = iwork;
770  Array<size_t> c_index = iwork2;
771  Array<GlobalOrdinal> combined_index = Array<GlobalOrdinal>(2*C_numCols);
772  Array<Scalar> combined_values = onlyCalculateStructure ? Array<Scalar>() : Array<Scalar>(2*C_numCols);
773 
774  size_t C_row_i_length, j, k, lastj, last_index;
775 
776  // Run through all the hash table lookups once and for all
777  Array<LocalOrdinal> Acol2Brow(Aview.colMap->getNodeNumElements());
778  if(Aview.colMap->isSameAs(*Bview.rowMap)){
779  // Maps are the same: Use local IDs as the hash
780  for(LocalOrdinal i=Aview.colMap->getMinLocalIndex(); i <=
781  Aview.colMap->getMaxLocalIndex(); i++)
782  Acol2Brow[i]=i;
783  }
784  else {
785  // Maps are not the same: Use the map's hash
786  for(LocalOrdinal i=Aview.colMap->getMinLocalIndex(); i <=
787  Aview.colMap->getMaxLocalIndex(); i++)
788  Acol2Brow[i]=Bview.rowMap->getLocalElement(
789  Aview.colMap->getGlobalElement(i));
790  }
791 
792  //To form C = A*B we're going to execute this expression:
793  //
794  // C(i,j) = sum_k( A(i,k)*B(k,j) )
795  //
796  //Our goal, of course, is to navigate the data in A and B once, without
797  //performing searches for column-indices, etc.
798 
799  bool C_filled = C.isFillComplete();
800 
801  for (size_t i = 0; i < C_numCols; i++)
802  c_index[i] = OrdinalTraits<size_t>::invalid();
803 
804  //loop over the rows of A.
805  for(size_t i=0; i<Aview.numRows; ++i) {
806 
807  //only navigate the local portion of Aview... (It's probable that we
808  //imported more of A than we need for A*B, because other cases like A^T*B
809  //need the extra rows.)
810  if (Aview.remote[i]) {
811  continue;
812  }
813 
814 
815  ArrayView<const LocalOrdinal> Aindices_i = Aview.indices[i];
816  ArrayView<const Scalar> Aval_i = onlyCalculateStructure ? null : Aview.values[i];
817 
818  GlobalOrdinal global_row = Aview.rowMap->getGlobalElement(i);
819 
820 
821  //loop across the i-th row of A and for each corresponding row
822  //in B, loop across colums and accumulate product
823  //A(i,k)*B(k,j) into our partial sum quantities C_row_i. In other words,
824  //as we stride across B(k,:) we're calculating updates for row i of the
825  //result matrix C.
826 
827 
828  C_row_i_length = OrdinalTraits<size_t>::zero();
829 
830  for(k = OrdinalTraits<size_t>::zero(); k < Aview.numEntriesPerRow[i]; ++k) {
831  LocalOrdinal Ak = Acol2Brow[Aindices_i[k]];
832  Scalar Aval = onlyCalculateStructure ? Teuchos::as<Scalar>(0) : Aval_i[k];
833 
834  if (Bview.remote[Ak]) continue;
835 
836  const LocalOrdinal *Bcol_inds = Bview.indices[Ak].getRawPtr();
837  const Scalar *Bvals_k = onlyCalculateStructure ? NULL :
838  Bview.values[Ak].getRawPtr();
839 
840  lastj = Bview.numEntriesPerRow[Ak];
841 
842  for(j=OrdinalTraits<size_t>::zero(); j< lastj; ++j) {
843  LocalOrdinal col = Bcol_inds[j];
844  //assert(col >= 0 && col < C_numCols);
845  if (c_index[col] == OrdinalTraits<size_t>::invalid()){
846  //assert(C_row_i_length >= 0 && C_row_i_length < C_numCols);
847  if(!onlyCalculateStructure){
848  // This has to be a += so insertGlobalValue goes out
849  C_row_i[C_row_i_length] = Aval*Bvals_k[j];
850  }
851  C_cols[C_row_i_length] = col;
852  c_index[col] = C_row_i_length;
853  C_row_i_length++;
854  }
855  else {
856  if(!onlyCalculateStructure){
857  C_row_i[c_index[col]] += Aval*Bvals_k[j];
858  }
859  }
860  }
861  }
862 
863  for (size_t ii = 0; ii < C_row_i_length; ii++) {
864  c_index[C_cols[ii]] = OrdinalTraits<size_t>::invalid();
865  C_cols[ii] = bcols[C_cols[ii]];
866  combined_index[ii] = C_cols[ii];
867  if (!onlyCalculateStructure)
868  combined_values[ii] = C_row_i[ii];
869  }
870  last_index = C_row_i_length;
871 
872  //
873  //Now put the C_row_i values into C.
874  //
875  // We might have to revamp this later.
876  /*if (!onlyCalculateStructure)
877  {
878  C_filled ?
879  C.sumIntoGlobalValues(
880  global_row,
881  C_cols.view(OrdinalTraits<size_t>::zero(), C_row_i_length),
882  onlyCalculateStructure ? null :
883  C_row_i.view(OrdinalTraits<size_t>::zero(), C_row_i_length))
884  :
885  C.insertGlobalValues(
886  global_row,
887  C_cols.view(OrdinalTraits<size_t>::zero(), C_row_i_length),
888  onlyCalculateStructure ? null :
889  C_row_i.view(OrdinalTraits<size_t>::zero(), C_row_i_length));
890  }*/
891 
892  C_row_i_length = OrdinalTraits<size_t>::zero();
893 
894  for(k = OrdinalTraits<size_t>::zero(); k < Aview.numEntriesPerRow[i]; ++k) {
895  LocalOrdinal Ak = Acol2Brow[Aindices_i[k]];
896  Scalar Aval = onlyCalculateStructure ? Teuchos::as<Scalar>(0) : Aval_i[k];
897 
898  if (!Bview.remote[Ak]) continue;
899 
900  const LocalOrdinal *Bcol_inds = Bview.indices[Ak].getRawPtr();
901  const Scalar *Bvals_k = onlyCalculateStructure ? NULL :
902  Bview.values[Ak].getRawPtr();
903 
904  lastj = Bview.numEntriesPerRow[Ak];
905  for(j=OrdinalTraits<size_t>::zero(); j< lastj; ++j) {
906  LocalOrdinal col = Bcol_inds[j];
907  //assert(col >= 0 && col < C_numCols);
908  if (c_index[col] == OrdinalTraits<size_t>::invalid()){
909  //assert(C_row_i_length >= 0 && C_row_i_length < C_numCols);
910  if(!onlyCalculateStructure){
911  // This has to be a += so insertGlobalValue goes out
912  C_row_i[C_row_i_length] = Aval*Bvals_k[j];
913  }
914  C_cols[C_row_i_length] = col;
915  c_index[col] = C_row_i_length;
916  C_row_i_length++;
917  }
918  else {
919  if(!onlyCalculateStructure){
920  // This has to be a += so insertGlobalValue goes out
921  C_row_i[c_index[col]] += Aval*Bvals_k[j];
922  }
923  }
924  }
925  }
926 
927  for (size_t ii = 0; ii < C_row_i_length; ii++) {
928  c_index[C_cols[ii]] = OrdinalTraits<size_t>::invalid();
929  C_cols[ii] = bcols_import[C_cols[ii]];
930  combined_index[last_index] = C_cols[ii];
931  if (!onlyCalculateStructure)
932  combined_values[last_index] = C_row_i[ii];
933  last_index++;
934  }
935 
936  //
937  //Now put the C_row_i values into C.
938  //
939  // We might have to revamp this later.
940  if (!onlyCalculateStructure)
941  {
942  C_filled ?
943  C.sumIntoGlobalValues(
944  global_row,
945  combined_index.view(OrdinalTraits<size_t>::zero(), last_index),
946  onlyCalculateStructure ? null : combined_values.view(
947  OrdinalTraits<size_t>::zero(), last_index))
948  :
949  C.insertGlobalValues(
950  global_row,
951  combined_index.view(OrdinalTraits<size_t>::zero(), last_index),
952  onlyCalculateStructure ? null : combined_values.view(
953  OrdinalTraits<size_t>::zero(), last_index));
954  }
955 
956  }
957 
958 }
959 
960 template<class Scalar,
961  class LocalOrdinal,
962  class GlobalOrdinal,
963  class Node,
964  class SpMatOps>
965 void setMaxNumEntriesPerRow(
966  CrsMatrixStruct<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& Mview)
967 {
968  typedef typename Array<ArrayView<const LocalOrdinal> >::size_type local_length_size;
969  Mview.maxNumRowEntries = OrdinalTraits<local_length_size>::zero();
970  if(Mview.indices.size() > OrdinalTraits<local_length_size>::zero() ){
971  Mview.maxNumRowEntries = Mview.indices[0].size();
972  for(local_length_size i = 1; i<Mview.indices.size(); ++i){
973  if(Mview.indices[i].size() > Mview.maxNumRowEntries){
974  Mview.maxNumRowEntries = Mview.indices[i].size();
975  }
976  }
977  }
978 }
979 
980 template<class Scalar,
981  class LocalOrdinal,
982  class GlobalOrdinal,
983  class Node,
984  class SpMatOps>
985 void import_and_extract_views(
986  const CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& M,
987  RCP<const Map<LocalOrdinal, GlobalOrdinal, Node> > targetMap,
988  CrsMatrixStruct<Scalar, LocalOrdinal, GlobalOrdinal, Node, SpMatOps>& Mview)
989 {
990  //Convience typedef
991  typedef Map<LocalOrdinal, GlobalOrdinal, Node> Map_t;
992  // The goal of this method is to populate the 'Mview' struct with views of the
993  // rows of M, including all rows that correspond to elements in 'targetMap'.
994  //
995  // If targetMap includes local elements that correspond to remotely-owned rows
996  // of M, then those remotely-owned rows will be imported into
997  // 'Mview.importMatrix', and views of them will be included in 'Mview'.
998  Mview.deleteContents();
999 
1000  RCP<const Map_t> Mrowmap = M.getRowMap();
1001 
1002  const int numProcs = Mrowmap->getComm()->getSize();
1003 
1004  ArrayView<const GlobalOrdinal> Mrows = targetMap->getNodeElementList();
1005 
1006  Mview.numRemote = 0;
1007  Mview.numRows = targetMap->getNodeNumElements();
1008  Mview.numEntriesPerRow.resize(Mview.numRows);
1009  Mview.indices.resize( Mview.numRows);
1010  Mview.values.resize( Mview.numRows);
1011  Mview.remote.resize( Mview.numRows);
1012 
1013 
1014  Mview.origRowMap = M.getRowMap();
1015  Mview.rowMap = targetMap;
1016  Mview.colMap = M.getColMap();
1017  Mview.domainMap = M.getDomainMap();
1018  Mview.importColMap = null;
1019 
1020 
1021  // mark each row in targetMap as local or remote, and go ahead and get a view for the local rows
1022 
1023  for(size_t i=0; i < Mview.numRows; ++i)
1024  {
1025  const LocalOrdinal mlid = Mrowmap->getLocalElement(Mrows[i]);
1026 
1027  if (mlid == OrdinalTraits<LocalOrdinal>::invalid()) {
1028  Mview.remote[i] = true;
1029  ++Mview.numRemote;
1030  }
1031  else {
1032  Mview.remote[i] = false;
1033  M.getLocalRowView(mlid, Mview.indices[i], Mview.values[i]);
1034  Mview.numEntriesPerRow[i] = Mview.indices[i].size();
1035  }
1036  }
1037 
1038  if (numProcs < 2) {
1039  TEUCHOS_TEST_FOR_EXCEPTION(Mview.numRemote > 0, std::runtime_error,
1040  "MatrixMatrix::import_and_extract_views ERROR, numProcs < 2 but attempting to import remote matrix rows." <<std::endl);
1041  setMaxNumEntriesPerRow(Mview);
1042  //If only one processor we don't need to import any remote rows, so return.
1043  return;
1044  }
1045 
1046  //
1047  // Now we will import the needed remote rows of M, if the global maximum
1048  // value of numRemote is greater than 0.
1049  //
1050 
1051  global_size_t globalMaxNumRemote = 0;
1052  Teuchos::reduceAll(*(Mrowmap->getComm()) , Teuchos::REDUCE_MAX, Mview.numRemote, Teuchos::outArg(globalMaxNumRemote) );
1053 
1054  if (globalMaxNumRemote > 0) {
1055  // Create a map that describes the remote rows of M that we need.
1056 
1057  Array<GlobalOrdinal> MremoteRows(Mview.numRemote);
1058 
1059 
1060  global_size_t offset = 0;
1061  for(size_t i=0; i < Mview.numRows; ++i) {
1062  if (Mview.remote[i]) {
1063  MremoteRows[offset++] = Mrows[i];
1064  }
1065  }
1066 
1067  RCP<const Map_t> MremoteRowMap = rcp(new Map_t(
1068  OrdinalTraits<global_size_t>::invalid(),
1069  MremoteRows(),
1070  Mrowmap->getIndexBase(),
1071  Mrowmap->getComm(),
1072  Mrowmap->getNode()));
1073 
1074  // Create an importer with target-map MremoteRowMap and source-map Mrowmap.
1075  Import<LocalOrdinal, GlobalOrdinal, Node> importer(Mrowmap, MremoteRowMap);
1076 
1077  // Now create a new matrix into which we can import the remote rows of M that we need.
1078  Mview.importMatrix = rcp(new CrsMatrix<Scalar,LocalOrdinal, GlobalOrdinal, Node, SpMatOps>( MremoteRowMap, 1 ));
1079  Mview.importMatrix->doImport(M, importer, INSERT);
1080  Mview.importMatrix->fillComplete(M.getDomainMap(), M.getRangeMap());
1081 
1082  // Save the column map of the imported matrix, so that we can convert indices back to global for arithmetic later
1083  Mview.importColMap = Mview.importMatrix->getColMap();
1084 
1085  // Finally, use the freshly imported data to fill in the gaps in our views of rows of M.
1086  for(size_t i=0; i < Mview.numRows; ++i)
1087  {
1088  if (Mview.remote[i]) {
1089  const LocalOrdinal importLID = MremoteRowMap->getLocalElement(Mrows[i]);
1090  Mview.importMatrix->getLocalRowView(importLID,
1091  Mview.indices[i],
1092  Mview.values[i]);
1093  Mview.numEntriesPerRow[i] = Mview.indices[i].size();
1094  }
1095  }
1096  }
1097  setMaxNumEntriesPerRow(Mview);
1098 }
1099 
1100 } //End namepsace MMdetails
1101 
1102 } //End namespace Tpetra
1103 //
1104 // Explicit instantiation macro
1105 //
1106 // Must be expanded from within the Tpetra namespace!
1107 //
1108 
1109 #define TPETRA_MATRIXMATRIX_INSTANT(SCALAR,LO,GO,NODE) \
1110  \
1111  template \
1112  void MatrixMatrix::Multiply( \
1113  const CrsMatrix< SCALAR , LO , GO , NODE >& A, \
1114  bool transposeA, \
1115  const CrsMatrix< SCALAR , LO , GO , NODE >& B, \
1116  bool transposeB, \
1117  CrsMatrix< SCALAR , LO , GO , NODE >& C, \
1118  bool call_FillComplete_on_result); \
1119 \
1120  template \
1121  void MatrixMatrix::Add( \
1122  const CrsMatrix< SCALAR , LO , GO , NODE >& A, \
1123  bool transposeA, \
1124  SCALAR scalarA, \
1125  const CrsMatrix< SCALAR , LO , GO , NODE >& B, \
1126  bool transposeB, \
1127  SCALAR scalarB, \
1128  RCP<CrsMatrix< SCALAR , LO , GO , NODE > > C); \
1129  \
1130  template \
1131  void MatrixMatrix::Add( \
1132  const CrsMatrix<SCALAR, LO, GO, NODE>& A, \
1133  bool transposeA, \
1134  SCALAR scalarA, \
1135  CrsMatrix<SCALAR, LO, GO, NODE>& B, \
1136  SCALAR scalarB ); \
1137  \
1138  template \
1139  Teuchos::RCP<CrsMatrix< SCALAR , LO , GO , NODE > > \
1140  MatrixMatrix::add (const SCALAR & alpha, \
1141  const bool transposeA, \
1142  const CrsMatrix< SCALAR , LO , GO , NODE >& A, \
1143  const SCALAR & beta, \
1144  const bool transposeB, \
1145  const CrsMatrix< SCALAR , LO , GO , NODE >& B, \
1146  const Teuchos::RCP<const Map< LO , GO , NODE > >& domainMap, \
1147  const Teuchos::RCP<const Map< LO , GO , NODE > >& rangeMap, \
1148  const Teuchos::RCP<Teuchos::ParameterList>& params); \
1149 \
1150 
1151 
1152 #endif // TPETRA_MATRIXMATRIX_DEF_HPP
size_t global_size_t
Global size_t object.
void keyValueMerge(KeyInputIterType keyBeg1, KeyInputIterType keyEnd1, ValueInputIterType valBeg1, ValueInputIterType valEnd1, KeyInputIterType keyBeg2, KeyInputIterType keyEnd2, ValueInputIterType valBeg2, ValueInputIterType valEnd2, KeyOutputIterType keyOut, ValueOutputIterType valOut, BinaryFunction f)
Merge two sorted (by keys) sequences of unique (key,value) pairs by combining pairs with equal keys...
Stand-alone utility functions and macros.