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("BPM/b_bpm.RData")
load("BPM/w_bpm.RData")

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

load("BPM/player_names_bpm.RData")
load("BPM/res_ada_bpm.RData")

alphas <- res_ada_bpm$alphas
dimnames(alphas) <- list(player_names_bpm[res_ada_bpm$cases], player_names_bpm) 
numArchoid <- 5 

# Set of similar players:
player <- "Joel Embiid_embiijo01" # Donovan Mitchell_mitchdo01
alphas[, grep(player, colnames(alphas))]
#Devin Gray_grayde01 Darryl Dawkins_dawkida01  Diamond Stone_stonedi01     Eddy Curry_curryed01 
#          0.2286803                0.1563753                0.0000000                0.1283133 
#LeBron James_jamesle01 
#             0.4866382
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_bpm <- executing_ropes(sim_pl, b_bpm, w_bpm, lambda2Ages, lambda1Ages, lambda0Ages)
s1 <- Sys.time() - s0
s1
#Time difference of 1.80342 mins
#save(res_ropes_bpm, file = "Predictions/res_ropes_bpm.RData")
#load("Predictions/res_ropes_bpm.RData")

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

b_ropes <- res_ropes_bpm$b_12
q <- res_fi_bpm
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] 87
cIn
#[1] 1660
(cOut / (cOut + cIn) * 100)
#[1] 4.979966
# 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, "", "BPM", TRUE, FALSE)
ggsave("Figures/Fig5_1.eps", width = 7)
