"""
   ## NFL RULE IMPROVEMENTS
"""
"""
**The National Football League is America's most popular sports league, comprised of 32 franchises that compete each year to win the Super Bowl, the world's biggest annual sporting event. Founded in 1920, the NFL developed the model for the successful modern sports league, including national and international distribution, extensive revenue sharing, competitive excellence, and strong franchises across the country.
**
**The NFL is committed to advancing progress in the diagnosis, prevention and treatment of sports-related injuries. The NFL's ongoing health and safety efforts include support for independent medical research and engineering advancements and a commitment to look at anything and everything to protect players and make the game safer, including enhancements to medical protocols and improvements to how our game is taught and played.**

**As more is learned, the league evaluates and changes rules to evolve the game and try to improve protections for players. Since 2002 alone, the NFL has made 50 rules changes intended to eliminate potentially dangerous tactics and reduce the risk of injuries.**
"""
"""
![](https://static.nfl.com/static/content/public/static/img/share/shield.jpg)
"""
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in 

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import plotly.offline as py
from plotly.offline import init_notebook_mode, iplot
import plotly.graph_objs as go
from plotly import tools
init_notebook_mode(connected=True)  
import plotly.figure_factory as ff
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory

import os
print(os.listdir("../input"))

# Any results you write to the current directory are saved as output.
game_data = pd.read_csv('../input/NFL-Punt-Analytics-Competition/game_data.csv')

game_data.head()
import random
def random_colors(number_of_colors):
    color = ["#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])
                 for i in range(number_of_colors)]
    return color
game_data['Temperature']= game_data['Temperature'].fillna(game_data['Temperature'].mean())

game_data.head()
"""
# Season Temperature Analysis
"""
from datetime import datetime
import pandas_datareader.data as web


data = [go.Scatter(x=game_data.Game_Date, y=game_data.Temperature)]

py.iplot(data)
"""
**The temperature of the season varies from High 90s to low 00s as it goes real low during the winter season.**
"""
"""
# Most Played Game Venue during the 2016 NFL Season
"""
pitch_count = game_data['Game_Site'].value_counts()
data = [go.Bar(
    x = pitch_count.index,
    y = pitch_count.values,
    marker = dict(color = random_colors(25))
)]
layout = dict(
         title= "Most Occurring Game Venue "
)
fig = dict( data=data, layout=layout )
iplot( fig, validate=False )
"""
**As it turns out East Rutherford site has seen 40 of the season's matches whereas Foxborough has seen 24 following by Atlanta Pittsburgh, Philadelphia e.t.c by 22.**
"""
"""
**If you don't know about that game site then you should as it's home to New york Giants (Metlife Stadium).**
"""
"""
![](https://media-cdn.tripadvisor.com/media/photo-s/0c/0c/d4/11/nfl.jpg)
"""
"""
# Most played day of the NFL season
"""
day_count = game_data['Game_Day'].value_counts()
trace = go.Pie(labels=day_count.index, values=day_count.values, hole=0.6)
layout = go.Layout(
    title='Game Day Percentage'
)
fig = go.Figure(data=[trace], layout=layout)
iplot(fig)
"""
**As i've expected most no of days belongs to the weekends, Sunday having 68% of all of game days.**
"""
"""
# Most Stadium's Type of the NFL Stadiums used
"""
pitch_count = game_data['StadiumType'].value_counts()
data = [go.Bar(
    x = pitch_count.index,
    y = pitch_count.values,
    marker = dict(color = random_colors(25))
)]
layout = dict(
         title= "Different types of Stadium"
)
fig = dict( data=data, layout=layout )
iplot( fig, validate=False )
"""
**There are lots of typing error in the data for the stadium type but if we add up the outdoor and outdoors as together it come out as 348+81= 429 something is the number of times outdoor stadium used in the whole season.**
"""
"""
![](http://footballstadiumdigest.com/wp-content/uploads/2015/11/new-atlanta-dec2015-4.jpg)
"""
"""
**Mercedes Benz Stadium is the best stadium among the football stadium, it's architecture is flabbergasting.**
"""
"""
# Weather of the whole season 
"""
pitch_count = game_data['GameWeather'].value_counts()
data = [go.Bar(
    x = pitch_count.index,
    y = pitch_count.values,
    marker = dict(color = random_colors(25))
)]
layout = dict(
         title= "Different types of Weathers"
)
fig = dict( data=data, layout=layout )
iplot( fig, validate=False )
"""
**Sunny weather has been very kind to the most of nfl matches with 145 times whereas partly Cloudy has been 119 times.**
"""
"""
# Turf on which most NFL games played in
"""
pitch_count = game_data['Turf'].value_counts()
data = [go.Bar(
    x = pitch_count.index,
    y = pitch_count.values,
    marker = dict(color = random_colors(25))
)]
layout = dict(
         title= "Different types of Turfs"
)
fig = dict( data=data, layout=layout )
iplot( fig, validate=False )
video_review= pd.read_csv('../input/NFL-Punt-Analytics-Competition/video_review.csv')
video_review.head()
"""
**As any NFL player would have wanted the turfs to be grass so less injury prone incidents.**
"""
"""
![](https://www.independentcollection.com/wp-content/uploads/2016/10/iStock_42500060_SMALL.jpg)
"""
NGS= pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2016-post.csv')
NGS.head()
NGS = NGS.fillna(0)
NGS1= NGS.truncate(before=1, after=1000)
import base64
with open("../input/picture2/61jq6q0FyJL._SY606_.jpg", "rb") as image_file:
    encoded_string = base64.b64encode(image_file.read()).decode()
#add the prefix that plotly will want when using the string as source
encoded_image = "data:image/png;base64," + encoded_string
"""
# Analysis of NFL Next Gen Stats Week and season wise
"""
def convert_to_mph(dis, converter):
    mph = dis * converter
    return mph
