RNetLogo

Handouts for this lesson need to be saved on your computer. Download and unzip this material into the directory (a.k.a. folder) where you plan to work.

Contents


The R package RNetLogo provides a way to interact with the agent-based modeling platform NetLogo through the R environment with or without a GUI.

Design, store, and analyze results from simulation experiments in a systematic way.

Top of Section


Setup

After installing the RNetLogo package, load the library and define the file path where NetLogo is installed on your computer.

On Windows, the following path is standard.

library(RNetLogo)

nl_path <- "C:/Program Files/NetLogo 5.3.1/app"

Top of Section


Modes

Create an instance of RNetLogo using NLStart(). Use the gui = argument to control which mode to operate in.

NLStart(nl_path, gui = TRUE)
Mode Control in R Control in NetLogo Multiple NetLogo sessions
GUI (default) yes yes no
Headless yes no yes

Quit a session using NLQuit(). Note that if you are running in GUI mode and quit, you will only be able to start NetLogo in a new R session.

Top of Section


Load a NetLogo model

Find the Wolf Sheep model file (with extension “.nlogo”) in the Models Library, and save the full path to a variable.

model_path <- file.path("models", "Sample Models", "Biology", "Wolf Sheep Predation.nlogo")

Load the model with NLLoadModel() by joining the NetLogo prefix to the model path.

NLLoadModel(file.path(nl_path, model_path))

Top of Section


Commands

Execute commands in NetLogo using NLCommand().

NLCommand("setup")             # call the setup routine 
NLCommand("go")                # launch the model from R

Repeat commands using NLDoCommand() and specifying a number of iterations.

NLDoCommand(iterations = 50, "go")

It is possible to submit more than one command at once and in combination with R variables.

init_sheep <- 50
NLCommand("set initial-number-sheep ", init_sheep, "setup")

Remember to call the “setup” routine after changing model parameters.

Top of Section


Reporting

Use NLReport() to get a value or list of values.

NLReport("count sheep")
[1] 50

Or use NLDoReport() to repeat a command and reporter a defined number of times. This function is like a combination of NLReport() and NLDoCommand().

NLDoReport(iterations = 5, command = "go", reporter = "count sheep")
[[1]]
[1] 54

[[2]]
[1] 55

[[3]]
[1] 56

[[4]]
[1] 59

[[5]]
[1] 59

The default output of NLDoReport() is an R list, or you can specify that the output should be a data frame with columns named in the df.col.names argument. Each iteration becomes a row in the data frame. You can use vector of strings to get the results of multiple NetLogo reporters.

NLCommand("setup")
sheep_count <- NLDoReport(iterations = 100, 
                          command = "go", 
                          reporter = c("ticks", "count sheep", "count wolves"),
                          as.data.frame = TRUE,
                          df.col.names = c("tick", "sheep", "wolves"))
tail(sheep_count)
    tick sheep wolves
95    95   831    111
96    96   829    112
97    97   839    122
98    98   840    129
99    99   850    137
100  100   846    141

Top of Section


Report While

Instead of specifying a given number of iterations, you can use the results of a NetLogo reporter to only repeat executing commands while a reporter returns TRUE using NLDoReportWhile().

NLCommand("setup")
sim_results <- NLDoReportWhile(condition = "any? wolves", 
                               command = "go",
                               reporter = c("ticks", "count sheep", "count wolves"),
                               as.data.frame = TRUE,
                               df.col.names = c("tick", "sheep", "wolves"))
head(sim_results)
  tick sheep wolves
1    1    51     51
2    2    55     50
3    3    58     46
4    4    58     48
5    5    58     50
6    6    59     56

Top of Section


Simulation

Streamline the process of executing a model run by defining an R function that runs multiple lines of RNetLogo functions. See the basic R lesson to learn about writing functions in R.

my_sim <- function(n_wolves){
  NLCommand("setup", "set initial-number-wolves", n_wolves)
  NLDoCommandWhile("any? wolves and any? sheep and ticks < 300", "go")
  ret <- NLReport(reporter = "ticks")
  return(ret)
}
my_sim(100)
[1] 187

