#R code that demonstrates the use of Rmpi

#Define a function that takes the loop iteration number and outputs a message containing
# the iteration number, the MPI rank, the hostname, and the number of cores on the host
hello.world <- function(i) {
   library(parallel)
   sprintf('Hello from loop iteration %d running on rank %d on node %s which has %d cores',
       i, mpi.comm.rank(), Sys.info()[c("nodename")], detectCores());
}

#Use the parallel libraries
library(Rmpi)
library(parallel)
library(snow)
# R is called with mpirun -n 1 which defines the master processes
# and then R master process spans worker processes up to the amount of cores
cl <- makeCluster( (mpi.universe.size()-1) , type='MPI' )

output.lines <- clusterApply( cl=cl, x=(1:500), fun=hello.world )
cat(unlist(output.lines), sep='\n')
stopCluster(cl)
mpi.exit()