def get_speed(ng_data, playId, gameKey, player, partner):
    ng_data = pd.read_csv(ng_data,low_memory=False)
    ng_data['mph'] = convert_to_mph(ng_data['dis'], 20.455)
    player_data = ng_data.loc[(ng_data.GameKey == gameKey) & (ng_data.PlayID == playId) 
                               & (ng_data.GSISID == player)].sort_values('Time')
    partner_data = ng_data.loc[(ng_data.GameKey == gameKey) & (ng_data.PlayID == playId) 
                              & (ng_data.GSISID == partner)].sort_values('Time')
    player_grouped = player_data.groupby(['GameKey','PlayID','GSISID'], 
                               as_index = False)['mph'].agg({'max_mph': max,
                                                             'avg_mph': np.mean
                                                            })
    player_grouped['Player_Involved'] = 'player_injured'
    partner_grouped = partner_data.groupby(['GameKey','PlayID','GSISID'], 
                               as_index = False)['mph'].agg({'max_mph': max,
                                                             'avg_mph': np.mean
                                                            })
    partner_grouped['Player_Involved'] = 'primary_partner'
    return pd.concat([player_grouped, partner_grouped], axis = 0)[['Player_Involved',
                                                                   'max_mph',
                                                                   'avg_mph']].reset_index(drop=True)
def load_layout():
    """
    Returns a dict for a Football themed Plot.ly layout 
    """
    layout = dict(
        title = "Player Activity",
        plot_bgcolor='darkseagreen',
        showlegend=True,
        xaxis=dict(
            autorange=False,
            range=[0, 120],
            showgrid=False,
            zeroline=False,
            showline=True,
            linecolor='black',
            linewidth=1,
            mirror=True,
            ticks='',
            tickmode='array',
            tickvals=[10,20, 30, 40, 50, 60, 70, 80, 90, 100, 110],
            ticktext=['Goal', 10, 20, 30, 40, 50, 40, 30, 20, 10, 'Goal'],
            showticklabels=True
        ),
        yaxis=dict(
            title='',
            autorange=False,
            range=[-3.3,56.3],
            showgrid=False,
            zeroline=False,
            showline=True,
            linecolor='black',
            linewidth=1,
            mirror=True,
            ticks='',
            showticklabels=False
        ),
        shapes=[
            dict(
                type='line',
                layer='below',
                x0=0,
                y0=0,
                x1=120,
                y1=0,
                line=dict(
                    color='white',
                    width=2
                )
            ),
            dict(
                type='line',
                layer='below',
                x0=0,
                y0=53.3,
                x1=120,
                y1=53.3,
                line=dict(
                    color='white',
                    width=2
                )
            ),
            dict(
                type='line',
                layer='below',
                x0=10,
                y0=0,
                x1=10,
                y1=53.3,
                line=dict(
                    color='white',
                    width=10
                )
            ),
            dict(
                type='line',
                layer='below',
                x0=20,
                y0=0,
                x1=20,
                y1=53.3,
                line=dict(
                    color='white'
                )
            ),
            dict(
                type='line',
                layer='below',
                x0=30,
                y0=0,
                x1=30,
                y1=53.3,
                line=dict(
                    color='white'
                )
            ),
            dict(
                type='line',
                layer='below',
                x0=40,
                y0=0,
                x1=40,
                y1=53.3,
                line=dict(
                    color='white'
                )
            ),
            dict(
                type='line',
                layer='below',
                x0=50,
                y0=0,
                x1=50,
                y1=53.3,
                line=dict(
                    color='white'
                )
            ),
            dict(
                type='line',
                layer='below',
                x0=60,
                y0=0,
                x1=60,
                y1=53.3,
                line=dict(
                    color='white'
                )
            ),dict(
                type='line',
                layer='below',
                x0=70,
                y0=0,
                x1=70,
                y1=53.3,
                line=dict(
                    color='white'
                )
            ),dict(
                type='line',
                layer='below',
                x0=80,
                y0=0,
                x1=80,
                y1=53.3,
                line=dict(
                    color='white'
                )
            ),
            dict(
                type='line',
                layer='below',
                x0=90,
                y0=0,
                x1=90,
                y1=53.3,
                line=dict(
                    color='white'
                )
            ),dict(
                type='line',
                layer='below',
                x0=100,
                y0=0,
                x1=100,
                y1=53.3,
                line=dict(
                    color='white'
                )
            ),
            dict(
                type='line',
                layer='below',
                x0=110,
                y0=0,
                x1=110,
                y1=53.3,
                line=dict(
                    color='white',
                    width=10
                )
            )
        ]
    )
    return layout

layout = load_layout()
Player_position= go.Scatter(x=NGS1.x,y=NGS1.y)

fig=go.Figure(data=[Player_position],layout=layout)
py.iplot(fig)
"""
**Position analysis of players during 1000 plays of 2016 Post season matches **
"""
# Loading and plotting functions

def load_plays_for_game(GameKey):
    """
    Returns a dataframe of play data for a given game (GameKey)
    """
    play_information = pd.read_csv('../input/NFL-Punt-Analytics-Competition/play_information.csv')
    play_information = play_information[play_information['GameKey'] == GameKey]
    return play_information


def load_game_and_ngs(ngs_file=None, GameKey=None):
    """
    Returns a dataframe of player movements (NGS data) for a given game
    """
    if ngs_file is None:
        print("Specifiy an NGS file.")
        return None
    if GameKey is None:
        print('Specify a GameKey')
        return None
    # Merge play data with NGS data    
    plays = load_plays_for_game(GameKey)
    ngs = pd.read_csv(ngs_file, low_memory=False)
    merged = pd.merge(ngs, plays, how="inner", on=["GameKey", "PlayID", "Season_Year"])
    return merged


