从R并行运行NetLogo模拟
如何能够并行运行以下NetLogo模拟从R并行运行NetLogo模拟,r,plugins,netlogo,R,Plugins,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) {
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;
}
执行时间最长,应并行运行。我希望在不打开NetLogo的多个实例的情况下以某种方式做到这一点
让问题更清楚:
前提:行为空间并行运行NetLogo模拟
目标:使用从R开始的同一NetLogo实例并并行运行while循环的模拟。我假设您想运行一个实验,改变参数
beta exit
的值并并行使用计算机上的所有可用内核。从R开始,这意味着打开同一NetLogo模型的多个实例,每个实例运行在不同的核心上(这与您声明的目标略有不同)
RNetLogo软件包的创建者Jan Thiele实际上已经为此写了一篇小插曲()
在您的例子中,只改变一个参数,他的示例代码应该正是您想要的。下面是对您的问题的一些修改:
1.一些基本参数:
您可能还想在中查看其他可用于并行计算的函数,这些函数可以代替
parSapply()
您研究过CRAN上的[High performance]任务视图吗?不知道为什么会有人投反对票。对我来说似乎是个明确的问题。现在检查一下。如果这有助于使问题更清楚。谢谢!我会尽快检查
NLCommand ("go");
gui <- TRUE
nl.path <- "C:/Program Files (x86)/NetLogo 5.1.0"
model.path <- "C:/..."
## 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()
}
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"))
## create vector of beta-exit values
i <- seq(0.006, 0.123, 0.009)
## run simulations
result.par <- parSapply(cl, i, simfun)
invisible(parLapply(cl, 1:processors, postpro))
stopCluster(cl)