32 long long nGlobal, std::vector<T>& out,
MPI_Comm comm) {
33 static_assert(std::is_trivially_copyable_v<T>,
"gatherByGlobalId moves T as raw bytes");
34 if (ids.size() != vals.size())
35 throw std::invalid_argument(
"gatherByGlobalId: ids and vals differ in length");
36 if (ids.size() >
static_cast<std::size_t
>(INT_MAX /
sizeof(T)) ||
37 ids.size() >
static_cast<std::size_t
>(INT_MAX /
sizeof(
long long)))
38 throw std::overflow_error(
"gatherByGlobalId: a rank's contribution exceeds INT_MAX bytes");
41 const int n =
static_cast<int>(ids.size());
42 std::vector<int> counts(
static_cast<std::size_t
>(size)), displs(
static_cast<std::size_t
>(size));
45 for (
int r = 0; r < size; ++r) {
46 displs[
static_cast<std::size_t
>(r)] =
static_cast<int>(tot);
47 tot += counts[
static_cast<std::size_t
>(r)];
49 throw std::overflow_error(
"gatherByGlobalId: the global vector exceeds INT_MAX entries");
52 throw std::invalid_argument(
"gatherByGlobalId: the ids do not cover [0, nGlobal) once each");
53 std::vector<long long> idAll(
static_cast<std::size_t
>(tot));
54 MPI_Allgatherv(ids.data(), n, MPI_LONG_LONG, idAll.data(), counts.data(), displs.data(),
56 std::vector<T> vAll(
static_cast<std::size_t
>(tot));
57 std::vector<int> bc(counts.size()), bd(displs.size());
58 for (std::size_t r = 0; r < counts.size(); ++r) {
59 if (
static_cast<std::size_t
>(counts[r]) >
static_cast<std::size_t
>(INT_MAX) /
sizeof(T) ||
60 static_cast<std::size_t
>(displs[r]) >
static_cast<std::size_t
>(INT_MAX) /
sizeof(T))
61 throw std::overflow_error(
"gatherByGlobalId: the global vector exceeds INT_MAX bytes");
62 bc[r] = counts[r] *
static_cast<int>(
sizeof(T));
63 bd[r] = displs[r] *
static_cast<int>(
sizeof(T));
65 MPI_Allgatherv(vals.data(), n *
static_cast<int>(
sizeof(T)),
MPI_BYTE, vAll.data(), bc.data(),
67 out.assign(
static_cast<std::size_t
>(nGlobal), T{});
68 std::vector<char> seen(
static_cast<std::size_t
>(nGlobal), 0);
69 for (std::size_t k = 0; k < idAll.size(); ++k) {
70 const long long id = idAll[k];
71 if (id < 0 || id >= nGlobal || seen[
static_cast<std::size_t
>(
id)])
72 throw std::invalid_argument(
"gatherByGlobalId: the ids do not cover [0, nGlobal) once each");
73 seen[
static_cast<std::size_t
>(id)] = 1;
74 out[
static_cast<std::size_t
>(id)] = vAll[k];
void gatherByGlobalId(const std::vector< long long > &ids, const std::vector< T > &vals, long long nGlobal, std::vector< T > &out, MPI_Comm comm)
ids[i] is the global id of vals[i] on this rank.