From 2981f4fdb5223bf99cda7c26ed3643c2bafa60df Mon Sep 17 00:00:00 2001
From: Dmitri Naumov <dmitri.naumov@ufz.de>
Date: Fri, 18 Oct 2024 19:23:28 +0200
Subject: [PATCH] [BL/MPI] allgather version for vectors

---
 BaseLib/MPI.h | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/BaseLib/MPI.h b/BaseLib/MPI.h
index 1d58b374b14..8601dc4976a 100644
--- a/BaseLib/MPI.h
+++ b/BaseLib/MPI.h
@@ -9,6 +9,8 @@
 
 #pragma once
 
+#include <algorithm>
+
 #include "Error.h"
 
 #ifdef USE_PETSC
@@ -86,6 +88,21 @@ static std::vector<T> allgather(T const& value, Mpi const& mpi)
     return result;
 }
 
+template <typename T>
+static std::vector<T> allgather(std::vector<T> const& vector, Mpi const& mpi)
+{
+    std::size_t const size = vector.size();
+    // Flat in memory over all ranks;
+    std::vector<T> result(mpi.size * size);
+
+    std::copy_n(vector.begin(), size, &result[mpi.rank * size]);
+
+    MPI_Allgather(&result[mpi.rank * size], size, mpiType<T>(), result.data(),
+                  size, mpiType<T>(), mpi.communicator);
+
+    return result;
+}
+
 template <typename T>
 static T allreduce(T const& value, MPI_Op const& mpi_op, Mpi const& mpi)
 {
-- 
GitLab