---
title: "NFL_Lagging_GR_animation"
author: "Alejandro Avalos Mar"
collaborators: "Michael Cho, Eli Levin, Austin Haygood"
date: "January 8, 2019"
output: html_document
---

```{r Load Functions, include = FALSE, message = FALSE, result = 'hide', echo = FALSE}
loadPackage <- function(package_name){
  if((package_name %in% installed.packages()) == FALSE ){
    print(paste("Installing ", package_name, sep = ""))
    install.packages(package_name)
    require(package_name, character.only = TRUE)
  }else{
    print(paste("Package ", package_name," is already installed", sep = ""))
    require(package_name, character.only = TRUE)
  }
}

# Create dataframes for return and coverage teams. These will be used to distinguish return/coverage teams in the plots
return_position_function <- function(){
  return_pos <- c("VR",
                  "PDR1",
                  "PDR2",
                  "PDR3",
                  "PDL3",
                  "PDL2",
                  "PDL1",
                  "PLR",
                  "PLM",
                  "PLL",
                  "PFB",
                  "PR",
                  "VL")
  return(return_pos)
}
coverage_position_function <- function(){
  coverage_pos <- c("GL",
                    "PLT",
                    "PLG",
                    "PLS",
                    "PRG",
                    "PRT",
                    "PLW",
                    "PRW",
                    "GR",
                    "PC",
                    "PPR",
                    "P")
  return(coverage_pos)
}

```

```{r Load Packages, include = FALSE, message = FALSE, result = 'hide', echo = FALSE}
loadPackage("plotly")
loadPackage("gapminder")
loadPackage("data.table")
loadPackage("dplyr")
loadPackage("htmlwidgets")
loadPackage("htmltools")

```

```{r Load Data, include = FALSE, message = FALSE, result = 'hide', echo = FALSE}
# Get the files that start with NGS-*
NGS_file_list <- list.files("../input/")[grep(pattern = "NGS-", list.files("../input/"))]
NGS_file_list_reg <- NGS_file_list[grep(pattern = "reg", NGS_file_list)]
# Load the files in a loop and append as they are being read
play_data_all <- c()
for(i in 1:length(NGS_file_list_reg)){
  print(paste("Loading: ", NGS_file_list_reg[i]))
  
  temp <- fread(paste("../input/", NGS_file_list_reg[i], sep = ""))
  
  #print("cbinding")
  play_data_all <- rbind(play_data_all, temp)
  
}


player_role_data <- fread("../input/play_player_role_data.csv")
play_information <- fread("../input/play_information.csv")

```


# PlayID = 2902 - GameKey = 266
## The Play
```{r Entire Play - Data Transformation, include = FALSE, message = FALSE, result = 'hide', echo = FALSE}

# select play to visualize
play_plot <- play_data_all %>%
  filter(PlayID == 2902 &
           GameKey == 266)

# Calculate rank: This is the sequence events happened by player
play_plot <- play_plot %>%
  group_by(Season_Year, GameKey, PlayID, GSISID) %>%
  arrange(Season_Year, GameKey, PlayID, GSISID, x, y, dis, o, dir, Event, Time) %>% 
  mutate(rank = rank(Time, ties.method = "first"))

# Reduce dataset. If use all data points, the animation becomes too heavy
play_plot_rank <- play_plot %>%
  inner_join(player_role_data, by = c("Season_Year", "GameKey", "PlayID", "GSISID")) %>%
  filter(rank%%10 == 0) %>% # %%10 to reduce the dataset to whole seconds
  select(Season_Year, GameKey, PlayID, GSISID, Time, x, y, Event, rank, Role)

# Get the positions that are part of the return team, and the ones that are part of the coverage team
return_pos <- return_position_function()
coverage_pos <- coverage_position_function()

pos_plot <- as.data.frame(
  rbind(cbind(coverage_pos, "coverage"),
        cbind(return_pos, "return"))
)
colnames(pos_plot) <- c("Role", "coverage_return")

# Add the coverage/return column to the main dataframe
play_plot_rank_plot <- play_plot_rank %>%
  left_join(pos_plot, by = c("Role"))

# Change from rank to play seconds
play_plot_rank_plot$play_seconds <- play_plot_rank_plot$rank/10

# Only show the first minute of the play
play_plot_rank_plot <- play_plot_rank_plot%>%
  filter(play_seconds <= 60)

```

