nesticot commited on
Commit
4cfc4c8
·
verified ·
1 Parent(s): f2e987c

Update functions/df_update.py

Browse files
Files changed (1) hide show
  1. functions/df_update.py +631 -631
functions/df_update.py CHANGED
@@ -1,632 +1,632 @@
1
- import polars as pl
2
- import numpy as np
3
- import joblib
4
-
5
- loaded_model = joblib.load('joblib_model/barrel_model.joblib')
6
- in_zone_model = joblib.load('joblib_model/in_zone_model_knn_20240410.joblib')
7
- attack_zone_model = joblib.load('joblib_model/model_attack_zone.joblib')
8
- xwoba_model = joblib.load('joblib_model/xwoba_model.joblib')
9
- px_model = joblib.load('joblib_model/linear_reg_model_x.joblib')
10
- pz_model = joblib.load('joblib_model/linear_reg_model_z.joblib')
11
-
12
-
13
- class df_update:
14
- def __init__(self):
15
- pass
16
-
17
- def update(self, df_clone: pl.DataFrame):
18
-
19
- df = df_clone.clone()
20
- # Assuming px_model is defined and df is your DataFrame
21
- hit_codes = ['single',
22
- 'double','home_run', 'triple']
23
-
24
- ab_codes = ['single', 'strikeout', 'field_out',
25
- 'grounded_into_double_play', 'fielders_choice', 'force_out',
26
- 'double', 'field_error', 'home_run', 'triple',
27
- 'double_play',
28
- 'fielders_choice_out', 'strikeout_double_play',
29
- 'other_out','triple_play']
30
-
31
-
32
- obp_true_codes = ['single', 'walk',
33
- 'double','home_run', 'triple',
34
- 'hit_by_pitch', 'intent_walk']
35
-
36
- obp_codes = ['single', 'strikeout', 'walk', 'field_out',
37
- 'grounded_into_double_play', 'fielders_choice', 'force_out',
38
- 'double', 'sac_fly', 'field_error', 'home_run', 'triple',
39
- 'hit_by_pitch', 'double_play', 'intent_walk',
40
- 'fielders_choice_out', 'strikeout_double_play',
41
- 'sac_fly_double_play',
42
- 'other_out','triple_play']
43
-
44
-
45
- contact_codes = ['In play, no out',
46
- 'Foul', 'In play, out(s)',
47
- 'In play, run(s)',
48
- 'Foul Bunt']
49
-
50
- bip_codes = ['In play, no out', 'In play, run(s)','In play, out(s)']
51
-
52
-
53
- conditions_barrel = [
54
- df['launch_speed'].is_null(),
55
- (df['launch_speed'] * 1.5 - df['launch_angle'] >= 117) &
56
- (df['launch_speed'] + df['launch_angle'] >= 124) &
57
- (df['launch_speed'] >= 98) &
58
- (df['launch_angle'] >= 4) & (df['launch_angle'] <= 50)
59
- ]
60
- choices_barrel = [False, True]
61
-
62
- conditions_tb = [
63
- (df['event_type'] == 'single'),
64
- (df['event_type'] == 'double'),
65
- (df['event_type'] == 'triple'),
66
- (df['event_type'] == 'home_run')
67
- ]
68
- choices_tb = [1, 2, 3, 4]
69
-
70
-
71
- conditions_woba = [
72
- 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']),
73
- df['event_type'] == 'walk',
74
- df['event_type'] == 'hit_by_pitch',
75
- df['event_type'] == 'single',
76
- df['event_type'] == 'double',
77
- df['event_type'] == 'triple',
78
- df['event_type'] == 'home_run'
79
- ]
80
- choices_woba = [0, 0.689, 0.720, 0.881, 1.254, 1.589, 2.048]
81
-
82
- 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']
83
-
84
- pitch_cat = {'FA': 'Fastball',
85
- 'FF': 'Fastball',
86
- 'FT': 'Fastball',
87
- 'FC': 'Fastball',
88
- 'FS': 'Off-Speed',
89
- 'FO': 'Off-Speed',
90
- 'SI': 'Fastball',
91
- 'ST': 'Breaking',
92
- 'SL': 'Breaking',
93
- 'CU': 'Breaking',
94
- 'KC': 'Breaking',
95
- 'SC': 'Off-Speed',
96
- 'GY': 'Off-Speed',
97
- 'SV': 'Breaking',
98
- 'CS': 'Breaking',
99
- 'CH': 'Off-Speed',
100
- 'KN': 'Off-Speed',
101
- 'EP': 'Breaking',
102
- 'UN': None,
103
- 'IN': None,
104
- 'PO': None,
105
- 'AB': None,
106
- 'AS': None,
107
- 'NP': None}
108
-
109
-
110
- df = df.with_columns([
111
- pl.when(df['type_ab'].is_not_null()).then(1).otherwise(0).alias('pa'),
112
- pl.when(df['is_pitch']).then(1).otherwise(0).alias('pitches'),
113
- pl.when(df['sz_top'] == 0).then(None).otherwise(df['sz_top']).alias('sz_top'),
114
- pl.when(df['sz_bot'] == 0).then(None).otherwise(df['sz_bot']).alias('sz_bot'),
115
- pl.when(df['zone'] > 0).then(df['zone'] < 10).otherwise(None).alias('in_zone'),
116
- pl.Series(px_model.predict(df[['x']].fill_null(0).to_numpy())[:, 0]).alias('px_predict'),
117
- pl.Series(pz_model.predict(df[['y']].fill_null(0).to_numpy())[:, 0] + 3.2).alias('pz_predict'),
118
- pl.Series(in_zone_model.predict(df[['px','pz','sz_top','sz_bot']].fill_null(0).to_numpy())[:]).alias('in_zone_predict'),
119
- pl.Series(attack_zone_model.predict(df[['px','pz','sz_top','sz_bot']].fill_null(0).to_numpy())[:]).alias('attack_zone_predict'),
120
- pl.when(df['event_type'].is_in(hit_codes)).then(True).otherwise(False).alias('hits'),
121
- pl.when(df['event_type'].is_in(ab_codes)).then(True).otherwise(False).alias('ab'),
122
- pl.when(df['event_type'].is_in(obp_true_codes)).then(True).otherwise(False).alias('on_base'),
123
- pl.when(df['event_type'].is_in(obp_codes)).then(True).otherwise(False).alias('obp'),
124
- pl.when(df['play_description'].is_in(bip_codes)).then(True).otherwise(False).alias('bip'),
125
- pl.when(conditions_barrel[0]).then(choices_barrel[0]).when(conditions_barrel[1]).then(choices_barrel[1]).otherwise(None).alias('barrel'),
126
- 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'),
127
- pl.when(df['launch_speed'].is_null()).then(False).when(df['launch_speed'] >= 94.5).then(True).otherwise(None).alias('hard_hit'),
128
- 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'),
129
- 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'),
130
- pl.when((df['play_code'] == 'S') | (df['play_code'] == 'W') | (df['play_code'] == 'T')).then(1).otherwise(0).alias('whiffs'),
131
- pl.when((df['play_code'] == 'S') | (df['play_code'] == 'W') | (df['play_code'] == 'T') | (df['play_code'] == 'C')).then(1).otherwise(0).alias('csw'),
132
- pl.when(pl.col('is_swing').cast(pl.Boolean)).then(1).otherwise(0).alias('swings'),
133
- pl.col('event_type').is_in(['strikeout','strikeout_double_play']).alias('k'),
134
- pl.col('event_type').is_in(['walk', 'intent_walk']).alias('bb'),
135
- pl.lit(None).alias('attack_zone'),
136
- pl.lit(None).alias('woba_pred'),
137
- pl.lit(None).alias('woba_pred_contact')
138
-
139
- ])
140
-
141
-
142
- df = df.with_columns([
143
- pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('woba_codes'),
144
- pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('xwoba_codes'),
145
- pl.when((pl.col('tb') >= 0)).then(df['woba']).otherwise(None).alias('woba_contact'),
146
- pl.when(pl.col('px').is_null()).then(pl.col('px_predict')).otherwise(pl.col('px')).alias('px'),
147
- pl.when(pl.col('pz').is_null()).then(pl.col('pz_predict')).otherwise(pl.col('pz')).alias('pz'),
148
- pl.when(pl.col('in_zone').is_null()).then(pl.col('in_zone_predict')).otherwise(pl.col('in_zone')).alias('in_zone_final'),
149
-
150
- ])
151
-
152
- df = df.with_columns([
153
- pl.when(df['launch_speed'].is_null()).then(None).otherwise(df['barrel']).alias('barrel'),
154
- pl.lit('average').alias('average'),
155
- pl.when(pl.col('in_zone_final') == False).then(True).otherwise(False).alias('out_zone'),
156
- pl.when((pl.col('in_zone_final') == True) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('zone_swing'),
157
- pl.when((pl.col('in_zone_final') == True) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('zone_contact'),
158
- pl.when((pl.col('in_zone_final') == False) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('ozone_swing'),
159
- pl.when((pl.col('in_zone_final') == False) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('ozone_contact'),
160
- pl.when(pl.col('event_type').str.contains('strikeout')).then(True).otherwise(False).alias('k'),
161
- pl.when(pl.col('event_type').is_in(['walk', 'intent_walk'])).then(True).otherwise(False).alias('bb'),
162
- pl.when(pl.col('attack_zone').is_null()).then(pl.col('attack_zone_predict')).otherwise(pl.col('attack_zone')).alias('attack_zone_final'),
163
-
164
-
165
- ])
166
-
167
- df = df.with_columns([
168
- (df['k'].cast(pl.Float32) - df['bb'].cast(pl.Float32)).alias('k_minus_bb'),
169
- (df['bb'].cast(pl.Float32) - df['k'].cast(pl.Float32)).alias('bb_minus_k'),
170
- (df['launch_speed'] > 0).alias('bip_div'),
171
- (df['attack_zone_final'] == 0).alias('heart'),
172
- (df['attack_zone_final'] == 1).alias('shadow'),
173
- (df['attack_zone_final'] == 2).alias('chase'),
174
- (df['attack_zone_final'] == 3).alias('waste'),
175
- ((df['attack_zone_final'] == 0) & (df['swings'] == 1)).alias('heart_swing'),
176
- ((df['attack_zone_final'] == 1) & (df['swings'] == 1)).alias('shadow_swing'),
177
- ((df['attack_zone_final'] == 2) & (df['swings'] == 1)).alias('chase_swing'),
178
- ((df['attack_zone_final'] == 3) & (df['swings'] == 1)).alias('waste_swing'),
179
- ((df['attack_zone_final'] == 0) & (df['whiffs'] == 1)).alias('heart_whiff'),
180
- ((df['attack_zone_final'] == 1) & (df['whiffs'] == 1)).alias('shadow_whiff'),
181
- ((df['attack_zone_final'] == 2) & (df['whiffs'] == 1)).alias('chase_whiff'),
182
- ((df['attack_zone_final'] == 3) & (df['whiffs'] == 1)).alias('waste_whiff')
183
- ])
184
-
185
-
186
- [0, 0.689, 0.720, 0.881, 1.254, 1.589, 2.048]
187
-
188
- df = df.with_columns([
189
- pl.Series(
190
- [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])]
191
- ).alias('woba_pred_predict')
192
- ])
193
-
194
- df = df.with_columns([
195
- pl.when(pl.col('event_type').is_in(['walk'])).then(0.689)
196
- .when(pl.col('event_type').is_in(['hit_by_pitch'])).then(0.720)
197
- .when(pl.col('event_type').is_in(['strikeout', 'strikeout_double_play'])).then(0)
198
- .otherwise(pl.col('woba_pred_predict')).alias('woba_pred_predict')
199
- ])
200
-
201
- df = df.with_columns([
202
- pl.when(pl.col('woba_codes').is_null()).then(None).otherwise(pl.col('woba_pred_predict')).alias('woba_pred'),
203
- pl.when(pl.col('bip')!=1).then(None).otherwise(pl.col('woba_pred_predict')).alias('woba_pred_contact'),
204
- ])
205
-
206
- df = df.with_columns([
207
- pl.when(pl.col('trajectory').is_in(['bunt_popup'])).then(pl.lit('popup'))
208
- .when(pl.col('trajectory').is_in(['bunt_grounder'])).then(pl.lit('ground_ball'))
209
- .when(pl.col('trajectory').is_in(['bunt_line_drive'])).then(pl.lit('line_drive'))
210
- .when(pl.col('trajectory').is_in([''])).then(pl.lit(None))
211
- .otherwise(pl.col('trajectory')).alias('trajectory')
212
- ])
213
-
214
-
215
- # Create one-hot encoded columns for the trajectory column
216
- dummy_df = df.select(pl.col('trajectory')).to_dummies()
217
-
218
- # Rename the one-hot encoded columns
219
- dummy_df = dummy_df.rename({
220
- 'trajectory_fly_ball': 'trajectory_fly_ball',
221
- 'trajectory_ground_ball': 'trajectory_ground_ball',
222
- 'trajectory_line_drive': 'trajectory_line_drive',
223
- 'trajectory_popup': 'trajectory_popup'
224
- })
225
-
226
- # Ensure the columns are present in the DataFrame
227
- for col in ['trajectory_fly_ball', 'trajectory_ground_ball', 'trajectory_line_drive', 'trajectory_popup']:
228
- if col not in dummy_df.columns:
229
- dummy_df = dummy_df.with_columns(pl.lit(0).alias(col))
230
-
231
- # Join the one-hot encoded columns back to the original DataFrame
232
- df = df.hstack(dummy_df)
233
-
234
- # Check if 'trajectory_null' column exists and drop it
235
- if 'trajectory_null' in df.columns:
236
- df = df.drop('trajectory_null')
237
-
238
-
239
- pitch_cat = {'FA': None,
240
- 'FF': 'Fastball',
241
- 'FT': 'Fastball',
242
- 'FC': 'Fastball',
243
- 'FS': 'Off-Speed',
244
- 'FO': 'Off-Speed',
245
- 'SI': 'Fastball',
246
- 'ST': 'Breaking',
247
- 'SL': 'Breaking',
248
- 'CU': 'Breaking',
249
- 'KC': 'Breaking',
250
- 'SC': 'Off-Speed',
251
- 'GY': 'Off-Speed',
252
- 'SV': 'Breaking',
253
- 'CS': 'Breaking',
254
- 'CH': 'Off-Speed',
255
- 'KN': 'Off-Speed',
256
- 'EP': 'Breaking',
257
- 'UN': None,
258
- 'IN': None,
259
- 'PO': None,
260
- 'AB': None,
261
- 'AS': None,
262
- 'NP': None}
263
- df = df.with_columns(
264
- df["pitch_type"].map_elements(lambda x: pitch_cat.get(x, x)).alias("pitch_group")
265
- )
266
-
267
- df = df.with_columns([
268
-
269
- (-(pl.col('vy0')**2 - (2 * pl.col('ay') * (pl.col('y0') - 17/12)))**0.5).alias('vy_f'),
270
- ])
271
-
272
- df = df.with_columns([
273
- ((pl.col('vy_f') - pl.col('vy0')) / pl.col('ay')).alias('t'),
274
- ])
275
-
276
- df = df.with_columns([
277
- (pl.col('vz0') + (pl.col('az') * pl.col('t'))).alias('vz_f'),
278
- (pl.col('vx0') + (pl.col('ax') * pl.col('t'))).alias('vx_f')
279
- ])
280
-
281
- df = df.with_columns([
282
- (-np.arctan(pl.col('vz_f') / pl.col('vy_f')) * (180 / np.pi)).alias('vaa'),
283
- (-np.arctan(pl.col('vx_f') / pl.col('vy_f')) * (180 / np.pi)).alias('haa')
284
- ])
285
-
286
- # Mirror horizontal break for left-handed pitchers
287
- df = df.with_columns(
288
- pl.when(pl.col('pitcher_hand') == 'L')
289
- .then(-pl.col('ax'))
290
- .otherwise(pl.col('ax'))
291
- .alias('ax')
292
- )
293
-
294
- # Mirror horizontal break for left-handed pitchers
295
- df = df.with_columns(
296
- pl.when(pl.col('pitcher_hand') == 'L')
297
- .then(-pl.col('hb'))
298
- .otherwise(pl.col('hb'))
299
- .alias('hb')
300
- )
301
-
302
- # Mirror horizontal release point for left-handed pitchers
303
- df = df.with_columns(
304
- pl.when(pl.col('pitcher_hand') == 'L')
305
- .then(pl.col('x0'))
306
- .otherwise(-pl.col('x0'))
307
- .alias('x0')
308
- )
309
-
310
- df = df.with_columns([
311
- pl.when(df['swings'].is_null()).then(None).otherwise(df['swings']).alias('is_swing'),
312
- pl.when(df['bip'].is_null()).then(None).otherwise(df['bip']).alias('is_bip')])
313
-
314
-
315
-
316
-
317
- df = df.with_columns([
318
- (np.arctan((pl.col("hit_x")*-1 + 125.42) / (198.27 - pl.col("hit_y"))) * 180 / np.pi * 0.75).alias("spray_angle")
319
- ])
320
-
321
- df = df.with_columns([
322
- pl.when(pl.col("batter_hand") == "L")
323
- .then(-pl.col("spray_angle"))
324
- .otherwise(pl.col("spray_angle"))
325
- .alias("adj_spray_angle")
326
- ]).drop("spray_angle")
327
-
328
-
329
- df = df.with_columns([
330
- pl.when(pl.col("adj_spray_angle").is_not_null() & (pl.col("adj_spray_angle") < -15))
331
- .then(pl.lit("oppo"))
332
- .when(pl.col("adj_spray_angle").is_not_null() & (pl.col("adj_spray_angle") > 15))
333
- .then(pl.lit("pull"))
334
- .when(pl.col("adj_spray_angle").is_not_null())
335
- .then(pl.lit("straight"))
336
- .otherwise(None) # Keep null if adj_spray_angle is null
337
- .alias("hit_direction")
338
- ])
339
-
340
- df = df.with_columns([
341
- pl.when(pl.col("hit_direction") == "oppo").then(1).otherwise(None).alias("oppo"),
342
- pl.when(pl.col("hit_direction") == "pull").then(1).otherwise(None).alias("pull"),
343
- pl.when(pl.col("hit_direction") == "straight").then(1).otherwise(None).alias("straight")
344
- ])
345
-
346
- df = df.with_columns([
347
- pl.when(pl.col("event_type") == "single").then(1).otherwise(0).alias("single"),
348
- pl.when(pl.col("event_type") == "double").then(1).otherwise(0).alias("double"),
349
- pl.when(pl.col("event_type") == "triple").then(1).otherwise(0).alias("triple"),
350
- pl.when(pl.col("event_type") == "home_run").then(1).otherwise(0).alias("home_run")
351
- ])
352
-
353
-
354
-
355
-
356
- return df
357
-
358
- # Assuming df is your Polars DataFrame
359
- def update_summary(self, df: pl.DataFrame, pitcher: bool = True) -> pl.DataFrame:
360
- """
361
- Update summary statistics for pitchers or batters.
362
-
363
- Parameters:
364
- df (pl.DataFrame): The input Polars DataFrame containing player statistics.
365
- pitcher (bool): A flag indicating whether to calculate statistics for pitchers (True) or batters (False).
366
-
367
- Returns:
368
- pl.DataFrame: A Polars DataFrame with aggregated and calculated summary statistics.
369
- """
370
-
371
- # Determine the position based on the pitcher flag
372
- if pitcher:
373
- position = 'pitcher'
374
- else:
375
- position = 'batter'
376
-
377
- # Group by position_id and position_name, then aggregate various statistics
378
- df_summ = df.group_by([f'{position}_id', f'{position}_name']).agg([
379
- pl.col('pa').sum().alias('pa'),
380
- pl.col('ab').sum().alias('ab'),
381
- pl.col('obp').sum().alias('obp_pa'),
382
- pl.col('hits').sum().alias('hits'),
383
- pl.col('on_base').sum().alias('on_base'),
384
- pl.col('k').sum().alias('k'),
385
- pl.col('bb').sum().alias('bb'),
386
- pl.col('bb_minus_k').sum().alias('bb_minus_k'),
387
- pl.col('csw').sum().alias('csw'),
388
- pl.col('bip').sum().alias('bip'),
389
- pl.col('bip_div').sum().alias('bip_div'),
390
- pl.col('tb').sum().alias('tb'),
391
- pl.col('woba').sum().alias('woba'),
392
- pl.col('woba_contact').sum().alias('woba_contact'),
393
- pl.col('woba_pred').sum().alias('xwoba'),
394
- pl.col('woba_pred_contact').sum().alias('xwoba_contact'),
395
- pl.col('woba_codes').sum().alias('woba_codes'),
396
- pl.col('xwoba_codes').sum().alias('xwoba_codes'),
397
- pl.col('hard_hit').sum().alias('hard_hit'),
398
- pl.col('barrel').sum().alias('barrel'),
399
- pl.col('sweet_spot').sum().alias('sweet_spot'),
400
- pl.col('launch_speed').max().alias('max_launch_speed'),
401
- pl.col('launch_speed').quantile(0.90).alias('launch_speed_90'),
402
- pl.col('launch_speed').mean().alias('launch_speed'),
403
- pl.col('launch_angle').mean().alias('launch_angle'),
404
- pl.col('is_pitch').sum().alias('pitches'),
405
- pl.col('swings').sum().alias('swings'),
406
- pl.col('in_zone').sum().alias('in_zone'),
407
- pl.col('out_zone').sum().alias('out_zone'),
408
- pl.col('whiffs').sum().alias('whiffs'),
409
- pl.col('zone_swing').sum().alias('zone_swing'),
410
- pl.col('zone_contact').sum().alias('zone_contact'),
411
- pl.col('ozone_swing').sum().alias('ozone_swing'),
412
- pl.col('ozone_contact').sum().alias('ozone_contact'),
413
- pl.col('trajectory_ground_ball').sum().alias('ground_ball'),
414
- pl.col('trajectory_line_drive').sum().alias('line_drive'),
415
- pl.col('trajectory_fly_ball').sum().alias('fly_ball'),
416
- pl.col('trajectory_popup').sum().alias('pop_up'),
417
- pl.col('attack_zone').count().alias('attack_zone'),
418
- pl.col('heart').sum().alias('heart'),
419
- pl.col('shadow').sum().alias('shadow'),
420
- pl.col('chase').sum().alias('chase'),
421
- pl.col('waste').sum().alias('waste'),
422
- pl.col('heart_swing').sum().alias('heart_swing'),
423
- pl.col('shadow_swing').sum().alias('shadow_swing'),
424
- pl.col('chase_swing').sum().alias('chase_swing'),
425
- pl.col('waste_swing').sum().alias('waste_swing'),
426
- pl.col('heart_whiff').sum().alias('heart_whiff'),
427
- pl.col('shadow_whiff').sum().alias('shadow_whiff'),
428
- pl.col('chase_whiff').sum().alias('chase_whiff'),
429
- pl.col('waste_whiff').sum().alias('waste_whiff')
430
- ])
431
-
432
- # Add calculated columns to the summary DataFrame
433
- df_summ = df_summ.with_columns([
434
- (pl.col('hits') / pl.col('ab')).alias('avg'),
435
- (pl.col('on_base') / pl.col('obp_pa')).alias('obp'),
436
- (pl.col('tb') / pl.col('ab')).alias('slg'),
437
- (pl.col('on_base') / pl.col('obp_pa') + pl.col('tb') / pl.col('ab')).alias('ops'),
438
- (pl.col('k') / pl.col('pa')).alias('k_percent'),
439
- (pl.col('bb') / pl.col('pa')).alias('bb_percent'),
440
- (pl.col('bb_minus_k') / pl.col('pa')).alias('bb_minus_k_percent'),
441
- (pl.col('bb') / pl.col('k')).alias('bb_over_k_percent'),
442
- (pl.col('csw') / pl.col('pitches')).alias('csw_percent'),
443
- (pl.col('sweet_spot') / pl.col('bip_div')).alias('sweet_spot_percent'),
444
- (pl.col('woba') / pl.col('woba_codes')).alias('woba_percent'),
445
- (pl.col('woba_contact') / pl.col('bip')).alias('woba_percent_contact'),
446
- (pl.col('hard_hit') / pl.col('bip_div')).alias('hard_hit_percent'),
447
- (pl.col('barrel') / pl.col('bip_div')).alias('barrel_percent'),
448
- (pl.col('zone_contact') / pl.col('zone_swing')).alias('zone_contact_percent'),
449
- (pl.col('zone_swing') / pl.col('in_zone')).alias('zone_swing_percent'),
450
- (pl.col('in_zone') / pl.col('pitches')).alias('zone_percent'),
451
- (pl.col('ozone_swing') / (pl.col('pitches') - pl.col('in_zone'))).alias('chase_percent'),
452
- (pl.col('ozone_contact') / pl.col('ozone_swing')).alias('chase_contact'),
453
- (pl.col('swings') / pl.col('pitches')).alias('swing_percent'),
454
- (pl.col('whiffs') / pl.col('swings')).alias('whiff_rate'),
455
- (pl.col('whiffs') / pl.col('pitches')).alias('swstr_rate'),
456
- (pl.col('ground_ball') / pl.col('bip')).alias('ground_ball_percent'),
457
- (pl.col('line_drive') / pl.col('bip')).alias('line_drive_percent'),
458
- (pl.col('fly_ball') / pl.col('bip')).alias('fly_ball_percent'),
459
- (pl.col('pop_up') / pl.col('bip')).alias('pop_up_percent'),
460
- (pl.col('heart') / pl.col('attack_zone')).alias('heart_zone_percent'),
461
- (pl.col('shadow') / pl.col('attack_zone')).alias('shadow_zone_percent'),
462
- (pl.col('chase') / pl.col('attack_zone')).alias('chase_zone_percent'),
463
- (pl.col('waste') / pl.col('attack_zone')).alias('waste_zone_percent'),
464
- (pl.col('heart_swing') / pl.col('heart')).alias('heart_zone_swing_percent'),
465
- (pl.col('shadow_swing') / pl.col('shadow')).alias('shadow_zone_swing_percent'),
466
- (pl.col('chase_swing') / pl.col('chase')).alias('chase_zone_swing_percent'),
467
- (pl.col('waste_swing') / pl.col('waste')).alias('waste_zone_swing_percent'),
468
- (pl.col('heart_whiff') / pl.col('heart_swing')).alias('heart_zone_whiff_percent'),
469
- (pl.col('shadow_whiff') / pl.col('shadow_swing')).alias('shadow_zone_whiff_percent'),
470
- (pl.col('chase_whiff') / pl.col('chase_swing')).alias('chase_zone_whiff_percent'),
471
- (pl.col('waste_whiff') / pl.col('waste_swing')).alias('waste_zone_whiff_percent'),
472
- (pl.col('xwoba') / pl.col('xwoba_codes')).alias('xwoba_percent'),
473
- (pl.col('xwoba_contact') / pl.col('bip')).alias('xwoba_percent_contact')
474
- ])
475
-
476
- return df_summ
477
-
478
-
479
-
480
-
481
-
482
-
483
- # Assuming df is your Polars DataFrame
484
- def update_summary_select(self, df: pl.DataFrame, selection: list) -> pl.DataFrame:
485
- """
486
- Update summary statistics for pitchers or batters.
487
-
488
- Parameters:
489
- df (pl.DataFrame): The input Polars DataFrame containing player statistics.
490
- pitcher (bool): A flag indicating whether to calculate statistics for pitchers (True) or batters (False).
491
-
492
- Returns:
493
- pl.DataFrame: A Polars DataFrame with aggregated and calculated summary statistics.
494
- """
495
-
496
- # Group by position_id and position_name, then aggregate various statistics
497
- df_summ = df.group_by(selection).agg([
498
- pl.col('pa').sum().alias('pa'),
499
- pl.col('ab').sum().alias('ab'),
500
- pl.col('obp').sum().alias('obp_pa'),
501
- pl.col('hits').sum().alias('hits'),
502
- pl.col('on_base').sum().alias('on_base'),
503
- pl.col('k').sum().alias('k'),
504
- pl.col('bb').sum().alias('bb'),
505
- pl.col('bb_minus_k').sum().alias('bb_minus_k'),
506
- pl.col('k_minus_bb').sum().alias('k_minus_bb'),
507
- pl.col('csw').sum().alias('csw'),
508
- pl.col('bip').sum().alias('bip'),
509
- pl.col('bip_div').sum().alias('bip_div'),
510
- pl.col('tb').sum().alias('tb'),
511
- pl.col('woba').sum().alias('woba'),
512
- pl.col('woba_contact').sum().alias('woba_contact'),
513
- pl.col('woba_pred').sum().alias('xwoba'),
514
- pl.col('woba_pred_contact').sum().alias('xwoba_contact'),
515
- pl.col('woba_codes').sum().alias('woba_codes'),
516
- pl.col('xwoba_codes').sum().alias('xwoba_codes'),
517
- pl.col('hard_hit').sum().alias('hard_hit'),
518
- pl.col('barrel').sum().alias('barrel'),
519
- pl.col('sweet_spot').sum().alias('sweet_spot'),
520
- pl.col('launch_speed').max().alias('max_launch_speed'),
521
- pl.col('launch_speed').quantile(0.90).alias('launch_speed_90'),
522
- pl.col('launch_speed').mean().alias('launch_speed'),
523
- pl.col('launch_angle').mean().alias('launch_angle'),
524
- pl.col('is_pitch').sum().alias('pitches'),
525
- pl.col('swings').sum().alias('swings'),
526
- pl.col('in_zone').sum().alias('in_zone'),
527
- pl.col('out_zone').sum().alias('out_zone'),
528
- pl.col('whiffs').sum().alias('whiffs'),
529
- pl.col('zone_swing').sum().alias('zone_swing'),
530
- pl.col('zone_contact').sum().alias('zone_contact'),
531
- pl.col('ozone_swing').sum().alias('ozone_swing'),
532
- pl.col('ozone_contact').sum().alias('ozone_contact'),
533
- pl.col('trajectory_ground_ball').sum().alias('ground_ball'),
534
- pl.col('trajectory_line_drive').sum().alias('line_drive'),
535
- pl.col('trajectory_fly_ball').sum().alias('fly_ball'),
536
- pl.col('trajectory_popup').sum().alias('pop_up'),
537
- pl.col('attack_zone').count().alias('attack_zone'),
538
- pl.col('heart').sum().alias('heart'),
539
- pl.col('shadow').sum().alias('shadow'),
540
- pl.col('chase').sum().alias('chase'),
541
- pl.col('waste').sum().alias('waste'),
542
- pl.col('heart_swing').sum().alias('heart_swing'),
543
- pl.col('shadow_swing').sum().alias('shadow_swing'),
544
- pl.col('chase_swing').sum().alias('chase_swing'),
545
- pl.col('waste_swing').sum().alias('waste_swing'),
546
- pl.col('heart_whiff').sum().alias('heart_whiff'),
547
- pl.col('shadow_whiff').sum().alias('shadow_whiff'),
548
- pl.col('chase_whiff').sum().alias('chase_whiff'),
549
- pl.col('waste_whiff').sum().alias('waste_whiff'),
550
- pl.col('pull').sum().alias('pull'),
551
- pl.col('straight').sum().alias('straight'),
552
- pl.col('oppo').sum().alias('oppo'),
553
- ((pl.col('trajectory_fly_ball') == 1) | (pl.col('trajectory_line_drive') == 1)).sum().alias('fly_line_bip'),
554
- (pl.col('pull') & ((pl.col('trajectory_fly_ball') == 1) | (pl.col('trajectory_line_drive') == 1))).sum().alias('pull_fly_ball'),
555
- pl.col('single').sum().alias('single'),
556
- pl.col('double').sum().alias('double'),
557
- pl.col('triple').sum().alias('triple'),
558
- pl.col('tj_stuff_plus').sum().alias('tj_stuff_plus'),
559
- pl.col('start_speed').sum(),
560
- pl.col('vb').sum(),
561
- pl.col('ivb').sum(),
562
- pl.col('hb').sum(),
563
- pl.col('x0').sum(),
564
- pl.col('z0').sum(),
565
- pl.col('vaa').sum(),
566
- pl.col('haa').sum(),
567
- pl.col('spin_rate').sum(),
568
- pl.col('extension').sum(),
569
- ])
570
-
571
- # Add calculated columns to the summary DataFrame
572
- df_summ = df_summ.with_columns([
573
- (pl.col('hits') / pl.col('ab')).alias('avg'),
574
- (pl.col('on_base') / pl.col('obp_pa')).alias('obp'),
575
- (pl.col('tb') / pl.col('ab')).alias('slg'),
576
- (pl.col('on_base') / pl.col('obp_pa') + pl.col('tb') / pl.col('ab')).alias('ops'),
577
- (pl.col('k') / pl.col('pa')).alias('k_percent'),
578
- (pl.col('bb') / pl.col('pa')).alias('bb_percent'),
579
- (pl.col('bb_minus_k') / pl.col('pa')).alias('bb_minus_k_percent'),
580
- (pl.col('k_minus_bb') / pl.col('pa')).alias('k_minus_bb_percent'),
581
- (pl.col('bb') / pl.col('k')).alias('bb_over_k_percent'),
582
- (pl.col('csw') / pl.col('pitches')).alias('csw_percent'),
583
- (pl.col('sweet_spot') / pl.col('bip_div')).alias('sweet_spot_percent'),
584
- (pl.col('woba') / pl.col('woba_codes')).alias('woba_percent'),
585
- (pl.col('woba_contact') / pl.col('bip')).alias('woba_percent_contact'),
586
- (pl.col('hard_hit') / pl.col('bip_div')).alias('hard_hit_percent'),
587
- (pl.col('barrel') / pl.col('bip_div')).alias('barrel_percent'),
588
- (pl.col('zone_contact') / pl.col('zone_swing')).alias('zone_contact_percent'),
589
- (pl.col('zone_swing') / pl.col('in_zone')).alias('zone_swing_percent'),
590
- (pl.col('in_zone') / pl.col('pitches')).alias('zone_percent'),
591
- (pl.col('ozone_swing') / (pl.col('pitches') - pl.col('in_zone'))).alias('chase_percent'),
592
- (pl.col('ozone_contact') / pl.col('ozone_swing')).alias('chase_contact'),
593
- (pl.col('swings') / pl.col('pitches')).alias('swing_percent'),
594
- (pl.col('whiffs') / pl.col('swings')).alias('whiff_rate'),
595
- (pl.col('whiffs') / pl.col('pitches')).alias('swstr_rate'),
596
- (pl.col('ground_ball') / pl.col('bip')).alias('ground_ball_percent'),
597
- (pl.col('line_drive') / pl.col('bip')).alias('line_drive_percent'),
598
- (pl.col('fly_ball') / pl.col('bip')).alias('fly_ball_percent'),
599
- (pl.col('pop_up') / pl.col('bip')).alias('pop_up_percent'),
600
- (pl.col('heart') / pl.col('attack_zone')).alias('heart_zone_percent'),
601
- (pl.col('shadow') / pl.col('attack_zone')).alias('shadow_zone_percent'),
602
- (pl.col('chase') / pl.col('attack_zone')).alias('chase_zone_percent'),
603
- (pl.col('waste') / pl.col('attack_zone')).alias('waste_zone_percent'),
604
- (pl.col('heart_swing') / pl.col('heart')).alias('heart_zone_swing_percent'),
605
- (pl.col('shadow_swing') / pl.col('shadow')).alias('shadow_zone_swing_percent'),
606
- (pl.col('chase_swing') / pl.col('chase')).alias('chase_zone_swing_percent'),
607
- (pl.col('waste_swing') / pl.col('waste')).alias('waste_zone_swing_percent'),
608
- (pl.col('heart_whiff') / pl.col('heart_swing')).alias('heart_zone_whiff_percent'),
609
- (pl.col('shadow_whiff') / pl.col('shadow_swing')).alias('shadow_zone_whiff_percent'),
610
- (pl.col('chase_whiff') / pl.col('chase_swing')).alias('chase_zone_whiff_percent'),
611
- (pl.col('waste_whiff') / pl.col('waste_swing')).alias('waste_zone_whiff_percent'),
612
- (pl.col('xwoba') / pl.col('xwoba_codes')).alias('xwoba_percent'),
613
- (pl.col('xwoba_contact') / pl.col('bip')).alias('xwoba_percent_contact'),
614
- (pl.col('pull') / pl.col('bip')).alias('pull_percent'),
615
- (pl.col('straight') / pl.col('bip')).alias('straight_percent'),
616
- (pl.col('oppo') / pl.col('bip')).alias('oppo_percent'),
617
- (pl.col('pull_fly_ball') / pl.col('fly_line_bip')).alias('pulled_fly_ball_percent'),
618
- (pl.col('tj_stuff_plus') / pl.col('pitches')).alias('tj_stuff_plus_avg'),
619
- (pl.col('start_speed')/ pl.col('pitches')).alias('start_speed_avg'),
620
- (pl.col('vb')/ pl.col('pitches')).alias('vb_avg'),
621
- (pl.col('ivb')/ pl.col('pitches')).alias('ivb_avg'),
622
- (pl.col('hb')/ pl.col('pitches')).alias('hb_avg'),
623
- (pl.col('x0')/ pl.col('pitches')).alias('x0_avg'),
624
- (pl.col('z0')/ pl.col('pitches')).alias('z0_avg'),
625
- (pl.col('vaa')/ pl.col('pitches')).alias('vaa_avg'),
626
- (pl.col('haa')/ pl.col('pitches')).alias('haa_avg'),
627
- (pl.col('spin_rate')/ pl.col('pitches')).alias('spin_rate_avg'),
628
- (pl.col('extension')/ pl.col('pitches')).alias('extension_avg'),
629
-
630
- ])
631
-
632
  return df_summ
 
1
+ import polars as pl
2
+ import numpy as np
3
+ import joblib
4
+
5
+ loaded_model = joblib.load('joblib_model/barrel_model.joblib')
6
+ in_zone_model = joblib.load('joblib_model/in_zone_model_knn_20240410.joblib')
7
+ attack_zone_model = joblib.load('joblib_model/model_attack_zone.joblib')
8
+ xwoba_model = joblib.load('joblib_model/xwoba_model.joblib')
9
+ px_model = joblib.load('joblib_model/linear_reg_model_x.joblib')
10
+ pz_model = joblib.load('joblib_model/linear_reg_model_z.joblib')
11
+
12
+
13
+ class df_update:
14
+ def __init__(self):
15
+ pass
16
+
17
+ def update(self, df_clone: pl.DataFrame):
18
+
19
+ df = df_clone.clone()
20
+ # Assuming px_model is defined and df is your DataFrame
21
+ hit_codes = ['single',
22
+ 'double','home_run', 'triple']
23
+
24
+ ab_codes = ['single', 'strikeout', 'field_out',
25
+ 'grounded_into_double_play', 'fielders_choice', 'force_out',
26
+ 'double', 'field_error', 'home_run', 'triple',
27
+ 'double_play',
28
+ 'fielders_choice_out', 'strikeout_double_play',
29
+ 'other_out','triple_play']
30
+
31
+
32
+ obp_true_codes = ['single', 'walk',
33
+ 'double','home_run', 'triple',
34
+ 'hit_by_pitch', 'intent_walk']
35
+
36
+ obp_codes = ['single', 'strikeout', 'walk', 'field_out',
37
+ 'grounded_into_double_play', 'fielders_choice', 'force_out',
38
+ 'double', 'sac_fly', 'field_error', 'home_run', 'triple',
39
+ 'hit_by_pitch', 'double_play', 'intent_walk',
40
+ 'fielders_choice_out', 'strikeout_double_play',
41
+ 'sac_fly_double_play',
42
+ 'other_out','triple_play']
43
+
44
+
45
+ contact_codes = ['In play, no out',
46
+ 'Foul', 'In play, out(s)',
47
+ 'In play, run(s)',
48
+ 'Foul Bunt']
49
+
50
+ bip_codes = ['In play, no out', 'In play, run(s)','In play, out(s)']
51
+
52
+
53
+ conditions_barrel = [
54
+ df['launch_speed'].is_null(),
55
+ (df['launch_speed'] * 1.5 - df['launch_angle'] >= 117) &
56
+ (df['launch_speed'] + df['launch_angle'] >= 124) &
57
+ (df['launch_speed'] >= 98) &
58
+ (df['launch_angle'] >= 4) & (df['launch_angle'] <= 50)
59
+ ]
60
+ choices_barrel = [False, True]
61
+
62
+ conditions_tb = [
63
+ (df['event_type'] == 'single'),
64
+ (df['event_type'] == 'double'),
65
+ (df['event_type'] == 'triple'),
66
+ (df['event_type'] == 'home_run')
67
+ ]
68
+ choices_tb = [1, 2, 3, 4]
69
+
70
+
71
+ conditions_woba = [
72
+ 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']),
73
+ df['event_type'] == 'walk',
74
+ df['event_type'] == 'hit_by_pitch',
75
+ df['event_type'] == 'single',
76
+ df['event_type'] == 'double',
77
+ df['event_type'] == 'triple',
78
+ df['event_type'] == 'home_run'
79
+ ]
80
+ choices_woba = [0, 0.689, 0.720, 0.881, 1.254, 1.589, 2.048]
81
+
82
+ 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']
83
+
84
+ pitch_cat = {'FA': 'Fastball',
85
+ 'FF': 'Fastball',
86
+ 'FT': 'Fastball',
87
+ 'FC': 'Fastball',
88
+ 'FS': 'Off-Speed',
89
+ 'FO': 'Off-Speed',
90
+ 'SI': 'Fastball',
91
+ 'ST': 'Breaking',
92
+ 'SL': 'Breaking',
93
+ 'CU': 'Breaking',
94
+ 'KC': 'Breaking',
95
+ 'SC': 'Off-Speed',
96
+ 'GY': 'Off-Speed',
97
+ 'SV': 'Breaking',
98
+ 'CS': 'Breaking',
99
+ 'CH': 'Off-Speed',
100
+ 'KN': 'Off-Speed',
101
+ 'EP': 'Breaking',
102
+ 'UN': None,
103
+ 'IN': None,
104
+ 'PO': None,
105
+ 'AB': None,
106
+ 'AS': None,
107
+ 'NP': None}
108
+
109
+
110
+ df = df.with_columns([
111
+ pl.when(df['type_ab'].is_not_null()).then(1).otherwise(0).alias('pa'),
112
+ pl.when(df['is_pitch']).then(1).otherwise(0).alias('pitches'),
113
+ pl.when(df['sz_top'] == 0).then(None).otherwise(df['sz_top']).alias('sz_top'),
114
+ pl.when(df['sz_bot'] == 0).then(None).otherwise(df['sz_bot']).alias('sz_bot'),
115
+ pl.when(df['zone'] > 0).then(df['zone'] < 10).otherwise(None).alias('in_zone'),
116
+ pl.Series(px_model.predict(df[['x']].fill_null(0).to_numpy())[:, 0]).alias('px_predict'),
117
+ pl.Series(pz_model.predict(df[['y']].fill_null(0).to_numpy())[:, 0] + 3.2).alias('pz_predict'),
118
+ pl.Series(in_zone_model.predict(df[['px','pz','sz_top','sz_bot']].fill_null(0).to_numpy())[:]).alias('in_zone_predict'),
119
+ pl.Series(attack_zone_model.predict(df[['px','pz','sz_top','sz_bot']].fill_null(0).to_numpy())[:]).alias('attack_zone_predict'),
120
+ pl.when(df['event_type'].is_in(hit_codes)).then(True).otherwise(False).alias('hits'),
121
+ pl.when(df['event_type'].is_in(ab_codes)).then(True).otherwise(False).alias('ab'),
122
+ pl.when(df['event_type'].is_in(obp_true_codes)).then(True).otherwise(False).alias('on_base'),
123
+ pl.when(df['event_type'].is_in(obp_codes)).then(True).otherwise(False).alias('obp'),
124
+ pl.when(df['play_description'].is_in(bip_codes)).then(True).otherwise(False).alias('bip'),
125
+ pl.when(conditions_barrel[0]).then(choices_barrel[0]).when(conditions_barrel[1]).then(choices_barrel[1]).otherwise(None).alias('barrel'),
126
+ 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'),
127
+ pl.when(df['launch_speed'].is_null()).then(False).when(df['launch_speed'] >= 94.5).then(True).otherwise(None).alias('hard_hit'),
128
+ 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'),
129
+ 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'),
130
+ pl.when((df['play_code'] == 'S') | (df['play_code'] == 'W') | (df['play_code'] == 'T')).then(1).otherwise(0).alias('whiffs'),
131
+ pl.when((df['play_code'] == 'S') | (df['play_code'] == 'W') | (df['play_code'] == 'T') | (df['play_code'] == 'C')).then(1).otherwise(0).alias('csw'),
132
+ pl.when(pl.col('is_swing').cast(pl.Boolean)).then(1).otherwise(0).alias('swings'),
133
+ pl.col('event_type').is_in(['strikeout','strikeout_double_play']).alias('k'),
134
+ pl.col('event_type').is_in(['walk', 'intent_walk']).alias('bb'),
135
+ pl.lit(None).alias('attack_zone'),
136
+ pl.lit(None).alias('woba_pred'),
137
+ pl.lit(None).alias('woba_pred_contact')
138
+
139
+ ])
140
+
141
+
142
+ df = df.with_columns([
143
+ pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('woba_codes'),
144
+ pl.when(df['event_type'].is_in(woba_codes)).then(1).otherwise(None).alias('xwoba_codes'),
145
+ pl.when((pl.col('tb') >= 0)).then(df['woba']).otherwise(None).alias('woba_contact'),
146
+ pl.when(pl.col('px').is_null()).then(pl.col('px_predict')).otherwise(pl.col('px')).alias('px'),
147
+ pl.when(pl.col('pz').is_null()).then(pl.col('pz_predict')).otherwise(pl.col('pz')).alias('pz'),
148
+ pl.when(pl.col('in_zone').is_null()).then(pl.col('in_zone_predict')).otherwise(pl.col('in_zone')).alias('in_zone_final'),
149
+
150
+ ])
151
+
152
+ df = df.with_columns([
153
+ pl.when(df['launch_speed'].is_null()).then(None).otherwise(df['barrel']).alias('barrel'),
154
+ pl.lit('average').alias('average'),
155
+ pl.when(pl.col('in_zone_final') == False).then(True).otherwise(False).alias('out_zone'),
156
+ pl.when((pl.col('in_zone_final') == True) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('zone_swing'),
157
+ pl.when((pl.col('in_zone_final') == True) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('zone_contact'),
158
+ pl.when((pl.col('in_zone_final') == False) & (pl.col('swings') == 1)).then(True).otherwise(False).alias('ozone_swing'),
159
+ pl.when((pl.col('in_zone_final') == False) & (pl.col('swings') == 1) & (pl.col('whiffs') == 0)).then(True).otherwise(False).alias('ozone_contact'),
160
+ pl.when(pl.col('event_type').str.contains('strikeout')).then(True).otherwise(False).alias('k'),
161
+ pl.when(pl.col('event_type').is_in(['walk', 'intent_walk'])).then(True).otherwise(False).alias('bb'),
162
+ pl.when(pl.col('attack_zone').is_null()).then(pl.col('attack_zone_predict')).otherwise(pl.col('attack_zone')).alias('attack_zone_final'),
163
+
164
+
165
+ ])
166
+
167
+ df = df.with_columns([
168
+ (df['k'].cast(pl.Float32) - df['bb'].cast(pl.Float32)).alias('k_minus_bb'),
169
+ (df['bb'].cast(pl.Float32) - df['k'].cast(pl.Float32)).alias('bb_minus_k'),
170
+ (df['launch_speed'] > 0).alias('bip_div'),
171
+ (df['attack_zone_final'] == 0).alias('heart'),
172
+ (df['attack_zone_final'] == 1).alias('shadow'),
173
+ (df['attack_zone_final'] == 2).alias('chase'),
174
+ (df['attack_zone_final'] == 3).alias('waste'),
175
+ ((df['attack_zone_final'] == 0) & (df['swings'] == 1)).alias('heart_swing'),
176
+ ((df['attack_zone_final'] == 1) & (df['swings'] == 1)).alias('shadow_swing'),
177
+ ((df['attack_zone_final'] == 2) & (df['swings'] == 1)).alias('chase_swing'),
178
+ ((df['attack_zone_final'] == 3) & (df['swings'] == 1)).alias('waste_swing'),
179
+ ((df['attack_zone_final'] == 0) & (df['whiffs'] == 1)).alias('heart_whiff'),
180
+ ((df['attack_zone_final'] == 1) & (df['whiffs'] == 1)).alias('shadow_whiff'),
181
+ ((df['attack_zone_final'] == 2) & (df['whiffs'] == 1)).alias('chase_whiff'),
182
+ ((df['attack_zone_final'] == 3) & (df['whiffs'] == 1)).alias('waste_whiff')
183
+ ])
184
+
185
+
186
+ [0, 0.689, 0.720, 0.881, 1.254, 1.589, 2.048]
187
+
188
+ df = df.with_columns([
189
+ pl.Series(
190
+ [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])]
191
+ ).alias('woba_pred_predict')
192
+ ])
193
+
194
+ df = df.with_columns([
195
+ pl.when(pl.col('event_type').is_in(['walk'])).then(0.689)
196
+ .when(pl.col('event_type').is_in(['hit_by_pitch'])).then(0.720)
197
+ .when(pl.col('event_type').is_in(['strikeout', 'strikeout_double_play'])).then(0)
198
+ .otherwise(pl.col('woba_pred_predict')).alias('woba_pred_predict')
199
+ ])
200
+
201
+ df = df.with_columns([
202
+ pl.when(pl.col('woba_codes').is_null()).then(None).otherwise(pl.col('woba_pred_predict')).alias('woba_pred'),
203
+ pl.when(pl.col('bip')!=1).then(None).otherwise(pl.col('woba_pred_predict')).alias('woba_pred_contact'),
204
+ ])
205
+
206
+ df = df.with_columns([
207
+ pl.when(pl.col('trajectory').is_in(['bunt_popup'])).then(pl.lit('popup'))
208
+ .when(pl.col('trajectory').is_in(['bunt_grounder'])).then(pl.lit('ground_ball'))
209
+ .when(pl.col('trajectory').is_in(['bunt_line_drive'])).then(pl.lit('line_drive'))
210
+ .when(pl.col('trajectory').is_in([''])).then(pl.lit(None))
211
+ .otherwise(pl.col('trajectory')).alias('trajectory')
212
+ ])
213
+
214
+
215
+ # Create one-hot encoded columns for the trajectory column
216
+ dummy_df = df.select(pl.col('trajectory')).to_dummies()
217
+
218
+ # Rename the one-hot encoded columns
219
+ dummy_df = dummy_df.rename({
220
+ 'trajectory_fly_ball': 'trajectory_fly_ball',
221
+ 'trajectory_ground_ball': 'trajectory_ground_ball',
222
+ 'trajectory_line_drive': 'trajectory_line_drive',
223
+ 'trajectory_popup': 'trajectory_popup'
224
+ })
225
+
226
+ # Ensure the columns are present in the DataFrame
227
+ for col in ['trajectory_fly_ball', 'trajectory_ground_ball', 'trajectory_line_drive', 'trajectory_popup']:
228
+ if col not in dummy_df.columns:
229
+ dummy_df = dummy_df.with_columns(pl.lit(0).alias(col))
230
+
231
+ # Join the one-hot encoded columns back to the original DataFrame
232
+ df = df.hstack(dummy_df)
233
+
234
+ # Check if 'trajectory_null' column exists and drop it
235
+ if 'trajectory_null' in df.columns:
236
+ df = df.drop('trajectory_null')
237
+
238
+
239
+ pitch_cat = {'FA': None,
240
+ 'FF': 'Fastball',
241
+ 'FT': 'Fastball',
242
+ 'FC': 'Fastball',
243
+ 'FS': 'Off-Speed',
244
+ 'FO': 'Off-Speed',
245
+ 'SI': 'Fastball',
246
+ 'ST': 'Breaking',
247
+ 'SL': 'Breaking',
248
+ 'CU': 'Breaking',
249
+ 'KC': 'Breaking',
250
+ 'SC': 'Off-Speed',
251
+ 'GY': 'Off-Speed',
252
+ 'SV': 'Breaking',
253
+ 'CS': 'Breaking',
254
+ 'CH': 'Off-Speed',
255
+ 'KN': 'Off-Speed',
256
+ 'EP': 'Breaking',
257
+ 'UN': None,
258
+ 'IN': None,
259
+ 'PO': None,
260
+ 'AB': None,
261
+ 'AS': None,
262
+ 'NP': None}
263
+ df = df.with_columns(
264
+ df["pitch_type"].map_elements(lambda x: pitch_cat.get(x, x)).alias("pitch_group")
265
+ )
266
+
267
+ df = df.with_columns([
268
+
269
+ (-(pl.col('vy0')**2 - (2 * pl.col('ay') * (pl.col('y0') - 17/12)))**0.5).alias('vy_f'),
270
+ ])
271
+
272
+ df = df.with_columns([
273
+ ((pl.col('vy_f') - pl.col('vy0')) / pl.col('ay')).alias('t'),
274
+ ])
275
+
276
+ df = df.with_columns([
277
+ (pl.col('vz0') + (pl.col('az') * pl.col('t'))).alias('vz_f'),
278
+ (pl.col('vx0') + (pl.col('ax') * pl.col('t'))).alias('vx_f')
279
+ ])
280
+
281
+ df = df.with_columns([
282
+ (-np.arctan(pl.col('vz_f') / pl.col('vy_f')) * (180 / np.pi)).alias('vaa'),
283
+ (-np.arctan(pl.col('vx_f') / pl.col('vy_f')) * (180 / np.pi)).alias('haa')
284
+ ])
285
+
286
+ # Mirror horizontal break for left-handed pitchers
287
+ df = df.with_columns(
288
+ pl.when(pl.col('pitcher_hand') == 'L')
289
+ .then(-pl.col('ax'))
290
+ .otherwise(pl.col('ax'))
291
+ .alias('ax')
292
+ )
293
+
294
+ # Mirror horizontal break for left-handed pitchers
295
+ df = df.with_columns(
296
+ pl.when(pl.col('pitcher_hand') == 'L')
297
+ .then(-pl.col('hb'))
298
+ .otherwise(pl.col('hb'))
299
+ .alias('hb')
300
+ )
301
+
302
+ # Mirror horizontal release point for left-handed pitchers
303
+ df = df.with_columns(
304
+ pl.when(pl.col('pitcher_hand') == 'L')
305
+ .then(pl.col('x0'))
306
+ .otherwise(-pl.col('x0'))
307
+ .alias('x0')
308
+ )
309
+
310
+ df = df.with_columns([
311
+ pl.when(df['swings'].is_null()).then(None).otherwise(df['swings']).alias('is_swing'),
312
+ pl.when(df['bip'].is_null()).then(None).otherwise(df['bip']).alias('is_bip')])
313
+
314
+
315
+
316
+
317
+ df = df.with_columns([
318
+ (np.arctan((pl.col("hit_x")*-1 + 125.42) / (198.27 - pl.col("hit_y"))) * 180 / np.pi * 0.75).alias("spray_angle")
319
+ ])
320
+
321
+ df = df.with_columns([
322
+ pl.when(pl.col("batter_hand") == "L")
323
+ .then(-pl.col("spray_angle"))
324
+ .otherwise(pl.col("spray_angle"))
325
+ .alias("adj_spray_angle")
326
+ ]).drop("spray_angle")
327
+
328
+
329
+ df = df.with_columns([
330
+ pl.when(pl.col("adj_spray_angle").is_not_null() & (pl.col("adj_spray_angle") < -15))
331
+ .then(pl.lit("oppo"))
332
+ .when(pl.col("adj_spray_angle").is_not_null() & (pl.col("adj_spray_angle") > 15))
333
+ .then(pl.lit("pull"))
334
+ .when(pl.col("adj_spray_angle").is_not_null())
335
+ .then(pl.lit("straight"))
336
+ .otherwise(None) # Keep null if adj_spray_angle is null
337
+ .alias("hit_direction")
338
+ ])
339
+
340
+ df = df.with_columns([
341
+ pl.when(pl.col("hit_direction") == "oppo").then(1).otherwise(None).alias("oppo"),
342
+ pl.when(pl.col("hit_direction") == "pull").then(1).otherwise(None).alias("pull"),
343
+ pl.when(pl.col("hit_direction") == "straight").then(1).otherwise(None).alias("straight")
344
+ ])
345
+
346
+ df = df.with_columns([
347
+ pl.when(pl.col("event_type") == "single").then(1).otherwise(0).alias("single"),
348
+ pl.when(pl.col("event_type") == "double").then(1).otherwise(0).alias("double"),
349
+ pl.when(pl.col("event_type") == "triple").then(1).otherwise(0).alias("triple"),
350
+ pl.when(pl.col("event_type") == "home_run").then(1).otherwise(0).alias("home_run")
351
+ ])
352
+
353
+
354
+
355
+
356
+ return df
357
+
358
+ # Assuming df is your Polars DataFrame
359
+ def update_summary(self, df: pl.DataFrame, pitcher: bool = True) -> pl.DataFrame:
360
+ """
361
+ Update summary statistics for pitchers or batters.
362
+
363
+ Parameters:
364
+ df (pl.DataFrame): The input Polars DataFrame containing player statistics.
365
+ pitcher (bool): A flag indicating whether to calculate statistics for pitchers (True) or batters (False).
366
+
367
+ Returns:
368
+ pl.DataFrame: A Polars DataFrame with aggregated and calculated summary statistics.
369
+ """
370
+
371
+ # Determine the position based on the pitcher flag
372
+ if pitcher:
373
+ position = 'pitcher'
374
+ else:
375
+ position = 'batter'
376
+
377
+ # Group by position_id and position_name, then aggregate various statistics
378
+ df_summ = df.group_by([f'{position}_id', f'{position}_name']).agg([
379
+ pl.col('pa').sum().alias('pa'),
380
+ pl.col('ab').sum().alias('ab'),
381
+ pl.col('obp').sum().alias('obp_pa'),
382
+ pl.col('hits').sum().alias('hits'),
383
+ pl.col('on_base').sum().alias('on_base'),
384
+ pl.col('k').sum().alias('k'),
385
+ pl.col('bb').sum().alias('bb'),
386
+ pl.col('bb_minus_k').sum().alias('bb_minus_k'),
387
+ pl.col('csw').sum().alias('csw'),
388
+ pl.col('bip').sum().alias('bip'),
389
+ pl.col('bip_div').sum().alias('bip_div'),
390
+ pl.col('tb').sum().alias('tb'),
391
+ pl.col('woba').sum().alias('woba'),
392
+ pl.col('woba_contact').sum().alias('woba_contact'),
393
+ pl.col('woba_pred').sum().alias('xwoba'),
394
+ pl.col('woba_pred_contact').sum().alias('xwoba_contact'),
395
+ pl.col('woba_codes').sum().alias('woba_codes'),
396
+ pl.col('xwoba_codes').sum().alias('xwoba_codes'),
397
+ pl.col('hard_hit').sum().alias('hard_hit'),
398
+ pl.col('barrel').sum().alias('barrel'),
399
+ pl.col('sweet_spot').sum().alias('sweet_spot'),
400
+ pl.col('launch_speed').max().alias('max_launch_speed'),
401
+ pl.col('launch_speed').quantile(0.90).alias('launch_speed_90'),
402
+ pl.col('launch_speed').mean().alias('launch_speed'),
403
+ pl.col('launch_angle').mean().alias('launch_angle'),
404
+ pl.col('is_pitch').sum().alias('pitches'),
405
+ pl.col('swings').sum().alias('swings'),
406
+ pl.col('in_zone').sum().alias('in_zone'),
407
+ pl.col('out_zone').sum().alias('out_zone'),
408
+ pl.col('whiffs').sum().alias('whiffs'),
409
+ pl.col('zone_swing').sum().alias('zone_swing'),
410
+ pl.col('zone_contact').sum().alias('zone_contact'),
411
+ pl.col('ozone_swing').sum().alias('ozone_swing'),
412
+ pl.col('ozone_contact').sum().alias('ozone_contact'),
413
+ pl.col('trajectory_ground_ball').sum().alias('ground_ball'),
414
+ pl.col('trajectory_line_drive').sum().alias('line_drive'),
415
+ pl.col('trajectory_fly_ball').sum().alias('fly_ball'),
416
+ pl.col('trajectory_popup').sum().alias('pop_up'),
417
+ pl.col('attack_zone').count().alias('attack_zone'),
418
+ pl.col('heart').sum().alias('heart'),
419
+ pl.col('shadow').sum().alias('shadow'),
420
+ pl.col('chase').sum().alias('chase'),
421
+ pl.col('waste').sum().alias('waste'),
422
+ pl.col('heart_swing').sum().alias('heart_swing'),
423
+ pl.col('shadow_swing').sum().alias('shadow_swing'),
424
+ pl.col('chase_swing').sum().alias('chase_swing'),
425
+ pl.col('waste_swing').sum().alias('waste_swing'),
426
+ pl.col('heart_whiff').sum().alias('heart_whiff'),
427
+ pl.col('shadow_whiff').sum().alias('shadow_whiff'),
428
+ pl.col('chase_whiff').sum().alias('chase_whiff'),
429
+ pl.col('waste_whiff').sum().alias('waste_whiff')
430
+ ])
431
+
432
+ # Add calculated columns to the summary DataFrame
433
+ df_summ = df_summ.with_columns([
434
+ (pl.col('hits') / pl.col('ab')).alias('avg'),
435
+ (pl.col('on_base') / pl.col('obp_pa')).alias('obp'),
436
+ (pl.col('tb') / pl.col('ab')).alias('slg'),
437
+ (pl.col('on_base') / pl.col('obp_pa') + pl.col('tb') / pl.col('ab')).alias('ops'),
438
+ (pl.col('k') / pl.col('pa')).alias('k_percent'),
439
+ (pl.col('bb') / pl.col('pa')).alias('bb_percent'),
440
+ (pl.col('bb_minus_k') / pl.col('pa')).alias('bb_minus_k_percent'),
441
+ (pl.col('bb') / pl.col('k')).alias('bb_over_k_percent'),
442
+ (pl.col('csw') / pl.col('pitches')).alias('csw_percent'),
443
+ (pl.col('sweet_spot') / pl.col('bip_div')).alias('sweet_spot_percent'),
444
+ (pl.col('woba') / pl.col('woba_codes')).alias('woba_percent'),
445
+ (pl.col('woba_contact') / pl.col('bip')).alias('woba_percent_contact'),
446
+ (pl.col('hard_hit') / pl.col('bip_div')).alias('hard_hit_percent'),
447
+ (pl.col('barrel') / pl.col('bip_div')).alias('barrel_percent'),
448
+ (pl.col('zone_contact') / pl.col('zone_swing')).alias('zone_contact_percent'),
449
+ (pl.col('zone_swing') / pl.col('in_zone')).alias('zone_swing_percent'),
450
+ (pl.col('in_zone') / pl.col('pitches')).alias('zone_percent'),
451
+ (pl.col('ozone_swing') / (pl.col('pitches') - pl.col('in_zone'))).alias('chase_percent'),
452
+ (pl.col('ozone_contact') / pl.col('ozone_swing')).alias('chase_contact'),
453
+ (pl.col('swings') / pl.col('pitches')).alias('swing_percent'),
454
+ (pl.col('whiffs') / pl.col('swings')).alias('whiff_rate'),
455
+ (pl.col('whiffs') / pl.col('pitches')).alias('swstr_rate'),
456
+ (pl.col('ground_ball') / pl.col('bip')).alias('ground_ball_percent'),
457
+ (pl.col('line_drive') / pl.col('bip')).alias('line_drive_percent'),
458
+ (pl.col('fly_ball') / pl.col('bip')).alias('fly_ball_percent'),
459
+ (pl.col('pop_up') / pl.col('bip')).alias('pop_up_percent'),
460
+ (pl.col('heart') / pl.col('attack_zone')).alias('heart_zone_percent'),
461
+ (pl.col('shadow') / pl.col('attack_zone')).alias('shadow_zone_percent'),
462
+ (pl.col('chase') / pl.col('attack_zone')).alias('chase_zone_percent'),
463
+ (pl.col('waste') / pl.col('attack_zone')).alias('waste_zone_percent'),
464
+ (pl.col('heart_swing') / pl.col('heart')).alias('heart_zone_swing_percent'),
465
+ (pl.col('shadow_swing') / pl.col('shadow')).alias('shadow_zone_swing_percent'),
466
+ (pl.col('chase_swing') / pl.col('chase')).alias('chase_zone_swing_percent'),
467
+ (pl.col('waste_swing') / pl.col('waste')).alias('waste_zone_swing_percent'),
468
+ (pl.col('heart_whiff') / pl.col('heart_swing')).alias('heart_zone_whiff_percent'),
469
+ (pl.col('shadow_whiff') / pl.col('shadow_swing')).alias('shadow_zone_whiff_percent'),
470
+ (pl.col('chase_whiff') / pl.col('chase_swing')).alias('chase_zone_whiff_percent'),
471
+ (pl.col('waste_whiff') / pl.col('waste_swing')).alias('waste_zone_whiff_percent'),
472
+ (pl.col('xwoba') / pl.col('xwoba_codes')).alias('xwoba_percent'),
473
+ (pl.col('xwoba_contact') / pl.col('bip')).alias('xwoba_percent_contact')
474
+ ])
475
+
476
+ return df_summ
477
+
478
+
479
+
480
+
481
+
482
+
483
+ # Assuming df is your Polars DataFrame
484
+ def update_summary_select(self, df: pl.DataFrame, selection: list) -> pl.DataFrame:
485
+ """
486
+ Update summary statistics for pitchers or batters.
487
+
488
+ Parameters:
489
+ df (pl.DataFrame): The input Polars DataFrame containing player statistics.
490
+ pitcher (bool): A flag indicating whether to calculate statistics for pitchers (True) or batters (False).
491
+
492
+ Returns:
493
+ pl.DataFrame: A Polars DataFrame with aggregated and calculated summary statistics.
494
+ """
495
+
496
+ # Group by position_id and position_name, then aggregate various statistics
497
+ df_summ = df.group_by(selection).agg([
498
+ pl.col('pa').sum().alias('pa'),
499
+ pl.col('ab').sum().alias('ab'),
500
+ pl.col('obp').sum().alias('obp_pa'),
501
+ pl.col('hits').sum().alias('hits'),
502
+ pl.col('on_base').sum().alias('on_base'),
503
+ pl.col('k').sum().alias('k'),
504
+ pl.col('bb').sum().alias('bb'),
505
+ pl.col('bb_minus_k').sum().alias('bb_minus_k'),
506
+ pl.col('k_minus_bb').sum().alias('k_minus_bb'),
507
+ pl.col('csw').sum().alias('csw'),
508
+ pl.col('bip').sum().alias('bip'),
509
+ pl.col('bip_div').sum().alias('bip_div'),
510
+ pl.col('tb').sum().alias('tb'),
511
+ pl.col('woba').sum().alias('woba'),
512
+ pl.col('woba_contact').sum().alias('woba_contact'),
513
+ pl.col('woba_pred').sum().alias('xwoba'),
514
+ pl.col('woba_pred_contact').sum().alias('xwoba_contact'),
515
+ pl.col('woba_codes').sum().alias('woba_codes'),
516
+ pl.col('xwoba_codes').sum().alias('xwoba_codes'),
517
+ pl.col('hard_hit').sum().alias('hard_hit'),
518
+ pl.col('barrel').sum().alias('barrel'),
519
+ pl.col('sweet_spot').sum().alias('sweet_spot'),
520
+ pl.col('launch_speed').max().alias('max_launch_speed'),
521
+ pl.col('launch_speed').quantile(0.90).alias('launch_speed_90'),
522
+ pl.col('launch_speed').mean().alias('launch_speed'),
523
+ pl.col('launch_angle').mean().alias('launch_angle'),
524
+ pl.col('is_pitch').sum().alias('pitches'),
525
+ pl.col('swings').sum().alias('swings'),
526
+ pl.col('in_zone').sum().alias('in_zone'),
527
+ pl.col('out_zone').sum().alias('out_zone'),
528
+ pl.col('whiffs').sum().alias('whiffs'),
529
+ pl.col('zone_swing').sum().alias('zone_swing'),
530
+ pl.col('zone_contact').sum().alias('zone_contact'),
531
+ pl.col('ozone_swing').sum().alias('ozone_swing'),
532
+ pl.col('ozone_contact').sum().alias('ozone_contact'),
533
+ pl.col('trajectory_ground_ball').sum().alias('ground_ball'),
534
+ pl.col('trajectory_line_drive').sum().alias('line_drive'),
535
+ pl.col('trajectory_fly_ball').sum().alias('fly_ball'),
536
+ pl.col('trajectory_popup').sum().alias('pop_up'),
537
+ pl.col('attack_zone').count().alias('attack_zone'),
538
+ pl.col('heart').sum().alias('heart'),
539
+ pl.col('shadow').sum().alias('shadow'),
540
+ pl.col('chase').sum().alias('chase'),
541
+ pl.col('waste').sum().alias('waste'),
542
+ pl.col('heart_swing').sum().alias('heart_swing'),
543
+ pl.col('shadow_swing').sum().alias('shadow_swing'),
544
+ pl.col('chase_swing').sum().alias('chase_swing'),
545
+ pl.col('waste_swing').sum().alias('waste_swing'),
546
+ pl.col('heart_whiff').sum().alias('heart_whiff'),
547
+ pl.col('shadow_whiff').sum().alias('shadow_whiff'),
548
+ pl.col('chase_whiff').sum().alias('chase_whiff'),
549
+ pl.col('waste_whiff').sum().alias('waste_whiff'),
550
+ pl.col('pull').sum().alias('pull'),
551
+ pl.col('straight').sum().alias('straight'),
552
+ pl.col('oppo').sum().alias('oppo'),
553
+ ((pl.col('trajectory_fly_ball') == 1) | (pl.col('trajectory_line_drive') == 1)).sum().alias('fly_line_bip'),
554
+ (pl.col('pull') & ((pl.col('trajectory_fly_ball') == 1) | (pl.col('trajectory_line_drive') == 1))).sum().alias('pull_fly_ball'),
555
+ pl.col('single').sum().alias('single'),
556
+ pl.col('double').sum().alias('double'),
557
+ pl.col('triple').sum().alias('triple'),
558
+ pl.col('tj_stuff_plus').sum().alias('tj_stuff_plus'),
559
+ pl.col('start_speed').sum(),
560
+ pl.col('vb').sum(),
561
+ pl.col('ivb').sum(),
562
+ pl.col('hb').sum(),
563
+ pl.col('release_pos_x').sum(),
564
+ pl.col('release_pos_z').sum(),
565
+ pl.col('vaa').sum(),
566
+ pl.col('haa').sum(),
567
+ pl.col('spin_rate').sum(),
568
+ pl.col('extension').sum(),
569
+ ])
570
+
571
+ # Add calculated columns to the summary DataFrame
572
+ df_summ = df_summ.with_columns([
573
+ (pl.col('hits') / pl.col('ab')).alias('avg'),
574
+ (pl.col('on_base') / pl.col('obp_pa')).alias('obp'),
575
+ (pl.col('tb') / pl.col('ab')).alias('slg'),
576
+ (pl.col('on_base') / pl.col('obp_pa') + pl.col('tb') / pl.col('ab')).alias('ops'),
577
+ (pl.col('k') / pl.col('pa')).alias('k_percent'),
578
+ (pl.col('bb') / pl.col('pa')).alias('bb_percent'),
579
+ (pl.col('bb_minus_k') / pl.col('pa')).alias('bb_minus_k_percent'),
580
+ (pl.col('k_minus_bb') / pl.col('pa')).alias('k_minus_bb_percent'),
581
+ (pl.col('bb') / pl.col('k')).alias('bb_over_k_percent'),
582
+ (pl.col('csw') / pl.col('pitches')).alias('csw_percent'),
583
+ (pl.col('sweet_spot') / pl.col('bip_div')).alias('sweet_spot_percent'),
584
+ (pl.col('woba') / pl.col('woba_codes')).alias('woba_percent'),
585
+ (pl.col('woba_contact') / pl.col('bip')).alias('woba_percent_contact'),
586
+ (pl.col('hard_hit') / pl.col('bip_div')).alias('hard_hit_percent'),
587
+ (pl.col('barrel') / pl.col('bip_div')).alias('barrel_percent'),
588
+ (pl.col('zone_contact') / pl.col('zone_swing')).alias('zone_contact_percent'),
589
+ (pl.col('zone_swing') / pl.col('in_zone')).alias('zone_swing_percent'),
590
+ (pl.col('in_zone') / pl.col('pitches')).alias('zone_percent'),
591
+ (pl.col('ozone_swing') / (pl.col('pitches') - pl.col('in_zone'))).alias('chase_percent'),
592
+ (pl.col('ozone_contact') / pl.col('ozone_swing')).alias('chase_contact'),
593
+ (pl.col('swings') / pl.col('pitches')).alias('swing_percent'),
594
+ (pl.col('whiffs') / pl.col('swings')).alias('whiff_rate'),
595
+ (pl.col('whiffs') / pl.col('pitches')).alias('swstr_rate'),
596
+ (pl.col('ground_ball') / pl.col('bip')).alias('ground_ball_percent'),
597
+ (pl.col('line_drive') / pl.col('bip')).alias('line_drive_percent'),
598
+ (pl.col('fly_ball') / pl.col('bip')).alias('fly_ball_percent'),
599
+ (pl.col('pop_up') / pl.col('bip')).alias('pop_up_percent'),
600
+ (pl.col('heart') / pl.col('attack_zone')).alias('heart_zone_percent'),
601
+ (pl.col('shadow') / pl.col('attack_zone')).alias('shadow_zone_percent'),
602
+ (pl.col('chase') / pl.col('attack_zone')).alias('chase_zone_percent'),
603
+ (pl.col('waste') / pl.col('attack_zone')).alias('waste_zone_percent'),
604
+ (pl.col('heart_swing') / pl.col('heart')).alias('heart_zone_swing_percent'),
605
+ (pl.col('shadow_swing') / pl.col('shadow')).alias('shadow_zone_swing_percent'),
606
+ (pl.col('chase_swing') / pl.col('chase')).alias('chase_zone_swing_percent'),
607
+ (pl.col('waste_swing') / pl.col('waste')).alias('waste_zone_swing_percent'),
608
+ (pl.col('heart_whiff') / pl.col('heart_swing')).alias('heart_zone_whiff_percent'),
609
+ (pl.col('shadow_whiff') / pl.col('shadow_swing')).alias('shadow_zone_whiff_percent'),
610
+ (pl.col('chase_whiff') / pl.col('chase_swing')).alias('chase_zone_whiff_percent'),
611
+ (pl.col('waste_whiff') / pl.col('waste_swing')).alias('waste_zone_whiff_percent'),
612
+ (pl.col('xwoba') / pl.col('xwoba_codes')).alias('xwoba_percent'),
613
+ (pl.col('xwoba_contact') / pl.col('bip')).alias('xwoba_percent_contact'),
614
+ (pl.col('pull') / pl.col('bip')).alias('pull_percent'),
615
+ (pl.col('straight') / pl.col('bip')).alias('straight_percent'),
616
+ (pl.col('oppo') / pl.col('bip')).alias('oppo_percent'),
617
+ (pl.col('pull_fly_ball') / pl.col('fly_line_bip')).alias('pulled_fly_ball_percent'),
618
+ (pl.col('tj_stuff_plus') / pl.col('pitches')).alias('tj_stuff_plus_avg'),
619
+ (pl.col('start_speed')/ pl.col('pitches')).alias('start_speed_avg'),
620
+ (pl.col('vb')/ pl.col('pitches')).alias('vb_avg'),
621
+ (pl.col('ivb')/ pl.col('pitches')).alias('ivb_avg'),
622
+ (pl.col('hb')/ pl.col('pitches')).alias('hb_avg'),
623
+ (pl.col('release_pos_z')/ pl.col('pitches')).alias('x0_avg'),
624
+ (pl.col('release_pos_x')/ pl.col('pitches')).alias('z0_avg'),
625
+ (pl.col('vaa')/ pl.col('pitches')).alias('vaa_avg'),
626
+ (pl.col('haa')/ pl.col('pitches')).alias('haa_avg'),
627
+ (pl.col('spin_rate')/ pl.col('pitches')).alias('spin_rate_avg'),
628
+ (pl.col('extension')/ pl.col('pitches')).alias('extension_avg'),
629
+
630
+ ])
631
+
632
  return df_summ