Debian Codegraph @

packages/belos/tpetra/src/BelosMultiVecTraits_Tpetra.hpp

raw
1 // @HEADER
2 // *****************************************************************************
3 // Belos: Block Linear Solvers Package
4 //
5 // Copyright 2004-2016 NTESS and the Belos contributors.
6 // SPDX-License-Identifier: BSD-3-Clause
7 // *****************************************************************************
8 // @HEADER
9
10 #ifndef BELOSMULTIVECTRAITS_TPETRA_HPP
11 #define BELOSMULTIVECTRAITS_TPETRA_HPP
12
13 /// \file BelosMultiVecTraits_Tpetra.hpp
14 /// \brief Partial specialization of Belos::MultiVecTraits for Tpetra objects.
15
16 #include "BelosMultiVecTraits.hpp"
17 #include "BelosTypes.hpp"
18 #include "Tpetra_Map.hpp"
19 #include "Tpetra_MultiVector.hpp"
20 #include "Tpetra_Details_Behavior.hpp"
21 #include "Tpetra_Details_StaticView.hpp"
22 #include "Teuchos_Array.hpp"
23 #include "Teuchos_ScalarTraits.hpp"
24 #include "Kokkos_ArithTraits.hpp"
25 #include <map>
26 #include <utility>
27 #include <vector>
28
29 #ifdef HAVE_BELOS_TSQR
30 # include "Tpetra_TsqrAdaptor.hpp"
31 #endif // HAVE_BELOS_TSQR
32
33 namespace impl {
34
35 // MapType: a Tpetra::Map specialization.
36 //
37 // inputMap: We use its communicator and index base.
38 template<class MapType>
39 Teuchos::RCP<const MapType>
40 makeLocalMap (const MapType& inputMap,
41 const typename MapType::local_ordinal_type lclNumRows)
42 {
43 Teuchos::RCP<MapType> map (new MapType (lclNumRows,
44 inputMap.getIndexBase (),
45 inputMap.getComm (),
46 Tpetra::LocallyReplicated));
47 return Teuchos::rcp_const_cast<const MapType> (map);
48 }
49
50 // Return a Tpetra::MultiVector with static storage and a local Map.
51 // "Static storage" means that you're only allowed to have one of
52 // these in operation at a time, since it stores its data in a static
53 // memory pool. "Local Map" means that the MultiVector is suitable
54 // for MultiVector::reduce, or for the result of MultiVector::multiply
55 // (e.g., for the X^T * Y or X*H * Y case, where X and Y have the same
56 // globally distributed Map).
57 //
58 // Contents of the returned Tpetra::MultiVector are undefined. If you
59 // want to set the entries to zero, you must do that yourself with
60 // MultiVector::putScalar.
61 //
62 // MultiVectorType: A Tpetra::MultiVector specialization.
63 //
64 // gblMv: We use its Map (though the returned MultiVector may have a
65 // different Map, since the returned MultiVector has a
66 // LocallyReplicated Map), and we also use it to deduce the return
67 // type.
68 template<class MultiVectorType>
69 MultiVectorType
70 makeStaticLocalMultiVector (const MultiVectorType& gblMv,
71 const size_t lclNumRows,
72 const size_t numCols)
73 {
74 using Tpetra::Details::getStatic2dDualView;
75 using IST = typename MultiVectorType::impl_scalar_type;
76 using DT = typename MultiVectorType::device_type;
77
78 auto lclMap = makeLocalMap (* (gblMv.getMap ()), lclNumRows);
79 auto dv = getStatic2dDualView<IST, DT> (lclNumRows, numCols);
80
81 if (::Tpetra::Details::Behavior::debug ()) {
82 // Filling with NaN is a cheap and effective way to tell if
83 // downstream code is trying to use a MultiVector's data without
84 // them having been initialized. ArithTraits lets us call nan()
85 // even if the scalar type doesn't define it; it just returns some
86 // undefined value in the latter case.
87 const IST nan = Kokkos::ArithTraits<IST>::nan ();
88 Kokkos::deep_copy (dv.view_device(), nan);
89 Kokkos::deep_copy (dv.view_host(), nan);
90 }
91 return MultiVectorType (lclMap, dv);
92 }
93
94 template<class Scalar, class LO, class GO, class Node>
95 class MultiVecPool
96 {
97 public:
98 MultiVecPool() {
99 Kokkos::push_finalize_hook([this]() { this->availableDVs.clear(); });
100 }
101
102 using MV = ::Tpetra::MultiVector<Scalar, LO, GO, Node>;
103
104 Teuchos::RCP<MV> getMV(const Teuchos::RCP<const ::Tpetra::Map<LO, GO, Node>> & map, const int numVecs) {
105 const auto num_local_elems = map->getLocalNumElements();
106 size_t total_size = num_local_elems * numVecs;
107
108 // Use lower_bound so that we can re-use a slightly larger allocation if it is available
109 auto available_it = availableDVs.lower_bound(total_size);
110 while(available_it != availableDVs.end() && available_it->second.empty()) {
111 ++available_it;
112 }
113 if(available_it != availableDVs.end()) {
114 auto & available = available_it->second;
115 auto full_size_dv = available.back();
116 available.pop_back();
117
118 typename dv_t::t_dev mv_dev(full_size_dv.view_device().data(), num_local_elems, numVecs);
119 typename dv_t::t_host mv_host(full_size_dv.view_host().data(), num_local_elems, numVecs);
120
121 return Teuchos::rcpWithDealloc(new MV(map, dv_t(mv_dev, mv_host)), RCPDeleter{available, full_size_dv});
122 }
123
124 // No sufficiently large allocations were found so we need to create a new one.
125 // Also remove the largest currently available allocation if there is one because it would be able
126 // to use the allocation we are adding instead.
127 auto available_rit = availableDVs.rbegin();
128 while(available_rit != availableDVs.rend() && available_rit->second.empty()) {
129 ++available_rit;
130 }
131 if(available_rit != availableDVs.rend()) {
132 available_rit->second.pop_back();
133 }
134 dv_t dv("Belos::MultiVecPool DV", num_local_elems, numVecs);
135 auto & available = availableDVs[total_size];
136 return Teuchos::rcpWithDealloc(new MV(map, dv), RCPDeleter{available, dv});
137 }
138
139 private:
140 using dv_t = typename MV::dual_view_type;
141 struct RCPDeleter
142 {
143 void free(MV * mv_ptr) {
144 if(mv_ptr) {
145 dv_pool.push_back(dv);
146 delete mv_ptr;
147 }
148 }
149 std::vector<dv_t> & dv_pool;
150 dv_t dv;
151 };
152 std::map<size_t, std::vector<dv_t>> availableDVs;
153 };
154
155
156 template<class Scalar, class LO, class GO, class Node>
157 inline MultiVecPool<Scalar, LO, GO, Node> & getPool()
158 {
159 static MultiVecPool<Scalar, LO, GO, Node> static_pool;
160 return static_pool;
161 }
162
163 template<class Scalar, class LO, class GO, class Node>
164 inline Teuchos::RCP<::Tpetra::MultiVector<Scalar, LO, GO, Node>> getMultiVectorFromPool(const Teuchos::RCP<const ::Tpetra::Map<LO, GO, Node>> & map, const int numVecs)
165 {
166 return getPool<Scalar, LO, GO, Node>().getMV(map, numVecs);
167 }
168
169 } // namespace impl
170
171 namespace Belos {
172
173 /// \brief Specialization of MultiVecTraits for MV = Tpetra::MultiVector.
174 ///
175 /// This interface lets Belos' solvers work directly with
176 /// Tpetra::MultiVector objects as the MultiVector type. That type
177 /// corresponds to the MV template parameter, which is the second
178 /// template parameter (after Scalar) of most Belos classes.
179 ///
180 /// The four template parameters of this partial specialization
181 /// correspond exactly to the four template parameters of
182 /// Tpetra::MultiVector. See the Tpetra::MultiVector documentation
183 /// for more information.
184 ///
185 /// \tparam Scalar Same as template parameter 1 of Tpetra::MultiVector.
186 /// \tparam LO Same as template parameter 2 of Tpetra::MultiVector.
187 /// \tparam GO Same as template parameter 3 of Tpetra::MultiVector.
188 /// \tparam Node Same as template parameter 4 of Tpetra::MultiVector.
189 template<class Scalar, class LO, class GO, class Node>
190 class MultiVecTraits<Scalar, ::Tpetra::MultiVector<Scalar,LO,GO,Node> > {
191 typedef ::Tpetra::MultiVector<Scalar, LO, GO, Node> MV;
192 public:
193 /// \brief Create a new MultiVector with \c numVecs columns.
194 ///
195 /// The returned Tpetra::MultiVector has the same Tpetra::Map
196 /// (distribution over one or more parallel processes) as \c X.
197 /// Its entries are not initialized and have undefined values.
198 static Teuchos::RCP<MV> Clone (const MV& X, const int numVecs) {
199 auto Y = impl::getMultiVectorFromPool<Scalar>(X.getMap(), numVecs);
200 Y->setCopyOrView (Teuchos::View);
201 return Y;
202 }
203
204 //! Create and return a deep copy of X.
205 static Teuchos::RCP<MV> CloneCopy (const MV& X)
206 {
207 // Make a deep copy of X. The one-argument copy constructor
208 // does a shallow copy by default; the second argument tells it
209 // to do a deep copy.
210 auto X_copy = impl::getMultiVectorFromPool<Scalar>(X.getMap(), X.getNumVectors());
211 Tpetra::deep_copy(*X_copy, X);
212 // Make Tpetra::MultiVector use the new view semantics. This is
213 // a no-op for the Kokkos refactor version of Tpetra; it only
214 // does something for the "classic" version of Tpetra. This
215 // shouldn't matter because Belos only handles MV through RCP
216 // and through this interface anyway, but it doesn't hurt to set
217 // it and make sure that it works.
218 X_copy->setCopyOrView (Teuchos::View);
219 return X_copy;
220 }
221
222 /// \brief Create and return a deep copy of the given columns of mv.
223 ///
224 /// \pre \code mv.getNumVectors() != 0 || index.size() == 0 \endcode
225 /// \pre For all k such that <tt>0 <= k < index.size()</tt>,
226 /// \code
227 /// 0 <= index[k] < mv.getNumVectors();
228 /// \endcode
229 /// \post If this method returns Y:
230 /// \code
231 /// Y->isConstantStride() && Y->getNumVectors() == index.size();
232 /// \endcode
233 static Teuchos::RCP<MV>
234 CloneCopy (const MV& mv, const std::vector<int>& index)
235 {
236 #ifdef HAVE_TPETRA_DEBUG
237 const char fnName[] = "Belos::MultiVecTraits::CloneCopy(mv,index)";
238 const size_t inNumVecs = mv.getNumVectors ();
239 TEUCHOS_TEST_FOR_EXCEPTION(
240 index.size () > 0 && *std::min_element (index.begin (), index.end ()) < 0,
241 std::runtime_error, fnName << ": All indices must be nonnegative.");
242 TEUCHOS_TEST_FOR_EXCEPTION(
243 index.size () > 0 &&
244 static_cast<size_t> (*std::max_element (index.begin (), index.end ())) >= inNumVecs,
245 std::runtime_error,
246 fnName << ": All indices must be strictly less than the number of "
247 "columns " << inNumVecs << " of the input multivector mv.");
248 #endif // HAVE_TPETRA_DEBUG
249
250 // Tpetra wants an array of size_t, not of int.
251 Teuchos::Array<size_t> columns (index.size ());
252 for (std::vector<int>::size_type j = 0; j < index.size (); ++j) {
253 columns[j] = index[j];
254 }
255 // mfh 14 Aug 2014: Tpetra already detects and optimizes for a
256 // continuous column index range in MultiVector::subCopy, so we
257 // don't have to check here.
258 auto X_copy = impl::getMultiVectorFromPool<Scalar>(mv.getMap(), index.size());
259 X_copy->setCopyOrView (Teuchos::View);
260 X_copy->assign(*mv.subView(columns()));
261 return X_copy;
262 }
263
264 /// \brief Create and return a deep copy of the given columns of mv.
265 ///
266 /// \post If this method returns Y:
267 /// \code
268 /// Y->isConstantStride() && Y->getNumVectors() == index.size();
269 /// \endcode
270 static Teuchos::RCP<MV>
271 CloneCopy (const MV& mv, const Teuchos::Range1D& index)
272 {
273 const bool validRange = index.size() > 0 &&
274 index.lbound() >= 0 &&
275 index.ubound() < GetNumberVecs(mv);
276 if (! validRange) { // invalid range; generate error message
277 std::ostringstream os;
278 os << "Belos::MultiVecTraits::CloneCopy(mv,index=["
279 << index.lbound() << "," << index.ubound() << "]): ";
280 TEUCHOS_TEST_FOR_EXCEPTION(
281 index.size() == 0, std::invalid_argument,
282 os.str() << "Empty index range is not allowed.");
283 TEUCHOS_TEST_FOR_EXCEPTION(
284 index.lbound() < 0, std::invalid_argument,
285 os.str() << "Index range includes negative index/ices, which is not "
286 "allowed.");
287 TEUCHOS_TEST_FOR_EXCEPTION(
288 index.ubound() >= GetNumberVecs(mv), std::invalid_argument,
289 os.str() << "Index range exceeds number of vectors "
290 << mv.getNumVectors() << " in the input multivector.");
291 TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error,
292 os.str() << "Should never get here!");
293 }
294 auto X_copy = impl::getMultiVectorFromPool<Scalar>(mv.getMap(), index.size());
295 X_copy->setCopyOrView (Teuchos::View);
296 X_copy->assign(*mv.subView(index));
297 return X_copy;
298 }
299
300 static Teuchos::RCP<MV>
301 CloneViewNonConst (MV& mv, const std::vector<int>& index)
302 {
303 #ifdef HAVE_TPETRA_DEBUG
304 const char fnName[] = "Belos::MultiVecTraits::CloneViewNonConst(mv,index)";
305 const size_t numVecs = mv.getNumVectors ();
306 TEUCHOS_TEST_FOR_EXCEPTION(
307 index.size () > 0 && *std::min_element (index.begin (), index.end ()) < 0,
308 std::invalid_argument,
309 fnName << ": All indices must be nonnegative.");
310 TEUCHOS_TEST_FOR_EXCEPTION(
311 index.size () > 0 &&
312 static_cast<size_t> (*std::max_element (index.begin (), index.end ())) >= numVecs,
313 std::invalid_argument,
314 fnName << ": All indices must be strictly less than the number of "
315 "columns " << numVecs << " in the input MultiVector mv.");
316 #endif // HAVE_TPETRA_DEBUG
317
318 // Tpetra wants an array of size_t, not of int.
319 Teuchos::Array<size_t> columns (index.size ());
320 for (std::vector<int>::size_type j = 0; j < index.size (); ++j) {
321 columns[j] = index[j];
322 }
323 // mfh 14 Aug 2014: Tpetra already detects and optimizes for a
324 // continuous column index range in
325 // MultiVector::subViewNonConst, so we don't have to check here.
326 Teuchos::RCP<MV> X_view = mv.subViewNonConst (columns ());
327 X_view->setCopyOrView (Teuchos::View);
328 return X_view;
329 }
330
331 static Teuchos::RCP<MV>
332 CloneViewNonConst (MV& mv, const Teuchos::Range1D& index)
333 {
334 // NOTE (mfh 11 Jan 2011) We really should check for possible
335 // overflow of int here. However, the number of columns in a
336 // multivector typically fits in an int.
337 const int numCols = static_cast<int> (mv.getNumVectors());
338 const bool validRange = index.size() > 0 &&
339 index.lbound() >= 0 && index.ubound() < numCols;
340 if (! validRange) {
341 std::ostringstream os;
342 os << "Belos::MultiVecTraits::CloneViewNonConst(mv,index=["
343 << index.lbound() << ", " << index.ubound() << "]): ";
344 TEUCHOS_TEST_FOR_EXCEPTION(
345 index.size() == 0, std::invalid_argument,
346 os.str() << "Empty index range is not allowed.");
347 TEUCHOS_TEST_FOR_EXCEPTION(
348 index.lbound() < 0, std::invalid_argument,
349 os.str() << "Index range includes negative inde{x,ices}, which is "
350 "not allowed.");
351 TEUCHOS_TEST_FOR_EXCEPTION(
352 index.ubound() >= numCols, std::invalid_argument,
353 os.str() << "Index range exceeds number of vectors " << numCols
354 << " in the input multivector.");
355 TEUCHOS_TEST_FOR_EXCEPTION(
356 true, std::logic_error,
357 os.str() << "Should never get here!");
358 }
359 Teuchos::RCP<MV> X_view = mv.subViewNonConst (index);
360 X_view->setCopyOrView (Teuchos::View);
361 return X_view;
362 }
363
364 static Teuchos::RCP<const MV>
365 CloneView (const MV& mv, const std::vector<int>& index)
366 {
367 #ifdef HAVE_TPETRA_DEBUG
368 const char fnName[] = "Belos::MultiVecTraits<Scalar, "
369 "Tpetra::MultiVector<...> >::CloneView(mv,index)";
370 const size_t numVecs = mv.getNumVectors ();
371 TEUCHOS_TEST_FOR_EXCEPTION(
372 *std::min_element (index.begin (), index.end ()) < 0,
373 std::invalid_argument,
374 fnName << ": All indices must be nonnegative.");
375 TEUCHOS_TEST_FOR_EXCEPTION(
376 static_cast<size_t> (*std::max_element (index.begin (), index.end ())) >= numVecs,
377 std::invalid_argument,
378 fnName << ": All indices must be strictly less than the number of "
379 "columns " << numVecs << " in the input MultiVector mv.");
380 #endif // HAVE_TPETRA_DEBUG
381
382 // Tpetra wants an array of size_t, not of int.
383 Teuchos::Array<size_t> columns (index.size ());
384 for (std::vector<int>::size_type j = 0; j < index.size (); ++j) {
385 columns[j] = index[j];
386 }
387 // mfh 14 Aug 2014: Tpetra already detects and optimizes for a
388 // continuous column index range in MultiVector::subView, so we
389 // don't have to check here.
390 Teuchos::RCP<const MV> X_view = mv.subView (columns);
391 Teuchos::rcp_const_cast<MV> (X_view)->setCopyOrView (Teuchos::View);
392 return X_view;
393 }
394
395 static Teuchos::RCP<const MV>
396 CloneView (const MV& mv, const Teuchos::Range1D& index)
397 {
398 // NOTE (mfh 11 Jan 2011) We really should check for possible
399 // overflow of int here. However, the number of columns in a
400 // multivector typically fits in an int.
401 const int numCols = static_cast<int> (mv.getNumVectors());
402 const bool validRange = index.size() > 0 &&
403 index.lbound() >= 0 && index.ubound() < numCols;
404 if (! validRange) {
405 std::ostringstream os;
406 os << "Belos::MultiVecTraits::CloneView(mv, index=["
407 << index.lbound () << ", " << index.ubound() << "]): ";
408 TEUCHOS_TEST_FOR_EXCEPTION(index.size() == 0, std::invalid_argument,
409 os.str() << "Empty index range is not allowed.");
410 TEUCHOS_TEST_FOR_EXCEPTION(index.lbound() < 0, std::invalid_argument,
411 os.str() << "Index range includes negative index/ices, which is not "
412 "allowed.");
413 TEUCHOS_TEST_FOR_EXCEPTION(
414 index.ubound() >= numCols, std::invalid_argument,
415 os.str() << "Index range exceeds number of vectors " << numCols
416 << " in the input multivector.");
417 TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error,
418 os.str() << "Should never get here!");
419 }
420 Teuchos::RCP<const MV> X_view = mv.subView (index);
421 Teuchos::rcp_const_cast<MV> (X_view)->setCopyOrView (Teuchos::View);
422 return X_view;
423 }
424
425 static ptrdiff_t GetGlobalLength (const MV& mv) {
426 return static_cast<ptrdiff_t> (mv.getGlobalLength ());
427 }
428
429 static int GetNumberVecs (const MV& mv) {
430 return static_cast<int> (mv.getNumVectors ());
431 }
432
433 static bool HasConstantStride (const MV& mv) {
434 return mv.isConstantStride ();
435 }
436
437 static void
438 MvTimesMatAddMv (Scalar alpha,
439 const MV& A,
440 const Teuchos::SerialDenseMatrix<int, Scalar>& B,
441 Scalar beta,
442 MV& mv)
443 {
444 #ifdef HAVE_BELOS_TPETRA_TIMERS
445 const std::string timerName ("Belos::MVT::MvTimesMatAddMv");
446 auto timer = Teuchos::TimeMonitor::getNewCounter (timerName);
447 Teuchos::TimeMonitor timeMon (*timer);
448 #endif // HAVE_BELOS_TPETRA_TIMERS
449
450 const size_t B_numRows = static_cast<size_t> (B.numRows ());
451 const size_t B_numCols = static_cast<size_t> (B.numCols ());
452
453 // Check if B is 1-by-1, in which case we can just call update()
454 if (B_numRows == size_t (1) && B_numCols == size_t (1)) {
455 mv.update (alpha*B(0,0), A, beta);
456 }
457 else {
458 MV B_mv = impl::makeStaticLocalMultiVector (A, B_numRows, B_numCols);
459 Tpetra::deep_copy (B_mv, B);
460 mv.multiply (Teuchos::NO_TRANS, Teuchos::NO_TRANS,
461 alpha, A, B_mv, beta);
462 }
463 Kokkos::fence(); // Belos with Thyra's MvTimesMatAddMv allowed failures
464 // when fence was not applied after mv.multiply;
465 // adding the fence fixed the tests in Thyra.
466 // Out of an abundance of caution (and with blessing
467 // from @hkthorn), we add the fence here as well.
468 // #8821 KDD
469 }
470
471 /// \brief <tt>mv := alpha*A + beta*B</tt>
472 ///
473 /// The Tpetra specialization of this method ignores and
474 /// completely overwrites any NaN or Inf entries in A. Thus, it
475 /// does <i>not</i> mean the same thing as <tt>mv := 0*mv +
476 /// alpha*A + beta*B</tt> in IEEE 754 floating-point arithmetic.
477 /// (Remember that NaN*0 = NaN.)
478 static void
479 MvAddMv (Scalar alpha,
480 const MV& A,
481 Scalar beta,
482 const MV& B,
483 MV& mv)
484 {
485 mv.update (alpha, A, beta, B, Teuchos::ScalarTraits<Scalar>::zero ());
486 }
487
488 static void MvScale (MV& mv, Scalar alpha) {
489 mv.scale (alpha);
490 }
491
492 static void MvScale (MV& mv, const std::vector<Scalar>& alphas) {
493 mv.scale (alphas);
494 }
495
496 static void
497 MvTransMv (const Scalar alpha,
498 const MV& A,
499 const MV& B,
500 Teuchos::SerialDenseMatrix<int,Scalar>& C)
501 {
502 #ifdef HAVE_BELOS_TPETRA_TIMERS
503 const std::string timerName ("Belos::MVT::MvTransMv");
504 auto timer = Teuchos::TimeMonitor::getNewCounter (timerName);
505 Teuchos::TimeMonitor timeMon (*timer);
506 #endif // HAVE_BELOS_TPETRA_TIMERS
507
508 const Scalar ZERO = Teuchos::ScalarTraits<Scalar>::zero ();
509 const int numRowsC = C.numRows ();
510 const int numColsC = C.numCols ();
511
512 // If numRowsC == numColsC == 1, then we can call dot().
513 if (numRowsC == 1 && numColsC == 1) {
514 if (alpha == ZERO) {
515 // Short-circuit, as required by BLAS semantics.
516 C(0,0) = alpha;
517 return;
518 }
519 A.dot (B, Teuchos::ArrayView<Scalar> (C.values (), 1));
520 if (alpha != Teuchos::ScalarTraits<Scalar>::one ()) {
521 C(0,0) *= alpha;
522 }
523 return;
524 }
525
526 MV C_mv = impl::makeStaticLocalMultiVector (A, numRowsC, numColsC);
527 // Filling with zero should be unnecessary, in theory, but not
528 // in practice, alas (Issue_3235 test fails).
529 C_mv.putScalar (ZERO);
530 C_mv.multiply (Teuchos::CONJ_TRANS, Teuchos::NO_TRANS, alpha, A, B, ZERO);
531 Tpetra::deep_copy (C, C_mv);
532 }
533
534 //! For all columns j of A, set <tt>dots[j] := A[j]^T * B[j]</tt>.
535 static void
536 MvDot (const MV& A, const MV& B, std::vector<Scalar> &dots)
537 {
538 const size_t numVecs = A.getNumVectors ();
539 TEUCHOS_TEST_FOR_EXCEPTION(
540 numVecs != B.getNumVectors (), std::invalid_argument,
541 "Belos::MultiVecTraits::MvDot(A,B,dots): "
542 "A and B must have the same number of columns. "
543 "A has " << numVecs << " column(s), "
544 "but B has " << B.getNumVectors () << " column(s).");
545 #ifdef HAVE_TPETRA_DEBUG
546 TEUCHOS_TEST_FOR_EXCEPTION(
547 dots.size() < numVecs, std::invalid_argument,
548 "Belos::MultiVecTraits::MvDot(A,B,dots): "
549 "The output array 'dots' must have room for all dot products. "
550 "A and B each have " << numVecs << " column(s), "
551 "but 'dots' only has " << dots.size() << " entry(/ies).");
552 #endif // HAVE_TPETRA_DEBUG
553
554 Teuchos::ArrayView<Scalar> av (dots);
555 A.dot (B, av (0, numVecs));
556 }
557
558 //! For all columns j of mv, set <tt>normvec[j] = norm(mv[j])</tt>.
559 static void
560 MvNorm (const MV& mv,
561 std::vector<typename Teuchos::ScalarTraits<Scalar>::magnitudeType>& normvec,
562 NormType type=TwoNorm)
563 {
564 typedef typename Teuchos::ScalarTraits<Scalar>::magnitudeType magnitude_type;
565 #ifdef HAVE_TPETRA_DEBUG
566 TEUCHOS_TEST_FOR_EXCEPTION(
567 normvec.size () < static_cast<std::vector<int>::size_type> (mv.getNumVectors ()),
568 std::invalid_argument,
569 "Belos::MultiVecTraits::MvNorm(mv,normvec): The normvec output "
570 "argument must have at least as many entries as the number of vectors "
571 "(columns) in the MultiVector mv. normvec.size() = " << normvec.size ()
572 << " < mv.getNumVectors() = " << mv.getNumVectors () << ".");
573 #endif // HAVE_TPETRA_DEBUG
574 Teuchos::ArrayView<magnitude_type> av (normvec);
575 switch (type) {
576 case OneNorm:
577 mv.norm1 (av (0, mv.getNumVectors ()));
578 break;
579 case TwoNorm:
580 mv.norm2 (av (0, mv.getNumVectors ()));
581 break;
582 case InfNorm:
583 mv.normInf (av (0,mv.getNumVectors ()));
584 break;
585 default:
586 // Throw logic_error rather than invalid_argument, because if
587 // we get here, it's probably the fault of a Belos solver,
588 // rather than a user giving Belos an invalid input.
589 TEUCHOS_TEST_FOR_EXCEPTION(
590 true, std::logic_error,
591 "Belos::MultiVecTraits::MvNorm: Invalid NormType value " << type
592 << ". Valid values are OneNorm=" << OneNorm << ", TwoNorm="
593 << TwoNorm <<", and InfNorm=" << InfNorm << ". If you are a Belos "
594 "user and have not modified Belos in any way, and you get this "
595 "message, then this is probably a bug in the Belos solver you were "
596 "using. Please report this to the Belos developers.");
597 }
598 }
599
600 static void
601 SetBlock (const MV& A, const std::vector<int>& index, MV& mv)
602 {
603 using Teuchos::Range1D;
604 using Teuchos::RCP;
605 const size_t inNumVecs = A.getNumVectors ();
606 #ifdef HAVE_TPETRA_DEBUG
607 TEUCHOS_TEST_FOR_EXCEPTION(
608 inNumVecs < static_cast<size_t> (index.size ()), std::invalid_argument,
609 "Belos::MultiVecTraits::SetBlock(A,index,mv): 'index' argument must "
610 "have no more entries as the number of columns in the input MultiVector"
611 " A. A.getNumVectors() = " << inNumVecs << " < index.size () = "
612 << index.size () << ".");
613 #endif // HAVE_TPETRA_DEBUG
614 RCP<MV> mvsub = CloneViewNonConst (mv, index);
615 if (inNumVecs > static_cast<size_t> (index.size ())) {
616 RCP<const MV> Asub = A.subView (Range1D (0, index.size () - 1));
617 ::Tpetra::deep_copy (*mvsub, *Asub);
618 } else {
619 ::Tpetra::deep_copy (*mvsub, A);
620 }
621 }
622
623 static void
624 SetBlock (const MV& A, const Teuchos::Range1D& index, MV& mv)
625 {
626 // Range1D bounds are signed; size_t is unsigned.
627 // Assignment of Tpetra::MultiVector is a deep copy.
628
629 // Tpetra::MultiVector::getNumVectors() returns size_t. It's
630 // fair to assume that the number of vectors won't overflow int,
631 // since the typical use case of multivectors involves few
632 // columns, but it's friendly to check just in case.
633 const size_t maxInt =
634 static_cast<size_t> (Teuchos::OrdinalTraits<int>::max ());
635 const bool overflow =
636 maxInt < A.getNumVectors () && maxInt < mv.getNumVectors ();
637 if (overflow) {
638 std::ostringstream os;
639 os << "Belos::MultiVecTraits::SetBlock(A, index=[" << index.lbound ()
640 << ", " << index.ubound () << "], mv): ";
641 TEUCHOS_TEST_FOR_EXCEPTION(
642 maxInt < A.getNumVectors (), std::range_error, os.str () << "Number "
643 "of columns (size_t) in the input MultiVector 'A' overflows int.");
644 TEUCHOS_TEST_FOR_EXCEPTION(
645 maxInt < mv.getNumVectors (), std::range_error, os.str () << "Number "
646 "of columns (size_t) in the output MultiVector 'mv' overflows int.");
647 }
648 // We've already validated the static casts above.
649 const int numColsA = static_cast<int> (A.getNumVectors ());
650 const int numColsMv = static_cast<int> (mv.getNumVectors ());
651 // 'index' indexes into mv; it's the index set of the target.
652 const bool validIndex =
653 index.lbound () >= 0 && index.ubound () < numColsMv;
654 // We can't take more columns out of A than A has.
655 const bool validSource = index.size () <= numColsA;
656
657 if (! validIndex || ! validSource) {
658 std::ostringstream os;
659 os << "Belos::MultiVecTraits::SetBlock(A, index=[" << index.lbound ()
660 << ", " << index.ubound () << "], mv): ";
661 TEUCHOS_TEST_FOR_EXCEPTION(
662 index.lbound() < 0, std::invalid_argument,
663 os.str() << "Range lower bound must be nonnegative.");
664 TEUCHOS_TEST_FOR_EXCEPTION(
665 index.ubound() >= numColsMv, std::invalid_argument,
666 os.str() << "Range upper bound must be less than the number of "
667 "columns " << numColsA << " in the 'mv' output argument.");
668 TEUCHOS_TEST_FOR_EXCEPTION(
669 index.size() > numColsA, std::invalid_argument,
670 os.str() << "Range must have no more elements than the number of "
671 "columns " << numColsA << " in the 'A' input argument.");
672 TEUCHOS_TEST_FOR_EXCEPTION(
673 true, std::logic_error, "Should never get here!");
674 }
675
676 // View of the relevant column(s) of the target multivector mv.
677 // We avoid view creation overhead by only creating a view if
678 // the index range is different than [0, (# columns in mv) - 1].
679 Teuchos::RCP<MV> mv_view;
680 if (index.lbound () == 0 && index.ubound () + 1 == numColsMv) {
681 mv_view = Teuchos::rcpFromRef (mv); // Non-const, non-owning RCP
682 } else {
683 mv_view = CloneViewNonConst (mv, index);
684 }
685
686 // View of the relevant column(s) of the source multivector A.
687 // If A has fewer columns than mv_view, then create a view of
688 // the first index.size() columns of A.
689 Teuchos::RCP<const MV> A_view;
690 if (index.size () == numColsA) {
691 A_view = Teuchos::rcpFromRef (A); // Const, non-owning RCP
692 } else {
693 A_view = CloneView (A, Teuchos::Range1D (0, index.size () - 1));
694 }
695
696 ::Tpetra::deep_copy (*mv_view, *A_view);
697 }
698
699 static void Assign (const MV& A, MV& mv)
700 {
701 const char errPrefix[] = "Belos::MultiVecTraits::Assign(A, mv): ";
702
703 // Range1D bounds are signed; size_t is unsigned.
704 // Assignment of Tpetra::MultiVector is a deep copy.
705
706 // Tpetra::MultiVector::getNumVectors() returns size_t. It's
707 // fair to assume that the number of vectors won't overflow int,
708 // since the typical use case of multivectors involves few
709 // columns, but it's friendly to check just in case.
710 const size_t maxInt =
711 static_cast<size_t> (Teuchos::OrdinalTraits<int>::max ());
712 const bool overflow =
713 maxInt < A.getNumVectors () && maxInt < mv.getNumVectors ();
714 if (overflow) {
715 TEUCHOS_TEST_FOR_EXCEPTION(
716 maxInt < A.getNumVectors(), std::range_error,
717 errPrefix << "Number of columns in the input multivector 'A' "
718 "(a size_t) overflows int.");
719 TEUCHOS_TEST_FOR_EXCEPTION(
720 maxInt < mv.getNumVectors(), std::range_error,
721 errPrefix << "Number of columns in the output multivector 'mv' "
722 "(a size_t) overflows int.");
723 TEUCHOS_TEST_FOR_EXCEPTION(
724 true, std::logic_error, "Should never get here!");
725 }
726 // We've already validated the static casts above.
727 const int numColsA = static_cast<int> (A.getNumVectors ());
728 const int numColsMv = static_cast<int> (mv.getNumVectors ());
729 if (numColsA > numColsMv) {
730 TEUCHOS_TEST_FOR_EXCEPTION(
731 numColsA > numColsMv, std::invalid_argument,
732 errPrefix << "Input multivector 'A' has " << numColsA << " columns, "
733 "but output multivector 'mv' has only " << numColsMv << " columns.");
734 TEUCHOS_TEST_FOR_EXCEPTION(true, std::logic_error, "Should never get here!");
735 }
736 if (numColsA == numColsMv) {
737 ::Tpetra::deep_copy (mv, A);
738 } else {
739 Teuchos::RCP<MV> mv_view =
740 CloneViewNonConst (mv, Teuchos::Range1D (0, numColsA - 1));
741 ::Tpetra::deep_copy (*mv_view, A);
742 }
743 }
744
745 static void MvRandom (MV& mv) {
746 mv.randomize ();
747 }
748
749 static void
750 MvInit (MV& mv, const Scalar alpha = Teuchos::ScalarTraits<Scalar>::zero ())
751 {
752 mv.putScalar (alpha);
753 }
754
755 static void MvPrint (const MV& mv, std::ostream& os) {
756 Teuchos::FancyOStream fos (Teuchos::rcpFromRef (os));
757 mv.describe (fos, Teuchos::VERB_EXTREME);
758 }
759
760 #ifdef HAVE_BELOS_TSQR
761 /// \typedef tsqr_adaptor_type
762 /// \brief TsqrAdaptor specialization for Tpetra::MultiVector
763 typedef ::Tpetra::TsqrAdaptor< ::Tpetra::MultiVector<Scalar, LO, GO, Node> > tsqr_adaptor_type;
764 #endif // HAVE_BELOS_TSQR
765 };
766
767 } // namespace Belos
768
769 #endif // BELOSMULTIVECTRAITS_TPETRA_HPP