# Introduction to SpaDES

## Package description

Easily implement a variety of simulation models, with a focus on spatially explicit models. These include raster-based, event-based, and agent-based models. The core simulation components are built upon a discrete event simulation framework that facilitates modularity, and easily enables the user to include additional functionality by running user-built simulation modules. Included are numerous tools to rapidly visualize raster and other maps.

### Requirements

This packages makes heavy use of the raster (Hijmans 2015) and sp (Pebesma and Bivand 2005; Bivand, Pebesma, and Gomez-Rubio 2013) packages, so familiarity with these packages, their classes and methods is recommended.

## Objectives and motivations

Building spatial simulation models often involves reusing various model components, often having to re-implement similar functionality in multiple simulation frameworks (i.e, in different programming languages). When various components of a simulation model become fragmented across multiple platforms, it becomes increasingly difficult to link these various components, and often solutions for this problem are idiosyncratic and specific to the model being implemented. As a result, developing general insights into complex computational models has, in the field of ecology at least, been hampered by modellers’ typically developing models from scratch (Thiele and Grimm 2015).

SpaDES is a generic simulation platform that can be used to create new model components quickly. It also provides a framework to link with existing simulation models, so that an already well described and mature model, e.g., Landis-II (Scheller et al. 2007), can be used with de novo components. Alternatively one could use several de novo models and several existing models in combination. This approach requires a platform that allows for modular reuse of model components (herein called ‘modules’) as hypotheses that can be evaluated and tested in various ways, as advocated by Thiele and Grimm (2015).

When beginning development of this package, we sought a general simulation platform at least the following characteristics:

1. Allow rapid building of models of a wide diversity of types (e.g., agent-based models, raster models, differential equation models);
2. Run faster and more memory efficiently than current systems for doing similar things (e.g., NetLogo (Wilensky 1999), SELES (A. Fall and Fall 2001));
3. Use a platform that already has strong data analysis, manipulation, and visualization capacities;
4. Be open source, but also make it as easy as possible for many people to easily contribute modules and code;
5. Be easy to use for a large number of scientists who aren’t formally trained as computer programmers or have limited programming experience;
6. Should be built around modularity so that models can be seen as modules that are easily replaceable, not just ‘in theory’ replaceable;
7. Allow tight coupling between data and model simulations so that the entire work flow from raw data to result generation or even report generation is not actually something that one has to redesign every time there is a new data set.

We selected R as the system within which to build SpaDES. R is currently the lingua franca for scientific data analysis. This means that anything developed in SpaDES is simply R code and can be easily shared with journals and the scientific community. We can likewise leverage R’s strengths as a data platform, its excellent visualization and graphics, its capabilities to run external code such as C/C++ and easily interact external software such as databases, and its abilities for high performance computing. SpaDES therefore doesn’t need to implement all of these from scratch, as they are achievable with already existing R packages.

### Is R fast enough?

High-level programming languages are often criticized for being much slower than their low-level counterparts. R has definitely received its share of criticism over not just speed but also memory use1. While some of these criticisms may be legitimate, many of them are overblown. They are based on test code that is not written for how R works2. The best example of this is using traditional C-like loops in R. R is a vectorized language, and code should rarely be written as loops in R. It should be vectorized, yet these sorts of biased comparisons get made all of the time, giving the false impression that R is too slow. Thus, these tests show that poorly written code can be slow, in any language.

Another major criticism of R is its high memory footprint. It’s true that similar structures take up less memory in C than in R. However, there are various simple optimizations for R code, such as explicitly pre-allocating memory to objects, that can drastically improve performance. In cases were further improvements are required, the Rcpp package (Eddelbuettel and Francois 2011; Eddelbuettel 2013) allows easy writing of low memory footprint C++ code that can then be called in R. Likewise, numerous upgrades to R, including minimizing object copying since R version 3.0, and extremely powerful user developed packages, like data.table and dplyr are eliminating many of these concerns.

## Discrete event simulation and SpaDES

