在JAGS中并行foreach()%dopar%{...}计算

时间:2017-11-21 05:11:08

标签: r parallel-processing parallel.foreach jags

我想我可以根据需要在JAGS中使用并行计算。

这是我的R脚本。

library(foreach)
list.data2 <- foreach(i=1:n.rep) %do% {
  foreach(j=1:2) %do% {list( cap       = cap_data[[i]][[j]],
                             loc       = loc_data[[i]][[j]],
                             eff       = eff_data[[i]][[j]],
                             trap.numb = trap.numb2,
                             av        = av,
                             forest    = env$forest,
                             crop      = env$crop,
                             bamboo    = env$bamboo,
                             grass     = env$grass,
                             abandoned = env$abandoned,
                             city      = env$city,
                             rate      = env$for_cr_rate,
                             m.numb    = m.numb,
                             ones = matrix( 1, m.numb, 5 )
                             )  #,bound_mat=bound_mat,bound_numb=bound_numb
  }
}

inits2 <- foreach(j=1:2) %do% {list( n=n.inits2[[j]],
                                     b0=0.5, b1=0.1, b2=0.1, b3=0.1, b4=0.1, b5=0.1, b6=0.1,
                                     a0=5,   a1=0.5, a2=0.5, a3=0.5, a4=0.5, a5=0.5, a6=0.5,
                                     sd=1,
                                     err=rep(0,m.numb),
                                     r_capt=0.10
                                     )
}

para2 <- c("a0","a1","a2","a3","a4", "a5","a6",
           "b0","b1","b2","b3","b4", "b5","b6", "n28", "n29", "r_capt")

library(R2jags)
start.time <- Sys.time()
install.packages("doParallel")

library(doParallel)
registerDoParallel(cores=6)
x_real2 <- foreach( i = 1:2, 
                   .packages = "R2jags"
                    ) %dopar% {jags( "realdata_5years.txt",
                                      data     = list.data2[[i]][[?]],
                                      inits    = inits2[[i]],
                                      para     = para2,
                                      n.chain  = 3,
                                      n.iter   = n.1000000,
                                      n.burnin = 400000,
                                      n.thin   = 200
                                      )
           }
sum_real2 <- foreach(i = 1:2) %do% {x_real2[[i]]$BUGSoutput$summary}
---------------------------------------------------------------------

所以,我有两个数据集,每个都有30次(== n.rep)次重复 因此,我总共有60个数据列表。

我想为两个数据集和每个3 MCMC链使用六个核心。 而且,我需要重复这个计算30(== n.rep)次 但是,我不知道这样写。我在最后4行中遇到了问题。

我应该两次使用 %dopar% 吗? 或
除了 jags.parallel 之外,我应该使用 foreach 吗?

0 个答案:

没有答案