Ifpack2 Templated Preconditioning Package  Version 1.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
Ifpack2_RILUK_def.hpp
1 // @HEADER
2 // *****************************************************************************
3 // Ifpack2: Templated Object-Oriented Algebraic Preconditioner Package
4 //
5 // Copyright 2009 NTESS and the Ifpack2 contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9 
10 #ifndef IFPACK2_CRSRILUK_DEF_HPP
11 #define IFPACK2_CRSRILUK_DEF_HPP
12 
13 #include "Ifpack2_RILUK_decl.hpp"
14 #include "Ifpack2_LocalFilter.hpp"
15 #include "Tpetra_CrsMatrix.hpp"
16 #include "Teuchos_StandardParameterEntryValidators.hpp"
17 #include "Ifpack2_LocalSparseTriangularSolver.hpp"
18 #include "Ifpack2_Details_getParamTryingTypes.hpp"
19 #include "Ifpack2_Details_getCrsMatrix.hpp"
20 #include "Kokkos_Sort.hpp"
21 #include "KokkosSparse_Utils.hpp"
22 #include "KokkosKernels_Sorting.hpp"
23 #include "KokkosSparse_IOUtils.hpp"
24 
25 namespace Ifpack2 {
26 
27 namespace Details {
28 struct IlukImplType {
29  enum Enum {
30  Serial,
31  KSPILUK
32  };
33 
34  static void loadPLTypeOption(Teuchos::Array<std::string>& type_strs, Teuchos::Array<Enum>& type_enums) {
35  type_strs.resize(2);
36  type_strs[0] = "Serial";
37  type_strs[1] = "KSPILUK";
38  type_enums.resize(2);
39  type_enums[0] = Serial;
40  type_enums[1] = KSPILUK;
41  }
42 };
43 } // namespace Details
44 
45 template <class MatrixType>
47  : A_(Matrix_in)
48  , LevelOfFill_(0)
49  , Overalloc_(2.)
50  , isAllocated_(false)
51  , isInitialized_(false)
52  , isComputed_(false)
53  , numInitialize_(0)
54  , numCompute_(0)
55  , numApply_(0)
56  , initializeTime_(0.0)
57  , computeTime_(0.0)
58  , applyTime_(0.0)
59  , RelaxValue_(Teuchos::ScalarTraits<magnitude_type>::zero())
60  , Athresh_(Teuchos::ScalarTraits<magnitude_type>::zero())
61  , Rthresh_(Teuchos::ScalarTraits<magnitude_type>::one())
62  , isKokkosKernelsSpiluk_(false)
63  , isKokkosKernelsStream_(false)
64  , num_streams_(0)
65  , hasStreamReordered_(false) {
66  allocateSolvers();
67 }
68 
69 template <class MatrixType>
71  : A_(Matrix_in)
72  , LevelOfFill_(0)
73  , Overalloc_(2.)
74  , isAllocated_(false)
75  , isInitialized_(false)
76  , isComputed_(false)
77  , numInitialize_(0)
78  , numCompute_(0)
79  , numApply_(0)
80  , initializeTime_(0.0)
81  , computeTime_(0.0)
82  , applyTime_(0.0)
83  , RelaxValue_(Teuchos::ScalarTraits<magnitude_type>::zero())
84  , Athresh_(Teuchos::ScalarTraits<magnitude_type>::zero())
85  , Rthresh_(Teuchos::ScalarTraits<magnitude_type>::one())
86  , isKokkosKernelsSpiluk_(false)
87  , isKokkosKernelsStream_(false)
88  , num_streams_(0)
89  , hasStreamReordered_(false) {
90  allocateSolvers();
91 }
92 
93 template <class MatrixType>
95  if (!isKokkosKernelsStream_) {
96  if (Teuchos::nonnull(KernelHandle_)) {
97  KernelHandle_->destroy_spiluk_handle();
98  }
99  } else {
100  for (int i = 0; i < num_streams_; i++) {
101  if (Teuchos::nonnull(KernelHandle_v_[i])) {
102  KernelHandle_v_[i]->destroy_spiluk_handle();
103  }
104  }
105  }
106 }
107 
108 template <class MatrixType>
111  L_solver_->setObjectLabel("lower");
113  U_solver_->setObjectLabel("upper");
114 }
115 
116 template <class MatrixType>
118  // It's legal for A to be null; in that case, you may not call
119  // initialize() until calling setMatrix() with a nonnull input.
120  // Regardless, setting the matrix invalidates any previous
121  // factorization.
122  if (A.getRawPtr() != A_.getRawPtr()) {
123  isAllocated_ = false;
124  isInitialized_ = false;
125  isComputed_ = false;
126  A_local_ = Teuchos::null;
127  Graph_ = Teuchos::null;
128 
129  // The sparse triangular solvers get a triangular factor as their
130  // input matrix. The triangular factors L_ and U_ are getting
131  // reset, so we reset the solvers' matrices to null. Do that
132  // before setting L_ and U_ to null, so that latter step actually
133  // frees the factors.
134  if (!L_solver_.is_null()) {
135  L_solver_->setMatrix(Teuchos::null);
136  }
137  if (!U_solver_.is_null()) {
138  U_solver_->setMatrix(Teuchos::null);
139  }
140 
141  L_ = Teuchos::null;
142  U_ = Teuchos::null;
143  D_ = Teuchos::null;
144  A_ = A;
145  }
146 }
147 
148 template <class MatrixType>
152  L_.is_null(), std::runtime_error,
153  "Ifpack2::RILUK::getL: The L factor "
154  "is null. Please call initialize() (and preferably also compute()) "
155  "before calling this method. If the input matrix has not yet been set, "
156  "you must first call setMatrix() with a nonnull input matrix before you "
157  "may call initialize() or compute().");
158  return *L_;
159 }
160 
161 template <class MatrixType>
162 const Tpetra::Vector<typename RILUK<MatrixType>::scalar_type,
168  D_.is_null(), std::runtime_error,
169  "Ifpack2::RILUK::getD: The D factor "
170  "(of diagonal entries) is null. Please call initialize() (and "
171  "preferably also compute()) before calling this method. If the input "
172  "matrix has not yet been set, you must first call setMatrix() with a "
173  "nonnull input matrix before you may call initialize() or compute().");
174  return *D_;
175 }
176 
177 template <class MatrixType>
181  U_.is_null(), std::runtime_error,
182  "Ifpack2::RILUK::getU: The U factor "
183  "is null. Please call initialize() (and preferably also compute()) "
184  "before calling this method. If the input matrix has not yet been set, "
185  "you must first call setMatrix() with a nonnull input matrix before you "
186  "may call initialize() or compute().");
187  return *U_;
188 }
189 
190 template <class MatrixType>
193  A_.is_null(), std::runtime_error,
194  "Ifpack2::RILUK::getNodeSmootherComplexity: "
195  "The input matrix A is null. Please call setMatrix() with a nonnull "
196  "input matrix, then call compute(), before calling this method.");
197  // RILUK methods cost roughly one apply + the nnz in the upper+lower triangles
198  if (!L_.is_null() && !U_.is_null())
199  return A_->getLocalNumEntries() + L_->getLocalNumEntries() + U_->getLocalNumEntries();
200  else
201  return 0;
202 }
203 
204 template <class MatrixType>
207  typename RILUK<MatrixType>::node_type> >
210  A_.is_null(), std::runtime_error,
211  "Ifpack2::RILUK::getDomainMap: "
212  "The matrix is null. Please call setMatrix() with a nonnull input "
213  "before calling this method.");
214 
215  // FIXME (mfh 25 Jan 2014) Shouldn't this just come from A_?
217  Graph_.is_null(), std::runtime_error,
218  "Ifpack2::RILUK::getDomainMap: "
219  "The computed graph is null. Please call initialize() before calling "
220  "this method.");
221  return Graph_->getL_Graph()->getDomainMap();
222 }
223 
224 template <class MatrixType>
227  typename RILUK<MatrixType>::node_type> >
230  A_.is_null(), std::runtime_error,
231  "Ifpack2::RILUK::getRangeMap: "
232  "The matrix is null. Please call setMatrix() with a nonnull input "
233  "before calling this method.");
234 
235  // FIXME (mfh 25 Jan 2014) Shouldn't this just come from A_?
237  Graph_.is_null(), std::runtime_error,
238  "Ifpack2::RILUK::getRangeMap: "
239  "The computed graph is null. Please call initialize() before calling "
240  "this method.");
241  return Graph_->getL_Graph()->getRangeMap();
242 }
243 
244 template <class MatrixType>
246  using Teuchos::null;
247  using Teuchos::rcp;
248 
249  if (!isAllocated_) {
250  if (!isKokkosKernelsStream_) {
251  // Deallocate any existing storage. This avoids storing 2x
252  // memory, since RCP op= does not deallocate until after the
253  // assignment.
254  L_ = null;
255  U_ = null;
256  D_ = null;
257 
258  // Allocate Matrix using ILUK graphs
259  L_ = rcp(new crs_matrix_type(Graph_->getL_Graph()));
260  U_ = rcp(new crs_matrix_type(Graph_->getU_Graph()));
261  L_->setAllToScalar(STS::zero()); // Zero out L and U matrices
262  U_->setAllToScalar(STS::zero());
263 
264  // FIXME (mfh 24 Jan 2014) This assumes domain == range Map for L and U.
265  L_->fillComplete();
266  U_->fillComplete();
267  D_ = rcp(new vec_type(Graph_->getL_Graph()->getRowMap()));
268  } else {
269  L_v_ = std::vector<Teuchos::RCP<crs_matrix_type> >(num_streams_);
270  U_v_ = std::vector<Teuchos::RCP<crs_matrix_type> >(num_streams_);
271  for (int i = 0; i < num_streams_; i++) {
272  L_v_[i] = null;
273  U_v_[i] = null;
274 
275  L_v_[i] = rcp(new crs_matrix_type(Graph_v_[i]->getL_Graph()));
276  U_v_[i] = rcp(new crs_matrix_type(Graph_v_[i]->getU_Graph()));
277  L_v_[i]->setAllToScalar(STS::zero()); // Zero out L and U matrices
278  U_v_[i]->setAllToScalar(STS::zero());
279 
280  L_v_[i]->fillComplete();
281  U_v_[i]->fillComplete();
282  }
283  }
284  }
285  isAllocated_ = true;
286 }
287 
288 template <class MatrixType>
291  using Details::getParamTryingTypes;
292  using Teuchos::Array;
294  using Teuchos::RCP;
295  const char prefix[] = "Ifpack2::RILUK: ";
296 
297  // Default values of the various parameters.
298  int fillLevel = 0;
299  magnitude_type absThresh = STM::zero();
300  magnitude_type relThresh = STM::one();
301  magnitude_type relaxValue = STM::zero();
302  double overalloc = 2.;
303  int nstreams = 0;
304 
305  // "fact: iluk level-of-fill" parsing is more complicated, because
306  // we want to allow as many types as make sense. int is the native
307  // type, but we also want to accept double (for backwards
308  // compatibilty with ILUT). You can't cast arbitrary magnitude_type
309  // (e.g., Sacado::MP::Vector) to int, so we use float instead, to
310  // get coverage of the most common magnitude_type cases. Weirdly,
311  // there's an Ifpack2 test that sets the fill level as a
312  // global_ordinal_type.
313  {
314  const std::string paramName("fact: iluk level-of-fill");
315  getParamTryingTypes<int, int, global_ordinal_type, double, float>(fillLevel, params, paramName, prefix);
316  }
317  // For the other parameters, we prefer magnitude_type, but allow
318  // double for backwards compatibility.
319  {
320  const std::string paramName("fact: absolute threshold");
321  getParamTryingTypes<magnitude_type, magnitude_type, double>(absThresh, params, paramName, prefix);
322  }
323  {
324  const std::string paramName("fact: relative threshold");
325  getParamTryingTypes<magnitude_type, magnitude_type, double>(relThresh, params, paramName, prefix);
326  }
327  {
328  const std::string paramName("fact: relax value");
329  getParamTryingTypes<magnitude_type, magnitude_type, double>(relaxValue, params, paramName, prefix);
330  }
331  {
332  const std::string paramName("fact: iluk overalloc");
333  getParamTryingTypes<double, double>(overalloc, params, paramName, prefix);
334  }
335 
336  // Parsing implementation type
337  Details::IlukImplType::Enum ilukimplType = Details::IlukImplType::Serial;
338  do {
339  static const char typeName[] = "fact: type";
340 
341  if (!params.isType<std::string>(typeName)) break;
342 
343  // Map std::string <-> IlukImplType::Enum.
344  Array<std::string> ilukimplTypeStrs;
345  Array<Details::IlukImplType::Enum> ilukimplTypeEnums;
346  Details::IlukImplType::loadPLTypeOption(ilukimplTypeStrs, ilukimplTypeEnums);
348  s2i(ilukimplTypeStrs(), ilukimplTypeEnums(), typeName, false);
349 
350  ilukimplType = s2i.getIntegralValue(params.get<std::string>(typeName));
351  } while (0);
352 
353  if (ilukimplType == Details::IlukImplType::KSPILUK) {
354  this->isKokkosKernelsSpiluk_ = true;
355  } else {
356  this->isKokkosKernelsSpiluk_ = false;
357  }
358 
359  {
360  const std::string paramName("fact: kspiluk number-of-streams");
361  getParamTryingTypes<int, int, global_ordinal_type>(nstreams, params, paramName, prefix);
362  }
363 
364  // Forward to trisolvers.
365  L_solver_->setParameters(params);
366  U_solver_->setParameters(params);
367 
368  // "Commit" the values only after validating all of them. This
369  // ensures that there are no side effects if this routine throws an
370  // exception.
371 
372  LevelOfFill_ = fillLevel;
373  Overalloc_ = overalloc;
374 #ifdef KOKKOS_ENABLE_OPENMP
375  if constexpr (std::is_same_v<execution_space, Kokkos::OpenMP>) {
376  nstreams = std::min(nstreams, execution_space{}.concurrency());
377  }
378 #endif
379  num_streams_ = nstreams;
380 
381  if (num_streams_ >= 1) {
382  this->isKokkosKernelsStream_ = true;
383  // Will we do reordering in streams?
384  if (params.isParameter("fact: kspiluk reordering in streams"))
385  hasStreamReordered_ = params.get<bool>("fact: kspiluk reordering in streams");
386  } else {
387  this->isKokkosKernelsStream_ = false;
388  }
389 
390  // mfh 28 Nov 2012: The previous code would not assign Athresh_,
391  // Rthresh_, or RelaxValue_, if the read-in value was -1. I don't
392  // know if keeping this behavior is correct, but I'll keep it just
393  // so as not to change previous behavior.
394 
395  if (absThresh != -STM::one()) {
396  Athresh_ = absThresh;
397  }
398  if (relThresh != -STM::one()) {
399  Rthresh_ = relThresh;
400  }
401  if (relaxValue != -STM::one()) {
402  RelaxValue_ = relaxValue;
403  }
404 }
405 
406 template <class MatrixType>
409  return Teuchos::rcp_implicit_cast<const row_matrix_type>(A_);
410 }
411 
412 template <class MatrixType>
415  return Teuchos::rcp_dynamic_cast<const crs_matrix_type>(A_, true);
416 }
417 
418 template <class MatrixType>
421  using Teuchos::RCP;
422  using Teuchos::rcp;
423  using Teuchos::rcp_dynamic_cast;
424  using Teuchos::rcp_implicit_cast;
425 
426  // If A_'s communicator only has one process, or if its column and
427  // row Maps are the same, then it is already local, so use it
428  // directly.
429  if (A->getRowMap()->getComm()->getSize() == 1 ||
430  A->getRowMap()->isSameAs(*(A->getColMap()))) {
431  return A;
432  }
433 
434  // If A_ is already a LocalFilter, then use it directly. This
435  // should be the case if RILUK is being used through
436  // AdditiveSchwarz, for example.
437  RCP<const LocalFilter<row_matrix_type> > A_lf_r =
438  rcp_dynamic_cast<const LocalFilter<row_matrix_type> >(A);
439  if (!A_lf_r.is_null()) {
440  return rcp_implicit_cast<const row_matrix_type>(A_lf_r);
441  } else {
442  // A_'s communicator has more than one process, its row Map and
443  // its column Map differ, and A_ is not a LocalFilter. Thus, we
444  // have to wrap it in a LocalFilter.
445  return rcp(new LocalFilter<row_matrix_type>(A));
446  }
447 }
448 
449 template <class MatrixType>
451  using Teuchos::Array;
452  using Teuchos::ArrayView;
453  using Teuchos::RCP;
454  using Teuchos::rcp;
455  using Teuchos::rcp_const_cast;
456  using Teuchos::rcp_dynamic_cast;
457  using Teuchos::rcp_implicit_cast;
458  typedef Tpetra::CrsGraph<local_ordinal_type,
460  node_type>
461  crs_graph_type;
462  typedef Tpetra::Map<local_ordinal_type,
463  global_ordinal_type,
464  node_type>
465  crs_map_type;
466  const char prefix[] = "Ifpack2::RILUK::initialize: ";
467 
468  TEUCHOS_TEST_FOR_EXCEPTION(A_.is_null(), std::runtime_error, prefix << "The matrix is null. Please "
469  "call setMatrix() with a nonnull input before calling this method.");
470  TEUCHOS_TEST_FOR_EXCEPTION(!A_->isFillComplete(), std::runtime_error, prefix << "The matrix is not "
471  "fill complete. You may not invoke initialize() or compute() with this "
472  "matrix until the matrix is fill complete. If your matrix is a "
473  "Tpetra::CrsMatrix, please call fillComplete on it (with the domain and "
474  "range Maps, if appropriate) before calling this method.");
475 
476  Teuchos::Time timer("RILUK::initialize");
477  double startTime = timer.wallTime();
478  { // Start timing
479  Teuchos::TimeMonitor timeMon(timer);
480 
481  // Calling initialize() means that the user asserts that the graph
482  // of the sparse matrix may have changed. We must not just reuse
483  // the previous graph in that case.
484  //
485  // Regarding setting isAllocated_ to false: Eventually, we may want
486  // some kind of clever memory reuse strategy, but it's always
487  // correct just to blow everything away and start over.
488  isInitialized_ = false;
489  isAllocated_ = false;
490  isComputed_ = false;
491  Graph_ = Teuchos::null;
492  Y_tmp_ = nullptr;
493  reordered_x_ = nullptr;
494  reordered_y_ = nullptr;
495 
496  if (isKokkosKernelsStream_) {
497  Graph_v_ = std::vector<Teuchos::RCP<iluk_graph_type> >(num_streams_);
498  A_local_diagblks = std::vector<local_matrix_device_type>(num_streams_);
499  for (int i = 0; i < num_streams_; i++) {
500  Graph_v_[i] = Teuchos::null;
501  }
502  }
503 
504  A_local_ = makeLocalFilter(A_);
505 
507  A_local_.is_null(), std::logic_error,
508  "Ifpack2::RILUK::initialize: "
509  "makeLocalFilter returned null; it failed to compute A_local. "
510  "Please report this bug to the Ifpack2 developers.");
511 
512  // FIXME (mfh 24 Jan 2014, 26 Mar 2014) It would be more efficient
513  // to rewrite RILUK so that it works with any RowMatrix input, not
514  // just CrsMatrix. (That would require rewriting IlukGraph to
515  // handle a Tpetra::RowGraph.) However, to make it work for now,
516  // we just copy the input matrix if it's not a CrsMatrix.
517 
518  {
519  A_local_crs_ = Details::getCrsMatrix(A_local_);
520  if (A_local_crs_.is_null()) {
521  local_ordinal_type numRows = A_local_->getLocalNumRows();
522  Array<size_t> entriesPerRow(numRows);
523  for (local_ordinal_type i = 0; i < numRows; i++) {
524  entriesPerRow[i] = A_local_->getNumEntriesInLocalRow(i);
525  }
526  A_local_crs_nc_ =
527  rcp(new crs_matrix_type(A_local_->getRowMap(),
528  A_local_->getColMap(),
529  entriesPerRow()));
530  // copy entries into A_local_crs
531  nonconst_local_inds_host_view_type indices("indices", A_local_->getLocalMaxNumRowEntries());
532  nonconst_values_host_view_type values("values", A_local_->getLocalMaxNumRowEntries());
533  for (local_ordinal_type i = 0; i < numRows; i++) {
534  size_t numEntries = 0;
535  A_local_->getLocalRowCopy(i, indices, values, numEntries);
536  A_local_crs_nc_->insertLocalValues(i, numEntries, reinterpret_cast<scalar_type*>(values.data()), indices.data());
537  }
538  A_local_crs_nc_->fillComplete(A_local_->getDomainMap(), A_local_->getRangeMap());
539  A_local_crs_ = rcp_const_cast<const crs_matrix_type>(A_local_crs_nc_);
540  }
541  if (!isKokkosKernelsStream_) {
542  Graph_ = rcp(new Ifpack2::IlukGraph<crs_graph_type, kk_handle_type>(A_local_crs_->getCrsGraph(),
543  LevelOfFill_, 0, Overalloc_));
544  } else {
545  std::vector<int> weights(num_streams_);
546  std::fill(weights.begin(), weights.end(), 1);
547  exec_space_instances_ = Kokkos::Experimental::partition_space(execution_space(), weights);
548 
549  auto lclMtx = A_local_crs_->getLocalMatrixDevice();
550  if (!hasStreamReordered_) {
551  KokkosSparse::Impl::kk_extract_diagonal_blocks_crsmatrix_sequential(lclMtx, A_local_diagblks);
552  } else {
553  perm_v_ = KokkosSparse::Impl::kk_extract_diagonal_blocks_crsmatrix_sequential(lclMtx, A_local_diagblks, true);
554  reverse_perm_v_.resize(perm_v_.size());
555  for (size_t istream = 0; istream < perm_v_.size(); ++istream) {
556  using perm_type = typename lno_nonzero_view_t::non_const_type;
557  const auto perm = perm_v_[istream];
558  const auto perm_length = perm.extent(0);
559  perm_type reverse_perm(
560  Kokkos::view_alloc(Kokkos::WithoutInitializing, "reverse_perm"),
561  perm_length);
562  Kokkos::parallel_for(
563  Kokkos::RangePolicy<execution_space>(exec_space_instances_[istream], 0, perm_length),
564  KOKKOS_LAMBDA(const local_ordinal_type ii) {
565  reverse_perm(perm(ii)) = ii;
566  });
567  reverse_perm_v_[istream] = reverse_perm;
568  }
569  }
570 
571  A_local_diagblks_rowmap_v_ = std::vector<lno_row_view_t>(num_streams_);
572  A_local_diagblks_entries_v_ = std::vector<lno_nonzero_view_t>(num_streams_);
573  A_local_diagblks_values_v_ = std::vector<scalar_nonzero_view_t>(num_streams_);
574 
575  for (int i = 0; i < num_streams_; i++) {
576  A_local_diagblks_rowmap_v_[i] = A_local_diagblks[i].graph.row_map;
577  A_local_diagblks_entries_v_[i] = A_local_diagblks[i].graph.entries;
578  A_local_diagblks_values_v_[i] = A_local_diagblks[i].values;
579 
580  Teuchos::RCP<const crs_map_type> A_local_diagblks_RowMap = rcp(new crs_map_type(A_local_diagblks[i].numRows(),
581  A_local_diagblks[i].numRows(),
582  A_local_crs_->getRowMap()->getComm()));
583  Teuchos::RCP<const crs_map_type> A_local_diagblks_ColMap = rcp(new crs_map_type(A_local_diagblks[i].numCols(),
584  A_local_diagblks[i].numCols(),
585  A_local_crs_->getColMap()->getComm()));
586  Teuchos::RCP<crs_matrix_type> A_local_diagblks_ = rcp(new crs_matrix_type(A_local_diagblks_RowMap,
587  A_local_diagblks_ColMap,
588  A_local_diagblks[i]));
589  Graph_v_[i] = rcp(new Ifpack2::IlukGraph<crs_graph_type, kk_handle_type>(A_local_diagblks_->getCrsGraph(),
590  LevelOfFill_, 0, Overalloc_));
591  }
592  }
593  }
594 
595  if (this->isKokkosKernelsSpiluk_) {
596  if (!isKokkosKernelsStream_) {
597  this->KernelHandle_ = Teuchos::rcp(new kk_handle_type());
598  KernelHandle_->create_spiluk_handle(KokkosSparse::Experimental::SPILUKAlgorithm::SEQLVLSCHD_TP1,
599  A_local_->getLocalNumRows(),
600  2 * A_local_->getLocalNumEntries() * (LevelOfFill_ + 1),
601  2 * A_local_->getLocalNumEntries() * (LevelOfFill_ + 1));
602  Graph_->initialize(KernelHandle_); // this calls spiluk_symbolic
603  } else {
604  KernelHandle_v_ = std::vector<Teuchos::RCP<kk_handle_type> >(num_streams_);
605  for (int i = 0; i < num_streams_; i++) {
606  KernelHandle_v_[i] = Teuchos::rcp(new kk_handle_type());
607  KernelHandle_v_[i]->create_spiluk_handle(KokkosSparse::Experimental::SPILUKAlgorithm::SEQLVLSCHD_TP1,
608  A_local_diagblks[i].numRows(),
609  2 * A_local_diagblks[i].nnz() * (LevelOfFill_ + 1),
610  2 * A_local_diagblks[i].nnz() * (LevelOfFill_ + 1));
611  Graph_v_[i]->initialize(KernelHandle_v_[i]); // this calls spiluk_symbolic
612  }
613  }
614  } else {
615  Graph_->initialize();
616  }
617 
618  allocate_L_and_U();
619  checkOrderingConsistency(*A_local_);
620  if (!isKokkosKernelsStream_) {
621  L_solver_->setMatrix(L_);
622  } else {
623  L_solver_->setStreamInfo(isKokkosKernelsStream_, num_streams_, exec_space_instances_);
624  L_solver_->setMatrices(L_v_);
625  }
626  L_solver_->initialize();
627 
628  if (!isKokkosKernelsStream_) {
629  U_solver_->setMatrix(U_);
630  } else {
631  U_solver_->setStreamInfo(isKokkosKernelsStream_, num_streams_, exec_space_instances_);
632  U_solver_->setMatrices(U_v_);
633  }
634  U_solver_->initialize();
635 
636  // Do not call initAllValues. compute() always calls initAllValues to
637  // fill L and U with possibly new numbers. initialize() is concerned
638  // only with the nonzero pattern.
639  } // Stop timing
640 
641  isInitialized_ = true;
642  ++numInitialize_;
643  initializeTime_ += (timer.wallTime() - startTime);
644 }
645 
646 template <class MatrixType>
648  checkOrderingConsistency(const row_matrix_type& A) {
649  // First check that the local row map ordering is the same as the local portion of the column map.
650  // The extraction of the strictly lower/upper parts of A, as well as the factorization,
651  // implicitly assume that this is the case.
652  Teuchos::ArrayView<const global_ordinal_type> rowGIDs = A.getRowMap()->getLocalElementList();
653  Teuchos::ArrayView<const global_ordinal_type> colGIDs = A.getColMap()->getLocalElementList();
654  bool gidsAreConsistentlyOrdered = true;
655  global_ordinal_type indexOfInconsistentGID = 0;
656  for (global_ordinal_type i = 0; i < rowGIDs.size(); ++i) {
657  if (rowGIDs[i] != colGIDs[i]) {
658  gidsAreConsistentlyOrdered = false;
659  indexOfInconsistentGID = i;
660  break;
661  }
662  }
663  TEUCHOS_TEST_FOR_EXCEPTION(gidsAreConsistentlyOrdered == false, std::runtime_error,
664  "The ordering of the local GIDs in the row and column maps is not the same"
665  << std::endl
666  << "at index " << indexOfInconsistentGID
667  << ". Consistency is required, as all calculations are done with"
668  << std::endl
669  << "local indexing.");
670 }
671 
672 template <class MatrixType>
673 void RILUK<MatrixType>::
674  initAllValues(const row_matrix_type& A) {
675  using Teuchos::ArrayRCP;
676  using Teuchos::Comm;
677  using Teuchos::ptr;
678  using Teuchos::RCP;
679  using Teuchos::REDUCE_SUM;
680  using Teuchos::reduceAll;
681  typedef Tpetra::Map<local_ordinal_type, global_ordinal_type, node_type> map_type;
682 
683  size_t NumIn = 0, NumL = 0, NumU = 0;
684  bool DiagFound = false;
685  size_t NumNonzeroDiags = 0;
686  size_t MaxNumEntries = A.getGlobalMaxNumRowEntries();
687 
688  // Allocate temporary space for extracting the strictly
689  // lower and upper parts of the matrix A.
690  nonconst_local_inds_host_view_type InI("InI", MaxNumEntries);
691  Teuchos::Array<local_ordinal_type> LI(MaxNumEntries);
692  Teuchos::Array<local_ordinal_type> UI(MaxNumEntries);
693  nonconst_values_host_view_type InV("InV", MaxNumEntries);
694  Teuchos::Array<scalar_type> LV(MaxNumEntries);
695  Teuchos::Array<scalar_type> UV(MaxNumEntries);
696 
697  // Check if values should be inserted or replaced
698  const bool ReplaceValues = L_->isStaticGraph() || L_->isLocallyIndexed();
699 
700  L_->resumeFill();
701  U_->resumeFill();
702  if (ReplaceValues) {
703  L_->setAllToScalar(STS::zero()); // Zero out L and U matrices
704  U_->setAllToScalar(STS::zero());
705  }
706 
707  D_->putScalar(STS::zero()); // Set diagonal values to zero
708  auto DV = Kokkos::subview(D_->getLocalViewHost(Tpetra::Access::ReadWrite), Kokkos::ALL(), 0);
709 
710  RCP<const map_type> rowMap = L_->getRowMap();
711 
712  // First we copy the user's matrix into L and U, regardless of fill level.
713  // It is important to note that L and U are populated using local indices.
714  // This means that if the row map GIDs are not monotonically increasing
715  // (i.e., permuted or gappy), then the strictly lower (upper) part of the
716  // matrix is not the one that you would get if you based L (U) on GIDs.
717  // This is ok, as the *order* of the GIDs in the rowmap is a better
718  // expression of the user's intent than the GIDs themselves.
719 
720  Teuchos::ArrayView<const global_ordinal_type> nodeGIDs = rowMap->getLocalElementList();
721  for (size_t myRow = 0; myRow < A.getLocalNumRows(); ++myRow) {
722  local_ordinal_type local_row = myRow;
723 
724  // TODO JJH 4April2014 An optimization is to use getLocalRowView. Not all matrices support this,
725  // we'd need to check via the Tpetra::RowMatrix method supportsRowViews().
726  A.getLocalRowCopy(local_row, InI, InV, NumIn); // Get Values and Indices
727 
728  // Split into L and U (we don't assume that indices are ordered).
729 
730  NumL = 0;
731  NumU = 0;
732  DiagFound = false;
733 
734  for (size_t j = 0; j < NumIn; ++j) {
735  const local_ordinal_type k = InI[j];
736 
737  if (k == local_row) {
738  DiagFound = true;
739  // Store perturbed diagonal in Tpetra::Vector D_
740  DV(local_row) += Rthresh_ * InV[j] + IFPACK2_SGN(InV[j]) * Athresh_;
741  } else if (k < 0) { // Out of range
743  true, std::runtime_error,
744  "Ifpack2::RILUK::initAllValues: current "
745  "GID k = "
746  << k << " < 0. I'm not sure why this is an error; it is "
747  "probably an artifact of the undocumented assumptions of the "
748  "original implementation (likely copied and pasted from Ifpack). "
749  "Nevertheless, the code I found here insisted on this being an error "
750  "state, so I will throw an exception here.");
751  } else if (k < local_row) {
752  LI[NumL] = k;
753  LV[NumL] = InV[j];
754  NumL++;
755  } else if (Teuchos::as<size_t>(k) <= rowMap->getLocalNumElements()) {
756  UI[NumU] = k;
757  UV[NumU] = InV[j];
758  NumU++;
759  }
760  }
761 
762  // Check in things for this row of L and U
763 
764  if (DiagFound) {
765  ++NumNonzeroDiags;
766  } else {
767  DV(local_row) = Athresh_;
768  }
769 
770  if (NumL) {
771  if (ReplaceValues) {
772  L_->replaceLocalValues(local_row, LI(0, NumL), LV(0, NumL));
773  } else {
774  // FIXME JJH 24April2014 Is this correct? I believe this case is when there aren't already values
775  // FIXME in this row in the column locations corresponding to UI.
776  L_->insertLocalValues(local_row, LI(0, NumL), LV(0, NumL));
777  }
778  }
779 
780  if (NumU) {
781  if (ReplaceValues) {
782  U_->replaceLocalValues(local_row, UI(0, NumU), UV(0, NumU));
783  } else {
784  // FIXME JJH 24April2014 Is this correct? I believe this case is when there aren't already values
785  // FIXME in this row in the column locations corresponding to UI.
786  U_->insertLocalValues(local_row, UI(0, NumU), UV(0, NumU));
787  }
788  }
789  }
790 
791  // At this point L and U have the values of A in the structure of L
792  // and U, and diagonal vector D
793 
794  isInitialized_ = true;
795 }
796 
797 template <class MatrixType>
798 void RILUK<MatrixType>::compute_serial() {
799  // Fill L and U with numbers. This supports nonzero pattern reuse by calling
800  // initialize() once and then compute() multiple times.
801  initAllValues(*A_local_);
802 
803  // MinMachNum should be officially defined, for now pick something a little
804  // bigger than IEEE underflow value
805 
806  const scalar_type MinDiagonalValue = STS::rmin();
807  const scalar_type MaxDiagonalValue = STS::one() / MinDiagonalValue;
808 
809  size_t NumIn, NumL, NumU;
810 
811  // Get Maximum Row length
812  const size_t MaxNumEntries =
813  L_->getLocalMaxNumRowEntries() + U_->getLocalMaxNumRowEntries() + 1;
814 
815  Teuchos::Array<local_ordinal_type> InI(MaxNumEntries); // Allocate temp space
816  Teuchos::Array<scalar_type> InV(MaxNumEntries);
817  size_t num_cols = U_->getColMap()->getLocalNumElements();
818  Teuchos::Array<int> colflag(num_cols, -1);
819 
820  auto DV = Kokkos::subview(D_->getLocalViewHost(Tpetra::Access::ReadWrite), Kokkos::ALL(), 0);
821 
822  // Now start the factorization.
823 
824  using IST = typename row_matrix_type::impl_scalar_type;
825  for (size_t i = 0; i < L_->getLocalNumRows(); ++i) {
826  local_ordinal_type local_row = i;
827  // Need some integer workspace and pointers
828  size_t NumUU;
829  local_inds_host_view_type UUI;
830  values_host_view_type UUV;
831 
832  // Fill InV, InI with current row of L, D and U combined
833 
834  NumIn = MaxNumEntries;
835  nonconst_local_inds_host_view_type InI_v(InI.data(), MaxNumEntries);
836  nonconst_values_host_view_type InV_v(reinterpret_cast<IST*>(InV.data()), MaxNumEntries);
837 
838  L_->getLocalRowCopy(local_row, InI_v, InV_v, NumL);
839 
840  InV[NumL] = DV(i); // Put in diagonal
841  InI[NumL] = local_row;
842 
843  nonconst_local_inds_host_view_type InI_sub(InI.data() + NumL + 1, MaxNumEntries - NumL - 1);
844  nonconst_values_host_view_type InV_sub(reinterpret_cast<IST*>(InV.data()) + NumL + 1, MaxNumEntries - NumL - 1);
845 
846  U_->getLocalRowCopy(local_row, InI_sub, InV_sub, NumU);
847  NumIn = NumL + NumU + 1;
848 
849  // Set column flags
850  for (size_t j = 0; j < NumIn; ++j) {
851  colflag[InI[j]] = j;
852  }
853 
854  scalar_type diagmod = STS::zero(); // Off-diagonal accumulator
855 
856  for (size_t jj = 0; jj < NumL; ++jj) {
857  local_ordinal_type j = InI[jj];
858  IST multiplier = InV[jj]; // current_mults++;
859 
860  InV[jj] *= static_cast<scalar_type>(DV(j));
861 
862  U_->getLocalRowView(j, UUI, UUV); // View of row above
863  NumUU = UUI.size();
864 
865  if (RelaxValue_ == STM::zero()) {
866  for (size_t k = 0; k < NumUU; ++k) {
867  const int kk = colflag[UUI[k]];
868  // FIXME (mfh 23 Dec 2013) Wait a second, we just set
869  // colflag above using size_t (which is generally unsigned),
870  // but now we're querying it using int (which is signed).
871  if (kk > -1) {
872  InV[kk] -= static_cast<scalar_type>(multiplier * UUV[k]);
873  }
874  }
875 
876  } else {
877  for (size_t k = 0; k < NumUU; ++k) {
878  // FIXME (mfh 23 Dec 2013) Wait a second, we just set
879  // colflag above using size_t (which is generally unsigned),
880  // but now we're querying it using int (which is signed).
881  const int kk = colflag[UUI[k]];
882  if (kk > -1) {
883  InV[kk] -= static_cast<scalar_type>(multiplier * UUV[k]);
884  } else {
885  diagmod -= static_cast<scalar_type>(multiplier * UUV[k]);
886  }
887  }
888  }
889  }
890 
891  if (NumL) {
892  // Replace current row of L
893  L_->replaceLocalValues(local_row, InI(0, NumL), InV(0, NumL));
894  }
895 
896  DV(i) = InV[NumL]; // Extract Diagonal value
897 
898  if (RelaxValue_ != STM::zero()) {
899  DV(i) += RelaxValue_ * diagmod; // Add off diagonal modifications
900  }
901 
902  if (STS::magnitude(DV(i)) > STS::magnitude(MaxDiagonalValue)) {
903  if (STS::real(DV(i)) < STM::zero()) {
904  DV(i) = -MinDiagonalValue;
905  } else {
906  DV(i) = MinDiagonalValue;
907  }
908  } else {
909  DV(i) = static_cast<impl_scalar_type>(STS::one()) / DV(i); // Invert diagonal value
910  }
911 
912  for (size_t j = 0; j < NumU; ++j) {
913  InV[NumL + 1 + j] *= static_cast<scalar_type>(DV(i)); // Scale U by inverse of diagonal
914  }
915 
916  if (NumU) {
917  // Replace current row of L and U
918  U_->replaceLocalValues(local_row, InI(NumL + 1, NumU), InV(NumL + 1, NumU));
919  }
920 
921  // Reset column flags
922  for (size_t j = 0; j < NumIn; ++j) {
923  colflag[InI[j]] = -1;
924  }
925  }
926 
927  // The domain of L and the range of U are exactly their own row maps
928  // (there is no communication). The domain of U and the range of L
929  // must be the same as those of the original matrix, However if the
930  // original matrix is a VbrMatrix, these two latter maps are
931  // translation from a block map to a point map.
932  // FIXME (mfh 23 Dec 2013) Do we know that the column Map of L_ is
933  // always one-to-one?
934  L_->fillComplete(L_->getColMap(), A_local_->getRangeMap());
935  U_->fillComplete(A_local_->getDomainMap(), U_->getRowMap());
936 
937  // If L_solver_ or U_solver store modified factors internally, we need to reset those
938  L_solver_->setMatrix(L_);
939  L_solver_->compute(); // NOTE: Only do compute if the pointer changed. Otherwise, do nothing
940  U_solver_->setMatrix(U_);
941  U_solver_->compute(); // NOTE: Only do compute if the pointer changed. Otherwise, do nothing
942 }
943 
944 template <class MatrixType>
945 void RILUK<MatrixType>::compute_kkspiluk() {
946  L_->resumeFill();
947  U_->resumeFill();
948 
949  L_->setAllToScalar(STS::zero()); // Zero out L and U matrices
950  U_->setAllToScalar(STS::zero());
951 
952  using row_map_type = typename crs_matrix_type::local_matrix_device_type::row_map_type;
953  auto lclL = L_->getLocalMatrixDevice();
954  row_map_type L_rowmap = lclL.graph.row_map;
955  auto L_entries = lclL.graph.entries;
956  auto L_values = lclL.values;
957 
958  auto lclU = U_->getLocalMatrixDevice();
959  row_map_type U_rowmap = lclU.graph.row_map;
960  auto U_entries = lclU.graph.entries;
961  auto U_values = lclU.values;
962 
963  auto lclMtx = A_local_crs_->getLocalMatrixDevice();
964  KokkosSparse::spiluk_numeric(KernelHandle_.getRawPtr(), LevelOfFill_,
965  lclMtx.graph.row_map, lclMtx.graph.entries, lclMtx.values,
966  L_rowmap, L_entries, L_values, U_rowmap, U_entries, U_values);
967 
968  L_->fillComplete(L_->getColMap(), A_local_->getRangeMap());
969  U_->fillComplete(A_local_->getDomainMap(), U_->getRowMap());
970 
971  L_solver_->compute();
972  U_solver_->compute();
973 }
974 
975 template <class MatrixType>
976 void RILUK<MatrixType>::compute_kkspiluk_stream() {
977  for (int i = 0; i < num_streams_; i++) {
978  L_v_[i]->resumeFill();
979  U_v_[i]->resumeFill();
980 
981  L_v_[i]->setAllToScalar(STS::zero()); // Zero out L and U matrices
982  U_v_[i]->setAllToScalar(STS::zero());
983  }
984  std::vector<lno_row_view_t> L_rowmap_v(num_streams_);
985  std::vector<lno_nonzero_view_t> L_entries_v(num_streams_);
986  std::vector<scalar_nonzero_view_t> L_values_v(num_streams_);
987  std::vector<lno_row_view_t> U_rowmap_v(num_streams_);
988  std::vector<lno_nonzero_view_t> U_entries_v(num_streams_);
989  std::vector<scalar_nonzero_view_t> U_values_v(num_streams_);
990  std::vector<kk_handle_type*> KernelHandle_rawptr_v_(num_streams_);
991  for (int i = 0; i < num_streams_; i++) {
992  auto lclL = L_v_[i]->getLocalMatrixDevice();
993  L_rowmap_v[i] = lclL.graph.row_map;
994  L_entries_v[i] = lclL.graph.entries;
995  L_values_v[i] = lclL.values;
996 
997  auto lclU = U_v_[i]->getLocalMatrixDevice();
998  U_rowmap_v[i] = lclU.graph.row_map;
999  U_entries_v[i] = lclU.graph.entries;
1000  U_values_v[i] = lclU.values;
1001  KernelHandle_rawptr_v_[i] = KernelHandle_v_[i].getRawPtr();
1002  }
1003 
1004  {
1005  auto lclMtx = A_local_crs_->getLocalMatrixDevice();
1006  // A_local_diagblks was already setup during initialize, just copy the corresponding
1007  // values from A_local_crs_ in parallel now.
1008  using TeamPolicy = Kokkos::TeamPolicy<execution_space>;
1009  const auto A_nrows = lclMtx.numRows();
1010  auto rows_per_block = ((A_nrows % num_streams_) == 0)
1011  ? (A_nrows / num_streams_)
1012  : (A_nrows / num_streams_ + 1);
1013  for (int i = 0; i < num_streams_; i++) {
1014  const auto start_row_offset = i * rows_per_block;
1015  auto rowptrs = A_local_diagblks_rowmap_v_[i];
1016  auto colindices = A_local_diagblks_entries_v_[i];
1017  auto values = A_local_diagblks_values_v_[i];
1018  const bool reordered = hasStreamReordered_;
1019  typename lno_nonzero_view_t::non_const_type reverse_perm = hasStreamReordered_ ? reverse_perm_v_[i] : typename lno_nonzero_view_t::non_const_type{};
1020  TeamPolicy pol(exec_space_instances_[i], A_local_diagblks_rowmap_v_[i].extent(0) - 1, Kokkos::AUTO);
1021  Kokkos::parallel_for(
1022  pol, KOKKOS_LAMBDA(const typename TeamPolicy::member_type& team) {
1023  const auto irow = team.league_rank();
1024  const auto irow_A = start_row_offset + (reordered ? reverse_perm(irow) : irow);
1025  const auto A_local_crs_row = lclMtx.rowConst(irow_A);
1026  const auto begin_row = rowptrs(irow);
1027  const auto num_entries = rowptrs(irow + 1) - begin_row;
1028  Kokkos::parallel_for(Kokkos::TeamThreadRange(team, num_entries), [&](const int j) {
1029  const auto colidx = colindices(begin_row + j);
1030  const auto colidx_A = start_row_offset + (reordered ? reverse_perm(colidx) : colidx);
1031  // Find colidx in A_local_crs_row
1032  const int offset = KokkosSparse::findRelOffset(
1033  &A_local_crs_row.colidx(0), A_local_crs_row.length, colidx_A, 0, false);
1034  values(begin_row + j) = A_local_crs_row.value(offset);
1035  });
1036  });
1037  }
1038  }
1039 
1040  KokkosSparse::Experimental::spiluk_numeric_streams(exec_space_instances_, KernelHandle_rawptr_v_, LevelOfFill_,
1041  A_local_diagblks_rowmap_v_, A_local_diagblks_entries_v_, A_local_diagblks_values_v_,
1042  L_rowmap_v, L_entries_v, L_values_v,
1043  U_rowmap_v, U_entries_v, U_values_v);
1044  for (int i = 0; i < num_streams_; i++) {
1045  L_v_[i]->fillComplete();
1046  U_v_[i]->fillComplete();
1047  }
1048 
1049  L_solver_->compute();
1050  U_solver_->compute();
1051 }
1052 
1053 template <class MatrixType>
1055  using Teuchos::Array;
1056  using Teuchos::ArrayView;
1057  using Teuchos::RCP;
1058  using Teuchos::rcp;
1059  using Teuchos::rcp_const_cast;
1060  using Teuchos::rcp_dynamic_cast;
1061  const char prefix[] = "Ifpack2::RILUK::compute: ";
1062 
1063  // initialize() checks this too, but it's easier for users if the
1064  // error shows them the name of the method that they actually
1065  // called, rather than the name of some internally called method.
1066  TEUCHOS_TEST_FOR_EXCEPTION(A_.is_null(), std::runtime_error, prefix << "The matrix is null. Please "
1067  "call setMatrix() with a nonnull input before calling this method.");
1068  TEUCHOS_TEST_FOR_EXCEPTION(!A_->isFillComplete(), std::runtime_error, prefix << "The matrix is not "
1069  "fill complete. You may not invoke initialize() or compute() with this "
1070  "matrix until the matrix is fill complete. If your matrix is a "
1071  "Tpetra::CrsMatrix, please call fillComplete on it (with the domain and "
1072  "range Maps, if appropriate) before calling this method.");
1073 
1074  if (!isInitialized()) {
1075  initialize(); // Don't count this in the compute() time
1076  }
1077 
1078  Teuchos::Time timer("RILUK::compute");
1079 
1080  // Start timing
1081  Teuchos::TimeMonitor timeMon(timer);
1082  double startTime = timer.wallTime();
1083 
1084  isComputed_ = false;
1085 
1086  if (!this->isKokkosKernelsSpiluk_) {
1087  compute_serial();
1088  } else {
1089  // Make sure values in A is picked up even in case of pattern reuse
1090  if (!A_local_crs_nc_.is_null()) {
1091  A_local_crs_nc_->resumeFill();
1092  local_ordinal_type numRows = A_local_->getLocalNumRows();
1093  Array<size_t> entriesPerRow(numRows);
1094  for (local_ordinal_type i = 0; i < numRows; i++) {
1095  entriesPerRow[i] = A_local_->getNumEntriesInLocalRow(i);
1096  }
1097  // copy entries into A_local_crs
1098  nonconst_local_inds_host_view_type indices("indices", A_local_->getLocalMaxNumRowEntries());
1099  nonconst_values_host_view_type values("values", A_local_->getLocalMaxNumRowEntries());
1100  for (local_ordinal_type i = 0; i < numRows; i++) {
1101  size_t numEntries = 0;
1102  A_local_->getLocalRowCopy(i, indices, values, numEntries);
1103  A_local_crs_nc_->replaceLocalValues(i, numEntries, reinterpret_cast<scalar_type*>(values.data()), indices.data());
1104  }
1105  A_local_crs_nc_->fillComplete(A_local_->getDomainMap(), A_local_->getRangeMap());
1106  }
1107 
1108  if (!isKokkosKernelsStream_) {
1109  compute_kkspiluk();
1110  } else {
1111  compute_kkspiluk_stream();
1112  }
1113  }
1114 
1115  isComputed_ = true;
1116  ++numCompute_;
1117  computeTime_ += (timer.wallTime() - startTime);
1118 }
1119 
1120 namespace Impl {
1121 template <typename MV, typename Map>
1122 void resetMultiVecIfNeeded(std::unique_ptr<MV>& mv_ptr, const Map& map, const size_t numVectors, bool initialize) {
1123  if (!mv_ptr || mv_ptr->getNumVectors() != numVectors) {
1124  mv_ptr.reset(new MV(map, numVectors, initialize));
1125  }
1126 }
1127 } // namespace Impl
1128 
1129 template <class MatrixType>
1131  apply(const Tpetra::MultiVector<scalar_type, local_ordinal_type, global_ordinal_type, node_type>& X,
1132  Tpetra::MultiVector<scalar_type, local_ordinal_type, global_ordinal_type, node_type>& Y,
1133  Teuchos::ETransp mode,
1134  scalar_type alpha,
1135  scalar_type beta) const {
1136  using Teuchos::RCP;
1137  using Teuchos::rcpFromRef;
1138 
1140  A_.is_null(), std::runtime_error,
1141  "Ifpack2::RILUK::apply: The matrix is "
1142  "null. Please call setMatrix() with a nonnull input, then initialize() "
1143  "and compute(), before calling this method.");
1145  !isComputed(), std::runtime_error,
1146  "Ifpack2::RILUK::apply: If you have not yet called compute(), "
1147  "you must call compute() before calling this method.");
1148  TEUCHOS_TEST_FOR_EXCEPTION(
1149  X.getNumVectors() != Y.getNumVectors(), std::invalid_argument,
1150  "Ifpack2::RILUK::apply: X and Y do not have the same number of columns. "
1151  "X.getNumVectors() = "
1152  << X.getNumVectors()
1153  << " != Y.getNumVectors() = " << Y.getNumVectors() << ".");
1154  TEUCHOS_TEST_FOR_EXCEPTION(
1155  STS::isComplex && mode == Teuchos::CONJ_TRANS, std::logic_error,
1156  "Ifpack2::RILUK::apply: mode = Teuchos::CONJ_TRANS is not implemented for "
1157  "complex Scalar type. Please talk to the Ifpack2 developers to get this "
1158  "fixed. There is a FIXME in this file about this very issue.");
1159 #ifdef HAVE_IFPACK2_DEBUG
1160  {
1161  if (!isKokkosKernelsStream_) {
1162  const magnitude_type D_nrm1 = D_->norm1();
1163  TEUCHOS_TEST_FOR_EXCEPTION(STM::isnaninf(D_nrm1), std::runtime_error, "Ifpack2::RILUK::apply: The 1-norm of the stored diagonal is NaN or Inf.");
1164  }
1165  Teuchos::Array<magnitude_type> norms(X.getNumVectors());
1166  X.norm1(norms());
1167  bool good = true;
1168  for (size_t j = 0; j < X.getNumVectors(); ++j) {
1169  if (STM::isnaninf(norms[j])) {
1170  good = false;
1171  break;
1172  }
1173  }
1174  TEUCHOS_TEST_FOR_EXCEPTION(!good, std::runtime_error, "Ifpack2::RILUK::apply: The 1-norm of the input X is NaN or Inf.");
1175  }
1176 #endif // HAVE_IFPACK2_DEBUG
1177 
1178  const scalar_type one = STS::one();
1179  const scalar_type zero = STS::zero();
1180 
1181  Teuchos::Time timer("RILUK::apply");
1182  double startTime = timer.wallTime();
1183  { // Start timing
1184  Teuchos::TimeMonitor timeMon(timer);
1185  if (alpha == one && beta == zero) {
1186  if (isKokkosKernelsSpiluk_ && isKokkosKernelsStream_ && hasStreamReordered_) {
1187  Impl::resetMultiVecIfNeeded(reordered_x_, X.getMap(), X.getNumVectors(), false);
1188  Impl::resetMultiVecIfNeeded(reordered_y_, Y.getMap(), Y.getNumVectors(), false);
1189  Kokkos::fence();
1190  for (size_t j = 0; j < X.getNumVectors(); j++) {
1191  auto X_j = X.getVector(j);
1192  auto ReorderedX_j = reordered_x_->getVectorNonConst(j);
1193  auto X_lcl = X_j->getLocalViewDevice(Tpetra::Access::ReadOnly);
1194  auto ReorderedX_lcl = ReorderedX_j->getLocalViewDevice(Tpetra::Access::ReadWrite);
1195  local_ordinal_type stream_begin = 0;
1196  local_ordinal_type stream_end;
1197  for (int i = 0; i < num_streams_; i++) {
1198  auto perm_i = perm_v_[i];
1199  stream_end = stream_begin + perm_i.extent(0);
1200  auto X_lcl_sub = Kokkos::subview(X_lcl, Kokkos::make_pair(stream_begin, stream_end), 0);
1201  auto ReorderedX_lcl_sub = Kokkos::subview(ReorderedX_lcl, Kokkos::make_pair(stream_begin, stream_end), 0);
1202  Kokkos::parallel_for(
1203  Kokkos::RangePolicy<execution_space>(exec_space_instances_[i], 0, static_cast<int>(perm_i.extent(0))), KOKKOS_LAMBDA(const int& ii) {
1204  ReorderedX_lcl_sub(perm_i(ii)) = X_lcl_sub(ii);
1205  });
1206  stream_begin = stream_end;
1207  }
1208  }
1209  Kokkos::fence();
1210  if (mode == Teuchos::NO_TRANS) { // Solve L (U Y) = X for Y.
1211  // Solve L Y = X for Y.
1212  L_solver_->apply(*reordered_x_, Y, mode);
1213  // Solve U Y = Y for Y.
1214  U_solver_->apply(Y, *reordered_y_, mode);
1215  } else { // Solve U^P (L^P Y) = X for Y (where P is * or T).
1216  // Solve U^P Y = X for Y.
1217  U_solver_->apply(*reordered_x_, Y, mode);
1218  // Solve L^P Y = Y for Y.
1219  L_solver_->apply(Y, *reordered_y_, mode);
1220  }
1221 
1222  for (size_t j = 0; j < Y.getNumVectors(); j++) {
1223  auto Y_j = Y.getVectorNonConst(j);
1224  auto ReorderedY_j = reordered_y_->getVector(j);
1225  auto Y_lcl = Y_j->getLocalViewDevice(Tpetra::Access::ReadWrite);
1226  auto ReorderedY_lcl = ReorderedY_j->getLocalViewDevice(Tpetra::Access::ReadOnly);
1227  local_ordinal_type stream_begin = 0;
1228  local_ordinal_type stream_end;
1229  for (int i = 0; i < num_streams_; i++) {
1230  auto perm_i = perm_v_[i];
1231  stream_end = stream_begin + perm_i.extent(0);
1232  auto Y_lcl_sub = Kokkos::subview(Y_lcl, Kokkos::make_pair(stream_begin, stream_end), 0);
1233  auto ReorderedY_lcl_sub = Kokkos::subview(ReorderedY_lcl, Kokkos::make_pair(stream_begin, stream_end), 0);
1234  Kokkos::parallel_for(
1235  Kokkos::RangePolicy<execution_space>(exec_space_instances_[i], 0, static_cast<int>(perm_i.extent(0))), KOKKOS_LAMBDA(const int& ii) {
1236  Y_lcl_sub(ii) = ReorderedY_lcl_sub(perm_i(ii));
1237  });
1238  stream_begin = stream_end;
1239  }
1240  }
1241  Kokkos::fence();
1242  } else {
1243  if (mode == Teuchos::NO_TRANS) { // Solve L (D (U Y)) = X for Y.
1244 #if defined(KOKKOSKERNELS_ENABLE_TPL_CUSPARSE) && defined(KOKKOS_ENABLE_CUDA) && (CUDA_VERSION >= 11030)
1245  // NOTE (Nov-15-2022):
1246  // This is a workaround for Cuda >= 11.3 (using cusparseSpSV)
1247  // since cusparseSpSV_solve() does not support in-place computation
1248  Impl::resetMultiVecIfNeeded(Y_tmp_, Y.getMap(), Y.getNumVectors(), false);
1249 
1250  // Start by solving L Y_tmp = X for Y_tmp.
1251  L_solver_->apply(X, *Y_tmp_, mode);
1252 
1253  if (!this->isKokkosKernelsSpiluk_) {
1254  // Solve D Y = Y. The operation lets us do this in place in Y, so we can
1255  // write "solve D Y = Y for Y."
1256  Y_tmp_->elementWiseMultiply(one, *D_, *Y_tmp_, zero);
1257  }
1258 
1259  U_solver_->apply(*Y_tmp_, Y, mode); // Solve U Y = Y_tmp.
1260 #else
1261  // Start by solving L Y = X for Y.
1262  L_solver_->apply(X, Y, mode);
1263 
1264  if (!this->isKokkosKernelsSpiluk_) {
1265  // Solve D Y = Y. The operation lets us do this in place in Y, so we can
1266  // write "solve D Y = Y for Y."
1267  Y.elementWiseMultiply(one, *D_, Y, zero);
1268  }
1269 
1270  U_solver_->apply(Y, Y, mode); // Solve U Y = Y.
1271 #endif
1272  } else { // Solve U^P (D^P (L^P Y)) = X for Y (where P is * or T).
1273 #if defined(KOKKOSKERNELS_ENABLE_TPL_CUSPARSE) && defined(KOKKOS_ENABLE_CUDA) && (CUDA_VERSION >= 11030)
1274  // NOTE (Nov-15-2022):
1275  // This is a workaround for Cuda >= 11.3 (using cusparseSpSV)
1276  // since cusparseSpSV_solve() does not support in-place computation
1277  Impl::resetMultiVecIfNeeded(Y_tmp_, Y.getMap(), Y.getNumVectors(), false);
1278 
1279  // Start by solving U^P Y_tmp = X for Y_tmp.
1280  U_solver_->apply(X, *Y_tmp_, mode);
1281 
1282  if (!this->isKokkosKernelsSpiluk_) {
1283  // Solve D^P Y = Y.
1284  //
1285  // FIXME (mfh 24 Jan 2014) If mode = Teuchos::CONJ_TRANS, we
1286  // need to do an elementwise multiply with the conjugate of
1287  // D_, not just with D_ itself.
1288  Y_tmp_->elementWiseMultiply(one, *D_, *Y_tmp_, zero);
1289  }
1290 
1291  L_solver_->apply(*Y_tmp_, Y, mode); // Solve L^P Y = Y_tmp.
1292 #else
1293  // Start by solving U^P Y = X for Y.
1294  U_solver_->apply(X, Y, mode);
1295 
1296  if (!this->isKokkosKernelsSpiluk_) {
1297  // Solve D^P Y = Y.
1298  //
1299  // FIXME (mfh 24 Jan 2014) If mode = Teuchos::CONJ_TRANS, we
1300  // need to do an elementwise multiply with the conjugate of
1301  // D_, not just with D_ itself.
1302  Y.elementWiseMultiply(one, *D_, Y, zero);
1303  }
1304 
1305  L_solver_->apply(Y, Y, mode); // Solve L^P Y = Y.
1306 #endif
1307  }
1308  }
1309  } else { // alpha != 1 or beta != 0
1310  if (alpha == zero) {
1311  // The special case for beta == 0 ensures that if Y contains Inf
1312  // or NaN values, we replace them with 0 (following BLAS
1313  // convention), rather than multiplying them by 0 to get NaN.
1314  if (beta == zero) {
1315  Y.putScalar(zero);
1316  } else {
1317  Y.scale(beta);
1318  }
1319  } else { // alpha != zero
1320  Impl::resetMultiVecIfNeeded(Y_tmp_, Y.getMap(), Y.getNumVectors(), false);
1321  apply(X, *Y_tmp_, mode);
1322  Y.update(alpha, *Y_tmp_, beta);
1323  }
1324  }
1325  } // end timing
1326 
1327 #ifdef HAVE_IFPACK2_DEBUG
1328  {
1329  Teuchos::Array<magnitude_type> norms(Y.getNumVectors());
1330  Y.norm1(norms());
1331  bool good = true;
1332  for (size_t j = 0; j < Y.getNumVectors(); ++j) {
1333  if (STM::isnaninf(norms[j])) {
1334  good = false;
1335  break;
1336  }
1337  }
1338  TEUCHOS_TEST_FOR_EXCEPTION(!good, std::runtime_error, "Ifpack2::RILUK::apply: The 1-norm of the output Y is NaN or Inf.");
1339  }
1340 #endif // HAVE_IFPACK2_DEBUG
1341 
1342  ++numApply_;
1343  applyTime_ += (timer.wallTime() - startTime);
1344 }
1345 
1346 // VINH comment out since multiply() is not needed anywhere
1347 // template<class MatrixType>
1348 // void RILUK<MatrixType>::
1349 // multiply (const Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& X,
1350 // Tpetra::MultiVector<scalar_type,local_ordinal_type,global_ordinal_type,node_type>& Y,
1351 // const Teuchos::ETransp mode) const
1352 //{
1353 // const scalar_type zero = STS::zero ();
1354 // const scalar_type one = STS::one ();
1355 //
1356 // if (mode != Teuchos::NO_TRANS) {
1357 // U_->apply (X, Y, mode); //
1358 // Y.update (one, X, one); // Y = Y + X (account for implicit unit diagonal)
1359 //
1360 // // FIXME (mfh 24 Jan 2014) If mode = Teuchos::CONJ_TRANS, we need
1361 // // to do an elementwise multiply with the conjugate of D_, not
1362 // // just with D_ itself.
1363 // Y.elementWiseMultiply (one, *D_, Y, zero); // y = D*y (D_ has inverse of diagonal)
1364 //
1365 // MV Y_tmp (Y, Teuchos::Copy); // Need a temp copy of Y
1366 // L_->apply (Y_tmp, Y, mode);
1367 // Y.update (one, Y_tmp, one); // (account for implicit unit diagonal)
1368 // }
1369 // else {
1370 // L_->apply (X, Y, mode);
1371 // Y.update (one, X, one); // Y = Y + X (account for implicit unit diagonal)
1372 // Y.elementWiseMultiply (one, *D_, Y, zero); // y = D*y (D_ has inverse of diagonal)
1373 // MV Y_tmp (Y, Teuchos::Copy); // Need a temp copy of Y1
1374 // U_->apply (Y_tmp, Y, mode);
1375 // Y.update (one, Y_tmp, one); // (account for implicit unit diagonal)
1376 // }
1377 // }
1378 
1379 template <class MatrixType>
1380 std::string RILUK<MatrixType>::description() const {
1381  std::ostringstream os;
1382 
1383  // Output is a valid YAML dictionary in flow style. If you don't
1384  // like everything on a single line, you should call describe()
1385  // instead.
1386  os << "\"Ifpack2::RILUK\": {";
1387  os << "Initialized: " << (isInitialized() ? "true" : "false") << ", "
1388  << "Computed: " << (isComputed() ? "true" : "false") << ", ";
1389 
1390  os << "Level-of-fill: " << getLevelOfFill() << ", ";
1391 
1392  if (isKokkosKernelsSpiluk_) os << "KK-SPILUK, ";
1393  if (isKokkosKernelsStream_) os << "KK-Stream, ";
1394 
1395  if (A_.is_null()) {
1396  os << "Matrix: null";
1397  } else {
1398  os << "Global matrix dimensions: ["
1399  << A_->getGlobalNumRows() << ", " << A_->getGlobalNumCols() << "]"
1400  << ", Global nnz: " << A_->getGlobalNumEntries();
1401  }
1402 
1403  if (!L_solver_.is_null()) os << ", " << L_solver_->description();
1404  if (!U_solver_.is_null()) os << ", " << U_solver_->description();
1405 
1406  os << "}";
1407  return os.str();
1408 }
1409 
1410 } // namespace Ifpack2
1411 
1412 #define IFPACK2_RILUK_INSTANT(S, LO, GO, N) \
1413  template class Ifpack2::RILUK<Tpetra::RowMatrix<S, LO, GO, N> >;
1414 
1415 #endif
Teuchos::RCP< const Tpetra::Map< local_ordinal_type, global_ordinal_type, node_type > > getRangeMap() const
Returns the Tpetra::Map object associated with the range of this operator.
Definition: Ifpack2_RILUK_def.hpp:228
node_type::execution_space execution_space
The Kokkos execution space of the input MatrixType.
Definition: Ifpack2_RILUK_decl.hpp:241
static Teuchos::RCP< const row_matrix_type > makeLocalFilter(const Teuchos::RCP< const row_matrix_type > &A)
Return A, wrapped in a LocalFilter, if necessary.
Definition: Ifpack2_RILUK_def.hpp:420
MatrixType::global_ordinal_type global_ordinal_type
The type of global indices in the input MatrixType.
Definition: Ifpack2_RILUK_decl.hpp:229
T & get(const std::string &name, T def_value)
bool nonnull(const std::shared_ptr< T > &p)
const Tpetra::Vector< scalar_type, local_ordinal_type, global_ordinal_type, node_type > & getD() const
Return the diagonal entries of the ILU factorization.
Definition: Ifpack2_RILUK_def.hpp:166
void initialize()
Initialize by computing the symbolic incomplete factorization.
Definition: Ifpack2_RILUK_def.hpp:450
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Tpetra::RowMatrix< scalar_type, local_ordinal_type, global_ordinal_type, node_type > row_matrix_type
Tpetra::RowMatrix specialization used by this class.
Definition: Ifpack2_RILUK_decl.hpp:248
size_type size() const
virtual void setMatrix(const Teuchos::RCP< const row_matrix_type > &A)
Change the matrix to be preconditioned.
Definition: Ifpack2_RILUK_def.hpp:117
std::string description() const
A one-line description of this object.
Definition: Ifpack2_RILUK_def.hpp:1380
void setParameters(const Teuchos::ParameterList &params)
Definition: Ifpack2_RILUK_def.hpp:290
ILU(k) factorization of a given Tpetra::RowMatrix.
Definition: Ifpack2_RILUK_decl.hpp:213
size_t getNodeSmootherComplexity() const
Get a rough estimate of cost per iteration.
Definition: Ifpack2_RILUK_def.hpp:191
Teuchos::RCP< const crs_matrix_type > getCrsMatrix() const
Return the input matrix A as a Tpetra::CrsMatrix, if possible; else throws.
Definition: Ifpack2_RILUK_def.hpp:414
Tpetra::CrsMatrix< scalar_type, local_ordinal_type, global_ordinal_type, node_type > crs_matrix_type
Tpetra::CrsMatrix specialization used by this class for representing L and U.
Definition: Ifpack2_RILUK_decl.hpp:250
const crs_matrix_type & getU() const
Return the U factor of the ILU factorization.
Definition: Ifpack2_RILUK_def.hpp:179
bool isParameter(const std::string &name) const
MatrixType::node_type node_type
The Node type used by the input MatrixType.
Definition: Ifpack2_RILUK_decl.hpp:232
T * getRawPtr() const
Teuchos::RCP< const Tpetra::Map< local_ordinal_type, global_ordinal_type, node_type > > getDomainMap() const
Returns the Tpetra::Map object associated with the domain of this operator.
Definition: Ifpack2_RILUK_def.hpp:208
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
MatrixType::local_ordinal_type local_ordinal_type
The type of local indices in the input MatrixType.
Definition: Ifpack2_RILUK_decl.hpp:226
virtual ~RILUK()
Destructor (declared virtual for memory safety).
Definition: Ifpack2_RILUK_def.hpp:94
&quot;Preconditioner&quot; that solves local sparse triangular systems.
Definition: Ifpack2_LocalSparseTriangularSolver_decl.hpp:46
void compute()
Compute the (numeric) incomplete factorization.
Definition: Ifpack2_RILUK_def.hpp:1054
void apply(const Tpetra::MultiVector< scalar_type, local_ordinal_type, global_ordinal_type, node_type > &X, Tpetra::MultiVector< scalar_type, local_ordinal_type, global_ordinal_type, node_type > &Y, Teuchos::ETransp mode=Teuchos::NO_TRANS, scalar_type alpha=Teuchos::ScalarTraits< scalar_type >::one(), scalar_type beta=Teuchos::ScalarTraits< scalar_type >::zero()) const
Apply the (inverse of the) incomplete factorization to X, resulting in Y.
Definition: Ifpack2_RILUK_def.hpp:1131
Teuchos::ScalarTraits< scalar_type >::magnitudeType magnitude_type
The type of the magnitude (absolute value) of a matrix entry.
Definition: Ifpack2_RILUK_decl.hpp:235
void resize(size_type new_size, const value_type &x=value_type())
Construct a level filled graph for use in computing an ILU(k) incomplete factorization.
Definition: Ifpack2_IlukGraph.hpp:67
IntegralType getIntegralValue(const std::string &str, const std::string &paramName="", const std::string &sublistName="") const
Teuchos::RCP< const row_matrix_type > getMatrix() const
Get the input matrix.
Definition: Ifpack2_RILUK_def.hpp:408
bool isType(const std::string &name) const
Declaration of MDF interface.
Access only local rows and columns of a sparse matrix.
Definition: Ifpack2_LocalFilter_decl.hpp:127
static double wallTime()
const crs_matrix_type & getL() const
Return the L factor of the ILU factorization.
Definition: Ifpack2_RILUK_def.hpp:150
std::string typeName(const T &t)
MatrixType::scalar_type scalar_type
The type of the entries of the input MatrixType.
Definition: Ifpack2_RILUK_decl.hpp:223
bool is_null() const