1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
#ifndef HPC_MPI_GRID_H
#define HPC_MPI_GRID_H 1

#include <mpi.h>

namespace hpc { namespace mpi {

struct Grid
{
    Grid()
    {
        int dims[2]    = {0, 0};
        int periods[2] = {false, false};

        /* create two-dimensional Cartesian grid for our prcesses */
        MPI_Comm_size(MPI_COMM_WORLD, &nof_processes);
        MPI_Dims_create(nof_processes, 2, dims);
        MPI_Cart_create(MPI_COMM_WORLD,
                        2,        // number of dimensions
                        dims,     // actual dimensions
                        periods,  // both dimensions are non-periodical
                        true,     // reorder is permitted
                        &comm     // newly created communication domain
                       );
        MPI_Comm_rank(MPI_COMM_WORLD, &rank); // update rank (could have changed)
        numNodeRows = dims[0];
        numNodeCols = dims[1];

        /* get our position within the grid */
        int coords[2];
        MPI_Cart_coords(comm, rank, 2, coords);
        nodeRow = coords[0];
        nodeCol = coords[1];
    }

    int         numNodeRows, numNodeCols;
    int         nodeRow, nodeCol;
    int         nof_processes, rank;

    MPI_Comm    comm;
};

} } // namespaces mpi, hpc

#endif // HPC_MPI_GRID_H