## ----setup--------------------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(cmrdesign)

## ----simulate-pilot-----------------------------------------------------------
set.seed(101)

n_pilot <- 160
d <- rbinom(n_pilot, size = 1, prob = 0.5)
y <- numeric(n_pilot)
y[d == 1] <- rbeta(sum(d == 1), shape1 = 5, shape2 = 3)
y[d == 0] <- rbeta(sum(d == 0), shape1 = 2.2, shape2 = 2.2)

pilot_summary <- aggregate(y, by = list(treatment = d), FUN = function(x) {
  c(mean = mean(x), variance = var(x), n = length(x))
})
pilot_summary

## ----bounded-cmr--------------------------------------------------------------
fit_bounded <- cmr_two_arm(y, d, method = "bounded", alpha = 0.05)

fit_bounded$pi
round(fit_bounded$rectangle, 4)
fit_bounded$U_CMR
fit_bounded$binding

## ----inspect-pilot-fields-----------------------------------------------------
fit_bounded$pilot$n
round(fit_bounded$pilot$vhat, 4)
fit_bounded$joint_error_bound

## ----realize-counts-----------------------------------------------------------
allocation <- realize_allocation(fit_bounded, n_main = 1000)

allocation$counts
allocation$shares
allocation$realized_U_CMR

## ----compare-methods----------------------------------------------------------
methods <- c("bounded", "mp", "mtr")

comparison <- do.call(rbind, lapply(methods, function(method) {
  fit <- cmr_two_arm(y, d, method = method, alpha = 0.05)
  c(
    pi = fit$pi,
    U_CMR = fit$U_CMR,
    v_l1 = fit$rectangle[["v_l1"]],
    v_u1 = fit$rectangle[["v_u1"]],
    v_l0 = fit$rectangle[["v_l0"]],
    v_u0 = fit$rectangle[["v_u0"]]
  )
}))
rownames(comparison) <- methods

round(comparison, 4)

## ----from-rectangle-----------------------------------------------------------
manual_fit <- cmr_two_arm_from_rectangle(fit_bounded$rectangle)

manual_fit$pi
manual_fit$U_CMR

