rm(list = ls())

setwd("[enter directory where MC_results_...RData is stored]")

library(dplyr)
library(ggplot2)

# Choose design
design <- 2 # 1 is uneqal MSEs, 2 is scaled t distribution
if (design == 1){
  svnm <- "unequal_MSEs_"
} else {
  svnm <- "t_distributed_forecasts_"
}
addns <- c("DSS", "LogS", "variance", "cords")

# Parameters for plots (pdf figures)
plot_width <- 5
plot_height <- 5

# Colors for plots
cols <- c("#000000", "#E69F00", "#56B4E9")

# Load results
load(paste0("MC_results_", substr(svnm, 1, nchar(svnm) - 1), ".RData"))
df <- mc_results$df
df_cor <- mc_results$df_cor

# Compute optimal weight 
w_opt <- df %>% group_by(measure, pool) %>% arrange(w) %>%
  summarise(w_opt = w[which.min(value)]) 

# Loop over plots for scores (DSS, LogS) and variance
line_width <- 1.2
for (kk in 1:3){
  inds <- ((kk-1)*3 + 1):(kk*3)
  measure_sel <- c("dss", "logs", "v")[kk]
  ylab_sel <- c("DSS", "LogS", "Variance")[kk]
  ggp <- ggplot(filter(df, measure == measure_sel),
                aes(x = w, y = value, color = pool,
                    linetype = pool)) + 
    geom_line(size = I(line_width)) + 
    scale_color_manual(values = cols, 
                       breaks = c("LP", "CLP", "VULP"), 
                       labels = c("LP", "CLP", "VULP"), 
                       name = "") + 
    xlab(expression("Combination Weight"~omega[1])) + ylab(ylab_sel) + 
    scale_linetype_manual(values = 1:3, name = "", 
                          breaks = c("LP", "CLP", "VULP"), 
                          labels = c("LP", "CLP", "VULP")) + 
    theme_minimal(base_size = 18) + 
    theme(legend.position = "top") 
  # Add vertical line for optimal weight
  if (kk %in% 1:2){
    ggp <- ggp + geom_vline(xintercept = 
                              filter(w_opt, measure == "v" & pool == "VULP")$w_opt,
                            color = cols[3], linetype = 3, size = I(2*line_width))
  }
  ggsave(plot = ggp, filename = paste0("outputs/", svnm, addns[kk], ".pdf"), 
         width = plot_width, height = plot_height)
}

# Plot for correlation between D and S
ggp2 <- ggplot(df_cor, aes(x = x, y = y)) + 
  geom_line(size = I(line_width), color = "#009E73") + 
  xlab(expression("Combination Weight"~omega[1])) + ylab("Cor(D,S)") + 
  theme_minimal(base_size = 18) + ylim(c(-.1, .5)) + 
  geom_hline(yintercept = 0, size = .4, lty = 2) + 
  geom_vline(xintercept = filter(w_opt, measure == "v" & pool == "VULP")$w_opt, 
             color = cols[3], linetype = 3, size = I(2*line_width))
ggsave(plot = ggp2, filename = paste0("outputs/", svnm, addns[4], ".pdf"), 
       width = plot_width, height = plot_height)