Tpetra parallel linear algebra  Version of the Day
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
Tpetra_RowMatrixTransposer_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_ROWMATRIXTRANSPOSER_DEF_HPP
43 #define TPETRA_ROWMATRIXTRANSPOSER_DEF_HPP
44 
45 #include "Tpetra_CrsMatrix.hpp"
46 #include "Tpetra_Export.hpp"
47 #include "Tpetra_Import.hpp"
48 #include "Teuchos_ParameterList.hpp"
49 #include "Teuchos_TimeMonitor.hpp"
50 
51 namespace Tpetra {
52 
53 template<class Scalar,
54  class LocalOrdinal,
55  class GlobalOrdinal,
56  class Node>
58 RowMatrixTransposer (const Teuchos::RCP<const crs_matrix_type>& origMatrix,const std::string & label)
59  : origMatrix_(origMatrix), label_(label) {}
60 
61 template<class Scalar,
62  class LocalOrdinal,
63  class GlobalOrdinal,
64  class Node>
65 Teuchos::RCP<CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >
67 createTranspose (const Teuchos::RCP<Teuchos::ParameterList> &params)
68 {
69  using Teuchos::RCP;
70  // Do the local transpose
71  RCP<crs_matrix_type> transMatrixWithSharedRows = createTransposeLocal (params);
72 
73 #ifdef HAVE_TPETRA_MMM_TIMINGS
74  std::string prefix = std::string("Tpetra ")+ label_ + std::string(": ");
75  using Teuchos::TimeMonitor;
76  Teuchos::RCP<Teuchos::TimeMonitor> MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("Transpose TAFC"))));
77 #endif
78 
79  // If transMatrixWithSharedRows has an exporter, that's what we
80  // want. If it doesn't, the rows aren't actually shared, and we're
81  // done!
82  RCP<const Export<LocalOrdinal,GlobalOrdinal,Node> > exporter =
83  transMatrixWithSharedRows->getGraph ()->getExporter ();
84  if (exporter.is_null ()) {
85  return transMatrixWithSharedRows;
86  }
87  else {
88  Teuchos::ParameterList labelList;
89 #ifdef HAVE_TPETRA_MMM_TIMINGS
90  labelList.set("Timer Label",label_);
91 #endif
92  if(!params.is_null()) labelList.set("compute global constants",params->get("compute global constants",true));
93  // Use the Export object to do a fused Export and fillComplete.
94  return exportAndFillCompleteCrsMatrix<crs_matrix_type> (transMatrixWithSharedRows, *exporter,Teuchos::null,Teuchos::null,Teuchos::rcp(&labelList,false));
95  }
96 }
97 
98 
99 // mfh 03 Feb 2013: In a definition outside the class like this, the
100 // return value is considered outside the class scope (for things like
101 // resolving typedefs), but the arguments are considered inside the
102 // class scope.
103 template<class Scalar,
104  class LocalOrdinal,
105  class GlobalOrdinal,
106  class Node>
107 Teuchos::RCP<CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node> >
109 createTransposeLocal (const Teuchos::RCP<Teuchos::ParameterList> &params)
110 {
111  using Teuchos::Array;
112  using Teuchos::ArrayRCP;
113  using Teuchos::ArrayView;
114  using Teuchos::RCP;
115  using Teuchos::rcp;
116  using Teuchos::rcp_dynamic_cast;
117  typedef LocalOrdinal LO;
118  typedef GlobalOrdinal GO;
119  typedef Tpetra::Import<LO, GO, Node> import_type;
120  typedef Tpetra::Export<LO, GO, Node> export_type;
121 
122 #ifdef HAVE_TPETRA_MMM_TIMINGS
123  std::string prefix = std::string("Tpetra ")+ label_ + std::string(": ");
124  using Teuchos::TimeMonitor;
125  Teuchos::RCP<Teuchos::TimeMonitor> MM = Teuchos::rcp(new TimeMonitor(*TimeMonitor::getNewTimer(prefix + std::string("Transpose Local"))));
126 #endif
127 
128  // Prebuild the importers and exporters the no-communication way,
129  // flipping the importers and exporters around.
130  RCP<const import_type> myImport;
131  RCP<const export_type> myExport;
132  if (! origMatrix_->getGraph ()->getImporter ().is_null ()) {
133  myExport = rcp (new export_type (*origMatrix_->getGraph ()->getImporter ()));
134  }
135  if (! origMatrix_->getGraph ()->getExporter ().is_null ()) {
136  myImport = rcp (new import_type (*origMatrix_->getGraph ()->getExporter ()));
137  }
138 
139  //
140  // This transpose is based upon the approach in EpetraExt.
141  //
142 
143  size_t numLocalCols = origMatrix_->getNodeNumCols();
144  size_t numLocalRows = origMatrix_->getNodeNumRows();
145  size_t numLocalNnz = origMatrix_->getNodeNumEntries();
146 
147  RCP<const crs_matrix_type> crsMatrix =
148  rcp_dynamic_cast<const crs_matrix_type> (origMatrix_);
149 
150  RCP<crs_matrix_type> transMatrixWithSharedRows;
151  if (crsMatrix != Teuchos::null) {
152  // The matrix is a CrsMatrix
153  using local_matrix_type = typename crs_matrix_type::local_matrix_type;
154  using row_map_type = typename local_matrix_type::row_map_type::non_const_type;
155  using index_type = typename local_matrix_type::index_type::non_const_type;
156  using values_type = typename local_matrix_type::values_type::non_const_type;
157  using execution_space = typename local_matrix_type::execution_space;
158 
159  // Determine how many nonzeros there are per row in the transpose.
160  auto lclMatrix = crsMatrix->getLocalMatrix();
161  auto lclGraph = lclMatrix.graph;
162 
163  using range_type = Kokkos::RangePolicy<LO,execution_space>;
164 
165  // Determine how many nonzeros there are per row in the transpose.
166  row_map_type t_rows("transpose_rows", numLocalCols+1);
167  Kokkos::parallel_for("compute_number_of_indices_per_column", range_type(0, numLocalRows),
168  KOKKOS_LAMBDA(const LO row) {
169  auto rowView = lclGraph.rowConst(row);
170  auto length = rowView.length;
171 
172  for (decltype(length) colID = 0; colID < length; colID++) {
173  auto col = rowView(colID);
174  Kokkos::atomic_fetch_add(&t_rows[col], 1);
175  }
176  });
177 
178  // Compute offsets
179  Kokkos::parallel_scan("compute_transpose_row_offsets", range_type(0, numLocalCols+1),
180  KOKKOS_LAMBDA(const LO i, LO& update, const bool& final_pass) {
181  const LO val = t_rows(i);
182  if (final_pass)
183  t_rows(i) = update;
184  update += val;
185  });
186 
187  row_map_type offsets("transpose_row_offsets_aux", numLocalCols+1);
188  Kokkos::deep_copy(offsets, t_rows);
189 
190  index_type t_cols("transpose_cols", numLocalNnz);
191  values_type t_vals("transpose_vals", numLocalNnz);
192  Kokkos::parallel_for("compute_transposed_rows", range_type(0, numLocalRows),
193  KOKKOS_LAMBDA(const LO row) {
194  auto rowView = lclMatrix.rowConst(row);
195  auto length = rowView.length;
196 
197  for (decltype(length) colID = 0; colID < length; colID++) {
198  auto col = rowView.colidx(colID);
199 
200  LO insert_pos = Kokkos::atomic_fetch_add(&offsets[col], 1);
201 
202  t_cols[insert_pos] = row;
203  t_vals[insert_pos] = rowView.value(colID);
204  }
205  });
206 
207  local_matrix_type lclTransposeMatrix("transpose", numLocalCols, numLocalRows, numLocalNnz, t_vals, t_rows, t_cols);
208 
209  transMatrixWithSharedRows =
210  rcp (new crs_matrix_type (lclTransposeMatrix,
211  origMatrix_->getColMap (), origMatrix_->getRowMap (),
212  origMatrix_->getRangeMap (), origMatrix_->getDomainMap ()));
213  } else {
214  // FIXME: are we ever here? There is no RowMatrix constructor, we seem to
215  // be working only with CrsMatrices
216 
217  // Determine how many nonzeros there are per row in the transpose.
218  Array<size_t> CurrentStart(numLocalCols,0);
219  ArrayView<const LO> localIndices;
220  ArrayView<const Scalar> localValues;
221  // RowMatrix path
222  for (size_t i=0; i<numLocalRows; ++i) {
223  const size_t numEntriesInRow = origMatrix_->getNumEntriesInLocalRow(i);
224  origMatrix_->getLocalRowView(i, localIndices, localValues);
225  for (size_t j=0; j<numEntriesInRow; ++j) {
226  ++CurrentStart[ localIndices[j] ];
227  }
228  }
229 
230  // create temporary row-major storage for the transposed matrix
231 
232  ArrayRCP<size_t> rowptr_rcp(numLocalCols+1);
233  ArrayRCP<LO> colind_rcp(numLocalNnz);
234  ArrayRCP<Scalar> values_rcp(numLocalNnz);
235 
236  // Since ArrayRCP's are slow...
237  ArrayView<size_t> TransRowptr = rowptr_rcp();
238  ArrayView<LO> TransColind = colind_rcp();
239  ArrayView<Scalar> TransValues = values_rcp();
240 
241  // Scansum the TransRowptr; reset CurrentStart
242  TransRowptr[0]=0;
243  for (size_t i=1; i<numLocalCols+1; ++i) TransRowptr[i] = CurrentStart[i-1] + TransRowptr[i-1];
244  for (size_t i=0; i<numLocalCols; ++i) CurrentStart[i] = TransRowptr[i];
245 
246  // populate the row-major storage so that the data for the transposed
247  // matrix is easy to access
248  for (size_t i=0; i<numLocalRows; ++i) {
249  const size_t numEntriesInRow = origMatrix_->getNumEntriesInLocalRow (i);
250  origMatrix_->getLocalRowView(i, localIndices, localValues);
251 
252  for (size_t j=0; j<numEntriesInRow; ++j) {
253  size_t idx = CurrentStart[localIndices[j]];
254  TransColind[idx] = Teuchos::as<LO>(i);
255  TransValues[idx] = localValues[j];
256  ++CurrentStart[localIndices[j]];
257  }
258  } //for (size_t i=0; i<numLocalRows; ++i)
259 
260  // Allocate and populate temporary matrix with rows not uniquely owned
261  transMatrixWithSharedRows =
262  rcp (new crs_matrix_type (origMatrix_->getColMap (),
263  origMatrix_->getRowMap (), 0));
264  transMatrixWithSharedRows->setAllValues (rowptr_rcp, colind_rcp, values_rcp);
265 
266  // Call ESFC & return
267  Teuchos::ParameterList eParams;
268 #ifdef HAVE_TPETRA_MMM_TIMINGS
269  eParams.set("Timer Label",label_);
270 #endif
271  if (!params.is_null())
272  eParams.set("compute global constants", params->get("compute global constants", true));
273 
274  transMatrixWithSharedRows->expertStaticFillComplete (origMatrix_->getRangeMap (),
275  origMatrix_->getDomainMap (),
276  myImport, myExport,rcp(&eParams,false));
277 
278  }
279 
280  return transMatrixWithSharedRows;
281 }
282 //
283 // Explicit instantiation macro
284 //
285 // Must be expanded from within the Tpetra namespace!
286 //
287 
288 #define TPETRA_ROWMATRIXTRANSPOSER_INSTANT(SCALAR,LO,GO,NODE) \
289  template class RowMatrixTransposer< SCALAR, LO , GO , NODE >;
290 
291 } // namespace Tpetra
292 
293 #endif
RowMatrixTransposer(const Teuchos::RCP< const crs_matrix_type > &origMatrix, const std::string &label=std::string())
Constructor that takes the matrix to transpose.
Communication plan for data redistribution from a uniquely-owned to a (possibly) multiply-owned distr...
Sparse matrix that presents a row-oriented interface that lets users read or modify entries...
void deep_copy(MultiVector< DS, DL, DG, DN > &dst, const MultiVector< SS, SL, SG, SN > &src)
Copy the contents of the MultiVector src into dst.
Communication plan for data redistribution from a (possibly) multiply-owned to a uniquely-owned distr...
local_matrix_type getLocalMatrix() const
The local sparse matrix.
Teuchos::RCP< crs_matrix_type > createTransposeLocal(const Teuchos::RCP< Teuchos::ParameterList > &params=Teuchos::null)
Compute and return the transpose of the matrix given to the constructor.
Teuchos::RCP< crs_matrix_type > createTranspose(const Teuchos::RCP< Teuchos::ParameterList > &params=Teuchos::null)
Compute and return the transpose of the matrix given to the constructor.
KokkosSparse::CrsMatrix< impl_scalar_type, local_ordinal_type, execution_space, void, typename local_graph_type::size_type > local_matrix_type
The specialization of Kokkos::CrsMatrix that represents the part of the sparse matrix on each MPI pro...