TRIQS/mpi 1.3.0
C++ interface to MPI
Loading...
Searching...
No Matches
Example 3: Custom type and operator

In this example, we show how to use mpi::mpi_type_from_tie, mpi::map_C_function and mpi::map_add to register a new MPI datatype and to define MPI operations for it.

#include <mpi/mpi.hpp>
#include <iostream>
// define a custom complex type
struct my_complex {
double real;
double imag;
};
// define an addition for my_complex
inline my_complex operator+(const my_complex& z1, const my_complex& z2) {
return { z1.real + z2.real, z1.imag + z2.imag };
}
// define a tie_data function for mpi_type_from_tie
inline auto tie_data(const my_complex& z) {
return std::tie(z.real, z.imag);
}
// register my_complex as an MPI type
template <> struct mpi::mpi_type<my_complex> : mpi::mpi_type_from_tie<my_complex> {};
int main(int argc, char *argv[]) {
// initialize MPI environment
mpi::environment env(argc, argv);
// create complex number z
my_complex z = { world.rank() + 1.0, static_cast<double>(world.rank()) };
// sum z over all processes
auto sum = mpi::reduce(z, world, 0, false, mpi::map_add<my_complex>());
// define a product for my_complex
auto my_product = [](const my_complex& z1, const my_complex& z2) {
return my_complex { z1.real * z2.real - z1.imag * z2.imag, z1.real * z2.imag + z1.imag * z2.real };
};
// multiply z over all processes
auto product = mpi::reduce(z, world, 0, false, mpi::map_C_function<my_complex, my_product>());
// print result
if (world.rank() == 0) {
std::cout << "sum = (" << sum.real << ", " << sum.imag << ")\n";
std::cout << "product = (" << product.real << ", " << product.imag << ")\n";
}
}
C++ wrapper around MPI_Comm providing various convenience functions.
int rank() const
Get the rank of the calling process in the communicator.
decltype(auto) reduce(T &&x, communicator c={}, int root=0, bool all=false, MPI_Op op=MPI_SUM)
Generic MPI reduce.
MPI_Op map_add()
Create a new MPI_Op for a generic addition by calling MPI_Op_create.
Definition operators.hpp:70
MPI_Op map_C_function()
Create a new MPI_Op from a given binary function by calling MPI_Op_create.
Definition operators.hpp:46
Includes all relevant mpi headers.
RAII class to initialize and finalize MPI.
Create an MPI_Datatype from some struct.
Map C++ datatypes to the corresponding MPI datatypes.
Definition datatypes.hpp:57

Output (running with -n 5):

sum = (15, 10)
product = (-185, 180)