---
title: "NFL Punts Analytics Position and Velocity Diagrams Cohort 2 NGS 2016 1-6"
author: "Author: Roger Rosales (rosalesjrr@gmail.com)"
output:
  html_document:
    theme: cosmo
    toc: true
---

# Background
This kernel contains the Position and Velocity Diagrams for each punt concussion play in the NGS 2016 1-6.

My official NFL Punts Analytics Competition write up and analysis can be found in this kernel:

<a href="https://www.kaggle.com/predact/nfl-punts-analytics-wait-and-barrier">NFL Punts Analytics Wait and Barrier</a>


Here are my other kernels for the other NFL punt plays with diagrams:

<a href="https://www.kaggle.com/predact/nfl-punts-pv-diagrams-ngs-2016-pre">-ngs-2016-pre</a>


```{r echo = FALSE, message=FALSE, warning=FALSE}
# Load in packages
##################################################################
library(data.table)
library(dplyr)
library(ggplot2)
library(stringr)
library(DT)
library(tidyr)
library(corrplot)
library(leaflet)
library(lubridate)
###################################################################




# Load in the NFL Punt Analytics data
####################################################################
player.punt.data <- read.csv("../input/player_punt_data.csv")
player.role.data <- read.csv("../input/play_player_role_data.csv")
play.info <- read.csv("../input/play_information.csv")
game.data <- read.csv('../input/game_data.csv')
video.review <- read.csv('../input/video_review.csv')
video_footage_injury <- read.csv("../input/video_footage-injury.csv")
video_footage_control <- read.csv("../input/video_footage-control.csv")

#ngs <- read.csv("../input/NGS-2016-pre.csv")
ngs <- read.csv("../input/NGS-2016-reg-wk1-6.csv")
#ngs <- read.csv("../input/NGS-2016-reg-wk7-12.csv")
#ngs <- read.csv("../input/NGS-2016-reg-wk13-17.csv")

#For Kaggle Kernel
#player.punt.data <- read.csv("../input/player_punt_data.csv")
###################################################################






# Change classes for variables for analysis later on
###################################################################
ngs$GSISID <- as.factor(ngs$GSISID)
ngs$Time <- as.POSIXct(ngs$Time)
player.role.data$GSISID <- as.factor(player.role.data$GSISID)
#summary(ngs)
###################################################################






# Bring in Punt play information (only for manual input)
##################################################################

# gk = GameKey  
# pi = PlayId  
# gs1 = GSISID for primary player 
# gs2 = GSISID for partner player


# User input
#gk='5'
#pi='3129'
#gs1='31057'
#gs2='32482'
#pr='32482'
#pls='28284'
```

