## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
has_cmdstan <- requireNamespace("cmdstanr", quietly = TRUE) &&
  !is.null(tryCatch(cmdstanr::cmdstan_version(error_on_NA = FALSE),
                    error = function(e) NULL))
run_stan <- has_cmdstan || requireNamespace("rstan", quietly = TRUE)

## ----data---------------------------------------------------------------------
library(cdtmbnma)
sv <- sacval_example()
head(sv)

## ----design-------------------------------------------------------------------
d <- cdt_data(
  sv,
  study = "study",
  components = c("d_sac", "d_val"),
  outcome = "continuous",
  y = "y",
  se = "se",
  dstar = c(d_sac = 200, d_val = 320)
)
d

## ----fit, eval = run_stan-----------------------------------------------------
fit <- cdt_fit(
  d,
  interaction = "bilinear",
  chains = 4,
  iter_warmup = 1000,
  iter_sampling = 1000,
  seed = 1
)
summary(fit)

## ----plot, eval = run_stan, fig.width = 7, fig.height = 4---------------------
plot(fit)

## ----predict, eval = run_stan-------------------------------------------------
predict(fit, newdata = data.frame(d_sac = 100, d_val = 160))

## ----additive, eval = FALSE---------------------------------------------------
# fit_add <- cdt_fit(d, interaction = "none")

## ----loo, eval = FALSE--------------------------------------------------------
# loo::loo_compare(
#   loo::loo(fit$fit$draws("log_lik")),
#   loo::loo(fit_add$fit$draws("log_lik"))
# )

## ----time-design--------------------------------------------------------------
long_dat <- data.frame(
  study = rep("trial1", 6),
  arm = rep(c("placebo", "A", "AB"), each = 2),
  week = rep(c(4, 8), 3),
  dose_A = rep(c(0, 10, 10), each = 2),
  dose_B = rep(c(0, 0, 20), each = 2),
  y = c(0, 0, -1, -2, -2, -3),
  se = rep(1, 6)
)

time_design <- cdt_time_data(
  long_dat,
  study = "study",
  arm = "arm",
  time = "week",
  components = c("dose_A", "dose_B"),
  y = "y",
  se = "se",
  dstar = c(dose_A = 10, dose_B = 20)
)
time_design

## ----time-fit, eval = FALSE---------------------------------------------------
# fit_time <- cdt_time_fit(time_design)
# predict(fit_time, data.frame(dose_A = 10, dose_B = 20))

