DaveM2430 commited on
Commit
5e8d833
Β·
verified Β·
1 Parent(s): f870466

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +127 -4
app.R CHANGED
@@ -4,6 +4,8 @@ library(arrow)
4
  library(DT)
5
  library(ggplot2)
6
  library(shinyjs)
 
 
7
 
8
  # ── Load data ──────────────────────────────────────────────────────────────────
9
  load_data <- function(level) {
@@ -11,6 +13,12 @@ load_data <- function(level) {
11
  arrow::read_parquet(path)
12
  }
13
 
 
 
 
 
 
 
14
  # ── Pitch colors ───────────────────────────────────────────────────────────────
15
  pitch_colors <- c(
16
  "Fastball" = "red", "Sinker" = "orange",
@@ -33,6 +41,112 @@ clean_pitch_type <- function(pt) {
33
  )
34
  }
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  # ── Pitcher stats ──────────────────────────────────────────────────────────────
37
  build_pitcher_stats <- function(df, min_pitches) {
38
 
@@ -94,6 +208,15 @@ build_pitcher_stats <- function(df, min_pitches) {
94
  .groups = "drop"
95
  ) %>%
96
  left_join(team_lookup, by="Pitcher") %>%
 
 
 
 
 
 
 
 
 
97
  filter(Pitches >= min_pitches) %>%
98
  mutate(
99
  Name = sapply(Pitcher, format_name),
@@ -131,7 +254,7 @@ build_pitcher_stats <- function(df, min_pitches) {
131
  ) %>%
132
  select(Name, Level, Team, Pitches, `FB Velo`, `Zone%`, `Strike%`,
133
  `K's`, `BB's`, `K/BB`, `Whiff%`, `Chase%`, `Hard Hit%`,
134
- `Plot`, `Twitter`) %>%
135
  arrange(desc(Pitches))
136
  }
137
 
@@ -390,9 +513,9 @@ server <- function(input, output, session) {
390
  dom = "lfrtip",
391
  columnDefs = list(
392
  list(className = "dt-left", targets = 0:1),
393
- list(className = "dt-center", targets = 2:14),
394
- list(orderable = FALSE, targets = c(13, 14))
395
- ),
396
  initComplete = JS("function(settings, json) {
397
  $('#loading_msg').hide();
398
  }")
 
4
  library(DT)
5
  library(ggplot2)
6
  library(shinyjs)
7
+ library(tidymodels)
8
+ library(xgboost)
9
 
10
  # ── Load data ──────────────────────────────────────────────────────────────────
11
  load_data <- function(level) {
 
13
  arrow::read_parquet(path)
14
  }
15
 
16
+ # ── Models ─────────────────────────────────────────────────────────────────────
17
+ model <- readRDS("/app/Stuff+2.rds")
18
+ league_stats <- readRDS("/app/NEW_LeagueStats2.rds")
19
+ xgb_fit <- readRDS("/app/location_plus_model.rds")
20
+ league_stats_pitcher <- readRDS("/app/location_plus_league_stats_pitcher.rds")
21
+
22
  # ── Pitch colors ───────────────────────────────────────────────────────────────
23
  pitch_colors <- c(
24
  "Fastball" = "red", "Sinker" = "orange",
 
41
  )
42
  }
43
 
44
+ # ── Pitch type mapper ──────────────────────────────────────────────────────────
45
+ map_pitch_type <- function(pt) {
46
+ case_when(
47
+ pt %in% c("Fastball","FourSeamFastBall","Four-Seam","FourSeam") ~ "Fastball",
48
+ pt %in% c("Sinker","TwoSeamFastBall","OneSeamFastball") ~ "Sinker",
49
+ pt == "Cutter" ~ "Cutter",
50
+ pt %in% c("Curveball","CurveBall") ~ "Curveball",
51
+ pt == "Slider" ~ "Slider",
52
+ pt == "Sweeper" ~ "Sweeper",
53
+ pt %in% c("ChangeUp","Changeup") ~ "Changeup",
54
+ pt == "Splitter" ~ "Splitter",
55
+ TRUE ~ NA_character_
56
+ )
57
+ }
58
+
59
+ # ── Stuff+ ─────────────────────────────────────────────────────────────────────
60
+ compute_stuff_plus <- function(data) {
61
+ fb_avgs <- data %>%
62
+ filter(TaggedPitchType %in% c("Fastball","FourSeamFastBall","Four-Seam","FourSeam",
63
+ "Sinker","TwoSeamFastBall","OneSeamFastball","Cutter")) %>%
64
+ mutate(
65
+ PitcherId = as.character(PitcherId),
66
+ priority = case_when(
67
+ TaggedPitchType %in% c("Fastball","FourSeamFastBall","Four-Seam","FourSeam") ~ 1,
68
+ TaggedPitchType %in% c("Sinker","TwoSeamFastBall","OneSeamFastball") ~ 2,
69
+ TaggedPitchType == "Cutter" ~ 3
70
+ )
71
+ ) %>%
72
+ group_by(PitcherId, priority) %>%
73
+ summarize(count=n(), fb_velo=mean(RelSpeed,na.rm=TRUE),
74
+ fb_ivb=mean(InducedVertBreak,na.rm=TRUE),
75
+ fb_hb=mean(HorzBreak,na.rm=TRUE), .groups="drop") %>%
76
+ arrange(PitcherId, priority, desc(count)) %>%
77
+ slice_head(by=PitcherId, n=1) %>%
78
+ select(PitcherId, PrimaryFB=priority, fb_velo, fb_ivb, fb_hb) %>%
79
+ mutate(PrimaryFB=case_when(
80
+ PrimaryFB==1 ~ "Fastball", PrimaryFB==2 ~ "Sinker", PrimaryFB==3 ~ "Cutter"
81
+ ))
82
+
83
+ if (nrow(fb_avgs)==0) return(tibble(Pitcher=character(), `Stuff+`=numeric()))
84
+
85
+ scored <- data %>%
86
+ mutate(PitcherId=as.character(PitcherId),
87
+ PitchType=map_pitch_type(TaggedPitchType)) %>%
88
+ filter(!is.na(PitchType)) %>%
89
+ left_join(fb_avgs, by="PitcherId") %>%
90
+ mutate(
91
+ FF_diff = ifelse(PitchType==PrimaryFB, 0, RelSpeed-fb_velo),
92
+ IVB_diff = ifelse(PitchType==PrimaryFB, 0, InducedVertBreak-fb_ivb),
93
+ HB_diff = ifelse(PitchType==PrimaryFB, 0, HorzBreak-fb_hb),
94
+ SameSide = as.factor(ifelse(BatterSide==PitcherThrows, 1, 0)),
95
+ PitchType= as.factor(PitchType)
96
+ ) %>%
97
+ filter(!is.na(InducedVertBreak), !is.na(RelSide), !is.na(HorzBreak),
98
+ !is.na(SpinRate), !is.na(Extension), !is.na(RelHeight),
99
+ !is.na(RelSpeed), !is.na(SameSide))
100
+
101
+ if (nrow(scored)==0) return(tibble(Pitcher=character(), `Stuff+`=numeric()))
102
+
103
+ scored %>%
104
+ bind_cols(suppressWarnings(predict(model, scored, type="prob"))) %>%
105
+ rename(expected_whiff=.pred_1) %>%
106
+ group_by(Pitcher, PitchType) %>%
107
+ summarise(expected_whiff_rate=mean(expected_whiff), .groups="drop") %>%
108
+ left_join(league_stats, by="PitchType") %>%
109
+ group_by(Pitcher) %>%
110
+ summarise(
111
+ `Stuff+` = round(weighted.mean(
112
+ ((expected_whiff_rate - league_avg) / league_sd) * 10 + 100,
113
+ w = rep(1, n()), na.rm=TRUE), 0),
114
+ .groups="drop"
115
+ )
116
+ }
117
+
118
+ # ── Location+ ��─────────────────────────────────────────────────────────────────
119
+ compute_location_plus <- function(data) {
120
+ loc_data <- data %>%
121
+ mutate(
122
+ Balls = as.integer(Balls),
123
+ Strikes = as.integer(Strikes),
124
+ count_state = paste0(Balls,"-",Strikes),
125
+ count_state = ifelse(!count_state %in% c("0-0","0-1","0-2","1-0","1-1","1-2",
126
+ "2-0","2-1","2-2","3-0","3-1","3-2"),
127
+ NA, count_state),
128
+ count_state = as.factor(count_state),
129
+ PitchType = map_pitch_type(TaggedPitchType)
130
+ ) %>%
131
+ filter(!is.na(PitchType), !is.na(count_state))
132
+
133
+ if (nrow(loc_data)==0) return(tibble(Pitcher=character(), `Location+`=numeric()))
134
+
135
+ predictions <- predict(xgb_fit, new_data=loc_data) %>% rename(xRV288=.pred)
136
+
137
+ bind_cols(predictions, loc_data) %>%
138
+ group_by(Pitcher, PitchType) %>%
139
+ summarise(avg_xRV288=mean(xRV288,na.rm=TRUE), .groups="drop") %>%
140
+ left_join(league_stats_pitcher, by="PitchType") %>%
141
+ group_by(Pitcher) %>%
142
+ summarise(
143
+ `Location+` = round(weighted.mean(
144
+ (-(avg_xRV288 - league_avg) / league_sd) * 10 + 100,
145
+ w = rep(1, n()), na.rm=TRUE), 0),
146
+ .groups="drop"
147
+ )
148
+ }
149
+
150
  # ── Pitcher stats ──────────────────────────────────────────────────────────────
151
  build_pitcher_stats <- function(df, min_pitches) {
152
 
 
208
  .groups = "drop"
209
  ) %>%
210
  left_join(team_lookup, by="Pitcher") %>%
211
+ %>%
212
+ left_join(
213
+ tryCatch(compute_stuff_plus(df), error=function(e) tibble(Pitcher=character(), `Stuff+`=numeric())),
214
+ by="Pitcher"
215
+ ) %>%
216
+ left_join(
217
+ tryCatch(compute_location_plus(df), error=function(e) tibble(Pitcher=character(), `Location+`=numeric())),
218
+ by="Pitcher"
219
+ ) %>%
220
  filter(Pitches >= min_pitches) %>%
221
  mutate(
222
  Name = sapply(Pitcher, format_name),
 
254
  ) %>%
255
  select(Name, Level, Team, Pitches, `FB Velo`, `Zone%`, `Strike%`,
256
  `K's`, `BB's`, `K/BB`, `Whiff%`, `Chase%`, `Hard Hit%`,
257
+ `Stuff+`, `Location+`, `Plot`, `Twitter`) %>%
258
  arrange(desc(Pitches))
259
  }
260
 
 
513
  dom = "lfrtip",
514
  columnDefs = list(
515
  list(className = "dt-left", targets = 0:1),
516
+ list(className = "dt-center", targets = 2:16),
517
+ list(orderable = FALSE, targets = c(15, 16))
518
+ )
519
  initComplete = JS("function(settings, json) {
520
  $('#loading_msg').hide();
521
  }")