Discrete event simulation (DES) as implemented here is ‘event driven’, meaning that an activity changes the state of the system at particular times (called events). This approach assumes that state of the system only changes due to events, therefore there is no change between events. A particular activity may have several events associated with it. Future events are scheduled in an event queue, and then processed in chronological order (with ties being resolved using ‘first-in-first-out’). Because the system state doesn’t change between events, we do not need to ‘run the clock’ in fixed increments each timestep. Rather, time advances to the time of the next event in the queue, effectively optimizing computations especially when different modules have different characteristic time intervals (i.e., ‘timestep’).

‘Time’ is the core concept linking various simulation components via the event queue. Activities schedule events (which change the state of the system according to their programmed rules) and do not need to know about each other. Rather than wrapping a sequence of functions (events) inside a for loop for time and iterating through each timestep, each event is simply scheduled to be completed. Repeated events are simply scheduled repeatedly. This not only allows for modularity of simulation components, it also allows complex model dynamics to emerge based on scheduling rules of each activity (module). Thus, complex simulations involving multiple processes (activities) can be built fairly easily, provided these processes are modelled using a common DES framework.

SpaDES provides such a framework, facilitating interaction between multiple processes (built as ‘modules’) that don’t interact with one another directly, but are scheduled in the event queue and carry out operations on shared data objects in the simulation environment. This package provides tools for building modules natively in R that can be reused. Additionally, because of the flexibility R provides for interacting with other programming languages and external data sources, modules can also be built using external tools and integrated with SpaDES (see figure below).

## SpaDES modules

A SpaDES module describes the processes or activities that drive simulation state changes via changes to objects stored in the simulation environment. Each activity consists of a collection of events which are scheduled depending on the rules of the simulation. Each event may evaluate or modify a simulation data object (e.g., update the values on a raster map), or perform other operations such as saving and loading data objects or plotting.

The power of SpaDES is in modularity and the relative ease with which existing modules can be modified and new modules created, in native R as well as through the incorporation of external simulation modules. Creating and customizing modules is a whole topic unto itself, and for that reason we have created a separate modules vignette with more details on module development.

Strict modularity requires that modules can act independently, without needing to know about other modules. However, what if two (or more) modules are incompatible with one another? To address this, each SpaDES module is required to explicitly state its input dependencies (data, package, and parameterization requirements), data outputs, as well as provide other useful metadata and documentation for the user. Upon initialization of a simulation, the dependencies of every module used are examined and evaluated. If dependency incompatibilities exists, the initialization fails and the user is notified.

## SpaDES demos and sample modules

The PDF format does not allow us to demonstrate the simulation visualization components of this package, so we invite you to check out the included demos, to run the sample simulation provided in this vignette, and to view the source code for the sample modules included in this package.

A simple demo is provided with the package that highlights the ‘real time’ graphics capabilities of package’s Plot function. This demo loads three sample modules provided with the packages: 1) randomLandscapes, 2) fireSpread, and 3) caribouMovement. These sample modules, respectively, highlight several keys features of the package: 1) the import, update, and plotting of raster map layers; 2) the computational speed of modeling spatial spread processes; and 3) the implementation of an agent-based (a.k.a., individual-based) model.

library("SpaDES.core")
demo("spades-simulation", package = "SpaDES.core")

Additional SpaDES modules are available via a GitHub repository: https://github.com/PredictiveEcology/SpaDES-modules. Modules from this repository can be downloaded to a local directory using:

downloadModule(name = "moduleName")

Note: by default, modules and their data are saved to the directory specified by the spades.modulesPath. An alternate path can be provided to downloadModule directly via the path argument, or specified using options(spades.modulesPath = "path/to/my/modules").

A detailed guide to module development is provided in the modules vignette.

# Simulation and data

Historically, simulation models were built separately from the analysis of input data (e.g., via regression) and outputs of data (e.g., graphically, statistically). On the input data side, this effectively broke the linkage between data (e.g., from field or satellites) and the simulation. This has the undesired effect of creating the appearance of reduced uncertainty in simulation model predictions, by breaking correlations between parameter estimates (that invariably occur in analyses of real data), or simply by passing an incorrectly specified parameter uncertainty to a simulation model.

Conversely, on the data output side, numerous tools, such as optimization (e.g., pattern oriented modeling Grimm et al. 2005) or statistical analyses could not directly interact with the simulation model, unless a specific extension was built for that purpose. In R, those tools already exist and are robust. Thus, validation, calibration, and verification of simulation models can become rolled into the simulation model itself, facilitating understanding of models’ forecasting performance and thus their predictive capacity. All of these enhance transparency and reproducibility, both desired properties for scientific studies.

