我在使用R中的并行包获取一些代码时遇到问题。我正在使用R 2.15。
这是一个简化的例子......我有一个'animal.R'文件,其中包含以下内容:
# animal.R
setClass("Animal", representation(species = "character", legs = "numeric"))
##Define some Animal methods
setGeneric("count",function(x) standardGeneric("count"))
setMethod("count", "Animal", function(x) { x@legs})
setGeneric("countAfterChopping",function(x) standardGeneric("countAfterChopping"))
setMethod("countAfterChopping", "Animal", function(x) { x@legs <- x@legs-1; x@legs})
然后,在我的R终端,我跑:
library(parallel)
source('animal.R')
启动两个节点的本地群集:
cl <- makeCluster(rep('localhost', 2))
告诉群集节点有关Animal类的信息:
clusterEvalQ(cl, parse('animal.R'))
然后在集群上运行一些代码:
# This works
parSapply(cl, list(daisy, fred), count)
# This doesn't...
parSapply(cl, list(daisy, fred), countAfterChopping)
停止群集:
stopCluster(cl)
对parSapply的第一次调用按预期工作,但第二次调用会产生此错误:
Error in checkForRemoteErrors(val) :
2 nodes produced errors; first error: "Animal" is not a defined class
任何想法发生了什么?为什么第二次调用parSapply不起作用?
答案 0 :(得分:3)
所以这是正在发生的事情:
对于“Animal”类的S4对象,count
函数只提取legs
个插槽。如果这就是您所做的一切,则无需在群集节点上评估或获取文件animal.R
。所有必要的信息都将由parSapply
传递。
但是,countAfterChopping
函数会为legs
广告位分配一个新值,这就是乐趣开始的地方。时隙分配函数`@<-`
包含对`slot<-`
的调用,其参数为check = TRUE
。这会触发对函数checkSlotAssignment
的评估,该函数通过查阅类的定义(来自?checkSlotAssignment
)来检查“此插槽允许的值是否允许”。
因此,在以这种方式分配给插槽时必须知道类定义,并且在集群节点上不知道S4类“Animal”。这就是为什么评估解析的文件animal.R
或采购它的原因。但是,只需评估文件的第一行,即在每个节点上定义“Animal”类,就可以了。
这是一个简化的,可重复的例子:
animal.R<-"
setClass('Animal', representation(species = 'character', legs = 'numeric'))
##Define some Animal methods
setGeneric('count',function(x) standardGeneric('count'))
setMethod('count', signature(x='Animal'), function(x) { x@legs})
setGeneric('countAfterChopping',function(x) standardGeneric('countAfterChopping'))
setMethod('countAfterChopping', signature(x='Animal'),
function(x) { x@legs <- x@legs-1; x@legs})
"
library(parallel)
source(textConnection(animal.R))
cl <- makeCluster(rep('localhost', 2))
daisy<-new("Animal",legs=2,species="H.sapiens")
fred<-new("Animal",legs=4,species="C.lupus")
parSapply(cl, list(daisy, fred), count)
# [1] 2 4
clusterExport(cl,"animal.R") #
clusterEvalQ(cl,eval(parse(textConnection(animal.R),n=1)))
parSapply(cl, list(daisy, fred), countAfterChopping)
# [1] 1 3