I'm trying to run a simulation with parameter values drawn from different distributions for many times. And I would like to save the results from each run by column to different matrices. This should be pretty common but I have a hard time parallelising my original scripts with nested loops. I wonder if I could find some help here.
And here is my try on parallelising:
library(foreach)
library(doParallel)
library(raster)
cl <- makeCluster(5)
registerDoParallel(cl)
ccomb <- function(...) {
args <- list(...)
lapply(seq_along(args[[1]]), function(i)
do.call('cbind', lapply(args, function(a) a[[i]])))}
sim.results<-foreach(i=1:n.iter, .combine='ccomb', .multicombine=TRUE,.packages =c("raster")) %dopar% {
for(k in 1:n.year) {
temp.s1<-matrix.s1[,k]*matrix.pro[,k]
temp.raster<-raster(nrow=10, ncol=10,xmn=0, xmx=10,ymn=0, ymx=10,crs=NA,resolution=c(1,1))
temp.raster[]<-temp.s1
temp.raster.mv<-focal(temp.raster,w=matrix.mv,fun=sum,na.rm=T)
post.mv<-as.vector(temp.raster.mv)
matrix.s1[,k+1]<-post.mv+matrix.s2[,k]
matrix.s2[,k+1]<-matrix.s2[,k]*matrix.pro[,k]}
matrix.s1_year2<-matrix.s1[,2]
matrix.s1_year3<-matrix.s1[,3]
matrix.s1_year4<-matrix.s1[,4]
matrix.s2_year2<-matrix.s2[,2]
matrix.s2_year3<-matrix.s2[,3]
matrix.s2_year4<-matrix.s2[,4]
list(matrix.s1_year2,matrix.s1_year3,matrix.s1_year4,matrix.s2_year2,matrix.s2_year3,matrix.s2_year4)}
stopCluster(cl)
The inner for(k in 1:n.year)
loop is sequential (computation for each year depends on the result from previous year) and contains a moving window function, I therefore assumed it has to stay as a whole. The outer foreach
loop is how many times I would like to run the inner loops, and I would like to save all the runs in the six matrices at the end of the outer loop.
However, when I run above code, I found it used only one core and wasn't sped up. If I understand this post right, putting for
loops within foreach
loops should be ok.
I wonder if anyone could give me a hand on finding where the problem might be? Thanks very much!
UPDATE
Here is sample data:
n.year<-3
n.iter<-5
matrix.s1<-matrix(NA,100,n.year+1,dimnames= list(NULL,c("year1","year2","year3","year4")))
matrix.s2<-matrix(NA,100,n.year+1,dimnames= list(NULL,c("year1","year2","year3","year4")))
matrix.pro<-matrix(rbeta(300,1,1),100,n.year,dimnames= list(NULL,c("year1","year2","year3")))
matrix.mv<-matrix(rbeta(25,1,1),5,5)
matrix.s1_year2<-matrix.s1_year3<-matrix.s1_year4<-matrix(NA,100,n.iter)
matrix.s2_year2<-matrix.s2_year3<-matrix.s2_year4<-matrix(NA,100,n.iter)
matrix.s1[,1]<-runif(100,0,10)
matrix.s2[,1]<-runif(100,10,20)