What are the input and output of this model?

The replicate function makes it easy to run this function multiple times.

replicate(n = 5, expr = my_sim(100))
[1] 189 266 211 170 205

To run the function using different parameters, create a vector to use with an lapply() function

n_wolves <- seq(100, 250, 50)

res <- lapply(n_wolves, function(x) my_sim(x))
head(res)
[[1]]
[1] 176

[[2]]
[1] 190

[[3]]
[1] 205

[[4]]
[1] 300

We can define a function that combines replicate and lapply to repeat a simulation the same number of times for each value in the range of parameters.

rep_sim <- function(n_wolves, reps){
  res <- lapply(n_wolves, function(x) replicate(n = reps, expr = my_sim(x)))
  return(res)
}

sim_results <- rep_sim(n_wolves = seq(100, 250, 50), reps = 5)
head(sim_results)
[[1]]
[1]  81 186 182 205 193

[[2]]
[1] 197 207  65 231 178

[[3]]
[1] 197 247 253 207  68

[[4]]
[1] 209  63  74 108 204

Top of Section


Plotting

To prepare the model output for plotting, let’s combine it with model inputs in a data frame. Remember that the output of the rep_sim() function is coming from an lapply() so it is a list.

n_wolves_rep <- rep(n_wolves, each=5)
df <- data.frame(as.factor(n_wolves_rep), unlist(sim_results))
names(df) <- c("n_wolves", "time")
head(df)
  n_wolves time
1      100   81
2      100  186
3      100  182
4      100  205
5      100  193
6      150  197

Show range of outcomes for each level of initial number of wolves using a boxplot.

library(ggplot2)
ggplot(df, aes(x=n_wolves, y=time)) + 
  geom_boxplot()

plot of chunk unnamed-chunk-3

Top of Section


Agents

Use NLGetAgentSet() for reporting variable values of one or more agents. You will need to know the names of the variable and the name of the agent or agentset. You can only get values from one type of agent at a time.

For example, get the x and y coordinates of all of the wolves using:

NLCommand("setup")

wolf_xy <- NLGetAgentSet(agent.var = c("pxcor", "pycor"), 
              agentset = "wolves")
head(wolf_xy)
  pxcor pycor
1     2   -17
2    25     4
3   -11    18
4    -7   -21
5   -20    17
6    24     0

Set a variable value for one or more agents using NLSetAgentSet().

Top of Section


Patches

Access information about patches using NLGetPatches(). Specify the variable of interest and which patches you are interested in.

Find the color ("pcolor") of the central patch (0, 0) using:

center_pcolor <- NLGetPatches(patch.var = c("pxcor", "pycor", "pcolor"),
             patchset = "patches with [pxcor = 0 and pycor = 0]")
center_pcolor
  pxcor pycor pcolor
1     0     0     55

Set patch variables using NLSetPatches(). Specify the patch variable and a matrix with the same dimensions as your NetLogo world.

By using the code 35 for the color brown, we can kill all the grass using:

NLSetPatches(patch.var = "pcolor", 
             in.matrix = matrix(35, nrow = 51, ncol = 51))

Use NLSetPatchSet() to set variable values for one or more patches instead of the whole landscape.

Top of Section


Review

Function(s) Does what
nl_path <- “%filepath% Define where NetLogo is installed on your computer
NLStart() Begin an instance of NetLogo in gui or headless mode
NLLoadModel() Load a model file
NLCommand(), NLDoCommand() & NLDoCommandWhile() Run commands
NLReport(), NLDoReport() & NLDoReportWhile() Report values
NLGetAgentSet(), NLSetAgentSet() Get & set values for agents
NLGetPatches(), NLSetPatches() & NLSetPatchSet() Get & set values for patches

RNetLogo package comes with sample R code showing implementation of each function in the package. In the RNetLogo folder, find these in examples/code_samples/

References and further reading

Top of Section