#this script assumes the data is already loaded, handled, and imputed in a dataframe called combined_dataset_complete
library(Rcpp)
library(ggplot2)
library(bayesplot)
library(StanHeaders)
library(rstantools)
library(loo)
library(rstan)
library(brms)

combined_dataset_complete$exposure_olanzapine <- combined_dataset_complete$exposure_dose * (combined_dataset_complete$treatment == "OLANZAPINE")
combined_dataset_complete$exposure_paliperidone <- combined_dataset_complete$exposure_dose * (combined_dataset_complete$treatment == "PALIPERIDONE")
combined_dataset_complete$exposure_risperidone <- combined_dataset_complete$exposure_dose * (combined_dataset_complete$treatment == "RISPERIDONE")


prior_coefs <- set_prior("student_t(5, 0, 2.5)", class = "b")
prior_sd <- set_prior("student_t(5, 0, 2)", class = "sd")
prior_cor <- set_prior("lkj(2)", class = "cor")

prior_all <- c(prior_coefs, prior_sd, prior_cor)

BRMFit <- brm(outcome ~ exposure_paliperidone + exposure_risperidone + exposure_olanzapine + (1 | trial) + (0 + exposure_paliperidone + exposure_risperidone + exposure_olanzapine | trial) + age + panss + bmi + race + sex + wg_drugs, family = "bernoulli", data = combined_dataset_complete, iter = 800, chains = 3, control = list(adapt_delta = .999, max_treedepth = 14), prior = prior_all)


#save(BRMFit, file = "brm_hierarchical_fit")



