2014-03-30 81 views
6

我正在編寫一個函數來組合和組織數據,然後使用基函數R中的並行函數並行運行MCMC鏈。我的函數如下所示。如何將對象導出到函數中的並行集羣R

dm100zip <- function(y, n.burn = 1, n.it = 3000, n.thin = 1) { 
    y <- array(c(as.matrix(y[,2:9]), as.matrix(y[ ,10:17])), c(length(y$Plot), 8, 2)) 
    nplots <- nrow(y) 
    ncap1 <- apply(y[,1:8, 1],1,sum) 
    ncap2 <- apply(y[,1:8, 2],1,sum) 
    ncap <- as.matrix(cbind(ncap1, ncap2)) 
    ymax1 <- apply(y[,1:8, 1],1,sum) 
    ymax2 <- apply(y[,1:8, 2],1,sum) 

    # Bundle data for JAGS/BUGS 
    jdata100 <- list(y=y, nplots=nplots, ncap=ncap) 

    # Set initial values for Gibbs sampler 
    inits100 <- function(){ 
    list(p0=runif(1, 1.1, 2), 
     p.precip=runif(1, 0, 0.1), 
     p.day = runif(1, -.5, 0.1)) 
    } 

    # Set parameters of interest to monitor and save 
    params100 <- c("N", "p0") 

    # Run JAGS in parallel for improved speed 
    CL <- makeCluster(3) # set number of clusters = to number of desired chains 
    clusterExport(cl=CL, list("jdata100", "params100", "inits100", "ymax1", "ymax2", "n.burn", "jag", "n.thin")) # make data available to jags in diff cores 
    clusterSetRNGStream(cl = CL, iseed = 5312) 

    out <- clusterEvalQ(CL, { 
    library(rjags) 
    load.module('glm') 
    jm <- jags.model("dm100zip.txt", jdata100, inits100, n.adapt = n.burn, n.chains = 1) 
    fm <- coda.samples(jm, params100, n.iter = n.it, thin = n.thin) 
    return(as.mcmc(fm)) 

    }) 

    out.list <- mcmc.list(out) # group output from each core into one list 
    stopCluster(CL) 

    return(out.list) 
} 

當我運行的功能我得到的n.burn,n.it和n.thin都沒有發現在clusterExport功能使用錯誤。例如,

dm100zip.list.nain <- dm100zip(NAIN, n.burn = 1, n.it = 3000, n.thin = 1) # returns error 

如果我運行函數之前設置爲他們每個人的價值觀,那麼使用這些值,並運行良好。例如,

n.burn = 1 
n.it = 1000 
n.thin = 1 
dm100zip.list.nain <- dm100zip(NAIN, n.burn = 1, n.it = 3000, n.thin = 1) 

這運行正常,但使用n.it = 1000個不3000個

有人能爲什麼在全球環境中的對象由ClusterExport功能使用幫助,但不是由賦值函數ClusterExport在哪裏運行?有沒有解決的辦法?

回答

12

默認情況下,clusterExport會在全局環境中查找由「varlist」指定的變量。在你的情況下,它應該查看dm100zip函數的本地環境。爲了使它做到這一點,你可以使用clusterExport「ENVIR」的說法:

clusterExport(cl=CL, list("jdata100", "params100", "inits100", "ymax1", 
          "ymax2", "n.burn", "jag", "n.thin"), 
       envir=environment()) 

注意,在「varlist中的」變量在全球環境中定義的也將被發現,但值dm100zip定義爲準。

3

由於R中的函數參數是通過延遲評估來處理的,因此您需要確保函數的執行環境中實際存在任何默認參數。實際上,R核心作者爲此包括force函數,它只是function(x) x,並強制參數從承諾轉換爲計算表達式。請嘗試進行以下修改:

dm100zip <- function(y, n.burn = 1, n.it = 3000, n.thin = 1) { 
    force(n.burn); force(n.it); force(n.thin) 
    # The rest of your code as above... 
} 

有關這些問題的更詳細說明,請參閱Lazy Evaluation section of Hadley's treatment of functions

+0

感謝您的信息。我不知道強制功能。不幸的是,我仍然得到相同的錯誤:> dm100zip.list.nain < - dm100zip(NAIN,n.burn = 1,n.it = 3000,n.thin = 1) get(name,envir = envir) :object'n.burn'找不到 調用自:eval(替代(瀏覽器(skipCalls = pos),列表(pos = 9-幀)), envir = sys.frame(frame)) – djhocking

+1

沒有必要強制對通過clusterExport導出的變量進行評估。您可能不得不強制發送到工作進程的變量隱式地在用戶提供的工作函數的序列化環境中,但這是ParLapply和clusterApplyLB之類的函數中的問題,而不是clusterEvalQ。 –