nesticot commited on
Commit
30629a5
1 Parent(s): 08c7820

Upload 13 files

Browse files
app.py CHANGED
@@ -10,9 +10,9 @@ import shinyswatch
10
  #Import pages
11
  from home import home
12
 
13
- from spray import spray
14
  from decision_value import decision_value
15
- #from damage import damage
16
  from batter_scatter import batter_scatter
17
  #from ev_angle import ev_angle
18
  from rolling_batter import rolling_batter
@@ -30,7 +30,7 @@ routes = [
30
 
31
  Mount('/spray',app=spray),
32
  Mount('/decision_value',app=decision_value),
33
- #Mount('/damage_model',app=damage),
34
  Mount('/batter_scatter',app=batter_scatter),
35
  #Mount('/ev_angle',app=ev_angle),
36
  Mount('/rolling_batter',app=rolling_batter),
 
10
  #Import pages
11
  from home import home
12
 
13
+ from spray_new import spray
14
  from decision_value import decision_value
15
+ from damage import damage
16
  from batter_scatter import batter_scatter
17
  #from ev_angle import ev_angle
18
  from rolling_batter import rolling_batter
 
30
 
31
  Mount('/spray',app=spray),
32
  Mount('/decision_value',app=decision_value),
33
+ Mount('/damage_model',app=damage),
34
  Mount('/batter_scatter',app=batter_scatter),
35
  #Mount('/ev_angle',app=ev_angle),
36
  Mount('/rolling_batter',app=rolling_batter),
batter_scatter.py CHANGED
@@ -406,17 +406,17 @@ batter_scatter = App(ui.page_fluid(
406
  href="rolling_batter/"
407
  ),
408
  ui.a(
409
- "Spray",
410
  href="spray/"
411
  ),
412
  ui.a(
413
  "Decision Value",
414
  href="decision_value/"
415
  ),
416
- ui.a(
417
- "Damage Model",
418
- href="damage_model/"
419
- ),
420
  ui.a(
421
  "Batter Scatter",
422
  href="batter_scatter/"
 
406
  href="rolling_batter/"
407
  ),
408
  ui.a(
409
+ "Spray & Damage",
410
  href="spray/"
411
  ),
412
  ui.a(
413
  "Decision Value",
414
  href="decision_value/"
415
  ),
416
+ # ui.a(
417
+ # "Damage Model",
418
+ # href="damage_model/"
419
+ # ),
420
  ui.a(
421
  "Batter Scatter",
422
  href="batter_scatter/"
decision_value.py CHANGED
@@ -577,17 +577,17 @@ decision_value = App(ui.page_fluid(
577
  href="rolling_batter/"
578
  ),
579
  ui.a(
580
- "Spray",
581
  href="spray/"
582
  ),
583
  ui.a(
584
  "Decision Value",
585
  href="decision_value/"
586
  ),
587
- ui.a(
588
- "Damage Model",
589
- href="damage_model/"
590
- ),
591
  ui.a(
592
  "Batter Scatter",
593
  href="batter_scatter/"
 
577
  href="rolling_batter/"
578
  ),
579
  ui.a(
580
+ "Spray & Damage",
581
  href="spray/"
582
  ),
583
  ui.a(
584
  "Decision Value",
585
  href="decision_value/"
586
  ),
587
+ # ui.a(
588
+ # "Damage Model",
589
+ # href="damage_model/"
590
+ # ),
591
  ui.a(
592
  "Batter Scatter",
593
  href="batter_scatter/"
ev_angle.py CHANGED
@@ -199,25 +199,25 @@ ev_angle = App(ui.page_fluid(
199
  href="rolling_batter/"
200
  ),
201
  ui.a(
202
- "Spray",
203
  href="spray/"
204
  ),
205
  ui.a(
206
  "Decision Value",
207
  href="decision_value/"
208
  ),
209
- ui.a(
210
- "Damage Model",
211
- href="damage_model/"
212
- ),
213
  ui.a(
214
  "Batter Scatter",
215
  href="batter_scatter/"
216
  ),
217
- ui.a(
218
- "EV vs LA Plot",
219
- href="ev_angle/"
220
- ),
221
  ui.a(
222
  "Statcast Compare",
223
  href="statcast_compare/"
 
199
  href="rolling_batter/"
200
  ),
201
  ui.a(
202
+ "Spray & Damage",
203
  href="spray/"
204
  ),
205
  ui.a(
206
  "Decision Value",
207
  href="decision_value/"
208
  ),
209
+ # ui.a(
210
+ # "Damage Model",
211
+ # href="damage_model/"
212
+ # ),
213
  ui.a(
214
  "Batter Scatter",
215
  href="batter_scatter/"
216
  ),
217
+ # ui.a(
218
+ # "EV vs LA Plot",
219
+ # href="ev_angle/"
220
+ # ),
221
  ui.a(
222
  "Statcast Compare",
223
  href="statcast_compare/"
home.py CHANGED
@@ -5,6 +5,7 @@
5
  # Import modules
6
  from shiny import *
7
  import shinyswatch
 
8
  from shinywidgets import output_widget, render_widget
9
  import pandas as pd
10
  from configure import base_url
@@ -43,17 +44,17 @@ home = App(ui.page_fluid(
43
  href="rolling_batter/"
44
  ),
45
  ui.a(
46
- "Spray",
47
  href="spray/"
48
  ),
49
  ui.a(
50
  "Decision Value",
51
  href="decision_value/"
52
  ),
53
- ui.a(
54
- "Damage Model",
55
- href="damage_model/"
56
- ),
57
  ui.a(
58
  "Batter Scatter",
59
  href="batter_scatter/"
 
5
  # Import modules
6
  from shiny import *
7
  import shinyswatch
8
+ #import plotly.express as px
9
  from shinywidgets import output_widget, render_widget
10
  import pandas as pd
11
  from configure import base_url
 
44
  href="rolling_batter/"
45
  ),
46
  ui.a(
47
+ "Spray & Damage",
48
  href="spray/"
49
  ),
50
  ui.a(
51
  "Decision Value",
52
  href="decision_value/"
53
  ),
54
+ # ui.a(
55
+ # "Damage Model",
56
+ # href="damage_model/"
57
+ # ),
58
  ui.a(
59
  "Batter Scatter",
60
  href="batter_scatter/"
pitcher_scatter.py CHANGED
@@ -423,17 +423,17 @@ pitcher_scatter = App(ui.page_fluid(
423
  href="rolling_batter/"
424
  ),
425
  ui.a(
426
- "Spray",
427
  href="spray/"
428
  ),
429
  ui.a(
430
  "Decision Value",
431
  href="decision_value/"
432
  ),
433
- ui.a(
434
- "Damage Model",
435
- href="damage_model/"
436
- ),
437
  ui.a(
438
  "Batter Scatter",
439
  href="batter_scatter/"
 
423
  href="rolling_batter/"
424
  ),
425
  ui.a(
426
+ "Spray & Damage",
427
  href="spray/"
428
  ),
429
  ui.a(
430
  "Decision Value",
431
  href="decision_value/"
432
  ),
433
+ # ui.a(
434
+ # "Damage Model",
435
+ # href="damage_model/"
436
+ # ),
437
  ui.a(
438
  "Batter Scatter",
439
  href="batter_scatter/"
pitching_summary_graphic_new_fg_api.py CHANGED
@@ -2027,17 +2027,17 @@ pitching_summary_graphic_new = App(ui.page_fluid(
2027
  href="rolling_batter/"
2028
  ),
2029
  ui.a(
2030
- "Spray",
2031
  href="spray/"
2032
  ),
2033
  ui.a(
2034
  "Decision Value",
2035
  href="decision_value/"
2036
  ),
2037
- ui.a(
2038
- "Damage Model",
2039
- href="damage_model/"
2040
- ),
2041
  ui.a(
2042
  "Batter Scatter",
2043
  href="batter_scatter/"
 
2027
  href="rolling_batter/"
2028
  ),
2029
  ui.a(
2030
+ "Spray & Damage",
2031
  href="spray/"
2032
  ),
2033
  ui.a(
2034
  "Decision Value",
2035
  href="decision_value/"
2036
  ),
2037
+ # ui.a(
2038
+ # "Damage Model",
2039
+ # href="damage_model/"
2040
+ # ),
2041
  ui.a(
2042
  "Batter Scatter",
2043
  href="batter_scatter/"
rolling_batter.py CHANGED
@@ -673,17 +673,17 @@ rolling_batter = App(ui.page_fluid(
673
  href="rolling_batter/"
674
  ),
675
  ui.a(
676
- "Spray",
677
  href="spray/"
678
  ),
679
  ui.a(
680
  "Decision Value",
681
  href="decision_value/"
682
  ),
683
- ui.a(
684
- "Damage Model",
685
- href="damage_model/"
686
- ),
687
  ui.a(
688
  "Batter Scatter",
689
  href="batter_scatter/"
 
673
  href="rolling_batter/"
674
  ),
675
  ui.a(
676
+ "Spray & Damage",
677
  href="spray/"
678
  ),
679
  ui.a(
680
  "Decision Value",
681
  href="decision_value/"
682
  ),
683
+ # ui.a(
684
+ # "Damage Model",
685
+ # href="damage_model/"
686
+ # ),
687
  ui.a(
688
  "Batter Scatter",
689
  href="batter_scatter/"
rolling_pitcher.py CHANGED
@@ -659,17 +659,17 @@ rolling_pitcher = App(ui.page_fluid(
659
  href="rolling_batter/"
660
  ),
661
  ui.a(
662
- "Spray",
663
  href="spray/"
664
  ),
665
  ui.a(
666
  "Decision Value",
667
  href="decision_value/"
668
  ),
669
- ui.a(
670
- "Damage Model",
671
- href="damage_model/"
672
- ),
673
  ui.a(
674
  "Batter Scatter",
675
  href="batter_scatter/"
 
659
  href="rolling_batter/"
660
  ),
661
  ui.a(
662
+ "Spray & Damage",
663
  href="spray/"
664
  ),
665
  ui.a(
666
  "Decision Value",
667
  href="decision_value/"
668
  ),
669
+ # ui.a(
670
+ # "Damage Model",
671
+ # href="damage_model/"
672
+ # ),
673
  ui.a(
674
  "Batter Scatter",
675
  href="batter_scatter/"
spray_new.py ADDED
@@ -0,0 +1,1047 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##### games.,py #####
2
+
3
+ # Import modules
4
+ from shiny import *
5
+ import shinyswatch
6
+ #import plotly.express as px
7
+ from shinywidgets import output_widget, render_widget
8
+ import pandas as pd
9
+ from configure import base_url
10
+ import math
11
+ import datetime
12
+ import datasets
13
+ from datasets import load_dataset
14
+ import numpy as np
15
+ import matplotlib
16
+ from matplotlib.ticker import MaxNLocator
17
+ from matplotlib.gridspec import GridSpec
18
+ import matplotlib.pyplot as plt
19
+ from scipy.stats import gaussian_kde
20
+ import seaborn as sns
21
+
22
+ ### Import Datasets
23
+ dataset = load_dataset('nesticot/mlb_data', data_files=['mlb_pitch_data_2023.csv',
24
+ 'mlb_pitch_data_2022.csv'])
25
+ dataset_train = dataset['train']
26
+ df_2023 = dataset_train.to_pandas().set_index(list(dataset_train.features.keys())[0]).reset_index(drop=True)
27
+ # Paths to data
28
+ ### Normalize Hit Locations
29
+ df_2023['hit_x'] = df_2023['hit_x'] - 126#df_2023['hit_x'].median()
30
+ df_2023['hit_y'] = -df_2023['hit_y']+204.5#df_2023['hit_y'].quantile(0.9999)
31
+
32
+ df_2023['hit_x_og'] = df_2023['hit_x']
33
+ df_2023.loc[df_2023['batter_hand'] == 'R','hit_x'] = -1*df_2023.loc[df_2023['batter_hand'] == 'R','hit_x']
34
+
35
+ ### Calculate Horizontal Launch Angles
36
+ df_2023['h_la'] = np.arctan(df_2023['hit_x'] / df_2023['hit_y'])*180/np.pi
37
+ conditions_ss = [
38
+ (df_2023['h_la']<-16+5/6),
39
+ (df_2023['h_la']<16+5/6)&(df_2023['h_la']>=-16+5/6),
40
+ (df_2023['h_la']>=16+5/6)
41
+ ]
42
+
43
+ choices_ss = ['Oppo','Straight','Pull']
44
+ df_2023['traj'] = np.select(conditions_ss, choices_ss, default=np.nan)
45
+ df_2023['bip'] = [1 if x > 0 else np.nan for x in df_2023['launch_speed']]
46
+
47
+ conditions_woba = [
48
+ (df_2023['event_type']=='walk'),
49
+ (df_2023['event_type']=='hit_by_pitch'),
50
+ (df_2023['event_type']=='single'),
51
+ (df_2023['event_type']=='double'),
52
+ (df_2023['event_type']=='triple'),
53
+ (df_2023['event_type']=='home_run'),
54
+ ]
55
+
56
+ choices_woba = [1,
57
+ 1,
58
+ 1,
59
+ 2,
60
+ 3,
61
+ 4]
62
+
63
+ choices_woba_train = [1,
64
+ 1,
65
+ 1,
66
+ 2,
67
+ 3,
68
+ 4]
69
+
70
+
71
+ df_2023['woba_train'] = np.select(conditions_woba, choices_woba_train, default=0)
72
+
73
+ conditions = [
74
+ (df_2023['launch_speed'].isna()),
75
+ (df_2023['launch_speed']*1.5 - df_2023['launch_angle'] >= 117 ) & (df_2023['launch_speed'] + df_2023['launch_angle'] >= 124) & (df_2023['launch_speed'] > 98) & (df_2023['launch_angle'] >= 8) & (df_2023['launch_angle'] <= 50)
76
+ ]
77
+
78
+ choices = [False,True]
79
+ df_2023['barrel'] = np.select(conditions, choices, default=np.nan)
80
+
81
+ test_df = df_2023.sort_values(by='batter_name').drop_duplicates(subset='batter_id').reset_index(drop=True)[['batter_id','batter_name']]#['pitcher'].to_dict()
82
+ test_df = test_df.set_index('batter_id')
83
+
84
+ #test_df = test_df[test_df.pitcher == 'Chris Bassitt'].append(test_df[test_df.pitcher != 'Chris Bassitt'])
85
+
86
+ batter_dict = test_df['batter_name'].to_dict()
87
+
88
+ colour_palette = ['#FFB000','#648FFF','#785EF0',
89
+ '#DC267F','#FE6100','#3D1EB2','#894D80','#16AA02','#B5592B','#A3C1ED']
90
+
91
+ angle_ev_list_df = pd.read_csv('angle_ev_list_df.csv')
92
+ ev_ranges = list(np.arange(97.5,130,0.1))
93
+ angle_ranges = list(range(8,51))
94
+
95
+
96
+ df_2023_bip = df_2023[~df_2023['bip'].isnull()].dropna(subset=['h_la','launch_angle'])
97
+ df_2023_bip['h_la'] = df_2023_bip['h_la'].round(0)
98
+
99
+
100
+ df_2023_bip['season'] = df_2023_bip['game_date'].str[0:4].astype(int)
101
+
102
+ #df_2023_bip = df_2023[~df_2023['bip'].isnull()].dropna(subset=['launch_angle','bip'])
103
+ df_2023_bip_train = df_2023_bip[df_2023_bip['season'] == 2023]
104
+
105
+
106
+ features = ['launch_angle','launch_speed','h_la']
107
+ target = ['woba_train']
108
+
109
+ df_2023_bip_train = df_2023_bip_train.dropna(subset=features)
110
+
111
+ import joblib
112
+ # # Dump the model to a file named 'model.joblib'
113
+ model = joblib.load('xtb_model.joblib')
114
+
115
+
116
+ df_2023_bip_train['y_pred'] = [sum(x) for x in model.predict_proba(df_2023_bip_train[features]) * ([0,1,2,3,4])]
117
+ # df_2023_bip_train['y_pred_noh'] = [sum(x) for x in model_noh.predict_proba(df_2023_bip_train[['launch_angle','launch_speed']]) * ([0,0.887,1.253,1.583,2.027])]
118
+
119
+ df_2023_output = df_2023_bip_train.groupby(['batter_id','batter_name']).agg(
120
+ bip = ('y_pred','count'),
121
+ y_pred = ('y_pred','sum'),
122
+ xslgcon = ('y_pred','mean'),
123
+ launch_speed = ('launch_speed','mean'),
124
+ launch_angle_std = ('launch_angle','median'),
125
+ h_la_std = ('h_la','mean'))
126
+
127
+ df_2023_output_copy = df_2023_output.copy()
128
+ # df_2023_output = df_2023_output[df_2023_output['bip'] > 100]
129
+ # df_2023_output[df_2023_output['bip'] > 100].sort_values(by='h_la_std',ascending=True).head(20)
130
+
131
+ import pandas as pd
132
+ import numpy as np
133
+
134
+
135
+ # Create grid coordinates
136
+ x = np.arange(30, 121,1 )
137
+ y = np.arange(-30, 61,1 )
138
+ z = np.arange(-45, 46,1 )
139
+
140
+ # Create a meshgrid
141
+ X, Y, Z = np.meshgrid(x, y, z, indexing='ij')
142
+ # Flatten the meshgrid to get x and y coordinates
143
+ x_flat = X.flatten()
144
+ y_flat = Y.flatten()
145
+ z_flat = Z.flatten()
146
+
147
+ # Create a DataFrame
148
+ df = pd.DataFrame({'launch_speed': x_flat, 'launch_angle': y_flat,'h_la':z_flat})
149
+
150
+ df['y_pred'] = [sum(x) for x in model.predict_proba(df[features]) * ([0,1,2,3,4])]
151
+
152
+
153
+ import matplotlib
154
+
155
+ colour_palette = ['#FFB000','#648FFF','#785EF0',
156
+ '#DC267F','#FE6100','#3D1EB2','#894D80','#16AA02','#B5592B','#A3C1ED']
157
+
158
+ cmap_hue = matplotlib.colors.LinearSegmentedColormap.from_list("", [colour_palette[1],'#ffffff',colour_palette[0]])
159
+ cmap_hue2 = matplotlib.colors.LinearSegmentedColormap.from_list("",['#ffffff',colour_palette[0]])
160
+
161
+
162
+ from matplotlib.pyplot import text
163
+ import inflect
164
+ from scipy.stats import percentileofscore
165
+ p = inflect.engine()
166
+
167
+
168
+ batter_dict = df_2023_bip.sort_values('batter_name').set_index('batter_id')['batter_name'].to_dict()
169
+
170
+
171
+ # def server(input: Inputs, output: Outputs, session: Session):
172
+
173
+ #if input.my_tabs() == '2023 vs MLB':
174
+ #return
175
+ # #if input.my_tabs() == 'Damage Hex':
176
+ # ui.insert_ui(
177
+ # ui.input_numeric("quant",
178
+ # "Select Percentile",
179
+ # value=50,
180
+ # min=0,max=100),
181
+ # selector="#go",
182
+ # where="beforeBegin",
183
+ # ),
184
+ # ui.insert_ui(
185
+ # ui.input_numeric("rolling_window",
186
+ # "Select Rolling Window",
187
+ # value=50,
188
+ # min=1),
189
+ # selector="#go",
190
+ # where="beforeBegin",
191
+ # )
192
+ #return
193
+
194
+ # ui.insert_ui(
195
+ # ui.input_numeric("quant",
196
+ # "Select Percentile",
197
+ # value=50,
198
+ # min=0,max=100),
199
+ # ),
200
+ # ui.insert_ui(
201
+ # ui.input_numeric("rolling_window",
202
+ # "Select Rolling Window",
203
+ # value=50,
204
+ # min=1),
205
+
206
+ # where="beforeEnd",
207
+ # )
208
+ # return
209
+ # if input.my_tabs() == 'Damage Roll':
210
+ # return ui.panel_sidebar(
211
+ # ui.input_select("batter_id",
212
+ # "Select Batter2",
213
+ # batter_dict,
214
+ # width=1,
215
+ # size=1,
216
+ # selectize=True),
217
+ # ui.input_action_button("go", "Generate",class_="btn-primary",
218
+ # )),
219
+ # if input.my_tabs() == 'EV vs LA':
220
+ # return ui.panel_sidebar(
221
+ # ui.input_select("batter_id",
222
+ # "Select Batter3",
223
+ # batter_dict,
224
+ # width=1,
225
+ # size=1,
226
+ # selectize=True),
227
+ # ui.input_action_button("go", "Generate",class_="btn-primary",
228
+ # )),
229
+
230
+
231
+
232
+ def server(input,output,session):
233
+ @reactive.Effect
234
+ @reactive.event(input.update_ui)
235
+ def test():
236
+ if input.my_tabs() == 'Damage Hex':
237
+ ui.remove_ui(selector="div:has(> #quant)")
238
+ ui.remove_ui(selector="div:has(> #rolling_window)")
239
+ ui.remove_ui(selector="div:has(> #plot_id)")
240
+
241
+ ui.insert_ui(
242
+ ui.input_numeric("quant",
243
+ "Select Percentile",
244
+ value=50,
245
+ min=0,max=100),
246
+ selector="#go",
247
+ where="beforeBegin")
248
+ print(input.quant())
249
+
250
+ if input.my_tabs() == 'Damage Roll':
251
+ ui.remove_ui(selector="div:has(> #rolling_window)")
252
+ ui.remove_ui(selector="div:has(> #quant)")
253
+ ui.remove_ui(selector="div:has(> #plot_id)")
254
+
255
+ ui.insert_ui(
256
+ ui.input_numeric("rolling_window",
257
+ "Select Rolling Window",
258
+ value=50,
259
+ min=1),
260
+ selector="#go",
261
+ where="beforeBegin",
262
+ )
263
+
264
+ # if input.my_tabs() == 'EV vs LA':
265
+ # ui.remove_ui(selector="div:has(> #rolling_window)")
266
+ # ui.remove_ui(selector="div:has(> #quant)")
267
+ # ui.remove_ui(selector="div:has(> #plot_id)")
268
+
269
+ # ui.insert_ui(
270
+ # ui.input_select("plot_id", "Select Plot",{'scatter':'Scatter Plot','dist':'Distribution Plot'}),
271
+ # selector="#go",
272
+ # where="beforeBegin",
273
+ # )
274
+
275
+ @output
276
+ @render.plot(alt="plot")
277
+ @reactive.event(input.go, ignore_none=False)
278
+ def plot():
279
+
280
+ batter_id_select = int(input.batter_id())
281
+ df_batter_2023 = df_2023_bip.loc[(df_2023_bip['batter_id'] == batter_id_select)&(df_2023_bip['season']==2023)]
282
+ df_batter_2022 = df_2023_bip.loc[(df_2023_bip['batter_id'] == batter_id_select)&(df_2023_bip['season']==2022)]
283
+
284
+ df_non_batter_2023 = df_2023_bip.loc[(df_2023_bip['batter_id'] != batter_id_select)&(df_2023_bip['season']==2023)]
285
+ df_non_batter_2022 = df_2023_bip.loc[(df_2023_bip['batter_id'] != batter_id_select)&(df_2023_bip['season']==2022)]
286
+
287
+ traj_df = df_batter_2023.groupby(['traj'])['launch_speed'].count() / len(df_batter_2023)
288
+ trajectory_df = df_batter_2023.groupby(['trajectory'])['launch_speed'].count() / len(df_batter_2023)#.loc['Oppo']
289
+
290
+
291
+
292
+
293
+ colour_palette = ['#FFB000','#648FFF','#785EF0',
294
+ '#DC267F','#FE6100','#3D1EB2','#894D80','#16AA02','#B5592B','#A3C1ED']
295
+
296
+ fig = plt.figure(figsize=(10, 10))
297
+
298
+
299
+
300
+ # Create a 2x2 grid of subplots using GridSpec
301
+ gs = GridSpec(3, 3, width_ratios=[0.1,0.8,0.1], height_ratios=[0.1,0.8,0.1])
302
+
303
+ # ax00 = fig.add_subplot(gs[0, 0])
304
+ ax01 = fig.add_subplot(gs[0, :]) # Subplot at the top-right position
305
+ # ax02 = fig.add_subplot(gs[0, 2])
306
+ # Subplot spanning the entire bottom row
307
+ ax10 = fig.add_subplot(gs[1, 0])
308
+ ax11 = fig.add_subplot(gs[1, 1]) # Subplot at the top-right position
309
+ ax12 = fig.add_subplot(gs[1, 2])
310
+ # ax20 = fig.add_subplot(gs[2, 0])
311
+ ax21 = fig.add_subplot(gs[2, :]) # Subplot at the top-right position
312
+ # ax22 = fig.add_subplot(gs[2, 2])
313
+
314
+ initial_position = ax12.get_position()
315
+
316
+ # Change the size of the axis
317
+ # new_width = 0.06 # Set your desired width
318
+ # new_height = 0.4 # Set your desired height
319
+ # new_position = [initial_position.x0-0.01, initial_position.y0+0.065, new_width, new_height]
320
+ # ax12.set_position(new_position)
321
+
322
+ cmap_hue = matplotlib.colors.LinearSegmentedColormap.from_list("", [colour_palette[1],'#ffffff',colour_palette[0]])
323
+ # Generate two sets of two-dimensional data
324
+ # data1 = np.random.multivariate_normal([0, 0], [[1, 0.5], [0.5, 1]], 1000)
325
+ # data2 = np.random.multivariate_normal([3, 3], [[1, -0.5], [-0.5, 1]], 1000)
326
+ bat_hand = df_batter_2023.groupby('batter_hand')['launch_speed'].count().sort_values(ascending=False).index[0]
327
+
328
+ bat_hand_value = 1
329
+
330
+ if bat_hand == 'R':
331
+ bat_hand_value = -1
332
+
333
+ kde1_df = df_batter_2023[['h_la','launch_angle']]
334
+ kde1_df['h_la'] = kde1_df['h_la'] * bat_hand_value
335
+ kde2_df = df_non_batter_2023[['h_la','launch_angle']].sample(n=50000, random_state=42)
336
+ kde2_df['h_la'] = kde2_df['h_la'] * bat_hand_value
337
+
338
+
339
+ # Calculate 2D KDE for each dataset
340
+ kde1 = gaussian_kde(kde1_df.values.T)
341
+ kde2 = gaussian_kde(kde2_df.values.T)
342
+
343
+ # Generate a grid of points for evaluation
344
+ x, y = np.meshgrid(np.arange(-45, 46,1 ), np.arange(-30, 61,1 ))
345
+ positions = np.vstack([x.ravel(), y.ravel()])
346
+
347
+ # Evaluate the KDEs on the grid
348
+ kde1_values = np.reshape(kde1(positions).T, x.shape)
349
+ kde2_values = np.reshape(kde2(positions).T, x.shape)
350
+
351
+ # Subtract one KDE from the other
352
+ result_kde_values = kde1_values - kde2_values
353
+
354
+ # Normalize the array to the range [0, 1]
355
+ # result_kde_values = (result_kde_values - np.min(result_kde_values)) / (np.max(result_kde_values) - np.min(result_kde_values))
356
+ result_kde_values = (result_kde_values - np.mean(result_kde_values)) / (np.std(result_kde_values))
357
+
358
+ result_kde_values = np.clip(result_kde_values, -3, 3)
359
+ # # Plot the original KDEs
360
+ # plt.contourf(x, y, kde1_values, cmap='Blues', alpha=0.5, levels=20)
361
+ # plt.contourf(x, y, kde2_values, cmap='Reds', alpha=0.5, levels=20)
362
+
363
+ # Plot the subtracted KDE
364
+ # Set the number of levels and midrange value
365
+ # Set the number of levels and midrange value
366
+ num_levels = 14
367
+ midrange_value = 0
368
+
369
+ # Create a filled contour plot with specified levels
370
+ levels = np.linspace(-3, 3, num_levels)
371
+
372
+ batter_plot = ax11.contourf(x, y, result_kde_values, cmap=cmap_hue, levels=levels, vmin=-3, vmax=3)
373
+
374
+
375
+ ax11.hlines(y=10,xmin=45,xmax=-45,color=colour_palette[3],linewidth=1)
376
+ ax11.hlines(y=25,xmin=45,xmax=-45,color=colour_palette[3],linewidth=1)
377
+ ax11.hlines(y=50,xmin=45,xmax=-45,color=colour_palette[3],linewidth=1)
378
+
379
+ ax11.vlines(x=-15,ymin=-30,ymax=60,color=colour_palette[3],linewidth=1)
380
+ ax11.vlines(x=15,ymin=-30,ymax=60,color=colour_palette[3],linewidth=1)
381
+ #ax11.axis('square')
382
+ #ax11.axis('off')
383
+ #ax.hlines(y=10,xmin=-45,xmax=-45)
384
+ # Add labels and legend
385
+ #plt.xlabel('X-axis')
386
+ #plt.ylabel('Y-axis')
387
+ #ax.plot('equal')
388
+ #plt.gca().set_aspect('equal')
389
+
390
+ #Choose a mappable (can be any plot or image)
391
+ ax12.set_ylim(0,1)
392
+ cbar = plt.colorbar(batter_plot, cax=ax12, orientation='vertical',shrink=1)
393
+ cbar.set_ticks([])
394
+ # Set the colorbar to have 13 levels
395
+ cbar_locator = MaxNLocator(nbins=13)
396
+ cbar.locator = cbar_locator
397
+ cbar.update_ticks()
398
+ #cbar.set_clim(vmin=-3, vmax=)
399
+ # Set ticks and tick labels
400
+ # cbar.set_ticks(np.linspace(-3, 3, 13))
401
+ # cbar.set_ticklabels(np.linspace(0, 3, 13))
402
+ cbar.set_ticks([])
403
+
404
+
405
+
406
+
407
+ ax10.text(s=f"Pop Up\n({trajectory_df.loc['popup']:.1%})",
408
+ x=1,
409
+ y=0.95,va='center',ha='right',fontsize=16)
410
+ # Choose a mappable (can be any plot or image)
411
+ ax10.text(s=f"Fly Ball\n({trajectory_df.loc['fly_ball']:.1%})",
412
+ x=1,
413
+ y=0.75,va='center',ha='right',fontsize=16)
414
+
415
+ ax10.text(s=f"Line\nDrive\n({trajectory_df.loc['line_drive']:.1%})",
416
+ x=1,
417
+ y=0.53,va='center',ha='right',fontsize=16)
418
+
419
+
420
+ ax10.text(s=f"Ground\nBall\n({trajectory_df.loc['ground_ball']:.1%})",
421
+ x=1,
422
+ y=0.23,va='center',ha='right',fontsize=16)
423
+ #ax12.axis(True)
424
+ # Set equal aspect ratio for the contour plot
425
+
426
+ if bat_hand == 'R':
427
+
428
+
429
+ ax21.text(s=f"Pull\n({traj_df.loc['Pull']:.1%})",
430
+ x=0.2+1/16*0.8,
431
+ y=1,va='top',ha='center',fontsize=16)
432
+
433
+ ax21.text(s=f"Straight\n({traj_df.loc['Straight']:.1%})",
434
+ x=0.5,
435
+ y=1,va='top',ha='center',fontsize=16)
436
+
437
+ ax21.text(s=f"Oppo\n({traj_df.loc['Oppo']:.1%})",
438
+ x=0.8-1/16*0.8,
439
+ y=1,va='top',ha='center',fontsize=16)
440
+
441
+ else:
442
+
443
+ ax21.text(s=f"Pull\n({traj_df.loc['Pull']:.1%})",
444
+ x=0.8-1/16*0.8,
445
+ y=1,va='top',ha='center',fontsize=16)
446
+
447
+ ax21.text(s=f"Straight\n({traj_df.loc['Straight']:.1%})",
448
+ x=0.5,
449
+ y=1,va='top',ha='center',fontsize=16)
450
+
451
+ ax21.text(s=f"Oppo\n({traj_df.loc['Oppo']:.1%})",
452
+ x=0.2+1/16*0.8,
453
+ y=1,va='top',ha='center',fontsize=16)
454
+
455
+ # Define the initial position of the axis
456
+
457
+ # Customize colorbar properties
458
+ # cbar = fig.colorbar(orientation='vertical', pad=0.1,ax=ax12)
459
+ #cbar.set_label('Difference', rotation=270, labelpad=15)
460
+ # Show the plot
461
+ # ax21.text(0.0, 0., "By: Thomas Nestico\n @TJStats",ha='left', va='bottom',fontsize=12)
462
+ # ax21.text(1, 0., "Data: MLB",ha='right', va='bottom',fontsize=12)
463
+ # ax21.text(0.5, 0., "Inspired by @blandalytics",ha='center', va='bottom',fontsize=12)
464
+
465
+ # ax00.axis('off')
466
+ ax01.axis('off')
467
+ # ax02.axis('off')
468
+ ax10.axis('off')
469
+ #ax11.axis('off')
470
+ #ax12.axis('off')
471
+ # ax20.axis('off')
472
+ ax21.axis('off')
473
+ # ax22.axis('off')
474
+
475
+ ax21.text(0.0, 0., "By: Thomas Nestico\n @TJStats",ha='left', va='bottom',fontsize=12)
476
+ ax21.text(0.98, 0., "Data: MLB",ha='right', va='bottom',fontsize=12)
477
+ ax21.text(0.5, 0., "Inspired by @blandalytics",ha='center', va='bottom',fontsize=12)
478
+
479
+
480
+ ax11.set_xticks([])
481
+ ax11.set_yticks([])
482
+
483
+ # ax12.text(s='Same',x=np.mean([x for x in ax12.get_xlim()]),y=np.median([x for x in ax12.get_ylim()]),
484
+ # va='center',ha='center',fontsize=12)
485
+
486
+ # ax12.text(s='More\nOften',x=0.5,y=0.74,
487
+ # va='top',ha='center',fontsize=12)
488
+
489
+ ax12.text(s='+3σ',x=0.5,y=3-1/14*3,
490
+ va='center',ha='center',fontsize=12)
491
+
492
+ ax12.text(s='+2σ',x=0.5,y=2-1/14*2,
493
+ va='center',ha='center',fontsize=12)
494
+
495
+ ax12.text(s='+1σ',x=0.5,y=1-1/14*1,
496
+ va='center',ha='center',fontsize=12)
497
+
498
+
499
+ ax12.text(s='±0σ',x=0.5,y=0,
500
+ va='center',ha='center',fontsize=12)
501
+
502
+ ax12.text(s='-1σ',x=0.5,y=-1-1/14*-1,
503
+ va='center',ha='center',fontsize=12)
504
+
505
+ ax12.text(s='-2σ',x=0.5,y=-2-1/14*-2,
506
+ va='center',ha='center',fontsize=12)
507
+
508
+ ax12.text(s='-3σ',x=0.5,y=-3-1/14*-3,
509
+ va='center',ha='center',fontsize=12)
510
+
511
+ # # ax12.text(s='Less\nOften',x=0.5,y=0.26,
512
+ # # va='bottom',ha='center',fontsize=12)
513
+
514
+ ax01.text(s=f"{df_batter_2023['batter_name'].values[0]}'s 2023 Batted Ball Tendencies",
515
+ x=0.5,
516
+ y=0.8,va='top',ha='center',fontsize=20)
517
+
518
+ ax01.text(s=f"(Compared to rest of MLB)",
519
+ x=0.5,
520
+ y=0.3,va='top',ha='center',fontsize=16)
521
+
522
+ #plt.show()
523
+
524
+ @output
525
+ @render.plot(alt="hex_plot")
526
+ @reactive.event(input.go, ignore_none=False)
527
+ def hex_plot():
528
+
529
+ if input.batter_id() is "":
530
+ fig = plt.figure(figsize=(12, 12))
531
+ fig.text(s='Please Select a Batter',x=0.5,y=0.5)
532
+ return
533
+
534
+ batter_select_id = int(input.batter_id())
535
+ # batter_select_name = 'Edouard Julien'
536
+ quant = int(input.quant())/100
537
+ df_batter_og = df_2023_bip_train[df_2023_bip_train['batter_id']==batter_select_id]
538
+ # df_batter_og = df_2023_bip_train[df_2023_bip_train['batter_name']==batter_select_name]
539
+ df_batter = df_batter_og[df_batter_og['launch_speed'] >= df_batter_og['launch_speed'].quantile(quant)]
540
+ # df_batter_best_speed = df_batter['launch_speed'].mean().round()
541
+
542
+ # df_bip_league = df_2023_bip_train[df_2023_bip_train['launch_speed'] >= df_2023_bip_train['launch_speed'].quantile(quant)]
543
+
544
+ import pandas as pd
545
+ import numpy as np
546
+
547
+
548
+ # Create grid coordinates
549
+ #x = np.arange(30, 121,1 )
550
+ y_b = np.arange(df_batter['launch_angle'].median()-df_batter['launch_angle'].std(),
551
+ df_batter['launch_angle'].median()+df_batter['launch_angle'].std(),1 )
552
+
553
+ z_b = np.arange(df_batter['h_la'].median()-df_batter['h_la'].std(),
554
+ df_batter['h_la'].median()+df_batter['h_la'].std(),1 )
555
+
556
+ # Create a meshgrid
557
+ Y_b, Z_b = np.meshgrid( y_b,z_b, indexing='ij')
558
+ # Flatten the meshgrid to get x and y coordinates
559
+
560
+ y_flat_b = Y_b.flatten()
561
+ z_flat_b = Z_b.flatten()
562
+
563
+ # Create a DataFrame
564
+ df_batter_base = pd.DataFrame({'launch_angle': y_flat_b,'h_la':z_flat_b,'c':[0]*len(y_flat_b)})
565
+
566
+ # df_batter_base['y_pred'] = [sum(x) for x in model.predict_proba(df_batter_base[features]) * ([0,1,2,3,4])]
567
+
568
+ from matplotlib.gridspec import GridSpec
569
+ # fig,ax = plt.subplots(figsize=(12, 12),dpi=150)
570
+ fig = plt.figure(figsize=(12,12))
571
+ gs = GridSpec(4, 3, height_ratios=[0.5,10,1.5,0.2], width_ratios=[0.05,0.9,0.05])
572
+
573
+ axheader = fig.add_subplot(gs[0, :])
574
+ ax10 = fig.add_subplot(gs[1, 0])
575
+ ax = fig.add_subplot(gs[1, 1]) # Subplot at the top-right position
576
+ ax12 = fig.add_subplot(gs[1, 2])
577
+ ax2_ = fig.add_subplot(gs[2, :])
578
+ axfooter1 = fig.add_subplot(gs[-1, :])
579
+
580
+ axheader.axis('off')
581
+ ax10.axis('off')
582
+ ax12.axis('off')
583
+ ax2_.axis('off')
584
+ axfooter1.axis('off')
585
+
586
+
587
+
588
+ extents = [-45,45,-30,60]
589
+
590
+ def hexLines(a=None,i=None,off=[0,0]):
591
+ '''regular hexagon segment lines as `(xy1,xy2)` in clockwise
592
+ order with points in line sorted top to bottom
593
+ for irregular hexagon pass both `a` (vertical) and `i` (horizontal)'''
594
+ if a is None: a = 2 / np.sqrt(3) * i;
595
+ if i is None: i = np.sqrt(3) / 2 * a;
596
+ h = a / 2
597
+ xy = np.array([ [ [ 0, a], [ i, h] ],
598
+ [ [ i, h], [ i,-h] ],
599
+ [ [ i,-h], [ 0,-a] ],
600
+ [ [-i,-h], [ 0,-a] ], #flipped
601
+ [ [-i, h], [-i,-h] ], #flipped
602
+ [ [ 0, a], [-i, h] ] #flipped
603
+ ])
604
+ return xy+off;
605
+
606
+
607
+ h = ax.hexbin(x=df_batter_base['h_la'],
608
+ y=df_batter_base['launch_angle'],
609
+ gridsize=25,
610
+ edgecolors='k',
611
+ extent=extents,mincnt=1,lw=2,zorder=-3,)
612
+
613
+ # cfg = {**cfg,'vmin':h.get_clim()[0], 'vmax':h.get_clim()[1]}
614
+ # plt.hexbin( ec="black" ,lw=6,zorder=4,mincnt=2,**cfg,alpha=0.1)
615
+ # plt.hexbin( ec="#ffffff",lw=1,zorder=5,mincnt=2,**cfg,alpha=0.1)
616
+
617
+
618
+ ax.hexbin(x=df[(df['launch_angle']>=-30)&(df['launch_angle']<=60)&(df['launch_speed']>=df_batter['launch_speed'].median())&(df['launch_speed']<=df_batter['launch_speed'].max())]['h_la'],
619
+ y=df[(df['launch_angle']>=-30)&(df['launch_angle']<=60)&(df['launch_speed']>=df_batter['launch_speed'].median())&(df['launch_speed']<=df_batter['launch_speed'].max())]['launch_angle'],
620
+ C=df[(df['launch_angle']>=-30)&(df['launch_angle']<=60)&(df['launch_speed']>=df_batter['launch_speed'].median())&(df['launch_speed']<=df_batter['launch_speed'].max())]['y_pred'],
621
+ gridsize=25,
622
+ vmin=0,
623
+ vmax=4,
624
+ cmap=cmap_hue2,
625
+ extent=extents,zorder=-3)
626
+
627
+
628
+ # Get the counts and centers of the hexagons
629
+ counts = ax.hexbin(x=df[(df['launch_angle']>=-30)&(df['launch_angle']<=60)&(df['launch_speed']>=df_batter['launch_speed'].median())&(df['launch_speed']<=df_batter['launch_speed'].max())]['h_la'],
630
+ y=df[(df['launch_angle']>=-30)&(df['launch_angle']<=60)&(df['launch_speed']>=df_batter['launch_speed'].median())&(df['launch_speed']<=df_batter['launch_speed'].max())]['launch_angle'],
631
+ C=df[(df['launch_angle']>=-30)&(df['launch_angle']<=60)&(df['launch_speed']>=df_batter['launch_speed'].median())&(df['launch_speed']<=df_batter['launch_speed'].max())]['y_pred'],
632
+ gridsize=25,
633
+ vmin=0,
634
+ vmax=4,
635
+ cmap=cmap_hue2,
636
+ extent=extents).get_array()
637
+
638
+ bin_centers = ax.hexbin(x=df[(df['launch_angle']>=-30)&(df['launch_angle']<=60)&(df['launch_speed']>=df_batter['launch_speed'].median())&(df['launch_speed']<=df_batter['launch_speed'].max())]['h_la'],
639
+ y=df[(df['launch_angle']>=-30)&(df['launch_angle']<=60)&(df['launch_speed']>=df_batter['launch_speed'].median())&(df['launch_speed']<=df_batter['launch_speed'].max())]['launch_angle'],
640
+ C=df[(df['launch_angle']>=-30)&(df['launch_angle']<=60)&(df['launch_speed']>=df_batter['launch_speed'].median())&(df['launch_speed']<=df_batter['launch_speed'].max())]['y_pred'],
641
+ gridsize=25,
642
+ vmin=0,
643
+ vmax=4,
644
+ cmap=cmap_hue2,
645
+ extent=extents).get_offsets()
646
+
647
+ # Add text with the values of "C" to each hexagon
648
+ for count, (x, y) in zip(counts, bin_centers):
649
+ if count >= 1:
650
+ ax.text(x, y, f'{count:.1f}', color='black', ha='center', va='center',fontsize=7)
651
+
652
+
653
+
654
+ #get hexagon centers that should be highlighted
655
+ verts = h.get_offsets()
656
+ cnts = h.get_array()
657
+ highl = verts[cnts > .5*cnts.max()]
658
+
659
+ #create hexagon lines
660
+ a = ((verts[0,1]-verts[1,1])/3).round(6)
661
+ i = ((verts[1:,0]-verts[:-1,0])/2).round(6)
662
+ i = i[i>0][0]
663
+ lines = np.concatenate([hexLines(a,i,off) for off in highl])
664
+
665
+ #select contour lines and draw
666
+ uls,c = np.unique(lines.round(4),axis=0,return_counts=True)
667
+ for l in uls[c==1]: ax.plot(*l.transpose(),'w-',lw=2,scalex=False,scaley=False,color=colour_palette[1],zorder=100)
668
+
669
+
670
+ # Plot filled hexagons
671
+ for hc in highl:
672
+ hx = hc[0] + np.array([0, i, i, 0, -i, -i])
673
+ hy = hc[1] + np.array([a, a/2, -a/2, -a, -a/2, a/2])
674
+ ax.fill(hx, hy, color=colour_palette[1], alpha=0.15, edgecolor=None) # Adjust color and alpha as needed
675
+
676
+ # # Create grid coordinates
677
+ # #x = np.arange(30, 121,1 )
678
+ # y_b = np.arange(df_bip_league['launch_angle'].median()-df_bip_league['launch_angle'].std(),
679
+ # df_bip_league['launch_angle'].median()+df_bip_league['launch_angle'].std(),1 )
680
+
681
+ # z_b = np.arange(df_bip_league['h_la'].median()-df_bip_league['h_la'].std(),
682
+ # df_bip_league['h_la'].median()+df_bip_league['h_la'].std(),1 )
683
+
684
+ # # Create a meshgrid
685
+ # Y_b, Z_b = np.meshgrid( y_b,z_b, indexing='ij')
686
+ # # Flatten the meshgrid to get x and y coordinates
687
+
688
+ # y_flat_b = Y_b.flatten()
689
+ # z_flat_b = Z_b.flatten()
690
+
691
+ # # Create a DataFrame
692
+ # df_league_base = pd.DataFrame({'launch_angle': y_flat_b,'h_la':z_flat_b,'c':[0]*len(y_flat_b)})
693
+
694
+ # h_league = ax.hexbin(x=df_league_base['h_la'],
695
+ # y=df_league_base['launch_angle'],
696
+ # gridsize=25,
697
+ # edgecolors=colour_palette[1],
698
+ # extent=extents,mincnt=1,lw=2,zorder=-3,)
699
+
700
+ # #get hexagon centers that should be highlighted
701
+ # verts = h_league.get_offsets()
702
+ # cnts = h_league.get_array()
703
+ # highl = verts[cnts > .5*cnts.max()]
704
+
705
+ # #create hexagon lines
706
+ # a = ((verts[0,1]-verts[1,1])/3).round(6)
707
+ # i = ((verts[1:,0]-verts[:-1,0])/2).round(6)
708
+ # i = i[i>0][0]
709
+ # lines = np.concatenate([hexLines(a,i,off) for off in highl])
710
+
711
+ # #select contour lines and draw
712
+ # uls,c = np.unique(lines.round(4),axis=0,return_counts=True)
713
+ # for l in uls[c==1]: ax.plot(*l.transpose(),'w-',lw=2,scalex=False,scaley=False,color=colour_palette[3],zorder=99)
714
+
715
+
716
+ axheader.text(s=f"{df_batter['batter_name'].values[0]} - {int(quant*100)}th% EV and Greater Batted Ball Tendencies",x=0.5,y=0.2,fontsize=20,ha='center',va='bottom')
717
+ axheader.text(s=f"2023 Season",x=0.5,y=-0.1,fontsize=14,ha='center',va='top')
718
+
719
+ ax.set_xlabel(f"Horizontal Spray Angle (°)",fontsize=12)
720
+ ax.set_ylabel(f"Vertical Launch Angle (°)",fontsize=12)
721
+
722
+ ax2_.text(x=0.5,
723
+ y=0.0,
724
+
725
+ s="Notes:\n" \
726
+ f"- {int(quant*100)}th% EV and Greater BBE is defined as a batter's top {100 - int(quant*100)}% hardest hit BBE\n" \
727
+ f"- Colour Scale and Number Labels Represents the Expected Total Bases for a batter's range of Best Speeds\n" \
728
+ f"- Shaded Area Represents the 2-D Region bounded by ±1σ Launch Angle and Horizontal Spray Angle on batter's Best Speed BBE\n"\
729
+ f"- {df_batter['batter_name'].values[0]} {int(quant*100)}th% EV and Greater BBE Range from {df_batter['launch_speed'].min():.0f} to {df_batter['launch_speed'].max():.0f} mph ({len(df_batter)} BBE)\n"\
730
+ f"- Positive Horizontal Spray Angle Represents a BBE hit in same direction as batter handedness (i.e. Pulled)" ,
731
+
732
+ fontsize=11,
733
+ fontstyle='oblique',
734
+ va='bottom',
735
+ ha='center',
736
+ bbox=dict(facecolor='white', edgecolor='black'),ma='left')
737
+
738
+ axfooter1.text(0.05, 0.5, "By: Thomas Nestico\n @TJStats",ha='left', va='bottom',fontsize=12)
739
+ axfooter1.text(0.95, 0.5, "Data: MLB",ha='right', va='bottom',fontsize=12)
740
+
741
+ if df_batter['batter_hand'].values[0] == 'R':
742
+ ax.invert_xaxis()
743
+ ax.grid(False)
744
+ ax.axis('equal')
745
+ # Adjusting subplot to center it within the figure
746
+ fig.subplots_adjust(left=0.01, right=0.99, top=0.975, bottom=0.025)
747
+
748
+ #ax.text(f"Vertical Spray Angle (°)")
749
+
750
+
751
+ @output
752
+ @render.plot(alt="roll_plot")
753
+ @reactive.event(input.go, ignore_none=False)
754
+ def roll_plot():
755
+ # player_select = 'Nolan Gorman'
756
+ # player_select_full =player_select
757
+
758
+ if input.batter_id() is "":
759
+ fig = plt.figure(figsize=(12, 12))
760
+ fig.text(s='Please Select a Batter',x=0.5,y=0.5)
761
+ return
762
+
763
+ # df_will = df_model_2023[df_model_2023.batter_name == player_select].sort_values(by=['game_date','start_time'])
764
+ # df_will = df_will[df_will['is_swing'] != 1]
765
+ batter_select_id = int(input.batter_id())
766
+ # batter_select_name = 'Edouard Julien'
767
+ df_batter_og = df_2023_bip_train[df_2023_bip_train['batter_id']==batter_select_id]
768
+ batter_select_name = df_batter_og['batter_name'].values[0]
769
+ win = min(int(input.rolling_window()),len(df_batter_og))
770
+ df_2023_output = df_2023_output_copy[df_2023_output_copy['bip'] >= win]
771
+ sns.set_theme(style="whitegrid", palette="pastel")
772
+ #fig, ax = plt.subplots(1, 1, figsize=(10, 10),dpi=300)
773
+
774
+ from matplotlib.gridspec import GridSpec
775
+ # fig,ax = plt.subplots(figsize=(12, 12),dpi=150)
776
+ fig = plt.figure(figsize=(12,12))
777
+ gs = GridSpec(3, 3, height_ratios=[0.3,10,0.2], width_ratios=[0.01,2,0.01])
778
+
779
+ axheader = fig.add_subplot(gs[0, :])
780
+ ax10 = fig.add_subplot(gs[1, 0])
781
+ ax = fig.add_subplot(gs[1, 1]) # Subplot at the top-right position
782
+ ax12 = fig.add_subplot(gs[1, 2])
783
+ axfooter1 = fig.add_subplot(gs[-1, :])
784
+
785
+ axheader.axis('off')
786
+ ax10.axis('off')
787
+ ax12.axis('off')
788
+ axfooter1.axis('off')
789
+
790
+
791
+ sns.lineplot( x= range(win,len(df_batter_og.y_pred.rolling(window=win).mean())+1),
792
+ y= df_batter_og.y_pred.rolling(window=win).mean().dropna(),
793
+ color=colour_palette[0],linewidth=2,ax=ax)
794
+
795
+ ax.hlines(y=df_batter_og.y_pred.mean(),xmin=win,xmax=len(df_batter_og),color=colour_palette[0],linestyle='--',
796
+ label=f'{batter_select_name} Average: {df_batter_og.y_pred.mean():.3f} xSLGCON ({p.ordinal(int(np.around(percentileofscore(df_2023_output["xslgcon"],df_batter_og.y_pred.mean(), kind="strict"))))} Percentile)')
797
+
798
+ # ax.hlines(y=df_model_2023.y_pred_no_swing.std()*100,xmin=win,xmax=len(df_will))
799
+
800
+ # sns.scatterplot( x= [976],
801
+ # y= df_will.y_pred.rolling(window=win).mean().min()*100,
802
+ # color=colour_palette[0],linewidth=2,ax=ax,zorder=100,s=100,edgecolor=colour_palette[7])
803
+
804
+
805
+ ax.hlines(y=df_2023_bip_train['y_pred'].mean(),xmin=win,xmax=len(df_batter_og),color=colour_palette[1],linestyle='-.',alpha=1,
806
+ label = f'MLB Average: {df_2023_bip_train["y_pred"].mean():.3f} xSLGCON')
807
+
808
+ ax.legend()
809
+
810
+ hard_hit_dates = [df_2023_output['xslgcon'].quantile(0.9),
811
+ df_2023_output['xslgcon'].quantile(0.75),
812
+ df_2023_output['xslgcon'].quantile(0.25),
813
+ df_2023_output['xslgcon'].quantile(0.1)]
814
+
815
+
816
+
817
+ ax.hlines(y=df_2023_output['xslgcon'].quantile(0.9),xmin=win,xmax=len(df_batter_og),color=colour_palette[2],linestyle='dotted',alpha=0.5,zorder=1)
818
+ ax.hlines(y=df_2023_output['xslgcon'].quantile(0.75),xmin=win,xmax=len(df_batter_og),color=colour_palette[3],linestyle='dotted',alpha=0.5,zorder=1)
819
+ ax.hlines(y=df_2023_output['xslgcon'].quantile(0.25),xmin=win,xmax=len(df_batter_og),color=colour_palette[4],linestyle='dotted',alpha=0.5,zorder=1)
820
+ ax.hlines(y=df_2023_output['xslgcon'].quantile(0.1),xmin=win,xmax=len(df_batter_og),color=colour_palette[5],linestyle='dotted',alpha=0.5,zorder=1)
821
+
822
+ hard_hit_text = ['90th %','75th %','25th %','10th %']
823
+ for i, x in enumerate(hard_hit_dates):
824
+ ax.text(min(win+win/50,win+win+5), x ,hard_hit_text[i], rotation=0,va='center', ha='left',
825
+ bbox=dict(facecolor='white',alpha=0.7, edgecolor=colour_palette[2+i], pad=2),zorder=11)
826
+
827
+ # # Annotate with an arrow
828
+ # ax.annotate('June 6, 2023\nSeason Worst Decision Value', xy=(976, df_will.y_pred.rolling(window=win).mean().min()*100-0.03),
829
+ # xytext=(976 - 150, df_will.y_pred.rolling(window=win).mean().min()*100 - 0.2),
830
+ # arrowprops=dict(facecolor=colour_palette[7], shrink=0.01),zorder=150,fontsize=10,
831
+ # bbox=dict(facecolor='white', edgecolor='black'),va='top')
832
+
833
+ ax.set_xlim(win,len(df_batter_og))
834
+ # ax.set_ylim(0.2,max(1,))
835
+
836
+ ax.set_yticks([0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1])
837
+
838
+ ax.set_xlabel('Balls In Play')
839
+ ax.set_ylabel('Expected Total Bases per Ball In Play (xSLGCON)')
840
+
841
+ from matplotlib.ticker import FormatStrFormatter
842
+
843
+ ax.yaxis.set_major_formatter(FormatStrFormatter('%.3f'))
844
+
845
+ axheader.text(s=f'{batter_select_name} - MLB - {win} Rolling BIP Expected Slugging on Contact (xSLGCON)',x=0.5,y=-0.5,ha='center',va='bottom',fontsize=14)
846
+ axfooter1.text(.05, 0.2, "By: Thomas Nestico",ha='left', va='bottom',fontsize=12)
847
+ axfooter1.text(0.95, 0.2, "Data: MLB",ha='right', va='bottom',fontsize=12)
848
+
849
+ fig.subplots_adjust(left=0.01, right=0.99, top=0.98, bottom=0.02)
850
+
851
+ @output
852
+ @render.plot(alt="A histogram")
853
+ @reactive.event(input.go, ignore_none=False)
854
+ def ev_plot():
855
+ data_df = df_2023_bip_train[df_2023_bip_train.batter_id==int(input.batter_id())]
856
+ #pitch_list = df_2023_small.pitch_type.unique()
857
+ sns.set_theme(style="whitegrid", palette="pastel")
858
+ fig, ax = plt.subplots(1, 1, figsize=(10, 10))
859
+
860
+
861
+
862
+ # if input.plot_id() == 'dist':
863
+ # sns.histplot(x=data_df.launch_angle,y=data_df.launch_speed,cbar=colour_palette,binwidth=(5,2.5),ax=ax,cbar_kws=dict(shrink=.75,label='Count'),binrange=(
864
+ # (math.floor((min(data_df.launch_angle.dropna())/5))*5,math.ceil((max(data_df.launch_angle.dropna())/5))*5),(math.floor((min(data_df.launch_speed.dropna())/5))*5,math.ceil((max(data_df.launch_speed.dropna())/5))*5)))
865
+
866
+ sns.scatterplot(x=data_df.launch_angle,y=data_df.launch_speed,color=colour_palette[1])
867
+ ax.set_xlim(math.floor((min(data_df.launch_angle.dropna())/10))*10,math.ceil((max(data_df.launch_angle.dropna())/10))*10)
868
+ #ticks=np.arange(revels.values.min(),revels.values.max()+1 )
869
+ sns.lineplot(x=angle_ev_list_df.launch_angle,y=angle_ev_list_df.launch_speed,color=colour_palette[0])
870
+ ax.vlines(x=angle_ev_list_df.launch_angle[0],ymin=angle_ev_list_df.launch_speed[0],ymax=ev_ranges[-1],color=colour_palette[0])
871
+ ax.vlines(x=angle_ev_list_df.launch_angle[len(angle_ev_list_df)-1],ymin=angle_ev_list_df.launch_speed[len(angle_ev_list_df)-1],ymax=ev_ranges[-1],color=colour_palette[0])
872
+
873
+ groundball = f'{sum(data_df.launch_angle.dropna()<=10)/len(data_df.launch_angle.dropna()):.1%}'
874
+ linedrive = f'{sum((data_df.launch_angle.dropna()<=25) & (data_df.launch_angle.dropna()>10))/len(data_df.launch_angle.dropna()):.1%}'
875
+ flyball = f'{sum((data_df.launch_angle.dropna()<=50) & (data_df.launch_angle.dropna()>25))/len(data_df.launch_angle.dropna()):.1%}'
876
+ popup = f'{sum(data_df.launch_angle.dropna()>50)/len(data_df.launch_angle.dropna()):.1%}'
877
+ percentages_list = [groundball,linedrive,flyball,popup]
878
+
879
+ hard_hit_percent = f'{sum(data_df.launch_speed.dropna()>=95)/len(data_df.launch_speed.dropna()):.1%}'
880
+
881
+ barrel_percentage = f'{data_df.barrel.dropna().sum()/len(data_df.launch_angle.dropna()):.1%}'
882
+
883
+ plt.text(x=27, y=math.ceil((max(data_df.launch_speed.dropna())/5))*5+5-3, s=f'Barrel% {barrel_percentage}',ha='left',bbox=dict(facecolor='white',alpha=0.8, edgecolor=colour_palette[4], pad=5))
884
+
885
+
886
+ sample_dates = np.array([math.floor((min(data_df.launch_angle.dropna())/10))*10,10,25,50])
887
+ sample_text = [f'Groundball ({groundball})',f'Line Drive ({linedrive})',f'Fly Ball ({flyball})',f'Pop-up ({popup})']
888
+
889
+ hard_hit_dates = [95]
890
+ hard_hit_text = [f'Hard Hit% ({hard_hit_percent})']
891
+
892
+
893
+
894
+ #sample_dates = mdates.date2num(sample_dates)
895
+ plt.hlines(y=hard_hit_dates,xmin=math.floor((min(data_df.launch_angle.dropna())/10))*10, xmax=math.ceil((max(data_df.launch_angle.dropna())/10))*10, color = colour_palette[4],linestyles='--')
896
+ plt.vlines(x=sample_dates, ymin=0, ymax=130, color = colour_palette[3],linestyles='--')
897
+
898
+
899
+ # ax.vlines(x=10,ymin=0,ymax=ev_ranges[-1],color=colour_palette[3],linestyles='--')
900
+ # ax.vlines(x=25,ymin=0,ymax=ev_ranges[-1],color=colour_palette[3],linestyles='--')
901
+ # ax.vlines(x=50,ymin=0,ymax=ev_ranges[-1],color=colour_palette[3],linestyles='--')
902
+
903
+
904
+
905
+ for i, x in enumerate(hard_hit_dates):
906
+ text(math.ceil((max(data_df.launch_angle.dropna())/10))*10-2.5, x+1.25,hard_hit_text[i], rotation=0, ha='right',
907
+ bbox=dict(facecolor='white',alpha=0.5, edgecolor=colour_palette[4], pad=5))
908
+
909
+
910
+ for i, x in enumerate(sample_dates):
911
+ text(x+0.75, (math.floor((min(data_df.launch_speed.dropna())/5))*5)+1,sample_text[i], rotation=90, verticalalignment='bottom',
912
+ bbox=dict(facecolor='white',alpha=0.5, edgecolor=colour_palette[3], pad=5))
913
+ #ax.vlines(x=math.floor((min(data_df.launch_angle.dropna())/10))*10+1,ymin=0,ymax=ev_ranges[-1],color=colour_palette[3],linestyles='--')
914
+
915
+ ax.set_xlim((math.floor((min(data_df.launch_angle.dropna())/10))*10,math.ceil((max(data_df.launch_angle.dropna())/10))*10))
916
+ ax.set_ylim((math.floor((min(data_df.launch_speed.dropna())/5))*5,math.ceil((max(data_df.launch_speed.dropna())/5))*5+5))
917
+ # ax.set_xlim(-90,90)
918
+ # ax.set_ylim(0,125)
919
+ ax.set_title(f'MLB - {data_df.batter_name.unique()[0]} Launch Angle vs EV Plot', fontsize=18,fontname='Century Gothic',)
920
+ #vals = ax.get_yticks()
921
+ ax.set_xlabel('Launch Angle', fontsize=16,fontname='Century Gothic')
922
+ ax.set_ylabel('Exit Velocity', fontsize=16,fontname='Century Gothic')
923
+ ax.fill_between(angle_ev_list_df.launch_angle, 130, angle_ev_list_df.launch_speed, interpolate=True, color=colour_palette[3],alpha=0.1,label='Barrel')
924
+ #fig.colorbar(plot_dist, ax=ax)
925
+ #fig.colorbar(plot_dist)
926
+ #fig.axes[0].invert_yaxis()
927
+ ax.legend(fontsize='16',loc='upper left')
928
+ fig.text(x=0.03,y=0.02,s='By: @TJStats')
929
+ fig.text(x=1-0.03,y=0.02,s='Data: MLB',ha='right')
930
+
931
+ # fig.text(x=0.25,y=0.02,s='Data: MLB',ha='right')
932
+ # fig.text(x=0.25,y=0.02,s='Data: MLB',ha='right')
933
+ # fig.text(x=0.25,y=0.02,s='Data: MLB',ha='right')
934
+ #cbar = plt.colorbar()
935
+ #fig.subplots_adjust(wspace=.02, hspace=.02)
936
+ #ax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: int(x)))
937
+ fig.set_facecolor('white')
938
+ fig.tight_layout()
939
+
940
+ spray = App(ui.page_fluid(
941
+ ui.tags.base(href=base_url),
942
+ ui.tags.div(
943
+ {"style": "width:90%;margin: 0 auto;max-width: 1600px;"},
944
+ ui.tags.style(
945
+ """
946
+ h4 {
947
+ margin-top: 1em;font-size:35px;
948
+ }
949
+ h2{
950
+ font-size:25px;
951
+ }
952
+ """
953
+ ),
954
+ shinyswatch.theme.simplex(),
955
+ ui.tags.h4("TJStats"),
956
+ ui.tags.i("Baseball Analytics and Visualizations"),
957
+ ui.markdown("""<a href='https://www.patreon.com/tj_stats'>Support me on Patreon for Access to 2024 Apps</a><sup>1</sup>"""),
958
+ ui.navset_tab(
959
+ ui.nav_control(
960
+ ui.a(
961
+ "Home",
962
+ href="home/"
963
+ ),
964
+ ),
965
+ ui.nav_menu(
966
+ "Batter Charts",
967
+ ui.nav_control(
968
+ ui.a(
969
+ "Batting Rolling",
970
+ href="rolling_batter/"
971
+ ),
972
+ ui.a(
973
+ "Spray & Damage",
974
+ href="spray/"
975
+ ),
976
+ ui.a(
977
+ "Decision Value",
978
+ href="decision_value/"
979
+ ),
980
+ # ui.a(
981
+ # "Damage Model",
982
+ # href="damage_model/"
983
+ # ),
984
+ ui.a(
985
+ "Batter Scatter",
986
+ href="batter_scatter/"
987
+ ),
988
+ # ui.a(
989
+ # "EV vs LA Plot",
990
+ # href="ev_angle/"
991
+ # ),
992
+ ui.a(
993
+ "Statcast Compare",
994
+ href="statcast_compare/"
995
+ )
996
+ ),
997
+ ),
998
+ ui.nav_menu(
999
+ "Pitcher Charts",
1000
+ ui.nav_control(
1001
+ ui.a(
1002
+ "Pitcher Rolling",
1003
+ href="rolling_pitcher/"
1004
+ ),
1005
+ ui.a(
1006
+ "Pitcher Summary",
1007
+ href="pitching_summary_graphic_new/"
1008
+ ),
1009
+ ui.a(
1010
+ "Pitcher Scatter",
1011
+ href="pitcher_scatter/"
1012
+ )
1013
+ ),
1014
+ )),ui.row(
1015
+ ui.layout_sidebar(
1016
+
1017
+ ui.panel_sidebar(
1018
+ ui.input_select("batter_id",
1019
+ "Select Batter",
1020
+ batter_dict,
1021
+ width=1,
1022
+ size=1,
1023
+ selectize=True),
1024
+ ui.input_action_button("go", "Generate",class_="btn-primary",
1025
+ ),
1026
+ ui.input_action_button("update_ui", "Update UI",class_="btn-secondary",
1027
+ )),
1028
+
1029
+ ui.page_navbar(
1030
+
1031
+
1032
+ ui.nav("2023 vs MLB",
1033
+ ui.output_plot('plot',
1034
+ width='1000px',
1035
+ height='1000px')),
1036
+ ui.nav("Damage Hex",
1037
+ ui.output_plot('hex_plot',
1038
+ width='1200px',
1039
+ height='1200px')),
1040
+ ui.nav("Damage Roll",
1041
+ ui.output_plot('roll_plot',
1042
+ width='1200px',
1043
+ height='1200px')),
1044
+ ui.nav("EV vs LA",
1045
+ ui.output_plot("ev_plot",height = "1000px",width="1000px")),id="my_tabs",
1046
+ )
1047
+ )),)),server)
statcast_compare.py CHANGED
@@ -609,17 +609,17 @@ statcast_compare = App(ui.page_fluid(
609
  href="rolling_batter/"
610
  ),
611
  ui.a(
612
- "Spray",
613
  href="spray/"
614
  ),
615
  ui.a(
616
  "Decision Value",
617
  href="decision_value/"
618
  ),
619
- ui.a(
620
- "Damage Model",
621
- href="damage_model/"
622
- ),
623
  ui.a(
624
  "Batter Scatter",
625
  href="batter_scatter/"
 
609
  href="rolling_batter/"
610
  ),
611
  ui.a(
612
+ "Spray & Damage",
613
  href="spray/"
614
  ),
615
  ui.a(
616
  "Decision Value",
617
  href="decision_value/"
618
  ),
619
+ # ui.a(
620
+ # "Damage Model",
621
+ # href="damage_model/"
622
+ # ),
623
  ui.a(
624
  "Batter Scatter",
625
  href="batter_scatter/"