Upload 27 files
Browse filesFiles changed (10)
- api_scraper.py+25
- app.py+488-400
- data/data_a_2024.parquetAdded+3
- data/data_aaa_2024.parquetAdded+3
- data/data_mlb_2024.parquetAdded+3
- functions/__pycache__/df_update.cpython-39.pyc
- functions/__pycache__/pitch_summary_functions.cpython-39.pyc
- functions/df_update.py+578-474
- functions/pitch_summary_functions.py+70-24
- stuff_model/__pycache__/feature_engineering.cpython-39.pyc
105 unmodified lines1061071081091101111123 unmodified lines11611711811912012112238 unmodified lines161162163164165166105 unmodified linestime_list = [item for sublist in [[y['gameDate'] for y in x['games']] for x in game_call['dates']] for item in sublist]date_list = [item for sublist in [[y['officialDate'] for y in x['games']] for x in game_call['dates']] for item in sublist]away_team_list = [item for sublist in [[y['teams']['away']['team']['name'] for y in x['games']] for x in game_call['dates']] for item in sublist]home_team_list = [item for sublist in [[y['teams']['home']['team']['name'] for y in x['games']] for x in game_call['dates']] for item in sublist]state_list = [item for sublist in [[y['status']['codedGameState'] for y in x['games']] for x in game_call['dates']] for item in sublist]venue_id = [item for sublist in [[y['venue']['id'] for y in x['games']] for x in game_call['dates']] for item in sublist]venue_name = [item for sublist in [[y['venue']['name'] for y in x['games']] for x in game_call['dates']] for item in sublist]3 unmodified lines'time': time_list,'date': date_list,'away': away_team_list,'home': home_team_list,'state': state_list,'venue_id': venue_id,'venue_name': venue_name})38 unmodified linesreturn data_totalreturn data_total105 unmodified lines1061071081091101111121131143 unmodified lines11811912012112212312412512638 unmodified lines165166167168169170171172173174175176177178179180181182183184185186187188189190191105 unmodified linestime_list = [item for sublist in [[y['gameDate'] for y in x['games']] for x in game_call['dates']] for item in sublist]date_list = [item for sublist in [[y['officialDate'] for y in x['games']] for x in game_call['dates']] for item in sublist]away_team_list = [item for sublist in [[y['teams']['away']['team']['name'] for y in x['games']] for x in game_call['dates']] for item in sublist]away_team_id_list = [item for sublist in [[y['teams']['away']['team']['id'] for y in x['games']] for x in game_call['dates']] for item in sublist]home_team_list = [item for sublist in [[y['teams']['home']['team']['name'] for y in x['games']] for x in game_call['dates']] for item in sublist]home_team_id_list = [item for sublist in [[y['teams']['home']['team']['id'] for y in x['games']] for x in game_call['dates']] for item in sublist]state_list = [item for sublist in [[y['status']['codedGameState'] for y in x['games']] for x in game_call['dates']] for item in sublist]venue_id = [item for sublist in [[y['venue']['id'] for y in x['games']] for x in game_call['dates']] for item in sublist]venue_name = [item for sublist in [[y['venue']['name'] for y in x['games']] for x in game_call['dates']] for item in sublist]3 unmodified lines'time': time_list,'date': date_list,'away': away_team_list,'away_id': away_team_id_list,'home': home_team_list,'home_id': home_team_id_list,'state': state_list,'venue_id': venue_id,'venue_name': venue_name})38 unmodified linesreturn data_totaldef get_data_new(self, game_list_input: list):"""Retrieves live game data for a list of game IDs in parallel.Parameters:- game_list_input (list): A list of game IDs for which to retrieve live data.Returns:- data_total (list): A list of JSON responses containing live game data for each game ID."""data_total = []print('This May Take a While. Progress Bar shows Completion of Data Retrieval.')def fetch_data(game_id):r = requests.get(f'https://statsapi.mlb.com/api/v1.1/game/{game_id}/feed/live')return r.json()with ThreadPoolExecutor() as executor:futures = {executor.submit(fetch_data, game_id): game_id for game_id in game_list_input}for future in tqdm(as_completed(futures), total=len(futures), desc="Processing", unit="iteration"):data_total.append(future.result())return data_total
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400import polars as plimport numpy as npimport pandas as pdimport api_scraperscrape = api_scraper.MLB_Scrape()from functions import df_updatefrom functions import pitch_summary_functionsupdate = df_update.df_update()from stuff_model import feature_engineering as fefrom stuff_model import stuff_applyimport requestsimport joblibfrom matplotlib.gridspec import GridSpecfrom shiny import App, reactive, ui, renderfrom shiny.ui import h2, tagsimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecimport seaborn as snsfrom functions.pitch_summary_functions import *from shiny import App, reactive, ui, renderfrom shiny.ui import h2, tagscolour_palette = ['#FFB000','#648FFF','#785EF0','#DC267F','#FE6100','#3D1EB2','#894D80','#16AA02','#B5592B','#A3C1ED']year_list = [2017,2018,2019,2020,2021,2022,2023,2024]level_dict = {'1':'MLB','11':'AAA',# '12':'AA',#'13':'A+','14':'A','17':'AFL','22':'College','21':'Prospects','51':'International' }function_dict={'velocity_kdes':'Velocity Distributions','break_plot':'Pitch Movement','tj_stuff_roling':'Rolling tjStuff+ by Pitch','tj_stuff_roling_game':'Rolling tjStuff+ by Game','location_plot_lhb':'Locations vs LHB','location_plot_rhb':'Locations vs RHB',}split_dict = {'all':'All','left':'LHH','right':'RHH'}split_dict_hand = {'all':['L','R'],'left':['L'],'right':['R']}type_dict = {'R':'Regular Season','S':'Spring','P':'Playoffs' }# List of MLB teams and their corresponding ESPN logo URLsmlb_teams = [{"team": "AZ", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/ari.png&h=500&w=500"},{"team": "ATH", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/oak.png&h=500&w=500"},{"team": "ATL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/atl.png&h=500&w=500"},{"team": "BAL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/bal.png&h=500&w=500"},{"team": "BOS", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/bos.png&h=500&w=500"},{"team": "CHC", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/chc.png&h=500&w=500"},{"team": "CWS", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/chw.png&h=500&w=500"},{"team": "CIN", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/cin.png&h=500&w=500"},{"team": "CLE", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/cle.png&h=500&w=500"},{"team": "COL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/col.png&h=500&w=500"},{"team": "DET", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/det.png&h=500&w=500"},{"team": "HOU", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/hou.png&h=500&w=500"},{"team": "KC", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/kc.png&h=500&w=500"},{"team": "LAA", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/laa.png&h=500&w=500"},{"team": "LAD", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/lad.png&h=500&w=500"},{"team": "MIA", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/mia.png&h=500&w=500"},{"team": "MIL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/mil.png&h=500&w=500"},{"team": "MIN", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/min.png&h=500&w=500"},{"team": "NYM", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/nym.png&h=500&w=500"},{"team": "NYY", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/nyy.png&h=500&w=500"},{"team": "PHI", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/phi.png&h=500&w=500"},{"team": "PIT", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/pit.png&h=500&w=500"},{"team": "SD", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/sd.png&h=500&w=500"},{"team": "SF", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/sf.png&h=500&w=500"},{"team": "SEA", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/sea.png&h=500&w=500"},{"team": "STL", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/stl.png&h=500&w=500"},{"team": "TB", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/tb.png&h=500&w=500"},{"team": "TEX", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/tex.png&h=500&w=500"},{"team": "TOR", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/tor.png&h=500&w=500"},{"team": "WSH", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/mlb/500/scoreboard/wsh.png&h=500&w=500"},{"team": "ZZZ", "logo_url": "https://a.espncdn.com/combiner/i?img=/i/teamlogos/leagues/500/mlb.png&w=500&h=500"}]df_image = pd.DataFrame(mlb_teams)image_dict = df_image.set_index('team')['logo_url'].to_dict()image_dict_flip = df_image.set_index('logo_url')['team'].to_dict()# # Define the features to be used for training# features_table = ['start_speed',# 'spin_rate',# 'extension',# 'ivb',# 'hb',# 'x0',# 'z0',# 'tj_stuff_plus']from shiny import App, reactive, ui, renderfrom shiny.ui import h2, tags# Define the UI layout for the appapp_ui = ui.page_sidebar(ui.sidebar(# Row for selecting season and levelui.row(ui.column(4, ui.input_select('year_input', 'Select Season', year_list, selected=2024)),ui.column(4, ui.input_select('level_input', 'Select Level', level_dict)),ui.column(4, ui.input_select('type_input', 'Select Type', type_dict,selected='R'))),# Row for the action button to get player listui.row(ui.input_action_button("player_button", "Get Player List", class_="btn-primary")),# Row for selecting the playerui.row(ui.column(12, ui.output_ui('player_select_ui', 'Select Player'))),# Row for selecting the date rangeui.row(ui.column(12, ui.output_ui('date_id', 'Select Date'))),# Rows for selecting plots and split optionsui.row(ui.column(4, ui.input_select('plot_id_1', 'Plot Left', function_dict, multiple=False, selected='velocity_kdes')),ui.column(4, ui.input_select('plot_id_2', 'Plot Middle', function_dict, multiple=False, selected='tj_stuff_roling')),ui.column(4, ui.input_select('plot_id_3', 'Plot Right', function_dict, multiple=False, selected='break_plot'))),ui.row(ui.column(6, ui.input_select('split_id', 'Select Split', split_dict, multiple=False)),ui.column(6, ui.input_numeric('rolling_window', 'Rolling Window (for tjStuff+ Plot)', min=1, value=50))),ui.row(ui.column(6, ui.input_switch("switch", "Custom Team?", False)),ui.column(6, ui.input_select('logo_select', 'Select Custom Logo', image_dict_flip, multiple=False))),# Row for the action button to generate plotui.row(ui.input_action_button("generate_plot", "Generate Plot", class_="btn-primary")),width="400px" # Added this parameter to control sidebar width),# Main content area with tabs (placed directly in page_sidebar)ui.navset_tab(ui.nav_panel("Pitching Summary",ui.output_text("status"),ui.output_plot('plot', width='2100px', height='2100px')),ui.nav_panel("Summary Table",ui.output_data_frame("grid"))))def server(input, output, session):@reactive.calc@reactive.event(input.pitcher_id, input.date_id,input.split_id)def cached_data():year_input = int(input.year_input())sport_id = int(input.level_input())player_input = int(input.pitcher_id())start_date = str(input.date_id()[0])end_date = str(input.date_id()[1])# Simulate an expensive data operationgame_list = scrape.get_player_games_list(sport_id = sport_id,season = year_input,player_id = player_input,start_date = start_date,end_date = end_date,game_type = [input.type_input()])data_list = scrape.get_data(game_list_input = game_list[:])df = (stuff_apply.stuff_apply(fe.feature_engineering(update.update(scrape.get_data_df(data_list = data_list).filter((pl.col("pitcher_id") == player_input)&(pl.col("is_pitch") == True)&(pl.col("start_speed") >= 50)&(pl.col('batter_hand').is_in(split_dict_hand[input.split_id()])))))).with_columns(pl.col('pitch_type').count().over('pitch_type').alias('pitch_count')))return df@render.ui@reactive.event(input.player_button, input.year_input, input.level_input, input.type_input,ignore_none=False)def player_select_ui():# Get the list of pitchers for the selected level and seasondf_pitcher_info = scrape.get_players(sport_id=int(input.level_input()), season=int(input.year_input()), game_type = [input.type_input()]).filter(pl.col("position").is_in(['P','TWP'])).sort("name")# Create a dictionary of pitcher IDs and namespitcher_dict = dict(zip(df_pitcher_info['player_id'], df_pitcher_info['name']))# Return a select input for choosing a pitcherreturn ui.input_select("pitcher_id", "Select Pitcher", pitcher_dict, selectize=True)@render.ui@reactive.event(input.player_button, input.year_input, input.level_input, input.type_input,ignore_none=False)def date_id():# Create a date range input for selecting the date range within the selected yearreturn ui.input_date_range("date_id", "Select Date Range",start=f"{int(input.year_input())}-01-01",end=f"{int(input.year_input())}-12-31",min=f"{int(input.year_input())}-01-01",max=f"{int(input.year_input())}-12-31")@output@render.textdef status():# Only show status when generatingif input.generate == 0:return ""return ""@output@render.plot@reactive.event(input.generate_plot, ignore_none=False)def plot():# Show progress/loading notificationwith ui.Progress(min=0, max=1) as p:p.set(message="Generating plot", detail="This may take a while...")p.set(0.3, "Gathering data...")year_input = int(input.year_input())sport_id = int(input.level_input())player_input = int(input.pitcher_id())start_date = str(input.date_id()[0])end_date = str(input.date_id()[1])print(year_input, sport_id, player_input, start_date, end_date)df = cached_data()df = df.clone()p.set(0.6, "Creating plot...")#plt.rcParams["figure.figsize"] = [10,10]fig = plt.figure(figsize=(26,26))plt.rcParams.update({'figure.autolayout': True})fig.set_facecolor('white')sns.set_theme(style="whitegrid", palette=colour_palette)print('this is the one plot')gs = gridspec.GridSpec(6, 8,height_ratios=[5,20,12,36,36,7],width_ratios=[4,18,18,18,18,18,18,4])gs.update(hspace=0.2, wspace=0.5)# Define the positions of each subplot in the gridax_headshot = fig.add_subplot(gs[1,1:3])ax_bio = fig.add_subplot(gs[1,3:5])ax_logo = fig.add_subplot(gs[1,5:7])ax_season_table = fig.add_subplot(gs[2,1:7])ax_plot_1 = fig.add_subplot(gs[3,1:3])ax_plot_2 = fig.add_subplot(gs[3,3:5])ax_plot_3 = fig.add_subplot(gs[3,5:7])ax_table = fig.add_subplot(gs[4,1:7])ax_footer = fig.add_subplot(gs[-1,1:7])ax_header = fig.add_subplot(gs[0,1:7])ax_left = fig.add_subplot(gs[:,0])ax_right = fig.add_subplot(gs[:,-1])# Hide axes for footer, header, left, and rightax_footer.axis('off')ax_header.axis('off')ax_left.axis('off')ax_right.axis('off')sns.set_theme(style="whitegrid", palette=colour_palette)fig.set_facecolor('white')df_teams = scrape.get_teams()player_headshot(player_input=player_input, ax=ax_headshot,sport_id=sport_id,season=year_input)player_bio(pitcher_id=player_input, ax=ax_bio,sport_id=sport_id,year_input=year_input)if input.switch():# Get the logo URL from the image dictionary using the team abbreviationlogo_url = input.logo_select()# Send a GET request to the logo URLresponse = requests.get(logo_url)# Open the image from the response contentimg = Image.open(BytesIO(response.content))# Display the image on the axisax_logo.set_xlim(0, 1.3)ax_logo.set_ylim(0, 1)ax_logo.imshow(img, extent=[0.3, 1.3, 0, 1], origin='upper')# Turn off the axisax_logo.axis('off')else:plot_logo(pitcher_id=player_input, ax=ax_logo, df_team=df_teams,df_players=scrape.get_players(sport_id,year_input))stat_summary_table(df=df,ax=ax_season_table,player_input=player_input,split=input.split_id(),sport_id=sport_id,game_type=[input.type_input()])# break_plot(df=df_plot,ax=ax2)for x,y,z in zip([input.plot_id_1(),input.plot_id_2(),input.plot_id_3()],[ax_plot_1,ax_plot_2,ax_plot_3],[1,3,5]):if x == 'velocity_kdes':velocity_kdes(df,ax=y,gs=gs,gs_x=[3,4],gs_y=[z,z+2],fig=fig)if x == 'tj_stuff_roling':tj_stuff_roling(df=df,window=int(input.rolling_window()),ax=y)if x == 'tj_stuff_roling_game':tj_stuff_roling_game(df=df,window=int(input.rolling_window()),ax=y)if x == 'break_plot':break_plot(df = df,ax=y)if x == 'location_plot_lhb':location_plot(df = df,ax=y,hand='L')if x == 'location_plot_rhb':location_plot(df = df,ax=y,hand='R')summary_table(df=df,ax=ax_table)plot_footer(ax_footer)fig.subplots_adjust(left=0.01, right=0.99, top=0.99, bottom=0.01)@output@render.data_frame@reactive.event(input.generate_plot, ignore_none=False)def grid():df = cached_data()df = df.clone()features_table = ['start_speed','spin_rate','extension','ivb','hb','x0','z0']selection = ['game_id','pitcher_id','pitcher_name','batter_id','batter_name','pitcher_hand','batter_hand','balls','strikes','play_code','event_type','pitch_type','vaa','haa']+features_table+['tj_stuff_plus']return render.DataGrid(df.select(selection).to_pandas().round(1),row_selection_mode='multiple',height='700px',width='fit-content',filters=True,)app = App(app_ui, server)app = App(app_ui, server)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488from shiny import App, ui, render, reactiveimport polars as plimport numpy as npimport pandas as pdimport api_scraperscrape = api_scraper.MLB_Scrape()from functions import df_updatefrom functions import pitch_summary_functionsupdate = df_update.df_update()from stuff_model import feature_engineering as fefrom stuff_model import stuff_applyimport requestsimport joblibfrom matplotlib.gridspec import GridSpecimport mathfrom pytabulator import TableOptions, Tabulator, output_tabulator, render_tabulator, themetheme.tabulator_site()colour_palette = ['#FFB000','#648FFF','#785EF0','#DC267F','#FE6100','#3D1EB2','#894D80','#16AA02','#B5592B','#A3C1ED']# df = pl.read_csv("data.csv")# df = pl.read_parquet("data_small.parquet")[:]# df = pl.read_parquet("data.parquet")[:]# print('df')season = 2024df_mlb = pl.read_parquet("data/data_mlb_2024.parquet")[:]df_aaa = pl.read_parquet("data/data_aaa_2024.parquet")[:]df_a = pl.read_parquet("data/data_a_2024.parquet")[:]def df_final(df:pl.dataframe,year_input:int,sport_id:int):df_schedule = scrape.get_schedule(year_input=[year_input],sport_id=[sport_id])df = df.join(df_schedule, on='game_id', how='left')df = df.with_columns(pl.when((pl.col('batter_team_id') == pl.col('away_id'))).then(pl.lit('Away')).when((pl.col('batter_team_id') == pl.col('home_id'))).then(pl.lit('Home')).otherwise(None).alias('home_away'))df = df.with_columns(pl.when((pl.col('pitcher_team_id') == pl.col('away_id'))).then(pl.lit('Away')).when((pl.col('pitcher_team_id') == pl.col('home_id'))).then(pl.lit('Home')).otherwise(None).alias('home_away_pitcher'))print('schedule')df_stuff = stuff_apply.stuff_apply(fe.feature_engineering(df))print('stuff')df_up = update.update(df)print('update')df_total = df_up.join(df_stuff[['play_id','tj_stuff_plus']], on='play_id', how='left')print('total')return df_totaldf_mlb_total = df_final(df=df_mlb,year_input=season,sport_id=1)df_aaa_total = df_final(df=df_aaa,year_input=season,sport_id=11)df_a_total = df_final(df=df_a.drop_nulls(subset=['start_speed']),year_input=season,sport_id=14)rounding_dict = {'pa': 0,'bip': 0,'hits': 0,'k': 0,'bb': 0,'max_launch_speed': 1,'launch_speed_90': 1,'launch_speed': 1,'pitches': 0,'tj_stuff_plus_avg': 0,'avg': 3,'obp': 3,'slg': 3,'ops': 3,'k_percent': 3,'bb_percent': 3,'k_minus_bb_percent': 3,'sweet_spot_percent': 3,'woba_percent': 3,'xwoba_percent': 3,'woba_percent_contact': 3,'xwoba_percent_contact': 3,'hard_hit_percent': 3,'barrel_percent': 3,'zone_contact_percent': 3,'zone_swing_percent': 3,'zone_percent': 3,'chase_percent': 3,'chase_contact': 3,'swing_percent': 3,'whiff_rate': 3,'swstr_rate': 3,'ground_ball_percent': 3,'line_drive_percent': 3,'fly_ball_percent': 3,'pop_up_percent': 3,'heart_zone_swing_percent': 3,'shadow_zone_swing_percent': 3,'chase_zone_swing_percent': 3,'waste_zone_swing_percent': 3,'heart_zone_whiff_percent': 3,'shadow_zone_whiff_percent': 3,'chase_zone_whiff_percent': 3,'waste_zone_whiff_percent': 3,'start_speed_avg': 1,'vb_avg': 1,'ivb_avg': 1,'hb_avg': 1,'z0_avg': 1,'x0_avg': 1,'vaa_avg': 1,'haa_avg': 1,'spin_rate_avg': 0,'extension_avg': 1}columns = [{ "title": "PA", "field": "pa", "width": 150},{ "title": "BBE", "field": "bip", "width": 150 },{ "title": "H", "field": "hits", "width": 150 },{ "title": "K", "field": "k", "width": 150 },{ "title": "BB", "field": "bb", "width": 150 },{ "title": "Max EV", "field": "max_launch_speed", "width": 150 },{ "title": "90th% EV", "field": "launch_speed_90", "width": 150 },{ "title": "EV", "field": "launch_speed", "width": 150 },{ "title": "Pitches", "field": "pitches", "width": 150 },{ "title": "AVG", "field": "avg", "width": 150 },{ "title": "OBP", "field": "obp", "width": 150 },{ "title": "SLG", "field": "slg", "width": 150 },{ "title": "OPS", "field": "ops", "width": 150 },{ "title": "K%", "field": "k_percent", "width": 150,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "BB%", "field": "bb_percent", "width": 150,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "K-BB%", "field": "k_minus_bb_percent", "width": 150,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "SwSpot%", "field": "sweet_spot_percent", "width": 150,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "wOBA", "field": "woba_percent", "width": 150 },{ "title": "xwOBA", "field": "xwoba_percent", "width": 150 },{ "title": "wOBACON", "field": "woba_percent_contact", "width": 150 },{ "title": "xwOBACON", "field": "xwoba_percent_contact", "width": 150 },{ "title": "HardHit%", "field": "hard_hit_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Barrel%", "field": "barrel_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Z-Contact%", "field": "zone_contact_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Z-Swing%", "field": "zone_swing_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Zone%", "field": "zone_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "O-Swing%", "field": "chase_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "O-Contact%", "field": "chase_contact", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Swing%", "field": "swing_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Whiff%", "field": "whiff_rate", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "SwStr%", "field": "swstr_rate", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "GB%", "field": "ground_ball_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "LD%", "field": "line_drive_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "FB%", "field": "fly_ball_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "PU%", "field": "pop_up_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Heart Swing%", "field": "heart_zone_swing_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Shadow Swing%", "field": "shadow_zone_swing_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Chase Swing%", "field": "chase_zone_swing_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Waste Swing%", "field": "waste_zone_swing_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Heart Whiff%", "field": "heart_zone_whiff_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Shadow Whiff%", "field": "shadow_zone_whiff_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Chase Whiff%", "field": "chase_zone_whiff_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "Waste Whiff%", "field": "waste_zone_whiff_percent", "width": 150 ,"formatter": "money", "formatterParams":{"decimal":".","thousand":".","symbol":"%","symbolAfter":"%","negativeSign":True,"precision":1}},{ "title": "tjStuff+", "field": "tj_stuff_plus_avg", "width": 150 },{ "title": "Velocity", "field": "start_speed_avg", "width": 150 },{ "title": "Extension", "field": "extension_avg", "width": 150 },{ "title": "VB", "field": "vb_avg", "width": 150 },{ "title": "iVB", "field": "ivb_avg", "width": 150 },{ "title": "HB", "field": "hb_avg", "width": 150 },{ "title": "vRel", "field": "z0_avg", "width": 150 },{ "title": "hRel", "field": "x0_avg", "width": 150 },{ "title": "VAA", "field": "vaa_avg", "width": 150 },{ "title": "HAA", "field": "haa_avg", "width": 150 },{ "title": "Spin Rate", "field": "spin_rate_avg", "width": 150 },{ "title": "Extension", "field": "extension_avg", "width": 150 },]stat_titles = dict(zip([col["field"] for col in columns],[col["title"] for col in columns]))stat_selection = [key for key in stat_titles.keys()]agg_titles = {'batter_id':'Batter ID','batter_name':'Batter Name','batter_team':'Batter Team','batter_hand':'Batter Hand','pitcher_id':'Pitcher ID','pitcher_name':'Pitcher Name','pitcher_team':'Pitcher Team','pitcher_hand':'Pitcher Hand','pitch_type':'Pitch Type','pitch_group':'Pitch Group','home_away_batter':'Home/Away Batter','home_away_pitcher':'Home/Away Pitcher','is_swing':'Is Swing?','is_bip':'Is BIP?','in_zone_final':'In Zone?','attack_zone_final':'Attack Zone'}columns_group = [{ "title": "Batter ID", "field": "batter_id", "width": 150, "headerFilter":"input","frozen":True,},{ "title": "Batter Name", "field": "batter_name", "width": 200,"frozen":True, "headerFilter":"input" },{ "title": "Batter Team", "field": "batter_team", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Batter Hand", "field": "batter_hand", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Pitcher ID", "field": "pitcher_id", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Pitcher Name", "field": "pitcher_name", "width": 200,"frozen":True, "headerFilter":"input" },{ "title": "Pitcher Team", "field": "pitcher_team", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Pitcher Hand", "field": "pitcher_hand", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Pitch Type", "field": "pitch_type", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Pitch Group", "field": "pitch_group", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Home/Away Batter", "field": "home_away_batter", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Home/Away Pitcher", "field": "home_away_pitcher", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Is Swing?", "field": "is_swing", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Is BIP?", "field": "is_bip", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "In Zone?", "field": "in_zone_final", "width": 150,"frozen":True, "headerFilter":"input" },{ "title": "Attack Zone", "field": "attack_zone_final", "width": 150,"frozen":True, "headerFilter":"input" }]app_ui = ui.page_sidebar(ui.sidebar(ui.input_selectize("level_input","Select Level:",choices=['MLB','AAA','A'],multiple=False,selected=['MLB']),ui.input_selectize("list_input","Select Aggregation:",choices=agg_titles,multiple=True,selected=['batter_id', 'batter_name']),ui.input_selectize("list_stats","Select Stats:",choices=stat_titles,multiple=True,selected=['pa']),ui.input_date_range("date_id","Select Date Range",start=f'{season}-01-01',end=f'{season}-12-01',min=f'{season}-01-01',max=f'{season}-12-01',),ui.hr(),ui.h4("Filters"),ui.div({"id": "filter-container"},ui.div({"class": "filter-row", "id": "filter_row_1"}, # Add id for deletionui.row(ui.column(5, # Adjusted column widths to make room for delete buttonui.input_select("filter_column_1","Metric",choices={})),ui.column(3,ui.input_select("filter_operator_1","Operator",choices=[">=", "<="]),),ui.column(3,ui.input_numeric("filter_value_1","Value",value=0)),ui.column(1,ui.markdown(" "),ui.input_action_button(f"delete_filter_1","",class_="btn-danger btn-sm",style="padding: 3px 6px;",icon='✖'))))),ui.input_action_button("add_filter","Add Filter",class_="btn-secondary"),ui.br(),ui.br(),ui.input_action_button("generate_table","Generate Table",class_="btn-primary"),width="400px"),ui.navset_tab(ui.nav_panel("Leaderboard",ui.card(#ui.card_header("Leaderboard"),output_tabulator("tabulator"))),))def server(input, output, session):# Store the number of active filtersfilter_count = reactive.value(1)# Store active filter IDsactive_filters = reactive.value([1])@reactive.effect@reactive.event(input.list_stats)def _():stat_choices = {k: k for k in input.list_stats()}filtered_stat_choices = {key: stat_titles[key] for key in stat_choices}ui.update_select("filter_column_1", choices=filtered_stat_choices)@reactive.effect@reactive.event(input.add_filter)def _():current_count = filter_count.get()new_count = current_count + 1stat_choices = {k: k for k in input.list_stats()}filtered_stat_choices = {key: stat_titles[key] for key in stat_choices}ui.insert_ui(selector="#filter-container",where="beforeEnd",ui=ui.div({"class": "filter-row", "id": f"filter_row_{new_count}"},ui.row(ui.column(5,ui.input_select(f"filter_column_{new_count}","Metric",choices=filtered_stat_choices),),ui.column(3,ui.input_select(f"filter_operator_{new_count}","Operator",choices=[">=", "<="]),),ui.column(3,ui.input_numeric(f"filter_value_{new_count}","Value",value=0)),ui.column(1,ui.markdown(" "),ui.input_action_button(f"delete_filter_{new_count}","",class_="btn-danger btn-sm",style="padding: 3px 6px;",icon='✖')))))filter_count.set(new_count)current_filters = active_filters.get()current_filters.append(new_count)active_filters.set(current_filters)@reactive.effectdef _():# Monitor all possible delete buttonsfor i in range(1, filter_count.get() + 1):try:if getattr(input, f"delete_filter_{i}")() > 0:# Remove the filter rowui.remove_ui(f"#filter_row_{i}")# Update active filterscurrent_filters = active_filters.get()if i in current_filters:current_filters.remove(i)active_filters.set(current_filters)except:continue@output@render_tabulator@reactive.event(input.generate_table, ignore_none=False)def tabulator():columns_c = columns.copy()selection_list = list(input.list_input())start_date = str(input.date_id()[0])end_date = str(input.date_id()[1])if input.level_input() == "MLB":df_agg = update.update_summary_select(df=df_mlb_total.filter((pl.col('game_date')>=start_date)&(pl.col('game_date')<=end_date)),selection=selection_list)elif input.level_input() == "AAA":df_agg = update.update_summary_select(df=df_aaa_total.filter((pl.col('game_date')>=start_date)&(pl.col('game_date')<=end_date)),selection=selection_list)elif input.level_input() == "A":df_agg = update.update_summary_select(df=df_a_total.filter((pl.col('game_date')>=start_date)&(pl.col('game_date')<=end_date)),selection=selection_list)df_agg = df_agg.select(selection_list + list(input.list_stats()))#.sort('pa', descending=True)# Apply filters - only for active filtersfor i in active_filters.get():try:col_name = getattr(input, f"filter_column_{i}")()if col_name: # Only apply filter if column is selectedoperator = getattr(input, f"filter_operator_{i}")()if col_name in [col["field"] for col in columns_c if col.get("formatter") == "money"]:value = getattr(input, f"filter_value_{i}")()/100else:value = getattr(input, f"filter_value_{i}")()if operator == ">=":df_agg = df_agg.filter(pl.col(col_name) >= value)elif operator == "<=":df_agg = df_agg.filter(pl.col(col_name) <= value)except:continuefor col in df_agg.columns[len(selection_list):]:if col in rounding_dict:df_agg = df_agg.with_columns(pl.col(col).round(rounding_dict[col]))for column in columns_c:if column.get("formatter") == "money" and column.get("field") in df_agg.columns:df_agg = df_agg.with_columns(pl.col(column.get("field"))*100)col_group = []for column in columns_group:if column.get("field") in df_agg.columns:col_group.append(column)col_group_stats = []for column in columns_c:if column.get("field") in df_agg.columns:col_group_stats.append(column)columns_c = col_group + col_group_statsreturn Tabulator(df_agg.to_pandas(),table_options=TableOptions(height=800,columns=columns_c,))app = App(app_ui, server)
123version https://git-lfs.github.com/spec/v1oid sha256:11ddeb5b35ced8d2a3c627af2cded75c78fbb333fa4331569b78a7fb29ddce1fsize 44964738123version https://git-lfs.github.com/spec/v1oid sha256:cf48b06263a3b0a25b701e98c589f7e11bdf0ec3665562082ea209a61b55468esize 117704536123version https://git-lfs.github.com/spec/v1oid sha256:e0f2c52277a98ecbba343650996f32bbb8a847631d676bce2f07dbd3931f09a8size 128295721123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475import polars as plimport numpy as npimport joblibloaded_model = joblib.load('joblib_model/barrel_model.joblib')in_zone_model = joblib.load('joblib_model/in_zone_model_knn_20240410.joblib')attack_zone_model = joblib.load('joblib_model/model_attack_zone.joblib')xwoba_model = joblib.load('joblib_model/xwoba_model.joblib')px_model = joblib.load('joblib_model/linear_reg_model_x.joblib')pz_model = joblib.load('joblib_model/linear_reg_model_z.joblib')class df_update:def __init__(self):passdef update(self, df_clone: pl.DataFrame):df = df_clone.clone()# Assuming px_model is defined and df is your DataFramehit_codes = ['single','double','home_run', 'triple']ab_codes = ['single', 'strikeout', 'field_out','grounded_into_double_play', 'fielders_choice', 'force_out','double', 'field_error', 'home_run', 'triple','double_play','fielders_choice_out', 'strikeout_double_play','other_out','triple_play']obp_true_codes = ['single', 'walk','double','home_run', 'triple','hit_by_pitch', 'intent_walk']obp_codes = ['single', 'strikeout', 'walk', 'field_out','grounded_into_double_play', 'fielders_choice', 'force_out','double', 'sac_fly', 'field_error', 'home_run', 'triple','hit_by_pitch', 'double_play', 'intent_walk','fielders_choice_out', 'strikeout_double_play','sac_fly_double_play','other_out','triple_play']contact_codes = ['In play, no out','Foul', 'In play, out(s)','In play, run(s)','Foul Bunt']bip_codes = ['In play, no out', 'In play, run(s)','In play, out(s)']conditions_barrel = [df['launch_speed'].is_null(),(df['launch_speed'] * 1.5 - df['launch_angle'] >= 117) &(df['launch_speed'] + df['launch_angle'] >= 124) &(df['launch_speed'] >= 98) &(df['launch_angle'] >= 4) & (df['launch_angle'] <= 50)]choices_barrel = [False, True]conditions_tb = [(df['event_type'] == 'single'),(df['event_type'] == 'double'),(df['event_type'] == 'triple'),(df['event_type'] == 'home_run')]choices_tb = [1, 2, 3, 4]conditions_woba = [df['event_type'].is_in(['strikeout', 'field_out', 'sac_fly', 'force_out', 'grounded_into_double_play', 'fielders_choice', 'field_error', 'sac_bunt', 'double_play', 'fielders_choice_out', 'strikeout_double_play', 'sac_fly_double_play', 'other_out']),df['event_type'] == 'walk',df['event_type'] == 'hit_by_pitch',df['event_type'] == 'single',df['event_type'] == 'double',df['event_type'] == 'triple',df['event_type'] == 'home_run']choices_woba = [0, 0.689, 0.720, 0.881, 1.254, 1.589, 2.048]woba_codes = ['strikeout', 'field_out', 'single', 'walk', 'hit_by_pitch', 'double', 'sac_fly', 'force_out', 'home_run', 'grounded_into_double_play', 'fielders_choice', 'field_error', 'triple', 'sac_bunt', 'double_play', 'fielders_choice_out', 'strikeout_double_play', 'sac_fly_double_play', 'other_out']pitch_cat = {'FA': 'Fastball','FF': 'Fastball','FT': 'Fastball','FC': 'Fastball','FS': 'Off-Speed','FO': 'Off-Speed','SI': 'Fastball','ST': 'Breaking','SL': 'Breaking','CU': 'Breaking','KC': 'Breaking','SC': 'Off-Speed','GY': 'Off-Speed','SV': 'Breaking','CS': 'Breaking','CH': 'Off-Speed','KN': 'Off-Speed','EP': 'Breaking','UN': None,'IN': None,'PO': None,'AB': None,'AS': None,'NP': None}df = df.with_columns([pl.when(df['type_ab'].is_not_null()).then(1).otherwise(0).alias('pa'),pl.when(df['is_pitch']).then(1).otherwise(0).alias('pitches'),pl.when(df['sz_top'] == 0).then(None).otherwise(df['sz_top']).alias('sz_top'),pl.when(df['sz_bot'] == 0).then(None).otherwise(df['sz_bot']).alias('sz_bot'),pl.when(df['zone'] > 0).then(df['zone'] < 10).otherwise(None).alias('in_zone'),pl.Series(px_model.predict(df[['x']].fill_null(0).to_numpy())[:, 0]).alias('px_predict'),pl.Series(pz_model.predict(df[['y']].fill_null(0).to_numpy())[:, 0] + 3.2).alias('pz_predict'),pl.Series(in_zone_model.predict(df[['px','pz','sz_top','sz_bot']].fill_null(0).to_numpy())[:]).alias('in_zone_predict'),pl.Series(attack_zone_model.predict(df[['px','pz','sz_top','sz_bot']].fill_null(0).to_numpy())[:]).alias('attack_zone_predict'),pl.when(df['event_type'].is_in(hit_codes)).then(True).otherwise(False).alias('hits'),pl.when(df['event_type'].is_in(ab_codes)).then(True).otherwise(False).alias('ab'),pl.when(df['event_type'].is_in(obp_true_codes)).then(True).otherwise(False).alias('on_base'),pl.when(df['event_type'].is_in(obp_codes)).then(True).otherwise(False).alias('obp'),pl.when(df['play_description'].is_in(bip_codes)).then(True).otherwise(False).alias('bip'),pl.when(conditions_barrel[0]).then(choices_barrel[0]).when(conditions_barrel[1]).then(choices_barrel[1]).otherwise(None).alias('barrel'),pl.when(df['launch_angle'].is_null()).then(False).when((df['launch_angle'] >= 8) & (df['launch_angle'] <= 32)).then(True).otherwise(None).alias('sweet_spot'),pl.when(df['launch_speed'].is_null()).then(False).when(df['launch_speed'] >= 94.5).then(True).otherwise(None).alias('hard_hit'),pl.when(conditions_tb[0]).then(choices_tb[0]).when(conditions_tb[1]).then(choices_tb[1]).when(conditions_tb[2]).then(choices_tb[2]).when(conditions_tb[3]).then(choices_tb[3]).otherwise(None).alias('tb'),pl.when(conditions_woba[0]).then(choices_woba[0]).when(conditions_woba[1]).then(choices_woba[1]).when(conditions_woba[2]).then(choices_woba[2]).when(conditions_woba[3]).then(choices_woba[3]).when(conditions_woba[4]).then(choices_woba[4]).when(conditions_woba[5]).then(choices_woba[5]).when(conditions_woba[6]).then(choices_woba[6]).otherwise(None).alias('woba'),pl.when((df['play_code'] == 'S') | (df['play_code'] == 'W') | (df['play_code'] == 'T')).then(1).otherwise(0).alias('whiffs'),pl.when((df['play_code'] == 'S') | (df['play_code'] == 'W') | (df['play_code'] == 'T') | (df['play_code'] == 'C')).then(1).otherwise(0).alias('csw'),pl.when(pl.col('is_swing').cast(pl.Boolean)).then(1).otherwise(0).alias('swings'),pl.col('event_type').is_in(['strikeout','strikeout_double_play']).alias('k'),pl.col('event_type').is_in(['walk', 'intent_walk']).alias('bb'),pl.lit(None).alias('attack_zone'),pl.lit(None).alias('woba_pred'),pl.lit(None).alias('woba_pred_contact')])df = df.with_columns([pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('woba_codes'),pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('xwoba_codes'),pl.when((pl.col('tb') >= 0)).then(df['woba']).otherwise(None).alias('woba_contact'),pl.when(pl.col('px').is_null()).then(pl.col('px_predict')).otherwise(pl.col('px')).alias('px'),pl.when(pl.col('pz').is_null()).then(pl.col('pz_predict')).otherwise(pl.col('pz')).alias('pz'),pl.when(pl.col('in_zone').is_null()).then(pl.col('in_zone_predict')).otherwise(pl.col('in_zone')).alias('in_zone'),pl.when(df['launch_speed'].is_null()).then(None).otherwise(df['barrel']).alias('barrel'),pl.lit('average').alias('average'),pl.when(pl.col('in_zone') == False).then(True).otherwise(False).alias('out_zone'),pl.when((pl.col('in_zone') == True) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('zone_swing'),pl.when((pl.col('in_zone') == True) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('zone_contact'),pl.when((pl.col('in_zone') == False) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('ozone_swing'),pl.when((pl.col('in_zone') == False) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('ozone_contact'),pl.when(pl.col('event_type').str.contains('strikeout')).then(True).otherwise(False).alias('k'),pl.when(pl.col('event_type').is_in(['walk', 'intent_walk'])).then(True).otherwise(False).alias('bb'),pl.when(pl.col('attack_zone').is_null()).then(pl.col('attack_zone_predict')).otherwise(pl.col('attack_zone')).alias('attack_zone'),])df = df.with_columns([(df['k'].cast(pl.Float32) - df['bb'].cast(pl.Float32)).alias('k_minus_bb'),(df['bb'].cast(pl.Float32) - df['k'].cast(pl.Float32)).alias('bb_minus_k'),(df['launch_speed'] > 0).alias('bip_div'),(df['attack_zone'] == 0).alias('heart'),(df['attack_zone'] == 1).alias('shadow'),(df['attack_zone'] == 2).alias('chase'),(df['attack_zone'] == 3).alias('waste'),((df['attack_zone'] == 0) & (df['swings'] == 1)).alias('heart_swing'),((df['attack_zone'] == 1) & (df['swings'] == 1)).alias('shadow_swing'),((df['attack_zone'] == 2) & (df['swings'] == 1)).alias('chase_swing'),((df['attack_zone'] == 3) & (df['swings'] == 1)).alias('waste_swing'),((df['attack_zone'] == 0) & (df['whiffs'] == 1)).alias('heart_whiff'),((df['attack_zone'] == 1) & (df['whiffs'] == 1)).alias('shadow_whiff'),((df['attack_zone'] == 2) & (df['whiffs'] == 1)).alias('chase_whiff'),((df['attack_zone'] == 3) & (df['whiffs'] == 1)).alias('waste_whiff')])[0, 0.689, 0.720, 0.881, 1.254, 1.589, 2.048]df = df.with_columns([pl.Series([sum(x) for x in xwoba_model.predict_proba(df[['launch_angle', 'launch_speed']].fill_null(0).to_numpy()[:]) * ([0, 0.881, 1.254, 1.589, 2.048])]).alias('woba_pred_predict')])df = df.with_columns([pl.when(pl.col('event_type').is_in(['walk'])).then(0.689).when(pl.col('event_type').is_in(['hit_by_pitch'])).then(0.720).when(pl.col('event_type').is_in(['strikeout', 'strikeout_double_play'])).then(0).otherwise(pl.col('woba_pred_predict')).alias('woba_pred_predict')])df = df.with_columns([pl.when(pl.col('woba_codes').is_null()).then(None).otherwise(pl.col('woba_pred_predict')).alias('woba_pred'),pl.when(pl.col('bip')!=1).then(None).otherwise(pl.col('woba_pred_predict')).alias('woba_pred_contact'),])df = df.with_columns([pl.when(pl.col('trajectory').is_in(['bunt_popup'])).then(pl.lit('popup')).when(pl.col('trajectory').is_in(['bunt_grounder'])).then(pl.lit('ground_ball')).when(pl.col('trajectory').is_in(['bunt_line_drive'])).then(pl.lit('line_drive')).when(pl.col('trajectory').is_in([''])).then(pl.lit(None)).otherwise(pl.col('trajectory')).alias('trajectory')])# Create one-hot encoded columns for the trajectory columndummy_df = df.select(pl.col('trajectory')).to_dummies()# Rename the one-hot encoded columnsdummy_df = dummy_df.rename({'trajectory_fly_ball': 'trajectory_fly_ball','trajectory_ground_ball': 'trajectory_ground_ball','trajectory_line_drive': 'trajectory_line_drive','trajectory_popup': 'trajectory_popup'})# Ensure the columns are present in the DataFramefor col in ['trajectory_fly_ball', 'trajectory_ground_ball', 'trajectory_line_drive', 'trajectory_popup']:if col not in dummy_df.columns:dummy_df = dummy_df.with_columns(pl.lit(0).alias(col))# Join the one-hot encoded columns back to the original DataFramedf = df.hstack(dummy_df)# Check if 'trajectory_null' column exists and drop itif 'trajectory_null' in df.columns:df = df.drop('trajectory_null')return df# Assuming df is your Polars DataFramedef update_summary(self, df: pl.DataFrame, pitcher: bool = True) -> pl.DataFrame:"""Update summary statistics for pitchers or batters.Parameters:df (pl.DataFrame): The input Polars DataFrame containing player statistics.pitcher (bool): A flag indicating whether to calculate statistics for pitchers (True) or batters (False).Returns:pl.DataFrame: A Polars DataFrame with aggregated and calculated summary statistics."""# Determine the position based on the pitcher flagif pitcher:position = 'pitcher'else:position = 'batter'# Group by position_id and position_name, then aggregate various statisticsdf_summ = df.group_by([f'{position}_id', f'{position}_name']).agg([pl.col('pa').sum().alias('pa'),pl.col('ab').sum().alias('ab'),pl.col('obp').sum().alias('obp_pa'),pl.col('hits').sum().alias('hits'),pl.col('on_base').sum().alias('on_base'),pl.col('k').sum().alias('k'),pl.col('bb').sum().alias('bb'),pl.col('bb_minus_k').sum().alias('bb_minus_k'),pl.col('csw').sum().alias('csw'),pl.col('bip').sum().alias('bip'),pl.col('bip_div').sum().alias('bip_div'),pl.col('tb').sum().alias('tb'),pl.col('woba').sum().alias('woba'),pl.col('woba_contact').sum().alias('woba_contact'),pl.col('woba_pred').sum().alias('xwoba'),pl.col('woba_pred_contact').sum().alias('xwoba_contact'),pl.col('woba_codes').sum().alias('woba_codes'),pl.col('xwoba_codes').sum().alias('xwoba_codes'),pl.col('hard_hit').sum().alias('hard_hit'),pl.col('barrel').sum().alias('barrel'),pl.col('sweet_spot').sum().alias('sweet_spot'),pl.col('launch_speed').max().alias('max_launch_speed'),pl.col('launch_speed').quantile(0.90).alias('launch_speed_90'),pl.col('launch_speed').mean().alias('launch_speed'),pl.col('launch_angle').mean().alias('launch_angle'),pl.col('is_pitch').sum().alias('pitches'),pl.col('swings').sum().alias('swings'),pl.col('in_zone').sum().alias('in_zone'),pl.col('out_zone').sum().alias('out_zone'),pl.col('whiffs').sum().alias('whiffs'),pl.col('zone_swing').sum().alias('zone_swing'),pl.col('zone_contact').sum().alias('zone_contact'),pl.col('ozone_swing').sum().alias('ozone_swing'),pl.col('ozone_contact').sum().alias('ozone_contact'),pl.col('trajectory_ground_ball').sum().alias('ground_ball'),pl.col('trajectory_line_drive').sum().alias('line_drive'),pl.col('trajectory_fly_ball').sum().alias('fly_ball'),pl.col('trajectory_popup').sum().alias('pop_up'),pl.col('attack_zone').count().alias('attack_zone'),pl.col('heart').sum().alias('heart'),pl.col('shadow').sum().alias('shadow'),pl.col('chase').sum().alias('chase'),pl.col('waste').sum().alias('waste'),pl.col('heart_swing').sum().alias('heart_swing'),pl.col('shadow_swing').sum().alias('shadow_swing'),pl.col('chase_swing').sum().alias('chase_swing'),pl.col('waste_swing').sum().alias('waste_swing'),pl.col('heart_whiff').sum().alias('heart_whiff'),pl.col('shadow_whiff').sum().alias('shadow_whiff'),pl.col('chase_whiff').sum().alias('chase_whiff'),pl.col('waste_whiff').sum().alias('waste_whiff')])# Add calculated columns to the summary DataFramedf_summ = df_summ.with_columns([(pl.col('hits') / pl.col('ab')).alias('avg'),(pl.col('on_base') / pl.col('obp_pa')).alias('obp'),(pl.col('tb') / pl.col('ab')).alias('slg'),(pl.col('on_base') / pl.col('obp_pa') + pl.col('tb') / pl.col('ab')).alias('ops'),(pl.col('k') / pl.col('pa')).alias('k_percent'),(pl.col('bb') / pl.col('pa')).alias('bb_percent'),(pl.col('bb_minus_k') / pl.col('pa')).alias('bb_minus_k_percent'),(pl.col('bb') / pl.col('k')).alias('bb_over_k_percent'),(pl.col('csw') / pl.col('pitches')).alias('csw_percent'),(pl.col('sweet_spot') / pl.col('bip_div')).alias('sweet_spot_percent'),(pl.col('woba') / pl.col('woba_codes')).alias('woba_percent'),(pl.col('woba_contact') / pl.col('bip')).alias('woba_percent_contact'),(pl.col('hard_hit') / pl.col('bip_div')).alias('hard_hit_percent'),(pl.col('barrel') / pl.col('bip_div')).alias('barrel_percent'),(pl.col('zone_contact') / pl.col('zone_swing')).alias('zone_contact_percent'),(pl.col('zone_swing') / pl.col('in_zone')).alias('zone_swing_percent'),(pl.col('in_zone') / pl.col('pitches')).alias('zone_percent'),(pl.col('ozone_swing') / (pl.col('pitches') - pl.col('in_zone'))).alias('chase_percent'),(pl.col('ozone_contact') / pl.col('ozone_swing')).alias('chase_contact'),(pl.col('swings') / pl.col('pitches')).alias('swing_percent'),(pl.col('whiffs') / pl.col('swings')).alias('whiff_rate'),(pl.col('whiffs') / pl.col('pitches')).alias('swstr_rate'),(pl.col('ground_ball') / pl.col('bip')).alias('ground_ball_percent'),(pl.col('line_drive') / pl.col('bip')).alias('line_drive_percent'),(pl.col('fly_ball') / pl.col('bip')).alias('fly_ball_percent'),(pl.col('pop_up') / pl.col('bip')).alias('pop_up_percent'),(pl.col('heart') / pl.col('attack_zone')).alias('heart_zone_percent'),(pl.col('shadow') / pl.col('attack_zone')).alias('shadow_zone_percent'),(pl.col('chase') / pl.col('attack_zone')).alias('chase_zone_percent'),(pl.col('waste') / pl.col('attack_zone')).alias('waste_zone_percent'),(pl.col('heart_swing') / pl.col('heart')).alias('heart_zone_swing_percent'),(pl.col('shadow_swing') / pl.col('shadow')).alias('shadow_zone_swing_percent'),(pl.col('chase_swing') / pl.col('chase')).alias('chase_zone_swing_percent'),(pl.col('waste_swing') / pl.col('waste')).alias('waste_zone_swing_percent'),(pl.col('heart_whiff') / pl.col('heart_swing')).alias('heart_zone_whiff_percent'),(pl.col('shadow_whiff') / pl.col('shadow_swing')).alias('shadow_zone_whiff_percent'),(pl.col('chase_whiff') / pl.col('chase_swing')).alias('chase_zone_whiff_percent'),(pl.col('waste_whiff') / pl.col('waste_swing')).alias('waste_zone_whiff_percent'),(pl.col('xwoba') / pl.col('xwoba_codes')).alias('xwoba_percent'),(pl.col('xwoba_contact') / pl.col('bip')).alias('xwoba_percent_contact')])return df_summ# Assuming df is your Polars DataFramedef update_summary_select(self, df: pl.DataFrame, selection: list) -> pl.DataFrame:"""Update summary statistics for pitchers or batters.Parameters:df (pl.DataFrame): The input Polars DataFrame containing player statistics.pitcher (bool): A flag indicating whether to calculate statistics for pitchers (True) or batters (False).Returns:pl.DataFrame: A Polars DataFrame with aggregated and calculated summary statistics."""# Group by position_id and position_name, then aggregate various statisticsdf_summ = df.group_by(selection).agg([pl.col('pa').sum().alias('pa'),pl.col('ab').sum().alias('ab'),pl.col('obp').sum().alias('obp_pa'),pl.col('hits').sum().alias('hits'),pl.col('on_base').sum().alias('on_base'),pl.col('k').sum().alias('k'),pl.col('bb').sum().alias('bb'),pl.col('bb_minus_k').sum().alias('bb_minus_k'),pl.col('csw').sum().alias('csw'),pl.col('bip').sum().alias('bip'),pl.col('bip_div').sum().alias('bip_div'),pl.col('tb').sum().alias('tb'),pl.col('woba').sum().alias('woba'),pl.col('woba_contact').sum().alias('woba_contact'),pl.col('woba_pred').sum().alias('xwoba'),pl.col('woba_pred_contact').sum().alias('xwoba_contact'),pl.col('woba_codes').sum().alias('woba_codes'),pl.col('xwoba_codes').sum().alias('xwoba_codes'),pl.col('hard_hit').sum().alias('hard_hit'),pl.col('barrel').sum().alias('barrel'),pl.col('sweet_spot').sum().alias('sweet_spot'),pl.col('launch_speed').max().alias('max_launch_speed'),pl.col('launch_speed').quantile(0.90).alias('launch_speed_90'),pl.col('launch_speed').mean().alias('launch_speed'),pl.col('launch_angle').mean().alias('launch_angle'),pl.col('is_pitch').sum().alias('pitches'),pl.col('swings').sum().alias('swings'),pl.col('in_zone').sum().alias('in_zone'),pl.col('out_zone').sum().alias('out_zone'),pl.col('whiffs').sum().alias('whiffs'),pl.col('zone_swing').sum().alias('zone_swing'),pl.col('zone_contact').sum().alias('zone_contact'),pl.col('ozone_swing').sum().alias('ozone_swing'),pl.col('ozone_contact').sum().alias('ozone_contact'),pl.col('trajectory_ground_ball').sum().alias('ground_ball'),pl.col('trajectory_line_drive').sum().alias('line_drive'),pl.col('trajectory_fly_ball').sum().alias('fly_ball'),pl.col('trajectory_popup').sum().alias('pop_up'),pl.col('attack_zone').count().alias('attack_zone'),pl.col('heart').sum().alias('heart'),pl.col('shadow').sum().alias('shadow'),pl.col('chase').sum().alias('chase'),pl.col('waste').sum().alias('waste'),pl.col('heart_swing').sum().alias('heart_swing'),pl.col('shadow_swing').sum().alias('shadow_swing'),pl.col('chase_swing').sum().alias('chase_swing'),pl.col('waste_swing').sum().alias('waste_swing'),pl.col('heart_whiff').sum().alias('heart_whiff'),pl.col('shadow_whiff').sum().alias('shadow_whiff'),pl.col('chase_whiff').sum().alias('chase_whiff'),pl.col('waste_whiff').sum().alias('waste_whiff'),pl.col('tj_stuff_plus').sum().alias('tj_stuff_plus')])# Add calculated columns to the summary DataFramedf_summ = df_summ.with_columns([(pl.col('hits') / pl.col('ab')).alias('avg'),(pl.col('on_base') / pl.col('obp_pa')).alias('obp'),(pl.col('tb') / pl.col('ab')).alias('slg'),(pl.col('on_base') / pl.col('obp_pa') + pl.col('tb') / pl.col('ab')).alias('ops'),(pl.col('k') / pl.col('pa')).alias('k_percent'),(pl.col('bb') / pl.col('pa')).alias('bb_percent'),(pl.col('bb_minus_k') / pl.col('pa')).alias('bb_minus_k_percent'),(pl.col('bb') / pl.col('k')).alias('bb_over_k_percent'),(pl.col('csw') / pl.col('pitches')).alias('csw_percent'),(pl.col('sweet_spot') / pl.col('bip_div')).alias('sweet_spot_percent'),(pl.col('woba') / pl.col('woba_codes')).alias('woba_percent'),(pl.col('woba_contact') / pl.col('bip')).alias('woba_percent_contact'),(pl.col('hard_hit') / pl.col('bip_div')).alias('hard_hit_percent'),(pl.col('barrel') / pl.col('bip_div')).alias('barrel_percent'),(pl.col('zone_contact') / pl.col('zone_swing')).alias('zone_contact_percent'),(pl.col('zone_swing') / pl.col('in_zone')).alias('zone_swing_percent'),(pl.col('in_zone') / pl.col('pitches')).alias('zone_percent'),(pl.col('ozone_swing') / (pl.col('pitches') - pl.col('in_zone'))).alias('chase_percent'),(pl.col('ozone_contact') / pl.col('ozone_swing')).alias('chase_contact'),(pl.col('swings') / pl.col('pitches')).alias('swing_percent'),(pl.col('whiffs') / pl.col('swings')).alias('whiff_rate'),(pl.col('whiffs') / pl.col('pitches')).alias('swstr_rate'),(pl.col('ground_ball') / pl.col('bip')).alias('ground_ball_percent'),(pl.col('line_drive') / pl.col('bip')).alias('line_drive_percent'),(pl.col('fly_ball') / pl.col('bip')).alias('fly_ball_percent'),(pl.col('pop_up') / pl.col('bip')).alias('pop_up_percent'),(pl.col('heart') / pl.col('attack_zone')).alias('heart_zone_percent'),(pl.col('shadow') / pl.col('attack_zone')).alias('shadow_zone_percent'),(pl.col('chase') / pl.col('attack_zone')).alias('chase_zone_percent'),(pl.col('waste') / pl.col('attack_zone')).alias('waste_zone_percent'),(pl.col('heart_swing') / pl.col('heart')).alias('heart_zone_swing_percent'),(pl.col('shadow_swing') / pl.col('shadow')).alias('shadow_zone_swing_percent'),(pl.col('chase_swing') / pl.col('chase')).alias('chase_zone_swing_percent'),(pl.col('waste_swing') / pl.col('waste')).alias('waste_zone_swing_percent'),(pl.col('heart_whiff') / pl.col('heart_swing')).alias('heart_zone_whiff_percent'),(pl.col('shadow_whiff') / pl.col('shadow_swing')).alias('shadow_zone_whiff_percent'),(pl.col('chase_whiff') / pl.col('chase_swing')).alias('chase_zone_whiff_percent'),(pl.col('waste_whiff') / pl.col('waste_swing')).alias('waste_zone_whiff_percent'),(pl.col('xwoba') / pl.col('xwoba_codes')).alias('xwoba_percent'),(pl.col('xwoba_contact') / pl.col('bip')).alias('xwoba_percent_contact'),(pl.col('tj_stuff_plus') / pl.col('pitches')).alias('tj_stuff_plus_avg'),])return df_summ123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579import polars as plimport numpy as npimport joblibloaded_model = joblib.load('joblib_model/barrel_model.joblib')in_zone_model = joblib.load('joblib_model/in_zone_model_knn_20240410.joblib')attack_zone_model = joblib.load('joblib_model/model_attack_zone.joblib')xwoba_model = joblib.load('joblib_model/xwoba_model.joblib')px_model = joblib.load('joblib_model/linear_reg_model_x.joblib')pz_model = joblib.load('joblib_model/linear_reg_model_z.joblib')class df_update:def __init__(self):passdef update(self, df_clone: pl.DataFrame):df = df_clone.clone()# Assuming px_model is defined and df is your DataFramehit_codes = ['single','double','home_run', 'triple']ab_codes = ['single', 'strikeout', 'field_out','grounded_into_double_play', 'fielders_choice', 'force_out','double', 'field_error', 'home_run', 'triple','double_play','fielders_choice_out', 'strikeout_double_play','other_out','triple_play']obp_true_codes = ['single', 'walk','double','home_run', 'triple','hit_by_pitch', 'intent_walk']obp_codes = ['single', 'strikeout', 'walk', 'field_out','grounded_into_double_play', 'fielders_choice', 'force_out','double', 'sac_fly', 'field_error', 'home_run', 'triple','hit_by_pitch', 'double_play', 'intent_walk','fielders_choice_out', 'strikeout_double_play','sac_fly_double_play','other_out','triple_play']contact_codes = ['In play, no out','Foul', 'In play, out(s)','In play, run(s)','Foul Bunt']bip_codes = ['In play, no out', 'In play, run(s)','In play, out(s)']conditions_barrel = [df['launch_speed'].is_null(),(df['launch_speed'] * 1.5 - df['launch_angle'] >= 117) &(df['launch_speed'] + df['launch_angle'] >= 124) &(df['launch_speed'] >= 98) &(df['launch_angle'] >= 4) & (df['launch_angle'] <= 50)]choices_barrel = [False, True]conditions_tb = [(df['event_type'] == 'single'),(df['event_type'] == 'double'),(df['event_type'] == 'triple'),(df['event_type'] == 'home_run')]choices_tb = [1, 2, 3, 4]conditions_woba = [df['event_type'].is_in(['strikeout', 'field_out', 'sac_fly', 'force_out', 'grounded_into_double_play', 'fielders_choice', 'field_error', 'sac_bunt', 'double_play', 'fielders_choice_out', 'strikeout_double_play', 'sac_fly_double_play', 'other_out']),df['event_type'] == 'walk',df['event_type'] == 'hit_by_pitch',df['event_type'] == 'single',df['event_type'] == 'double',df['event_type'] == 'triple',df['event_type'] == 'home_run']choices_woba = [0, 0.689, 0.720, 0.881, 1.254, 1.589, 2.048]woba_codes = ['strikeout', 'field_out', 'single', 'walk', 'hit_by_pitch', 'double', 'sac_fly', 'force_out', 'home_run', 'grounded_into_double_play', 'fielders_choice', 'field_error', 'triple', 'sac_bunt', 'double_play', 'fielders_choice_out', 'strikeout_double_play', 'sac_fly_double_play', 'other_out']pitch_cat = {'FA': 'Fastball','FF': 'Fastball','FT': 'Fastball','FC': 'Fastball','FS': 'Off-Speed','FO': 'Off-Speed','SI': 'Fastball','ST': 'Breaking','SL': 'Breaking','CU': 'Breaking','KC': 'Breaking','SC': 'Off-Speed','GY': 'Off-Speed','SV': 'Breaking','CS': 'Breaking','CH': 'Off-Speed','KN': 'Off-Speed','EP': 'Breaking','UN': None,'IN': None,'PO': None,'AB': None,'AS': None,'NP': None}df = df.with_columns([pl.when(df['type_ab'].is_not_null()).then(1).otherwise(0).alias('pa'),pl.when(df['is_pitch']).then(1).otherwise(0).alias('pitches'),pl.when(df['sz_top'] == 0).then(None).otherwise(df['sz_top']).alias('sz_top'),pl.when(df['sz_bot'] == 0).then(None).otherwise(df['sz_bot']).alias('sz_bot'),pl.when(df['zone'] > 0).then(df['zone'] < 10).otherwise(None).alias('in_zone'),pl.Series(px_model.predict(df[['x']].fill_null(0).to_numpy())[:, 0]).alias('px_predict'),pl.Series(pz_model.predict(df[['y']].fill_null(0).to_numpy())[:, 0] + 3.2).alias('pz_predict'),pl.Series(in_zone_model.predict(df[['px','pz','sz_top','sz_bot']].fill_null(0).to_numpy())[:]).alias('in_zone_predict'),pl.Series(attack_zone_model.predict(df[['px','pz','sz_top','sz_bot']].fill_null(0).to_numpy())[:]).alias('attack_zone_predict'),pl.when(df['event_type'].is_in(hit_codes)).then(True).otherwise(False).alias('hits'),pl.when(df['event_type'].is_in(ab_codes)).then(True).otherwise(False).alias('ab'),pl.when(df['event_type'].is_in(obp_true_codes)).then(True).otherwise(False).alias('on_base'),pl.when(df['event_type'].is_in(obp_codes)).then(True).otherwise(False).alias('obp'),pl.when(df['play_description'].is_in(bip_codes)).then(True).otherwise(False).alias('bip'),pl.when(conditions_barrel[0]).then(choices_barrel[0]).when(conditions_barrel[1]).then(choices_barrel[1]).otherwise(None).alias('barrel'),pl.when(df['launch_angle'].is_null()).then(False).when((df['launch_angle'] >= 8) & (df['launch_angle'] <= 32)).then(True).otherwise(None).alias('sweet_spot'),pl.when(df['launch_speed'].is_null()).then(False).when(df['launch_speed'] >= 94.5).then(True).otherwise(None).alias('hard_hit'),pl.when(conditions_tb[0]).then(choices_tb[0]).when(conditions_tb[1]).then(choices_tb[1]).when(conditions_tb[2]).then(choices_tb[2]).when(conditions_tb[3]).then(choices_tb[3]).otherwise(None).alias('tb'),pl.when(conditions_woba[0]).then(choices_woba[0]).when(conditions_woba[1]).then(choices_woba[1]).when(conditions_woba[2]).then(choices_woba[2]).when(conditions_woba[3]).then(choices_woba[3]).when(conditions_woba[4]).then(choices_woba[4]).when(conditions_woba[5]).then(choices_woba[5]).when(conditions_woba[6]).then(choices_woba[6]).otherwise(None).alias('woba'),pl.when((df['play_code'] == 'S') | (df['play_code'] == 'W') | (df['play_code'] == 'T')).then(1).otherwise(0).alias('whiffs'),pl.when((df['play_code'] == 'S') | (df['play_code'] == 'W') | (df['play_code'] == 'T') | (df['play_code'] == 'C')).then(1).otherwise(0).alias('csw'),pl.when(pl.col('is_swing').cast(pl.Boolean)).then(1).otherwise(0).alias('swings'),pl.col('event_type').is_in(['strikeout','strikeout_double_play']).alias('k'),pl.col('event_type').is_in(['walk', 'intent_walk']).alias('bb'),pl.lit(None).alias('attack_zone'),pl.lit(None).alias('woba_pred'),pl.lit(None).alias('woba_pred_contact')])df = df.with_columns([pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('woba_codes'),pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('xwoba_codes'),pl.when((pl.col('tb') >= 0)).then(df['woba']).otherwise(None).alias('woba_contact'),pl.when(pl.col('px').is_null()).then(pl.col('px_predict')).otherwise(pl.col('px')).alias('px'),pl.when(pl.col('pz').is_null()).then(pl.col('pz_predict')).otherwise(pl.col('pz')).alias('pz'),pl.when(pl.col('in_zone').is_null()).then(pl.col('in_zone_predict')).otherwise(pl.col('in_zone')).alias('in_zone_final'),])df = df.with_columns([pl.when(df['launch_speed'].is_null()).then(None).otherwise(df['barrel']).alias('barrel'),pl.lit('average').alias('average'),pl.when(pl.col('in_zone_final') == False).then(True).otherwise(False).alias('out_zone'),pl.when((pl.col('in_zone_final') == True) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('zone_swing'),pl.when((pl.col('in_zone_final') == True) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('zone_contact'),pl.when((pl.col('in_zone_final') == False) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('ozone_swing'),pl.when((pl.col('in_zone_final') == False) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('ozone_contact'),pl.when(pl.col('event_type').str.contains('strikeout')).then(True).otherwise(False).alias('k'),pl.when(pl.col('event_type').is_in(['walk', 'intent_walk'])).then(True).otherwise(False).alias('bb'),pl.when(pl.col('attack_zone').is_null()).then(pl.col('attack_zone_predict')).otherwise(pl.col('attack_zone')).alias('attack_zone_final'),])df = df.with_columns([(df['k'].cast(pl.Float32) - df['bb'].cast(pl.Float32)).alias('k_minus_bb'),(df['bb'].cast(pl.Float32) - df['k'].cast(pl.Float32)).alias('bb_minus_k'),(df['launch_speed'] > 0).alias('bip_div'),(df['attack_zone_final'] == 0).alias('heart'),(df['attack_zone_final'] == 1).alias('shadow'),(df['attack_zone_final'] == 2).alias('chase'),(df['attack_zone_final'] == 3).alias('waste'),((df['attack_zone_final'] == 0) & (df['swings'] == 1)).alias('heart_swing'),((df['attack_zone_final'] == 1) & (df['swings'] == 1)).alias('shadow_swing'),((df['attack_zone_final'] == 2) & (df['swings'] == 1)).alias('chase_swing'),((df['attack_zone_final'] == 3) & (df['swings'] == 1)).alias('waste_swing'),((df['attack_zone_final'] == 0) & (df['whiffs'] == 1)).alias('heart_whiff'),((df['attack_zone_final'] == 1) & (df['whiffs'] == 1)).alias('shadow_whiff'),((df['attack_zone_final'] == 2) & (df['whiffs'] == 1)).alias('chase_whiff'),((df['attack_zone_final'] == 3) & (df['whiffs'] == 1)).alias('waste_whiff')])[0, 0.689, 0.720, 0.881, 1.254, 1.589, 2.048]df = df.with_columns([pl.Series([sum(x) for x in xwoba_model.predict_proba(df[['launch_angle', 'launch_speed']].fill_null(0).to_numpy()[:]) * ([0, 0.881, 1.254, 1.589, 2.048])]).alias('woba_pred_predict')])df = df.with_columns([pl.when(pl.col('event_type').is_in(['walk'])).then(0.689).when(pl.col('event_type').is_in(['hit_by_pitch'])).then(0.720).when(pl.col('event_type').is_in(['strikeout', 'strikeout_double_play'])).then(0).otherwise(pl.col('woba_pred_predict')).alias('woba_pred_predict')])df = df.with_columns([pl.when(pl.col('woba_codes').is_null()).then(None).otherwise(pl.col('woba_pred_predict')).alias('woba_pred'),pl.when(pl.col('bip')!=1).then(None).otherwise(pl.col('woba_pred_predict')).alias('woba_pred_contact'),])df = df.with_columns([pl.when(pl.col('trajectory').is_in(['bunt_popup'])).then(pl.lit('popup')).when(pl.col('trajectory').is_in(['bunt_grounder'])).then(pl.lit('ground_ball')).when(pl.col('trajectory').is_in(['bunt_line_drive'])).then(pl.lit('line_drive')).when(pl.col('trajectory').is_in([''])).then(pl.lit(None)).otherwise(pl.col('trajectory')).alias('trajectory')])# Create one-hot encoded columns for the trajectory columndummy_df = df.select(pl.col('trajectory')).to_dummies()# Rename the one-hot encoded columnsdummy_df = dummy_df.rename({'trajectory_fly_ball': 'trajectory_fly_ball','trajectory_ground_ball': 'trajectory_ground_ball','trajectory_line_drive': 'trajectory_line_drive','trajectory_popup': 'trajectory_popup'})# Ensure the columns are present in the DataFramefor col in ['trajectory_fly_ball', 'trajectory_ground_ball', 'trajectory_line_drive', 'trajectory_popup']:if col not in dummy_df.columns:dummy_df = dummy_df.with_columns(pl.lit(0).alias(col))# Join the one-hot encoded columns back to the original DataFramedf = df.hstack(dummy_df)# Check if 'trajectory_null' column exists and drop itif 'trajectory_null' in df.columns:df = df.drop('trajectory_null')pitch_cat = {'FA': None,'FF': 'Fastball','FT': 'Fastball','FC': 'Fastball','FS': 'Off-Speed','FO': 'Off-Speed','SI': 'Fastball','ST': 'Breaking','SL': 'Breaking','CU': 'Breaking','KC': 'Breaking','SC': 'Off-Speed','GY': 'Off-Speed','SV': 'Breaking','CS': 'Breaking','CH': 'Off-Speed','KN': 'Off-Speed','EP': 'Breaking','UN': None,'IN': None,'PO': None,'AB': None,'AS': None,'NP': None}df = df.with_columns(df["pitch_type"].map_elements(lambda x: pitch_cat.get(x, x)).alias("pitch_group"))df = df.with_columns([(-(pl.col('vy0')**2 - (2 * pl.col('ay') * (pl.col('y0') - 17/12)))**0.5).alias('vy_f'),])df = df.with_columns([((pl.col('vy_f') - pl.col('vy0')) / pl.col('ay')).alias('t'),])df = df.with_columns([(pl.col('vz0') + (pl.col('az') * pl.col('t'))).alias('vz_f'),(pl.col('vx0') + (pl.col('ax') * pl.col('t'))).alias('vx_f')])df = df.with_columns([(-np.arctan(pl.col('vz_f') / pl.col('vy_f')) * (180 / np.pi)).alias('vaa'),(-np.arctan(pl.col('vx_f') / pl.col('vy_f')) * (180 / np.pi)).alias('haa')])# Mirror horizontal break for left-handed pitchersdf = df.with_columns(pl.when(pl.col('pitcher_hand') == 'L').then(-pl.col('ax')).otherwise(pl.col('ax')).alias('ax'))# Mirror horizontal break for left-handed pitchersdf = df.with_columns(pl.when(pl.col('pitcher_hand') == 'L').then(-pl.col('hb')).otherwise(pl.col('hb')).alias('hb'))# Mirror horizontal release point for left-handed pitchersdf = df.with_columns(pl.when(pl.col('pitcher_hand') == 'L').then(pl.col('x0')).otherwise(-pl.col('x0')).alias('x0'))df = df.with_columns([pl.when(df['swings'].is_null()).then(None).otherwise(df['swings']).alias('is_swing'),pl.when(df['bip'].is_null()).then(None).otherwise(df['bip']).alias('is_bip')])return df# Assuming df is your Polars DataFramedef update_summary(self, df: pl.DataFrame, pitcher: bool = True) -> pl.DataFrame:"""Update summary statistics for pitchers or batters.Parameters:df (pl.DataFrame): The input Polars DataFrame containing player statistics.pitcher (bool): A flag indicating whether to calculate statistics for pitchers (True) or batters (False).Returns:pl.DataFrame: A Polars DataFrame with aggregated and calculated summary statistics."""# Determine the position based on the pitcher flagif pitcher:position = 'pitcher'else:position = 'batter'# Group by position_id and position_name, then aggregate various statisticsdf_summ = df.group_by([f'{position}_id', f'{position}_name']).agg([pl.col('pa').sum().alias('pa'),pl.col('ab').sum().alias('ab'),pl.col('obp').sum().alias('obp_pa'),pl.col('hits').sum().alias('hits'),pl.col('on_base').sum().alias('on_base'),pl.col('k').sum().alias('k'),pl.col('bb').sum().alias('bb'),pl.col('bb_minus_k').sum().alias('bb_minus_k'),pl.col('csw').sum().alias('csw'),pl.col('bip').sum().alias('bip'),pl.col('bip_div').sum().alias('bip_div'),pl.col('tb').sum().alias('tb'),pl.col('woba').sum().alias('woba'),pl.col('woba_contact').sum().alias('woba_contact'),pl.col('woba_pred').sum().alias('xwoba'),pl.col('woba_pred_contact').sum().alias('xwoba_contact'),pl.col('woba_codes').sum().alias('woba_codes'),pl.col('xwoba_codes').sum().alias('xwoba_codes'),pl.col('hard_hit').sum().alias('hard_hit'),pl.col('barrel').sum().alias('barrel'),pl.col('sweet_spot').sum().alias('sweet_spot'),pl.col('launch_speed').max().alias('max_launch_speed'),pl.col('launch_speed').quantile(0.90).alias('launch_speed_90'),pl.col('launch_speed').mean().alias('launch_speed'),pl.col('launch_angle').mean().alias('launch_angle'),pl.col('is_pitch').sum().alias('pitches'),pl.col('swings').sum().alias('swings'),pl.col('in_zone').sum().alias('in_zone'),pl.col('out_zone').sum().alias('out_zone'),pl.col('whiffs').sum().alias('whiffs'),pl.col('zone_swing').sum().alias('zone_swing'),pl.col('zone_contact').sum().alias('zone_contact'),pl.col('ozone_swing').sum().alias('ozone_swing'),pl.col('ozone_contact').sum().alias('ozone_contact'),pl.col('trajectory_ground_ball').sum().alias('ground_ball'),pl.col('trajectory_line_drive').sum().alias('line_drive'),pl.col('trajectory_fly_ball').sum().alias('fly_ball'),pl.col('trajectory_popup').sum().alias('pop_up'),pl.col('attack_zone').count().alias('attack_zone'),pl.col('heart').sum().alias('heart'),pl.col('shadow').sum().alias('shadow'),pl.col('chase').sum().alias('chase'),pl.col('waste').sum().alias('waste'),pl.col('heart_swing').sum().alias('heart_swing'),pl.col('shadow_swing').sum().alias('shadow_swing'),pl.col('chase_swing').sum().alias('chase_swing'),pl.col('waste_swing').sum().alias('waste_swing'),pl.col('heart_whiff').sum().alias('heart_whiff'),pl.col('shadow_whiff').sum().alias('shadow_whiff'),pl.col('chase_whiff').sum().alias('chase_whiff'),pl.col('waste_whiff').sum().alias('waste_whiff')])# Add calculated columns to the summary DataFramedf_summ = df_summ.with_columns([(pl.col('hits') / pl.col('ab')).alias('avg'),(pl.col('on_base') / pl.col('obp_pa')).alias('obp'),(pl.col('tb') / pl.col('ab')).alias('slg'),(pl.col('on_base') / pl.col('obp_pa') + pl.col('tb') / pl.col('ab')).alias('ops'),(pl.col('k') / pl.col('pa')).alias('k_percent'),(pl.col('bb') / pl.col('pa')).alias('bb_percent'),(pl.col('bb_minus_k') / pl.col('pa')).alias('bb_minus_k_percent'),(pl.col('bb') / pl.col('k')).alias('bb_over_k_percent'),(pl.col('csw') / pl.col('pitches')).alias('csw_percent'),(pl.col('sweet_spot') / pl.col('bip_div')).alias('sweet_spot_percent'),(pl.col('woba') / pl.col('woba_codes')).alias('woba_percent'),(pl.col('woba_contact') / pl.col('bip')).alias('woba_percent_contact'),(pl.col('hard_hit') / pl.col('bip_div')).alias('hard_hit_percent'),(pl.col('barrel') / pl.col('bip_div')).alias('barrel_percent'),(pl.col('zone_contact') / pl.col('zone_swing')).alias('zone_contact_percent'),(pl.col('zone_swing') / pl.col('in_zone')).alias('zone_swing_percent'),(pl.col('in_zone') / pl.col('pitches')).alias('zone_percent'),(pl.col('ozone_swing') / (pl.col('pitches') - pl.col('in_zone'))).alias('chase_percent'),(pl.col('ozone_contact') / pl.col('ozone_swing')).alias('chase_contact'),(pl.col('swings') / pl.col('pitches')).alias('swing_percent'),(pl.col('whiffs') / pl.col('swings')).alias('whiff_rate'),(pl.col('whiffs') / pl.col('pitches')).alias('swstr_rate'),(pl.col('ground_ball') / pl.col('bip')).alias('ground_ball_percent'),(pl.col('line_drive') / pl.col('bip')).alias('line_drive_percent'),(pl.col('fly_ball') / pl.col('bip')).alias('fly_ball_percent'),(pl.col('pop_up') / pl.col('bip')).alias('pop_up_percent'),(pl.col('heart') / pl.col('attack_zone')).alias('heart_zone_percent'),(pl.col('shadow') / pl.col('attack_zone')).alias('shadow_zone_percent'),(pl.col('chase') / pl.col('attack_zone')).alias('chase_zone_percent'),(pl.col('waste') / pl.col('attack_zone')).alias('waste_zone_percent'),(pl.col('heart_swing') / pl.col('heart')).alias('heart_zone_swing_percent'),(pl.col('shadow_swing') / pl.col('shadow')).alias('shadow_zone_swing_percent'),(pl.col('chase_swing') / pl.col('chase')).alias('chase_zone_swing_percent'),(pl.col('waste_swing') / pl.col('waste')).alias('waste_zone_swing_percent'),(pl.col('heart_whiff') / pl.col('heart_swing')).alias('heart_zone_whiff_percent'),(pl.col('shadow_whiff') / pl.col('shadow_swing')).alias('shadow_zone_whiff_percent'),(pl.col('chase_whiff') / pl.col('chase_swing')).alias('chase_zone_whiff_percent'),(pl.col('waste_whiff') / pl.col('waste_swing')).alias('waste_zone_whiff_percent'),(pl.col('xwoba') / pl.col('xwoba_codes')).alias('xwoba_percent'),(pl.col('xwoba_contact') / pl.col('bip')).alias('xwoba_percent_contact')])return df_summ# Assuming df is your Polars DataFramedef update_summary_select(self, df: pl.DataFrame, selection: list) -> pl.DataFrame:"""Update summary statistics for pitchers or batters.Parameters:df (pl.DataFrame): The input Polars DataFrame containing player statistics.pitcher (bool): A flag indicating whether to calculate statistics for pitchers (True) or batters (False).Returns:pl.DataFrame: A Polars DataFrame with aggregated and calculated summary statistics."""# Group by position_id and position_name, then aggregate various statisticsdf_summ = df.group_by(selection).agg([pl.col('pa').sum().alias('pa'),pl.col('ab').sum().alias('ab'),pl.col('obp').sum().alias('obp_pa'),pl.col('hits').sum().alias('hits'),pl.col('on_base').sum().alias('on_base'),pl.col('k').sum().alias('k'),pl.col('bb').sum().alias('bb'),pl.col('bb_minus_k').sum().alias('bb_minus_k'),pl.col('k_minus_bb').sum().alias('k_minus_bb'),pl.col('csw').sum().alias('csw'),pl.col('bip').sum().alias('bip'),pl.col('bip_div').sum().alias('bip_div'),pl.col('tb').sum().alias('tb'),pl.col('woba').sum().alias('woba'),pl.col('woba_contact').sum().alias('woba_contact'),pl.col('woba_pred').sum().alias('xwoba'),pl.col('woba_pred_contact').sum().alias('xwoba_contact'),pl.col('woba_codes').sum().alias('woba_codes'),pl.col('xwoba_codes').sum().alias('xwoba_codes'),pl.col('hard_hit').sum().alias('hard_hit'),pl.col('barrel').sum().alias('barrel'),pl.col('sweet_spot').sum().alias('sweet_spot'),pl.col('launch_speed').max().alias('max_launch_speed'),pl.col('launch_speed').quantile(0.90).alias('launch_speed_90'),pl.col('launch_speed').mean().alias('launch_speed'),pl.col('launch_angle').mean().alias('launch_angle'),pl.col('is_pitch').sum().alias('pitches'),pl.col('swings').sum().alias('swings'),pl.col('in_zone').sum().alias('in_zone'),pl.col('out_zone').sum().alias('out_zone'),pl.col('whiffs').sum().alias('whiffs'),pl.col('zone_swing').sum().alias('zone_swing'),pl.col('zone_contact').sum().alias('zone_contact'),pl.col('ozone_swing').sum().alias('ozone_swing'),pl.col('ozone_contact').sum().alias('ozone_contact'),pl.col('trajectory_ground_ball').sum().alias('ground_ball'),pl.col('trajectory_line_drive').sum().alias('line_drive'),pl.col('trajectory_fly_ball').sum().alias('fly_ball'),pl.col('trajectory_popup').sum().alias('pop_up'),pl.col('attack_zone').count().alias('attack_zone'),pl.col('heart').sum().alias('heart'),pl.col('shadow').sum().alias('shadow'),pl.col('chase').sum().alias('chase'),pl.col('waste').sum().alias('waste'),pl.col('heart_swing').sum().alias('heart_swing'),pl.col('shadow_swing').sum().alias('shadow_swing'),pl.col('chase_swing').sum().alias('chase_swing'),pl.col('waste_swing').sum().alias('waste_swing'),pl.col('heart_whiff').sum().alias('heart_whiff'),pl.col('shadow_whiff').sum().alias('shadow_whiff'),pl.col('chase_whiff').sum().alias('chase_whiff'),pl.col('waste_whiff').sum().alias('waste_whiff'),pl.col('tj_stuff_plus').sum().alias('tj_stuff_plus'),pl.col('start_speed').sum(),pl.col('vb').sum(),pl.col('ivb').sum(),pl.col('hb').sum(),pl.col('x0').sum(),pl.col('z0').sum(),pl.col('vaa').sum(),pl.col('haa').sum(),pl.col('spin_rate').sum(),pl.col('extension').sum(),])# Add calculated columns to the summary DataFramedf_summ = df_summ.with_columns([(pl.col('hits') / pl.col('ab')).alias('avg'),(pl.col('on_base') / pl.col('obp_pa')).alias('obp'),(pl.col('tb') / pl.col('ab')).alias('slg'),(pl.col('on_base') / pl.col('obp_pa') + pl.col('tb') / pl.col('ab')).alias('ops'),(pl.col('k') / pl.col('pa')).alias('k_percent'),(pl.col('bb') / pl.col('pa')).alias('bb_percent'),(pl.col('bb_minus_k') / pl.col('pa')).alias('bb_minus_k_percent'),(pl.col('k_minus_bb') / pl.col('pa')).alias('k_minus_bb_percent'),(pl.col('bb') / pl.col('k')).alias('bb_over_k_percent'),(pl.col('csw') / pl.col('pitches')).alias('csw_percent'),(pl.col('sweet_spot') / pl.col('bip_div')).alias('sweet_spot_percent'),(pl.col('woba') / pl.col('woba_codes')).alias('woba_percent'),(pl.col('woba_contact') / pl.col('bip')).alias('woba_percent_contact'),(pl.col('hard_hit') / pl.col('bip_div')).alias('hard_hit_percent'),(pl.col('barrel') / pl.col('bip_div')).alias('barrel_percent'),(pl.col('zone_contact') / pl.col('zone_swing')).alias('zone_contact_percent'),(pl.col('zone_swing') / pl.col('in_zone')).alias('zone_swing_percent'),(pl.col('in_zone') / pl.col('pitches')).alias('zone_percent'),(pl.col('ozone_swing') / (pl.col('pitches') - pl.col('in_zone'))).alias('chase_percent'),(pl.col('ozone_contact') / pl.col('ozone_swing')).alias('chase_contact'),(pl.col('swings') / pl.col('pitches')).alias('swing_percent'),(pl.col('whiffs') / pl.col('swings')).alias('whiff_rate'),(pl.col('whiffs') / pl.col('pitches')).alias('swstr_rate'),(pl.col('ground_ball') / pl.col('bip')).alias('ground_ball_percent'),(pl.col('line_drive') / pl.col('bip')).alias('line_drive_percent'),(pl.col('fly_ball') / pl.col('bip')).alias('fly_ball_percent'),(pl.col('pop_up') / pl.col('bip')).alias('pop_up_percent'),(pl.col('heart') / pl.col('attack_zone')).alias('heart_zone_percent'),(pl.col('shadow') / pl.col('attack_zone')).alias('shadow_zone_percent'),(pl.col('chase') / pl.col('attack_zone')).alias('chase_zone_percent'),(pl.col('waste') / pl.col('attack_zone')).alias('waste_zone_percent'),(pl.col('heart_swing') / pl.col('heart')).alias('heart_zone_swing_percent'),(pl.col('shadow_swing') / pl.col('shadow')).alias('shadow_zone_swing_percent'),(pl.col('chase_swing') / pl.col('chase')).alias('chase_zone_swing_percent'),(pl.col('waste_swing') / pl.col('waste')).alias('waste_zone_swing_percent'),(pl.col('heart_whiff') / pl.col('heart_swing')).alias('heart_zone_whiff_percent'),(pl.col('shadow_whiff') / pl.col('shadow_swing')).alias('shadow_zone_whiff_percent'),(pl.col('chase_whiff') / pl.col('chase_swing')).alias('chase_zone_whiff_percent'),(pl.col('waste_whiff') / pl.col('waste_swing')).alias('waste_zone_whiff_percent'),(pl.col('xwoba') / pl.col('xwoba_codes')).alias('xwoba_percent'),(pl.col('xwoba_contact') / pl.col('bip')).alias('xwoba_percent_contact'),(pl.col('tj_stuff_plus') / pl.col('pitches')).alias('tj_stuff_plus_avg'),(pl.col('start_speed')/ pl.col('pitches')).alias('start_speed_avg'),(pl.col('vb')/ pl.col('pitches')).alias('vb_avg'),(pl.col('ivb')/ pl.col('pitches')).alias('ivb_avg'),(pl.col('hb')/ pl.col('pitches')).alias('hb_avg'),(pl.col('x0')/ pl.col('pitches')).alias('x0_avg'),(pl.col('z0')/ pl.col('pitches')).alias('z0_avg'),(pl.col('vaa')/ pl.col('pitches')).alias('vaa_avg'),(pl.col('haa')/ pl.col('pitches')).alias('haa_avg'),(pl.col('spin_rate')/ pl.col('pitches')).alias('spin_rate_avg'),(pl.col('extension')/ pl.col('pitches')).alias('extension_avg'),])return df_summ
661 unmodified lines6626636646656666676686696706716726736746756766776786795 unmodified lines6856866876886896906916921 unmodified line69469569669769869970024 unmodified lines7257267277287297307313 unmodified lines7357367377387397407418 unmodified lines7507517527537547558 unmodified lines76476576676776876977077177277377477577677777877978078178278 unmodified lines861862863864865866867868869661 unmodified linesformat_cells(['count_percent', 'zone_percent', 'chase_percent', 'whiff_percent'], '{:,.1%}')format_cells(['tj_stuff_plus', 'pitch_grade', 'spin_rate'], '{:,.0f}')# Create legend for pitch typesitems_in_order = (df.sort("pitch_count", descending=True)['pitch_type'].unique(maintain_order=True).to_numpy())colour_pitches = [dict_colour[x] for x in items_in_order]label = [dict_pitch[x] for x in items_in_order]handles = [plt.scatter([], [], color=color, marker='o', s=100) for color in colour_pitches]if len(label) > 5:ax.legend(handles, label, bbox_to_anchor=(0.1, 0.81, 0.8, 0.14), ncol=5,fancybox=True, loc='lower center', fontsize=16, framealpha=1.0, markerscale=1.7, prop={'family': 'calibi', 'size': 16})else:ax.legend(handles, label, bbox_to_anchor=(0.1, 0.81, 0.8, 0.14), ncol=5,fancybox=True, loc='lower center', fontsize=20, framealpha=1.0, markerscale=2, prop={'family': 'calibi', 'size': 20})ax.axis('off')def plot_footer(ax: plt.Axes):"""5 unmodified linesThe axis to add the footer text to."""# Add footer textax.text(0, 1, 'By: @TJStats', ha='left', va='top', fontsize=24)ax.text(0.5, 0.25,'''Colour Coding Compares to League Average By PitchtjStuff+ calculates the Expected Run Value (xRV) of a pitch regardless of type1 unmodified linePitch Grade scales tjStuff+ to the traditional 20-80 Scouting Scale for a given pitch type''',ha='center', va='bottom', fontsize=12)ax.text(1, 1, 'Data: MLB, Fangraphs\nImages: MLB, ESPN', ha='right', va='top', fontsize=24)ax.axis('off')# Function to get an image from a URL and display it on the given axis24 unmodified linesimg = Image.open(BytesIO(response.content))# Display the image on the axisax.set_xlim(0, 1.3)ax.set_ylim(0, 1)ax.imshow(img, extent=[0, 1, 0, 1] if sport_id == 1 else [1/6, 5/6, 0, 1], origin='upper')except PIL.UnidentifiedImageError:3 unmodified lines# Turn off the axisax.axis('off')def player_bio(pitcher_id: str, ax: plt.Axes, sport_id: int, year_input: int):"""Display the player's bio information on the given axis.8 unmodified linesyear_input : intThe season year."""# Construct the URL to fetch player dataurl = f"https://statsapi.mlb.com/api/v1/people?personIds={pitcher_id}&hydrate=currentTeam"8 unmodified linesweight = data['people'][0]['weight']# Display the player's name, handedness, age, height, and weight on the axisax.text(0.5, 1, f'{player_name}', va='top', ha='center', fontsize=56)ax.text(0.5, 0.7, f'{pitcher_hand}HP, Age: {age}, {height}/{weight}', va='top', ha='center', fontsize=30)ax.text(0.5, 0.45, f'Season Pitching Summary', va='top', ha='center', fontsize=40)# Make API call to retrieve sports informationresponse = requests.get(url='https://statsapi.mlb.com/api/v1/sports').json()# Convert the JSON response into a Polars DataFramedf_sport_id = pl.DataFrame(response['sports'])abb = df_sport_id.filter(pl.col('id') == sport_id)['abbreviation'][0]# Display the season and sport abbreviationax.text(0.5, 0.20, f'{year_input} {abb} Season', va='top', ha='center', fontsize=30, fontstyle='italic')# Turn off the axisax.axis('off')78 unmodified linesimg = Image.open(BytesIO(response.content))# Display the image on the axisax.set_xlim(0, 1.3)ax.set_ylim(0, 1)ax.imshow(img, extent=[0.3, 1.3, 0, 1], origin='upper')# Turn off the axisax.axis('off')661 unmodified lines6626636646656666676686696706716726736746756766776786796806816825 unmodified lines6886896906916926936946951 unmodified line69769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672724 unmodified lines7527537547557567577583 unmodified lines7627637647657667677687697707717727737747757767777787798 unmodified lines7887897907917927937947957968 unmodified lines80580680780880981081181281381481581681781881982082182282382482582682782878 unmodified lines907908909910911912913914915661 unmodified linesformat_cells(['count_percent', 'zone_percent', 'chase_percent', 'whiff_percent'], '{:,.1%}')format_cells(['tj_stuff_plus', 'pitch_grade', 'spin_rate'], '{:,.0f}')# # Create legend for pitch types# items_in_order = (df.sort("pitch_count", descending=True)['pitch_type'].unique(maintain_order=True).to_numpy())# colour_pitches = [dict_colour[x] for x in items_in_order]# label = [dict_pitch[x] for x in items_in_order]# handles = [plt.scatter([], [], color=color, marker='o', s=100) for color in colour_pitches]# if len(label) > 5:# ax.legend(handles, label, bbox_to_anchor=(0.1, 0.81, 0.8, 0.14), ncol=5,# fancybox=True, loc='lower center', fontsize=16, framealpha=1.0, markerscale=1.7, prop={'family': 'calibi', 'size': 16})# else:# ax.legend(handles, label, bbox_to_anchor=(0.1, 0.81, 0.8, 0.14), ncol=5,# fancybox=True, loc='lower center', fontsize=20, framealpha=1.0, markerscale=2, prop={'family': 'calibi', 'size': 20})ax.axis('off')# ax.set_title(f'{df["pitcher_name"][0]}', fontdict=font_properties_titles)# ax.text(x=0.5,y=0.90,s=f'{df["pitcher_name"][0]}',# fontsize=30, ha='center', va='bottom',)def plot_footer(ax: plt.Axes):"""5 unmodified linesThe axis to add the footer text to."""# Add footer textax.text(0, 1, 'By: Thomas Nestico\n @TJStats', ha='left', va='top', fontsize=24)ax.text(0.5, 0.15,'''Colour Coding Compares to League Average By PitchtjStuff+ calculates the Expected Run Value (xRV) of a pitch regardless of type1 unmodified linePitch Grade scales tjStuff+ to the traditional 20-80 Scouting Scale for a given pitch type''',ha='center', va='bottom', fontsize=12)ax.text(1, 1, 'Data: MLB\nImages: MLB, ESPN', ha='right', va='top', fontsize=24)ax.axis('off')def plot_footer_break(ax: plt.Axes):"""Add footer text to the plot.Parameters----------ax : plt.AxesThe axis to add the footer text to."""# Add footer textax.text(0, 0.25, 'By: Thomas Nestico\n @TJStats', ha='left', va='bottom', fontsize=24)# ax.text(0.5, 0.15,# '''# Colour Coding Compares to League Average By Pitch# tjStuff+ calculates the Expected Run Value (xRV) of a pitch regardless of type# tjStuff+ is normally distributed, where 100 is the mean and Standard Deviation is 10# Pitch Grade scales tjStuff+ to the traditional 20-80 Scouting Scale for a given pitch type# ''',# ha='center', va='bottom', fontsize=12)ax.text(1, 0.25, 'Data: MLB\nImages: MLB, ESPN', ha='right', va='bottom', fontsize=24)ax.axis('off')# Function to get an image from a URL and display it on the given axis24 unmodified linesimg = Image.open(BytesIO(response.content))# Display the image on the axisax.set_xlim(0, 1)ax.set_ylim(0, 1)ax.imshow(img, extent=[0, 1, 0, 1] if sport_id == 1 else [1/6, 5/6, 0, 1], origin='upper')except PIL.UnidentifiedImageError:3 unmodified lines# Turn off the axisax.axis('off')splits_title = {'all':'','left':' vs LHH','right':' vs RHH',}type_dict = {'R':'Regular Season','S':'Spring','P':'Playoffs' }def player_bio(pitcher_id: str, ax: plt.Axes, sport_id: int,game_type: str, year_input: int,split: str,df: pl.DataFrame):"""Display the player's bio information on the given axis.8 unmodified linesyear_input : intThe season year."""start_date = df['game_date'][0]end_date = df['game_date'][-1]# Construct the URL to fetch player dataurl = f"https://statsapi.mlb.com/api/v1/people?personIds={pitcher_id}&hydrate=currentTeam"8 unmodified linesweight = data['people'][0]['weight']# Display the player's name, handedness, age, height, and weight on the axisax.text(0.5, 1, f'{player_name}', va='top', ha='center', fontsize=36)ax.text(0.5, 0.68, f'{pitcher_hand}HP, Age: {age}, {height}/{weight}', va='top', ha='center', fontsize=24)# Convert the JSON response into a Polars DataFrame# Make API call to retrieve sports informationresponse = requests.get(url='https://statsapi.mlb.com/api/v1/sports').json()df_sport_id = pl.DataFrame(response['sports'])abb = df_sport_id.filter(pl.col('id') == sport_id)['abbreviation'][0]# title = f'{df["game_date"][0]} vs {df["batter_team"][0]} ({type_dict[game_type[0]]}){split_title[split]}'ax.text(0.5, 0.45, f'{year_input} {abb} {type_dict[game_type]}', va='top', ha='center', fontsize=24)# Display the season and sport abbreviationax.text(0.5, 0.20, f'{start_date} to {end_date}{splits_title[split]}', va='top', ha='center', fontsize=24, fontstyle='italic')# Turn off the axisax.axis('off')78 unmodified linesimg = Image.open(BytesIO(response.content))# Display the image on the axisax.set_xlim(0, 1)ax.set_ylim(0, 1)ax.imshow(img, extent=[0, 1, 0, 1], origin='upper')# Turn off the axisax.axis('off')
api_scraper.py+25
app.py+488-400
data/data_a_2024.parquetAdded+3
data/data_aaa_2024.parquetAdded+3
data/data_mlb_2024.parquetAdded+3
functions/__pycache__/df_update.cpython-39.pyc
functions/__pycache__/pitch_summary_functions.cpython-39.pyc
functions/df_update.py+578-474
functions/pitch_summary_functions.py+70-24
stuff_model/__pycache__/feature_engineering.cpython-39.pyc