从 R 并行运行 NetLogo 模拟



怎么可能并行运行以下NetLogo模拟。

library(RNetLogo)
path.to.NetLogo <- "C:/Program Files (x86)/NetLogo 5.1.0" #change this path to your Netlogo directory
NLStart(path.to.NetLogo, nl.version=5)
#open specific model from NetLogo then.    
while(i < 0.123)
{
NLCommand("set beta-exit", i)
NLCommand("setup");
a=NLReport("count inboxturtles with [exit = true]");
NLCommand ("go");
e=((NLReport("total-time"))/a)
i=i+0.009;
}

考虑一下,这个声明:

NLCommand ("go");

执行需要的时间最多,应并行运行。我希望在不打开NetLogo的多个实例的情况下以某种方式做到这一点。

为了使问题更清楚:

前提:Behavior Space并行运行NetLogo模拟。

目的:使用从R开始的同一NetLogo实例,并行运行while循环的模拟。

我假设你想运行一个实验,改变参数beta-exit的值,并并行使用计算机上的所有可用内核。从R开始,这意味着打开同一NetLogo模型的多个实例,每个实例在不同的内核上运行(这与你所说的目标略有不同)。

RNetLogo-package的创建者Jan Thiele实际上已经写了一个关于这个的小插曲(链接)。

在您的情况下,只改变一个参数,他的示例代码应该正是您想要的。这是对您的问题进行一些调整:

1.一些基本参数:

gui <- TRUE
nl.path <- "C:/Program Files (x86)/NetLogo 5.1.0"
model.path <- "C:/..."

2.辅助功能:

## To start NetLogo and open desired model
prepro <- function(gui, nl.path, model.path) {
  library(RNetLogo)
  NLStart(nl.path, gui=gui)
  NLLoadModel(model.path)
}
## simulation function
simfun <- function(i_value) {
  NLCommand("set beta-exit", i_value)
  NLCommand("setup")
  a <- NLReport("count inboxturtles with [exit = true]")
  NLCommand ("go")
  e <- (NLReport("total-time"))/a
  ret <- data.frame(count = a, time = e)
  return(ret)
}
## To close NetLogo
postpro <- function(x) {
  NLQuit()
}

3. 并行计算的设置:

library(parallel)
processors <- detectCores()
cl <- makeCluster(processors, outfile="./log.txt") 
# Logfile in working directory, oftentimes helpful as there is no console output
## Extension: If you define your own functions that are to be called 
## from within the simulation, they need to be made known to each of the cores
clusterExport(cl, list("own_function1", "own_function1")) 
## load NetLogo on each core
invisible(parLapply(cl, 1:processors, prepro, gui=gui, 
                    nl.path=nl.path, model.path=model.path))
## re-set working directory for each cluster (relevant for logfile).
## There's probably a more elegant way to do this, but it gets the job done.
clusterEvalQ(cl, setwd("C:/DESIRED_WD"))

4. 运行并行仿真:

## create vector of beta-exit values
i <- seq(0.006, 0.123, 0.009)
## run simulations
result.par <- parSapply(cl, i, simfun)

5. 退出网络徽标并停止集群:

invisible(parLapply(cl, 1:processors, postpro))
stopCluster(cl)

您可能还想在 snow-package 中查看其他用于并行计算的功能,这些函数可用于代替 parSapply()

最新更新