# Chris Gill Podcast, tested on data - rahulch.site/chris-gill-podcast/
# Data: StatsBomb open data, Premier League 2015/16 (competition 2, season 27): github.com/statsbomb/open-data
# Order: download events to /tmp/sb/events, run flatten.py, base.py, then a1 (needed by a8), a2, a3, a5, a6, a8

import pandas as pd, numpy as np
ev=pd.read_parquet('/tmp/sb/epl1516.parquet'); mins=pd.read_parquet('/tmp/sb/mins.parquet')
NX,NY=16,12
def cell(x,y):
    cx=np.clip((x/120*NX).astype(int),0,NX-1); cy=np.clip((y/80*NY).astype(int),0,NY-1); return cx*NY+cy
mv=ev[(ev.type.isin(['Pass','Carry']))&(ev.pass_type.isna()|ev.pass_type.isin(['Recovery','Interception']))].dropna(subset=['x','y'])
sh=ev[(ev.type=='Shot')&(ev.shot_type=='Open Play')]
N=NX*NY
s_c=np.bincount(cell(sh.x.values,sh.y.values),minlength=N)
g_c=np.bincount(cell(sh.x.values,sh.y.values),weights=(sh.outcome=='Goal').values,minlength=N)
m_c=np.bincount(cell(mv.x.values,mv.y.values),minlength=N)
tot=s_c+m_c
ps=np.divide(s_c,tot,out=np.zeros(N),where=tot>0); pm=np.divide(m_c,tot,out=np.zeros(N),where=tot>0)
pg=np.divide(g_c,s_c,out=np.zeros(N),where=s_c>0)
ok=mv[mv.outcome.isna() & mv.ex.notna()]
T=np.zeros((N,N)); np.add.at(T,(cell(ok.x.values,ok.y.values),cell(ok.ex.values,ok.ey.values)),1)
T=np.divide(T,m_c[:,None],out=np.zeros_like(T),where=m_c[:,None]>0)
xt=np.zeros(N)
for _ in range(30): xt=ps*pg+pm*(T@xt)
grid=xt.reshape(NX,NY)
np.save('/tmp/sb/xt.npy',grid)
print((grid.T*100).round(1)[::-1][:, -6:])
print('max',grid.max().round(3),'own box',grid[0].mean().round(4))
# xT added per player per 90 (successful passes+carries)
ok=ok.copy(); ok['xt']=xt[cell(ok.ex.values,ok.ey.values)]-xt[cell(ok.x.values,ok.y.values)]
pl=ok.groupby(['player','team']).xt.sum().reset_index()
mp=mins.groupby('player').mins.sum()
pl['m']=pl.player.map(mp); pl=pl[pl.m>=1500]; pl['xt90']=pl.xt/pl.m*90
print(pl.sort_values('xt90',ascending=False).head(12).round(3).to_string())
# split pass vs carry for top
ok['kind']=ok.type
top=pl.sort_values('xt90',ascending=False).head(12).player
sp=ok[ok.player.isin(top)].groupby(['player','kind']).xt.sum().unstack().fillna(0)
sp=sp.div(sp.index.map(mp),axis=0)*90
print(sp.round(3))
pl.to_csv('/tmp/sb/xt_players.csv',index=False); sp.to_csv('/tmp/sb/xt_split.csv')
