首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从R并行运行NetLogo仿真

从R并行运行NetLogo仿真
EN

Stack Overflow用户
提问于 2014-11-17 08:54:05
回答 1查看 530关注 0票数 2

如何能够并行运行下面的NetLogo模拟。

代码语言:javascript
复制
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;
}

考虑到这一点,这一声明:

代码语言:javascript
复制
NLCommand ("go");

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

为了使问题更加明确:

前提:行为空间并行运行NetLogo模拟。

目标:使用相同的NetLogo实例,从R开始,并行运行NetLogo循环的仿真。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-18 09:35:52

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

RNetLogo软件包的创建者Jan实际上已经写了一篇关于这一点的文章(链接)。

在你的例子中,只改变一个参数,他的示例代码应该就是你想要的。以下是对您的问题的一些修改:

1.一些基本参数:

代码语言:javascript
复制
gui <- TRUE
nl.path <- "C:/Program Files (x86)/NetLogo 5.1.0"
model.path <- "C:/..."

2.帮助者职能:

代码语言:javascript
复制
## 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.并行计算的设置:

代码语言:javascript
复制
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.并行模拟:

代码语言:javascript
复制
## create vector of beta-exit values
i <- seq(0.006, 0.123, 0.009)

## run simulations
result.par <- parSapply(cl, i, simfun)

5.退出NetLogo并停止集群:

代码语言:javascript
复制
invisible(parLapply(cl, 1:processors, postpro))
stopCluster(cl)

您还可能希望查看雪包中其他可代替parSapply()使用的并行计算函数。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26968817

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档