---
title: "Trial Simulation Example of Bayesian MCPMod for Binary Data"
format: 
  html:
    fig-height: 3.5
    self-contained: true
    toc: true
    number-sections: true
    code-summary: setup
    #code-fold: true
    message: false
    warning: false
bibliography: references.bib
vignette: >
  %\VignetteIndexEntry{Trial Simulation Example of Bayesian MCPMod for Binary Data}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup}
#| message: false
#| warning: false

suppressPackageStartupMessages({
  library(BayesianMCPMod)
  library(RBesT)
  library(DoseFinding)
  library(clinDR)
  library(dplyr)
  library(tibble)
  library(reactable)
})

set.seed(7015)
```

# Background and Data

In this vignette, we will show the use of the `BayesianMCPMod` R package for trial planning for binary data. 

For this setting the main specifications need to happen on the logit scale, see also the [binary analysis example vignette](binary_endpoint.html).

<div class="alert alert-info">

- Internally, `BayesianMCPMod` fits binary endpoints on the **logit scale**.
- The function argument `probability_scale` controls whether outputs (summaries, predictions, plots)
  are back-transformed to **probabilities**.
- In `simulateData()`, outcomes are simulated on the response scale if `probability_scale = TRUE`.
- In `getMED()`, `delta` is interpreted on the **probability scale** if `probability_scale = TRUE`.

</div>

As in the [analysis example vignette](analysis_normal.html), we make use of historical data that is included in the clinDR package. 
More specifically, trial results for XELJANZ will be utilized to establish an informative prior for the control group.

This package makes use of the [future](https://cran.r-project.org/package=future) framework for parallel processing, which can be set up for example as follows:
```{r, eval = FALSE}
future::plan(future::multisession, workers = 4L)
```
Kindly note that due to overhead a reduced number of worker nodes can be preferable and that for short calculations sequential execution can be faster.

# Calculation of a MAP Prior
For this example, in a first step, a meta analytic prior will be calculated.
The approach to establish the prior is the same as outlined in the [binary analysis example vignette](binary_endpoint.html). 
Please note that only information from the control group will be integrated leading to an informative mixture prior for the control group, while for the active groups a non-informative prior will be specified.

```{r}
data("metaData")
testdata    <- as.data.frame(metaData)
dataset     <- filter(testdata, bname == "XELJANZ")
histcontrol <- filter(dataset, dose == 0, primtime == 12, indication == "RHEUMATOID ARTHRITIS")

hist_data <- data.frame(
  trial = histcontrol$nctno,
  est   = histcontrol$rslt,
  se    = histcontrol$se,
  sd    = histcontrol$sd,
  r     = round(histcontrol$sampsize*histcontrol$rslt),
  n     = histcontrol$sampsize)

sd_tot <- with(hist_data, sum(sd * n) / sum(n))
```

```{r}
dose_levels <- c(0, 2.5, 5, 10,20)

# 1) Establish MAP prior (beta mixture distribution) 
set.seed(7015) # re-sets seed only for this example; remove in your analysis script
map <- gMAP(
  cbind(hist_data$r, hist_data$n - hist_data$r) ~ 1 | histcontrol$nctno,
  family     = binomial,
  tau.dist   = "HalfNormal",
  tau.prior  = 0.5,
  beta.prior = (1 / sqrt(0.1 * 0.9)),
  warmup     = 1000,
  iter       = 10000,
  chains     = 2,
  thin       = 1
)

prior <- automixfit(map) #fits mixture distribution from MCMC samples from above

p <- summary(prior)[1]

# 2) Robustify prior
prior_rob <- RBesT::robustify(
      priormix = prior,
      mean     = 0.5,
      weight   = 0.2)

# 3) Translate prior to logit scale (to approximate via normal mixture model)
r         <- rmix(prior_rob, n = 1e4)
log_r     <- logit(r)
prior_ctr <- automixfit(log_r, type = "norm")

# Specification of reference scale (this follows the idea of [@Neuenschwander2016]). 
sigma(prior_ctr) <- sqrt(1 / (p * (1 - p)))

# Specify a prior list
prior_trt <- RBesT::mixnorm(
    comp1 = c(w = 1, m = logit(summary(prior)[1]), n = 1),
    sigma = sqrt(1/(p*(1-p))),
    param = "mn")
  
  prior_list <- c(list(prior_ctr),
                  rep(x     = list(prior_trt),
                      times = length(dose_levels[-1])))

dose_names        <- c("Ctr", paste0("DG_", seq_along(dose_levels[-1])))
names(prior_list) <- dose_names
```

Kindly note that a vague prior could be implemented via
```{r Setting Vague Prior Without Execution, eval = TRUE}
prior_list_vague <- rep(list(RBesT::mixnorm(
  comp1 = c(w = 1, m = logit(p), n = 1),
  sigma = sqrt(1 / (p * (1 - p))),
  param = "mn"
)), times = length(dose_levels))
names(prior_list_vague) <- c("Ctrl", "DG_1", "DG_2", "DG_3", "DG_4")
```

# Specification of the New Trial Design 

For the hypothetical new trial, we plan with 4 active dose levels \eqn{2.5, 5, 10, 20} and we specify a broad set of potential dose-response relationships, including a linear, an exponential, an emax, a logistic and a sigEMAX models.  
Furthermore, we assume a maximum response rate of 48% (resp. 30% on top of control) and plan a trial with 40 patients for all active groups and 30 patients for control.
Please note that the response rates need to be provided on the **logit scale**.

```{r}
n_patients <- c(30, 40, 40, 40, 40)

models <- Mods(
  linear      = NULL,
  sigEmax     = c(10, 5),
  logistic    = c(11, 15),
  exponential = 10,
  emax        = 2,
  doses       = dose_levels,
  placEff     = RBesT::logit(0.18),
  maxEff      = (RBesT::logit(0.48) - RBesT::logit(0.18))
)
```

# Calculation of the Success Probabilities

To calculate success probabilities for the different assumed dose-response models and the specified trial design we will apply the `assessDesign()` function. 
We are not only interested in the success probability for the testing step, but also the assessment of the Minimally Efficacious Dose (MED).
This effect delta is provided on the probability scale.
In our case we would like to see a difference of 20% compared to control to claim efficacy. 

For illustration purposes, the number of simulated trial results is reduced to `100` in this example.
```{r}
set.seed(7015) # re-sets seed only for this example; remove in your analysis script
success_probabilities <- assessDesign(
  n_patients        = n_patients,
  mods              = models,
  prior_list        = prior_list,
  probability_scale = TRUE,
  delta             = 0.2,
  n_sim             = 100) # speed up example run-time
success_probabilities
```

As an alternative, we will evaluate a design with the same overall sample size but allocating more patients on the highest dose group and control.
```{r}
set.seed(7015) # re-sets seed only for this example; remove in your analysis script
success_probabilities_uneq <- assessDesign(
  n_patients        = c(40, 30, 30, 30, 50),
  mods              = models,
  prior_list        = prior_list,
  probability_scale = TRUE,
  delta             = 0.2,
  n_sim             = 100) # speed up example run-time
success_probabilities_uneq
```

As a second alternative we will use the vague prior:
```{r}
set.seed(7015) # re-sets seed only for this example; remove in your analysis script
success_probabilities_vague <- assessDesign(
  n_patients        = n_patients,
  mods              = models,
  prior_list        = prior_list_vague,
  probability_scale = TRUE,
  delta             = 0.2,
  n_sim             = 100) # speed up example run-time
success_probabilities_vague
```


