[R] help with random numbers and Rmpi
Na Li
nali at biostat.umn.edu
Tue Dec 2 06:32:26 CET 2003
On 1 Dec 2003, Faheem Mitha spake thusly:
> I am trying to get a simple program working using Rmpi with the model of 1
> R master and n C slaves. What I am trying to do is have each of the C
> slaves generate a random number from U[0,1], and then have the master
> collect all n numbers as a vector and output it. However even doing this
> is rather over my head. I'm trying to use rsprng and sprng, but I am sure
> what I am currently doing is wrong.
>
> *************************************************************************
> rand.R
> *************************************************************************
> library(Rmpi)
>
> rand <- function ()
> {
> if (mpi.comm.size(1) > 1)
> stop ("It seems some slaves running on comm 1.")
> mpi.comm.spawn("./rand")
> mpi.intercomm.merge(2,0,1)
>
>X mpi.init.sprng()
>X free.sprng() #does this function exist here?
I'm not familiar with Rmpi code. But here you don't need call any SPRNG
function. Instead, generate a seed (an integer) can pass it on to the
slaves.
> rdata <- double(sum(mpi.comm.size(1)))
> out <- mpi.gather(0, 2, rdata) ##this isn't right
> mpi.comm.free()
> out
> }
>
> *************************************************************************
> rand.c
> *************************************************************************
> #include <mpi.h>
> #include <sprng.h>
>
> int main(int argc, char **argv)
> {
> double rand;
> double* randarray;
>
> MPI_Comm slavecomm, all_processes;
>
> /*Initialize MPI*/
> MPI_Init(&argc, &argv);
>
> MPI_Comm_get_parent(&slavecomm);
> MPI_Intercomm_merge(slavecomm, 1, &all_processes);
>
> /*How many processes are there?*/
> MPI_Comm_size(all_processes, &size);
>
> /*Which one am I?*/
> MPI_Comm_rank(all_processes, &rank);
>
>X init_sprng()
>X rand = sprng();
>X free.sprng()
Receive the seed from the master and call
int * stream_id;
stream_id = init_sprng (gtype, rank, size, seed, param);
where gtype and param can be predefined or got from the master as well.
Now you can generate random numbers by:
rand = sprng (stream_id);
free_sprng (stream_id);
> randarray = (double *)malloc(sizeof(double)*size);
>
> /*Gather random numbers from all C slave processes*/
> /* Using randarray doesn't make sense since this should correspond
> to the rdata vector in the R master process */
> MPI_GAther(&rand, 1, 1, MPI_DOUBLE, randarray, 1, MPI_DOUBLE, 0,
> all_processes);
>
> /*All done*/
> MPI_Comm_free(&all_processes);
> MPI_Finalize();
> exit(0);
> }
There is nothing mysterious about the MPI code in SPRNG, don't use it.
Generating and passing seeds around yourself.
Michael
--
Na (Michael) Li, Ph.D.
Assistant Professor
Division of Biostatistics, University of Minnesota
A443 Mayo Bldg, MMC 303 Phone: (612) 626-4765
420 Delaware St SE Fax: (612) 626-0660
More information about the R-help
mailing list