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("WS/b_ws.RData")
load("WS/w_ws.RData")

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

load("WS/player_names_ws.RData")
load("WS/res_ada_ws.RData")

alphas <- res_ada_ws$alphas
dimnames(alphas) <- list(player_names_ws[res_ada_ws$cases], player_names_ws) 
numArchoid <- 4

# Set of similar players:
player <- "Joel Embiid_embiijo01"
alphas[, grep(player, colnames(alphas))]
#Steve Burtt_burttst01   Ben Wallace_wallabe01  Otis Birdsong_birdsot01   LeBron James_jamesle01 
#            0.4175013               0.1784859                0.2895601                0.1144515
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_ws <- executing_ropes(sim_pl, b_ws, w_ws, lambda2Ages, lambda1Ages, lambda0Ages)
s1 <- Sys.time() - s0
s1
#Time difference of 57.17655 secs
#save(res_ropes_ws, file = "Predictions/res_ropes_ws.RData")
#load("Predictions/res_ropes_ws.RData")

num_iter <- 10
s0 <- Sys.time()
res_fi_ws <- forec_intervals_ropes(res_ropes_ws, num_iter, lambda2Ages, lambda1Ages, lambda0Ages)
s1 <- Sys.time() - s0
s1
#Time difference of 4.007152 mins
#save(res_fi_ws, file = "Predictions/res_fi_ws.RData")
#load("Predictions/res_fi_ws.RData")

b_ropes <- res_ropes_ws$b_12
q <- res_fi_ws
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] 17
cIn
#[1] 355
(cOut / (cOut + cIn) * 100)
#[1] 4.569892
# True value is out of the confidence interval in approx. the 5% of the intervals.

# Forecasting plot:
# Compare with https://projects.fivethirtyeight.com/carmelo/joel-embiid/
library(ggplot2)
do_plot_forec_players(player, b_ropes, q, "Ages (time points)", "WS", TRUE, FALSE)
ggsave("Figures/Fig5_2.eps", width = 7)

