An R wrapper for pysd, using the CRAN reticulate package.
The goal of this package is to allow R users run system dynamics models using pysd, (designed and developed by James Houghton). The pysd project “is a simple library for running System Dynamics models in python, with the purpose of improving integration of Big Data and Machine Learning into the SD workflow.”
The pysd system must be installed before installing this package: see pysd installation instructions
pysd2r has been tested with python3, and the following command was used to install pysd from source.
python3 setup.py install
Given R’s facility for also providing big data and machine learning support, this package opens up the functionality of pysd for R users, and provides an interface to the basic set of methods provided by pysd, including the functions:
The API provide by pysd2r includes the following functions (for list of parameters type ?function_name in R) which call the mapping functions in pysd.
You can install pysd2r from github with:
# install.packages("devtools")
::install_github("JimDuggan/pysd2r") devtools
The following example shows how pysd2r can be used to run a simulation model (Population.mdl which is a one-stock Vensim model of population growth).
## basic example code
library(pysd2r)
#> Welcome to package pysd2r.
library(ggplot2)
<- system.file("models/vensim", "Population.mdl", package = "pysd2r")
target
<- pysd_connect()
py
<- read_vensim(py, target)
py
<- run_model(py)
results
<- list("Growth Fraction"=0.02)
l
set_components(py,l)
<- run_model(py)
out2
ggplot(data=results)+
geom_point(aes(x=TIME,y=Population),colour="blue")+
geom_point(data=out2,aes(x=TIME,y=Population),colour="red")
The following example shows how pysd2r can be used to run an ensemble of simulations.
library(pysd2r)
library(ggplot2)
library(plyr)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:plyr':
#>
#> arrange, count, desc, failwith, id, mutate, rename, summarise,
#> summarize
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
<- system.file("models/vensim", "Population.mdl", package = "pysd2r")
target
<- seq(0.01,0.04,by=0.0025)
gr
<- pysd_connect()
py <- read_vensim(py, target)
py
<- lapply(gr, function (g){
ans <- list("Growth Fraction"=g)
l set_components(py,l)
<- run_model(py)
out $Key <- paste0("GR=",g)
out<- select(out,TIME,Population,Key)
out
})
<- rbind.fill(ans)
full
ggplot(data=full)+
geom_point(aes(x=TIME,y=Population,colour=Key))