Link Search Menu Expand Document

SimEngine

SimEngine

An open-source framework for statistical simulations in R

View source code on GitHub


Overview

SimEngine is an open-source R package for structuring, maintaining, running, and debugging statistical simulations on both local and cluster-based computing environments. Emphasis is placed on thorough documentation and scalability.

Installation

The latest stable version of SimEngine can be installed from CRAN using install.packages(). The current development version can be installed using devtools::install_github():

install.packages("SimEngine")
devtools::install_github(repo="Avi-Kenny/SimEngine")

Getting started

The goal of many statistical simulations is to test how a new statistical method performs against existing methods. Most statistical simulations include three basic phases: (1) generate some data, (2) run one or more methods using the generated data, and (3) compare the performance of the methods.

To briefly illustrate how these phases are implemented using SimEngine, we will use the example of estimating the average treatment effect of a drug in the context of a randomized controlled trial (RCT).

1) Load the package and create a “simulation object”

The simulation object (an R object of class SimEngine) will contain all data, functions, and results related to your simulation. Note that we make extensive use of the pipe operators (%>% and %<>%) from the magrittr package; if you have never used pipes, check out the magrittr documentation.

library(SimEngine)
sim <- new_sim()

2) Write a function to generate some data

In SimEngine, functions that generate data are called creators. Our creator will simulate data from an RCT in which we compare a continuous outcome (e.g. blood pressure) between two groups (the “treatment group” versus the “control group”). We generate the data by looping through individuals, assigning them randomly to either the treatment group or the control group, and generating their outcome according to a simple model (note: although we use a for-loop for illustrative purposes, vectorized methods are often faster).

create_rct_data <- function (num_patients) {
  df <- data.frame(
    "patient_id" = integer(),
    "group" = character(),
    "outcome" = double(),
    stringsAsFactors = FALSE
  )
  for (i in 1:num_patients) {
    group <- ifelse(sample(c(0,1), size=1)==1, "treatment", "control")
    treatment_effect <- ifelse(group=="treatment", -7, 0)
    outcome <- rnorm(n=1, mean=130, sd=5) + treatment_effect
    df[i,] <- list(i, group, outcome)
  }
  return (df)
}

# Test our creator function
create_rct_data(5)
#>   patient_id     group  outcome
#> 1          1 treatment 140.6040
#> 2          2 treatment 125.9386
#> 3          3   control 106.2271
#> 4          4 treatment 131.7250
#> 5          5   control 129.4923

Once you have declared your creator function, add it to your simulation object using the add_creator() function.

sim %<>% add_creator(create_rct_data)

3) Code your methods

In this example, we test two different estimators of the average treatment effect. The first estimator uses the known probability of being assigned to the treatment group (0.5), whereas the second estimator uses an estimate of this probability based on the observed data. Don’t worry too much about the mathematical deatils; the important thing is that both methods attempt to take in the dataset generated by the create_rct_data() function and return an estimate of the true treatment effect, which in this case is -7.

estimator_1 <- function(df) {
  n <- nrow(df)
  true_prob <- 0.5
  sum_t <- sum(df$outcome * (df$group=="treatment"))
  sum_c <- sum(df$outcome * (df$group=="control"))
  return ( sum_t/(n*true_prob) - sum_c/(n*(1-true_prob)) )
}
estimator_2 <- function(df) {
  n <- nrow(df)
  est_prob <- sum(df$group=="treatment") / n
  sum_t <- sum(df$outcome * (df$group=="treatment"))
  sum_c <- sum(df$outcome * (df$group=="control"))
  return ( sum_t/(n*est_prob) - sum_c/(n*(1-est_prob)) )
}

# Test our estimator functions
df <- create_rct_data(10000)
estimator_1(df)
#> [1] -7.291477
estimator_2(df)
#> [1] -7.038604

Next, add the methods to your simulation object using the add_method() function.

