-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_pipeline.R
More file actions
1647 lines (1476 loc) · 64.8 KB
/
Copy pathgraph_pipeline.R
File metadata and controls
1647 lines (1476 loc) · 64.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
suppressPackageStartupMessages({
library(dplyr)
library(forcats)
library(fs)
library(ggplot2)
library(ggrepel)
library(here)
library(lubridate)
library(patchwork)
library(readr)
library(scales)
library(slider)
library(stringr)
library(tibble)
library(tidyr)
})
model_palette <- c(
annual_seasonal_naive = wmata_colors[["light_grey"]],
lag_7 = wmata_colors[["dark_grey"]],
linear = wmata_colors[["turquoise"]],
glmnet = wmata_colors[["true_blue"]],
xgboost = wmata_colors[["dodger_blue"]],
fallback_hierarchy = wmata_colors[["dark_blue"]],
station_aggregated = wmata_colors[["green"]]
)
mode_palette <- c(
Bus = wmata_colors[["dodger_blue"]],
Rail = wmata_colors[["green"]]
)
label_model_name <- function(model_name) {
dplyr::recode(
model_name,
annual_seasonal_naive = "Annual seasonal naive",
lag_7 = "Lag 7 baseline",
linear = "Linear regression",
glmnet = "GLMNET",
xgboost = "XGBoost",
fallback_hierarchy = "Fallback hierarchy",
station_aggregated = "Station-aggregated",
.default = model_name
)
}
filter_visual_models <- function(model_summary, metric_col = "mae", multiplier = 20) {
metric_values <- model_summary[[metric_col]]
finite_values <- metric_values[is.finite(metric_values) & metric_values > 0]
if (length(finite_values) == 0) {
return(model_summary %>% mutate(visual_keep = TRUE))
}
threshold <- min(finite_values, na.rm = TRUE) * multiplier
model_summary %>%
mutate(
visual_keep = is.finite(.data[[metric_col]]) & .data[[metric_col]] <= threshold
)
}
feature_group <- function(feature_name) {
case_when(
str_detect(feature_name, "^lag_|^roll_mean_|same_weekday") ~ "Recent ridership",
str_detect(feature_name, "day_of_week|is_weekend|weekday_saturday_sunday|service_type|holiday") ~ "Calendar structure",
str_detect(feature_name, "month|week_of_year|week_number") ~ "Seasonality",
str_detect(feature_name, "time_index|year|station_age_days|new_station_flag") ~ "Trend and age",
str_detect(feature_name, "^station_name") ~ "Station identity",
TRUE ~ "Other"
)
}
is_winter_date <- function(date) {
lubridate::month(date) %in% c(12L, 1L, 2L)
}
winter_season_label <- function(date) {
if_else(
lubridate::month(date) == 12L,
paste0(lubridate::year(date), "-", lubridate::year(date) + 1L),
paste0(lubridate::year(date) - 1L, "-", lubridate::year(date))
)
}
format_day_name <- function(date) {
factor(
lubridate::wday(date, label = TRUE, abbr = TRUE, week_start = 1),
levels = lubridate::wday(seq(as.Date("2026-01-05"), by = "day", length.out = 7), label = TRUE, abbr = TRUE, week_start = 1)
)
}
build_rail_system_history <- function(silver_data) {
silver_data$ridership_rail_station_daily %>%
group_by(date) %>%
summarise(
ridership = sum(ridership, na.rm = TRUE),
holiday = dplyr::first(holiday),
day_of_week = dplyr::first(day_of_week),
weekday_saturday_sunday = dplyr::first(weekday_saturday_sunday),
service_type = dplyr::first(service_type),
.groups = "drop"
) %>%
arrange(date)
}
build_rail_future_context <- function(rail_results) {
bind_rows(
rail_results$main_results$final_future_forecasts,
rail_results$fallback_results$future_forecasts
) %>%
group_by(date) %>%
summarise(
day_of_week = dplyr::first(day_of_week),
weekday_saturday_sunday = dplyr::first(weekday_saturday_sunday),
service_type = dplyr::first(service_type),
.groups = "drop"
) %>%
arrange(date)
}
selected_backtest_predictions <- function(bus_results, rail_results, bus_data, rail_system_history) {
bind_rows(
bus_results$backtest_predictions %>%
filter(model == bus_results$selected_model_name) %>%
left_join(bus_data %>% select(date, holiday, day_of_week, weekday_saturday_sunday, service_type), by = "date") %>%
mutate(mode = "Bus"),
rail_results$system_backtest_predictions %>%
filter(model == rail_results$main_results$selected_model_name) %>%
left_join(rail_system_history %>% select(date, holiday, day_of_week, weekday_saturday_sunday, service_type), by = "date") %>%
mutate(mode = "Rail")
)
}
selected_holdout_predictions <- function(bus_results, rail_results, bus_data, rail_system_history) {
bind_rows(
bus_results$holdout_predictions %>%
left_join(bus_data %>% select(date, holiday, day_of_week, weekday_saturday_sunday, service_type), by = "date") %>%
mutate(mode = "Bus"),
rail_results$system_holdout_predictions %>%
left_join(rail_system_history %>% select(date, holiday, day_of_week, weekday_saturday_sunday, service_type), by = "date") %>%
mutate(mode = "Rail")
)
}
build_future_forecasts_by_mode <- function(bus_results, rail_results) {
rail_future_context <- build_rail_future_context(rail_results)
bind_rows(
add_prediction_intervals(
bus_results$final_future_forecasts %>% select(date, prediction),
bus_results$backtest_predictions %>% filter(model == bus_results$selected_model_name)
) %>%
left_join(
bus_results$final_future_forecasts %>% select(date, day_of_week, weekday_saturday_sunday, service_type),
by = "date"
) %>%
mutate(mode = "Bus"),
add_prediction_intervals(
rail_results$system_future_forecasts,
rail_results$system_backtest_predictions %>% filter(model == rail_results$main_results$selected_model_name)
) %>%
left_join(rail_future_context, by = "date") %>%
mutate(mode = "Rail")
)
}
compute_coverage_summary <- function(predictions) {
bind_rows(
predictions %>%
group_by(mode) %>%
summarise(
interval = "80%",
nominal_coverage = 0.80,
observed_coverage = mean(actual >= lower_80 & actual <= upper_80, na.rm = TRUE),
average_width = mean(upper_80 - lower_80, na.rm = TRUE),
.groups = "drop"
),
predictions %>%
group_by(mode) %>%
summarise(
interval = "95%",
nominal_coverage = 0.95,
observed_coverage = mean(actual >= lower_95 & actual <= upper_95, na.rm = TRUE),
average_width = mean(upper_95 - lower_95, na.rm = TRUE),
.groups = "drop"
)
)
}
compute_success_rate <- function(actual, prediction, tolerance = 0.10) {
mean(abs(prediction - actual) / pmax(actual, 1) <= tolerance, na.rm = TRUE)
}
build_model_leaderboard <- function(backtest_predictions) {
backtest_predictions %>%
filter(is.finite(actual), is.finite(prediction)) %>%
group_by(model) %>%
summarise(
mae = mean(abs(prediction - actual), na.rm = TRUE),
rmse = sqrt(mean((prediction - actual) ^ 2, na.rm = TRUE)),
mape = 100 * mean(abs(prediction - actual) / pmax(actual, 1), na.rm = TRUE),
success_rate_10 = 100 * compute_success_rate(actual, prediction, tolerance = 0.10),
.groups = "drop"
) %>%
filter_visual_models(metric_col = "mae") %>%
filter(visual_keep) %>%
mutate(
model_label = label_model_name(model)
)
}
build_feature_importance_groups <- function(feature_importance) {
if (nrow(feature_importance) == 0) {
return(tibble(feature_group = character(), importance = numeric()))
}
feature_column <- if ("term" %in% names(feature_importance)) "term" else if ("Variable" %in% names(feature_importance)) "Variable" else names(feature_importance)[[1]]
importance_column <- if ("importance" %in% names(feature_importance)) "importance" else if ("Importance" %in% names(feature_importance)) "Importance" else names(feature_importance)[[2]]
feature_importance %>%
transmute(
feature = .data[[feature_column]],
importance = abs(.data[[importance_column]])
) %>%
filter(!is.na(feature), !is.na(importance)) %>%
mutate(feature_group = feature_group(feature)) %>%
group_by(feature_group) %>%
summarise(importance = sum(importance, na.rm = TRUE), .groups = "drop") %>%
arrange(desc(importance))
}
build_horizon_decay <- function(predictions) {
predictions %>%
filter(horizon_day >= 1, horizon_day <= 30, is.finite(actual), is.finite(prediction)) %>%
group_by(mode, horizon_day) %>%
summarise(
mae = mean(abs(prediction - actual), na.rm = TRUE),
.groups = "drop"
)
}
build_error_by_month <- function(predictions) {
predictions %>%
mutate(month_label = factor(month(date, label = TRUE, abbr = TRUE), levels = month.abb)) %>%
group_by(mode, month_label) %>%
summarise(
mae = mean(abs(prediction - actual), na.rm = TRUE),
.groups = "drop"
)
}
build_error_by_ridership_level <- function(predictions) {
predictions %>%
group_by(mode) %>%
mutate(
ridership_band = ntile(actual, 4),
ridership_band = factor(ridership_band, labels = c("Lowest quartile", "Lower-middle", "Upper-middle", "Highest quartile"))
) %>%
group_by(mode, ridership_band) %>%
summarise(
mae = mean(abs(prediction - actual), na.rm = TRUE),
.groups = "drop"
)
}
build_calibration_curve <- function(predictions) {
predictions %>%
group_by(mode) %>%
mutate(calibration_bin = ntile(prediction, 10)) %>%
group_by(mode, calibration_bin) %>%
summarise(
avg_prediction = mean(prediction, na.rm = TRUE),
avg_actual = mean(actual, na.rm = TRUE),
.groups = "drop"
)
}
build_directional_accuracy <- function(predictions) {
predictions %>%
arrange(mode, date) %>%
group_by(mode) %>%
mutate(
previous_actual = lag(actual),
actual_direction = sign(actual - previous_actual),
predicted_direction = sign(prediction - previous_actual)
) %>%
filter(!is.na(previous_actual)) %>%
summarise(
directional_accuracy = mean(actual_direction == predicted_direction, na.rm = TRUE),
.groups = "drop"
)
}
build_accuracy_traffic_light <- function(predictions) {
predictions %>%
mutate(horizon_bucket = horizon_bucket(horizon_day)) %>%
group_by(mode, horizon_bucket) %>%
summarise(
mape = 100 * mean(abs(prediction - actual) / pmax(actual, 1), na.rm = TRUE),
.groups = "drop"
) %>%
mutate(
status = case_when(
mape <= 10 ~ "Green",
mape <= 15 ~ "Yellow",
TRUE ~ "Red"
)
)
}
build_worst_prediction_days <- function(predictions, top_n = 5) {
predictions %>%
mutate(
abs_error = abs(prediction - actual)
) %>%
group_by(mode) %>%
slice_max(abs_error, n = top_n, with_ties = FALSE) %>%
mutate(
error = prediction - actual,
error_direction = if_else(error >= 0, "Overpredicted", "Underpredicted"),
likely_explanation = case_when(
!is.na(holiday) & holiday != "No" ~ "Holiday or service-calendar effect",
!is.na(weekday_saturday_sunday) & weekday_saturday_sunday != "Weekday" ~ "Weekend demand shift",
abs_error / pmax(actual, 1) >= 0.20 ~ "Possible disruption or special event",
TRUE ~ "Needs manual review"
)
) %>%
ungroup()
}
build_success_rate_summary <- function(predictions) {
prediction_splits <- predictions %>%
group_by(mode) %>%
summarise(data = list(pick(everything())), .groups = "drop")
crossing(
mode = unique(predictions$mode),
threshold = c(0.05, 0.10, 0.15)
) %>%
left_join(prediction_splits, by = "mode") %>%
rowwise() %>%
mutate(
success_rate = compute_success_rate(data$actual, data$prediction, tolerance = threshold)
) %>%
ungroup() %>%
transmute(
mode,
threshold_label = paste0("Within ±", round(threshold * 100), "%"),
success_rate
)
}
build_smoothed_horizon_decay <- function(predictions) {
build_horizon_decay(predictions) %>%
arrange(mode, horizon_day) %>%
group_by(mode) %>%
mutate(
smoothed_mae = slider::slide_dbl(mae, mean, .before = 3, .after = 3, .complete = FALSE, na.rm = TRUE)
) %>%
ungroup()
}
build_decision_matrix <- function(future_forecasts) {
future_forecasts %>%
mutate(
interval_width = upper_80 - lower_80,
day_type = if_else(weekday_saturday_sunday == "Weekday", "Weekday", "Weekend")
) %>%
group_by(mode) %>%
mutate(
demand_midpoint = median(prediction, na.rm = TRUE),
uncertainty_midpoint = median(interval_width, na.rm = TRUE),
action_bucket = case_when(
prediction >= demand_midpoint & interval_width < uncertainty_midpoint ~ "Plan capacity",
prediction >= demand_midpoint & interval_width >= uncertainty_midpoint ~ "Prepare contingency",
prediction < demand_midpoint & interval_width < uncertainty_midpoint ~ "Optimize resources",
TRUE ~ "Manual review"
)
) %>%
ungroup()
}
build_forecast_extremes <- function(future_forecasts) {
bind_rows(
future_forecasts %>%
group_by(mode) %>%
slice_max(prediction, n = 1, with_ties = FALSE) %>%
mutate(extreme_type = "Highest forecast day"),
future_forecasts %>%
group_by(mode) %>%
slice_min(prediction, n = 1, with_ties = FALSE) %>%
mutate(extreme_type = "Lowest forecast day")
) %>%
ungroup()
}
build_recent_growth_table <- function(rail_results, silver_data) {
recent_actual <- silver_data$ridership_rail_station_daily %>%
filter(date >= max(date) - 27) %>%
group_by(station_name) %>%
summarise(recent_avg_ridership = mean(ridership, na.rm = TRUE), .groups = "drop")
future_station_forecasts <- bind_rows(
rail_results$main_results$final_future_forecasts %>% mutate(forecast_group = "main"),
rail_results$fallback_results$future_forecasts %>% mutate(forecast_group = "fallback")
) %>%
group_by(station_name) %>%
summarise(
forecast_avg_ridership = mean(prediction, na.rm = TRUE),
.groups = "drop"
)
future_station_forecasts %>%
left_join(recent_actual, by = "station_name") %>%
mutate(
recent_avg_ridership = coalesce(recent_avg_ridership, 0),
absolute_growth = forecast_avg_ridership - recent_avg_ridership,
pct_growth = if_else(recent_avg_ridership > 0, absolute_growth / recent_avg_ridership, NA_real_)
) %>%
arrange(desc(absolute_growth))
}
build_rail_station_risk <- function(rail_results, silver_data) {
station_growth <- build_recent_growth_table(rail_results, silver_data)
station_accuracy <- rail_results$main_results$holdout_predictions %>%
group_by(station_name) %>%
summarise(
holdout_mae = mean(abs(prediction - actual), na.rm = TRUE),
.groups = "drop"
)
station_growth %>%
left_join(station_accuracy, by = "station_name") %>%
filter(is.finite(holdout_mae))
}
build_data_freshness <- function(bus_data, rail_system_history) {
tibble(
mode = c("Bus", "Rail"),
latest_actual_date = c(max(bus_data$date, na.rm = TRUE), max(rail_system_history$date, na.rm = TRUE))
) %>%
mutate(
report_date = Sys.Date(),
days_old = as.integer(report_date - latest_actual_date)
)
}
build_ridership_history <- function(bus_data, rail_system_history) {
bind_rows(
bus_data %>%
select(date, ridership) %>%
mutate(mode = "Bus"),
rail_system_history %>%
select(date, ridership) %>%
mutate(mode = "Rail")
) %>%
arrange(mode, date) %>%
group_by(mode) %>%
mutate(
rolling_28 = slider::slide_dbl(ridership, mean, .before = 27, .complete = FALSE, na.rm = TRUE)
) %>%
ungroup()
}
build_recovery_index <- function(history_data) {
baseline <- history_data %>%
filter(date >= as.Date("2019-01-01"), date <= as.Date("2019-12-31")) %>%
group_by(mode) %>%
summarise(baseline_ridership = mean(ridership, na.rm = TRUE), .groups = "drop")
history_data %>%
mutate(month_date = floor_date(date, unit = "month")) %>%
group_by(mode, month_date) %>%
summarise(monthly_ridership = mean(ridership, na.rm = TRUE), .groups = "drop") %>%
left_join(baseline, by = "mode") %>%
mutate(index_to_2019 = monthly_ridership / baseline_ridership)
}
plot_actual_vs_predicted <- function(predictions, title_text, subtitle_text) {
interval_layer <- if (all(c("lower_80", "upper_80") %in% names(predictions))) {
geom_ribbon(
data = predictions,
aes(x = date, ymin = lower_80, ymax = upper_80),
inherit.aes = FALSE,
fill = wmata_colors[["sky_blue"]],
alpha = 0.35
)
} else {
NULL
}
ggplot(predictions, aes(x = date)) +
interval_layer +
geom_line(aes(y = actual, color = "Actual"), linewidth = 0.95) +
geom_line(aes(y = prediction, color = "Predicted"), linewidth = 0.95, linetype = "dashed") +
scale_color_manual(values = c(Actual = wmata_colors[["midnight_blue"]], Predicted = wmata_colors[["dodger_blue"]])) +
scale_y_continuous(labels = scales::comma) +
labs(
title = title_text,
subtitle = subtitle_text,
x = NULL,
y = "Daily Ridership",
color = NULL,
caption = "What this shows: held-out actual ridership versus model predictions and the 80% planning band when available | Why it matters: it is the clearest out-of-sample reliability view | What WMATA should do: use it as the main credibility check before operational use"
) +
theme_wmata()
}
plot_decision_workflow <- function(title_text) {
workflow_steps <- tibble(
step = factor(
c("Ridership history", "Forecast model", "30-day outlook", "WMATA actions"),
levels = c("Ridership history", "Forecast model", "30-day outlook", "WMATA actions")
),
x = c(1, 2, 3, 4),
y = c(1, 1, 1, 1),
detail = c(
"Daily Bus and Rail demand history",
"Forecast-safe features\nand shared production pipeline",
"Expected demand,\npeaks, troughs, uncertainty",
"Staffing, service assumptions,\nmanual review, communications"
)
)
arrows_tbl <- tibble(
x = c(1.2, 2.2, 3.2),
xend = c(1.8, 2.8, 3.8),
y = 1,
yend = 1
)
ggplot() +
geom_segment(data = arrows_tbl, aes(x = x, xend = xend, y = y, yend = yend), arrow = arrow(length = grid::unit(0.15, "inches")), linewidth = 0.9, color = wmata_colors[["dark_grey"]]) +
geom_label(
data = workflow_steps,
aes(x = x, y = y, label = step),
fill = wmata_colors[["midnight_blue"]],
color = "white",
fontface = "bold",
size = 4.2,
linewidth = 0
) +
geom_text(data = workflow_steps, aes(x = x, y = y - 0.2, label = detail), color = wmata_colors[["dark_blue"]], size = 3.5, lineheight = 1.1, vjust = 1) +
coord_cartesian(xlim = c(0.5, 4.5), ylim = c(0.3, 1.25), clip = "off") +
labs(
title = title_text,
subtitle = "The forecast is meant to help planners prioritize attention, not automate service changes by itself"
) +
theme_wmata() +
theme(
axis.text = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
panel.grid = element_blank()
)
}
plot_pattern_capture <- function(predictions, title_text) {
window_n <- min(42L, nrow(predictions))
window_data <- predictions %>%
arrange(date) %>%
slice_tail(n = window_n) %>%
mutate(
abs_error = abs(prediction - actual),
label_type = case_when(
date == date[which.max(if_else(weekday_saturday_sunday == "Weekday", actual, -Inf))] ~ "Weekday peak",
date == date[which.min(if_else(weekday_saturday_sunday != "Weekday", actual, Inf))] ~ "Weekend trough",
date == date[which.max(abs_error)] ~ "Largest miss",
TRUE ~ NA_character_
)
)
label_points <- window_data %>% filter(!is.na(label_type))
ggplot(window_data, aes(x = date)) +
geom_ribbon(aes(ymin = lower_80, ymax = upper_80), fill = wmata_colors[["sky_blue"]], alpha = 0.28) +
geom_line(aes(y = actual, color = "Actual"), linewidth = 0.95) +
geom_line(aes(y = prediction, color = "Predicted"), linewidth = 0.95, linetype = "dashed") +
geom_point(data = label_points, aes(y = actual), color = wmata_colors[["red"]], size = 2.4) +
geom_text_repel(
data = label_points,
aes(y = actual, label = label_type),
size = 3.3,
color = wmata_colors[["midnight_blue"]],
nudge_y = 0.04 * max(window_data$actual, na.rm = TRUE)
) +
scale_color_manual(values = c(Actual = wmata_colors[["midnight_blue"]], Predicted = wmata_colors[["dodger_blue"]])) +
scale_y_continuous(labels = scales::comma) +
labs(
title = title_text,
subtitle = "A shorter 6-week window makes the weekly operating rhythm and the most visible miss easier to interpret",
x = NULL,
y = "Daily Ridership",
color = NULL
) +
theme_wmata()
}
plot_forecast_trend <- function(history_data, forecast_data, title_text) {
history_tail <- history_data %>% filter(date >= max(date) - 60)
ggplot() +
geom_line(data = history_tail, aes(x = date, y = ridership), color = wmata_colors[["dark_grey"]], linewidth = 0.8) +
geom_ribbon(
data = forecast_data,
aes(x = date, ymin = lower_80, ymax = upper_80),
fill = wmata_colors[["sky_blue"]],
alpha = 0.35
) +
geom_line(data = forecast_data, aes(x = date, y = prediction), color = wmata_colors[["green"]], linewidth = 1) +
scale_y_continuous(labels = scales::comma) +
labs(
title = title_text,
subtitle = "Recent actuals are shown in gray and the 30-day production forecast is shown in green",
x = NULL,
y = "Daily Ridership",
caption = "What this shows: the near-term planning outlook with empirical uncertainty | Why it matters: helps planners distinguish expected demand from upside risk | What WMATA should do: use it for staffing, service planning, and rider communications"
) +
theme_wmata()
}
plot_residual_distribution <- function(predictions, title_text) {
residual_data <- predictions %>%
mutate(
residual = prediction - actual,
ape = abs(prediction - actual) / pmax(actual, 1)
)
stats_label <- glue::glue(
"Mean: {scales::comma(round(mean(residual_data$residual, na.rm = TRUE)))}\n",
"Median: {scales::comma(round(median(residual_data$residual, na.rm = TRUE)))}\n",
"Within 10%: {scales::percent(mean(residual_data$ape <= 0.10, na.rm = TRUE), accuracy = 1)}\n",
"Within 15%: {scales::percent(mean(residual_data$ape <= 0.15, na.rm = TRUE), accuracy = 1)}"
)
ggplot(residual_data, aes(x = residual)) +
geom_histogram(fill = wmata_colors[["dodger_blue"]], color = "white", bins = 30) +
geom_vline(xintercept = 0, color = wmata_colors[["red"]], linewidth = 0.8, linetype = "dashed") +
annotate("label", x = Inf, y = Inf, label = stats_label, hjust = 1.02, vjust = 1.1, size = 3.2, fill = "white") +
scale_x_continuous(labels = scales::comma) +
labs(
title = title_text,
subtitle = "The summary callout converts the residual shape into an operational performance statement",
x = "Prediction Error",
y = "Count",
caption = "What this shows: the spread and bias of remaining error | Why it matters: systematic drift creates planning risk | What WMATA should do: watch for widening residuals before reusing the model operationally"
) +
theme_wmata()
}
plot_error_by_horizon <- function(horizon_summary, title_text) {
horizon_visual <- horizon_summary %>%
filter_visual_models(metric_col = "mae") %>%
filter(visual_keep) %>%
mutate(model_label = label_model_name(model))
ggplot(horizon_visual, aes(x = horizon_bucket, y = mae, color = model, group = model)) +
geom_line(linewidth = 0.9) +
geom_point(size = 2.4) +
scale_color_manual(values = model_palette, labels = label_model_name) +
scale_y_continuous(labels = scales::comma) +
labs(
title = title_text,
subtitle = "Only stable candidate models are shown to avoid broken scale distortion",
x = NULL,
y = "MAE",
color = NULL
) +
theme_wmata()
}
plot_error_by_service_type <- function(predictions, title_text) {
service_summary <- predictions %>%
mutate(service_group = coalesce(as.character(service_type), as.character(weekday_saturday_sunday), "Unknown")) %>%
group_by(service_group) %>%
summarise(mae = mean(abs(prediction - actual), na.rm = TRUE), .groups = "drop")
ggplot(service_summary, aes(x = reorder(service_group, mae), y = mae)) +
geom_col(fill = wmata_colors[["true_blue"]]) +
coord_flip() +
scale_y_continuous(labels = scales::comma) +
labs(
title = title_text,
subtitle = "Segments with higher MAE may need separate monitoring",
x = NULL,
y = "MAE"
) +
theme_wmata()
}
plot_station_error_rank <- function(predictions, title_text) {
station_summary <- predictions %>%
group_by(station_name) %>%
summarise(mae = mean(abs(prediction - actual), na.rm = TRUE), .groups = "drop") %>%
arrange(desc(mae)) %>%
slice_head(n = 20)
ggplot(station_summary, aes(x = mae, y = reorder(station_name, mae))) +
geom_col(fill = wmata_colors[["dark_blue"]]) +
geom_text_repel(aes(label = scales::comma(round(mae))), direction = "y", size = 3.1, color = wmata_colors[["midnight_blue"]]) +
scale_x_continuous(labels = scales::comma) +
labs(
title = title_text,
subtitle = "Highest-error stations in the holdout window",
x = "MAE",
y = NULL
) +
theme_wmata()
}
plot_model_leaderboard <- function(leaderboard_data, title_text) {
metric_labels <- c(
mae = "MAE",
rmse = "RMSE",
mape = "MAPE",
success_rate_10 = "Share Within 10%"
)
leaderboard_long <- leaderboard_data %>%
select(model, model_label, mae, rmse, mape, success_rate_10) %>%
pivot_longer(cols = c(mae, rmse, mape, success_rate_10), names_to = "metric", values_to = "value") %>%
mutate(
metric = factor(metric, levels = names(metric_labels), labels = unname(metric_labels))
)
ggplot(leaderboard_long, aes(x = value, y = fct_reorder(model_label, value, .fun = min), color = model)) +
geom_point(size = 3) +
facet_wrap(~ metric, scales = "free_x", ncol = 2) +
scale_color_manual(values = model_palette, guide = "none") +
scale_x_continuous(labels = scales::label_number(accuracy = 0.1, big.mark = ",")) +
labs(
title = title_text,
subtitle = "The leaderboard removes visually broken candidates so the meaningful comparisons stay readable",
x = NULL,
y = NULL
) +
theme_wmata()
}
plot_feature_importance <- function(feature_importance, title_text) {
feature_groups <- build_feature_importance_groups(feature_importance)
if (nrow(feature_groups) == 0) {
return(
ggplot() +
annotate("text", x = 0, y = 0, label = "Feature importance unavailable for this run", color = wmata_colors[["dark_grey"]], size = 5) +
labs(title = title_text, subtitle = "No feature importance output was available") +
theme_wmata() +
theme(axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank())
)
}
feature_groups <- feature_groups %>%
mutate(share = importance / sum(importance, na.rm = TRUE))
ggplot(feature_groups, aes(x = share, y = fct_reorder(feature_group, share))) +
geom_col(fill = wmata_colors[["green"]]) +
geom_text(aes(label = scales::percent(share, accuracy = 1)), hjust = -0.1, size = 3.3) +
scale_x_continuous(labels = scales::percent, expand = expansion(mult = c(0, 0.12))) +
labs(
title = title_text,
subtitle = "The grouped view makes the model story legible: recent ridership and calendar timing drive most of the forecast movement",
x = "Share of grouped importance",
y = NULL,
caption = "What this shows: the model is driven mostly by recent ridership and calendar structure, not opaque black-box effects | Why it matters: easier auditability and easier stakeholder explanation | What WMATA should do: use this to explain why the forecast moves on specific days"
) +
theme_wmata()
}
plot_winter_actual_vs_predicted <- function(predictions, title_text) {
winter_predictions <- predictions %>%
filter(is_winter_date(date)) %>%
mutate(
winter_season = winter_season_label(date)
)
ggplot(winter_predictions, aes(x = date)) +
geom_line(aes(y = actual, color = "Actual"), linewidth = 0.9) +
geom_line(aes(y = prediction, color = "Predicted"), linewidth = 0.9, linetype = "dashed") +
facet_grid(mode ~ winter_season, scales = "free_x") +
scale_color_manual(values = c(Actual = wmata_colors[["midnight_blue"]], Predicted = wmata_colors[["dodger_blue"]])) +
scale_y_continuous(labels = scales::comma) +
labs(
title = title_text,
subtitle = "Winter months are isolated explicitly so stakeholders can judge cold-season performance rather than annual averages alone",
x = NULL,
y = "Daily Ridership",
color = NULL
) +
theme_wmata(base_size = 13)
}
plot_winter_mae_comparison <- function(predictions, title_text) {
winter_summary <- predictions %>%
mutate(season_group = if_else(is_winter_date(date), "Winter months", "Non-winter months")) %>%
group_by(mode, season_group) %>%
summarise(mae = mean(abs(prediction - actual), na.rm = TRUE), .groups = "drop")
ggplot(winter_summary, aes(x = season_group, y = mae, fill = mode)) +
geom_col(position = position_dodge(width = 0.7), width = 0.65) +
geom_text(aes(label = scales::comma(round(mae))), position = position_dodge(width = 0.7), vjust = -0.3, size = 3.2) +
scale_fill_manual(values = mode_palette) +
scale_y_continuous(labels = scales::comma, expand = expansion(mult = c(0, 0.12))) +
labs(
title = title_text,
subtitle = "This directly answers whether winter is materially harder than the rest of the year",
x = NULL,
y = "MAE",
fill = NULL
) +
theme_wmata()
}
plot_winter_weekday_pattern <- function(predictions, title_text) {
weekday_pattern <- predictions %>%
filter(is_winter_date(date)) %>%
mutate(day_name = format_day_name(date)) %>%
group_by(mode, day_name) %>%
summarise(
actual = mean(actual, na.rm = TRUE),
prediction = mean(prediction, na.rm = TRUE),
.groups = "drop"
) %>%
pivot_longer(cols = c(actual, prediction), names_to = "series", values_to = "ridership") %>%
mutate(series = recode(series, actual = "Actual", prediction = "Predicted"))
ggplot(weekday_pattern, aes(x = day_name, y = ridership, color = series, group = series)) +
geom_line(linewidth = 0.9) +
geom_point(size = 2.1) +
facet_wrap(~ mode, scales = "free_y") +
scale_color_manual(values = c(Actual = wmata_colors[["midnight_blue"]], Predicted = wmata_colors[["dodger_blue"]])) +
scale_y_continuous(labels = scales::comma) +
labs(
title = title_text,
subtitle = "Average winter weekday and weekend structure is a useful sanity check for service planning relevance",
x = NULL,
y = "Average Daily Ridership",
color = NULL
) +
theme_wmata()
}
plot_winter_coverage <- function(predictions, title_text) {
coverage_tbl <- predictions %>%
filter(is_winter_date(date)) %>%
compute_coverage_summary()
ggplot(coverage_tbl, aes(x = interval, y = observed_coverage, fill = mode)) +
geom_col(position = position_dodge(width = 0.7), width = 0.65) +
geom_point(aes(y = nominal_coverage), position = position_dodge(width = 0.7), color = wmata_colors[["red"]], size = 2.5) +
scale_fill_manual(values = mode_palette) +
scale_y_continuous(labels = scales::percent, limits = c(0, 1)) +
labs(
title = title_text,
subtitle = "Bars show observed winter coverage and red points show the nominal interval target",
x = NULL,
y = "Coverage",
fill = NULL
) +
theme_wmata()
}
plot_backtest_mae_over_time <- function(selected_backtests, title_text) {
fold_summary <- selected_backtests %>%
group_by(mode, origin_date) %>%
summarise(mae = mean(abs(prediction - actual), na.rm = TRUE), .groups = "drop") %>%
group_by(mode) %>%
mutate(
avg_mae = mean(mae, na.rm = TRUE),
season_group = if_else(is_winter_date(origin_date), "Winter fold", "Non-winter fold")
) %>%
ungroup()
label_points <- bind_rows(
fold_summary %>% group_by(mode) %>% slice_max(mae, n = 1, with_ties = FALSE) %>% mutate(label = "Worst month"),
fold_summary %>% group_by(mode) %>% slice_min(mae, n = 1, with_ties = FALSE) %>% mutate(label = "Best month")
)
ggplot(fold_summary, aes(x = origin_date, y = mae)) +
geom_hline(aes(yintercept = avg_mae), linetype = "dashed", color = wmata_colors[["dark_grey"]]) +
geom_line(color = wmata_colors[["midnight_blue"]], linewidth = 0.9) +
geom_point(aes(fill = season_group), color = wmata_colors[["midnight_blue"]], size = 3, shape = 21) +
geom_text_repel(data = label_points, aes(label = label), size = 3.1, color = wmata_colors[["midnight_blue"]]) +
scale_fill_manual(values = c("Winter fold" = wmata_colors[["dodger_blue"]], "Non-winter fold" = wmata_colors[["light_grey"]])) +
scale_y_continuous(labels = scales::comma) +
scale_x_date(date_labels = "%b", date_breaks = "1 month") +
facet_wrap(~ mode, scales = "free_y", ncol = 1) +
labs(
title = title_text,
subtitle = "Each point is a simulated future forecast from that month, with winter folds highlighted and the dashed line marking average MAE",
x = "Validation origin",
y = "MAE",
fill = NULL
) +
theme_wmata()
}
plot_horizon_decay_curve <- function(horizon_decay, title_text) {
zone_labels <- tibble(
xmin = c(1, 8),
xmax = c(7, 30),
ymin = -Inf,
ymax = Inf,
zone = c("Days 1-7:\nOperational planning", "Days 8-30:\nService and staffing outlook")
)
ggplot(horizon_decay, aes(x = horizon_day, y = smoothed_mae, color = mode)) +
geom_rect(data = zone_labels, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), inherit.aes = FALSE, fill = wmata_colors[["light_grey"]], alpha = 0.25) +
geom_line(linewidth = 1) +
scale_color_manual(values = mode_palette) +
scale_y_continuous(labels = scales::comma) +
scale_x_continuous(breaks = c(1, 7, 14, 21, 30)) +
annotate("text", x = 4, y = Inf, label = "Operational planning", vjust = 1.4, color = wmata_colors[["midnight_blue"]], size = 3.2) +
annotate("text", x = 19, y = Inf, label = "Directional staffing/service view", vjust = 1.4, color = wmata_colors[["midnight_blue"]], size = 3.2) +
labs(
title = title_text,
subtitle = "The line is a 7-day rolling MAE by horizon, which makes the planning value of near-term versus farther-out forecasts easier to read",
x = "Forecast horizon day",
y = "MAE",
color = NULL
) +
theme_wmata()
}
plot_residual_distribution_by_mode <- function(predictions, title_text) {
residuals <- predictions %>%
mutate(residual = prediction - actual)
ggplot(residuals, aes(x = residual, fill = mode)) +
geom_histogram(bins = 30, alpha = 0.85, color = "white") +
geom_vline(xintercept = 0, linetype = "dashed", color = wmata_colors[["midnight_blue"]]) +
facet_wrap(~ mode, scales = "free_y") +
scale_fill_manual(values = mode_palette) +
scale_x_continuous(labels = scales::comma) +
labs(
title = title_text,
subtitle = "The two residual distributions can be compared directly for spread and bias",
x = "Residual",
y = "Count",
fill = NULL
) +
theme_wmata()
}
plot_predicted_vs_actual_scatter <- function(predictions, title_text) {
ggplot(predictions, aes(x = actual, y = prediction, color = mode)) +
geom_abline(intercept = 0, slope = 1, color = wmata_colors[["dark_grey"]], linetype = "dashed") +
geom_point(alpha = 0.6, size = 2) +
facet_wrap(~ mode, scales = "free") +
scale_color_manual(values = mode_palette) +
scale_x_continuous(labels = scales::comma) +
scale_y_continuous(labels = scales::comma) +
labs(
title = title_text,
subtitle = "Points near the diagonal indicate better calibration",
x = "Actual ridership",
y = "Predicted ridership",
color = NULL
) +
theme_wmata()
}
plot_coverage_chart <- function(coverage_summary, title_text) {
ggplot(coverage_summary, aes(x = interval, y = observed_coverage, fill = mode)) +
geom_col(position = position_dodge(width = 0.7), width = 0.65) +
geom_point(aes(y = nominal_coverage), position = position_dodge(width = 0.7), size = 2.8, color = wmata_colors[["red"]]) +
scale_fill_manual(values = mode_palette) +
scale_y_continuous(labels = scales::percent, limits = c(0, 1)) +
labs(
title = title_text,
subtitle = "Bars are observed holdout coverage and red points are the nominal interval targets",
x = NULL,
y = "Coverage",
fill = NULL
) +
theme_wmata()
}
plot_error_by_month <- function(error_by_month, title_text) {
ggplot(error_by_month, aes(x = month_label, y = mae, group = mode, color = mode)) +
geom_line(linewidth = 0.95) +
geom_point(size = 2.2) +
scale_color_manual(values = mode_palette) +
scale_y_continuous(labels = scales::comma) +
labs(
title = title_text,
subtitle = "This is a simple seasonality robustness check on the selected models",
x = NULL,
y = "MAE",
color = NULL
) +
theme_wmata()
}
plot_error_by_ridership_level <- function(error_by_ridership_level, title_text) {
ggplot(error_by_ridership_level, aes(x = ridership_band, y = mae, fill = mode)) +
geom_col(position = position_dodge(width = 0.7), width = 0.65) +