library(MASS)
library(compiler)
library(parallel)
library(foreach)
library(doMC)
library(bigmemory)
library(synchronicity)

# Set working directory.
#setwd(".../Code_and_data_v1/")

# Ropes functions:
source("Algorithm/BAwR_internalROPES.R")
source("Algorithm/ropes.R")
source("Algorithm/executing_ropes.R")
source("Algorithm/forec_intervals_ropes.R")
source("do_similar_players.R")
source("Figures/do_plot_forec_players.R")

# Load b and w matrices:
load("ACB/Code/b_pir_acb.RData")
load("ACB/Code/w_pir_acb.RData")

# Optimal lambda combination for ropes:
lambda2Ages <- 900
lambda1Ages <- 10
lambda0Ages <- 10

load("ACB/Code/player_names_pir_acb.RData")
load("ACB/Code/res_ada_pir_acb.RData")

alphas <- res_ada_pir_acb$alphas
dimnames(alphas) <- list(player_names_pir_acb[res_ada_pir_acb$cases], player_names_pir_acb) 
numArchoid <- 4

# Set of similar players:
player <- "Doncic, Luka~460"
alphas[, grep(player, colnames(alphas))]
#Vazquez, Paco~AR4     Sabonis, A.~AAM      Bell, T.~B6W    Fernandez, Rudy~B0X 
#        0.0000000           0.5437567         0.0000000              0.4655219

sim_pl <- do_similar_players(player, alphas, numArchoid, FALSE)
# In order to avoid a long computational time, when the set of similar players
# is very large, we restrict it to the first 100 players (and the target player 
# itself). This makes sense, because we can assume that the rest of the players 
# don't provide additional valuable information.
if (length(sim_pl) > 200) {
  sim_pl <- c(sim_pl[1:100], sim_pl[length(sim_pl)])
}

s0 <- Sys.time()
res_ropes_pir_acb <- executing_ropes(sim_pl, b_pir_acb, w_pir_acb, lambda2Ages, lambda1Ages, lambda0Ages)
s1 <- Sys.time() - s0
s1
#Time difference of 1.291141 mins
save(res_ropes_pir_acb, file = "ACB/Code/res_ropes_pir_acb.RData")
#load("ACB/Code/res_ropes_pir_acb.RData")

num_iter <- 10
s0 <- Sys.time()
res_fi_pir_acb <- forec_intervals_ropes(res_ropes_pir_acb, num_iter, lambda2Ages, lambda1Ages, lambda0Ages)
s1 <- Sys.time() - s0
s1
#Time difference of 10.3737 mins
#save(res_fi_pir_acb, file = "ACB/Code/res_fi_pir_acb.RData")
#load("ACB/Code/res_fi_pir_acb.RData")

b_ropes <- res_ropes_pir_acb$b_12
q <- res_fi_pir_acb
cIn = cOut = 0
for (i in 1:nrow(b_ropes)) {
  for (j in 1:ncol(b_ropes)) {
    if (!is.na(b_ropes[i,j])) {
      val = b_ropes[i,j]
      if (val >= q[1,i,j] && val <= q[5,i,j]) {
        cIn = cIn + 1
      }
      else{
        cOut = cOut + 1
      }
    }
  }
}
cOut
#[1] 12
cIn
#[1] 322
(cOut / (cOut + cIn) * 100)
#[1] 3.592814
# True value is out of the confidence interval in approx. the 5% of the intervals.

# Forecasting plot:
# Compare with https://projects.fivethirtyeight.com/carmelo/luka-doncic/
library(ggplot2)
g1 <- do_plot_forec_players(player, b_ropes, q, "Ages (time points)", "PIR", TRUE, FALSE)
g1 + ggtitle("Luka Doncic") + theme(axis.text.x = element_text(size = 8))
ggsave("ACB/Doncic.eps", width = 7)