sim %<>% add_method(estimator_1)
sim %<>% add_method(estimator_2)

4) Set the simulation levels

Often, we want to run the same simulation multiple times (with each run referred to as a “simulation replicate”), but with certain things changed. In this example, perhaps we want to vary the number of patients and the method used to estimate the average treatment effect. We refer to the things that vary as “simulation levels”. By default, SimEngine will run our simulation 10 times for each level combination. Below, since there are two methods and three values of num_patients, we have six level combinations and so SimEngine will run a total of 60 simulation replicates.

sim %<>% set_levels(
  estimator = c("estimator_1", "estimator_2"),
  num_patients = c(50, 200, 1000)
)

5) Create a simulation script

The simulation script is a function that runs a single simulation replicate and returns the results. Within a script, you can reference the current simulation level values using the variable L. For example, when the first simulation replicate is running, L$estimator will equal “estimator_1” and L$num_patients will equal 50. In the last simulation replicate, L$estimator will equal “estimator_2” and L$num_patients will equal 1,000. This can be used in conjunction with use_method() to dynamically run different methods within different simulation replicates (as is illustrated below). Your script will have access to any creators and methods that have been added to your simulation object.

sim %<>% set_script(function() {
  df <- create_rct_data(L$num_patients)
  estimate <- use_method(L$estimator, list(df))
  return (list("estimate"=estimate))
})

Your script should always return a named list, although your list can be complex and contain dataframes, multiple levels of nesting, etc.

6) Set the simulation configuration

This controls options related to your entire simulation, such as the number of simulation replicates to run for each level combination and how to parallelize your code. This is discussed in detail on the set_config page. We set num_sim to 10, and so SimEngine will run a total of 60 simulation replicates (10 for each level combination).

sim %<>% set_config(
  num_sim = 10,
  parallel = "outer",
  n_cores = 2
)

7) Run the simulation

All 600 replicates are run at once and results are stored in the simulation object.

sim %<>% run()
#> "Done. No errors detected."

8) View and summarize results

Once the simulations have finished, use the summarize() function to calculate common summary statistics, such as bias, variance, MSE, and coverage.

sim %>% summarize(
  bias = list(name="bias_ate", truth=-7, estimate="estimate"),
  mse = list(name="mse_ate", truth=-7, estimate="estimate")
)
#>   level_id   estimator num_patients mean_runtime mean_estimate    bias_ate      mse_ate
#> 1        1 estimator_1           50  0.004853940     -4.086867  2.91313267 1221.3380496
#> 2        2 estimator_2           50  0.004429979     -7.116263 -0.11626316    1.9830060
#> 3        3 estimator_1          100  0.008662744    -12.559415 -5.55941452  614.2357481
#> 4        4 estimator_2          100  0.008607748     -7.057722 -0.05772176    0.9293629
#> 5        5 estimator_1          200  0.018162758     -6.771745  0.22825547  376.3410262
#> 6        6 estimator_2          200  0.016390090     -6.795681  0.20431877    0.5332393

In this example, we see that the MSE of estimator 1 is much higher than that of estimator 2 and that MSE decreases with increasing sample size for both estimators, as expected.

You can also directly access the results for individual simulation replicates.

head(sim$results)
#>   sim_uid level_id sim_id   estimator num_patients     runtime   estimate
#> 1       1        1      1 estimator_1           50 0.007977009 -47.961709
#> 2       2        1      2 estimator_1           50 0.010969162  23.805217
#> 3       3        1      3 estimator_1           50 0.006983995  -8.066438
#> 4       4        1      4 estimator_1           50 0.004987001 -15.221781
#> 5       5        1      5 estimator_1           50 0.003988981   2.726603
#> 6       6        1      6 estimator_1           50 0.010968924  13.232685

About this project

SimEngine was created by Avi Kenny and Charles Wolock. The package is licensed using the GNU General Public Licence (GPL) V3.