/* 10_rma_pi.c - the pi example again, with one-sided communication instead of Bcast/Reduce.
 * Rank 0 exposes two variables in windows. The other ranks fetch n with MPI_Get and add
 * their partial result into pi with MPI_Accumulate. Rank 0 never posts a receive.
 * Build: mpicc -O2 -o 10_rma_pi 10_rma_pi.c -lm
 * Run:   mpirun -np 4 ./10_rma_pi
 */
#include <stdio.h>
#include <math.h>
#include <mpi.h>

int main(int argc, char **argv)
{
    const double PI25DT = 3.141592653589793238462643;
    int rank, size;
    long n = 0;
    double pi = 0.0;
    MPI_Win nwin, piwin;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    if (rank == 0) n = 10000000;

    /* Window creation is collective. Ranks other than 0 expose no memory (size 0). */
    MPI_Win_create(&n,  rank == 0 ? sizeof(long)   : 0, sizeof(long),   MPI_INFO_NULL, MPI_COMM_WORLD, &nwin);
    MPI_Win_create(&pi, rank == 0 ? sizeof(double) : 0, sizeof(double), MPI_INFO_NULL, MPI_COMM_WORLD, &piwin);

    /* Epoch 1: everyone reads n from rank 0. The fence before opens the epoch,
     * the fence after guarantees the MPI_Get has completed. */
    MPI_Win_fence(0, nwin);
    if (rank != 0) MPI_Get(&n, 1, MPI_LONG, 0, 0, 1, MPI_LONG, nwin);
    MPI_Win_fence(0, nwin);

    double h = 1.0 / (double)n, sum = 0.0;
    for (long i = rank + 1; i <= n; i += size) {
        double x = h * ((double)i - 0.5);
        sum += 4.0 / (1.0 + x * x);
    }
    double mypi = h * sum;

    /* Epoch 2: everyone adds its part into pi on rank 0. Concurrent MPI_Accumulate
     * calls to the same location are allowed; plain MPI_Put calls would not be. */
    MPI_Win_fence(0, piwin);
    MPI_Accumulate(&mypi, 1, MPI_DOUBLE, 0, 0, 1, MPI_DOUBLE, MPI_SUM, piwin);
    MPI_Win_fence(0, piwin);

    if (rank == 0)
        printf("pi = %.16f, error = %.2e (from %d processes)\n", pi, fabs(pi - PI25DT), size);

    MPI_Win_free(&nwin);
    MPI_Win_free(&piwin);
    MPI_Finalize();
    return 0;
}