```{r Entire Play - Animation, echo = FALSE, fig.align = 'center'}

# Plot the animation
# First we need to create a ggplot object, and then we can animate it usind the variables ids and frame in aes()
play_ggplot <- ggplot(play_plot_rank_plot, aes(x = x, y = y, color = coverage_return, ids = GSISID, frame = play_seconds)) +
  geom_point(size = 3, alpha = .6) +
  geom_text(ggplot2::aes(label = Role), size = 1.5, color = 'black') +
  theme_minimal() +
  theme(legend.position = "none")

# Animate it
ggplotly(play_ggplot) 
```

## Lagging GR 2 seconds

```{r Lagging GR - Data Transformation, include = FALSE, message = FALSE, result = 'hide', echo = FALSE}

# Select only GR and PR roles
play_plot_rank_plot <- play_plot_rank_plot %>%
  filter(Role %in% c("GR", "PR")) %>%
  mutate(GSISID_2 = as.character(GSISID))

# subset GR to lag it for 2 seconds
slow_GR <- play_plot_rank_plot %>%
  filter(Role == 'GR') %>%
  mutate(new_rank = rank + 20) %>% # lag 2 seconds
  arrange(rank)

# Initial positions. These will be used for the first 2 seconds
slow_GR_init <- slow_GR %>%
  filter(rank <= 10)

# Grab the first 2 seconds 
slow_GR_pushed <- slow_GR %>%
  filter(rank <= 20) %>%
  mutate(x = ifelse(rank == 20, slow_GR_init$x, x),
         y = ifelse(rank == 20, slow_GR_init$y, y)) %>%
  select(Season_Year, GameKey, PlayID, GSISID, Time, x, y, Event, rank, Role, coverage_return, GSISID_2)

# Grab the 
slow_GR <- slow_GR %>%
  mutate(rank = new_rank) %>%
  select(Season_Year, GameKey, PlayID, GSISID, Time, x, y, Event, rank, Role, coverage_return, GSISID_2)

slower_GR <- rbind(slow_GR_pushed, slow_GR) %>%
  mutate(Event = 'SLOWER',
         GSISID_2 = paste(GSISID,"slow", sep = "_"))

play_plot_rank_plot_slow_GR <- rbind(play_plot_rank_plot, slower_GR)

play_plot_rank_plot_slow_GR$play_seconds <- play_plot_rank_plot_slow_GR$rank/10

# Only display the first 30 seconds of the play
play_plot_rank_plot_slow_GR <- play_plot_rank_plot_slow_GR %>%
  filter(play_seconds <= 30)

```

```{r Lagging GR - Animation, echo = FALSE, fig.align = 'center'}
play_ggplot_slower_GR <- ggplot(play_plot_rank_plot_slow_GR, aes(x = x, y = y, color = coverage_return, ids = GSISID_2, frame = play_seconds)) +
  geom_point(size = 7, alpha = .6) +
  geom_text(ggplot2::aes(label = Role), size = 2.5, color = 'black') +
  theme_minimal() +
  theme(legend.position = "none")


#play_ggplot_slower_GR

ggplotly(play_ggplot_slower_GR) 

# p_slow <- ggplotly(play_ggplot_slower_GR) 
```



```{r Distance from each other, echo = FALSE}

tackle_moment <- play_plot_rank_plot_slow_GR %>%
  filter(play_seconds == 10 &
           (Event == 'SLOWER' | Role == 'PR'))

HTML(cat("At play second = 10:", "\n",
         " - The GR already hit the PR", "\n",
         " - The lagged GR is:", round(dist(tackle_moment[, c("x","y")]), 2), "yards away from the PR", "\n", "\n", "Note: Euclidean distance used for distance calculation",
         sep = " ") 
     )



```