如何在R中对这个递归图搜索功能进行矢量化(并加速)?

时间:2014-05-21 00:46:24

标签: r optimization recursion vectorization igraph

我在R中编写了一个递归函数,用于查找有向图的所有路径s-t路径(无循环)。我使用此页面作为我的模型:All possible paths from one node to another in a directed tree (igraph)并输出正确的结果,但速度很慢。用小图表,没什么大不了的。对于大图,这是一个问题。

我是R的新手但已经读到它在避免循环和使用矢量化时表现得更好。我试图绕过它,我希望你可以提供帮助。我的代码:

findAllPaths <- function(graph,start,end) {
  return(fastFindPaths(graph, start, end))
}   


fastFindPaths <- function(graph, from, to, path) {
  if(missing(path)) path <- c()
  path <- cbind(path, from)
  if (from == to) return(path)
  paths <- c()
  adjList <- get.adjlist(graph, mode="out")[[from]]
  for (child in adjList) {
    if (!child %in% path) {
      childPaths <- fastFindPaths(graph, child, to, path)
      for (childPath in childPaths) paths <- c(paths, childPath)
    }
  }
  return(paths)
}

那么,这是矢量化的候选者吗?我怎样才能加快速度呢?你给别人学习R的其他任何提示吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

igraph的开发版本具有get.all.simple.paths()功能,您可以从此处获取:http://igraph.org/nightly

答案 1 :(得分:0)

我使用Tamas的建议不要拨打get.adjlist(),而是使用neighbors()并提供适当的速度提升。然而,真正有助于提高性能的是通过在每个起始节点的子节点上调用fastFindPaths()并聚合结果来并行化搜索。我目前在Windows机器上,所以使用了clusterApply()功能。虽然我可能会将代码概括为检查Sys.info()[1]并使用mclapply()(如果不是Windows)。

相关问题