Tpetra parallel linear algebra Version of the Day
Loading...
Searching...
No Matches
Tpetra_Import_Util2.hpp
Go to the documentation of this file.
1// @HEADER
2// *****************************************************************************
3// Tpetra: Templated Linear Algebra Services Package
4//
5// Copyright 2008 NTESS and the Tpetra contributors.
6// SPDX-License-Identifier: BSD-3-Clause
7// *****************************************************************************
8// @HEADER
9
10#ifndef TPETRA_IMPORT_UTIL2_HPP
11#define TPETRA_IMPORT_UTIL2_HPP
12
17
18#include "Tpetra_ConfigDefs.hpp"
19#include "Tpetra_Import.hpp"
20#include "Tpetra_HashTable.hpp"
21#include "Tpetra_Map.hpp"
22#include "Tpetra_Util.hpp"
23#include "Tpetra_Distributor.hpp"
25#include "Tpetra_Vector.hpp"
26#include "Kokkos_DualView.hpp"
27#include "KokkosSparse_SortCrs.hpp"
28#include <Teuchos_Array.hpp>
31#include <Kokkos_Core.hpp>
32#include <Kokkos_UnorderedMap.hpp>
33#include <Kokkos_Sort.hpp>
34#include <utility>
35#include <set>
36
38
39namespace {
40
41struct LocalRemoteCount {
42 size_t numLocalColGIDs;
43 size_t numRemoteColGIDs;
44
45 KOKKOS_INLINE_FUNCTION
46 LocalRemoteCount()
47 : numLocalColGIDs(0)
48 , numRemoteColGIDs(0) {}
49
50 KOKKOS_INLINE_FUNCTION
51 LocalRemoteCount& operator+=(const LocalRemoteCount& src) {
52 numLocalColGIDs += src.numLocalColGIDs;
53 numRemoteColGIDs += src.numRemoteColGIDs;
54 return *this;
55 }
56};
57
58} // namespace
59
60namespace Kokkos {
61
62template <>
63struct reduction_identity<LocalRemoteCount> {
64 KOKKOS_FORCEINLINE_FUNCTION static LocalRemoteCount sum() {
65 return LocalRemoteCount();
66 }
67};
68} // namespace Kokkos
69
70namespace Tpetra {
71namespace Import_Util {
72
75template <typename Scalar, typename Ordinal>
76void sortCrsEntries(const Teuchos::ArrayView<size_t>& CRS_rowptr,
77 const Teuchos::ArrayView<Ordinal>& CRS_colind,
78 const Teuchos::ArrayView<Scalar>& CRS_vals);
79
80template <typename Ordinal>
81void sortCrsEntries(const Teuchos::ArrayView<size_t>& CRS_rowptr,
82 const Teuchos::ArrayView<Ordinal>& CRS_colind);
83
84template <typename rowptr_array_type, typename colind_array_type, typename vals_array_type>
85void sortCrsEntries(const rowptr_array_type& CRS_rowptr,
86 const colind_array_type& CRS_colind,
87 const vals_array_type& CRS_vals);
88
89template <typename rowptr_array_type, typename colind_array_type>
90void sortCrsEntries(const rowptr_array_type& CRS_rowptr,
91 const colind_array_type& CRS_colind);
92
93template <typename local_crs_matrix>
94void sortCrsMatrix(local_crs_matrix& lclMatrix);
95
96template <typename local_crs_graph>
97void sortCrsGraph(local_crs_graph& lclGraph);
98
103template <typename Scalar, typename Ordinal>
104void sortAndMergeCrsEntries(const Teuchos::ArrayView<size_t>& CRS_rowptr,
105 const Teuchos::ArrayView<Ordinal>& CRS_colind,
106 const Teuchos::ArrayView<Scalar>& CRS_vals);
107
108template <typename Ordinal>
109void sortAndMergeCrsEntries(const Teuchos::ArrayView<size_t>& CRS_rowptr,
110 const Teuchos::ArrayView<Ordinal>& CRS_colind);
111
112template <class rowptr_view_type, class colind_view_type, class vals_view_type>
113void sortAndMergeCrsEntries(rowptr_view_type& CRS_rowptr,
114 colind_view_type& CRS_colind,
115 vals_view_type& CRS_vals,
116 const ::KokkosSparse::SortAlgorithm option);
117
133template <typename LocalOrdinal, typename GlobalOrdinal, typename Node>
135 const Teuchos::ArrayView<const size_t>& rowptr,
136 const Teuchos::ArrayView<LocalOrdinal>& colind_LID,
137 const Teuchos::ArrayView<GlobalOrdinal>& colind_GID,
138 const Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>>& domainMapRCP,
139 const Teuchos::ArrayView<const int>& owningPIDs,
140 Teuchos::Array<int>& remotePIDs,
141 Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>>& colMap,
142 const Teuchos::RCP<Teuchos::ParameterList>& params = Teuchos::null);
143
148template <typename LocalOrdinal, typename GlobalOrdinal, typename Node>
150 const Kokkos::View<const size_t*, typename Node::device_type> rowptr_view,
151 const Kokkos::View<LocalOrdinal*, typename Node::device_type> colind_LID_view,
152 const Kokkos::View<GlobalOrdinal*, typename Node::device_type> colind_GID_view,
153 const Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>>& domainMapRCP,
154 const Kokkos::View<const int*, typename Node::device_type> owningPIDs_view,
155 Teuchos::Array<int>& remotePIDs,
156 Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>>& colMap,
157 const Teuchos::RCP<Teuchos::ParameterList>& params = Teuchos::null);
158
172template <typename LocalOrdinal, typename GlobalOrdinal, typename Node>
173void getTwoTransferOwnershipVector(const ::Tpetra::Details::Transfer<LocalOrdinal, GlobalOrdinal, Node>& transferThatDefinesOwnership,
174 bool useReverseModeForOwnership,
175 const ::Tpetra::Details::Transfer<LocalOrdinal, GlobalOrdinal, Node>& transferForMigratingData,
176 bool useReverseModeForMigration,
177 Tpetra::Vector<int, LocalOrdinal, GlobalOrdinal, Node>& owningPIDs);
178
179} // namespace Import_Util
180} // namespace Tpetra
181
182//
183// Implementations
184//
185
186namespace Tpetra {
187namespace Import_Util {
188
189template <typename PID, typename GlobalOrdinal>
190bool sort_PID_then_GID(const std::pair<PID, GlobalOrdinal>& a,
191 const std::pair<PID, GlobalOrdinal>& b) {
192 if (a.first != b.first)
193 return (a.first < b.first);
194 return (a.second < b.second);
195}
196
197template <typename PID,
198 typename GlobalOrdinal,
199 typename LocalOrdinal>
200bool sort_PID_then_pair_GID_LID(const std::pair<PID, std::pair<GlobalOrdinal, LocalOrdinal>>& a,
201 const std::pair<PID, std::pair<GlobalOrdinal, LocalOrdinal>>& b) {
202 if (a.first != b.first)
203 return a.first < b.first;
204 else
205 return (a.second.first < b.second.first);
206}
207
208template <typename Scalar,
209 typename LocalOrdinal,
210 typename GlobalOrdinal,
211 typename Node>
212void reverseNeighborDiscovery(const CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>& SourceMatrix,
213 const typename CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>::row_ptrs_host_view_type& rowptr,
214 const typename CrsMatrix<Scalar, LocalOrdinal, GlobalOrdinal, Node>::local_inds_host_view_type& colind,
215 const Tpetra::Details::Transfer<LocalOrdinal, GlobalOrdinal, Node>& RowTransfer,
216 Teuchos::RCP<const Tpetra::Import<LocalOrdinal, GlobalOrdinal, Node>> MyImporter,
217 Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>> MyDomainMap,
218 Teuchos::ArrayRCP<int>& type3PIDs,
219 Teuchos::ArrayRCP<LocalOrdinal>& type3LIDs,
220 Teuchos::RCP<const Teuchos::Comm<int>>& rcomm) {
221#ifdef HAVE_TPETRACORE_MPI
222 using ::Tpetra::Details::Behavior;
223 typedef LocalOrdinal LO;
224 typedef GlobalOrdinal GO;
225 typedef std::pair<GO, GO> pidgidpair_t;
226 using Teuchos::RCP;
227 const std::string prefix{" Import_Util2::ReverseND:: "};
228 const std::string label("IU2::Neighbor");
229
230 // There can be no neighbor discovery if you don't have an importer
231 if (MyImporter.is_null()) return;
232
233 std::ostringstream errstr;
234 bool error = false;
235 auto const comm = MyDomainMap->getComm();
236
237 MPI_Comm rawComm = getRawMpiComm(*comm);
238 const int MyPID = rcomm->getRank();
239
240 // Things related to messages I am sending in forward mode (RowTransfer)
241 // *** Note: this will be incorrect for transferAndFillComplete if it is in reverse mode. FIXME cbl.
242 auto ExportPIDs = RowTransfer.getExportPIDs();
243 auto ExportLIDs = RowTransfer.getExportLIDs();
244 auto NumExportLIDs = RowTransfer.getNumExportIDs();
245
246 Distributor& Distor = MyImporter->getDistributor();
247 const size_t NumRecvs = Distor.getNumReceives();
248 const size_t NumSends = Distor.getNumSends();
249 auto RemoteLIDs = MyImporter->getRemoteLIDs();
250 auto const ProcsFrom = Distor.getProcsFrom();
251 auto const ProcsTo = Distor.getProcsTo();
252
253 auto LengthsFrom = Distor.getLengthsFrom();
254 auto MyColMap = SourceMatrix.getColMap();
255 const size_t numCols = MyColMap->getLocalNumElements();
256 RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>> target = MyImporter->getTargetMap();
257
258 // Get the owning pids in a special way,
259 // s.t. ProcsFrom[RemotePIDs[i]] is the proc that owns RemoteLIDs[j]....
260 Teuchos::Array<int> RemotePIDOrder(numCols, -1);
261
262 // For each remote ID, record index into ProcsFrom, who owns it.
263 for (size_t i = 0, j = 0; i < NumRecvs; ++i) {
264 for (size_t k = 0; k < LengthsFrom[i]; ++k) {
265 const int pid = ProcsFrom[i];
266 if (pid != MyPID) {
267 RemotePIDOrder[RemoteLIDs[j]] = i;
268 }
269 j++;
270 }
271 }
272
273 // Step One: Start tacking the (GID,PID) pairs on the std sets
274 //
275 // For each index in ProcsFrom, we will insert into a set of (PID,
276 // GID) pairs, in order to build a list of such pairs for each of
277 // those processes. Since this is building a reverse, we will send
278 // to these processes.
279 Teuchos::Array<int> ReverseSendSizes(NumRecvs, 0);
280 // do this as C array to avoid Teuchos::Array value initialization of all reserved memory
281 Teuchos::Array<Teuchos::ArrayRCP<pidgidpair_t>> RSB(NumRecvs);
282
283 {
284 Tpetra::Details::ProfilingRegion set_all("Import_Util2::ReverseND::isMMallSetRSB");
285
286 // 25 Jul 2018: CBL
287 // todo:std::unordered_set (hash table),
288 // with an adequate prereservation ("bucket count").
289 // An onordered_set has to have a custom hasher for pid/gid pair
290 // However, when pidsets is copied to RSB, it will be in key
291 // order _not_ in pid,gid order. (unlike std::set).
292 // Impliment this with a reserve, and time BOTH building pidsets
293 // _and_ the sort after the receive. Even if unordered_set saves
294 // time, if it causes the sort to be longer, it's not a win.
295
296 Teuchos::Array<std::set<pidgidpair_t>> pidsets(NumRecvs);
297 {
298 Tpetra::Details::ProfilingRegion set_insert("Import_Util2::ReverseND::isMMallSetRSBinsert");
299 for (size_t i = 0; i < NumExportLIDs; i++) {
300 LO lid = ExportLIDs[i];
301 GO exp_pid = ExportPIDs[i];
302 for (auto j = rowptr[lid]; j < rowptr[lid + 1]; j++) {
303 int pid_order = RemotePIDOrder[colind[j]];
304 if (pid_order != -1) {
305 GO gid = MyColMap->getGlobalElement(colind[j]); // Epetra SM.GCID46 =>sm->graph-> {colmap(colind)}
306 auto tpair = pidgidpair_t(exp_pid, gid);
307 pidsets[pid_order].insert(pidsets[pid_order].end(), tpair);
308 }
309 }
310 }
311 }
312
313 {
314 Tpetra::Details::ProfilingRegion set_cpy("Import_Util2::ReverseND::isMMallSetRSBcpy");
315 int jj = 0;
316 for (auto&& ps : pidsets) {
317 auto s = ps.size();
318 RSB[jj] = Teuchos::arcp(new pidgidpair_t[s], 0, s, true);
319 std::copy(ps.begin(), ps.end(), RSB[jj]);
320 ReverseSendSizes[jj] = s;
321 ++jj;
322 }
323 }
324 } // end of set based packing.
325
326 Teuchos::Array<int> ReverseRecvSizes(NumSends, -1);
327 Teuchos::Array<MPI_Request> rawBreq(ProcsFrom.size() + ProcsTo.size(), MPI_REQUEST_NULL);
328 // 25 Jul 2018: MPI_TAG_UB is the largest tag value; could be < 32768.
329 const int mpi_tag_base_ = 3;
330
331 int mpireq_idx = 0;
332 for (int i = 0; i < ProcsTo.size(); ++i) {
333 int Rec_Tag = mpi_tag_base_ + ProcsTo[i];
334 int* thisrecv = (int*)(&ReverseRecvSizes[i]);
335 MPI_Request rawRequest = MPI_REQUEST_NULL;
336 MPI_Irecv(const_cast<int*>(thisrecv),
337 1,
338 MPI_INT,
339 ProcsTo[i],
340 Rec_Tag,
341 rawComm,
342 &rawRequest);
343 rawBreq[mpireq_idx++] = rawRequest;
344 }
345 for (int i = 0; i < ProcsFrom.size(); ++i) {
346 int Send_Tag = mpi_tag_base_ + MyPID;
347 int* mysend = (int*)(&ReverseSendSizes[i]);
348 MPI_Request rawRequest = MPI_REQUEST_NULL;
349 MPI_Isend(mysend,
350 1,
351 MPI_INT,
352 ProcsFrom[i],
353 Send_Tag,
354 rawComm,
355 &rawRequest);
356 rawBreq[mpireq_idx++] = rawRequest;
357 }
358 Teuchos::Array<MPI_Status> rawBstatus(rawBreq.size());
359#ifdef HAVE_TPETRA_DEBUG
360 const int err1 =
361#endif
362 MPI_Waitall(rawBreq.size(), rawBreq.getRawPtr(),
363 rawBstatus.getRawPtr());
364
365#ifdef HAVE_TPETRA_DEBUG
366 if (err1) {
367 errstr << MyPID << "sE1 reverseNeighborDiscovery Mpi_Waitall error on send ";
368 error = true;
369 std::cerr << errstr.str() << std::flush;
370 }
371#endif
372
373 int totalexportpairrecsize = 0;
374 for (size_t i = 0; i < NumSends; ++i) {
375 totalexportpairrecsize += ReverseRecvSizes[i];
376#ifdef HAVE_TPETRA_DEBUG
377 if (ReverseRecvSizes[i] < 0) {
378 errstr << MyPID << "E4 reverseNeighborDiscovery: got < 0 for receive size " << ReverseRecvSizes[i] << std::endl;
379 error = true;
380 }
381#endif
382 }
383 Teuchos::ArrayRCP<pidgidpair_t> AllReverseRecv = Teuchos::arcp(new pidgidpair_t[totalexportpairrecsize], 0, totalexportpairrecsize, true);
384 int offset = 0;
385 mpireq_idx = 0;
386 for (int i = 0; i < ProcsTo.size(); ++i) {
387 MPI_Request rawRequest = MPI_REQUEST_NULL;
388 if (offset < AllReverseRecv.size() && (ReverseRecvSizes[i] > 0)) {
389 int recvData_MPI_Tag = mpi_tag_base_ * 2 + ProcsTo[i];
390 int recv_data_size = ReverseRecvSizes[i] * 2;
391 GO* rec_bptr = (GO*)(&AllReverseRecv[offset]);
392 offset += ReverseRecvSizes[i];
393 MPI_Irecv(rec_bptr,
394 recv_data_size,
395 ::Tpetra::Details::MpiTypeTraits<GO>::getType(rec_bptr[0]),
396 ProcsTo[i],
397 recvData_MPI_Tag,
398 rawComm,
399 &rawRequest);
400 }
401 rawBreq[mpireq_idx++] = rawRequest;
402 }
403 for (int ii = 0; ii < ProcsFrom.size(); ++ii) {
404 MPI_Request rawSequest = MPI_REQUEST_NULL;
405 if ((RSB[ii].size() > 0) && (ReverseSendSizes[ii] > 0)) {
406 int send_data_size = ReverseSendSizes[ii] * 2; // 2 == count of pair
407 GO* send_bptr = (GO*)(RSB[ii].getRawPtr());
408
409 int sendData_MPI_Tag = mpi_tag_base_ * 2 + MyPID;
410 MPI_Isend(send_bptr,
411 send_data_size,
412 ::Tpetra::Details::MpiTypeTraits<GO>::getType(send_bptr[0]),
413 ProcsFrom[ii],
414 sendData_MPI_Tag,
415 rawComm,
416 &rawSequest);
417 }
418 rawBreq[mpireq_idx++] = rawSequest;
419 }
420#ifdef HAVE_TPETRA_DEBUG
421 const int err =
422#endif
423 MPI_Waitall(rawBreq.size(),
424 rawBreq.getRawPtr(),
425 rawBstatus.getRawPtr());
426#ifdef HAVE_TPETRA_DEBUG
427 if (err) {
428 errstr << MyPID << "E3.r reverseNeighborDiscovery Mpi_Waitall error on receive ";
429 error = true;
430 std::cerr << errstr.str() << std::flush;
431 }
432#endif
433 std::sort(AllReverseRecv.begin(), AllReverseRecv.end(), Tpetra::Import_Util::sort_PID_then_GID<GlobalOrdinal, GlobalOrdinal>);
434
435 auto newEndOfPairs = std::unique(AllReverseRecv.begin(), AllReverseRecv.end());
436 // don't resize to remove non-unique, just use the end-of-unique iterator
437 if (AllReverseRecv.begin() == newEndOfPairs) return;
438 int ARRsize = std::distance(AllReverseRecv.begin(), newEndOfPairs);
439 auto rPIDs = Teuchos::arcp(new int[ARRsize], 0, ARRsize, true);
440 auto rLIDs = Teuchos::arcp(new LocalOrdinal[ARRsize], 0, ARRsize, true);
441
442 int tsize = 0;
443 for (auto itr = AllReverseRecv.begin(); itr != newEndOfPairs; ++itr) {
444 if ((int)(itr->first) != MyPID) {
445 rPIDs[tsize] = (int)itr->first;
446 LocalOrdinal lid = MyDomainMap->getLocalElement(itr->second);
447 rLIDs[tsize] = lid;
448 tsize++;
449 }
450 }
451
452 type3PIDs = rPIDs.persistingView(0, tsize);
453 type3LIDs = rLIDs.persistingView(0, tsize);
454
455 if (error) {
456 std::cerr << errstr.str() << std::flush;
457 comm->barrier();
458 comm->barrier();
459 comm->barrier();
460 MPI_Abort(MPI_COMM_WORLD, -1);
461 }
462#endif
463}
464
465// Note: This should get merged with the other Tpetra sort routines eventually.
466template <typename Scalar, typename Ordinal>
467void sortCrsEntries(const Teuchos::ArrayView<size_t>& CRS_rowptr,
468 const Teuchos::ArrayView<Ordinal>& CRS_colind,
469 const Teuchos::ArrayView<Scalar>& CRS_vals) {
470 auto rowptr_k = Kokkos::View<size_t*, Kokkos::HostSpace, Kokkos::MemoryUnmanaged>(CRS_rowptr.data(), CRS_rowptr.size());
471 auto colind_k = Kokkos::View<Ordinal*, Kokkos::HostSpace, Kokkos::MemoryUnmanaged>(CRS_colind.data(), CRS_colind.size());
472 auto vals_k = Kokkos::View<Scalar*, Kokkos::HostSpace, Kokkos::MemoryUnmanaged>(CRS_vals.data(), CRS_vals.size());
473 sortCrsEntries(rowptr_k, colind_k, vals_k);
474}
475
476template <typename Ordinal>
477void sortCrsEntries(const Teuchos::ArrayView<size_t>& CRS_rowptr,
478 const Teuchos::ArrayView<Ordinal>& CRS_colind) {
479 auto rowptr_k = Kokkos::View<size_t*, Kokkos::HostSpace, Kokkos::MemoryUnmanaged>(CRS_rowptr.data(), CRS_rowptr.size());
480 auto colind_k = Kokkos::View<Ordinal*, Kokkos::HostSpace, Kokkos::MemoryUnmanaged>(CRS_colind.data(), CRS_colind.size());
481 sortCrsEntries(rowptr_k, colind_k);
482}
483
484template <typename rowptr_array_type, typename colind_array_type, typename vals_array_type>
485void sortCrsEntries(const rowptr_array_type& CRS_rowptr,
486 const colind_array_type& CRS_colind,
487 const vals_array_type& CRS_vals) {
488 KokkosSparse::SortAlgorithm option = KokkosSparse::SortAlgorithm::DEFAULT;
489#if KOKKOSKERNELS_VERSION >= 50100
490 static constexpr bool is_cpu = std::is_same_v<typename rowptr_array_type::memory_space, Kokkos::HostSpace>;
491 if constexpr (is_cpu)
492 option = KokkosSparse::SortAlgorithm::SHELL;
493#endif
494 KokkosSparse::sort_crs_matrix(CRS_rowptr, CRS_colind, CRS_vals,
495 KokkosKernels::ArithTraits<typename colind_array_type::non_const_value_type>::max(),
496 option);
497}
498
499template <typename local_crs_matrix>
500void sortCrsMatrix(local_crs_matrix& lclMatrix) {
501 KokkosSparse::SortAlgorithm option = KokkosSparse::SortAlgorithm::DEFAULT;
502#if KOKKOSKERNELS_VERSION >= 50100
503 static constexpr bool is_cpu = std::is_same_v<typename local_crs_matrix::device_type::memory_space, Kokkos::HostSpace>;
504 if constexpr (is_cpu)
505 option = KokkosSparse::SortAlgorithm::SHELL;
506#endif
507 KokkosSparse::sort_crs_matrix(lclMatrix, option);
508}
509
510template <typename local_crs_graph>
511void sortCrsGraph(local_crs_graph& lclGraph) {
512 KokkosSparse::SortAlgorithm option = KokkosSparse::SortAlgorithm::DEFAULT;
513 KokkosSparse::sort_crs_graph(lclGraph, KokkosKernels::ArithTraits<typename local_crs_graph::entries_type::non_const_value_type>::max(), option);
514}
515
516template <typename rowptr_array_type, typename colind_array_type>
517void sortCrsEntries(const rowptr_array_type& CRS_rowptr,
518 const colind_array_type& CRS_colind) {
519 KokkosSparse::SortAlgorithm option = KokkosSparse::SortAlgorithm::DEFAULT;
520 KokkosSparse::sort_crs_graph(CRS_rowptr, CRS_colind,
521 KokkosKernels::ArithTraits<typename colind_array_type::non_const_value_type>::max(),
522 option);
523}
524
525// Note: This should get merged with the other Tpetra sort routines eventually.
526template <typename Scalar, typename Ordinal>
527void sortAndMergeCrsEntries(const Teuchos::ArrayView<size_t>& CRS_rowptr,
528 const Teuchos::ArrayView<Ordinal>& CRS_colind,
529 const Teuchos::ArrayView<Scalar>& CRS_vals) {
530 // For each row, sort column entries from smallest to largest,
531 // merging column ids that are identify by adding values. Use shell
532 // sort. Stable sort so it is fast if indices are already sorted.
533 // Code copied from Epetra_CrsMatrix::SortEntries()
534
535 if (CRS_rowptr.size() == 0) {
536 return; // no rows, so nothing to sort
537 }
538 const size_t NumRows = CRS_rowptr.size() - 1;
539 const size_t nnz = CRS_colind.size();
540 size_t new_curr = CRS_rowptr[0];
541 size_t old_curr = CRS_rowptr[0];
542
543 const bool permute_values_array = CRS_vals.size() > 0;
544
545 for (size_t i = 0; i < NumRows; i++) {
546 const size_t old_rowptr_i = CRS_rowptr[i];
547 CRS_rowptr[i] = old_curr;
548 if (old_rowptr_i >= nnz) continue;
549
550 size_t NumEntries = CRS_rowptr[i + 1] - old_rowptr_i;
551 Teuchos::ArrayRCP<Scalar> locValues;
552 if (permute_values_array)
553 locValues = Teuchos::arcp<Scalar>(&CRS_vals[old_rowptr_i], 0, NumEntries, false);
554 Teuchos::ArrayRCP<Ordinal> locIndices(&CRS_colind[old_rowptr_i], 0, NumEntries, false);
555
556 // Sort phase
557 Ordinal n = NumEntries;
558 Ordinal m = n / 2;
559
560 while (m > 0) {
561 Ordinal max = n - m;
562 for (Ordinal j = 0; j < max; j++) {
563 for (Ordinal k = j; k >= 0; k -= m) {
564 if (locIndices[k + m] >= locIndices[k])
565 break;
566 if (permute_values_array) {
567 Scalar dtemp = locValues[k + m];
568 locValues[k + m] = locValues[k];
569 locValues[k] = dtemp;
570 }
571 Ordinal itemp = locIndices[k + m];
572 locIndices[k + m] = locIndices[k];
573 locIndices[k] = itemp;
574 }
575 }
576 m = m / 2;
577 }
578
579 // Merge & shrink
580 for (size_t j = old_rowptr_i; j < CRS_rowptr[i + 1]; j++) {
581 if (j > old_rowptr_i && CRS_colind[j] == CRS_colind[new_curr - 1]) {
582 if (permute_values_array) CRS_vals[new_curr - 1] += CRS_vals[j];
583 } else if (new_curr == j) {
584 new_curr++;
585 } else {
586 CRS_colind[new_curr] = CRS_colind[j];
587 if (permute_values_array) CRS_vals[new_curr] = CRS_vals[j];
588 new_curr++;
589 }
590 }
591 old_curr = new_curr;
592 }
593
594 CRS_rowptr[NumRows] = new_curr;
595}
596
597template <typename Ordinal>
598void sortAndMergeCrsEntries(const Teuchos::ArrayView<size_t>& CRS_rowptr,
599 const Teuchos::ArrayView<Ordinal>& CRS_colind) {
600 Teuchos::ArrayView<Tpetra::Details::DefaultTypes::scalar_type> CRS_vals;
601 return sortAndMergeCrsEntries<Tpetra::Details::DefaultTypes::scalar_type, Ordinal>(CRS_rowptr, CRS_colind, CRS_vals);
602}
603
604template <class rowptr_view_type, class colind_view_type, class vals_view_type>
605void sortAndMergeCrsEntries(rowptr_view_type& CRS_rowptr,
606 colind_view_type& CRS_colind,
607 vals_view_type& CRS_vals,
608 const ::KokkosSparse::SortAlgorithm option) {
609 using execution_space = typename vals_view_type::execution_space;
610
611 auto CRS_rowptr_in = CRS_rowptr;
612 auto CRS_colind_in = CRS_colind;
613 auto CRS_vals_in = CRS_vals;
614
615 KokkosSparse::sort_and_merge_matrix<execution_space, rowptr_view_type,
616 colind_view_type, vals_view_type>(CRS_rowptr_in, CRS_colind_in, CRS_vals_in,
617 CRS_rowptr, CRS_colind, CRS_vals,
618 KokkosKernels::ArithTraits<typename colind_view_type::non_const_value_type>::max(),
619 option);
620}
621
622template <typename LocalOrdinal, typename GlobalOrdinal, typename Node>
623void lowCommunicationMakeColMapAndReindexSerial(const Teuchos::ArrayView<const size_t>& rowptr,
624 const Teuchos::ArrayView<LocalOrdinal>& colind_LID,
625 const Teuchos::ArrayView<GlobalOrdinal>& colind_GID,
626 const Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>>& domainMapRCP,
627 const Teuchos::ArrayView<const int>& owningPIDs,
628 Teuchos::Array<int>& remotePIDs,
629 Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>>& colMap,
630 const Teuchos::RCP<Teuchos::ParameterList>& params = Teuchos::null) {
631 using Teuchos::rcp;
632 typedef LocalOrdinal LO;
633 typedef GlobalOrdinal GO;
634 typedef Tpetra::global_size_t GST;
635 typedef Tpetra::Map<LO, GO, Node> map_type;
636 const char prefix[] = "lowCommunicationMakeColMapAndReindexSerial: ";
637
638 // The domainMap is an RCP because there is a shortcut for a
639 // (common) special case to return the columnMap = domainMap.
640 const map_type& domainMap = *domainMapRCP;
641
642 // Scan all column indices and sort into two groups:
643 // Local: those whose GID matches a GID of the domain map on this processor and
644 // Remote: All others.
645 const size_t numDomainElements = domainMap.getLocalNumElements();
646 Teuchos::Array<bool> LocalGIDs;
647 if (numDomainElements > 0) {
648 LocalGIDs.resize(numDomainElements, false); // Assume domain GIDs are not local
649 }
650
651 // In principle it is good to have RemoteGIDs and RemotGIDList be as
652 // long as the number of remote GIDs on this processor, but this
653 // would require two passes through the column IDs, so we make it
654 // the max of 100 and the number of block rows.
655 //
656 // FIXME (mfh 11 Feb 2015) Tpetra::Details::HashTable can hold at
657 // most INT_MAX entries, but it's possible to have more rows than
658 // that (if size_t is 64 bits and int is 32 bits).
659 const size_t numMyRows = rowptr.size() - 1;
660 const int hashsize = std::max(static_cast<int>(numMyRows), 100);
661
662 Tpetra::Details::HashTable<GO, LO> RemoteGIDs(hashsize);
663 Teuchos::Array<GO> RemoteGIDList;
664 RemoteGIDList.reserve(hashsize);
665 Teuchos::Array<int> PIDList;
666 PIDList.reserve(hashsize);
667
668 // Here we start using the *LocalOrdinal* colind_LID array. This is
669 // safe even if both columnIndices arrays are actually the same
670 // (because LocalOrdinal==GO). For *local* GID's set
671 // colind_LID with with their LID in the domainMap. For *remote*
672 // GIDs, we set colind_LID with (numDomainElements+NumRemoteColGIDs)
673 // before the increment of the remote count. These numberings will
674 // be separate because no local LID is greater than
675 // numDomainElements.
676
677 size_t NumLocalColGIDs = 0;
678 LO NumRemoteColGIDs = 0;
679 for (size_t i = 0; i < numMyRows; ++i) {
680 for (size_t j = rowptr[i]; j < rowptr[i + 1]; ++j) {
681 const GO GID = colind_GID[j];
682 // Check if GID matches a row GID
683 const LO LID = domainMap.getLocalElement(GID);
684 if (LID != -1) {
685 const bool alreadyFound = LocalGIDs[LID];
686 if (!alreadyFound) {
687 LocalGIDs[LID] = true; // There is a column in the graph associated with this domain map GID
688 NumLocalColGIDs++;
689 }
690 colind_LID[j] = LID;
691 } else {
692 const LO hash_value = RemoteGIDs.get(GID);
693 if (hash_value == -1) { // This means its a new remote GID
694 const int PID = owningPIDs[j];
695 TEUCHOS_TEST_FOR_EXCEPTION(
696 PID == -1, std::invalid_argument, prefix << "Cannot figure out if "
697 "PID is owned.");
698 colind_LID[j] = static_cast<LO>(numDomainElements + NumRemoteColGIDs);
699 RemoteGIDs.add(GID, NumRemoteColGIDs);
700 RemoteGIDList.push_back(GID);
701 PIDList.push_back(PID);
702 NumRemoteColGIDs++;
703 } else {
704 colind_LID[j] = static_cast<LO>(numDomainElements + hash_value);
705 }
706 }
707 }
708 }
709
710 // Possible short-circuit: If all domain map GIDs are present as
711 // column indices, then set ColMap=domainMap and quit.
712 if (domainMap.getComm()->getSize() == 1) {
713 // Sanity check: When there is only one process, there can be no
714 // remoteGIDs.
715 TEUCHOS_TEST_FOR_EXCEPTION(
716 NumRemoteColGIDs != 0, std::runtime_error, prefix << "There is only one "
717 "process in the domain Map's communicator, which means that there are no "
718 "\"remote\" indices. Nevertheless, some column indices are not in the "
719 "domain Map.");
720 if (static_cast<size_t>(NumLocalColGIDs) == numDomainElements) {
721 // In this case, we just use the domainMap's indices, which is,
722 // not coincidently, what we clobbered colind with up above
723 // anyway. No further reindexing is needed.
724 colMap = domainMapRCP;
725 return;
726 }
727 }
728
729 // Launch reduction to get global num entries in the column map
730 const LO numMyCols = NumLocalColGIDs + NumRemoteColGIDs;
731 GST numMyColsGST = static_cast<GST>(numMyCols);
732 GST numGlobalCols;
733 auto req = Details::iallreduce(numMyColsGST, numGlobalCols, Teuchos::REDUCE_SUM, *domainMap.getComm());
734
735 // Now build the array containing column GIDs
736 // Build back end, containing remote GIDs, first
737 Teuchos::Array<GO> ColIndices;
738 GO* RemoteColIndices = NULL;
739 if (numMyCols > 0) {
740 ColIndices.resize(numMyCols);
741 if (NumLocalColGIDs != static_cast<size_t>(numMyCols)) {
742 RemoteColIndices = &ColIndices[NumLocalColGIDs]; // Points to back half of ColIndices
743 }
744 }
745
746 for (LO i = 0; i < NumRemoteColGIDs; ++i) {
747 RemoteColIndices[i] = RemoteGIDList[i];
748 }
749
750 // Build permute array for *remote* reindexing.
751 Teuchos::Array<LO> RemotePermuteIDs(NumRemoteColGIDs);
752 for (LO i = 0; i < NumRemoteColGIDs; ++i) {
753 RemotePermuteIDs[i] = i;
754 }
755
756 // Sort External column indices so that all columns coming from a
757 // given remote processor are contiguous. This is a sort with two
758 // auxilary arrays: RemoteColIndices and RemotePermuteIDs.
759 Tpetra::sort3(PIDList.begin(), PIDList.end(),
760 ColIndices.begin() + NumLocalColGIDs,
761 RemotePermuteIDs.begin());
762
763 // Stash the RemotePIDs.
764 //
765 // Note: If Teuchos::Array had a shrink_to_fit like std::vector,
766 // we'd call it here.
767 remotePIDs = PIDList;
768
769 // Sort external column indices so that columns from a given remote
770 // processor are not only contiguous but also in ascending
771 // order. NOTE: I don't know if the number of externals associated
772 // with a given remote processor is known at this point ... so I
773 // count them here.
774
775 // NTS: Only sort the RemoteColIndices this time...
776 LO StartCurrent = 0, StartNext = 1;
777 while (StartNext < NumRemoteColGIDs) {
778 if (PIDList[StartNext] == PIDList[StartNext - 1]) {
779 StartNext++;
780 } else {
781 Tpetra::sort2(ColIndices.begin() + NumLocalColGIDs + StartCurrent,
782 ColIndices.begin() + NumLocalColGIDs + StartNext,
783 RemotePermuteIDs.begin() + StartCurrent);
784 StartCurrent = StartNext;
785 StartNext++;
786 }
787 }
788 if (NumRemoteColGIDs > 0 && StartNext > StartCurrent) {
789 Tpetra::sort2(ColIndices.begin() + NumLocalColGIDs + StartCurrent,
790 ColIndices.begin() + NumLocalColGIDs + StartNext,
791 RemotePermuteIDs.begin() + StartCurrent);
792 }
793
794 // Reverse the permutation to get the information we actually care about
795 Teuchos::Array<LO> ReverseRemotePermuteIDs(NumRemoteColGIDs);
796 for (LO i = 0; i < NumRemoteColGIDs; ++i) {
797 ReverseRemotePermuteIDs[RemotePermuteIDs[i]] = i;
798 }
799
800 // Build permute array for *local* reindexing.
801 bool use_local_permute = false;
802 Teuchos::Array<LO> LocalPermuteIDs(numDomainElements);
803
804 // Now fill front end. Two cases:
805 //
806 // (1) If the number of Local column GIDs is the same as the number
807 // of Local domain GIDs, we can simply read the domain GIDs into
808 // the front part of ColIndices, otherwise
809 //
810 // (2) We step through the GIDs of the domainMap, checking to see if
811 // each domain GID is a column GID. we want to do this to
812 // maintain a consistent ordering of GIDs between the columns
813 // and the domain.
814 Teuchos::ArrayView<const GO> domainGlobalElements = domainMap.getLocalElementList();
815 if (static_cast<size_t>(NumLocalColGIDs) == numDomainElements) {
816 if (NumLocalColGIDs > 0) {
817 // Load Global Indices into first numMyCols elements column GID list
818 std::copy(domainGlobalElements.begin(), domainGlobalElements.end(),
819 ColIndices.begin());
820 }
821 } else {
822 LO NumLocalAgain = 0;
823 use_local_permute = true;
824 for (size_t i = 0; i < numDomainElements; ++i) {
825 if (LocalGIDs[i]) {
826 LocalPermuteIDs[i] = NumLocalAgain;
827 ColIndices[NumLocalAgain++] = domainGlobalElements[i];
828 }
829 }
830 TEUCHOS_TEST_FOR_EXCEPTION(
831 static_cast<size_t>(NumLocalAgain) != NumLocalColGIDs,
832 std::runtime_error, prefix << "Local ID count test failed.");
833 }
834
835 // Low-cost reindex of the matrix
836 for (size_t i = 0; i < numMyRows; ++i) {
837 for (size_t j = rowptr[i]; j < rowptr[i + 1]; ++j) {
838 const LO ID = colind_LID[j];
839 if (static_cast<size_t>(ID) < numDomainElements) {
840 if (use_local_permute) {
841 colind_LID[j] = LocalPermuteIDs[colind_LID[j]];
842 }
843 // In the case where use_local_permute==false, we just copy
844 // the DomainMap's ordering, which it so happens is what we
845 // put in colind_LID to begin with.
846 } else {
847 colind_LID[j] = NumLocalColGIDs + ReverseRemotePermuteIDs[colind_LID[j] - numDomainElements];
848 }
849 }
850 }
851
852 // Make column Map
853 req->wait();
854 colMap = rcp(new map_type(numGlobalCols, ColIndices, domainMap.getIndexBase(),
855 domainMap.getComm(),
856 params));
857}
858
859template <typename LocalOrdinal, typename GlobalOrdinal, typename Node>
861 const Teuchos::ArrayView<const size_t>& rowptr,
862 const Teuchos::ArrayView<LocalOrdinal>& colind_LID,
863 const Teuchos::ArrayView<GlobalOrdinal>& colind_GID,
864 const Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>>& domainMapRCP,
865 const Teuchos::ArrayView<const int>& owningPIDs,
866 Teuchos::Array<int>& remotePIDs,
867 Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>>& colMap,
868 const Teuchos::RCP<Teuchos::ParameterList>& params) {
869 using DT = typename Node::device_type;
870 using execution_space = typename DT::execution_space;
871 execution_space exec;
872 DT device;
873
874 // Create device mirror and host mirror views from function parameters
875 // When we pass in views instead of Teuchos::ArrayViews, we can avoid copying views
876 auto colind_LID_view = Details::create_mirror_view_from_raw_host_array(device, colind_LID.getRawPtr(), colind_LID.size(), true, "colind_LID");
877 auto rowptr_view = Details::create_mirror_view_from_raw_host_array(device, rowptr.getRawPtr(), rowptr.size(), true, "rowptr");
878 auto colind_GID_view = Details::create_mirror_view_from_raw_host_array(device, colind_GID.getRawPtr(), colind_GID.size(), true, "colind_GID");
879 auto owningPIDs_view = Details::create_mirror_view_from_raw_host_array(device, owningPIDs.getRawPtr(), owningPIDs.size(), true, "owningPIDs");
880
881 typename decltype(colind_LID_view)::host_mirror_type colind_LID_host(colind_LID.getRawPtr(), colind_LID.size());
882
883 lowCommunicationMakeColMapAndReindex(rowptr_view, colind_LID_view, colind_GID_view, domainMapRCP, owningPIDs_view, remotePIDs, colMap, params);
884
885 // For now, we copy back into colind_LID_host (which also overwrites the colind_LID Teuchos array)
886 // When colind_LID becomes a Kokkos View we can delete this
887 Kokkos::deep_copy(exec, colind_LID_host, colind_LID_view);
888 // fence so colind_LID is safe to access by caller immediately
889 exec.fence();
890}
891
892template <typename LocalOrdinal, typename GlobalOrdinal, typename Node>
894 const Kokkos::View<const size_t*, typename Node::device_type> rowptr_view,
895 const Kokkos::View<LocalOrdinal*, typename Node::device_type> colind_LID_view,
896 const Kokkos::View<GlobalOrdinal*, typename Node::device_type> colind_GID_view,
897 const Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>>& domainMapRCP,
898 const Kokkos::View<const int*, typename Node::device_type> owningPIDs_view,
899 Teuchos::Array<int>& remotePIDs,
900 Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>>& colMap,
901 const Teuchos::RCP<Teuchos::ParameterList>& params) {
902 using Teuchos::rcp;
903 typedef LocalOrdinal LO;
904 typedef GlobalOrdinal GO;
905 typedef Tpetra::global_size_t GST;
907 const char prefix[] = "lowCommunicationMakeColMapAndReindex: ";
908 Tpetra::Details::ProfilingRegion regOuter("lowCommunicationMakeColMapAndReindex");
909
910 typedef typename Node::device_type DT;
911 using execution_space = typename DT::execution_space;
912 using memory_space = typename DT::memory_space;
913 execution_space exec;
914 using team_policy = Kokkos::TeamPolicy<execution_space, Kokkos::Schedule<Kokkos::Dynamic>>;
915 typedef typename map_type::local_map_type local_map_type;
916
917 // The domainMap is an RCP because there is a shortcut for a
918 // (common) special case to return the columnMap = domainMap.
919 const map_type& domainMap = *domainMapRCP;
920
921 const size_t numMyRows = rowptr_view.size() - 1;
922 local_map_type domainMap_local = domainMap.getLocalMap();
923
924 const size_t numDomainElements = domainMap.getLocalNumElements();
925 Kokkos::View<bool*, DT> LocalGIDs_view("LocalGIDs", numDomainElements);
926
927 auto map_capacity = std::max(std::min(uint32_t(1.2 * colind_LID_view.size()),
928 uint32_t(2 * numDomainElements)),
929 uint32_t(5000));
930 Kokkos::UnorderedMap<GO, int, DT> GIDs_map(map_capacity);
931 size_t NumLocalColGIDs;
932 size_t NumRemoteColGIDs;
933 while (true) {
934 Tpetra::Details::ProfilingRegion reg("lowCommunicationMakeColMapAndReindex::fill_map");
935 const LO LINVALID = Teuchos::OrdinalTraits<LO>::invalid();
936
937 // Scan all column indices and sort into two groups:
938 // Local: those whose GID matches a GID of the domain map on this processor and
939 // Remote: All others.
940 // Kokkos::Parallel_reduce sums up NumLocalColGIDs, while we use the size of the Remote GIDs map to find NumRemoteColGIDs
941 LocalRemoteCount counts;
942 Kokkos::parallel_reduce(
943 team_policy(numMyRows, Kokkos::AUTO), KOKKOS_LAMBDA(const typename team_policy::member_type& member, LocalRemoteCount& update) {
944 const int i = member.league_rank();
945 LocalRemoteCount NumLocalColGIDs_temp;
946 size_t rowptr_start = rowptr_view[i];
947 size_t rowptr_end = rowptr_view[i + 1];
948 Kokkos::parallel_reduce(
949 Kokkos::TeamThreadRange(member, rowptr_start, rowptr_end), [&](const size_t j, LocalRemoteCount& innerUpdate) {
950 const GO GID = colind_GID_view[j];
951 // Check if GID matches a row GID in local domain map
952 const LO LID = domainMap_local.getLocalElement(GID);
953 if (LID != LINVALID) {
954 auto outcome = GIDs_map.insert(GID, -1);
955 // Fresh insert
956 if (outcome.success()) {
957 LocalGIDs_view[LID] = true;
958 innerUpdate.numLocalColGIDs++;
959 }
960 } else {
961 const int PID = owningPIDs_view[j];
962 auto outcome = GIDs_map.insert(GID, PID);
963 if (outcome.success()) {
964 innerUpdate.numRemoteColGIDs++;
965 if (PID == -1) {
966 Kokkos::abort("Cannot figure out if ID is owned.\n");
967 }
968 }
969 }
970 },
971 NumLocalColGIDs_temp);
972 if (member.team_rank() == 0) update += NumLocalColGIDs_temp;
973 },
974 counts);
975 if (!GIDs_map.failed_insert()) {
976 NumLocalColGIDs = counts.numLocalColGIDs;
977 NumRemoteColGIDs = counts.numRemoteColGIDs;
978 break;
979 } else {
980 map_capacity *= 1.5;
981 GIDs_map = Kokkos::UnorderedMap<GO, int, DT>(map_capacity);
982 }
983 }
984
985 // Possible short-circuit: If all domain map GIDs are present as
986 // column indices, then set ColMap=domainMap and quit.
987 if (domainMap.getComm()->getSize() == 1) {
988 // Sanity check: When there is only one process, there can be no
989 // remoteGIDs.
990 TEUCHOS_TEST_FOR_EXCEPTION(
991 NumRemoteColGIDs != 0, std::runtime_error, prefix << "There is only one "
992 "process in the domain Map's communicator, which means that there are no "
993 "\"remote\" indices. Nevertheless, some column indices are not in the "
994 "domain Map.");
995 if (static_cast<size_t>(NumLocalColGIDs) == numDomainElements) {
996 // In this case, we just use the domainMap's indices, which is,
997 // not coincidently, what we clobbered colind with up above
998 // anyway. No further reindexing is needed.
999 colMap = domainMapRCP;
1000
1001 // Fill out local colMap (which should only contain local GIDs)
1002 auto localColMap = colMap->getLocalMap();
1003 Kokkos::parallel_for(
1004 Kokkos::RangePolicy<execution_space>(0, colind_GID_view.size()), KOKKOS_LAMBDA(const int i) {
1005 colind_LID_view(i) = localColMap.getLocalElement(colind_GID_view(i));
1006 });
1007 return;
1008 }
1009 }
1010
1011 Kokkos::View<GO*, DT> RemoteColMapIndices_unsorted(Kokkos::ViewAllocateWithoutInitializing("RemoteColMapIndices_unsorted"), NumRemoteColGIDs);
1012 Kokkos::View<int*, DT> RemotePIDs_unsorted(Kokkos::ViewAllocateWithoutInitializing("RemotePIDs_unsorted"), NumRemoteColGIDs);
1013
1014 // For each index in RemoteGIDs_map that contains a GID, use "update" to indicate the number of GIDs "before" this GID
1015 // This maps each element in the RemoteGIDs hash table to an index in RemoteGIDList / PIDList without any overwriting or empty spaces between indices
1016
1017 {
1018 Tpetra::Details::ProfilingRegion reg("lowCommunicationMakeColMapAndReindex::process_map");
1019 size_t numEnteredRemotes;
1020 Kokkos::parallel_scan(
1021 Kokkos::RangePolicy<execution_space>(0, GIDs_map.capacity()), KOKKOS_LAMBDA(const int i, size_t& update, const bool final) {
1022 if (GIDs_map.valid_at(i) && GIDs_map.value_at(i) != -1) {
1023 if (final) {
1024 RemoteColMapIndices_unsorted(update) = GIDs_map.key_at(i);
1025 RemotePIDs_unsorted(update) = GIDs_map.value_at(i);
1026 }
1027 ++update;
1028 }
1029 },
1030 numEnteredRemotes);
1031 TEUCHOS_ASSERT(numEnteredRemotes == NumRemoteColGIDs);
1032 }
1033
1034 // Launch reduction to get global num entries in the column map
1035 const size_t numMyCols = NumLocalColGIDs + NumRemoteColGIDs;
1036 GST numMyColsGST = static_cast<GST>(numMyCols);
1037 GST numGlobalCols;
1038 auto req = Details::iallreduce(numMyColsGST, numGlobalCols, Teuchos::REDUCE_SUM, *domainMap.getComm());
1039
1040 // Now build the array containing column GIDs
1041 // Build back end, containing remote GIDs, first
1042 Kokkos::View<GO*, DT> ColMapIndices(Kokkos::ViewAllocateWithoutInitializing("ColMapIndices"), numMyCols);
1043
1044 // We don't need to load the back end of ColMapIndices or sort if there are no remote GIDs
1045 if (NumRemoteColGIDs > 0) {
1046 Tpetra::Details::ProfilingRegion reg("lowCommunicationMakeColMapAndReindex::sort");
1047 auto RemoteColMapIndices_sorted = Kokkos::subview(ColMapIndices, Kokkos::make_pair(NumLocalColGIDs, numMyCols));
1048
1049 // Create a permutation that sorts by first by PID and then by GID.
1050 Kokkos::View<size_t*, memory_space> index(Kokkos::ViewAllocateWithoutInitializing("index"), NumRemoteColGIDs);
1051 Kokkos::parallel_for(
1052 Kokkos::RangePolicy<execution_space>(0, NumRemoteColGIDs), KOKKOS_LAMBDA(const size_t i) {
1053 index(i) = i;
1054 });
1055 Kokkos::sort(
1056 exec, index, KOKKOS_LAMBDA(const size_t i, const size_t j) {
1057 auto pid_i = RemotePIDs_unsorted(i);
1058 auto pid_j = RemotePIDs_unsorted(j);
1059 if (pid_i == pid_j)
1060 return RemoteColMapIndices_unsorted(i) < RemoteColMapIndices_unsorted(j);
1061 else
1062 return pid_i < pid_j;
1063 });
1064 // Apply the permutation to remote GIDs and PIDs.
1065 Kokkos::View<int*, memory_space> RemotePIDs_sorted(Kokkos::ViewAllocateWithoutInitializing("RemotePIDs_new"), NumRemoteColGIDs);
1066 Kokkos::parallel_for(
1067 Kokkos::RangePolicy<execution_space>(0, NumRemoteColGIDs), KOKKOS_LAMBDA(const size_t i) {
1068 RemoteColMapIndices_sorted(i) = RemoteColMapIndices_unsorted(index(i));
1069 RemotePIDs_sorted(i) = RemotePIDs_unsorted(index(i));
1070 });
1071
1072 // Deep copy back from device to host
1073 // Stash the RemotePIDs. Once remotePIDs is changed to become a Kokkos view, we can remove this and copy directly.
1074 Teuchos::Array<int> PIDList(NumRemoteColGIDs);
1075 Kokkos::View<int*, Kokkos::HostSpace> RemotePIDs_sorted_host(PIDList.data(), NumRemoteColGIDs);
1076 Kokkos::deep_copy(exec, RemotePIDs_sorted_host, RemotePIDs_sorted);
1077 exec.fence();
1078
1079 remotePIDs = PIDList;
1080 }
1081
1082 // Build permute array for *local* reindexing.
1083
1084 // Now fill front end. Two cases:
1085 //
1086 // (1) If the number of Local column GIDs is the same as the number
1087 // of Local domain GIDs, we can simply read the domain GIDs into
1088 // the front part of ColIndices, otherwise
1089 //
1090 // (2) We step through the GIDs of the domainMap, checking to see if
1091 // each domain GID is a column GID. we want to do this to
1092 // maintain a consistent ordering of GIDs between the columns
1093 // and the domain.
1094 if (static_cast<size_t>(NumLocalColGIDs) == numDomainElements) {
1095 if (NumLocalColGIDs > 0) {
1096 // Load Global Indices into first numMyCols elements column GID list
1097 auto LocalColMapIndices = Kokkos::subview(ColMapIndices, Kokkos::make_pair((size_t)0, numDomainElements));
1098 Kokkos::deep_copy(LocalColMapIndices, domainMap.getMyGlobalIndicesDevice());
1099 }
1100 } else {
1101 // This part isn't actually tested in the unit tests
1102 LO NumLocalAgain = 0;
1103 Kokkos::parallel_scan(
1104 Kokkos::RangePolicy<execution_space>(0, numDomainElements), KOKKOS_LAMBDA(const int i, LO& update, const bool final) {
1105 if (LocalGIDs_view(i)) {
1106 if (final) {
1107 ColMapIndices(update) = domainMap_local.getGlobalElement(i);
1108 }
1109 update++;
1110 }
1111 },
1112 NumLocalAgain);
1113
1114 TEUCHOS_TEST_FOR_EXCEPTION(
1115 static_cast<size_t>(NumLocalAgain) != NumLocalColGIDs,
1116 std::runtime_error, prefix << "Local ID count test failed.");
1117 }
1118
1119 // Make column Map
1120 req->wait();
1121 colMap = rcp(new map_type(numGlobalCols, ColMapIndices, domainMap.getIndexBase(),
1122 domainMap.getComm(), params));
1123
1124 // Fill out colind_LID using local map
1125 auto localColMap = colMap->getLocalMap();
1126 Kokkos::parallel_for(
1127 Kokkos::RangePolicy<execution_space>(0, colind_GID_view.size()), KOKKOS_LAMBDA(const int i) {
1128 colind_LID_view(i) = localColMap.getLocalElement(colind_GID_view(i));
1129 });
1130}
1131
1132// Generates an list of owning PIDs based on two transfer (aka import/export objects)
1133// Let:
1134// OwningMap = useReverseModeForOwnership ? transferThatDefinesOwnership.getTargetMap() : transferThatDefinesOwnership.getSourceMap();
1135// MapAo = useReverseModeForOwnership ? transferThatDefinesOwnership.getSourceMap() : transferThatDefinesOwnership.getTargetMap();
1136// MapAm = useReverseModeForMigration ? transferThatDefinesMigration.getTargetMap() : transferThatDefinesMigration.getSourceMap();
1137// VectorMap = useReverseModeForMigration ? transferThatDefinesMigration.getSourceMap() : transferThatDefinesMigration.getTargetMap();
1138// Precondition:
1139// 1) MapAo.isSameAs(*MapAm) - map compatibility between transfers
1140// 2) VectorMap->isSameAs(*owningPIDs->getMap()) - map compabibility between transfer & vector
1141// 3) OwningMap->isOneToOne() - owning map is 1-to-1
1142// --- Precondition 3 is only checked in DEBUG mode ---
1143// Postcondition:
1144// owningPIDs[VectorMap->getLocalElement(GID i)] = j iff (OwningMap->isLocalElement(GID i) on rank j)
1145template <typename LocalOrdinal, typename GlobalOrdinal, typename Node>
1146void getTwoTransferOwnershipVector(const ::Tpetra::Details::Transfer<LocalOrdinal, GlobalOrdinal, Node>& transferThatDefinesOwnership,
1147 bool useReverseModeForOwnership,
1148 const ::Tpetra::Details::Transfer<LocalOrdinal, GlobalOrdinal, Node>& transferThatDefinesMigration,
1149 bool useReverseModeForMigration,
1153
1154 Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>> OwningMap = useReverseModeForOwnership ? transferThatDefinesOwnership.getTargetMap() : transferThatDefinesOwnership.getSourceMap();
1155 Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>> MapAo = useReverseModeForOwnership ? transferThatDefinesOwnership.getSourceMap() : transferThatDefinesOwnership.getTargetMap();
1156 Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>> MapAm = useReverseModeForMigration ? transferThatDefinesMigration.getTargetMap() : transferThatDefinesMigration.getSourceMap();
1157 Teuchos::RCP<const Tpetra::Map<LocalOrdinal, GlobalOrdinal, Node>> VectorMap = useReverseModeForMigration ? transferThatDefinesMigration.getSourceMap() : transferThatDefinesMigration.getTargetMap();
1158
1159 TEUCHOS_TEST_FOR_EXCEPTION(!MapAo->isSameAs(*MapAm), std::runtime_error, "Tpetra::Import_Util::getTwoTransferOwnershipVector map mismatch between transfers");
1160 TEUCHOS_TEST_FOR_EXCEPTION(!VectorMap->isSameAs(*owningPIDs.getMap()), std::runtime_error, "Tpetra::Import_Util::getTwoTransferOwnershipVector map mismatch transfer and vector");
1161#ifdef HAVE_TPETRA_DEBUG
1162 TEUCHOS_TEST_FOR_EXCEPTION(!OwningMap->isOneToOne(), std::runtime_error, "Tpetra::Import_Util::getTwoTransferOwnershipVector owner must be 1-to-1");
1163#endif
1164
1165 int rank = OwningMap->getComm()->getRank();
1166 // Generate "A" vector and fill it with owning information. We can read this from transferThatDefinesOwnership w/o communication
1167 // Note: Due to the 1-to-1 requirement, several of these options throw
1169 const import_type* ownAsImport = dynamic_cast<const import_type*>(&transferThatDefinesOwnership);
1170 const export_type* ownAsExport = dynamic_cast<const export_type*>(&transferThatDefinesOwnership);
1171
1172 Teuchos::ArrayRCP<int> pids = temp.getDataNonConst();
1173 Teuchos::ArrayView<int> v_pids = pids();
1174 if (ownAsImport && useReverseModeForOwnership) {
1175 TEUCHOS_TEST_FOR_EXCEPTION(1, std::runtime_error, "Tpetra::Import_Util::getTwoTransferOwnershipVector owner must be 1-to-1");
1176 } else if (ownAsImport && !useReverseModeForOwnership)
1177 getPids(*ownAsImport, v_pids, false);
1178 else if (ownAsExport && useReverseModeForMigration) {
1179 TEUCHOS_TEST_FOR_EXCEPTION(1, std::runtime_error, "Tpetra::Import_Util::getTwoTransferOwnershipVector this option not yet implemented");
1180 } else {
1181 TEUCHOS_TEST_FOR_EXCEPTION(1, std::runtime_error, "Tpetra::Import_Util::getTwoTransferOwnershipVector owner must be 1-to-1");
1182 }
1183
1184 const import_type* xferAsImport = dynamic_cast<const import_type*>(&transferThatDefinesMigration);
1185 const export_type* xferAsExport = dynamic_cast<const export_type*>(&transferThatDefinesMigration);
1186 TEUCHOS_TEST_FOR_EXCEPTION(!xferAsImport && !xferAsExport, std::runtime_error, "Tpetra::Import_Util::getTwoTransferOwnershipVector transfer undefined");
1187
1188 // Migrate from "A" vector to output vector
1189 owningPIDs.putScalar(rank);
1190 if (xferAsImport && useReverseModeForMigration)
1191 owningPIDs.doExport(temp, *xferAsImport, Tpetra::REPLACE);
1192 else if (xferAsImport && !useReverseModeForMigration)
1193 owningPIDs.doImport(temp, *xferAsImport, Tpetra::REPLACE);
1194 else if (xferAsExport && useReverseModeForMigration)
1195 owningPIDs.doImport(temp, *xferAsExport, Tpetra::REPLACE);
1196 else
1197 owningPIDs.doExport(temp, *xferAsExport, Tpetra::REPLACE);
1198}
1199
1200} // namespace Import_Util
1201} // namespace Tpetra
1202
1203#endif // TPETRA_IMPORT_UTIL_HPP
Declaration of the Tpetra::CrsMatrix class.
Add specializations of Teuchos::Details::MpiTypeTraits for Kokkos::complex<float> and Kokkos::complex...
Declaration of Tpetra::Details::Profiling, a scope guard for Kokkos Profiling.
Functions that wrap Kokkos::create_mirror_view, in order to avoid deep copies when not necessary,...
void getTwoTransferOwnershipVector(const ::Tpetra::Details::Transfer< LocalOrdinal, GlobalOrdinal, Node > &transferThatDefinesOwnership, bool useReverseModeForOwnership, const ::Tpetra::Details::Transfer< LocalOrdinal, GlobalOrdinal, Node > &transferForMigratingData, bool useReverseModeForMigration, Tpetra::Vector< int, LocalOrdinal, GlobalOrdinal, Node > &owningPIDs)
Generates an list of owning PIDs based on two transfer (aka import/export objects) Let: OwningMap = u...
void sortAndMergeCrsEntries(const Teuchos::ArrayView< size_t > &CRS_rowptr, const Teuchos::ArrayView< Ordinal > &CRS_colind, const Teuchos::ArrayView< Scalar > &CRS_vals)
Sort and merge the entries of the (raw CSR) matrix by column index within each row.
void lowCommunicationMakeColMapAndReindex(const Teuchos::ArrayView< const size_t > &rowptr, const Teuchos::ArrayView< LocalOrdinal > &colind_LID, const Teuchos::ArrayView< GlobalOrdinal > &colind_GID, const Teuchos::RCP< const Tpetra::Map< LocalOrdinal, GlobalOrdinal, Node > > &domainMapRCP, const Teuchos::ArrayView< const int > &owningPIDs, Teuchos::Array< int > &remotePIDs, Teuchos::RCP< const Tpetra::Map< LocalOrdinal, GlobalOrdinal, Node > > &colMap, const Teuchos::RCP< Teuchos::ParameterList > &params=Teuchos::null)
lowCommunicationMakeColMapAndReindex
void sortCrsEntries(const Teuchos::ArrayView< size_t > &CRS_rowptr, const Teuchos::ArrayView< Ordinal > &CRS_colind, const Teuchos::ArrayView< Scalar > &CRS_vals)
Sort the entries of the (raw CSR) matrix by column index within each row.
void getPids(const Tpetra::Import< LocalOrdinal, GlobalOrdinal, Node > &Importer, Teuchos::Array< int > &pids, bool use_minus_one_for_local)
Like getPidGidPairs, but just gets the PIDs, ordered by the column Map.
Stand-alone utility functions and macros.
Teuchos::RCP< const Teuchos::Comm< int > > getComm() const override
The communicator over which the matrix is distributed.
GlobalOrdinal getIndexBase() const override
The index base for global indices for this matrix.
Teuchos::ArrayView< const LO > getExportLIDs() const
List of entries in the source Map that will be sent to other processes.
size_t getNumExportIDs() const
Number of entries that must be sent by the calling process to other processes.
Teuchos::ArrayView< const int > getExportPIDs() const
List of processes to which entries will be sent.
void doImport(const SrcDistObject &source, const Import< LocalOrdinal, GlobalOrdinal, Node > &importer, const CombineMode CM, const bool restrictedMode=false)
Import data into this object using an Import object ("forward mode").
void doExport(const SrcDistObject &source, const Export< LocalOrdinal, GlobalOrdinal, Node > &exporter, const CombineMode CM, const bool restrictedMode=false)
Export data into this object using an Export object ("forward mode").
virtual Teuchos::RCP< const map_type > getMap() const
The Map describing the parallel distribution of this object.
Communication plan for data redistribution from a (possibly) multiply-owned to a uniquely-owned distr...
Communication plan for data redistribution from a uniquely-owned to a (possibly) multiply-owned distr...
A parallel distribution of indices over processes.
void putScalar(const Scalar &value)
Set all values in the multivector with the given value.
A distributed dense vector.
Teuchos::ArrayRCP< Scalar > getDataNonConst()
View of the local values of this vector.
Impl::CreateMirrorViewFromUnmanagedHostArray< ValueType, OutputDeviceType >::output_view_type create_mirror_view_from_raw_host_array(const OutputDeviceType &, ValueType *inPtr, const size_t inSize, const bool copy=true, const char label[]="")
Variant of Kokkos::create_mirror_view that takes a raw host 1-d array as input.
Namespace Tpetra contains the class and methods constituting the Tpetra library.
void sort2(const IT1 &first1, const IT1 &last1, const IT2 &first2, const bool stableSort=false)
Sort the first array, and apply the resulting permutation to the second array.
size_t global_size_t
Global size_t object.
void sort3(const IT1 &first1, const IT1 &last1, const IT2 &first2, const IT3 &first3, const bool stableSort=false)
Sort the first array, and apply the same permutation to the second and third arrays.
@ REPLACE
Replace existing values with new values.