```{r echo=FALSE}
# Start of the function
puntstory <- function(gk,pi,gs1,gs2,pr,pls){


# Gather Data on the Primary and Partner players involved 
# Also manipulating the data for analysis
###################################################################


  
# Get primary player's punt role
Primary_Punt_Role <- player.role.data[player.role.data$GSISID==gs1&
                                        player.role.data$GameKey==gk&
                                        player.role.data$PlayID==pi,"Role"]

# Get primary player's activity derived
Primary_Activity <- video.review[video.review$GSISID==gs1&
                                   video.review$GameKey==gk&
                                   video.review$PlayID==pi,"Player_Activity_Derived"]

# Get primary player's impact type
Primary_Impact <- video.review[video.review$GSISID==gs1&
                                   video.review$GameKey==gk&
                                   video.review$PlayID==pi,"Primary_Impact_Type"]

# Get the flag if the concussion collision was friendly fire or not
Friendly_Fire <- video.review[video.review$GSISID==gs1&
                                 video.review$GameKey==gk&
                                 video.review$PlayID==pi,"Friendly_Fire"]


# Get partner player's punt role
Partner_Punt_Role <- player.role.data[player.role.data$GSISID==gs2&
                                        player.role.data$GameKey==gk&
                                        player.role.data$PlayID==pi,"Role"]

# Get partner player's activity derived
Partner_Activity <- video.review[video.review$GSISID==gs1&
                                   video.review$GameKey==gk&
                                   video.review$PlayID==pi,"Primary_Partner_Activity_Derived"]


# Filter the NGS data for the Primary Player and Sort by Time
primary.allplay <- ngs[ngs$GameKey == gk & ngs$PlayID == pi &
                         ngs$GSISID == gs1,]

primary.allplay <- primary.allplay[order(primary.allplay$Time),]



# Filter the NGS data for the Partner Player and Sort by Time
partner.allplay <- ngs[ngs$GameKey == gk & ngs$PlayID == pi &
                         ngs$GSISID == gs2,]

partner.allplay <- partner.allplay[order(partner.allplay$Time),]

# Filter the NGS data for the Punt Returner and Sort by Time
puntreturner.allplay <- ngs[ngs$GameKey == gk & ngs$PlayID == pi &
                         ngs$GSISID == pr,]

puntreturner.allplay <- puntreturner.allplay[order(puntreturner.allplay$Time),]

# Filter the NGS data for the PLS line of scrimmage and Sort by Time
pls.allplay <- ngs[ngs$GameKey == gk & ngs$PlayID == pi &
                              ngs$GSISID == pls,]

pls.allplay <- pls.allplay[order(pls.allplay$Time),]

# Keep track of important times during the punt
snap.time <- primary.allplay[primary.allplay$Event=="ball_snap","Time"]
punt.time <- primary.allplay[primary.allplay$Event=="punt","Time"]
punt_received.time <- primary.allplay[primary.allplay$Event=="punt_received","Time"]
fair_catch.time <- primary.allplay[primary.allplay$Event=="fair_catch","Time"]
touchback.time <- primary.allplay[primary.allplay$Event=="touchback","Time"]
oob.time <- primary.allplay[primary.allplay$Event=="out_of_bounds","Time"]
tackle.time <- primary.allplay[primary.allplay$Event=="tackle","Time"]
punt_downed.time <- primary.allplay[primary.allplay$Event=="punt_downed","Time"]

# Set the end of the punt play time by the maximum time of the ending events
end.time <-  max(punt_received.time,
                 fair_catch.time,
                 touchback.time,
                 oob.time,
                 tackle.time,
                 punt_downed.time)

#Punt location based on PLS position
pls.x <- pls.allplay[pls.allplay$Event=="ball_snap","x"]
pls.y <- pls.allplay[pls.allplay$Event=="ball_snap","y"]

#Punt Received Location
puntreturner.x <- puntreturner.allplay[puntreturner.allplay$Event=="punt_received","x"]
puntreturner.y <- puntreturner.allplay[puntreturner.allplay$Event=="punt_received","y"]

#Punt Downed Location
puntdowned.x <- puntreturner.allplay[puntreturner.allplay$Event=="punt_downed","x"]
puntdowned.y <- puntreturner.allplay[puntreturner.allplay$Event=="punt_downed","y"]

# Location of primary when punt received
primary.punt_received.x <- primary.allplay[primary.allplay$Event=="punt_received","x"]
primary.punt_received.y <- primary.allplay[primary.allplay$Event=="punt_received","y"]

# Location of partner when punt received
partner.punt_received.x <- partner.allplay[partner.allplay$Event=="punt_received","x"]
partner.punt_received.y <- partner.allplay[partner.allplay$Event=="punt_received","y"]


# Create a new data set from just the snap to the end of punt play time
primary.play <- as.data.frame(primary.allplay[primary.allplay$Time >= snap.time & primary.allplay$Time <= end.time,])

# Calculate the time since the play began
primary.play$playtime <- primary.play$Time - snap.time

table(primary.play$Event)

#str(primary.play$Event)

# OMIT: Calculate speed by MPH. Not very good because dist is not reliable.
# primary.play$mph <- primary.play$dis * (1/1760) / (0.1/3600)  

# Calculated Velocity for Primary by X and Y coordinates. Correct way
# Velocity = meters / sec  = Distance in meters / 1 second
primary.play$x_lag <- lag(primary.play$x, n = 10L) #10L to get one second change in time
primary.play$y_lag <- lag(primary.play$y, n = 10L)
primary.play$dist_meters <- 0.9144*sqrt((primary.play$x-primary.play$x_lag)^2 + (primary.play$y-primary.play$y_lag)^2)
primary.play$velocity <- primary.play$dist_meters / 1
primary.maxvelocity <- round(max(primary.play$velocity,na.rm = TRUE),digits=1)

# OMIT: Calculated MPH speed for Partner by dist column. Incorrect way.
# partner.play$mph <- partner.play$dis * (1/1760) / (0.1/3600)  

# Create partner play
partner.play <- as.data.frame(partner.allplay[partner.allplay$Time >= snap.time & partner.allplay$Time <= end.time,])

# Calculate the time since the play began
partner.play$playtime <- partner.play$Time - snap.time

# Calculated Velocity for Partner by X and Y coordinates
# 1 yard = 0.9144 meters
partner.play$x_lag <- lag(partner.play$x, n = 10L)
partner.play$y_lag <- lag(partner.play$y, n = 10L)
partner.play$dist_meters <- 0.9144*sqrt((partner.play$x-partner.play$x_lag)^2 + (partner.play$y-partner.play$y_lag)^2)
partner.play$velocity <- partner.play$dist_meters / 1
partner.maxvelocity <- round(max(partner.play$velocity,na.rm = TRUE),1)

# Primary Player Indicators
primary.play$Suffered.Concussion <- "Yes"
partner.play$Suffered.Concussion <- "No"




# Combine the primary play and the partner play
names(primary.play)
names(partner.play)
trueplay <- rbind(primary.play,partner.play)

trueplay[is.na(trueplay$velocity),"velocity"] <- 0

################################################################

#Visualize the location of the primary and partner player during the concussion play.
print(h <- ggplot(data=trueplay, aes (x=x,y=y,color=Suffered.Concussion))+
  geom_point() + 
    
    geom_vline(aes(xintercept=pls.x),
               size=5,
               color="orange")+
    annotate("text",x=pls.x,y=pls.y+2,label="Play Start")+
    
    annotate("rect", xmin = primary.punt_received.x-3, xmax = primary.punt_received.x+3, ymin = primary.punt_received.y-3, ymax = primary.punt_received.y+3,
               alpha = .2)+
    annotate("rect", xmin = partner.punt_received.x-3, xmax = partner.punt_received.x+3, ymin = partner.punt_received.y-3, ymax = partner.punt_received.y+3,
             alpha = .2)+
    
    annotate("rect", xmin = puntreturner.x-3, xmax = puntreturner.x+3, ymin = puntreturner.y-3, ymax = puntreturner.y+3,
             alpha = .2, fill="green")+
    annotate("text",x=puntreturner.x,y=puntreturner.y,label="Punt Received")+
    
    annotate("rect", xmin = puntdowned.x-3, xmax = puntdowned.x+3, ymin = puntdowned.y-3, ymax = puntdowned.y+3,
             alpha = .2, fill="green")+
    annotate("text",x=puntdowned.x,y=puntdowned.y,label="Punt Downed")+
    
    labs(title="Zoomed Paths Traveled Leading to Concussion",
       subtitle=paste("GameKey =",gk,"          PlayId=",pi,
                      "\nConcussed Player:",Primary_Punt_Role,"--",Primary_Activity,Primary_Impact," -- Maximum Velocity= ",primary.maxvelocity," m/s",
                      "\nPartner Player:",Partner_Punt_Role,"--",Partner_Activity," -- Maximum Velocity= ",partner.maxvelocity," m/s",
                      "\nFriendly Fire? ",Friendly_Fire),
       caption = paste("+++The gray box indicates the player's location when the punt was received",
                      "\nSnap time: ",snap.time,
                      "\nPunt time: ",punt.time,
                      "\nPunt Received: ",punt_received.time,
                      "\nTackle time: ",tackle.time,
                      "\nPunt Downed time: ",punt_downed.time,
                      "\nFair Catch: ",fair_catch.time,
                      "\nOut of Bounds: ",oob.time,
                      "\nTouchback: ",touchback.time),
       x = "Yards along the Home Sideline",
       y = "Yards increasing up the Endzone"
       )
  )


# Visualize the velocity of the primary and partner player 
# in meters per second
print(g <- ggplot(data=trueplay, aes(x=Time, y = velocity, color=Suffered.Concussion)) + 
  geom_line(size=2)+ 
    geom_vline(aes(xintercept=punt.time),
               size=5,
               color="orange")+

    annotate("text",x=punt.time,y=4.25,label="Punt")+
    
    geom_vline(aes(xintercept=punt_received.time),
               size=5,
               color="green")+
    annotate("text",x=punt_received.time,y=4.25,label="Punt Received")+
    
    #annotate("pointrange", x = punt_downed.time, y = 4, ymin = 0, ymax = primary.maxvelocity,
    #         colour = "green", size = 0.5)+
    #annotate("text",x=punt_received.time,y=4.25,label="Punt Received")+
    #
    
    geom_vline(aes(xintercept=tackle.time),
               size=5,
               color="red")+
    annotate("text",x=tackle.time,y=4.25,label="Tackle")+
    
    #annotate("pointrange", x = oob.time, y = 4, ymin = 0, ymax = primary.maxvelocity,
    #         colour = "black", size = 0.5)+
    #annotate("text",x=oob.time,y=4.25,label="Out of Bounds")+
    
    
    labs(title="Velocity of Players leading to the Concussion Collision",
         subtitle=paste("GameKey =",gk,"          PlayId=",pi,
                        "\nConcussed Player:",Primary_Punt_Role,"--",Primary_Activity,Primary_Impact," -- Maximum Velocity= ",primary.maxvelocity," m/s",
                        "\nPartner Player:",Partner_Punt_Role,"--",Partner_Activity," -- Maximum Velocity= ",partner.maxvelocity," m/s",
                        "\nFriendly Fire? ",Friendly_Fire),
         caption = paste("\nSnap time: ",snap.time,
                         "\nPunt time: ",punt.time,
                         "\nPunt Received: ",punt_received.time,
                         "\nTackle time: ",tackle.time,
                         "\nPunt Downed time: ",punt_downed.time,
                         "\nFair Catch: ",fair_catch.time,
                         "\nOut of Bounds: ",oob.time,
                         "\nTouchback: ",touchback.time),
         x = "Time (seconds)",
         y = "Velocity (meters per second)"
         )
  )








} 
#end of function











# Run Plays
#ngs <- read.csv("NGS-2016-pre.csv")
```

# Run Cohort 2 plays from the NGS 2016 1-6

## GameKey = 144, Play Id = 2342

```{r}
#####################################################################################
puntstory('144','2342','32410','23259','28091','26844')
```

* Blindside block on Receiving Team San Francisco #33 at 0:11. 
* Concussion happened after the punt was received.


<video width="800" height="600" controls> <source src="http://a.video.nfl.com//films/vodzilla/153239/Punt_Return_by_Jeremy_Kerley-U64gqush-20181119_154406175_5000k.mp4" type="video/mp4"></video>




## GameKey = 149, Play Id = 3663

```{r}
#####################################################################################
puntstory('149','3663','28128','29629','25396','27197')
```

* Three person collision at 0:11. See top of the screen.
* Concussion happened after the punt was received, but near the punt catch location.


<video width="800" height="600" controls> <source src="http://a.video.nfl.com//films/vodzilla/153240/Punt_by_Thomas_Morstead-eZpDKgMR-20181119_154525222_5000k.mp4" type="video/mp4"></video>

