Package {nlrx}


Type: Package
Title: Setup, Run and Analyze 'NetLogo' Model Simulations from 'R' via 'XML'
Version: 0.5.0
Description: Setup, run and analyze 'NetLogo' (https://www.netlogo.org) model simulations in 'R'. 'nlrx' experiments use a similar structure as the Behavior Space experiments of 'NetLogo'. However, 'nlrx' offers more flexibility and additional tools for running and analyzing complex simulation designs and sensitivity analyses. The user defines all information that is needed in an intuitive framework, using class objects. Experiments are submitted from 'R' to 'NetLogo' via 'XML' files that are dynamically written, based on specifications defined by the user. Simulations are organised into blocks that each run in one 'NetLogo' instance with several parallel threads, so large simulation designs with many runs can be executed efficiently. This also enables simulating 'NetLogo' experiments on remote high performance computing machines. In order to use this package, 'Java' and 'NetLogo' (>= 7.0.0) need to be available on the executing system.
License: GPL-3
Encoding: UTF-8
LazyData: true
URL: https://docs.ropensci.org/nlrx/, https://github.com/ropensci/nlrx/
BugReports: https://github.com/ropensci/nlrx/issues/
Imports: lhs, sensitivity, dplyr, readr, purrr, magrittr, stats, utils, GenSA, genalg, raster, rstudioapi, sf, tidyr, methods, tibble, crayon, igraph, stringr, progressr, EasyABC, logolink (≥ 1.0.0), cli, janitor, xml2
Depends: R (≥ 4.1.0)
Suggests: testthat, curl, knitr, rmarkdown, covr
VignetteBuilder: knitr
SystemRequirements: NetLogo (>= 7.0.0), Java (>= 11), pandoc, OpenSSL, udunits-2, PROJ.4, GEOS, GDAL, libxml2
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-11-25 09:23:05 UTC; ubuntu
Author: Jan Salecker ORCID iD [aut], Marco Sciaini ORCID iD [aut], Marina Papadopoulou [rev] (Marina reviewed the package for ropensci, see <https://github.com/ropensci/software-review/issues/262>), Sebastian Hanss ORCID iD [cre] (Package maintainer together with Jan Salecker), Marten Hossfeld [aut] (Major maintenance update including NetLogo 7 support and backend redesign)
Maintainer: Sebastian Hanss <nlrx@mailbox.org>
Repository: CRAN
Date/Publication: 2026-11-25 10:30:02 UTC

nlrx: A package for running NetLogo simulations from R.

Description

The nlrx package provides tools to setup NetLogo simulations in R. It uses a similar structure as NetLogos Behavior Space but offers more flexibility and additional tools for running sensitivity analyses.

Details

Get started:

General information that is needed to run NetLogo simulations remotely, such as path to the NetLogo installation folder is stored within a nl class object. Nested within this nl class are the classes experiment and simdesign. The experiment class stores all experiment specifications. After attaching a valid experiment, a simdesign class object can be attached to the nl class object, by using one of the simdesign helper functions. These helper functions create different parameter input matrices from the experiment variable definitions that can then be executed by the run_nl_one() and run_nl_all() functions. The nested design allows to store everything related to the experiment within one R object. Additionally, different simdesign helper functions can be applied to the same nl object in order to repeat the same experiment with different parameter exploration methods (simdesigns).

Step by step application example

The "Wolf Sheep Predation" model from the NetLogo models library is used to present a basic example on how to setup and run NetLogo model simulations from R.

Step 1: Create a nl object:

The nl object holds all information on the NetLogo version, a path to the NetLogo directory with the defined version, a path to the model file, and the desired memory for the java virtual machine. Depending on the operation system, paths to NetLogo and the model need to be adjusted.

library(nlrx)
# Windows default NetLogo installation path (adjust to your needs!):
netlogopath <- file.path("C:/Program Files/NetLogo 7.0.4")
modelpath <- file.path(netlogopath, "models/Sample Models/Biology/Wolf Sheep Predation.nlogox")
outpath <- file.path("C:/out")
# Unix default NetLogo installation path (adjust to your needs!):
netlogopath <- file.path("/home/NetLogo 7.0.4")
modelpath <- file.path(netlogopath, "models/Sample Models/Biology/Wolf Sheep Predation.nlogox")
outpath <- file.path("/home/out")
nl <- nl(nlversion = "7.0.4",
         nlpath = netlogopath,
         modelpath = modelpath,
         jvmmem = 1024)

Step 2: Attach an experiment

The experiment object is organized in a similar fashion as NetLogo Behavior Space experiments. It contains all information that is needed to generate a simulation parameter matrix and to execute the NetLogo simulations. Details on the specific slots of the experiment class can be found in the package documentation (?experiment) and the "Advanced configuration" vignette.

nl@experiment <- experiment(expname="wolf-sheep",
                             outpath=outpath,
                             tickmetrics="true",
                             idsetup="setup",
                             idgo="go",
                             runtime=50,
                             evalticks=seq(40,50),
                             metrics=c("count sheep", "count wolves", "count patches with [pcolor = green]"),
                             variables = list('initial-number-sheep' = list(min=50, max=150, qfun="qunif"),
                                              'initial-number-wolves' = list(min=50, max=150, qfun="qunif")),
                             constants = list("model-version" = "sheep-wolves-grass",
                                              "grass-regrowth-time" = 30,
                                              "sheep-gain-from-food" = 4,
                                              "wolf-gain-from-food" = 20,
                                              "sheep-reproduce" = 4,
                                              "wolf-reproduce" = 5,
                                              "show-energy?" = FALSE))

Step 3: Attach a simulation design

While the experiment defines the variables and specifications of the model, the simulation design creates a parameter input table based on these model specifications and the chosen simulation design method. nlrx provides a bunch of different simulation designs, such as full-factorial, latin-hypercube, sobol, morris and eFast (see "Simdesign Examples" vignette for more information on simdesigns). All simdesign helper functions need a properly defined nl object with a valid experiment design. Each simdesign helper also allows to define a number of random seeds that are randomly generated and can be used to execute repeated simulations of the same parameter matrix with different random-seeds (see "Advanced configuration" vignette for more information on random-seed and replication management). A simulation design is attached to a nl object by using one of the simdesign helper functions:

nl@simdesign <- simdesign_lhs(nl=nl,
                               samples=100,
                               nseeds=3,
                               precision=3)

Step 4: Run simulations

All information that is needed to run the simulations is now stored within the nl object. The run_nl_one() function allows to run one specific simulation from the siminput parameter table. The run_nl_all() function runs a loop over all simseeds and rows of the parameter input table siminput. Simulations are organised into blocks that can be executed in parallel via NetLogo's native multithreading (threads) and, for large designs, distributed across remote HPC machines (see "Advanced configuration" vignette for more information on parallelisation).

results <- run_nl_all(nl = nl)

Step 5: Attach results to nl and run analysis

nlrx provides method specific analysis functions for each simulation design. Depending on the chosen design, the function reports a tibble with aggregated results or sensitivity indices. In order to run the analyze_nl() function, the simulation output has to be attached to the nl object first. After attaching the simulation results, these can also be written to the defined outpath of the experiment object.

# Attach results to nl object:
setsim(nl, "simoutput") <- results
# Write output to outpath of experiment within nl
write_simoutput(nl)
# Do further analysis:
analyze_nl(nl)

Author(s)

Jan Salecker jan.salecker@posteo.de

See Also

Useful links:


Pipe operator

Description

See magrittr::%>% for details.

Usage

lhs %>% rhs

Analyze NetLogo simulation output of simdesign eFast

Description

Analyze NetLogo simulation output of simdesign eFast

Usage

analyze_eFast(nl, metrics, funs)

Arguments

nl

nl object

metrics

vector of strings defining metric columns for evaluation. Defaults to metrics of the experiment within the nl object

funs

list with the summary metrics for the sensitivity results

Details

The function calculates eFast sensitivity indices from the output results using the sensitivity package.


Analyze NetLogo simulation output of simdesign full-factorial

Description

Analyze NetLogo simulation output of simdesign full-factorial

Usage

analyze_ff(nl, metrics, funs)

Arguments

nl

nl object

metrics

vector of strings defining metric columns for evaluation. Defaults to metrics of the experiment within the nl object

funs

list with the summary metrics for the sensitivity results

Details

The function calculates aggregated output metrics by dropping random seeds and aggregating values with the provided functions.


Analyze NetLogo simulation output of simdesign latin-hypercube

Description

Analyze NetLogo simulation output of simdesign latin-hypercube

Usage

analyze_lhs(nl, metrics, funs)

Arguments

nl

nl object

metrics

vector of strings defining metric columns for evaluation. Defaults to metrics of the experiment within the nl object

funs

list with the summary metrics for the sensitivity results

Details

The function calculates aggregated output metrics by dropping random seeds and aggregating values with the provided functions.


Analyze NetLogo simulation output of simdesign morris

Description

Analyze NetLogo simulation output of simdesign morris

Usage

analyze_morris(nl, metrics, funs)

Arguments

nl

nl object

metrics

vector of strings defining metric columns for evaluation. Defaults to metrics of the experiment within the nl object

funs

list with the summary metrics for the sensitivity results

Details

The function calculates morris sensitivity indices from the output results using the sensitivity package.


Analyze NetLogo simulation output

Description

Analyze NetLogo simulation output

Usage

analyze_nl(nl, metrics = getexp(nl, "metrics"), funs = list(mean = mean))

Arguments

nl

nl object

metrics

vector of strings defining metric columns for evaluation. Defaults to metrics of the experiment within the nl object

funs

list with the summary metrics for the sensitivity results

Details

The analyze_nl function runs basic analyses on NetLogo simulation output. In order to execute this function, simulation output needs to be attached to the simdesign first with setsim(nl, "output") <- results.

analyze_nl calls different post-processing analysis functions, depending on the specified method in the simdesign object of the nl object.

The following simdesign are currently supported:

simdesign_ff

Calls analyze_ff. The function calculates aggregated output metrics by dropping random seeds and aggregating values with the provided functions.

simdesign_lhs

Calls analyze_lhs. The function calculates aggregated output metrics by dropping random seeds and aggregating values with the provided functions.

simdesign_sobol

Calls analyze_sobol. The function calculates sobol sensitivity indices from the output results using the sensitivity package.

simdesign_sobol2007

Calls analyze_sobol2007. The function calculates sobol sensitivity indices from the output results using the sensitivity package.

simdesign_soboljansen

Calls analyze_soboljansen. The function calculates sobol sensitivity indices from the output results using the sensitivity package.

simdesign_morris

Calls analyze_morris. The function calculates morris sensitivity indices from the output results using the sensitivity package.

simdesign_eFast

Calls analyze_eFast. The function calculates eFast sensitivity indices from the output results using the sensitivity package.

For the following simdesign no postprocessing analysis function has been implemented yet:

simdesign_simple, simdesign_distinct, simdesign_GenSA, simdesign_GenAlg

Value

analysis summary tibble

Examples


# Load nl object including output data from testdata
nl <- nl_sobol

# Define aggregation measurements:
myfuns <- list(mean=mean, sd=sd, min=min, max=max)

# Calculate sensitivity indices:
analyze_nl(nl, funs = myfuns)


Analyze NetLogo simulation output of simdesign simple

Description

Analyze NetLogo simulation output of simdesign simple

Usage

analyze_simple(nl, metrics, funs)

Arguments

nl

nl object

metrics

vector of strings defining metric columns for evaluation. Defaults to metrics of the experiment within the nl object

funs

list with the summary metrics for the sensitivity results

Details

The simdesign_simple analysis functions is not yet supported and will only print a warning message.


Analyze NetLogo simulation output of simdesign sobol

Description

Analyze NetLogo simulation output of simdesign sobol

Usage

analyze_sobol(nl, metrics, funs)

Arguments

nl

nl object

metrics

vector of strings defining metric columns for evaluation. Defaults to metrics of the experiment within the nl object

funs

list with the summary metrics for the sensitivity results

Details

The function calculates sobol sensitivity indices from the output results using the sensitivity package.


Analyze NetLogo simulation output of simdesign sobol2007

Description

Analyze NetLogo simulation output of simdesign sobol2007

Usage

analyze_sobol2007(nl, metrics, funs)

Arguments

nl

nl object

metrics

vector of strings defining metric columns for evaluation. Defaults to metrics of the experiment within the nl object

funs

list with the summary metrics for the sensitivity results

Details

The function calculates sobol sensitivity indices from the output results using the sensitivity package.


Analyze NetLogo simulation output of simdesign soboljansen

Description

Analyze NetLogo simulation output of simdesign soboljansen

Usage

analyze_soboljansen(nl, metrics, funs)

Arguments

nl

nl object

metrics

vector of strings defining metric columns for evaluation. Defaults to metrics of the experiment within the nl object

funs

list with the summary metrics for the sensitivity results

Details

The function calculates sobol sensitivity indices from the output results using the sensitivity package.


Description

Checks constants and variable formatting of the experiment as required by Logolink

Usage

check_constants_and_variables_logolink(nl)

Arguments

nl

nl object

Details

Checks constants and variable formatting of the experiment, as NetLogo 7+ (or at least Logolink) has different formatting specifications than before.

Value

Character vector of detected issues


Check NetLogo versions

Description

Auxiliary function to check a NetLogo version number against the tested versions

Usage

check_netlogo_version(version, throw_error = FALSE)

Arguments

version

Character string naming which NetLogo Version to check

throw_error

TRUE/FALSE, if TRUE untested versions are reported (see details)

Details

With throw_error = TRUE a version that is not among the tested ones is reported according to how likely it is to work:

Value

logical, TRUE if the version is one of supported_netlogo_versions

Examples

## Not run: 
check_netlogo_version("7.0.0")
check_netlogo_version("1.0")
check_netlogo_version("1.0", TRUE)

## End(Not run)


Helper function for check_constants_and_variables_logolink()

Description

Checks variables and constants for value patterns that nlrx cannot repair

Usage

check_value_format(x, name = NULL)

Arguments

x

value to check

name

optional name of the checked entry

Details

Escaped string quotes and boolean strings are normalized by util_normalize_nl_value and are not reported here. What remains are values that cannot survive the handover to 'logolink' at all: it quotes every character value, so NetLogo literals such as "[1 2 3]" would be passed to the model as a string.

Value

Character vector of detected issues


Backend function for run_nl_all() (NetLogo 7+)

Description

Splits nl@simdesign@siminput into blocks of size block_size, to be executed by run_nl_block()

Usage

create_simulation_blocks(nl, block_size)

Arguments

nl

See run_nl_all()

block_size

See run_nl_all()

Value

A list of data frames, each representing one bundle of simulations


Description

Auxiliary function to download NetLogo

Usage

download_netlogo(to, version, os = NA, extract = FALSE, arch = NA)

Arguments

to

Path to folder where the downloaded file is saved.

version

Character string naming which NetLogo Version to download (see Details)

os

operation system ("win", "mac", "unix") decides which version of netlogo (msi, dmg, tgz) is downloaded. If set to NA (default) os will be detected automatically (util_get_os())

extract

TRUE/FALSE, if TRUE downloaded archive is extracted to subfolder of to (only unix)

arch

macOS architecture of the disk image, "aarch64" (Apple Silicon) or "x86_64" (Intel). If NA (default) the architecture of the running machine is detected (util_get_mac_arch()). Ignored for Windows and Linux, which have one download each.

Details

Retrieve the versions nlrx is tested with (parameter version): supported_netlogo_versions()

Newer NetLogo 7 releases can be downloaded as well: the download URL is derived from the version number, so an untested version only emits a warning (check_netlogo_version) and fails with an error pointing to the NetLogo releases page if no such release exists.

The download (about 400 MB) may take longer than R's default timeout of 60 seconds, so the timeout is raised to at least one hour while it runs.

Value

The path of the downloaded file, invisibly.

Examples

## Not run: 
dlpath <- tempdir()  # adjust path to your needs
try(download_netlogo(dlpath, "7.0.4"))

## End(Not run)


Evaluate input/output integrity

Description

Evaluate input/output integrity

Usage

eval_simoutput(nl)

Arguments

nl

nl object with attached simulation output

Details

This function checks if the attached simulation output in the simoutput slot of the simdesign, corresponds to the defined siminput matrix.

Warning messages are thrown if data is missing in the simoutput tibble. Additionally, missing combinations of siminputrow and random seed for which no data was found can be reported as tibble. Such a tibble can then be used directly to rerun missing combinations conveniently (see examples below)

Examples

## Not run: 
# Check eval_simoutput for testdata nl_lhs:
nl <- nl_lhs
eval_simoutput(nl)

# Now remove one row of simoutput and check output:
nl <- nl_lhs
nl@simdesign@simoutput <- nl@simdesign@simoutput[-1,]
check <- eval_simoutput(nl)
check

# Rerun missing combinations within check tibble:
rerun <- purrr::map_dfr(seq(nrow(check)), function(x) {
  res <- run_nl_one(nl, siminputrow=check$siminputrow[x], seed=check$seed[x])
    return(res)
    }) %>%
      dplyr::bind_rows(., nl@simdesign@simoutput)



## End(Not run)


Evaluate variable validity

Description

Evaluate variables and constants defined in experiment

Usage

eval_variables_constants(nl)

Arguments

nl

nl object

Details

This function checks if the variables and constants that are defined in the experiment are valid. It loads the model code of the NetLogo model and checks if these variables and constants really exist. In case of nonvalid entries, the function throws an error message, indicating which variables and constants are not valid. Please note, that this function might fail if the supported modelpath does not point to an existing nlogo file. This might for example happen, if the modelpath is set up for a remote cluster execution.

Examples

## Not run: 
nl <- nl_lhs
eval_variables_constants(nl)

## End(Not run)


Construct a new experiment object

Description

Construct a new experiment object

Usage

experiment(
  expname = "defaultexp",
  outpath = NA_character_,
  tickmetrics = "true",
  evalticks = NA_integer_,
  idsetup = "setup",
  idgo = "go",
  idfinal = NA_character_,
  idrunnum = NA_character_,
  runtime = 1,
  stopcond = NA_character_,
  metrics = c("count turtles"),
  metrics.turtles = list(),
  metrics.patches = NA_character_,
  metrics.links = list(),
  variables = list(),
  constants = list(),
  ...
)

Arguments

expname

A character string defining the name of the experiment, no whitespaces allowed

outpath

Path to a directory where experiment output will be stored

tickmetrics

Character string "true" runs defined metrics on each simulation tick (or on the ticks in evalticks). "false" runs metrics only after simulation is finished, and evalticks is ignored

evalticks

vector of tick numbers defining when measurements are taken. NA_integer_ to measure each tick

idsetup

character string or vector of character strings, defining the name of the NetLogo setup procedure

idgo

character string or vector of character strings, defining the name of the NetLogo go procedure

idfinal

character string or vector of character strings, defining the name of NetLogo procedures that should be run at the end of each run, after the last tick (BehaviorSpace post run commands)

idrunnum

character string, defining the name of a string input widget in the NetLogo model. Before each run, nlrx writes a run identifier ("expname_seed_siminputrow") into this widget. Model code that writes its own output files (e.g. export-world, file-open) can use it in filenames, which keeps the files of different runs apart and allows matching them to the nlrx results. Must be an interface widget, not a variable declared in globals [], because the value is set before the setup procedure and clear-all would reset a code global. Note: run_nl_dyn() currently passes the same identifier to every evaluation of an optimization. See the article "Capturing NetLogo output manually" for a worked example: https://docs.ropensci.org/nlrx/articles/manual-output.html

runtime

number of model ticks that should be run for each simulation

stopcond

a NetLogo reporter that reports TRUE/FALSE. If it reports TRUE the current simulation run is stopped (e.g. "not any? turtles")

metrics

vector of strings defining valid NetLogo reporters that are taken as output measurements (e.g. c("count turtles", "count patches"))

metrics.turtles

a list with named vectors of strings defining valid turtles-own variables that are taken as output measurements (e.g. list("turtles" = c("who", "pxcor", "pycor", "color"))

metrics.patches

vector of strings defining valid patches-own variables that are taken as output measurements (e.g. c("pxcor", "pycor", "pcolor"))

metrics.links

a list with named vectors of strings defining valid links-own variables that are taken as output measurements (e.g. list("links" = c("end1", "end2")))

variables

a nested list of variables that are changed within a simulation design. The name of each sublist item has to be a valid global of the defined NetLogo model. Depending on the desired simdesign each list item consist of a vector of values, a min value, a max value, a step value and a qfun (e.g. list("paramA" = list(values=c(0, 0.5, 1), min=0, max=1, step=0.1, qfun="qunif")))

constants

a list of constants that are kept constant within a simulation design. The name of each list item has to be a valid global of the defined NetLogo model. Give strings as plain character values and booleans as logicals (e.g. list("pNUM" = 12, "pLOGIC" = TRUE, "pSTRING" = "default")). The escaped-quote convention of nlrx < 0.5.0 ("\"default\"") and boolean strings ("true") are still accepted and repaired silently.

...

...

Details

The experiment class stores all information related to the NetLogo simulation experiment. The class holds all information that is typically entered into NetLogo Behavior Space experiments. When setting up an experiment, it is usually attached to an already defined nl object (see examples). After attaching an experiment, different simdesign helper functions can be used to attach a simdesign to the nl object simdesign. The simdesign helper functions use the variable definitions from the experiment within the nl object to generate a parameter tibble for simulations.

The following class slots are obligatory to run an experiment:

tickmetrics

If "true", the defined output reporters are collected on each simulation tick that is defined in evalticks. If "false" measurements are taken only on the last tick.

evalticks

Only applied if tickmetrics = TRUE. Evalticks may contain a vector of integers, defining the ticks for which the defined metrics will be measured. Set evalticks to NA_integer_ to measure on every tick.

idsetup, idgo

These two class slots accept strings, or vectors of strings, defining NetLogo model procedures that should be executed for model setup (idsetup) and model execution (idgo).

runtime

Defines the maximum number of simulation ticks that are executed. Use 0 or NA_integer_ to execute simulations without predefined number of ticks. Warning: This is only recommended in combination with a stop condition (see slot stopcond), or NetLogo models with a built-in stop condition. Otherwise, simulations might get stuck in endless loops.

Depending on the simdesign, the following slots may be obligatory:

metrics

A vector of valid netlogo reporters that defines which measurements are taken. The optimization simdesigns need at least one defined metrics reporter for fitness calculation of the optimization algorithm.

constants, variables

These slots accept lists with NetLogo parameters that should be varied within a simdesign (variables) or should be kept constant (constants) for each simulation. Any NetLogo parameter that is not entered in at least one of these two lists will be set up as constant with the default value from the NetLogo interface. It is not possible to enter a NetLogo parameter in both lists (a warning message will appear when a simdesign is attached to such an experiment). All simdesigns except simdesign_simple need defined variables for setting up a parameter matrix. Variables can be defined as distinct values, value distributions or range with increment. The information that is needed, depends on the chosen simdesign (details on variable definition requirements can be found in the helpfiles of each simdesign helper function).

All remaining slots are optional:

expname

A character string defining the name of the experiment, useful for documentation purposes. The string must not contain any whitespaces.

outpath

A valid path to an existing directory. The directory is used by the write_simoutput function to store attached simulation results to disk in csv format.

idfinal

A character string or vector of strings defining NetLogo procedures that are executed at the end of each simulation (e.g. cleanup or self-written output procedures).

idrunnum

This slot can be used to transfer the current nlrx experiment name, random seed and runnumber (siminputrow) to NetLogo. To use this functionality, a string input field widget needs to be created on the GUI of your NetLogo model. The name of this widget can be entered into the "idrunnum" field of the experiment. During simulations, the value of this widget is automatically updated with a generated string that contains the current nlrx experiment name, random seed and siminputrow ("expname_seed_siminputrow"). For self-written output In NetLogo, we suggest to include this global variable which allows referencing the self-written output files to the collected output of the nlrx simulations in R.

stopcond

The stopcond slot can be used to define a stop condition by providing a string with valid NetLogo code that reports either true or false. Each simulation will be stopped automatically, once the reporter reports true.

metrics.patches

The metrics.patches slot accepts a vector of valid patches-own variables of the NetLogo model. These patch variables are measured in addition to the defined metrics. Results of these metrics will be nested inside the output results tibble of the simulations. Please note that NetLogo models may contain a huge number of patches and output measurements of agent variables on each tick may need a lot of ressources.

metrics.turtles

The metrics.turtles slot accepts a list with named vectors of valid turtle breed metrics. Each name of a vector in this list defines a specified breed of the NetLogo model, whereas the vector defines the variables that are measured for this breed. For example metrics.turtles = list("sheep"=c("color"), "wolves"=c("who")) - would measure the color of each sheep and the who number of each wolf agent. To measure turtles-own variables for all turtles, use "turtles" = c(...). Be aware, that NetLogo will produce runtime errors if you measure breed-own variables for agents that do not belong to this breed. Please note that NetLogo models may contain a huge number of turtles and output measurements of agent variables on each tick may need a lot of ressources.

metrics.links

The metrics.links slot accepts a list with named vectors of valid link breed metrics. Each name of a vector in this list defines a specified link breed of the NetLogo model, whereas the vector defines the variables that are measured for this link breed. For example metrics.links = list("linktype-a"=c("end1"), "linktype-b"=c("end2")) - would measure the start agent of each linktype-a link and the end agent of each linktype-b link. To measure links-own variables for all links, use "links" = c(...). Be aware, that NetLogo will produce runtime errors if you measure link-breed-own variables for agents that do not belong to this breed. Please note that NetLogo models may contain a huge number of turtles and output measurements of agent variables on each tick may need a lot of ressources.

Value

experiment S4 class object

Examples


# To attach an experiment, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

# Example for Wolf Sheep Predation model from NetLogo models library:
nl <- nl_simple
nl@experiment <- experiment(expname="wolf-sheep",
                             outpath="C:/out/",
                             tickmetrics="true",
                             evalticks=seq(40,50),
                             idsetup="setup",
                             idgo="go",
                             idfinal=NA_character_,
                             idrunnum=NA_character_,
                             runtime=50,
                             stopcond="not any? turtles",
                             metrics=c("count sheep",
                                       "count wolves",
                                     "count patches with [pcolor = green]"),
                             metrics.turtles=list("turtles" = c("who",
                                               "pxcor",
                                               "pycor",
                                               "color")),
                             metrics.patches=c("pxcor", "pycor", "pcolor"),
                             variables = list('initial-number-sheep' =
                             list(min=50, max=150, step=10, qfun="qunif"),
                                              'initial-number-wolves' =
                             list(min=50, max=150, step=10, qfun="qunif")),
                             constants = list("model-version" =
                                              "sheep-wolves-grass",
                                              "grass-regrowth-time" = 30,
                                              "sheep-gain-from-food" = 4,
                                              "wolf-gain-from-food" = 20,
                                              "sheep-reproduce" = 4,
                                              "wolf-reproduce" = 5,
                                              "show-energy?" = FALSE))



Export NetLogo Experiment

Description

Export NetLogo Experiment as tar.gz file

Usage

export_nl(nl, path = dirname(getnl(nl, "modelpath")), tarfile)

Arguments

nl

nl object

path

Path to folder that contains files to run NetLogo experiment

tarfile

Path to the tar.gz file the experiment gets stored in

Details

Exports your folder that contains data and scripts for NetLogo + nlrx analyses as a tar.gz file. Furthermore, export_nl takes your nl object and saves it as nlobject.rds in the archived folder. This enables other person to run the same experiment as you. The folder itself is not changed.

By default, the folder that contains the NetLogo model is exported. Everything in that folder ends up in the archive, so keep the model in a project folder of its own. The home directory and the filesystem root are refused, and the tar.gz file must not be stored within the exported folder.

Value

The path of the created tar.gz file, invisibly.

Examples

## Not run: 

# Load nl object from testdata:
nl <- nl_lhs
path <- getwd() # adjust path to your needs, path should point to a directory with model data
outfile <- tempfile(fileext = ".tar.gz") # adjust file path to your needs
export_nl(nl, path = path, tarfile = outfile)

## End(Not run)

Getter function to get a variable of an experiment object

Description

Getter function to get a variable of an experiment object

Usage

getexp(nl, var)

Arguments

nl

nl object

var

valid experiment variable string

Examples

# Example for Wolf Sheep Predation model from NetLogo models library:
nl <- nl(nlversion = "7.0.4",
nlpath = "/home/user/NetLogo 7.0.4/",
modelpath = "/home/user/NetLogo 7.0.4/models/Sample Models/Biology/Wolf Sheep Predation.nlogox",
jvmmem = 1024)

# Set experiment name
setexp(nl, "expname") <- "experimentName"

# Get experiment name
getexp(nl, "experiment")


Getter function to get a variable of a nl object

Description

Getter function to get a variable of a nl object

Usage

getnl(nl, var)

Arguments

nl

nl object

var

valid nl variable string

Examples


# Example for Wolf Sheep Predation model from NetLogo models library:
nl <- nl(nlversion = "7.0.4",
nlpath = "/home/user/NetLogo 7.0.4/",
modelpath = "/home/user/NetLogo 7.0.4/models/Sample Models/Biology/Wolf Sheep Predation.nlogox",
jvmmem = 1024)

# get NetLogo version
getnl(nl, "nlversion")


Getter function to get a variable of a simdesign object

Description

Getter function to get a variable of a simdesign object

Usage

getsim(nl, var)

Arguments

nl

nl object

var

valid simdesign variable string

Examples

# Example for Wolf Sheep Predation model from NetLogo models library:
nl <- nl(nlversion = "7.0.4",
nlpath = "/home/user/NetLogo 7.0.4/",
modelpath = "/home/user/NetLogo 7.0.4/models/Sample Models/Biology/Wolf Sheep Predation.nlogox",
jvmmem = 1024)

# Set simulation seeds
setsim(nl, "simseeds") <- c(123, 456, 789)

# Set simulation seeds
getsim(nl, "simseeds")


Import NetLogo Experiment

Description

Import NetLogo Experiment from export_nl

Usage

import_nl(tarfile, targetdir, new_session = FALSE)

Arguments

tarfile

Path to tarfile that contains files to run NetLogo experiment

targetdir

Path to folder where the experiments gets extracted

new_session

If TRUE, opens a new RStudio Session with an Rproj

Details

Imports NetLogo experiments that were saved with export_nl. The archived folder is extracted into targetdir and the nl object stored with it is returned. If the folder comes with an .Rproj file (which is recommended because relative paths enhance the reproducability of your analysis), import_nl can open this project in a new RStudio session (new_session = TRUE).

Note that the paths stored in the nl object (nlpath, modelpath, outpath) still point to the locations on the machine the experiment was exported from.

Value

The imported nl object, invisibly.

Examples

## Not run: 

infile <- "/home/user/test.tar.gz"
targetdirectory <- "/home/user/test"
nl <- import_nl(infile, targetdirectory)

## End(Not run)

initClasses

Description

empty

Usage

.initClasses()

Backend function for run_nl_all()

Description

Merges results produced by run_nl_block() into one tibble. Temporarily handles column name restoration until logolink supports preserving original column names.

Usage

merge_result_blocks(nl, results_list)

Arguments

nl

See run_nl_all()

results_list

List of result tibbles returned by run_nl_block()

Value

Tibble with simulation output results


Construct a new nl object

Description

Construct a new nl object

Usage

nl(
  nlversion = "7.0.4",
  nlpath = Sys.getenv("NETLOGO_HOME"),
  modelpath = character(),
  jvmmem = 1024,
  experiment = methods::new("experiment"),
  simdesign = methods::new("simdesign"),
  check_version = TRUE,
  ...
)

Arguments

nlversion

A character string defining the NetLogo version that is used

nlpath

Path to the NetLogo main directory matching the defined version. Defaults to the NETLOGO_HOME environment variable, so it can be omitted when that is set. When a path is given, it takes precedence: it is used for the duration of each run_nl_all / run_nl_one / run_nl_dyn call, so one nl object can be run against a different NetLogo installation than another without changing the session

modelpath

Path to the NetLogo model file (.nlogox) that is used for simulations. NetLogo 6 model files (.nlogo) are rejected; open them in NetLogo 7 and save them to convert them. Since NetLogo 6.3.0 the models shipped with NetLogo are stored at the installation root, so a sample model is reached with file.path(nlpath, "models/Sample Models/...")

jvmmem

Java virtual machine memory capacity in megabytes

experiment

Holds a experiment S4 class object

simdesign

Holds a simdesign S4 class object

check_version

Logical. If TRUE (default), the NetLogo version is checked against the versions nlrx is tested with (supported_netlogo_versions): an untested NetLogo 7.x version emits a warning and is accepted, a version below 7.0.0 is an error. Set to FALSE to silence the warning.

...

...

Details

nl objects are the main class objects used in the nlrx package. These objects store all information that is needed to run NetLogo simulations. nl objects are initialized with basic information on Netlogo and the model.

After setting up the nl object, an experiment needs to be attached. The experiment class stores all information related to the NetLogo simulation experiment, such as runtime, variables, constants, measurements, and more.

After attaching an experiment, different simdesign helper functions can be used to attach a simdesign to the nl object. The simdesign helper functions use the variable definitions from the experiment within the nl object to generate a parameter tibble for simulations.

Value

nl S4 class object

Examples

# Example for Wolf Sheep Predation model from NetLogo models library:
# Windows default NetLogo installation path (adjust to your needs!):
netlogopath <- file.path("C:/Program Files/NetLogo 7.0.4")
modelpath <- file.path(netlogopath, "models/Sample Models/Biology/Wolf Sheep Predation.nlogox")
outpath <- file.path("C:/out")
# Unix default NetLogo installation path (adjust to your needs!):
netlogopath <- file.path("/home/NetLogo 7.0.4")
modelpath <- file.path(netlogopath, "models/Sample Models/Biology/Wolf Sheep Predation.nlogox")
outpath <- file.path("/home/out")

nl <- nl(nlversion = "7.0.4",
         nlpath = netlogopath,
         modelpath = modelpath,
         jvmmem = 1024)


Wolf Sheep model sample data: simdesign distinct

Description

The dataset contains a complete nl object. The nl object has been used to setup and run a distinct simulation design. It also contains the model outputs within the simdesign object.

Usage

nl_distinct

Format

nl object with defined experiment, simdesign and model output


Wolf Sheep model sample data: simdesign eFast

Description

The dataset contains a complete nl object. The nl object has been used to setup and run an eFast simulation design. It also contains the model outputs within the simdesign object. Further analysis output can be derived by submitting the dataset to analyze_nl().

Usage

nl_eFast

Format

nl object with defined experiment, simdesign and model output


Wolf Sheep model sample data: simdesign ff

Description

The dataset contains a complete nl object. The nl object has been used to setup and run a full-factorial simulation design. It also contains the model outputs within the simdesign object. Further analysis output can be derived by submitting the dataset to analyze_nl().

Usage

nl_ff

Format

nl object with defined experiment, simdesign and model output


Wolf Sheep model sample data: gensa

Description

The dataset contains a complete nl object. The nl object has been used to setup and run a simulated annealing simulation design.

Usage

nl_gensa

Format

nl object with defined experiment, simdesign and model output


Wolf Sheep model sample data: simdesign lhs

Description

The dataset contains a complete nl object. The nl object has been used to setup and run a latin hypercube simulation design. It also contains the model outputs within the simdesign object. Further analysis output can be derived by submitting the dataset to analyze_nl().

Usage

nl_lhs

Format

nl object with defined experiment, simdesign and model output


Wolf Sheep model sample data: simdesign morris

Description

The dataset contains a complete nl object. The nl object has been used to setup and run a morris simulation design. It also contains the model outputs within the simdesign object. Further analysis output can be derived by submitting the dataset to analyze_nl().

Usage

nl_morris

Format

nl object with defined experiment, simdesign and model output


Wolf Sheep model sample data: simdesign simple

Description

The dataset contains a complete nl object. The nl object has been used to setup and run a simple simulation design. It also contains the model outputs within the simdesign object.

Usage

nl_simple

Format

nl object with defined experiment, simdesign and model output


Wolf Sheep model sample data: simdesign sobol

Description

The dataset contains a complete nl object. The nl object has been used to setup and run a sobol simulation design. It also contains the model outputs within the simdesign object. Further analysis output can be derived by submitting the dataset to analyze_nl().

Usage

nl_sobol

Format

nl object with defined experiment, simdesign and model output


Wolf Sheep model sample data: simdesign sobol2007

Description

The dataset contains a complete nl object. The nl object has been used to setup and run a sobol2007 simulation design. It also contains the model outputs within the simdesign object. Further analysis output can be derived by submitting the dataset to analyze_nl().

Usage

nl_sobol2007

Format

nl object with defined experiment, simdesign and model output


Wolf Sheep model sample data: simdesign soboljansen

Description

The dataset contains a complete nl object. The nl object has been used to setup and run a soboljansen simulation design. It also contains the model outputs within the simdesign object. Further analysis output can be derived by submitting the dataset to analyze_nl().

Usage

nl_soboljansen

Format

nl object with defined experiment, simdesign and model output


Wolf Sheep model sample data: spatial

Description

The dataset contains a complete nl object. The nl object has been used to setup and run a simple simulation design. For these simulations, spatial agent output has been collected. metrics.turtles was set up to measure turtle coordinates. metrics.patches was set up to measure colors of cells. It also contains the model outputs within the simdesign object.

Usage

nl_spatial

Format

nl object with defined experiment, simdesign and model output


Generate igraph objects from measured turtles and links metrics

Description

Generate igraph objects from measured turtles and links metrics

Usage

nl_to_graph(nl)

Arguments

nl

nl object

Generate igraph objects from measured turtles and links metrics. Output has to be attached to the simdesign first with simoutput(nl) <- results I graph objects are created automatically for each combination of random-seed, siminputrow and step. An additional column with igraph objects is attached to the original output results tibble of the nl object. In order to generate igraph objects some metrics are mandatory: The metrics.turtles slot of the experiment must contain "who" numbers (see example experiment). Additional turtle metrics will be stored as properties of the igraph vertices. The metrics.links slot of the experiment must contain "who" numbers of link end1 and end2 (see example experiment). Additional link metrics will be stored as properties of the igraph edges.

Examples

## Not run: 
## Example running the Giant Component model from the NetLogo models library:
library(nlrx)
library(igraph)
# Windows default NetLogo installation path (adjust to your needs!):
netlogopath <- file.path("C:/Program Files/NetLogo 7.0.4")
modelpath <- file.path(netlogopath, "models/Sample Models/Networks/Giant Component.nlogox")
outpath <- file.path("C:/out")
# Unix default NetLogo installation path (adjust to your needs!):
netlogopath <- file.path("/home/NetLogo 7.0.4")
modelpath <- file.path(netlogopath, "models/Sample Models/Networks/Giant Component.nlogox")
outpath <- file.path("/home/out")

nl <- nl(nlversion = "7.0.4",
         nlpath = netlogopath,
         modelpath = modelpath,
         jvmmem = 1024)

nl@experiment <- experiment(expname="networks",
                            outpath=outpath,
                            tickmetrics="false",
                            idsetup="setup",
                            idgo="go",
                            runtime=50,
                            metrics.turtles = list("turtles" = c("who", "color")),
                            metrics.links = list("links" = c("[who] of end1", "[who] of end2")),
                            constants = list("num-nodes" = 80,
                                             "layout?" = TRUE))

nl@simdesign <- simdesign_simple(nl, 1)
nl@simdesign@simoutput <- run_nl_all(nl)
nl.graph <- nl_to_graph(nl)

## Extract graph of tick 1:
nl.graph.i <- nl.graph$spatial.links[[1]]
## Set vertex colors by measured color variable:
vcols <- c("7" = "grey", "15" = "red")
V(nl.graph.i)$color <- vcols[as.character(V(nl.graph.i)$color)]
## Set edge colors by measured link breed:
ecols <- c("links" = "black")
E(nl.graph.i)$color <- ecols[E(nl.graph.i)$breed]

## Plot:
plot.igraph(nl.graph.i, vertex.size=8, vertex.label=NA, edge.arrow.size=0.2)


## End(Not run)

Get spatial data from metrics.turtles output

Description

Turn turtle metrics from NetLogo in spatial data objects

Usage

nl_to_points(nl, coords)

Arguments

nl

nl object

coords

nl object

Details

Converts measured metrics.turtles into spatial sf point objects. In order to so, a pair of turtle coordinates needs to be measured. Any additional metrics will be stored as properties of the spatial points. Because turtle coordinates in NetLogo can be measured in two formats, pxcor/pycor or xcor/ycor coordinates, the type of coordinate used for transformation to spatial objects need to be defined, using the parameter coords: "px" for pxcor/pycor coordinates, "x" for xcor/ycor coordinates.

In order to use this function, simulation results need to be attached to the nl object first.

Value

tibble with spatial data objects

Examples


# Load nl object (with spatial output data already attached) from test data:
nl <- nl_spatial

# Convert turtle metrics (pxcor/pycor) to spatial point objects:
results.sf <- nl_to_points(nl, coords="px")



Get spatial data from metrics.patches output

Description

Turn patch metrics from NetLogo in spatial data objects

Usage

nl_to_raster(nl)

Arguments

nl

nl object

Details

Converts measured metrics.patches into spatial raster objects. In order to so, a patch coordinates needs to be measured (pxcor/pycor). For each additional patch metric, a raster will be created using the measured coordinates as x and y and the additional metric as z dimension. In case of multiple measured metrics, a raster stack with one raster for each metric will be reported.

In order to use this function, simulation results need to be attached to the nl object first.

Value

tibble with spatial data objects

Examples


# Load nl object (with spatial output data already attached) from test data:
nl <- nl_spatial

# Convert patch metrics to spatial raster objects:
results.raster <- nl_to_raster(nl)


Create NetLogo documentation

Description

Create NetLogo documentation

Usage

nldoc(
  modelfiles,
  outpath,
  infotab = TRUE,
  gui = TRUE,
  bs = TRUE,
  output_format = "html",
  number_sections = TRUE,
  theme = "journal",
  date = as.Date(Sys.time()),
  toc = TRUE
)

Arguments

modelfiles

vector of filepaths to model files

outpath

Path to folder where rendered documentation should be created

infotab

TRUE/FALSE, if TRUE infotab section will be included in the documentation

gui

TRUE/FALSE, if TRUE a table with GUI elements from the model will be included in the documentation

bs

TRUE/FALSE, if TRUE a table with behavior space experiments will be included in the documentation

output_format

either "html", "pdf" or "docx"

number_sections

TRUE/FALSE, if TRUE sections in the documentation will be numbered

theme

markdown theme, supported themes are "journal", "cerulean", "flatly", "readable", "spacelab", "united", "cosmo"

date

date that is printed in the documentation header

toc

TRUE/FALSE, if TRUE the documentation contains a table of contents - only for html and pdf output format

Details

nldoc reads model code from the provided model files. The code is then split into several groups (code, gui, behavior space). The procedures then finds noxygen commands within the NetLogo model code. The noxygen commands are listed in the nldoc article: https://docs.ropensci.org/nlrx/articles/nlrx_nldoc.html. Without a @model header, the name of the model file is used as title. These commands are translated into a markdown documentation file. If needed, tables of gui elements and behavior space experiments are added to the markdown file. Finally, the document is rendered in the specified format.

Examples

## Not run: 

# List model files (.nls subfiles are also supported)
modelfiles <- c("https://raw.githubusercontent.com/nldoc/nldoc_pg/master/WSP.nlogox",
                "https://raw.githubusercontent.com/nldoc/nldoc_pg/master/WSP.nls")

# Define output directory:
outdir <- tempdir()  # adjust path to your needs

# Create documentation:
nldoc(modelfiles = modelfiles,
      infotab=TRUE,
      gui=TRUE,
      bs=TRUE,
      outpath = outdir,
      output_format = "html",
      number_sections = TRUE,
      theme = "cosmo",
      date = date(),
      toc = TRUE)

## End(Not run)


Read the value sets of a behavior space experiment

Description

Read the enumerated and stepped value sets of a behavior space experiment (constants) or sub-experiment

Usage

nldoc_bs_valuesets(node)

Arguments

node

xml node holding the value sets

Value

tibble with the columns name, type and values


Determine procedure calls

Description

Determine procedure calls

Usage

nldoc_find_procedure_calls(nlogocode)

Arguments

nlogocode

vector of netlogo code strings

Details

The procedure searches netlogo code for procedure definitions and calls. The information is stored within a tibble that can be further processed.

Value

tibble with procedure names and procedure calls


Escape text for a markdown table cell

Description

Escapes pipes and removes line breaks, which would end the cell or the row of a markdown table

Usage

nldoc_md_cell(x)

Arguments

x

character vector

Value

escaped character vector


Create NetLogo procedure network

Description

Create NetLogo procedure network

Usage

nldoc_network(modelfiles)

Arguments

modelfiles

vector of filepaths to model files

Details

Reads model code from the provided model files. The procedure identifies NetLogo procedures and searches for procedure calls within the code. From this data, an igraph network is created and returned. This network can be used to plot the model procedure network and identify model components.

Value

network of model procedures (igraph)

Examples

## Not run: 

# List model files (.nls subfiles are also supported)
modelfiles <- c("https://raw.githubusercontent.com/nldoc/nldoc_pg/master/WSP.nlogo",
                "https://raw.githubusercontent.com/nldoc/nldoc_pg/master/WSP.nls")

# Determine the function network:
nw <- nldoc_network(modelfiles)

# Determine communities within the network and plot using Igraph package:
library(igraph)
com <- walktrap.community(nw)
V(nw)$community <- com$membership
rain <- rainbow(14, alpha=.5)
V(nw)$color <- rain[V(nw)$community]

plot(nw,
     edge.arrow.size=.2,
     vertex.label.color="black",
     vertex.label.dist=1,
     vertex.size=5,
     edge.curved=0,
     vertex.label.cex=.5,
     layout=layout_with_fr(nw, niter = 2000))

# Interactive plot using igraph::tkplot
tkplot(nw, layout=layout_with_fr(nw, niter = 2000))

## End(Not run)

Parse model code

Description

Parse model code

Usage

nldoc_parse_modelcode(nlogocode)

Arguments

nlogocode

vector of netlogo code strings

Details

The procedure searches for noxygen commands within the NetLogo code. This information is used to structure the netlogo code strings in a tibble. Additionally, tibbles with gui and behavior space information are created.

Value

tibble with structured netlogo code


Read NetLogo model code from files

Description

Read NetLogo model code from files

Usage

nldoc_read_nlogox(modelfiles)

Arguments

modelfiles

vector of filepaths to model files

Details

The procedure reads text from the provided model files and reports the code as a vector of strings.

Value

vector of strings containing NetLogo model code


Read NetLogo behavior space experiments from files

Description

Read NetLogo behavior space experiments from files

Usage

nldoc_table_bs(modelfiles)

Arguments

modelfiles

vector of filepaths to model files

Details

The procedure reads the behavior space experiments of the main model file (.nlogox) and reports one list per experiment: its name, the definitions (procedures, time limit, metrics, ...) as a named character vector, the parameters (constants) and the parameter sets of its subexperiments as tibbles with the columns name, type and values.

Value

list containing NetLogo behavior space experiments


Read NetLogo GUI elements from files

Description

Read NetLogo GUI elements from files

Usage

nldoc_table_gui(modelfiles)

Arguments

modelfiles

vector of filepaths to model files

Details

The procedure reads the parameter widgets (sliders, switches, input boxes and choosers) of the main model file (.nlogox) and reports a list of GUI elements.

Value

list containing NetLogo GUI elements, or NA if the model has none


Write NetLogo documentation

Description

Write NetLogo documentation

Usage

nldoc_write_nldoc(
  noxygen,
  noxygen_it,
  noxygen_gui,
  noxygen_bs,
  outpath,
  output_format,
  number_sections,
  theme,
  date,
  toc,
  modelname = "Untitled Model"
)

Arguments

noxygen

list with parsed and processed noxygen tags from NetLogo model code

noxygen_it

list with parsed and processed infotab strings

noxygen_gui

list with parsed and processed noxygen tags from NetLogo GUI elements

noxygen_bs

list with parsed and processed noxygen tags from NetLogo behavior space experiments

outpath

Path to folder where rendered documentation should be created

output_format

either "html", "pdf" or "docx"

number_sections

TRUE/FALSE, if TRUE sections in the documentation will be numbered

theme

markdown theme, supported themes are "journal", "cerulean", "flatly", "readable", "spacelab", "united", "cosmo"

date

date that is printed in the documentation header

toc

TRUE/FALSE, if TRUE the documentation contains a table of contents - only for html and pdf output format

modelname

title of the documentation if the model code has no @model header

Details

The procedure uses parsed and processed noxygen tags to create and render a markdown documentation in the specified format.

Value

list containing NetLogo GUI elements


Print content of nl object

Description

Print content of nl object and embedded experiment and simdesign objects to console

Usage

## S3 method for class 'nl'
print(x, ...)

Arguments

x

nl object to print

...

further arguments passed to or from other methods

Details

Print content of the provided nl object in a readable format.

Examples


print(nl_lhs)


Report globals from a NetLogo model that is defined within a nl object

Description

Report globals from a NetLogo model that is defined within a nl object

Usage

report_model_parameters(nl)

Arguments

nl

nl object with a defined modelpath that points to a NetLogo model (.nlogox)

Details

The function reads the NetLogo model file that is defined within the nl object and reports all global parameters that are defined as widget elements on the GUI of the NetLogo model. Only globals that are found by this function are valid globals that can be entered into the variables or constants vector of an experiment object.

Examples

## Not run: 
nl <- nl_lhs
report_model_parameters(nl)

## End(Not run)


Execute all NetLogo simulations from a nl object

Description

Execute all NetLogo simulations from a nl object with a defined experiment and simdesign

Usage

run_nl_all(nl, block_size = 100, threads = 1, ...)

Arguments

nl

nl object

block_size

number of simulations bundled into one execution block (one NetLogo instance can only receive one block).

threads

number of NetLogo threads used for execution (handled via NetLogo).

...

additional arguments; currently only used to detect and warn about arguments that were deprecated in earlier nlrx versions.

Details

run_nl_all executes all simulations of the specified NetLogo model within the provided nl object.

The function structures the simdesign table into blocks, sized via block_size. Each block is passed to logolink, which writes a BehaviorSpace XML file and executes it.

Multithreading is supported via NetLogo natively, and controlled using threads. See how many threads you can assign using parallel::detectCores().

Progress can be shown by wrapping run_nl_all() with progressr (see examples). Progress updates on completion of one block.

Small block_size results in frequent updates of simulation status, but causes simulations to take longer, as NetLogo has to restart after every block. Large block_size results in infrequent updates but will generally be faster (although with rapidly diminishing returns).

Debugging:

Make sure you can run your NetLogo model on your machine. Make sure that Java is installed and available from the terminal (java -version). Use eval_variables_constants(nl) to check the validity of model settings. Lastly, the R console outputs XML filepaths. These XML files are BehaviorSpace definitions. Run these manually via NetLogo BehaviorSpace to diagnose issues with the experiment and simdesign setup.

Value

tibble with simulation output results

Reproducibility and Seeds

Every simulation is executed with an explicit random seed, taken from the nseeds seeds of the attached simdesign (nl@simdesign@simseeds). NetLogo is seeded with that value and reports it back, so each row of the results can be traced to the parameterisation (siminputrow) and the seed (random-seed) that produced it. Re-running a design with the same seeds therefore reproduces the results exactly. To replicate a parameterisation under different stochasticity, increase nseeds in the simdesign helper.

Suppressing Messages

Informational messages (e.g., XML file paths) are displayed using the cli package. To suppress these messages, wrap the function call with suppressMessages(), e.g., suppressMessages(run_nl_all(nl)).

Examples

## Not run: 

# Load nl object from test data:
nl <- nl_lhs

# Execute all simulations from an nl object with properly attached simdesign.
results <- run_nl_all(nl)

# Run in parallel on local machine (NetLogo 7+):
library(progressr)
with_progress({ # progress bar
results <- run_nl_all(nl, threads = 10) # 10 threads
})

# Adjust block size for performance tuning:
# Larger block_size means fewer NetLogo restarts (re-initialized once per block):
results <- run_nl_all(nl, block_size = 500, threads = 10)

## End(Not run)

Backend function used by run_nl_all() and run_nl_one() to run simulations (NetLogo 7+)

Description

Creates a BehaviorSpace XML file for simulations defined in block_df and executes them via logolink

Usage

run_nl_block(nl, block_df, block_number, threads)

Arguments

nl

See run_nl_all()

block_df

Data frame of simulation definitions, with one row being one run

block_number

Assigned by run_nl_all(), used for naming the XML file.

Details

Runs a single block (block_df) by writing a single BehaviorSpace XML file and executing it via logolink.

Value

Tibble with simulation output results


Execute NetLogo simulation without pregenerated parametersets

Description

Execute NetLogo simulation from a nl object with a defined experiment and simdesign but no pregenerated input parametersets

Usage

run_nl_dyn(nl, threads = 1, nreplicates = 1, ...)

Arguments

nl

nl object

threads

number of NetLogo threads used for execution (handled via NetLogo).

nreplicates

number of replicated model runs per evaluation of the dynamic design (default 1)

...

additional arguments; currently only used to detect and warn about arguments that were deprecated in earlier nlrx versions.

Details

run_nl_dyn can be used for simdesigns where no predefined parametersets exist. This is the case for dynamic designs, such as Simulated Annealing and Genetic Algorithms, where parametersets are dynamically generated, based on the output of previous simulations.

Simulations are executed sequentially, one parameterization at a time, as each new parameterization depends on the results of the previous simulation. Internally, each simulation step is executed via run_nl_one().

One complete optimization is executed for each random seed of the simdesign (nl@simdesign@simseeds, defined by the nseeds argument of the simdesign helper functions). The optimizations are independent of each other and are executed one after another. To run only some of the seeds, for example to distribute them over the nodes of a cluster, reduce the seed vector of the simdesign beforehand with setsim(nl, "simseeds") <- ....

The returned tibble contains one row per seed, with the seed in the seed column and the result of the optimization in the result list column. Results are stored as the objects that the respective optimization package returns (GenSA, genalg, EasyABC), so that the summary and plot functions of these packages can be applied to them, for example results$result[[1]].

If an optimization fails, the loop is not interrupted: the error is stored in the result column of the respective seed, a warning lists the failed seeds, and the results of the remaining seeds are returned.

Value

tibble with one row per random seed of the simdesign, with the columns seed and result

Replicated evaluations

Dynamic designs evaluate a stochastic model, so every evaluation of the objective carries simulation noise. With nreplicates > 1, each parameterisation proposed by the algorithm is simulated nreplicates times with different random seeds, and the reported value is aggregated over these replicates. Aggregation happens in two steps: first the mean over all measured ticks within a replicate, then the mean over the replicates. The replicated runs of one evaluation are executed within a single NetLogo instance, so threads can be used to run them in parallel.

The replicate seeds are derived from the seed of the respective optimization and are identical for every evaluation of that optimization. Reusing the same seeds across evaluations (known as common random numbers) means that differences between two proposed parameterisations reflect the parameters rather than the random draw, which makes the objective easier for the algorithm to optimize. It also means that the optimum is found for this particular set of random realisations; it is good practice to re-evaluate it with different seeds.

Because the replicate seeds are derived from the seed of the optimization, they are not stored in the nl object. A dynamic design is reproduced by the nl object together with nreplicates, so nreplicates should be recorded alongside the results.

Reproducibility and Seeds

Each seed of the simdesign is used as the random seed of the NetLogo runs of one optimization, and, with nreplicates > 1, as the basis from which the replicate seeds of that optimization are derived. The stochastic elements of the optimization algorithms themselves (for example the starting values of GenSA or the initial population of GenAlg) are drawn from the random number generator of R and are not controlled by these seeds; call set.seed() before run_nl_dyn() if these should be reproducible as well. Several seeds (nseeds > 1) therefore yield independent repetitions of the whole optimization, which shows whether the algorithm converges to the same solution under different stochasticity.

Suppressing Messages

Informational messages (e.g., XML file paths) are displayed using the cli package. To suppress these messages, wrap the function call with suppressMessages(), e.g., suppressMessages(run_nl_dyn(nl)).

Examples

## Not run: 

# Load nl object form test data:
nl <- nl_lhs

# Add genalg simdesign with three seeds, thus three independent optimizations:
nl@simdesign <- simdesign_GenAlg(nl=nl,
                                  popSize = 20,
                                  iters = 10,
                                  evalcrit = 1,
                                  nseeds = 3)

# Run simulations:
results <- run_nl_dyn(nl)

# The optimization objects are stored in the result column:
summary(results$result[[1]])

# Average each evaluation over 5 replicated model runs to reduce simulation noise:
results <- run_nl_dyn(nl, nreplicates = 5, threads = 5)


## End(Not run)

Execute one NetLogo simulation from a nl object

Description

Execute one NetLogo simulation from a nl object with a defined experiment and simdesign

Usage

run_nl_one(nl, seed, threads = 1, siminputrow, ...)

Arguments

nl

nl object

seed

a random seed for the NetLogo simulation, or a vector of random seeds to run the same parameterisation repeatedly

threads

number of NetLogo threads used for execution (handled via NetLogo).

siminputrow

rownumber of the input tibble within the attached simdesign object that should be executed

...

additional arguments; currently only used to detect and warn about arguments that were deprecated in earlier nlrx versions.

Details

Uses the logolink backend for NetLogo 7+. run_nl_one() executes one simulation of the specified NetLogo model within the provided nl object. The random seed is set within the NetLogo model to control stochasticity. For further information, see the Reproducibility section in run_nl_all(). The siminputrow number defines which row of the input data tibble within the simdesign object of the provided nl object is executed.

If seed is a vector of more than one seed, the same parameterisation is executed once per seed. These replicated runs are independent of each other, and each of them reports its own seed in the random-seed column of the results.

The threads argument controls NetLogo's native multithreading. This is relevant when more than one seed is executed, because the runs are then parallelized within one NetLogo instance. For a single run, threads has no effect.

Value

tibble with simulation output results

Suppressing Messages

Informational messages (e.g., XML file paths) are displayed using the cli package. To suppress these messages, wrap the function call with suppressMessages(), e.g., suppressMessages(run_nl_one(nl, 123, 1)).

Examples

## Not run: 

# Load nl object from test data:
nl <- nl_lhs

# Run one simulation:
results <- run_nl_one(nl = nl,
                      seed = getsim(nl, "simseeds")[1],
                      siminputrow = 1)

# Run the same parameterisation with three different seeds:
results <- run_nl_one(nl = nl,
                      seed = getsim(nl, "simseeds")[1:3],
                      siminputrow = 1)


## End(Not run)

Setter function to set a variable of an experiment object

Description

Setter function to set a variable of an experiment object

Usage

setexp(nl, var) <- value

Arguments

nl

nl object

var

valid experiment variable string

value

valid value for the specified variable

Examples


# Example for Wolf Sheep Predation model from NetLogo models library:
nl <- nl(nlversion = "7.0.4",
nlpath = "/home/user/NetLogo 7.0.4/",
modelpath = "/home/user/NetLogo 7.0.4/models/Sample Models/Biology/Wolf Sheep Predation.nlogox",
jvmmem = 1024)

# Set experiment name
setexp(nl, "expname") <- "experimentName"


Setter function to set a variable of a nl object

Description

Setter function to set a variable of a nl object

Usage

setnl(nl, var) <- value

Arguments

nl

nl object

var

valid nl variable string

value

valid value for the specified variable

Examples

# Example for Wolf Sheep Predation model from NetLogo models library:
nl <- nl(
nlpath = "/home/user/NetLogo 7.0.4/",
modelpath = "/home/user/NetLogo 7.0.4/models/Sample Models/Biology/Wolf Sheep Predation.nlogox",
jvmmem = 1024)

# set NetLogo version
setnl(nl, "nlversion") <- "7.0.4"


Setter function to set a variable of a simdesign object

Description

Setter function to set a variable of a simdesign object

Usage

setsim(nl, var) <- value

Arguments

nl

nl object

var

valid simdesign variable string

value

valid value for the specified variable

Examples

# Example for Wolf Sheep Predation model from NetLogo models library:
nl <- nl(nlversion = "7.0.4",
nlpath = "/home/user/NetLogo 7.0.4/",
modelpath = "/home/user/NetLogo 7.0.4/models/Sample Models/Biology/Wolf Sheep Predation.nlogox",
jvmmem = 1024)

# Set simulation seeds
setsim(nl, "simseeds") <- c(123, 456, 789)


Construct a new simdesign object

Description

Construct a new simdesign object

Usage

simdesign(
  simmethod = character(),
  siminput = tibble::tibble(),
  simobject = list(),
  simseeds = NA_integer_,
  simoutput = tibble::tibble(),
  ...
)

Arguments

simmethod

character string defining the method of the simulation design

siminput

tibble providing input parameterisations for the NetLogo model (cols=parameter, rows=runs)

simobject

used for some methods to store additional information (sobol, morris, eFast)

simseeds

a vector or model random seeds

simoutput

tibble containing model results

...

...

Details

The simulation design class holds information on the input parameter design of model simulations. It also stores information that is needed to run method specific analysis functions. The simseeds can be used to run all model simulations that are defined within the siminput tibble several times with changing random-seeds. While it is possible to add simdesign directly with this function, we suggest to use our simdesign_helper functions. A simulation design can be attached to a nl object by using one of these simdesign_helper functions on an already defined nl object with a valid experiment. All simdesign helpers use the defined constants and variables of the experiment to create the siminput tibble. NetLogo parameters that are not defined in constants or variables will be set with their default value from the NetLogo interface.

Currently, following simdesign_helper functions are provided:

simdesign_simple

The simple simdesign only uses defined constants and reports a parameter matrix with only one parameterization. To setup a simple simdesign, no variables have to be defined.

simdesign_distinct

The distinct simdesign can be used to run distinct parameter combinations. To setup a distinct simdesign, vectors of values need to be defined for each variable. These vectors must have the same number of elements across all variables. The first simulation run consist of all 1st elements of these variable vectors; the second run uses all 2nd values, and so on.

simdesign_ff

The full factorial simdesign creates a full-factorial parameter matrix with all possible combinations of parameter values. To setup a full-factorial simdesign, vectors of values need to be defined for each variable. Alternatively, a sequence can be defined by setting min, max and step. However, if both (values and min, max, step) are defined, the values vector is prioritized.

simdesign_lhs

The latin hypercube simdesign creates a Latin Hypercube sampling parameter matrix. The method can be used to generate a near-random sample of parameter values from the defined parameter distributions. More Details on Latin Hypercube Sampling can be found in McKay (1979) doi:10.1080/00401706.1979.10489755. nlrx uses the lhs package to generate the Latin Hypercube parameter matrix. To setup a latin hypercube sampling simdesign, variable distributions need to be defined (min, max, qfun).

Sensitivity Analyses: simdesign_sobol, simdesign_sobol2007, simdesign_soboljansen, simdesign_morris, simdesign_eFast

Sensitivity analyses are useful to estimate the importance of model parameters and to scan the parameter space in an efficient way. nlrx uses the sensitivity package to setup sensitivity analysis parameter matrices. All supported sensitivity analysis simdesigns can be used to calculate sensitivity indices for each parameter-output combination. These indices can be calculated by using the analyze_nl function after attaching the simulation results to the nl object. To setup sensitivity analysis simdesigns, variable distributions (min, max, qfun) need to be defined.

Optimization techniques: simdesign_GenSA, simdesign_GenAlg

Optimization techniques are a powerful tool to search the parameter space for specific solutions. Both approaches try to minimize a specified model output reporter by systematically (genetic algorithm, utilizing the genalg package) or randomly (simulated annealing, utilizing the genSA package) changing the model parameters within the allowed ranges. To setup optimization simdesigns, variable ranges (min, max) need to be defined. Optimization simdesigns can only be executed using the run_nl_dyn function instead of run_nl_all or run_nl_one.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load nl objects from test data.

# Simdesign examples for Wolf Sheep Predation model from NetLogo models library:

nl <- nl_simple
nl@simdesign <- simdesign_simple(nl = nl,
                                 nseeds = 3)

nl <- nl_distinct
nl@simdesign <- simdesign_distinct(nl = nl,
                                   nseeds = 3)

nl <- nl_ff
nl@simdesign <- simdesign_ff(nl = nl,
                             nseeds = 3)

nl <- nl_lhs
nl@simdesign <- simdesign_lhs(nl=nl,
                              samples=100,
                              nseeds=3,
                              precision=3)

nl <- nl_sobol
nl@simdesign <- simdesign_sobol(nl=nl,
                                samples=200,
                                sobolorder=2,
                                sobolnboot=20,
                                sobolconf=0.95,
                                nseeds=3,
                                precision=3)

nl <- nl_sobol2007
nl@simdesign <- simdesign_sobol2007(nl=nl,
                                    samples=200,
                                    sobolnboot=20,
                                    sobolconf=0.95,
                                    nseeds=3,
                                    precision=3)

nl <- nl_soboljansen
nl@simdesign <- simdesign_soboljansen(nl=nl,
                                      samples=200,
                                      sobolnboot=20,
                                      sobolconf=0.95,
                                      nseeds=3,
                                      precision=3)

nl <- nl_morris
nl@simdesign <- simdesign_morris(nl=nl,
                                 morristype="oat",
                                 morrislevels=4,
                                 morrisr=100,
                                 morrisgridjump=2,
                                 nseeds=3)

nl <- nl_eFast
nl@simdesign <- simdesign_eFast(nl=nl,
                                samples=100,
                                nseeds=3)

nl <- nl_lhs
nl@simdesign <- simdesign_GenAlg(nl=nl,
                                 popSize = 20,
                                 iters = 10,
                                 evalcrit = 1,
                                 elitism = NA,
                                 mutationChance = NA,
                                 nseeds = 1)

nl <- nl_lhs
nl@simdesign <- simdesign_GenSA(nl=nl,
                                par=NULL,
                                evalcrit=1,
                                control=list(max.time = 600),
                                nseeds=1)



Add an Approximate Bayesian Computation (Monte-Carlo Markov-Chain) simdesign using the Majoram algorithm to a nl object

Description

Add an Approximate Bayesian Computation (Monte-Carlo Markov-Chain) simdesign using the Majoram algorithm to a nl object

Usage

simdesign_ABCmcmc_Marjoram(
  nl,
  postpro_function = NULL,
  summary_stat_target,
  prior_test = NULL,
  n_rec,
  n_between_sampling = 10,
  use_seed = FALSE,
  dist_weights = NULL,
  n_calibration = 10000,
  tolerance_quantile = 0.01,
  proposal_phi = 1,
  seed_count = 0,
  progress_bar = FALSE,
  nseeds,
  ...
)

Arguments

nl

nl object with a defined experiment

postpro_function

default is NULL. Allows to provide a function that is called to post-process the output Tibble of the NetLogo simulations. The function must accept the nl object with attached results as input argument. The function must return a one-dimensional vector of output metrics that corresponds in length and order to the specified summary_stat_target.

summary_stat_target

a vector of target values in the same order as the defined metrics of the experiment

prior_test

a string expressing the constraints between model parameters. This expression will be evaluated as a logical expression, you can use all the logical operators including "<", ">", ... Each parameter should be designated with "X1", "X2", ... in the same order as in the prior definition. Set to NULL to disable.

n_rec

Number of samples along the MCMC

n_between_sampling

a positive integer equal to the desired spacing between sampled points along the MCMC.

use_seed

if TRUE, seeds will be automatically created for each new model run

dist_weights

a vector containing the weights to apply to the distance between the computed and the targeted statistics. These weights can be used to give more importance to a summary statistic for example. The weights will be normalized before applying them. Set to NULL to disable.

n_calibration

a positive integer. This is the number of simulations performed during the calibration step. Default value is 10000.

tolerance_quantile

a positive number between 0 and 1 (strictly). This is the percentage of simulations retained during the calibration step to determine the tolerance threshold to be used during the MCMC. Default value is 0.01.

proposal_phi

a positive number. This is a scaling factor defining the range of MCMC jumps. Default value is 1.

seed_count

a positive integer, the initial seed value provided to the function model (if use_seed=TRUE). This value is incremented by 1 at each call of the function model.

progress_bar

logical, FALSE by default. If TRUE, ABC_mcmc will output a bar of progression with the estimated remaining computing time. Option not available with multiple cores.

nseeds

number of seeds for this simulation design

...

deprecated arguments (e.g. n_cluster); currently only used to detect and warn about arguments that were deprecated in earlier nlrx versions.

Details

This function creates a simdesign S4 class which can be added to a nl object.

Every evaluation of the optimization is one NetLogo run (or nreplicates runs, see run_nl_dyn), which takes from seconds to minutes depending on the model. run_nl_dyn reports the number of evaluations when it starts and shows their progress. An optimization takes about n_calibration + n_rec * n_between_sampling evaluations; the default calibration alone amounts to 10,000 NetLogo runs per seed. The calibration has to keep at least two runs (ceiling(tolerance_quantile * n_calibration) >= 2).

Variables in the experiment variable list need to provide a numeric distribution with min, max and a shape of the distribution (qunif, qnorm, qlnorm, qexp)(e.g. list(min=1, max=4, qfun="qunif")).

The function uses the EasyABC package to set up the ABC_mcmc function. For details on the ABC_mcmc function parameters see ?EasyABC::ABC_mcmc Finally, the function reports a simdesign object.

Approximate Bayesian Computation simdesigns can only be executed using the run_nl_dyn function instead of run_nl_all or run_nl_one.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_lhs

# Attach the simdesign to the nl object
nl@simdesign <- simdesign_ABCmcmc_Marjoram(nl = nl,
                                            summary_stat_target = c(100, 80),
                                            n_rec = 50,
                                            n_between_sampling = 2,
                                            use_seed = FALSE,
                                            n_calibration = 200,
                                            tolerance_quantile = 0.05,
                                            proposal_phi = 1,
                                            progress_bar = FALSE,
                                            nseeds = 1)


Add an Approximate Bayesian Computation (Monte-Carlo Markov-Chain) simdesign using the Majoram Original algorithm to a nl object

Description

Add an Approximate Bayesian Computation (Monte-Carlo Markov-Chain) simdesign using the Majoram Original algorithm to a nl object

Usage

simdesign_ABCmcmc_Marjoram_original(
  nl,
  postpro_function = NULL,
  summary_stat_target,
  prior_test = NULL,
  n_rec,
  n_between_sampling = 10,
  use_seed = FALSE,
  dist_weights = NULL,
  dist_max = 0,
  tab_normalization = summary_stat_target,
  proposal_range = vector(mode = "numeric", length = length(getexp(nl, "variables"))),
  seed_count = 0,
  progress_bar = FALSE,
  nseeds,
  ...
)

Arguments

nl

nl object with a defined experiment

postpro_function

default is NULL. Allows to provide a function that is called to post-process the output Tibble of the NetLogo simulations. The function must accept the nl object with attached results as input argument. The function must return a one-dimensional vector of output metrics that corresponds in leght and order to the specified summary_stat_target.

summary_stat_target

a vector of target values in the same order as the defined metrics of the experiment

prior_test

a string expressing the constraints between model parameters. This expression will be evaluated as a logical expression, you can use all the logical operators including "<", ">", ... Each parameter should be designated with "X1", "X2", ... in the same order as in the prior definition. Set to NULL to disable.

n_rec

Number of samples along the MCMC

n_between_sampling

a positive integer equal to the desired spacing between sampled points along the MCMC.

use_seed

if TRUE, seeds will be automatically created for each new model run

dist_weights

a vector containing the weights to apply to the distance between the computed and the targeted statistics. These weights can be used to give more importance to a summary statistic for example. The weights will be normalized before applying them. Set to NULL to disable.

dist_max

a positive number. This is the tolerance threshold used during the MCMC. If not provided by the user, it is automatically computed as half the distance between the first simulation and the target summary statistics and a warning is printed.

tab_normalization

a vector of the same length as summary_stat_target. Each element contains a positive number by which each summary statistics must be divided before the computation of the Euclidean distance between simulations and data. If not provided by the user, the simulated summary statistics are divided by the target summary statistics and a warning is printed.

proposal_range

a vector of the same length as the number of model parameters, used when method is "Marjoram_original". Each element contains a positive number defining the range of MCMC jumps for each model parameter. If not provided by the user, a default value is used for each parameter and a warning is printed. The default value is 1/50 of the prior range for uniform distributions, 1/20 of the standard deviation of the prior distribution for normal distributions, 1/20 * exp ( sigma * sigma

seed_count

a positive integer, the initial seed value provided to the function model (if use_seed=TRUE). This value is incremented by 1 at each call of the function model.

progress_bar

logical, FALSE by default. If TRUE, ABC_mcmc will output a bar of progression with the estimated remaining computing time. Option not available with multiple cores.

nseeds

number of seeds for this simulation design

...

deprecated arguments (e.g. n_cluster); currently only used to detect and warn about arguments that were deprecated in earlier nlrx versions.

Details

This function creates a simdesign S4 class which can be added to a nl object.

Every evaluation of the optimization is one NetLogo run (or nreplicates runs, see run_nl_dyn), which takes from seconds to minutes depending on the model. run_nl_dyn reports the number of evaluations when it starts and shows their progress. An optimization takes about n_rec * n_between_sampling evaluations.

Variables in the experiment variable list need to provide a numeric distribution with min, max and a shape of the distribution (qunif, qnorm, qlnorm, qexp)(e.g. list(min=1, max=4, qfun="qunif")).

The function uses the EasyABC package to set up the ABC_mcmc function. For details on the ABC_mcmc function parameters see ?EasyABC::ABC_mcmc Finally, the function reports a simdesign object.

Approximate Bayesian Computation simdesigns can only be executed using the run_nl_dyn function instead of run_nl_all or run_nl_one.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_lhs

# Attach the simdesign to the nl object
nl@simdesign <- simdesign_ABCmcmc_Marjoram_original(nl = nl,
                                                     summary_stat_target = c(100, 80),
                                                     n_rec = 50,
                                                     n_between_sampling = 2,
                                                     nseeds = 1)


Add an Approximate Bayesian Computation (Monte-Carlo Markov-Chain) simdesign using the Wegmann algorithm to a nl object

Description

Add an Approximate Bayesian Computation (Monte-Carlo Markov-Chain) simdesign using the Wegmann algorithm to a nl object

Usage

simdesign_ABCmcmc_Wegmann(
  nl,
  postpro_function = NULL,
  summary_stat_target,
  prior_test = NULL,
  n_rec,
  n_between_sampling = 10,
  use_seed = FALSE,
  dist_weights = NULL,
  n_calibration = 10000,
  tolerance_quantile = 0.01,
  proposal_phi = 1,
  numcomp = 0,
  seed_count = 0,
  progress_bar = FALSE,
  nseeds,
  ...
)

Arguments

nl

nl object with a defined experiment

postpro_function

default is NULL. Allows to provide a function that is called to post-process the output Tibble of the NetLogo simulations. The function must accept the nl object with attached results as input argument. The function must return a one-dimensional vector of output metrics that corresponds in leght and order to the specified summary_stat_target.

summary_stat_target

a vector of target values in the same order as the defined metrics of the experiment

prior_test

a string expressing the constraints between model parameters. This expression will be evaluated as a logical expression, you can use all the logical operators including "<", ">", ... Each parameter should be designated with "X1", "X2", ... in the same order as in the prior definition. Set to NULL to disable.

n_rec

Number of samples along the MCMC

n_between_sampling

a positive integer equal to the desired spacing between sampled points along the MCMC.

use_seed

if TRUE, seeds will be automatically created for each new model run

dist_weights

a vector containing the weights to apply to the distance between the computed and the targeted statistics. These weights can be used to give more importance to a summary statistic for example. The weights will be normalized before applying them. Set to NULL to disable.

n_calibration

a positive integer. This is the number of simulations performed during the calibration step. Default value is 10000.

tolerance_quantile

a positive number between 0 and 1 (strictly). This is the percentage of simulations retained during the calibration step to determine the tolerance threshold to be used during the MCMC. Default value is 0.01.

proposal_phi

a positive number. This is a scaling factor defining the range of MCMC jumps. Default value is 1.

numcomp

a positive integer. This is the number of components to be used for PLS transformations. Default value is 0 which encodes that this number is equal to the number of summary statistics.

seed_count

a positive integer, the initial seed value provided to the function model (if use_seed=TRUE). This value is incremented by 1 at each call of the function model.

progress_bar

logical, FALSE by default. If TRUE, ABC_mcmc will output a bar of progression with the estimated remaining computing time. Option not available with multiple cores.

nseeds

number of seeds for this simulation design

...

deprecated arguments (e.g. n_cluster); currently only used to detect and warn about arguments that were deprecated in earlier nlrx versions.

Details

This function creates a simdesign S4 class which can be added to a nl object.

Every evaluation of the optimization is one NetLogo run (or nreplicates runs, see run_nl_dyn), which takes from seconds to minutes depending on the model. run_nl_dyn reports the number of evaluations when it starts and shows their progress. An optimization takes about n_calibration + n_rec * n_between_sampling evaluations; the default calibration alone amounts to 10,000 NetLogo runs per seed. The calibration has to keep at least two runs (ceiling(tolerance_quantile * n_calibration) >= 2).

Variables in the experiment variable list need to provide a numeric distribution with min, max and a shape of the distribution (qunif, qnorm, qlnorm, qexp)(e.g. list(min=1, max=4, qfun="qunif")).

The function uses the EasyABC package to set up the ABC_mcmc function. For details on the ABC_mcmc function parameters see ?EasyABC::ABC_mcmc Finally, the function reports a simdesign object.

Approximate Bayesian Computation simdesigns can only be executed using the run_nl_dyn function instead of run_nl_all or run_nl_one.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_lhs

# Attach the simdesign to the nl object
nl@simdesign <- simdesign_ABCmcmc_Wegmann(nl = nl,
                                            summary_stat_target = c(100, 80),
                                            n_rec = 50,
                                            n_between_sampling = 2,
                                            use_seed = FALSE,
                                            n_calibration = 200,
                                            tolerance_quantile = 0.05,
                                            proposal_phi = 1,
                                            progress_bar = FALSE,
                                            nseeds = 1)


Add a Genetic Algorithm simdesign to a nl object

Description

Add a Genetic Algorithm simdesign to a nl object

Usage

simdesign_GenAlg(
  nl,
  popSize = 200,
  iters = 100,
  evalcrit = 1,
  elitism = NA,
  mutationChance = NA,
  nseeds = 1
)

Arguments

nl

nl object with a defined experiment

popSize

population Size parameter for genetic algorithm

iters

number of iterations for genetic algorithm function

evalcrit

position of evaluation criterion within defined NetLogo metrics of nl experiment or a function that reports a single numeric value

elitism

elitism rate of genetic algorithm function

mutationChance

mutation rate of genetic algorithm function

nseeds

number of seeds for this simulation design

Details

This function creates a simdesign S4 class which can be added to a nl object.

Every evaluation of the optimization is one NetLogo run (or nreplicates runs, see run_nl_dyn), which takes from seconds to minutes depending on the model. run_nl_dyn reports the number of evaluations when it starts and shows their progress. An optimization takes at most popSize * iters evaluations; the defaults (200 x 100) amount to 20,000 NetLogo runs per seed.

Variables in the experiment variable list need to provide a numeric distribution with min and max (e.g. list(min=1, max=4)).

The GenAlg simdesign generates a Genetic Algorithm experiment within the defined min and max parameter boundaries that are defined in the variables field of the experiment object within the nl object.

The evalcrit reporter defines the evaluation criterion for the Genetic algorithm procedure. There are two options to evaluate the fitness value of each iteration of the algorithm:

  1. Use a reporter that is defined within the experiment metrics vector. You can just enter the position of that metric within the experiment metrics vector (e.g. 1 would use the first defined metric of the experiment to evaluate each iteration). The algorithm automatically calculates the mean value of this reporter if evalticks is defined to measure multiple ticks during each simulation.

  2. Use a self-defined evaluation function You can define a function that post-processes NetLogo output to calculate an evaluation value. This function must accept the nl object as input and return one single numeric value. The nl object that is then provided to the evaluation function will have results of the current iteration attached. The results can be accessed via the simoutput slot of the simdesign. You can pass this function to evalcrit. It is then applied to the output of each iteration.

The function uses the genalg package to set up a Genetic Algorithm function. For details on the genalg function parameters see ?genalg::rbga Finally, the function reports a simdesign object.

Genetic Algorithm simdesigns can only be executed using the run_nl_dyn function instead of run_nl_all or run_nl_one.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_lhs

# Example 1: Using a metric from the experiment metrics vector for evaluation:
nl@simdesign <- simdesign_GenAlg(nl=nl,
                                  popSize = 20,
                                  iters = 10,
                                  evalcrit=1,
                                  nseeds=1)

# Example 2: Using a self-defined evaluation function
# For demonstration we define a simple function that calculates
# the maximum value of count sheep output.
critfun <- function(nl) {
results <- nl@simdesign@simoutput
crit <- as.integer(max(results$`count sheep`))
return(crit)
}

nl@simdesign <- simdesign_GenAlg(nl=nl,
                                  popSize = 20,
                                  iters = 10,
                                  evalcrit=critfun,
                                  nseeds=1)



Add a Simulated Annealing simdesign to a nl object

Description

Add a Simulated Annealing simdesign to a nl object

Usage

simdesign_GenSA(nl, par = NULL, evalcrit = 1, control = list(), nseeds = 1)

Arguments

nl

nl object with a defined experiment

par

optional vector of start values, one for each variable of the experiment, in the order in which the variables are defined. If NULL (default), GenSA draws a random start point within the parameter boundaries.

evalcrit

position of evaluation criterion within defined NetLogo metrics of nl experiment or a function that reports a single numeric value

control

list with further arguments passed to the GenSA function (see ?GenSA for details)

nseeds

number of seeds for this simulation design

Details

This function creates a simdesign S4 class which can be added to a nl object.

Every evaluation of the optimization is one NetLogo run (or nreplicates runs, see run_nl_dyn), which takes from seconds to minutes depending on the model. run_nl_dyn reports the number of evaluations when it starts and shows their progress. With an empty control list, GenSA runs with its defaults (maxit = 5000), which amounts to tens of thousands of evaluations; set a stop criterion such as max.call or max.time in control.

Variables in the experiment variable list need to provide a numeric distribution with min and max (e.g. list(min=1, max=4)). Only min and max are used: the algorithm searches the range they define, so a qfun of the variable definition is irrelevant for this simdesign.

The GenSA simdesign generates a simulated Annealing experiment within the defined min and max parameter boundaries that are defined in the variables field of the experiment object within the nl object.

The evalcrit reporter defines the evaluation criterion for the simulated annealing procedure. There are two options to evaluate the fitness value of each iteration of the algorithm:

  1. Use a reporter that is defined within the experiment metrics vector. You can just enter the position of that metric within the experiment metrics vector (e.g. 1 would use the first defined metric of the experiment to evaluate each iteration). The algorithm automatically calculates the mean value of this reporter if evalticks is defined to measure multiple ticks during each simulation. You can define a function that post-processes NetLogo output to calculate an evaluation value. This function must accept the nl object as input and return one single numeric value. The nl object that is then provided to the evaluation function will have results of the current iteration attached. The results can be accessed via the simoutput slot of the simdesign. You can pass this function to evalcrit. It is then applied to the output of each iteration.

The function uses the GenSA package to set up a Simulated Annealing function. For details on the GenSA function parameters see ?GenSA Finally, the function reports a simdesign object.

Simulated Annealing simdesigns can only be executed using the run_nl_dyn function instead of run_nl_all or run_nl_one.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_lhs

# Example 1: Using a metric from the experiment metrics vector for evaluation:
nl@simdesign <- simdesign_GenSA(nl=nl,
                                 par=NULL,
                                 evalcrit=1,
                                 control=list(max.time = 600),
                                 nseeds=1)


# Example 2: Using a self-defined evaluation function
# For demonstration we define a simple function that calculates
# the maximum value of count sheep output.
critfun <- function(nl) {
results <- nl@simdesign@simoutput
crit <- as.integer(max(results$`count sheep`))
return(crit)
}

nl@simdesign <- simdesign_GenSA(nl=nl,
                                 par=NULL,
                                 evalcrit=critfun,
                                 control=list(max.time = 600),
                                 nseeds=1)



Add a distinct simdesign to a nl object

Description

Add a distinct simdesign to a nl object

Usage

simdesign_distinct(nl, nseeds)

Arguments

nl

nl object with a defined experiment

nseeds

number of seeds for this simulation design

Details

This function creates a simdesign S4 class which can be added to a nl object. The distinct simdesign allows to create a parameter matrix with distinct parameterisations.

Variables in the experiment variable list need to provide a vector of distinct values (e.g. list(values=c(1,2,3,4)). All vectors of values must have the same length across variables.

The distinct simdesign then creates one simulation run for all first elements of these values vectors, one run for all second items, and so on. With this function, multiple distinct simulations can be run at once. Finally, the function reports a simdesign object.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_distinct
nl@simdesign <- simdesign_distinct(nl = nl, nseeds = 3)



Add an eFast simdesign to a nl object

Description

Add an eFast simdesign to a nl object

Usage

simdesign_eFast(nl, samples, nseeds)

Arguments

nl

nl object with a defined experiment

samples

number of samples for the eFast sensitivity analysis

nseeds

number of seeds for this simulation design

Details

This function creates a simdesign S4 class which can be added to a nl object.

Variables in the experiment variable list need to provide a numeric distribution with min, max and qfun (e.g. list(min=1, max=4, qfun="qunif")).

The eFast simdesign uses the sensitivity package to set up a fast99 elementary effects sensitivity analysis, including a simobject of class fast99 and a input tibble for simulations. For details on method specific sensitivity analysis function parameters see ?fast99 Finally, the function reports a simdesign object.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_eFast
nl@simdesign <- simdesign_eFast(nl=nl,
                                 samples=100,
                                 nseeds=1)



Add a full-factorial simdesign to a nl object

Description

Add a full-factorial simdesign to a nl object

Usage

simdesign_ff(nl, nseeds)

Arguments

nl

nl object with a defined experiment

nseeds

number of seeds for this simulation design

Details

This function creates a simdesign S4 class which can be added to a nl object.

Variables in the experiment variable list need to provide a vector of distinct values (e.g. list(values=c(1,2,3,4)). Or a sequence definition with min, max and step (e.g. list=(min=1, max=4, step=1)). If both (values and sequence) are defined, the full-factorial design gives priority to the values.

The full-factorial simdesign uses these defined parameter ranges within the nl object. A full-factorial matrix of all parameter combinations is created as input tibble for the simdesign. Finally, the function reports a simdesign object.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_ff
nl@simdesign <- simdesign_ff(nl = nl, nseeds = 3)



Add a latin-hypercube simdesign to a nl object

Description

Add a latin-hypercube simdesign to a nl object

Usage

simdesign_lhs(nl, samples, nseeds, precision)

Arguments

nl

nl object with a defined experiment

samples

number of samples for the latin hypercube

nseeds

number of seeds for this simulation design

precision

number of digits for the decimal fraction of parameter values

Details

This function creates a simdesign S4 class which can be added to a nl object.

Variables in the experiment variable list need to provide a numeric distribution with min, max and qfun (e.g. list(min=1, max=4, qfun="qunif")).

The latin hypercube simdesign creates a parameter matrix based on these defined distributions. Finally, the function reports a simdesign object.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_lhs
nl@simdesign <- simdesign_lhs(nl=nl,
                               samples=100,
                               nseeds=3,
                               precision=3)


Add a morris elementary effects simdesign to a nl object

Description

Add a morris elementary effects simdesign to a nl object

Usage

simdesign_morris(
  nl,
  morristype,
  morrislevels,
  morrisr,
  morrisgridjump,
  nseeds,
  scale = TRUE
)

Arguments

nl

nl object with a defined experiment

morristype

morris design type

morrislevels

number of parameter levels

morrisr

morris r value

morrisgridjump

morris grid jump value

nseeds

number of seeds for this simulation design

scale

logical, if TRUE (default) the input factors are scaled to ⁠[0, 1]⁠ before the elementary effects are computed, which makes them comparable across parameters with different units and ranges. Set to FALSE to obtain unscaled effects

Details

This function creates a simdesign S4 class which can be added to a nl object.

Variables in the experiment variable list need to provide a numeric distribution with min, max and qfun (e.g. list(min=1, max=4, qfun="qunif")).

The morris simdesign uses the sensitivity package to set up a morris elementary effects sensitivity analysis, including a simobject of class morris and a input tibble for simulations. For details on method specific sensitivity analysis function parameters see ?morris Finally, the function reports a simdesign object.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_morris
nl@simdesign <- simdesign_morris(nl=nl,
                                  morristype="oat",
                                  morrislevels=4,
                                  morrisr=20,
                                  morrisgridjump=2,
                                  nseeds=3)



Add a simple simdesign to a nl object

Description

Add a simple simdesign to a nl object

Usage

simdesign_simple(nl, nseeds)

Arguments

nl

nl object with a defined experiment

nseeds

number of seeds for this simulation design

Details

This function creates a simdesign S4 class which can be added to a nl object. The simple simdesign only uses model parameters that are defined in the constants field of the experiment object within the nl object. Thus, the resulting input tibble of the simdesign has only one run with constant parameterisations. This can be useful to run one simulation with a specific parameterset. Finally, the function reports a simdesign object.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_simple
nl@simdesign <- simdesign_simple(nl = nl, nseeds = 3)



Add a sobol simdesign to a nl object

Description

Add a sobol simdesign to a nl object

Usage

simdesign_sobol(
  nl,
  samples,
  sobolorder,
  sobolnboot,
  sobolconf,
  nseeds,
  precision
)

Arguments

nl

nl object with a defined experiment

samples

number of samples for the sobol sensitivity analysis

sobolorder

order of interactions of the sobol sensitivity analysis

sobolnboot

number of bootstrap replicates of the sobol sensitivity analysis

sobolconf

the confidence level for bootstrap confidence intervals

nseeds

number of seeds for this simulation design

precision

number of digits for the decimal fraction of parameter values

Details

This function creates a simdesign S4 class which can be added to a nl object.

Variables in the experiment variable list need to provide a numeric distribution with min, max and qfun (e.g. list(min=1, max=4, qfun="qunif")).

The sobol simdesign uses the sensitivity package to set up a sobol sensitivity analysis, including a simobject of class sobol and a input tibble for simulations. For details on method specific sensitivity analysis function parameters see ?sobol Finally, the function reports a simdesign object.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_sobol
nl@simdesign <- simdesign_sobol(nl=nl,
samples=1000,
sobolorder=2,
sobolnboot=100,
sobolconf=0.95,
nseeds=3,
precision=3)



Add a sobol2007 simdesign to a nl object

Description

Add a sobol2007 simdesign to a nl object

Usage

simdesign_sobol2007(nl, samples, sobolnboot, sobolconf, nseeds, precision)

Arguments

nl

nl object with a defined experiment

samples

number of samples for the sobol sensitivity analysis

sobolnboot

number of bootstrap replicates of the sobol sensitivity analysis

sobolconf

the confidence level for bootstrap confidence intervals

nseeds

number of seeds for this simulation design

precision

number of digits for the decimal fraction of parameter values

Details

This function creates a simdesign S4 class which can be added to a nl object.

Variables in the experiment variable list need to provide a numeric distribution with min, max and qfun (e.g. list(min=1, max=4, qfun="qunif")).

The sobol2007 simdesign uses the sensitivity package to set up a sobol2007 sensitivity analysis, including a simobject of class sobol and a input tibble for simulations. For details on method specific sensitivity analysis function parameters see ?sobol2007 Finally, the function reports a simdesign object.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_sobol2007
nl@simdesign <- simdesign_sobol2007(nl=nl,
samples=1000,
sobolnboot=100,
sobolconf=0.95,
nseeds=3,
precision=3)



Add a soboljansen simdesign to a nl object

Description

Add a soboljansen simdesign to a nl object

Usage

simdesign_soboljansen(nl, samples, sobolnboot, sobolconf, nseeds, precision)

Arguments

nl

nl object with a defined experiment

samples

number of samples for the sobol sensitivity analysis

sobolnboot

number of bootstrap replicates of the sobol sensitivity analysis

sobolconf

the confidence level for bootstrap confidence intervals

nseeds

number of seeds for this simulation design

precision

number of digits for the decimal fraction of parameter values

Details

This function creates a simdesign S4 class which can be added to a nl object.

Variables in the experiment variable list need to provide a numeric distribution with min, max and qfun (e.g. list(min=1, max=4, qfun="qunif")).

The soboljansen simdesign uses the sensitivity package to set up a soboljansen sensitivity analysis, including a simobject of class sobol and a input tibble for simulations. For details on method specific sensitivity analysis function parameters see ?soboljansen Finally, the function reports a simdesign object.

Value

simdesign S4 class object

Examples


# To attach a simdesign, a nl object needs to be created first (see ?nl).
# For this example, we load a nl object from test data.

nl <- nl_soboljansen
nl@simdesign <- simdesign_soboljansen(nl=nl,
samples=1000,
sobolnboot=100,
sobolconf=0.95,
nseeds=3,
precision=3)



Report tested NetLogo versions

Description

Auxiliary function to report the NetLogo versions nlrx is tested with

Usage

supported_netlogo_versions()

Details

These are the versions used in the automated tests and for download_netlogo. Newer NetLogo 7 releases are not rejected: because execution is delegated to 'logolink', they are likely to work and only emit a warning (see check_netlogo_version).

Value

a vector of NetLogo versions that nlrx is tested with (parameter version)

Examples

## Not run: 
supported_netlogo_versions()

## End(Not run)


Test if nlrx runs on the local system

Description

Runs a short test if nlrx runs on the local system

Usage

test_nlrx(nlpath, nlversion)

Arguments

nlpath

Provide a path to a netlogo folder

nlversion

Matching version string of the provided NetLogo folder (e.g. "7.0.4")

Details

Runs a short test if nlrx runs on the local system. Reports TRUE if successful!

Examples

## Not run: 
test_nlrx(nlpath="/Users/xyz/netlogo/NetLogo 7.0.4", nlversion="7.0.4")

## End(Not run)


Get spatial data from metrics.turtles and metrics.patches output

Description

Turn results from NetLogo in spatial data objects

Usage

unnest_simoutput(nl)

Arguments

nl

nl object

Details

Unnests output from run_nl into long format.

Value

tibble with spatial data objects

Examples


# To unnest data a nl object containing spatial output data is needed.
# For this example, we load a nl object from test data.

nl <- nl_spatial
unnest_simoutput(nl)



Signal an error with an advice-style message

Description

Signal an error for a problem in the user's setup (wrong NetLogo version, wrong model format, ...) that the user can fix.

Usage

util_abort(message, class = NULL, .envir = parent.frame())

Arguments

message

Character vector, formatted with cli::format_error(). Unnamed elements state the problem, "i" elements give context and ">" elements say what to do. cli inline markup and glue interpolation are evaluated in .envir.

class

Character vector of condition classes, prepended to "nlrx_error".

.envir

Environment in which the message is interpolated.

Details

The condition is a base R error without a call, so neither the call nor a backtrace is printed - the user sees the advice only. Genuine runtime failures (NetLogo errors, internal errors) keep using stop().


Utility function for checking for deprecated or unsupported arguments

Description

Utility function for checking for deprecated or unsupported arguments

Usage

util_check_deprecated_args(dots, deprecated_args)

Arguments

dots

Named list of arguments captured from ...

deprecated_args

Character vector of deprecated argument names that should trigger depreciation warnings (and not errors)


Reject NetLogo 6 model files

Description

Stops with an advice-style error if any of the model files is in the NetLogo 6 format (.nlogo).

Usage

util_check_model_format(modelpath)

Arguments

modelpath

Character vector of model file paths. An empty vector passes, so an nl object can be created before the model is known.

Details

NetLogo 7 converts .nlogo files when it opens them, so a .nlogo model would even run. nlrx itself cannot read the old format (parameter reports, variable checks, nldoc), and the conversion is meant as a deliberate step, so the user is asked to convert the model once in NetLogo 7.


Backend function for cleaning agent metrics

Description

Internal helper for formatting turtle, patch and link metrics in simulation output.

Usage

util_clean_agent_metrics(NLtable, nl, expect_cleaned_names = FALSE)

Arguments

NLtable

simulation output table

nl

nl object

expect_cleaned_names

TRUE/FALSE, if TRUE reporter column names are expected to be cleaned by janitor::make_clean_names().

Details

Converts raw turtle, patch and link metric reporter output into nested output columns.

Value

simulation output table with cleaned agent metrics


Collapse NetLogo commands into one code block

Description

Turns an experiment slot that may hold several procedures or commands into one string

Usage

util_collapse_commands(commands)

Arguments

commands

character vector of NetLogo procedures or commands, possibly NA

Details

idsetup, idgo, idfinal and stopcond accept a vector, which NetLogo expects as one block of code with one command per line. Returns NULL for an undefined slot, which is what 'logolink' expects for "not set".

Value

a single character string, or NULL if nothing is defined


Backend function for collecting experiment metrics

Description

Internal helper for combining regular metrics with turtle, patch and link metrics.

Usage

util_collect_experiment_metrics(nl)

Arguments

nl

nl object

Details

Combines regular experiment metrics with additional agent metrics defined in metrics.turtles, metrics.patches and metrics.links.

Value

character vector of NetLogo reporter metrics


Create turtle/patches/links owns reporter

Description

The reporter is used to measure agent variables in NetLogo and parse them to a readable format

Usage

util_create_agentset_reporter(metrics, breed)

Arguments

metrics

character vector, the names of variables to measure

breed

character, the corresponding breed/agentset (e.g. "turtles", "patches", "links", "wolves", ...)


Identify and report the current OS

Description

Identify and report the current OS

Usage

util_create_lhs(input, samples, precision)

Arguments

input

list with variables and value ranges

samples

number of lhs samples

precision

number of digits for the decimal fraction of parameter values


Check the calibration step of an ABC-MCMC simdesign

Description

Stops if the calibration step keeps fewer than two runs, from which EasyABC cannot derive the proposal range of the MCMC.

Usage

util_eval_abc_calibration(n_calibration, tolerance_quantile)

Arguments

n_calibration

number of simulations of the calibration step

tolerance_quantile

share of the calibration simulations that is kept


Evaluate if constants list of an experiment object is empty

Description

Evaluate if constants list of an experiment object is empty

Usage

util_eval_constants(nl)

Arguments

nl

nl object util_eval_constants checks if the constants list of an experiment within a nl object is empty. It reports an error message if no constants were defined. This evaluation is only done for simdesign_simple.


Evaluate all slots of an experiment object

Description

Evaluate all slots of an experiment object

Usage

util_eval_experiment(nl)

Arguments

nl

nl object

Details

util_eval_experiment checks if the information stored within the experiment slots are valid.


Evaluate all slots of a simdesign object

Description

Evaluate all slots of a simdesign object

Usage

util_eval_simdesign(nl)

Arguments

nl

nl object

Details

util_eval_simdesign checks if the information stored within the simdesign slots are valid.


Evaluate if variables list of an experiment object is empty

Description

Evaluate if variables list of an experiment object is empty

Usage

util_eval_variables(nl)

Arguments

nl

nl object

Details

util_eval_variables checks if the variables list of an experiment within a nl object is empty. It reports an error message if no variables were defined.


Evaluate variables list of an experiment object for distinct simdesign

Description

Evaluate variables list of an experiment object for distinct simdesign

Usage

util_eval_variables_distinct(nl)

Arguments

nl

nl object

Details

util_eval_variables_distinct checks if the variables list of an experiment within a nl object has enough information to create a simdesign_distinct. It reports an error message if at least one variable does not have a vector of distinct values or if there is a mismatch in length of these values vectors.


Evaluate variables list of an experiment object for full-factorial simdesign

Description

Evaluate variables list of an experiment object for full-factorial simdesign

Usage

util_eval_variables_ff(nl)

Arguments

nl

nl object

Details

util_eval_variables_ff checks if the variables list of an experiment within a nl object has enough information to create a simdesign_ff. It reports an error message if at least one variable does not have a defined sequence (min, max, step) or a vector of distinct values.


Evaluate variables list of an experiment object for optimization simdesigns

Description

Evaluate variables list of an experiment object for optimization simdesigns

Usage

util_eval_variables_op(nl)

Arguments

nl

nl object

Details

util_eval_variables_op checks if the variables list of an experiment within a nl object has enough information to create an optimization simdesign. It reports an error message if at least one variable does not have a defined range (min, max).


Evaluate variables list of an experiment object for sensitivity analysis simdesigns

Description

Evaluate variables list of an experiment object for sensitivity analysis simdesigns

Usage

util_eval_variables_sa(nl)

Arguments

nl

nl object

Details

util_eval_variables_sa checks if the variables list of an experiment within a nl object has enough information to create a sensitivity analysis simdesign. It reports an error message if at least one variable does not have a defined distribution (min, max, qfun).


Derive a vector of replicate seeds from a single design seed

Description

Derive a reproducible vector of random seeds for replicated model runs

Usage

util_generate_replicate_seeds(seed, nreplicates)

Arguments

seed

the design seed the replicate seeds are derived from

nreplicates

number of replicate seeds to derive

Details

The derived seeds are a deterministic function of seed and therefore do not need to be stored: the same seed always yields the same replicate seeds. Because the seeds are drawn from the head of one stream, the seed vector for a smaller nreplicates is a prefix of the vector for a larger one.

The random number generator state of the calling environment is saved and restored, so that deriving replicate seeds does not interfere with the random number stream of the dynamic simulation designs (genalg and EasyABC draw from it).

Value

numeric vector of length nreplicates


Generate a vector of random seeds

Description

Generate a vector of random seeds

Usage

util_generate_seeds(nseeds)

Arguments

nseeds

desired length of the random seeds vector


Report the macOS architecture

Description

Reports which macOS architecture a NetLogo disk image should be downloaded for

Usage

util_get_mac_arch()

Details

Under Rosetta, R reports x86_64 even on Apple Silicon, so the hardware is asked directly via sysctl hw.optional.arm64 in that case. Pass arch to download_netlogo to override the result, for example to fetch an image for a different machine.

Value

"aarch64" on Apple Silicon, "x86_64" otherwise


Identify and report the current OS

Description

Identify and report the current OS

Usage

util_get_os()

Harmonize result column types across simulation blocks

Description

Makes columns that have different types in different blocks bindable

Usage

util_harmonize_block_types(results_list)

Arguments

results_list

list of result tibbles, one per simulation block

Details

A metric can come back as a number in one block and as a character in another, for example when a run reports a NetLogo error message. Binding the blocks then fails and the results of all completed runs are lost. Such columns are converted to character in every block instead, with a warning naming them. List columns (agent metrics) are left untouched.

Value

results_list with conflicting columns converted to character


Normalize parameter values for the logolink backend

Description

Repairs the two value conventions of nlrx < 0.5.0 that are no longer valid now that 'logolink' writes the BehaviorSpace XML: strings that were wrapped in escaped quotes and booleans that were given as character strings.

Usage

util_normalize_nl_value(x)

Arguments

x

value or vector of values of a single NetLogo global

Details

'logolink' quotes character values itself and lowercases logical values, so a value like "\"default\"" would reach NetLogo as ""default"" and abort the run, and a value like "false" would reach it as the string "false" instead of a boolean.

One layer of enclosing double quotes is therefore removed, and character values that are entirely "true"/"false" (in any capitalisation) are converted to logical. This also applies to a quoted "\"true\"": NetLogo parses an unquoted true as a boolean, so a global whose value is the string "true" could not be expressed before 0.5.0 either.

Values that are not character (numbers, logicals, stepped value lists) are returned unchanged. The function is idempotent, so it can be applied at several points of the pipeline.

Value

x with legacy quoting and boolean strings normalized


Print experiment object content

Description

Print experiment object content

Usage

util_print.experiment(x, ...)

Arguments

x

experiment object

...

further arguments passed to or from other methods

Details

Print content of experiment object in a nice formatted overview to console


Print nl object content

Description

Print nl object content

Usage

util_print.nl(x, ...)

Arguments

x

nl object

...

further arguments passed to or from other methods

Details

Print content of nl object in a nice formatted overview to console


Print simdesign object content

Description

Print simdesign object content

Usage

util_print.simdesign(x, ...)

Arguments

x

simdesign object

...

further arguments passed to or from other methods

Details

Print content of simdesign object in a nice formatted overview to console


Print nl object summary

Description

Print nl object summary

Usage

util_print.summary(x, ...)

Arguments

x

nl object

...

further arguments passed to or from other methods

Details

Print summary of nl object and embedded experiment and simdesign objects in a nice formatted overview to console


Read the parameter widgets of a NetLogo 7 model

Description

Reads the sliders, switches, input boxes and choosers of a .nlogox model file.

Usage

util_read_nlogox_widgets(modelpath)

Arguments

modelpath

Path to a .nlogox model file

Details

Used by report_model_parameters() and nldoc().

Value

named list with one entry per widget (type, value and the properties of the widget type), or NULL if the model has no widgets block


Reduce replicated simulation results to one value per metric

Description

Aggregate simulation results over measured ticks and over replicates

Usage

util_reduce_replicates(results, cols)

Arguments

results

tibble of simulation results, as returned by run_nl_one()

cols

character vector of metric columns that should be reduced

Details

Reduction happens in two stages: first the mean over all measured ticks within each replicate, then the mean over the replicates. Replicates are identified by the random-seed column. The two stages matter whenever replicates return a different number of ticks (for example when an exit condition is defined), because a single mean over all rows would weight long runs higher than short ones.

Value

tibble with one row and one column per entry of cols


Report the evaluation budget of a dynamic simdesign

Description

Tells how many evaluations (NetLogo runs) the optimization of each seed may take, and which arguments control that number.

Usage

util_report_dyn_budget(nl, nseeds, nreplicates)

Arguments

nl

nl object with a GenSA, GenAlg or ABCmcmc simdesign

nseeds

number of seeds, i.e. optimizations

nreplicates

number of replicated runs per evaluation

Details

A GenSA simdesign without any stop criterion in control (max.call, max.time, maxit, nb.stop.improvement or threshold.stop) runs with the GenSA defaults (maxit = 5000, max.call = 1e7), which take tens of thousands of evaluations; this is reported as a warning.

Value

The (approximate) maximum number of evaluations per seed, NA if unknown, invisibly.


Report a NetLogo version that nlrx is not tested with

Description

Signals the advice-style error or warning for a NetLogo version that is not among supported_netlogo_versions (see check_netlogo_version for the rules).

Usage

util_report_netlogo_version(version, in_nl = FALSE)

Arguments

version

Character string naming the NetLogo version

in_nl

TRUE if called from nl(), which adds the hint how to silence the warning for untested NetLogo 7 versions


ABCmcmc call simulations function

Description

ABCmcmc call simulations function

Usage

util_run_nl_dyn_ABCmcmc(nl, seed, threads = 1, nreplicates = 1, ...)

Arguments

nl

nl object

seed

current model seed

threads

number of NetLogo threads used for execution (handled via NetLogo).

nreplicates

number of replicated model runs per evaluation


Genetic Algorithm call simulations function

Description

Genetic Algorithm call simulations function

Usage

util_run_nl_dyn_GenAlg(nl, seed, threads = 1, nreplicates = 1, ...)

Arguments

nl

nl object

seed

current model seed

threads

number of NetLogo threads used for execution (handled via NetLogo).

nreplicates

number of replicated model runs per evaluation


Genetic Algorithm run simulation function

Description

Genetic Algorithm run simulation function

Genetic Algorithm run simulation function

Usage

util_run_nl_dyn_GenAlg_fn(param, nl, evalcrit, seed, threads = 1, ...)

util_run_nl_dyn_ABCmcmc_fn(param, threads = 1)

Arguments

param

vector of model parameters passed from ABC_mcmc function. If use_seeds = TRUE, the first element of this vector is a random seed

nl

nl object

evalcrit

evaluation criterion for simulated annealing

seed

vector of model seeds, one per replicated run of this evaluation

threads

number of NetLogo threads used for execution (handled via NetLogo).


Simulated Annealing call simulations function

Description

Simulated Annealing call simulations function

Usage

util_run_nl_dyn_GenSA(nl, seed, threads = 1, nreplicates = 1, ...)

Arguments

nl

nl object

seed

current model seed

threads

number of NetLogo threads used for execution (handled via NetLogo).

nreplicates

number of replicated model runs per evaluation


Simulated Annealing run simulation function

Description

Simulated Annealing run simulation function

Usage

util_run_nl_dyn_GenSA_fn(param, nl, evalcrit, seed, threads = 1, ...)

Arguments

param

vector of model parameters, generated by GenSA function

nl

nl object

evalcrit

evaluation criterion for simulated annealing

seed

vector of model seeds, one per replicated run of this evaluation

threads

number of NetLogo threads used for execution (handled via NetLogo).


Run one evaluation of a dynamic simdesign

Description

Runs the simulations of one evaluation via run_nl_one(), without its console output, and advances the progress bar of run_nl_dyn().

Usage

util_run_nl_dyn_evaluation(nl, seed, threads = 1)

Arguments

nl

nl object with the parameterisation of this evaluation as siminput

seed

vector of model seeds, one per replicated run of this evaluation

threads

number of NetLogo threads used for execution (handled via NetLogo).

Details

An optimization runs thousands of evaluations, so the messages of each run (BehaviorSpace XML path, NetLogo progress) are held back. They are shown when the run fails, together with the error.

Value

Tibble with simulation output results


Identify evalticks without results

Description

Reports the evalticks of an experiment for which no simulation records were returned

Usage

util_unreported_evalticks(evalticks, steps)

Arguments

evalticks

the evalticks of the experiment

steps

the tick numbers present in the simulation results

Details

Simulations can end before a requested tick is reached, either because runtime is shorter or because a stopcond ended them. The affected ticks then silently carry no results, which this function surfaces.

Value

the requested evalticks that are missing from steps, in the order given


Signal a warning with an advice-style message

Description

Warning counterpart of util_abort().

Usage

util_warn(message, class = NULL, .envir = parent.frame())

Arguments

message

Character vector, formatted with cli::format_warning() (see util_abort()).

class

Character vector of condition classes, prepended to "nlrx_warning".

.envir

Environment in which the message is interpolated.


Write attached NetLogo simulation output to file

Description

Write attached NetLogo simulation output to file

Usage

write_simoutput(nl, outpath = NA)

Arguments

nl

nl object

outpath

optional path to directory where output is written

Write NetLogo simulation output to a csv file in the directory outpath of the nl object Output has to be attached to the simdesign first with simoutput(nl) <- results The outpath argument can be optionally used to write output to a different directory than the defined outpath of the nl object.

Examples


# Load nl object including output data from testdata
nl <- nl_lhs

# Write output to outpath directory
write_simoutput(nl, outpath=tempdir())

mirror server hosted at Truenetwork, Russian Federation.