Linking the raw data, data analysis, validation, calibration (via optimization), simulation forecasting, and output analyses into a single work flow allow for several powerful outcomes:

1. updates to raw data can be easily propagated into the outputs;
2. uncertainty in raw data can be passed through to simulations;
3. decision makers can be given tools that draw directly on raw data and so lag times between data updates and decision making updates can be dramatically shortened;
4. feedbacks between disciplinary silos can be simulated, promoting disciplinary integration.

# Using SpaDES

As you can see in the sample simulation code provided above, setting up and running a simulation in SpaDES is straightforward using existing modules. You need to specify some things about the simulation environment including 1) which modules to use for the simulation, and 2) any data objects (e.g., parameter values) that should be used to store the simulation state. Each of these are passed as named lists to the simulation object upon initialization.

## SpaDES documentation and vignettes

### Help files

From within R, typing ?'spades-package', will give an categorized view of the functions within SpaDES.

### Vignettes

The following package vignettes are intended to be read in sequence, and follow a progression from higher-level package organization and motivation, to detailed implementation of user-built modules and simulations. To view available vignettes use browseVignettes(package = "SpaDES.core") (this will only be available from a CRAN download).

1. introduction: Introduction to SpaDES. This vignette.
2. modules: Building modules in SpaDES. A detailed guide to module design, modifying existing modules, and creating new modules.
3. caching: Caching SpaDES simulations. A closer look at caching for a rproducible workflow.

### Wiki

Additional guides for getting started with SpaDES and debugging are provided at our wiki:

### Q&A Forum

General help and discussion of SpaDES usage and module development.

## SpaDES module repository

We provide a number of modules to facilitate getting started:

Modules from this (or another suitable GitHub repository) can be downloaded using downloadModule.

We welcome additional contributions to this module repository.

## Reporting bugs

For general help with SpaDES and module development please see our Q&A Forum https://groups.google.com/d/forum/spades-users.

# References

Bivand, Roger S, Edzer J Pebesma, and Virgilio Gomez-Rubio. 2013. Applied spatial data analysis with R. Second edi. NY: Springer. http://www.asdar-book.org/.

Eddelbuettel, Dirk. 2013. Seamless R and C++ Integration with Rcpp. New York, NY: Springer.

Eddelbuettel, Dirk, and Romain Francois. 2011. “Rcpp : Seamless R and C++ Integration.” Journal of Statistical Software 40 (8): 1–18. http://www.jstatsoft.org/v40/i08/.

Fall, Andrew, and Joseph Fall. 2001. “A domain-specific language for models of landscape dynamics.” Ecological Modelling 141: 1–18.

Grimm, Volker, and Steven F Railsback. 2005. Individual-based modelling and ecology. Princeton, NJ: Princeton University Press. http://www.humboldt.edu/ecomodel/documents/Grimm-Railsback05.pdf.

Grimm, Volker, Eloy Revilla, Uta Berger, Florian Jeltsch, Wolf M Mooij, Steven F Railsback, Hans-Hermann Thulke, Jacob Weiner, Thorsten Wiegand, and Donald L DeAngelis. 2005. “Pattern-oriented modeling of agent-based complex systems: lessons from ecology.” Science 310 (5750): 987–91. doi:10.1126/science.1116681.

Hijmans, Robert J. 2015. raster: Geographic Data Analysis and Modeling. https://CRAN.R-project.org/package=raster.

Pebesma, Edzer J, and Roger S Bivand. 2005. “Classes and methods for spatial data in R.” R News 5 (2). https://cran.r-project.org/doc/Rnews/.

Scheller, Robert M, James B Domingo, Brian R Sturtevant, Jeremy S Williams, Arnold Rudy, Eric J Gustafson, and David J Mladenoff. 2007. “Design, development, and application of LANDIS-II, a spatial landscape simulation model with flexible temporal and spatial resolution.” Ecological Modelling 201: 409–19. doi:10.1016/j.ecolmodel.2006.10.009.

Thiele, Jan C, and Volker Grimm. 2015. “Replicating and breaking models: good for you and good for ecology.” Oikos. doi:10.1111/oik.02170.