def plot_play(game_df, PlayID, player1=None, player2=None, custom_layout=False):
    """
    Plots player movements on the field for a given game, play, and two players
    """
    game_df = game_df[game_df.PlayID==PlayID]
    
    GameKey=str(pd.unique(game_df.GameKey)[0])
    HomeTeam = pd.unique(game_df.Home_Team_Visit_Team)[0].split("-")[0]
    VisitingTeam = pd.unique(game_df.Home_Team_Visit_Team)[0].split("-")[1]
    YardLine = game_df[(game_df.PlayID==PlayID) & (game_df.GSISID==player1)]['YardLine'].iloc[0]
    
    traces=[]   
    if (player1 is not None) & (player2 is not None):
        game_df = game_df[ (game_df['GSISID']==player1) | (game_df['GSISID']==player2)]
        for player in pd.unique(game_df.GSISID):
            player = int(player)
            trace = go.Scatter(
                x = game_df[game_df.GSISID==player].x,
                y = game_df[game_df.GSISID==player].y,
                name='GSISID '+str(player),
                mode='markers'
            )
            traces.append(trace)
    else:
        print("Specify GSISIDs for player1 and player2")
        return None
    
    if custom_layout is not True:
        layout = load_layout()
        layout['title'] =  HomeTeam + \
        ' vs. ' + VisitingTeam + \
        '<br>Possession: ' + \
        YardLine.split(" ")[0] +'@'+YardLine.split(" ")[1]
    data = traces
    fig = dict(data=data, layout=layout)
    play_description = game_df[(game_df.PlayID==PlayID) & (game_df.GSISID==player1)].iloc[0]["PlayDescription"]
    print("\n\n\t",play_description)
    offline.iplot(fig, config=config)
    

video_review1 = pd.merge(video_review,NGS, on=['Season_Year','GameKey','PlayID','GSISID'])
video_review1
import glob
from plotly import offline
import plotly.graph_objs as go


pd.set_option('max.columns', None)
offline.init_notebook_mode()
config = dict(showLink=False)
"""
# **No concussion incident happened during 2016 post season matches.**
"""
"""
# **Let's analyse all 37 cases and the player and primary partner's movement which lead to concussion**
"""
"""
# Pre Season Analysis of 2016 NFL Matches
"""
NGS_pre= pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv')
NGS_pre.head()
NGS_pre1= NGS_pre.truncate(before=1, after=1000)
trace1= go.Scatter(x=NGS_pre1.x,y=NGS_pre1.y)

