---
title: "Trial Simulation"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Trial Simulation}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```


## Example

This is a basic example which shows how to run simulations from a CRM with 
a 2-parameter logistic regression model, using a log normal prior distribution,
and custom cohort size, stopping and maximum increments rules:

```{r example, message = FALSE}
library(crmPack)

# Define the dose grid.
empty_data <- Data(doseGrid = c(1, 3, 5, 10, 15, 20, 25, 40, 50, 80, 100))

# Initialize the CRM model.
model <- LogisticLogNormal(
  mean = c(-0.85, 1),
  cov = matrix(c(1, -0.5, -0.5, 1), nrow = 2),
  ref_dose = 56
)

# Choose the rule for selecting the next dose.
my_next_best <- NextBestNCRM(
  target = c(0.2, 0.35),
  overdose = c(0.35, 1),
  max_overdose_prob = 0.25
)

# Choose the rule for the cohort size.
my_size_1 <- CohortSizeRange(
  intervals = c(0, 30),
  cohort_size = c(1, 3)
)
my_size_2 <- CohortSizeDLT(
  intervals = c(0, 1),
  cohort_size = c(1, 3)
)
my_size <- maxSize(my_size_1, my_size_2)

# Choose the rule for stopping.
my_stopping_1 <- StoppingMinCohorts(nCohorts = 3)
my_stopping_2 <- StoppingTargetProb(
  target = c(0.2, 0.35),
  prob = 0.5
)
my_stopping_3 <- StoppingMinPatients(nPatients = 20)
my_stopping <- (my_stopping_1 & my_stopping_2) | my_stopping_3

# Choose the rule for dose increments.
my_increments <- IncrementsRelative(
  intervals = c(0, 20),
  increments = c(1, 0.33)
)

# Initialize the design.
design <- Design(
  model = model,
  nextBest = my_next_best,
  stopping = my_stopping,
  increments = my_increments,
  cohort_size = my_size,
  data = empty_data,
  startingDose = 3
)

# Define the true function.
my_truth <- function(dose) {
  alpha0 <- 7
  alpha1 <- 8
  ref_dose <- 56
  stand_log_dose <- log(dose / ref_dose)
  plogis(alpha0 + alpha1 * stand_log_dose)
}

# Run the simulation on the desired design.
# We only generate 1 trial outcome here for illustration, for the actual study
# this should be increased of course.
options <- McmcOptions(
  burnin = 100,
  step = 1,
  samples = 2000
)
time <- system.time(my_sims <- simulate(design,
  args = NULL,
  truth = my_truth,
  nsim = 1,
  seed = 819,
  mcmcOptions = options,
  parallel = FALSE
))[3]
```
