# install from local tar
setwd("./software_release")
install.packages("quantbayes_v0.1.0_R.tar.gz", repos = NULL, type = "source")

# load
library(quantbayes)
citation(package = "quantbayes", lib.loc = NULL, auto = NULL)

set.seed(666)

??quantbayes() # open the vignette manual

# 1. LOAD DEMO DATA ----
data(core_test_data, package = "quantbayes")
print(head(core_test_data))

# Construct matrix
x <- as.matrix(core_test_data[, -1])
rownames(x) <- core_test_data[[1]]

# 2. RUN CORE FUNCTION ----
res <- quant_es_core(x)
print(res$global)
print(head(res$variants))

# if you want data frame
res_df <- as.data.frame(res$variants)
global_df <- as.data.frame(res$global)

# sort by theta_mean decreasing
res_df <- res_df[order(res_df$theta_mean, decreasing = TRUE), ]
head(res_df)
head(global_df)

# 3. CORE FUNCTION WITH CUSTOM PRIORS ----
# not recommended for our use but may be useful
res_custom <- quant_es_core(x, a = 2, b = 3, ci_level = 0.90)
print(res_custom$global)

# 4. TEST PLOTTING (default aesthetics) ----
plots <- quant_es_plots(res, x)
print(plots$p_global)
print(plots$p_overlay)
print(plots$p_matrix)
print(plots$p_p_hat)
print(plots$p_theta_ci)

# 5. FLAGSHIP PLOT  ----

# Flagship overlay plot with internal colours and clean legend
swiss_red <- "#ee4035"
federal_blue <- "#2f4356"

highlight_flagship <- list(
  list(id = core_test_data[[1]][1], colour = swiss_red, size = 4),
  list(id = "6-17481874-C-G_AR", colour = federal_blue, size = 4)
)

plots_flagship <- quant_es_plots(
  res,
  x,
  highlight_points = highlight_flagship
)

flagship_plot <- plots_flagship$p_overlay +
  ggplot2::guides(
    fill = ggplot2::guide_legend(title = "highlighted variants"),
    # colour = "none",
    size = "none"
  ) +
  ggplot2::labs(
    title = "GLobal posterior theta distribution",
    subtitle = "Top 10 CrI estimates with evidence available\nand two highlighted variants"
  ) +
  ggplot2::theme(
    legend.position = "right",
    legend.title = ggplot2::element_text(size = 10),
    legend.text = ggplot2::element_text(size = 9)
  )

flagship_plot