fig=go.Figure(data=[trace1],layout=layout)
py.iplot(fig)
"""
**Position analysis of play during 2016 Pre season matches **
"""
video_review1 = pd.merge(video_review,NGS_pre, on=['Season_Year','GameKey','PlayID','GSISID'])
video_review1= video_review1.sort_values('GSISID', ascending=False).drop_duplicates('GameKey').sort_index()
game5 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv',GameKey=5)
game21 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv',GameKey=21)
game29 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv',GameKey=29)
game45 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv',GameKey=45)
game54 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv',GameKey=54)
game60 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv',GameKey=60)
"""
# **Player and their Primary Partner's  Movement during the play which lead to concussion **
"""
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[0]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[0]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[0]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[0]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv', 3129, 5, 31057, 32482))
plot_play(game_df=game5, PlayID=3129, player1=31057, player2=32482 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[1]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[1]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[1]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[1]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv', 2587, 21, 29343, 31059))
plot_play(game_df=game21, PlayID=2587, player1=29343, player2=31059 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[2]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[2]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[2]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[2]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv', 538, 29, 31023, 31941))
plot_play(game_df=game29, PlayID=538, player1=31023, player2=31941 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[3]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[3]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[3]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[3]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv', 1212, 45, 33121, 28429))
plot_play(game_df=game45, PlayID=1212, player1=33121, player2=28429 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[4]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[4]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[4]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[4]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv', 1045, 54, 32444, 31756))
plot_play(game_df=game54, PlayID=1045, player1=32444, player2=31756 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[5]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[5]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[5]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[5]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-pre.csv', 905, 60, 30786, 29815))
plot_play(game_df=game60, PlayID=905, player1=30786, player2=29815 )
"""
# Regular Weekly Play Analysis from Week 1 - 6 
"""
NGS_reg= pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk1-6.csv')
NGS_reg.head()
NGS_reg1= NGS_reg.truncate(before=1, after=1000)
trace1= go.Scatter(x=NGS_reg1.x,y=NGS_reg1.y)

fig=go.Figure(data=[trace1],layout=layout)
py.iplot(fig)
"""
**Position analysis of play during 2016 Weekly season matches **
"""
video_review1 = pd.merge(video_review,NGS_reg, on=['Season_Year','GameKey','PlayID','GSISID'])
video_review1= video_review1.sort_values('GSISID', ascending=False).drop_duplicates('GameKey').sort_index()
game149 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk1-6.csv',GameKey=149)
game144 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk1-6.csv',GameKey=144)
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[0]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[0]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[0]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[0]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk1-6.csv', 2342, 144, 32410, 23259))
plot_play(game_df=game144, PlayID=2342, player1=32410, player2=23259 )
"""
# **Players and their Partner's Movement during the play which caused concussion**
"""
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[1]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[1]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[1]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[1]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk1-6.csv', 3663, 149, 28128, 29629))
plot_play(game_df=game149, PlayID=3663, player1=28128, player2=29629 )
"""
# Regular Weekly Play Analysis from Week 7 - 12 
"""
NGS_reg= pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk7-12.csv')
NGS_reg.head()
NGS_reg1= NGS_reg.truncate(before=1, after=1000)
trace1= go.Scatter(x=NGS_reg1.x,y=NGS_reg1.y)

fig=go.Figure(data=[trace1],layout=layout)
py.iplot(fig)
"""
**Position analysis of play during 2016 Weekly season matches **
"""
video_review1 = pd.merge(video_review,NGS_reg, on=['Season_Year','GameKey','PlayID','GSISID'])
video_review1= video_review1.sort_values('GSISID', ascending=False).drop_duplicates('GameKey').sort_index()
game189 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk7-12.csv',GameKey=189)
game218 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk7-12.csv',GameKey=218)
game231 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk7-12.csv',GameKey=231)
game234 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk7-12.csv',GameKey=234)
"""
# **Players and their Partner's Movement during the play which caused concussion**
"""
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[0]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[0]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[0]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[0]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk7-12.csv', 3509, 189, 27595, 31950))
plot_play(game_df=game189, PlayID=3509, player1=27595, player2=31950 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[1]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[1]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[1]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[1]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk7-12.csv', 3468, 218, 28987, 31950))
plot_play(game_df=game218, PlayID=3468, player1=28987, player2=31950 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[2]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[2]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[2]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[2]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk7-12.csv', 1976, 231, 32214, 32807))
plot_play(game_df=game231, PlayID=1976, player1=32214, player2=32807 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[3]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[3]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[3]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[3]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk7-12.csv', 3278, 234, 28620, 27860))
plot_play(game_df=game234, PlayID=3278, player1=28620, player2=27860 )
"""
# Regular Weekly Play Analysis from Week 13 - 17 
"""
NGS_reg= pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv',low_memory=False)
NGS_reg.head()
NGS_reg= NGS_reg.fillna(0)
NGS_reg1= NGS_reg.truncate(before=1, after=1000)
trace1= go.Scatter(x=NGS_reg1.x,y=NGS_reg1.y)

fig=go.Figure(data=[trace1],layout=layout)
py.iplot(fig)
"""
**Position analysis of play during 2016 Weekly season matches **
"""
video_review1 = pd.merge(video_review,NGS_reg, on=['Season_Year','GameKey','PlayID','GSISID'])
video_review1= video_review1.sort_values('GSISID', ascending=False).drop_duplicates('GameKey').sort_index()
game266 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv',GameKey=266)
game274 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv',GameKey=274)
game280 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv',GameKey=280)
game281 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv',GameKey=281)
game289 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv',GameKey=289)
game296 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv',GameKey=296)
"""
# **Players and their Partner's Movement during the play which caused concussion**
"""
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[0]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[0]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[0]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[0]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv', 2902, 266, 23564, 31844))
plot_play(game_df=game266, PlayID=2902, player1=23564, player2=31844 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[1]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[1]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[1]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[1]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv', 3609, 274, 23742, 31785))
plot_play(game_df=game274, PlayID=3609, player1=23742, player2=31785 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[2]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[2]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[2]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[2]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv', 2918, 280, 32120, 32725))
plot_play(game_df=game280, PlayID=2918, player1=32120, player2=32725 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[3]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[3]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[3]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[3]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv', 1526, 281, 28987, 30789))
plot_play(game_df=game281, PlayID=1526, player1=28987, player2=30789 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[4]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[4]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[4]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[4]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv', 2341, 289, 32007, 32998))
plot_play(game_df=game289, PlayID=2341, player1=32007, player2=32998 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[5]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[5]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[5]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[5]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2016-reg-wk13-17.csv', 2667, 296, 32783, 32810))
plot_play(game_df=game296, PlayID=2667, player1=32783, player2=32810 )
"""
# Post Season Analysis of 2017 NFL Matches
"""
NGS_post= pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2017-post.csv')
NGS_post.head()
NGS_post1= NGS_post.truncate(before=1, after=1000)
trace1= go.Scatter(x=NGS_post1.x,y=NGS_post1.y)

fig=go.Figure(data=[trace1],layout=layout)
py.iplot(fig)
"""
**Position analysis of play during 2017 Post season matches **
"""
video_review1 = pd.merge(video_review,NGS_post, on=['Season_Year','GameKey','PlayID','GSISID'])
video_review1
"""
# **No concussion incident happened during 2017 post season matches.**
"""
"""
# Pre Season Analysis of 2017 NFL Matches
"""
NGS_pre= pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2017-pre.csv')
NGS_pre.head()
NGS_pre1= NGS_pre.truncate(before=1, after=1000)
trace1= go.Scatter(x=NGS_pre1.x,y=NGS_pre1.y)

fig=go.Figure(data=[trace1],layout=layout)
py.iplot(fig)
"""
**Position analysis of play during 2017 Pre season matches **
"""
video_review1 = pd.merge(video_review,NGS_pre, on=['Season_Year','GameKey','PlayID','GSISID'])
video_review1= video_review1.sort_values('GSISID', ascending=False).drop_duplicates('GameKey').sort_index()
game357 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-pre.csv',GameKey=357)
game364 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-pre.csv',GameKey=364)
game384 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-pre.csv',GameKey=384)
game392 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-pre.csv',GameKey=392)
game397 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-pre.csv',GameKey=397)
"""
# **Players and their Partner's Movement during the play which caused concussion**
"""
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[0]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[0]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[0]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[0]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-pre.csv', 3630, 357, 30171, 29384))
plot_play(game_df=game357, PlayID=3630, player1=30171, player2=29384 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[1]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[1]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[1]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[1]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-pre.csv', 2764, 364, 32323, 31930))
plot_play(game_df=game364, PlayID=2764, player1=32323, player2=31930 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[2]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[2]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[2]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[2]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-pre.csv', 183, 384, 33813, 33841))
plot_play(game_df=game384, PlayID=183, player1=33813, player2=33841 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[3]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[3]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[3]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[3]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-pre.csv', 1088, 392, 32615, 31999))
plot_play(game_df=game392, PlayID=1088, player1=32615, player2=31999 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[4]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[4]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[4]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[4]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-pre.csv', 1526, 397, 32894, 31763))
plot_play(game_df=game397, PlayID=1526, player1=32894, player2=31763 )
"""
# Regular Weekly Play Analysis from Week 1 - 6 
"""
NGS_reg= pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk1-6.csv')
NGS_reg.head()
NGS_reg1= NGS_reg.truncate(before=1, after=1000)
trace1= go.Scatter(x=NGS_reg1.x,y=NGS_reg1.y)

fig=go.Figure(data=[trace1],layout=layout)
py.iplot(fig)
"""
**Position analysis of play during 2017 Weekly season matches **
"""
video_review1 = pd.merge(video_review,NGS_reg, on=['Season_Year','GameKey','PlayID','GSISID'])
video_review1= video_review1.sort_values('GSISID', ascending=False).drop_duplicates('GameKey').sort_index()
game399 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk1-6.csv',GameKey=399)
game414 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk1-6.csv',GameKey=414)
game448 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk1-6.csv',GameKey=448)
game473 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk1-6.csv',GameKey=473)
"""
# **Players and their Partner's Movement during the play which caused concussion**
"""
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[0]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[0]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[0]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[0]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk1-6.csv', 3312, 399, 26035, 27442))
plot_play(game_df=game399, PlayID=3312, player1=26035, player2=27442 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[1]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[1]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[1]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[1]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk1-6.csv', 1262, 414, 33941, 27442))
plot_play(game_df=game414, PlayID=1262, player1=33941, player2=27442 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[2]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[2]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[2]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[2]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk1-6.csv', 2792, 448, 33838, 31317))
plot_play(game_df=game448, PlayID=2792, player1=33838, player2=31317 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[3]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[3]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[3]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[3]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk1-6.csv', 2072, 473, 29492, 33445))
plot_play(game_df=game473, PlayID=2072, player1=29492, player2=33445 )
"""
# Regular Weekly Play Analysis from Week 7 - 12 
"""
NGS_reg= pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk7-12.csv')
NGS_reg.head()
NGS_reg1= NGS_reg.truncate(before=1, after=1000)
trace1= go.Scatter(x=NGS_reg1.x,y=NGS_reg1.y)

fig=go.Figure(data=[trace1],layout=layout)
py.iplot(fig)
"""
**Position analysis of play during 2017 Weekly season matches **
"""
video_review1 = pd.merge(video_review,NGS_reg, on=['Season_Year','GameKey','PlayID','GSISID'])
video_review1= video_review1.sort_values('GSISID', ascending=False).drop_duplicates('GameKey').sort_index()
game506 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk7-12.csv',GameKey=506)
game553 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk7-12.csv',GameKey=553)
game567 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk7-12.csv',GameKey=567)
"""
# **Players and their Partner's Movement during the play which caused concussion**
"""
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[0]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[0]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[0]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[0]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk7-12.csv', 1988, 506, 27060, 30780))
plot_play(game_df=game506, PlayID=1988, player1=27060, player2=30780 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[1]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[1]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[1]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[1]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk7-12.csv', 1683, 553, 32820, 25503))
plot_play(game_df=game553, PlayID=1683, player1=32820, player2=25503 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[2]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[2]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[2]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[2]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk7-12.csv', 1407, 567, 32403, 32891))
plot_play(game_df=game567, PlayID=1407, player1=32403, player2=32891 )
"""
# Regular Weekly Play Analysis from Week 13 - 17 
"""
NGS_reg= pd.read_csv('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk13-17.csv')
NGS_reg.head()
NGS_reg1= NGS_reg.truncate(before=1, after=1000)
trace1= go.Scatter(x=NGS_reg1.x,y=NGS_reg1.y)

fig=go.Figure(data=[trace1],layout=layout)
py.iplot(fig)
"""
**Position analysis of play during 2017 Weekly season matches **
"""
video_review1 = pd.merge(video_review,NGS_reg, on=['Season_Year','GameKey','PlayID','GSISID'])
video_review1= video_review1.sort_values('GSISID', ascending=False).drop_duplicates('GameKey').sort_index()
game585 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk13-17.csv',GameKey=585)
game601 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk13-17.csv',GameKey=601)
game607 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk13-17.csv',GameKey=607)
game618 = load_game_and_ngs('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk13-17.csv',GameKey=618)
"""
# **Players and their Partner's Movement during the play which caused concussion**
"""
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[0]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[0]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[0]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[0]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk13-17.csv', 2208, 585, 33069, 29414))
plot_play(game_df=game585, PlayID=2208, player1=33069, player2=29414 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[1]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[1]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[1]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[1]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk13-17.csv', 602, 601, 33260, 31697))
plot_play(game_df=game601, PlayID=602, player1=33260, player2=31697 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[2]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[2]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[2]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[2]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk13-17.csv', 978, 607, 29793, 32114))
plot_play(game_df=game607, PlayID=978, player1=29793, player2=32114 )
# Plot a single play, with two players
print('Primary Impact:',video_review1.iloc[3]["Primary_Impact_Type"]) 
print('Primary Activity:',video_review1.iloc[3]["Player_Activity_Derived"] )
print('Partners Activity:',video_review1.iloc[3]["Primary_Partner_Activity_Derived"] )
print('Players from same team :',video_review1.iloc[3]["Friendly_Fire"] )
print(get_speed('../input/NFL-Punt-Analytics-Competition/NGS-2017-reg-wk13-17.csv', 2792, 618, 31950, 326))
plot_play(game_df=game618, PlayID=2792, player1=31950, player2=32677 )
"""
# **Analysis**
**Over all the 37 visual of concussion play and players movement we can conclude few important things -**

**1- Most of these tackles were full speed tackle or scrimmages.**

**2- Most of these tackles were made on the end line.**

**3- Most of these tackles were made while running back.**

**4- These tackles almost happened at the maximum mph which shows full speed tackle or blocking helmet to helmet/body will increase the concussion rate.**

**5- A better helmet or better rule for tackling/blocking using helmets.**

**6- Play continued on in many cases without the follow checkup on the injured/down player.**
"""
play_info= pd.read_csv('../input/NFL-Punt-Analytics-Competition/play_information.csv')
play_info.head()
play_info1 = pd.merge(video_review,play_info, on=['Season_Year','GameKey','PlayID'])
play_info1.sort_values('PlayID', ascending=False).drop_duplicates('GameKey').sort_index()
punt_count = play_info1['Quarter'].value_counts()
trace = go.Pie(labels=punt_count.index, values=punt_count.values, hole=0.6)
layout = go.Layout(
    title='Most concussion Quarter'
)
fig = go.Figure(data=[trace], layout=layout)
iplot(fig, filename="plotting-library")
punt_count = play_info1['Poss_Team'].value_counts()
trace = go.Pie(labels=punt_count.index, values=punt_count.values, hole=0.6)
layout = go.Layout(
    title='Team percentage Punt play which lead to injury'
)
fig = go.Figure(data=[trace], layout=layout)
iplot(fig, filename="plotting-library")
punt_data= pd.read_csv('../input/NFL-Punt-Analytics-Competition/player_punt_data.csv')
punt_data.head()
punt_data1 = pd.merge(video_review,punt_data, on=['GSISID'])
punt_data1.sort_values('GSISID', ascending=False).drop_duplicates('GameKey').sort_index()
punt_count = punt_data1['Position'].value_counts()
trace = go.Pie(labels=punt_count.index, values=punt_count.values, hole=0.6)
layout = go.Layout(
    title='Concussion Position Percentage'
)
fig = go.Figure(data=[trace], layout=layout)
iplot(fig, filename="plotting-library")
"""
**Tight End (TE) – This player is a hybrid between a receiver and an offensive lineman. Generally, he lines up next to the LT or RT or he can “split out” like a wide receiver. His duties include blocking for both the quarterback and the running backs, but he can also run into the field and catch passes. Tight ends can catch like a receiver, but has the strength and size to dominate on the line.**

**Inside linebackers (ILB) are usually responsible for shadowing RBs, TEs and sometimes WRs; rushing the passer; and tackling ball carriers. Those who are linebackers are likely strong and fast.**

**These two positions where concussion happened more than often and due to tackling and getting blocked in such positions they player got injured, these two position each share equal percentage of 15.5%.**
"""
"""
**In American football If the receiving team drops the ball or touches the ball beyond the line of scrimmage without catching it then it is considered a live ball and may be recovered by either team. If the receiving team never had full possession, it is considered to be a muffed punt rather than a fumble.**
"""
"""
![](http://images.performgroup.com/di/library/sporting_news/12/2e/tyler-matakevich-britton-colquitt-ftr-091017jpg_c0c6pnoga1ak1ovwx0mhut0dg.jpg?t=1824294750&w=960&quality=70)
"""
player_role= pd.read_csv('../input/NFL-Punt-Analytics-Competition/play_player_role_data.csv')
player_role.head()
player_role1 = pd.merge(video_review,player_role, on=['Season_Year','GameKey','PlayID','GSISID'])
player_role1.sort_values('GSISID', ascending=False).drop_duplicates('GameKey').sort_index()
role_count = player_role1['Role'].value_counts()
data = [go.Bar(
    x = role_count.index,
    y = role_count.values,
    marker = dict(color = random_colors(100))
)]
layout = dict(
         title= "Role count leading to Injury"
)
fig = dict( data=data, layout=layout )
iplot( fig, validate=False )
punt_count = player_role1['Role'].value_counts()
trace = go.Pie(labels=punt_count.index, values=punt_count.values, hole=0.6)
layout = go.Layout(
    title='Player role percentage'
)
fig = go.Figure(data=[trace], layout=layout)
iplot(fig, filename="plotting-library")
"""
**Punt Returners are responsible for catching kicked balls (either on kickoffs or punts) and running the ball back. These are usually among the fastest players on a team. Teams may use the same player for both positions or may have a separate returner for punts and for kickoffs. Returners typically also play wide receiver or cornerback. Due to the relatively high likelihood of injury during kick returns, most professional teams will not regularly use their very best WRs or CBs as returners.**
"""
video_footage_control= pd.read_csv('../input/NFL-Punt-Analytics-Competition/video_footage-control.csv')
video_footage_control.head()
video_footage_control.rename(columns={'season': 'Season_Year', 'gamekey': 'GameKey', 'playid': 'PlayID'}, inplace=True)
player_role1 = pd.merge(video_review,video_footage_control, on=['GameKey','PlayID','Season_Year'])
player_role1.sort_values('PlayID', ascending=False).drop_duplicates('GameKey').sort_index()
video_footage_injury= pd.read_csv('../input/NFL-Punt-Analytics-Competition/video_footage-injury.csv')
video_footage_injury.head()
video_footage_injury.rename(columns={'season': 'Season_Year', 'gamekey': 'GameKey', 'playid': 'PlayID'}, inplace=True)
player_role1 = pd.merge(video_review,video_footage_injury, on=['GameKey','PlayID','Season_Year'])
player_role1.sort_values('PlayID', ascending=False).drop_duplicates('GameKey').sort_index()
punt_count = player_role1['Home_team'].value_counts()
trace = go.Pie(labels=punt_count.index, values=punt_count.values, hole=0.6)
layout = go.Layout(
    title='Home team injury involvement percentage'
)
fig = go.Figure(data=[trace], layout=layout)
iplot(fig, filename="plotting-library")
punt_count = player_role1['Visit_Team'].value_counts()
trace = go.Pie(labels=punt_count.index, values=punt_count.values, hole=0.6)
layout = go.Layout(
    title='Visit team injury involvement percentage'
)
fig = go.Figure(data=[trace], layout=layout)
iplot(fig, filename="plotting-library")
trace0 = go.Scatter(
    x=player_role1.Home_team,
    y=player_role1.Player_Activity_Derived,
    mode='markers',
    marker=dict(
        color=random_colors(50)

    )
)
layout = dict(
            title='Home team players activity leading to concussion '
)
fig = go.Figure(data=[trace0], layout=layout)
py.iplot(fig, filename='bubblechart-color')
trace0 = go.Scatter(
    x=player_role1.Visit_Team,
    y=player_role1.Player_Activity_Derived,
    mode='markers',
    marker=dict(
        color=random_colors(50)

    )
)
layout = dict(
            title='Away team players activity leading to concussion '
)
fig = go.Figure(data=[trace0], layout=layout)
py.iplot(fig, filename='bubblechart-color')
"""
# Major Foul Rules In NFL
"""
"""
> SECTION 14 - FOULS AND SPOTS OF ENFORCEMENT, VIOLATION
> ARTICLE 1. TYPES OF FOULS
> A Foul is any infraction of a playing rule for which a penalty is prescribed.
> 
> A Live Ball Foul is a foul that occurs during the period after the snap until the ball is dead.
> A Dead Ball Foul is a foul that occurs in the continuing action after a down ends, or a taunting foul that occurs at any time.
> A Foul Between Downs is a foul that occurs after the end of the down and after any continuing action resulting from the down, but prior to the next snap or free kick.
> A Multiple Foul is one of two or more fouls by the same team during the same down (14-1-3), including dead ball fouls.
> A Double Foul is a foul by either team during the same down during which both teams commit at least one foul, including dead ball fouls.
> ARTICLE 2. BASIC SPOT
> The Basic Spot is a reference point for specific types of plays that is used to determine the Spot of Enforcement.
> 
> ARTICLE 3. SPOTS OF ENFORCEMENT
> The Spot of Enforcement is the spot at which a penalty is enforced. Six such spots are commonly used:
> 
> The Previous Spot: The spot at which the ball was last put in play.
> The Spot of the Foul: The spot at which a foul was committed or, by rule, is considered to have been committed.
> The Spot of a Backward Pass or a Fumble: The spot at which the backward pass or fumble occurred during the down in which there was a foul.
> The Dead Ball Spot: The spot at which the ball became dead.
> The Succeeding Spot: The spot at which the ball will next be put in play (i.e., the spot of the ball after enforcement for a foul, or, if there has been no foul, the spot at which the ball became dead.)
> The Spot of a Change of Possession: The spot at which possession is gained by or awarded to the opponent.
> ARTICLE 4. VIOLATION
> A violation is an infraction of a playing rule for which a penalty is not prescribed. A violation does not offset a foul.
> 
> SECTION 15 - HANDLING THE BALL
> Handing the ball is transferring player possession from one teammate to another without passing or kicking it.
> 
> Except where permitted by rule, handing the ball forward to a teammate is illegal.
> Loss of player possession by unsuccessful execution of attempted handing is a fumble charged to the player that last had possession. A muffed handoff (legal or illegal) is a fumble, and the ball remains alive.
> A forward handoff occurs when the ball is handed (regardless of the direction of the movement of the ball) to a player who is in advance of a teammate from whose hands he takes or receives it.
> SECTION 16 - HUDDLE
> A Huddle is the action of two or more players in the field of play or in the end zone who, instead of assuming their normal position for the snap, free kick, or Fair Catch kick form a group for receiving instructions for the next play or for any other reason.
> 
> SECTION 17 - IMPETUS
> Impetus is the action of a player who carries the ball or provides the force (i.e., a pass, kick, snap, or fumble) that causes a ball in the field of play to touch or cross a goal line. If a Loose Ball touches or crosses a goal line, the impetus is attributed to the team whose player passed, kicked, snapped, or fumbled the ball, unless an opponent:
> 
> muffs a ball that is at rest, or nearly at rest; or
> bats a ball that has been kicked or fumbled; or
> bats a backward pass after it has struck the ground; or
> illegally kicks any ball (12-5-2).
> Notes
> 
> 1. The impetus is always attributed to the offense, unless the defense creates a new force that sends the ball behind its own goal line by muffing a ball which is at rest or nearly at rest, or by batting a loose ball on the ground or kicking any loose ball.
> 
> 2. If a passive player is pushed or blocked into any kicked or fumbled ball or into a backward pass after it has struck the ground, causing the Loose Ball to touch a goal line or anything on or behind a goal line, the impetus is attributed to the pusher or blocker, provided that the pushed (blocked) player was not making an attempt to block an opponent.**
"""
video_review= video_review.fillna(0)
video_review= video_review[['Player_Activity_Derived','Turnover_Related','Primary_Impact_Type','Primary_Partner_Activity_Derived','Friendly_Fire']]
s = pd.crosstab(video_review['Primary_Impact_Type'],
                video_review['Friendly_Fire'] ,normalize='index').style.background_gradient(cmap='RdBu', low=.1, high=0).highlight_null('red')
s
"""
# Analysis -
**1. Helmet to body contact in non friendly manner leads to 76% of injuries.**

**2. Helmet to helmet contact in non friendly manner leads to 88% of injuries.**
"""
s = pd.crosstab(video_review['Player_Activity_Derived'],
                video_review['Primary_Partner_Activity_Derived'] ,normalize='index').style.background_gradient(cmap='RdBu', low=.1, high=0).highlight_null('red')
s
"""
# Analysis-

**1. While player has blocked already the opponent and their primary partner still is trying to do the blocking its leads to 55% of the concussions.**
.

**2. While player is trying to tackle the opponent and their primary partner has already tackled it leads to 67% of the concussions.**
"""
video_review_count = video_review['Primary_Impact_Type'].value_counts()
trace = go.Pie(labels=video_review_count.index, values=video_review_count.values, hole=0.6)
layout = go.Layout(
    title='Most Impact Type'
)
fig = go.Figure(data=[trace], layout=layout)
iplot(fig, filename="plotting-library")
"""
# Analysis-
**1.  Helmet to Body and Helmet to Helmet contact type leads to most concussion injuries. **
"""
video_review_count = video_review['Player_Activity_Derived'].value_counts()
trace = go.Pie(labels=video_review_count.index, values=video_review_count.values, hole=0.6)
layout = go.Layout(
    title='Most activity percentage leading to concussion injury'
)
fig = go.Figure(data=[trace], layout=layout)
iplot(fig, filename="plotting-library")
"""
# Analysis-
**1. Blocking and tackling each share fare amount of percentage leading to concussion injury.**
"""
serious_tackle= video_review.groupby(['Primary_Partner_Activity_Derived', 'Friendly_Fire'])
partner_count = serious_tackle['Primary_Partner_Activity_Derived'].value_counts()
trace = go.Pie(labels=partner_count.index, values=partner_count.values, hole=0.6)
layout = go.Layout(
    title='Percentage of partners serious play'
)
fig = go.Figure(data=[trace], layout=layout)
iplot(fig, filename="plotting-library")
"""
# Anlaysis
**1. Blocking event with primary partner also blocking with not in a friendly manner- 22.9 %**

**2. Tackling event with primary partner also tackling  with not in a friendly manner- 22.9%**
"""
"""
# NFL Injury Statistics (including Concussion, MCL, ACL)
"""
"""
![](https://www.playsmartplaysafe.com/wp-content/uploads/2018/01/injury-data-slide-1.jpg)
"""
"""
![](https://www.playsmartplaysafe.com/wp-content/uploads/2018/01/injury-data-slide-2.jpg)
"""
"""
![](https://www.playsmartplaysafe.com/wp-content/uploads/2018/01/injury-data-slide-3.jpg)
"""
"""
![](https://www.playsmartplaysafe.com/wp-content/uploads/2018/01/injury-data-slide-4.jpg)
"""
"""
# NIH Report on Concussion
"""
"""
**A concussion is a type of brain injury. It involves a short loss of normal brain function. It happens when a hit to the head or body causes your head and brain to move rapidly back and forth. This sudden movement can cause the brain to bounce around or twist in the skull, creating chemical changes in your brain. Sometimes it can also stretch and damage your brain cells.**

**Sometimes people call a concussion a "mild" brain injury. It is important to understand that while concussions may not be life-threatening, they can still be serious.**

**Concussions are a common type of sports injury. Other causes of concussions include blows to the head, bumping your head when you fall, being violently shaken, and car accidents.**

**Symptoms of a concussion may not start right away; they may start days or weeks after the injury. Symptoms may include a headache or neck pain. You may also have nausea, ringing in your ears, dizziness, or tiredness. You may feel dazed or not your normal self for several days or weeks after the injury. Consult your health care professional if any of your symptoms get worse, or if you have more serious symptoms such as**

**Convulsions or seizures
Drowsiness or inability to wake up
A headache that gets worse and does not go away
Weakness, numbness, or decreased coordination
Repeated vomiting or nausea
Confusion
Slurred speech
Loss of consciousness
To diagnose a concussion, your health care provider will do a physical exam and will ask about your injury. You will most likely have a neurological exam, which checks your vision, balance, coordination, and reflexes. Your health care provider may also evaluate your memory and thinking. In some cases, you may also have a scan of the brain, such as a CT scan or an MRI. A scan can check for bleeding or inflammation in the brain, as well as skull fractures.**

**Most people recover fully after a concussion, but it can take some time. Rest is very important after a concussion because it helps the brain to heal. In the very beginning, you may need to limit physical activities or activities that involve a lot of concentration, such as studying, working on the computer, or playing video games. Doing these may cause concussion symptoms (such as headache or tiredness) to come back or get worse. Then when your health care provider says that it is ok, you can start to return to your normal activities slowly.**
"""
"""
![](https://c.o0bg.com/rf/image_1200w/Boston/2011-2020/2017/12/29/BostonGlobe.com/Sports/Images/df718101b1e04231b54ac3d654e9c5a0-df718101b1e04231b54ac3d654e9c5a0-0.jpg?uuid=uQuK7OzeEeerbgMQBVbbXg)
"""
"""
**Concussion Protocol On Tom Savage as it should be mandatory for every Non-Friendly Blocking or Non Friendly Tackle**
"""
"""
**Prevention Tips**	

**Teach athletes proper techniques and ways to avoid hits to the head.**

**Limit the amount of contact during practices. This may include**

**No full speed head-on blocking or tackling drills in which the players line up more than 3 yards apart.**

**Limiting the amount of practice time that includes scrimmages or full-speed drills.**

**The American Academy of Pediatrics recommends:**

**Expanding the availability of non-contact football programs.**

**Having skilled athletic trainers available at games and practices.**

**Keep a close eye on athletes during running plays, especially an athlete in the running back position.**

**Enforce the rules of the sport for fair play, safety, and sportsmanship.**

**Ensure athletes avoid unsafe actions such as:**

**Hitting another athlete in the head;**

**Using their helmet to contact another athlete (helmet-to-helmet or helmet-to-body contact);**

**Making illegal contacts, tackling, or colliding with an unprotected opponent; and/or
Trying to injure or put another athlete at risk for injury.**

**Make sure athletes always wear a helmet that fits well and is in good condition.**

**Work with the game or event administrator to remove tripping hazards and ensure equipment, such as goalposts, have padding that is in good condition.**

**Why This Is Important**

**Almost half (49%) of concussions in high school football happen during running plays.**

**Tackling is responsible for almost two-thirds (63%) of concussions in high school football.**

**Linebackers sustain over half (59%) of all concussions among high school football defensive players.**

**Running backs sustain 46% of concussions among high school football offensive players.**
"""
"""
# Suggested Changes

1. **As part of the new rule, which is considered unneccessary roughness, players will receive a 15-yard penalty and could possibly be ejected. The previous rule limited the penalty to contact to the crown of the helmet.The new rule officially reads, Lowering the head to initiate contact with the helmet is a foul. It is intended to remove unnecessary use of the helmet. The hits do not have to come to the head or neck but anywhere on the body. Players cannot use their helmets to butt, spear or ram an opponent.**

**Plays subject to ejection include when a player has an unobstructed path to his opponent or contact was clearly avoidable, but the player chose to lower his head and use his helmet.**

**Correction- There should be a speed parameter included to the rule, as in my analysis most of these players were travelling more than their avg miles/hr. If the player is lowering his helmet and moving more than avg miles/hr decided by NFL then he should be ejected from the game with 15 yards penalty and no ejection shall be committed if player lowers his helmet under stationary motion unless the player is taking down the moving player using his helmet.**

2.**Protection of Punt Returners-
It is most often the Punt returners which face concussion during the tackle or by being blocked by imposing fair catch rule on them(5 yard award) or use canadian football rules which is The kicker and any players behind him at the time of the kick are considered onside; any other players on the kicking team are considered offside. A player who is onside may recover the kicked ball, while a player who is offside may not be the first to touch the kicked ball and is required to remain at least 5 yards from an opposing player attempting to catch the ball. Violations of these restrictions on an offside player are called no yards infractions, with various penalties associated with them. Better helmet for Punt Returners, punt left guard or punt right guard, or more protection for PR by giving him extra man in front of him in lineup formation rather than just PR only by himself.**

3. **Blindsided block or Moving backwards block/tackle-**

**Almost 30% of these concussion happened due to blindsided block or while those PLG/PLG were trying to catch the ball while moving backwards this cause some serious head blow to catchers if they got tackled while moving backwards.**

**Another thing to mention that bad landing happened due to lack of vision to upcoming tackles, which caused them injury leading to concussion.**

**Rule- A player who receives a “blindside” block when the path of the offensive blocker is toward or parallel to his own end line is a defensenless player.**

**Correction- The blocking/tackling player should be in the eye range(180 degrees) of the player getting tackled regardless of it's position or direction.**

**Rule- A receiver attempting to catch a pass who has not had time to clearly become a runner. If the player is capable of avoiding or warding off the impending contact of an opponent, he is no longer a defenseless player.**

**Correction- There should not be any tackle on wing players who's moving towards his own end line or running backwards regardless of the player is capable of avoiding or warding off the impending contact of an opponent.**


"""
"""
# Upvote if you liked as i'll update more
"""