在Linux平台上从R foreach调用Fortran子例程

时间:2017-12-07 14:35:29

标签: r linux foreach fortran doparallel

rm(list=ls())
library(doParallel)
dyn.load("bar.so")
foo <- function(x) {
        if (!is.numeric(x))
                stop("arg x must be numeric")
        out <- .Fortran("bar",
                n=as.integer(length(x)),
                x=as.double(x))
        return(out$x)
}
foo2 <- function(y) {
        y2 <- y * y
        return(y2)
}
cl <- makeCluster(2)
registerDoParallel(cl)
result <- array(data=0.0,c(5,3))
for(num in 10:14){
  num_list <- c(num, num+3, num-1)
  result[num-9,] <-foo(num_list)
  cat(paste("num = ",num," ", result[num-9,],"\n"))
}
result2 <- array(data=0.0,c(5,3))
for(num in 10:14){
  num_list <- c(num, num+3, num-1)
  result2[num-9,] <-foo2(num_list)
  cat(paste("num = ",num," ", result2[num-9,],"\n"))
}
result_par <- array(data=0.0,c(5,3))
foreach(num = 10:14, .verbose=TRUE) %dopar%{
  num_list <- c(num, num+3, num-1)
  filename <- paste0("Result_",num)
  result_par[num-9,] <-foo(num_list)
  #result_par[num-9,] <-foo2(num_list)
  write.csv(result_par[num-9,],filename)
}
stopCluster(cl)

以上是我编写的一些测试代码,它重现了我的真实代码所带来的错误。实际的Fortran代码冗长而复杂,重新编码需要很长时间,这就是我试图通过将其作为共享对象加载来调用它的原因。共享对象是从命令提示符创建的,其中包含以下行:    R CMD SHLIB bar.f

它工作正常,直到我尝试从foreach循环中调用Fortran子例程。然后我收到以下错误:

automatically exporting the following variables from the local environment:
  foo, num_list, result_par 
numValues: 5, numResults: 0, stopped: TRUE
got results for task 1
accumulate got an error result
numValues: 5, numResults: 1, stopped: TRUE
returning status FALSE
got results for task 2
numValues: 5, numResults: 2, stopped: TRUE
returning status FALSE
got results for task 3
numValues: 5, numResults: 3, stopped: TRUE
returning status FALSE
got results for task 4
numValues: 5, numResults: 4, stopped: TRUE
returning status FALSE
got results for task 5
numValues: 5, numResults: 5, stopped: TRUE
not calling combine function due to errors
returning status TRUE
Error in { : 
  task 1 failed - "Fortran symbol name "bar" not in load table"

如果我在foreach循环中使用foo2而不是foo,它似乎工作正常。所以看起来这个问题与使用共享库有关。

我正在使用:

R version 3.3.1(2016-06-21) - “你头发中的虫子” 版权所有(C)2016 R统计计算基金会

平台:x86_64-pc-linux-gnu(64位)

0 个答案:

没有答案