Ifpack2 Templated Preconditioning Package  Version 1.0
Ifpack2_SparseContainer_def.hpp
1 /*@HEADER
2 // ***********************************************************************
3 //
4 // Ifpack2: Tempated Object-Oriented Algebraic Preconditioner Package
5 // Copyright (2009) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
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 
43 #ifndef IFPACK2_SPARSECONTAINER_DEF_HPP
44 #define IFPACK2_SPARSECONTAINER_DEF_HPP
45 
46 #include "Ifpack2_SparseContainer_decl.hpp"
47 #ifdef HAVE_MPI
48 #include <mpi.h>
49 #include "Teuchos_DefaultMpiComm.hpp"
50 #else
51 #include "Teuchos_DefaultSerialComm.hpp"
52 #endif
53 
54 namespace Ifpack2 {
55 
56 //==============================================================================
57 template<class MatrixType, class InverseType>
58 SparseContainer<MatrixType,InverseType>::SparseContainer(const size_t NumRows, const size_t NumVectors) :
59  NumRows_(NumRows),
60  NumVectors_(NumVectors),
61  IsInitialized_(false),
62  IsComputed_(false)
63 {
64 #ifdef HAVE_MPI
65  LocalComm_ = Teuchos::rcp(new Teuchos::MpiComm<int>(Teuchos::opaqueWrapper((MPI_Comm)MPI_COMM_SELF)));
66 #else
67  LocalComm_ = Teuchos::rcp( new Teuchos::SerialComm<int>() );
68 #endif
69 }
70 
71 //==============================================================================
72 template<class MatrixType, class InverseType>
73 SparseContainer<MatrixType,InverseType>::SparseContainer(const SparseContainer<MatrixType,InverseType>& rhs)
74 {
75  // nobody should ever call this
76 }
77 
78 //==============================================================================
79 template<class MatrixType, class InverseType>
80 SparseContainer<MatrixType,InverseType>::~SparseContainer()
81 {
82  destroy();
83 }
84 
85 //==============================================================================
86 template<class MatrixType, class InverseType>
87 size_t SparseContainer<MatrixType,InverseType>::getNumRows() const
88 {
89  if (isInitialized()) return NumRows_;
90  else return 0;
91 }
92 
93 //==============================================================================
94 // Sets the number of vectors for X/Y
95 template<class MatrixType, class InverseType>
96 void SparseContainer<MatrixType,InverseType>::setNumVectors(const size_t NumVectors_in)
97 {
98  TEUCHOS_TEST_FOR_EXCEPTION(NumVectors_in<=0, std::runtime_error, "Ifpack2::SparseContainer::setNumVectors NumVectors cannot be negative.");
99 
100  // Do nothing if the vectors are the right size. Always do something if we're not initialized.
101  if(!IsInitialized_ || NumVectors_!=NumVectors_in) {
102  NumVectors_=NumVectors_in;
103  X_ = Teuchos::rcp( new Tpetra::MultiVector<InverseScalar,InverseLocalOrdinal,InverseGlobalOrdinal,InverseNode>(Map_,NumVectors_) );
104  Y_ = Teuchos::rcp( new Tpetra::MultiVector<InverseScalar,InverseLocalOrdinal,InverseGlobalOrdinal,InverseNode>(Map_,NumVectors_) );
105  }
106 
107 }
108 
109 //==============================================================================
110 // Returns the ID associated to local row i.
111 template<class MatrixType, class InverseType>
112 typename MatrixType::local_ordinal_type & SparseContainer<MatrixType,InverseType>::ID(const size_t i)
113 {
114  return GID_[i];
115 }
116 
117 //==============================================================================
118 // Returns true is the container has been successfully initialized.
119 template<class MatrixType, class InverseType>
120 bool SparseContainer<MatrixType,InverseType>::isInitialized() const
121 {
122  return IsInitialized_;
123 }
124 
125 //==============================================================================
126 // Returns true is the container has been successfully computed.
127 template<class MatrixType, class InverseType>
128 bool SparseContainer<MatrixType,InverseType>::isComputed() const
129 {
130  return IsComputed_;
131 }
132 
133 //==============================================================================
134 // Sets all necessary parameters.
135 template<class MatrixType, class InverseType>
136 void SparseContainer<MatrixType,InverseType>::setParameters(const Teuchos::ParameterList& List)
137 {
138  List_ = List;
139 }
140 
141 //==============================================================================
142 template<class MatrixType, class InverseType>
143 void SparseContainer<MatrixType,InverseType>::initialize()
144 {
145  if(IsInitialized_) destroy();
146  IsInitialized_=false;
147 
148  // Allocations
149  Map_ = Teuchos::rcp( new Tpetra::Map<InverseLocalOrdinal,InverseGlobalOrdinal,InverseNode>(NumRows_,0,LocalComm_) );
150  Matrix_ = Teuchos::rcp( new Tpetra::CrsMatrix<InverseScalar,InverseLocalOrdinal,InverseGlobalOrdinal,InverseNode>(Map_,0) );
151  GID_.resize(NumRows_);
152  setNumVectors(NumVectors_);
153 
154  // create the inverse
155  Inverse_ = Teuchos::rcp( new InverseType(Matrix_) );
156  TEUCHOS_TEST_FOR_EXCEPTION( Inverse_ == Teuchos::null, std::runtime_error, "Ifpack2::SparseContainer::initialize error in inverse constructor.");
157  Inverse_->setParameters(List_);
158 
159  // Note from IFPACK: Call Inverse_->Initialize() in Compute(). This saves
160  // some time, because the diagonal blocks can be extracted faster,
161  // and only once.
162  IsInitialized_ = true;
163 }
164 
165 //==============================================================================
166 // Finalizes the linear system matrix and prepares for the application of the inverse.
167 template<class MatrixType, class InverseType>
168 void SparseContainer<MatrixType,InverseType>::compute(const Teuchos::RCP<const Tpetra::RowMatrix<MatrixScalar,MatrixLocalOrdinal,MatrixGlobalOrdinal,MatrixNode> >& Matrix)
169 {
170  IsComputed_=false;
171  TEUCHOS_TEST_FOR_EXCEPTION( !IsInitialized_, std::runtime_error, "Ifpack2::SparseContainer::compute please call initialize first.");
172 
173  // extract the submatrices
174  extract(Matrix);
175 
176  // initialize & compute the inverse operator
177  Inverse_->initialize();
178  Inverse_->compute();
179  IsComputed_=true;
180 }
181 
182 //==============================================================================
183 // Computes Y = alpha * M^{-1} X + beta*Y
184 template<class MatrixType, class InverseType>
185 void SparseContainer<MatrixType,InverseType>::apply(const Tpetra::MultiVector<MatrixScalar,MatrixLocalOrdinal,MatrixGlobalOrdinal,MatrixNode>& X,
186  Tpetra::MultiVector<MatrixScalar,MatrixLocalOrdinal,MatrixGlobalOrdinal,MatrixNode>& Y,
187  Teuchos::ETransp mode,
188  MatrixScalar alpha,
189  MatrixScalar beta)
190 {
191  TEUCHOS_TEST_FOR_EXCEPTION( !IsComputed_, std::runtime_error, "Ifpack2::SparseContainer::apply compute has not been called.");
192  TEUCHOS_TEST_FOR_EXCEPTION( X.getNumVectors() != Y.getNumVectors(), std::runtime_error, "Ifpack2::SparseContainer::apply X/Y have different numbers of vectors.");
193 
194  // This is a noop if our internal vectors are already the right size.
195  setNumVectors(X.getNumVectors());
196 
197  // Pull the Data Pointers
198  Teuchos::ArrayRCP<Teuchos::ArrayRCP<const MatrixScalar> > global_x_ptr = X.get2dView();
199  Teuchos::ArrayRCP<Teuchos::ArrayRCP<InverseScalar> > local_x_ptr = X_->get2dViewNonConst();
200  Teuchos::ArrayRCP<Teuchos::ArrayRCP<const InverseScalar> > local_y_ptr = Y_->get2dView();
201  Teuchos::ArrayRCP<Teuchos::ArrayRCP<MatrixScalar> > global_y_ptr = Y.get2dViewNonConst();
202 
203  // Copy in
204  for(size_t j=0; j < NumRows_; j++){
205  MatrixLocalOrdinal LID = ID(j);
206  for (size_t k = 0 ; k < NumVectors_ ; k++)
207  local_x_ptr[k][j] = global_x_ptr[k][LID];
208  }
209 
210  // Apply inverse
211  Inverse_->apply(*X_, *Y_);
212 
213  // copy out into solution vector Y
214  for (size_t j = 0 ; j < NumRows_ ; j++) {
215  MatrixLocalOrdinal LID = ID(j);
216  for (size_t k = 0 ; k < NumVectors_ ; k++)
217  global_y_ptr[k][LID] = alpha * local_y_ptr[k][j] + beta * global_y_ptr[k][LID];
218  }
219 
220 }
221 
222 
223 //==============================================================================
224 // Computes Y = alpha * diag(D) * M^{-1} (diag(D) X) + beta*Y
225 template<class MatrixType, class InverseType>
226 void SparseContainer<MatrixType,InverseType>::weightedApply(const Tpetra::MultiVector<MatrixScalar,MatrixLocalOrdinal,MatrixGlobalOrdinal,MatrixNode>& X,
227  Tpetra::MultiVector<MatrixScalar,MatrixLocalOrdinal,MatrixGlobalOrdinal,MatrixNode>& Y,
228  const Tpetra::Vector<MatrixScalar,MatrixLocalOrdinal,MatrixGlobalOrdinal,MatrixNode>& D,
229  Teuchos::ETransp mode,
230  MatrixScalar alpha,
231  MatrixScalar beta)
232 {
233  TEUCHOS_TEST_FOR_EXCEPTION( !IsComputed_, std::runtime_error, "Ifpack2::SparseContainer::apply compute has not been called.");
234  TEUCHOS_TEST_FOR_EXCEPTION( X.getNumVectors() != Y.getNumVectors(), std::runtime_error, "Ifpack2::SparseContainer::apply X/Y have different numbers of vectors.");
235 
236  // This is a noop if our internal vectors are already the right size.
237  setNumVectors(X.getNumVectors());
238 
239  // Pull the data pointers
240  Teuchos::ArrayRCP<const MatrixScalar > global_d_ptr = D.getData(0);
241  Teuchos::ArrayRCP<Teuchos::ArrayRCP<const MatrixScalar> > global_x_ptr = X.get2dView();
242  Teuchos::ArrayRCP<Teuchos::ArrayRCP<InverseScalar> > local_x_ptr = X_->get2dViewNonConst();
243  Teuchos::ArrayRCP<Teuchos::ArrayRCP<const InverseScalar> > local_y_ptr = Y_->get2dView();
244  Teuchos::ArrayRCP<Teuchos::ArrayRCP<MatrixScalar> > global_y_ptr = Y.get2dViewNonConst();
245 
246  // Copy in
247  for(size_t j=0; j < NumRows_; j++){
248  MatrixLocalOrdinal LID = ID(j);
249  for (size_t k = 0 ; k < NumVectors_ ; k++)
250  local_x_ptr[k][j] = global_d_ptr[LID] * global_x_ptr[k][LID];
251  }
252 
253  // Apply inverse
254  Inverse_->apply(*X_, *Y_);
255 
256  // copy out into solution vector Y
257  for (size_t j = 0 ; j < NumRows_ ; j++) {
258  MatrixLocalOrdinal LID = ID(j);
259  for (size_t k = 0 ; k < NumVectors_ ; k++)
260  global_y_ptr[k][LID] = alpha * global_d_ptr[LID] * local_y_ptr[k][j] + beta * global_y_ptr[k][LID];
261  }
262 }
263 
264 //==============================================================================
265 // Destroys all data.
266 template<class MatrixType, class InverseType>
267 void SparseContainer<MatrixType,InverseType>::destroy()
268 {
269  IsInitialized_ = false;
270  IsComputed_ = false;
271 }
272 
273 //==============================================================================
274 // Prints basic information on iostream. This function is used by operator<<
275 template<class MatrixType, class InverseType>
276 std::ostream& SparseContainer<MatrixType,InverseType>::print(std::ostream& os) const
277 {
278  Teuchos::FancyOStream fos(Teuchos::rcp(&os,false));
279  fos.setOutputToRootOnly(0);
280  describe(fos);
281  return(os);
282 }
283 
284 
285 //==============================================================================
286 template<class MatrixType, class InverseType>
287 std::string SparseContainer<MatrixType,InverseType>::description() const
288 {
289  std::ostringstream oss;
290  oss << Teuchos::Describable::description();
291  if (isInitialized()) {
292  if (isComputed()) {
293  oss << "{status = initialized, computed";
294  }
295  else {
296  oss << "{status = initialized, not computed";
297  }
298  }
299  else {
300  oss << "{status = not initialized, not computed";
301  }
302 
303  oss << "}";
304  return oss.str();
305 }
306 
307 //==============================================================================
308 template<class MatrixType, class InverseType>
309 void SparseContainer<MatrixType,InverseType>::describe(Teuchos::FancyOStream &os, const Teuchos::EVerbosityLevel verbLevel) const
310 {
311  using std::endl;
312  if(verbLevel==Teuchos::VERB_NONE) return;
313  os << "================================================================================" << endl;
314  os << "Ifpack2_SparseContainer" << endl;
315  os << "Number of rows = " << NumRows_ << endl;
316  os << "Number of vectors = " << NumVectors_ << endl;
317  os << "isInitialized() = " << IsInitialized_ << endl;
318  os << "isComputed() = " << IsComputed_ << endl;
319  os << "================================================================================" << endl;
320  os << endl;
321 }
322 
323 //==============================================================================
324 // Extract the submatrices identified by the ID set int ID().
325 template<class MatrixType, class InverseType>
326 void SparseContainer<MatrixType,InverseType>::extract(const Teuchos::RCP<const Tpetra::RowMatrix<MatrixScalar,MatrixLocalOrdinal,MatrixGlobalOrdinal,MatrixNode> >& Matrix_in)
327 {
328  size_t MatrixInNumRows= Matrix_in->getNodeNumRows();
329 
330  // Sanity checking
331  for (size_t j = 0 ; j < NumRows_ ; ++j) {
332  TEUCHOS_TEST_FOR_EXCEPTION( GID_[j] < 0 || (size_t) GID_[j] >= MatrixInNumRows, std::runtime_error, "Ifpack2::SparseContainer::applyInverse compute has not been called.");
333  }
334 
335  int Length = Matrix_in->getNodeMaxNumRowEntries();
336  Teuchos::Array<MatrixScalar> Values;
337  Teuchos::Array<MatrixLocalOrdinal> Indices;
338  Teuchos::Array<InverseScalar> Values_insert;
339  Teuchos::Array<InverseGlobalOrdinal> Indices_insert;
340 
341  Values.resize(Length);
342  Indices.resize(Length);
343  Values_insert.resize(Length);
344  Indices_insert.resize(Length);
345 
346  for (size_t j = 0 ; j < NumRows_ ; ++j) {
347  MatrixLocalOrdinal LRID = ID(j);
348  size_t NumEntries;
349 
350  Matrix_in->getLocalRowCopy(LRID,Indices(),Values(),NumEntries);
351 
352  size_t num_entries_found=0;
353  for (size_t k = 0 ; k < NumEntries ; ++k) {
354  MatrixLocalOrdinal LCID = Indices[k];
355 
356  // skip off-processor elements
357  if ((size_t)LCID >= MatrixInNumRows)
358  continue;
359 
360  // for local column IDs, look for each ID in the list
361  // of columns hosted by this object
362  // FIXME: use STL
363  InverseLocalOrdinal jj = -1;
364  for (size_t kk = 0 ; kk < NumRows_ ; ++kk)
365  if (ID(kk) == LCID)
366  jj = kk;
367 
368  if (jj != -1) {
369  Indices_insert[num_entries_found] = Map_->getGlobalElement(jj);
370  Values_insert[num_entries_found] = Values[k];
371  num_entries_found++;
372  }
373 
374  }
375  Matrix_->insertGlobalValues(j,Indices_insert(0,num_entries_found),Values_insert(0,num_entries_found));
376  }
377 
378  Matrix_->fillComplete();
379 }
380 
381 
382 } // namespace Ifpack2
383 #endif // IFPACK2_SPARSECONTAINER_HPP
Ifpack2::Container: a pure virtual class for creating and solving local linear problems.
Definition: Ifpack2_AdditiveSchwarz_decl.hpp:67