# 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')
ev=ev.sort_values(['match_id','idx'])
c=ev[(ev.type=='Pass')&(ev.pass_type=='Corner')].copy()
c['side']=np.where(c.y<40,'top','bot')
# distance across goal mouth measured from the corner side: 0 at near touchline, 80 at far
c['across']=np.where(c.side=='top',c.ey,80-c.ey)
def zone(r):
    if r.length<15: return 'Short'
    if r.ex<102: return 'Edge of box'
    a=r.across
    if a<36: return 'Front / near post'   # before near post (y=36)
    if a<44: return 'Central (goal mouth)'
    return 'Far post'
c['zone']=c.apply(zone,axis=1)
# outcomes: shots & goals in same possession, by team taking corner, within 20s window approx using same possession
sh=ev[ev.type=='Shot'][['match_id','possession','team','xg','outcome','x','y']]
first=sh.groupby(['match_id','possession','team']).agg(shots=('xg','size'),xg=('xg','sum'),goals=('outcome',lambda s:(s=='Goal').sum())).reset_index()
c=c.drop(columns=['xg']).merge(first,on=['match_id','possession','team'],how='left').fillna({'shots':0,'xg':0,'goals':0})
order=['Front / near post','Central (goal mouth)','Far post','Edge of box','Short']
z=c.groupby('zone').agg(corners=('id','size'),shots=('shots','sum'),goals=('goals','sum'),xg=('xg','sum')).reindex(order)
z['share']=z.corners/z.corners.sum(); z['goal_share']=z.goals/z.goals.sum(); z['goals_per_100']=100*z.goals/z.corners; z['xg_per_100']=100*z.xg/z.corners
print(z.round(3)); print('total corners',len(c),'goals',c.goals.sum())
# first contact won by attackers? pass outcome NaN = completed to teammate
c['att_first']=c.outcome.isna()
print(c.groupby('zone').att_first.mean().reindex(order).round(3))
# shots taken from corner possessions: where is the shot? relative to corner side
s2=c[c.shots>0][['match_id','possession','team','side']].drop_duplicates()
shots=ev[ev.type=='Shot'].merge(s2,on=['match_id','possession','team'])
shots['across']=np.where(shots.side=='top',shots.y,80-shots.y)
shots['sz']=pd.cut(shots.across,[-1,36,44,81],labels=['near side','goal-mouth centre','far side'])
print(shots.groupby('sz',observed=True).agg(n=('id','size'),goals=('outcome',lambda s:(s=='Goal').sum())))
# inswing vs outswing
print(c.groupby('technique').agg(n=('id','size'),goals=('goals','sum'),xg=('xg','sum')).assign(g100=lambda d:100*d.goals/d.n,xg100=lambda d:100*d.xg/d.n).round(2))
c.to_parquet('/tmp/sb/corners.parquet')
