{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# How far kicker from me ? (Long Snapper's asking)\nOr how i realize that there is a Punter(Holder) among Kickers in tracking.position\n\nimport libraries and load data","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:03:32.19604Z","iopub.execute_input":"2021-12-24T11:03:32.196332Z","iopub.status.idle":"2021-12-24T11:03:32.200683Z","shell.execute_reply.started":"2021-12-24T11:03:32.196298Z","shell.execute_reply":"2021-12-24T11:03:32.199892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\n!pip install joypy\nfrom joypy import joyplot\nimport math\nimport seaborn as sns","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:03:32.201937Z","iopub.execute_input":"2021-12-24T11:03:32.20256Z","iopub.status.idle":"2021-12-24T11:03:39.461284Z","shell.execute_reply.started":"2021-12-24T11:03:32.202522Z","shell.execute_reply":"2021-12-24T11:03:39.460511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"game = pd.read_csv('/kaggle/input/nfl-big-data-bowl-2022/games.csv')\nplay = pd.read_csv('/kaggle/input/nfl-big-data-bowl-2022/plays.csv')\ntracking2018 = pd.read_csv('/kaggle/input/nfl-big-data-bowl-2022/tracking2018.csv')\ntracking2019 = pd.read_csv('/kaggle/input/nfl-big-data-bowl-2022/tracking2019.csv')\ntracking2020 = pd.read_csv('/kaggle/input/nfl-big-data-bowl-2022/tracking2020.csv')","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:03:39.462463Z","iopub.execute_input":"2021-12-24T11:03:39.462704Z","iopub.status.idle":"2021-12-24T11:05:14.643546Z","shell.execute_reply.started":"2021-12-24T11:03:39.462674Z","shell.execute_reply":"2021-12-24T11:05:14.642583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tracking = tracking2018\ntracking.append(tracking2019)\ntracking.append(tracking2020)\n\nprint('')","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:05:14.644769Z","iopub.execute_input":"2021-12-24T11:05:14.645007Z","iopub.status.idle":"2021-12-24T11:05:28.011344Z","shell.execute_reply.started":"2021-12-24T11:05:14.644979Z","shell.execute_reply":"2021-12-24T11:05:28.0102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# I. Field goals","metadata":{}},{"cell_type":"markdown","source":"LS and K from only one team on field at moment of snap . Get the coordinates of these two. \n(I assume that field position of a player in tracking-data and position of player in players-data the same or even better)","metadata":{}},{"cell_type":"code","source":"data_fg = pd.merge(play[play.specialTeamsPlayType=='Field Goal'],\n               tracking[(tracking.position=='LS') & (tracking.event == 'ball_snap')],\n               how = 'inner', on = ['playId','gameId'])\ndata_fg = data_fg[['gameId','playId','x','y']]\n\n# add kickers info\nkickers = pd.merge(play[play.specialTeamsPlayType=='Field Goal'],\n               tracking[(tracking.position=='K') & (tracking.event == 'ball_snap')],\n               how = 'inner', on = ['playId','gameId'])\ndata_fg = pd.merge(data_fg, kickers, how = 'inner', on = ['playId','gameId'], \n                   suffixes=(\"_ls\", \"_k\") )\ndata_fg = data_fg[['x_ls','y_ls', 'x_k','y_k', 'playDirection','displayName','specialTeamsResult','possessionTeam']]\n#data_fg.head(3)","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:05:28.013615Z","iopub.execute_input":"2021-12-24T11:05:28.013868Z","iopub.status.idle":"2021-12-24T11:05:31.270862Z","shell.execute_reply.started":"2021-12-24T11:05:28.013837Z","shell.execute_reply":"2021-12-24T11:05:31.270223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# distance to goal post (i assume that starting point coinside with LS coordinates)\ndistance_to_goal = []\n# distance between Kicker and Long Snapper\ndistance_between = []\n# is kick good?\nfg_goal =[]\n\nfor i in range(len(data_fg)):\n    distance_between.append(math.sqrt((data_fg['x_ls'][i]-data_fg['x_k'][i])**2+(data_fg['y_ls'][i]-data_fg['y_k'][i])**2))\n    if data_fg.playDirection[i]=='left':\n        distance_to_goal.append(math.sqrt((data_fg['x_ls'][i])**2 + (data_fg['y_ls'][i]-53.33/2)**2))\n    else:\n        distance_to_goal.append(math.sqrt((120-data_fg['x_ls'][i])**2 + (data_fg['y_ls'][i]-53.33/2)**2))\n    if data_fg.specialTeamsResult[i]=='Kick Attempt Good':\n        fg_goal.append(1)\n    else:\n        fg_goal.append(0)\ndata_fg = pd.concat([data_fg,\n                     pd.DataFrame(distance_to_goal,columns=['distance_to_goal']),\n                     pd.DataFrame(distance_between,columns=['distance_between']),\n                     pd.DataFrame(fg_goal,columns=['fg_goal'])], axis=1)\n#data_fg.head(5)","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:05:31.271999Z","iopub.execute_input":"2021-12-24T11:05:31.273021Z","iopub.status.idle":"2021-12-24T11:05:31.34191Z","shell.execute_reply.started":"2021-12-24T11:05:31.272974Z","shell.execute_reply":"2021-12-24T11:05:31.341197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ax = sns.scatterplot(x='distance_to_goal', y='distance_between',\n                hue=\"specialTeamsResult\", #size=\"depth\",\n                #palette=\"ch:r=-.2,d=.3_r\",\n                #hue_order=clarity_ranking,\n                sizes=(1, 8), linewidth=0,\n                data=data_fg\n               )\nax.set(title ='Scatter plot!')","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:05:31.343024Z","iopub.execute_input":"2021-12-24T11:05:31.34321Z","iopub.status.idle":"2021-12-24T11:05:31.803202Z","shell.execute_reply.started":"2021-12-24T11:05:31.343186Z","shell.execute_reply":"2021-12-24T11:05:31.802403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Look like distance for run-up is not depend on distance to goal post? (open quation)","metadata":{}},{"cell_type":"code","source":"ax = sns.displot(data=data_fg[['distance_between','specialTeamsResult']],\n                 x=\"distance_between\", binwidth=0.1, \n                 hue=\"specialTeamsResult\", multiple=\"stack\")\nax.set(title='Field goals \\n Distance between LS and K at moment of snap (yards)')","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:05:31.804606Z","iopub.execute_input":"2021-12-24T11:05:31.805141Z","iopub.status.idle":"2021-12-24T11:05:32.737388Z","shell.execute_reply.started":"2021-12-24T11:05:31.805103Z","shell.execute_reply":"2021-12-24T11:05:32.736506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fg_visual = data_fg\n# filter by number of field-goal attempts\nfg_visual = fg_visual[fg_visual['displayName'].map(fg_visual['displayName'].value_counts()) >= 5]\n\n#fg_visual['order'] = fg_visual.groupby('displayName').distance_between.transform(lambda x: np.mean(x))\nfg_visual['order'] = fg_visual.groupby('displayName').fg_goal.transform(lambda x: np.average(x))\n\nfg_visual = fg_visual.sort_values(['order'], ascending=False)\n\nfg_grouped = fg_visual.groupby(\"displayName\", sort=False)\n\njoyplot(fg_grouped, column = 'distance_between', figsize = (10,10), \n        overlap = 0.5, color = 'lightblue')\n\nplt.xticks([0.0, 2.5, 5.0, 7.5, 10.0, 12.5])\nplt.rc('grid', linestyle=':', color='lightgray', linewidth=0.5)\nplt.grid(True, zorder = 0)\nplt.title(\"Density of field-goal attempts \\n Ordered by field goal accuracy \\n best on top\", fontsize = 16)\nplt.xlabel(\"Distance to LS\", fontsize = 14)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:05:32.738976Z","iopub.execute_input":"2021-12-24T11:05:32.739189Z","iopub.status.idle":"2021-12-24T11:05:35.210859Z","shell.execute_reply.started":"2021-12-24T11:05:32.739162Z","shell.execute_reply":"2021-12-24T11:05:35.209877Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Looks like distance to Long Snapper is something personal\n\n# II. Extra points","metadata":{}},{"cell_type":"code","source":"data_ep = pd.merge(play[play.specialTeamsPlayType=='Extra Point'],\n               tracking[(tracking.position=='LS') & (tracking.event == 'ball_snap')],\n               how = 'inner', on = ['playId','gameId'])\ndata_ep = data_ep[['gameId','playId','x','y']]\n\n# add kickers info\nkickers = pd.merge(play[play.specialTeamsPlayType=='Extra Point'],\n               tracking[(tracking.position=='K') & (tracking.event == 'ball_snap')],\n               how = 'inner', on = ['playId','gameId'])\ndata_ep = pd.merge(data_ep, kickers, how = 'inner', on = ['playId','gameId'], \n                   suffixes=(\"_ls\", \"_k\") )\ndata_ep = data_ep[['x_ls','y_ls', 'x_k','y_k', 'playDirection','displayName','specialTeamsResult','possessionTeam']]\n\ndistance_between = []\n# is kick good?\nep_goal =[]\n\nfor i in range(len(data_ep)):\n    distance_between.append(math.sqrt((data_ep['x_ls'][i]-data_ep['x_k'][i])**2+(data_ep['y_ls'][i]-data_ep['y_k'][i])**2))\n    if data_ep.playDirection[i]=='left':\n        distance_to_goal.append(math.sqrt((data_ep['x_ls'][i])**2 + (data_ep['y_ls'][i]-53.33/2)**2))\n    else:\n        distance_to_goal.append(math.sqrt((120-data_ep['x_ls'][i])**2 + (data_ep['y_ls'][i]-53.33/2)**2))\n    if data_ep.specialTeamsResult[i]=='Kick Attempt Good':\n        ep_goal.append(1)\n    else:\n        ep_goal.append(0)\ndata_ep = pd.concat([data_ep,\n                     pd.DataFrame(distance_between,columns=['distance_between']),\n                     pd.DataFrame(ep_goal,columns=['ep_goal'])], axis=1)\n#data_ep.head(5)","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:05:35.21236Z","iopub.execute_input":"2021-12-24T11:05:35.21278Z","iopub.status.idle":"2021-12-24T11:05:38.257334Z","shell.execute_reply.started":"2021-12-24T11:05:35.212734Z","shell.execute_reply":"2021-12-24T11:05:38.256686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ax = sns.displot(data=data_ep[['distance_between','specialTeamsResult']],\n                 x=\"distance_between\", binwidth=0.1, \n                 hue=\"specialTeamsResult\", multiple=\"stack\")\nax.set(title='Extra points \\n Distance between LS and K at moment of snap (yards)')","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:05:38.258483Z","iopub.execute_input":"2021-12-24T11:05:38.258838Z","iopub.status.idle":"2021-12-24T11:05:39.174613Z","shell.execute_reply.started":"2021-12-24T11:05:38.258809Z","shell.execute_reply":"2021-12-24T11:05:39.17391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ep_visual = data_ep\n# filter by number of field-goal attempts\nep_visual = ep_visual[ep_visual['displayName'].map(ep_visual['displayName'].value_counts()) >= 5]\n\n#ep_visual['order'] = ep_visual.groupby('displayName').distance_between.transform(lambda x: np.mean(x))\nep_visual['order'] = ep_visual.groupby('displayName').ep_goal.transform(lambda x: np.average(x))\n\nep_visual = ep_visual.sort_values(['order'], ascending=False)\n\nep_grouped = ep_visual.groupby(\"displayName\", sort=False)\n\njoyplot(ep_grouped, column = 'distance_between', figsize = (10,10), \n        overlap = 0.5, color = 'lightblue')\n\nplt.xticks([0.0, 2.5, 5.0, 7.5, 10.0, 12.5])\nplt.rc('grid', linestyle=':', color='lightgray', linewidth=0.5)\nplt.grid(True, zorder = 0)\nplt.title(\"Density of field-goal attempts \\n Ordered by field goal accuracy \\n (best on top)\", fontsize = 16)\nplt.xlabel(\"Distance to LS\", fontsize = 14)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:05:39.175749Z","iopub.execute_input":"2021-12-24T11:05:39.176092Z","iopub.status.idle":"2021-12-24T11:05:41.621065Z","shell.execute_reply.started":"2021-12-24T11:05:39.17606Z","shell.execute_reply":"2021-12-24T11:05:41.620112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"One Kicker has original style ( except that he worst on field goals)\nLook at map of his field goals attempts\n\n# III. Map of field goals","metadata":{}},{"cell_type":"code","source":"data_s = pd.merge(play[play.specialTeamsPlayType=='Field Goal'],\n               tracking[(tracking.position=='LS') & (tracking.event == 'ball_snap')],\n               how = 'inner', on = ['playId','gameId'])\ndata_s = pd.merge(data_s,game,\n                   how = 'inner', on = 'gameId')\ndata_s = data_s[['gameId','playId','x','y','homeTeamAbbr','visitorTeamAbbr']]\n# add kickers info\nkickers = pd.merge(play[play.specialTeamsPlayType=='Field Goal'],\n               tracking[(tracking.position=='K') & (tracking.event == 'ball_snap') \n                        & (tracking.displayName=='Matt Wile')],\n               how = 'inner', on = ['playId','gameId'])\ndata_s = pd.merge(data_s, kickers, how = 'inner', on = ['playId','gameId'], \n                   suffixes=(\"_ls\", \"_k\") )\ndata_s = data_s[['x_ls','y_ls', 'x_k','y_k', 'playDirection','displayName','specialTeamsResult','possessionTeam','homeTeamAbbr','visitorTeamAbbr']]\n#data_fg.head(3)","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:05:41.622745Z","iopub.execute_input":"2021-12-24T11:05:41.623257Z","iopub.status.idle":"2021-12-24T11:05:45.298844Z","shell.execute_reply.started":"2021-12-24T11:05:41.623214Z","shell.execute_reply":"2021-12-24T11:05:45.297968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import cbook\n# its local file\nimageFile = cbook.get_sample_data('/kaggle/input/nfl2022/nfl_field5.png')\nimage = plt.imread(imageFile)\nextent = -60, 60, 0, 53.3\n\ndata_s.loc[(data_s['playDirection'] == \"left\") & (data_s['possessionTeam']==data_s['homeTeamAbbr']), 'x_ls'] = 120-data_s.loc[(data_s['playDirection'] == \"left\") & (data_s['possessionTeam']==data_s['homeTeamAbbr']), 'x_ls']\ndata_s.loc[(data_s['playDirection'] == \"right\") & (data_s['possessionTeam']==data_s['visitorTeamAbbr']), 'x_ls'] = 120-data_s.loc[(data_s['playDirection'] == \"right\") & (data_s['possessionTeam']==data_s['visitorTeamAbbr']), 'x_ls']\n\n\ndata_s.loc[(data_s['playDirection'] == \"left\") & (data_s['possessionTeam']==data_s['homeTeamAbbr']), 'y_ls'] = 160/3-data_s.loc[(data_s['playDirection'] == \"left\") & (data_s['possessionTeam']==data_s['homeTeamAbbr']), 'y_ls']\ndata_s.loc[(data_s['playDirection'] == \"right\") & (data_s['possessionTeam']==data_s['visitorTeamAbbr']), 'y_ls'] = 160/3-data_s.loc[(data_s['playDirection'] == \"right\") & (data_s['possessionTeam']==data_s['visitorTeamAbbr']), 'y_ls']\n\nplt.plot(data_s[['x_ls']][data_s.specialTeamsResult=='Kick Attempt Good']*1215/120,\n         data_s[['y_ls']][data_s.specialTeamsResult=='Kick Attempt Good']*553/53.3, 'o', markersize=8, color='cyan', alpha=0.9)\n\nplt.plot(data_s[['x_ls']][data_s.specialTeamsResult=='Kick Attempt No Good']*1215/120,\n         data_s[['y_ls']][data_s.specialTeamsResult =='Kick Attempt No Good']*553/53.3, 'o', markersize=8, color='red', alpha=0.9)\n\nplt.rcParams[\"figure.figsize\"] = (20,10)\nplt.axis('off')\nplt.title(\"Matt Wile Field Goal Attempts\")\nplt.imshow(image)","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:05:45.301179Z","iopub.execute_input":"2021-12-24T11:05:45.301495Z","iopub.status.idle":"2021-12-24T11:05:45.632802Z","shell.execute_reply.started":"2021-12-24T11:05:45.301463Z","shell.execute_reply":"2021-12-24T11:05:45.631956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"check this (all goals where made onroad)","metadata":{}},{"cell_type":"code","source":"data_s","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:05:45.634085Z","iopub.execute_input":"2021-12-24T11:05:45.634543Z","iopub.status.idle":"2021-12-24T11:05:45.657107Z","shell.execute_reply.started":"2021-12-24T11:05:45.63451Z","shell.execute_reply":"2021-12-24T11:05:45.656316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"kickers","metadata":{"execution":{"iopub.status.busy":"2021-12-24T11:21:56.724708Z","iopub.execute_input":"2021-12-24T11:21:56.725569Z","iopub.status.idle":"2021-12-24T11:21:56.762548Z","shell.execute_reply.started":"2021-12-24T11:21:56.72552Z","shell.execute_reply":"2021-12-24T11:21:56.761883Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"But there is no nflId of Matt Wile among kicker_Id in plays-data.\n(his position , mentioned in data is 'K', but he plays on another position - Holder/Punter)","metadata":{}}]}