2013-07-04 18 views
1

我試圖在筆記本上使用並行處理在R中運行NetLogo模擬(使用RNetLogo軟件包)。我試圖用3個(即0,25和50)不同的「最小間隔」值來評估「女性的餵食」。對於每個「最小分離」值,我想重複模擬10次。我可以使用lapply正確運行所有內容,但我遇到了parLapply問題。我剛開始使用「parallel」包,所以我確定它是語法中的一些東西。使用parLapply運行NetLogo模型遇到問題

#Set up clusters for parallel 
processors <- detectCores() 
cl <- makeCluster(processors) 

#Simulation 
sim3 <- function(min_sep) { 
NLCommand("set minimum-separation ", min_sep, "setup") 
ret <- NLDoReport(720, "go", "[t-feeding] of females", as.data.frame=TRUE) 
tot <- sum(ret[,1]) 
return(tot) 
} 

#Replicate simulations 10 times using lapply and create boxplots. This one works. 
rep.sim3 <- function(min_sep, rep) { 
return(
lapply(min_sep, function(min_sep) { 
replicate(rep, sim3(min_sep)) 
}) 
) 
} 
d <- seq(0,50,25) 
res <- rep.sim3(d,10) 
boxplot(res,names=d, xlab="Minimum Separation", ylab="Time spent feeding") 

#Replicate simulations 10 times using parLapply. This one does not work. 
rep.sim3 <- function(min_sep, rep) { 
return(
parLapply(cl, min_sep, function(min_sep) { 
replicate(rep, sim3(min_sep)) 
}) 
) 
} 
d <- seq(0,50,25) 
res <- rep.sim3(d,10) 

# Error in checkForRemoteErrors(val) : 3 nodes produced errors; first error: could not find function "sim3" 

#Replicate simulations 10 times using parLapply. This one does work but creates a list of the wrong length and therefore the boxplot cannot be plotted correctly. 
rep.sim3 <- function(min_sep, rep) { 
return(
parLapply(cl, replicate(rep, d), sim3)) 
} 
d <- seq(0,50,25) 
res <- rep.sim3(d,10) 

理想情況下,我想使第一個parLapply工作。或者,我想我可以修改parLapply中的res,它的作用是讓列表的長度爲max_sep,而不是30.但是,我似乎無法做到這一點。任何幫助將非常感激!

在此先感謝。

回答

3

您需要在執行rep.sim3之前初始化羣集工作者。該錯誤消息表明您的工作人員無法執行sim3函數,因爲您尚未將其導出給他們。另外,我注意到你還沒有在工人身上加載RNetlogo包。

初始化工人最簡單的方法是用clusterEvalQclusterExport功能:

clusterEvalQ(cl, library(RNetLogo)) 
clusterExport(cl, 'sim3') 

注意,你不應該這樣做在你的rep.sim3功能,因爲這將是低效的和不必要的。在創建羣集對象後只做一次,並已定義sim3

此初始化是必需的,因爲通過makeCluster啓動的工作人員不知道有關變量或函數的任何內容,或者有關R會話的任何其他信息。並且parLapply不會分析您傳遞給它的功能比lapply多。區別在於lapply在您的本地R會話中執行,其中定義了sim3並且加載了RNetLogo包。 parLapply通過執行您的R腳本來執行遠程R會話中尚未初始化的指定功能。

+0

謝謝Steve!這就說得通了。現在就開始工作了。 – user2359494