packs <- c("ggplot2", "gridExtra", "grid", "gridtext", "latex2exp")
packs <- packs[!packs %in% installed.packages()]
if(length(packs) != 0) install.packages(packs)
rm(packs)

library(ggplot2)
library(latex2exp)
library(gridExtra)
library(grid)
library(gridtext)

gg_qq_empirical <- function(a, b, quantiles = seq(0, 1, 0.01)){
  ggplot(mapping = aes(x = quantile(a, quantiles, na.rm = T), 
                       y = quantile(scale(b), quantiles, na.rm = T))) + 
    geom_point() +
    geom_abline(aes(slope = 1, intercept = 0), linetype = 2)
}

q1den <- function(x, quant, item, model){
  mu <- plogis(model$b[item,1,1] + model$b[item,2,1]*x)
  sg <- plogis(model$b[item,1,2] + model$b[item,2,2]*x)
  shape1 = mu*(1-sg^2)/(sg^2)
  shape2 = (1-mu)*(1-sg^2)/(sg^2)
  return(qbeta(quant, shape1, shape2))
}

gg_q_data <- function(data){
  ggplot(mapping = aes(data)) + 
    stat_ecdf(geom = "step", linewidth = 1, na.rm = T, alpha = 1, colour = "black", pad = F) + 
    ylab(TeX(r"(Empirical percentiles (CDF))")) + 
    xlab(TeX(r"(Thermometer rating (scaled))"))
}