forked from nantesmetropole/school_meal_forecast_xgboost
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shiny_app.R
1636 lines (1441 loc) · 76.5 KB
/
shiny_app.R
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
# util functions -------------------------------------------------------------
# the business functions are in another section below
create_folder <- function(folder) {
# Creating a temp folder if needed to handle downloads
if (!(dir.exists(folder))) {
dir.create(folder)
}
}
# Set parameters -------------------------------------------------------------
pkgs_to_load <- "shiny"
pkgs_not_load <- c("shiny","purrr", "DT", "readr", "arrow",
"data.table", "stringr", "lubridate", "plotly", "forcats",
"shinyalert", "dplyr", "tidyr", "shinyjs", "shinyhttr",
"waiter", "odbc", "DBI", "waiter", "shinyalert", "writexl")
# A function to install required packages
install_load <- function(mypkg, to_load = FALSE) {
for (i in seq_along(mypkg)) {
if (!is.element(mypkg[i], installed.packages()[,1])) {
install.packages(mypkg[i], repos="http://cran.irsn.fr/")
}
if (to_load) { library(mypkg[i], character.only=TRUE) }
}
}
# install_load("reticulate")
## Environment parameters
# Appropriate .Rprofile needs to be included in the project folder
# reticulate::virtualenv_remove("venv_shiny_app")
virtualenv_dir = Sys.getenv("VIRTUALENV_NAME")
python_path = Sys.getenv("PYTHON_PATH")
if (!reticulate::virtualenv_exists(envname = "venv_shiny_app")) {
reticulate::virtualenv_create(envname = virtualenv_dir, python = python_path)
reticulate::virtualenv_install(virtualenv_dir, packages = c("pandas==1.1.0",
"numpy==1.19.1",
"xgboost==1.1.1",
"scikit-learn==0.23.1",
"dask[dataframe]==0.19.4",
"lunardate==0.2.0",
"convertdate==2.2.1",
"matplotlib==3.2.1",
"python-dateutil==2.8.1"))
}
reticulate::use_virtualenv(virtualenv = virtualenv_dir, required = TRUE)
# Libraries -------------------------------------------------------------------
# install_load(pkgs_to_load, to_load = TRUE)
# install_load(pkgs_not_load)
library(magrittr)
library(lubridate)
library(shinyalert)
library(waiter)
# library(dplyr)
# library(tidyr)
# Parameters --------------------------------------------------------------
data_path <- "data"
index <- dplyr::tribble(
~name, ~path,
"schoolyears", "calculators/annees_scolaires.csv",
"strikes", "calculators/greves.csv",
"holidays", "calculators/jours_feries.csv",
"vacs", "calculators/vacances.csv",
"cafets", "raw/cantines.csv",
"effs", "raw/effectifs.csv",
"freqs", "raw/frequentation.csv",
"menus", "raw/menus_tous.csv",
"map_schools", "mappings/mapping_ecoles_cantines.csv",
"map_freqs", "mappings/mapping_frequentation_cantines.csv") %>%
dplyr::mutate(path = paste(data_path, path, sep = "/"))
# Begin and end year for selecting school years when loading headcounts
schoolyear_hq_start <- 2010
schoolyear_hq_end <- 2025
# A parameter for the display of widgets on the "load data" page
width_load_widgets <- "317px"
# A function to build open data urls from portal and dataset id
portal = "data.nantesmetropole.fr"
od_url <- function(portal, dataset_id,
params = "/exports/csv") {
left <- paste0("https://", portal, "/api/v2/catalog/datasets/")
paste(left, dataset_id, params, sep = "")
}
# Creating a temp folder if needed to handle downloads
create_folder("temp")
create_folder(data_path)
freq_id = "244400404_nombre-convives-jour-cantine-nantes-2011"
freq_od <- od_url(portal = portal, dataset_id = freq_id)
freq_od_temp_loc <- "temp/freq_od.csv"
menus_id <- "244400404_menus-cantines-nantes-depuis-2011"
menus_od <- od_url(portal = portal, dataset_id = menus_id)
menus_od_temp_loc <- "temp/menus_od.csv"
hc_id <- "244400404_effectifs-eleves-ecoles-publiques-maternelles-elementaires-nantes"
hc_od <- od_url(portal = portal, dataset_id = hc_id)
hc_od_temp_loc <- "temp/headcounts_od.csv"
vacs_od <- paste0("https://data.education.gouv.fr/explore/dataset/",
"fr-en-calendrier-scolaire/download/?format=csv")
vacs_od_temp_loc <- "temp/vacs_od.csv"
# Python functions and R bindings ---------------------------------------------------
reticulate::source_python("main.py")
prepare_arborescence()
# Cette fonction exécute la fonction 'run' avec les paramètres par défaut du readme
run_verteego <- function(begin_date = '2017-09-30',
column_to_predict = 'reel',
data_path = "tests/data",
confidence = 0.90,
end_date = '2017-12-15',
prediction_mode=TRUE,
preprocessing=TRUE,
remove_no_school=TRUE,
remove_outliers=TRUE,
school_cafeteria='',
start_training_date='2012-09-01',
training_type='xgb',
weeks_latency=10) {
# On passe les arguments à pyton au travers d'une classe
args <- reticulate::PyClass(classname = "arguments",
defs = list(
begin_date = begin_date,
column_to_predict = column_to_predict,
data_path = data_path,
confidence = confidence,
end_date = end_date,
prediction_mode = prediction_mode,
preprocessing = preprocessing,
remove_no_school = remove_no_school,
remove_outliers = remove_outliers,
school_cafeteria = school_cafeteria,
start_training_date = start_training_date,
training_type = training_type,
weeks_latency = weeks_latency))
run(args)
}
# R functions -------------------------------------------------------------
# A function to load the outputs of the model forecasts
load_results <- function(folder = "output", pattern = "results_by_cafeteria.*csv") {
prev_results <- dir(folder, pattern = pattern, full.names = TRUE) %>%
dplyr::tibble(filename = .)
if (nrow(prev_results) > 0 ) {
prev_results <- prev_results %>%
dplyr::mutate(created = stringr::str_extract(filename,
"[0-9]{4}-[0-9]{2}-[0-9]{2}_[0-9]{2}-[0-9]{2}"),
variable = stringr::str_extract(filename,
"(?<=cafeteria_)[a-z]*"),
training_type = stringr::str_extract(filename,
"xgb_interval|xgb"),
file_contents = purrr::map(filename, ~ arrow::read_csv_arrow(.))) %>%
tidyr::unnest(cols = c(file_contents)) %>%
dplyr::arrange(dplyr::desc(created), dplyr::desc(training_type)) %>%
dplyr::distinct(date_str, variable, cantine_nom, cantine_type, .keep_all = TRUE)
} else {
prev_results <- NA
}
return(prev_results)
}
# A function to retrieve results' timestamps
check_results_fresh <- function(folder = "output", pattern = "results_by_cafeteria.*csv") {
file.info(dir(folder, pattern, full.names = TRUE))$ctime
}
# A function to load the input data. Defaults to the index specified above
load_traindata <- function(name = index$name, path = index$path) {
dt <- purrr::map(path, ~ arrow::read_csv_arrow(.)) %>%
purrr::set_names(name)
}
# A function to retrieve training data time stamps
check_traindata_fresh <- function(path = index$path) {
file.info(path)$ctime
}
# A function to generate inter-vacation periods from the vacation calendar
gen_piv <- function(vacations) {
vacations %>%
dplyr::filter(vacances_nom != "Pont de l'Ascension") %>%
unique() %>%
dplyr::arrange(date_debut) %>%
dplyr::mutate(piv_nom2 = stringr::str_remove(vacances_nom,
"Vacances (d'|de la |de )"),
piv_nom2 = stringr::str_replace(piv_nom2, "Avril", "Printemps"),
piv_nom2 = stringr::str_replace(piv_nom2, "Début des Été", "Ete"),
piv_nom1 = dplyr::lag(piv_nom2, 1),
periode = paste(piv_nom1, piv_nom2, sep = "-"),
`Début` = dplyr::lag(date_fin, 1),
Fin = date_debut) %>%
dplyr::filter(!is.na(piv_nom1)) %>%
dplyr::select(annee = annee_scolaire,periode, `Début`, `Fin`) %>%
dplyr::mutate(periode = stringi::stri_trans_general(str = periode, id = "Latin-ASCII"),
periode = factor(periode, c(
"Ete-Toussaint", "Toussaint-Noel", "Noel-Hiver", "Hiver-Printemps",
"Printemps-Ete")))
}
# A function to inventory the available data
compute_availability <- function(x) {
avail_strikes <- x$strikes %>%
dplyr::mutate("avail_data" = "Grèves") %>%
dplyr::select(date, avail_data, n= greve)
# Compute the number of values of staff previsions and kid attendance
avail_freqs <- x$freqs %>%
dplyr::select(date, prevision, reel) %>%
tidyr::pivot_longer(cols = -date, names_to = "avail_data") %>%
dplyr::mutate(avail_data = dplyr::recode(avail_data,
prevision = "Commandes",
reel = "Fréquentation")) %>%
dplyr::group_by(date, avail_data) %>%
dplyr::summarise(n = dplyr::n())
# Compute the number of menu items registered per day
avail_menus <- x$menus %>%
dplyr::mutate("avail_data" = "Menus",
date = lubridate::dmy(date)) %>%
dplyr::group_by(date, avail_data) %>%
dplyr::summarise(n = dplyr::n())
# Vacances
vacs <- x$vacs
vacs_dates <- purrr:::map2(vacs$date_debut, vacs$date_fin,
~ seq(.x, .y, by = "1 day")) %>%
purrr::reduce(c)
avail_vacs <-tidyr::tibble(
date = vacs_dates,
avail_data = "Vacances",
n = 1)
avail_holidays <- x$holidays %>%
dplyr::mutate(avail_data = "Fériés") %>%
dplyr::select(date, avail_data, n = jour_ferie)
avail_data <- dplyr::bind_rows(avail_freqs, avail_menus, avail_strikes,
avail_vacs) %>%
dplyr::bind_rows(dplyr::filter(avail_holidays,
date <= max(.$date),
date >= (min(.$date)))) %>%
dplyr::mutate(annee = lubridate::year(date),
an_scol_start = ifelse(lubridate::month(date) > 8,
lubridate::year(date),
lubridate::year(date)-1),
an_scol = paste(an_scol_start, an_scol_start+1, sep = "-"),
an_scol = forcats::fct_rev(an_scol),
`Jour` = lubridate::ymd(
paste(ifelse(lubridate::month(date) > 8, "1999", "2000"),
lubridate::month(date), lubridate::day(date), sep = "-"))) %>%
dplyr::group_by(an_scol, avail_data) %>%
dplyr::mutate(max_year_var = max(n, na.rm = TRUE),
nday_vs_nyearmax = n / max_year_var) %>%
dplyr::mutate(avail_data = factor(avail_data,
levels = c("Vacances", "Fériés", "Grèves", "Menus", "Commandes", "Fréquentation")))
return(avail_data)
}
# A function to transform data from Fusion for training data
transform_fusion <- function(x, check_against) {
x %>%
dplyr::rename(date = DATPLGPRESAT, site_nom = NOMSAT, repas = LIBPRE, convive = LIBCON,
reel = TOTEFFREE, prev = TOTEFFPREV) %>%
dplyr::filter(repas == "DEJEUNER") %>%
dplyr::filter(stringr::str_starts(site_nom, "CL", negate = TRUE)) %>%
dplyr::filter(stringr::str_detect(site_nom, "TOURNEE", negate = TRUE)) %>%
dplyr::select(-repas) %>%
dplyr::mutate(convive = dplyr::recode(convive,
"1MATER." = "maternelle",
"2GS." = "grande_section",
"3PRIMAIRE" = "primaire",
"4ADULTE" = "adulte"),
site_id = stringr::str_remove(site_nom, "[0-9]{3}"),
site_nom = stringr::str_remove(site_nom, "[0-9]{3} "),
site_nom = stringr::str_replace(site_nom, "COUDRAY MAT", "COUDRAY M\\."),
site_nom = stringr::str_replace(site_nom, "MAT", "M"),
site_nom = stringr::str_replace(site_nom, "COUDRAY ELEM", "COUDRAY E\\."),
site_nom = stringr::str_replace(site_nom, "ELEM", "E"),
site_nom = stringr::str_remove(site_nom, " M/E"),
site_nom = stringr::str_remove(site_nom, " PRIM"),
site_nom = stringr::str_remove(site_nom, "\\(.*\\)$"),
site_nom = stringr::str_trim(site_nom),
site_nom = stringr::str_replace(site_nom, "BAUT", "LE BAUT"),
site_nom = stringr::str_replace(site_nom, " ", " "),
site_nom = stringr::str_replace(site_nom, "FOURNIER", "FOURNIER E"),
site_nom = stringr::str_replace(site_nom, " E / ", "/"),
site_nom = stringr::str_replace(site_nom, "MACE$", "MACE M"),
site_nom = ifelse(!(site_nom %in% check_against) & stringr::str_ends(site_nom, " (E|M)"),
stringr::str_remove(site_nom, " (E|M)$"), site_nom),
site_nom = stringr::str_replace(site_nom, "A.LEDRU-ROLLIN/S.BERNHARDT",
"LEDRU ROLLIN/SARAH BERNHARDT"),
site_nom = stringr::str_replace(site_nom, "F.DALLET/DOCT TEILLAIS",
"FRANCOIS DALLET/DOCTEUR TEILLAIS")) %>%
dplyr::group_by(date, site_id, site_nom, convive) %>%
dplyr::summarise(reel = sum(reel, na.rm = TRUE),
prev = sum(prev, na.rm = TRUE)) %>%
tidyr::pivot_wider(names_from = convive, values_from = c(reel, prev),
values_fill = 0) %>%
dplyr::mutate(reel = reel_maternelle + reel_grande_section + reel_primaire + reel_adulte,
prevision = prev_maternelle + prev_grande_section + prev_primaire + prev_adulte,
date = lubridate::date(date)) # %>%
# dplyr::select(site_id, site_nom, site_type, date, prevision, reel)
}
load_fusion <- function(x, freqs) {
new_days <- x %>%
dplyr::anti_join(freqs, by = c("date", "site_nom"))
alert_exist <- ""
if (!("reel_adulte" %in% colnames(freqs))) {
exist_days <- x %>%
dplyr::select(-reel, -prevision) %>%
dplyr::inner_join(dplyr::select(freqs, -reel, -prevision, -site_type),
by = c("date", "site_nom"))
alert_exist <- paste("Complément des fréquentation par type de convive pour",
nrow(exist_days),
"effectifs de repas par établissement pour",
length(unique(exist_days$date)),
"jours de service.\n")
freqs <- freqs %>%
dplyr::left_join(exist_days, by = c("date", "site_nom"))
}
freqs <- dplyr::bind_rows(freqs, new_days) %>%
readr::write_csv(index$path[index$name == "freqs"])
alert_new <- paste("Ajout des fréquentation par type de convive pour ",
nrow(new_days),
" effectifs de repas par établissement pour ",
length(unique(new_days$date)),
" jours de service.")
shinyalert(title = "Import depuis le fichier issu de Fusion réussi !",
text = paste0(alert_exist, alert_new),
type = "success")
}
# A function to generate a vector of school years
schoolyears <- function(year_start, year_end) {
if(!(year_start > 2000 & year_end < 2050 & year_start < year_end)) {
print("Specified year must be integers between 2000 and 2050 and start must be before end.")
} else {
left_side <- year_start:year_end
right_side <- left_side + 1
schoolyears <- paste(left_side, right_side, sep = "-")
return (schoolyears)
}
}
hc_years <- schoolyears(schoolyear_hq_start, schoolyear_hq_end)
# A function to enrich cafet list after frequentation import
update_mapping_cafet_freq <- function(x,
map_freq_loc = paste0(data_path,
"/mappings/mapping_frequentation_cantines.csv")) {
map_freq <- readr::read_csv(map_freq_loc)
new_site_names <- x %>%
dplyr::select(site_nom) %>%
unique() %>%
dplyr::filter(!(site_nom %in% map_freq$site_nom)) %>%
dplyr::left_join(dplyr::select(x, site_nom, site_type), by = "site_nom") %>%
unique() %>%
dplyr::mutate(site_type = ifelse(is.na(site_type), "M/E", site_type),
cantine_nom = site_nom,
cantine_type = site_type)
if (nrow(new_site_names) > 0) {
map_freq <- map_freq %>%
dplyr::bind_rows(new_site_names)
readr::write_csv(map_freq, map_freq_loc)
}
}
# a function to sync training data or generated previsions to SSPCloud
sync_ssp_cloud <- function(folders) {
# Check if the app is running on SSPCloud
if (Sys.info()[['user']] == "rstudio") {
# Then send selected objects to SSP Cloud
for (i in 1:length(folders)) {
folder <- folders[i]
# Check that folder name has a trailing slash and add it if needed
folder <- ifelse(stringr::str_ends(folder, "/"), folder, paste0(folder, "/"))
aws.s3::s3sync(path = folder,
bucket = "fbedecarrats",
prefix = paste0("diffusion/cantines/", folder), # diffusion to be able to share
create = FALSE,
region = "") # Important for the aws.s3 functions to work
}
}
}
# A function to check that mapping include all occurrences and display a
# meaningful message
not_in <- function(x, y, index = index) {
# extract function argument
my_x <- deparse(substitute(x))
my_y <- deparse(substitute(y))
# check that arguments literals have the right format
if (!(stringr::str_detect(my_x, "(.*[:alpha:]|_)*\\$.*$") &
stringr::str_detect(my_y, "([:alpha:]|_)*\\$.*$"))) {
print(my_x)
print(my_y)
print("argument for {not in} must look like 'dataframe$column'")
stop()
}
# parse argument to provide helpful messages
# left part of the argument
x_ds <- my_x %>%
stringr::str_remove("dt\\(\\)\\$") %>%
stringr::str_extract("([:alpha:]|_)*\\$") %>%
stringr::str_remove("\\$")
y_ds <- my_y %>%
stringr::str_remove("dt\\(\\)\\$") %>%
stringr::str_extract("([:alpha:]|_)*\\$") %>%
stringr::str_remove("\\$")
# right part of the function argument
x_col <- stringr::str_extract(my_x, "([:alpha:]|_)*$")
y_col <- stringr::str_extract(my_y, "([:alpha:]|_)*$")
# Extract the missmatches
x <- unique(x)
missings <- x[!(x %in% y)]
n_miss <- length(missings)
# Prepare message element
if (n_miss > 0) {
out <- paste0(n_miss, " établissement(s) mentionné(s) dans le champ ",
x_col, " du fichier ", my_x,
" mais pas dans le champ ", y_col,
" du fichier ", my_y, " : ",
paste(missings, collapse = ", "), ".")
}
}
# Test_pipeline -----------------------------------------------------------
# A function structure attendance data in a harmonized way with prevision data
prep_freqs <- function (x = dt()$freqs) {
x %>%
dplyr::mutate(Date = lubridate::as_date(date)) %>%
dplyr::select(Date, site_nom, reel, prevision) %>%
tidyr::pivot_longer(reel:prevision, names_to = "Source", values_to = "Repas") %>%
dplyr::mutate(Source = dplyr::case_when(Source == "reel" ~ "reel_frequentation",
Source == "prevision" ~ "reel_commandes"))
}
# A function structure prevision data in a harmonized way with attendance data
prep_prevs <- function (x = prev()) {
x %>%
dplyr::mutate(Date = lubridate::as_date(date_str),
Source = dplyr::case_when(variable == "reel" ~ "prevision_frequentation",
variable == "prevision" ~ "prevision_commandes")) %>%
dplyr::select(Date, site_nom = cantine_nom, Source, Repas = output)
}
# A function to merge the results
merge_freqs_prevs <- function(freqs, prevs) {
join_filtered <- freqs %>%
dplyr::bind_rows(prevs)
}
filter_merged <- function (x, date_start, date_end, cafet) {
# Filter dates
filtered <- x %>%
dplyr::filter(Date >= date_start & Date <= date_end)
# Filter cafet
if (cafet != "Tous") {
filtered <- filtered %>%
dplyr::filter(site_nom == cafet)
}
# Summarise
filtered <- filtered %>%
dplyr::group_by(Date, Source) %>%
dplyr::summarise(Repas = sum(Repas, na.rm = TRUE))
no_prevs <- nrow(dplyr::filter(filtered, stringr::str_starts(Source, "prevision_"))) == 0
no_freqs<- nrow(dplyr::filter(filtered, stringr::str_starts(Source, "reel_"))) == 0
# Conditional to enable displaying only training data if no previsions
if (!no_prevs & no_freqs) {
filtered <- filtered %>%
dplyr::bind_rows(dplyr::mutate(filtered,
Source = stringr::str_replace(Source, "prevision_", "reel_"),
Repas = NA))
} else if (no_prevs & !no_freqs) {
filtered <- filtered %>%
dplyr::bind_rows(dplyr::mutate(filtered,
Source = stringr::str_replace(Source, "reel_", "prevision_"),
Repas = NA))
}
return(filtered)
}
# Function to compute errors
# TO ADD TO meal4cast
compute_errors <- function(dt, strikes) {
dt %>%
dplyr::filter(!(Date %in% strikes)) %>%
dplyr::distinct(Date, site_nom, Source, .keep_all = TRUE) %>%
tidyr::pivot_wider(names_from = Source, values_from = Repas) %>%
dplyr::mutate(erreur_frequentation_agents = reel_commandes - reel_frequentation,
erreur_frequentation_modele = prevision_frequentation - reel_frequentation,
erreur_commandes_modele = prevision_commandes - reel_commandes)
}
filter_errors <- function(errors, date_start = NULL, date_end = NULL, global = FALSE) {
if (!is.null(date_start) & !is.null(date_end)) {
errors <- errors %>%
filter(Date >= date_start & Date <= date_end)
}
if (global) {
errors <- errors %>%
dplyr::group_by(Date) %>%
dplyr::summarise(erreur_frequentation_agents = sum(erreur_frequentation_agents, na.rm = TRUE),
erreur_frequentation_modele = sum(erreur_frequentation_modele, na.rm = TRUE),
erreur_commandes_modele = sum(erreur_commandes_modele, na.rm = TRUE))
}
return(errors)
}
keep_dates_with_both_prevs_and_freqs <- function(errors) {
errors %>%
dplyr::filter(!is.na(reel_frequentation) & !is.na(reel_commandes) & !is.na(prevision_frequentation))
}
get_dates_min_max <- function(errors) {
errors %>%
dplyr::summarise(min = min(Date),
max = max(Date))
}
average_errors <- function(errors) {
errors %>%
dplyr::group_by(type) %>%
dplyr::summarise(mean_error = mean(Erreur, na.rm = TRUE))
}
pivot_errors_to_plot <- function(errors) {
errors %>%
dplyr::select(Date, Agents = erreur_frequentation_agents, Modele = erreur_frequentation_modele) %>%
tidyr::pivot_longer(-Date, names_to = "type", values_to = "Erreur")
}
# UI ----------------------------------------------------------------------
ui <- navbarPage("Prévoir commandes et fréquentation", id = "tabs",
theme = bslib::bs_theme(bootswatch = "simplex", version = 5),
# cosmo, simplex
## Result visualization ----------------------------------------------------
tabPanel("Consulter des prévisions",
# Hide temporary error messages
tags$style(type="text/css",
".shiny-output-error { visibility: hidden; }",
".shiny-output-error:before { visibility: hidden; }"
),
fluidRow(
column(1, actionButton("avant",
"<< Avant",
style = "margin-top:25px; background-color: #E8E8E8")),
column(2, uiOutput("select_period")),
column(2, uiOutput("select_year")),
column(1, actionButton("apres",
"Après >>",
style = "margin-top:25px; background-color: #E8E8E8")),
column(3, uiOutput("select_cafet"))),
fluidRow(plotly::plotlyOutput("plot")),
fluidRow(
column(3, downloadButton("dwn_filtered",
"Télécharger les données affichées")),
column(4, downloadButton("dwn_period_all",
"Télécharger toutes les données pour la période sélectionnée")))#☺,
# column(3, downloadButton("dwn_filtered",
# "Télécharger toutes les données")))
),
## Import new data ------------------------------------------------------
tabPanel("Charger des données",
autoWaiter(id = "available_data",
html = tagList(
spin_flower(),
h4("Inventaire en cours, patientez 20 secondes environ...")
)),
shinyalert::useShinyalert(),
sidebarLayout(
sidebarPanel(
shinyjs::inlineCSS(list(
".shiny-input-container" = "margin-bottom: -1px",
".btn" = "margin-bottom: 5px"
)),
# sources for icons: https://icons.getbootstrap.com/
h4("Importer de nouvelles données"),
p(strong("Commandes et fréquentation réelle"),
tags$button(id = "help_freqs",
type = "button",
class="action-button",
HTML("?"))),
#icon("question-circle")),
actionButton("add_effs_real_od", "Open data",
icon = icon("cloud-download-alt")),
actionButton("add_effs_real_sal", "Application Fusion",
icon = icon("hdd")),
fileInput("add_effs_real",
label = NULL,
buttonLabel = "Parcourir",
placeholder = "Fichier extrait de Fusion",
width = width_load_widgets),
p(strong("Menus pour la restauration scolaire"),
tags$button(id = "help_menus",
type = "button",
class="action-button",
HTML("?"))),
actionButton("add_menus_od", "Open data",
icon = icon("cloud-download-alt")),
actionButton("add_menus_sal", "Application Fusion",
icon = icon("hdd")),
fileInput("add_menus", label = NULL,
buttonLabel = "Parcourir",
placeholder = "Fichier extrait de Fusion",
width = width_load_widgets),
p(strong("Grèves (éducation ou restauration)"),
tags$button(id = "help_strikes",
type = "button",
class="action-button",
HTML("?"))),
fileInput("add_strikes", label = NULL,
buttonLabel = "Parcourir",
placeholder = "Fichier de suivi",
width = width_load_widgets),
p(strong("Effectifs des écoles"),
tags$button(id = "help_effs",
type = "button",
class="action-button",
HTML("?"))),
actionButton("add_hc_od", "Open data",
icon = icon("cloud-download-alt")),
fileInput("add_headcounts", label = NULL,
buttonLabel = "Parcourir",
placeholder = "Fichier sur le PC",
accept = c(".xls", ".xlsx"),
width = width_load_widgets),
selectInput("schoolyear_hc", NULL,
choices = c("Préciser l'année",
hc_years),
width = width_load_widgets),
p(strong("Vacances scolaires pour la zone B"),
tags$button(id = "help_holi",
type = "button",
class="action-button",
HTML("?"))),
actionButton("add_vacs_od", "Open data",
icon = icon("cloud-download-alt")),
width = 3),
mainPanel(actionButton("process_inventory",
"Inventorier les données disponibles"),
actionButton("check_mappings",
"Vérifier les tables de correspondance"),
plotOutput("available_data"))
)
),
## Model parameters --------------------------------------------------------
tabPanel("Générer des prévisions",
fluidRow(
column(2,
selectInput("column_to_predict", "Variable à prévoir :",
c("Fréquentation réelle" = "reel",
"Commandes par les écoles" = "prevision")),
dateRangeInput("daterange_forecast", "Période à prévoir :",
start = "2019-09-01",
end = "2019-12-31",
min = "2015-01-01",
max = "2025-12-31",
format = "dd/mm/yyyy",
separator = " - ",
language = "fr",
weekstart = 1),
br(),
dateInput("start_training_date", "Date de début d'apprentissage :",
value = "2015-09-01",
min = "2012-01-01",
max = "2021-12-31",
format = "dd/mm/yyyy",
language = "fr",
weekstart = 1),
br(),
sliderInput("week_latency", "Dernières semaines à exclure pour l'apprentissage :",
min = 0, max = 100, value = 10, step = 1, round = TRUE)),
column(3,
selectInput("training_type", "Algorithme de prédiction :",
c("XGBoost avec intervalle de confiance" = "xgb_interval",
"XGBoost simple" = "xgb"), width = "100%"),
sliderInput("confidence", "Niveau de confiance :",
min = 0, max = 1, value = 0.9, step = 0.01),
br(),
checkboxGroupInput("model_options", "Autres options",
c("Réexécuter la préparation des données" = "preprocessing",
"Ne pas prédire les jours sans école" = "remove_no_school",
"Omettre les valeurs extrèmes (3 sigma)" = "remove_outliers"),
selected = c("preprocessing", "remove_no_school", "remove_outliers")),
br(),
actionButton("launch_model", "Lancer la prédiction")),
column(7,
pre(id = "console")))),
## UI display of server parameters --------------------------------------------------
tabPanel("Superviser",
plotOutput("error_by_school"),
plotOutput("error_global"),
h3('Information système'),
"(Ces valeurs changent selon le poste ou serveur qui fait tourner l'application)",
hr(),
DT::dataTableOutput('sysinfo'),
br(),
verbatimTextOutput('which_python'),
verbatimTextOutput('python_version'),
verbatimTextOutput('ret_env_var'),
verbatimTextOutput('venv_root')),
bslib::nav_item(actionButton("set_simple", "Simple"),
actionButton("set_advanced", "Avancé"))
)
# Server ------------------------------------------------------------------
# Define server logic required to draw a histogram
server <- function(session, input, output) {
# To enable upload of large files (Parquet files from Fusion)
options(shiny.maxRequestSize=30*1024^2)
# Handle simple vs. advanced interface ------------------------------------
# Start with hidden tabs
set_ui <- reactiveValues(simple = TRUE)
hideTab(inputId = "tabs", target = "Superviser", session = session)
hideTab(inputId = "tabs", target = "Générer des prévisions", session = session)
hideTab(inputId = "tabs", target = "Charger des données", session = session)
# Open advanced tabs on click
observeEvent(input$set_advanced, {
set_ui$simple <- FALSE
showTab(inputId = "tabs", target = "Superviser", session = session)
showTab(inputId = "tabs", target = "Générer des prévisions", session = session)
showTab(inputId = "tabs", target = "Charger des données", session = session)
}, ignoreInit = TRUE)
# Close advanced tabs on click
observeEvent(input$set_simple, {
set_ui$simple <- TRUE
hideTab(inputId = "tabs", target = "Superviser", session = session)
hideTab(inputId = "tabs", target = "Générer des prévisions", session = session)
hideTab(inputId = "tabs", target = "Charger des données", session = session)
updateNavlistPanel(inputId = "tabs", session = session, selected = "Consulter des prévisions")
}, ignoreInit = TRUE)
# Reactive values for result display -----------------------------------
# prev <- reactive({ load_results() })
prev <- reactivePoll(5000, session, # Previsions
function() check_results_fresh(),
function() load_results())
# dt <- reactive({ load_traindata() })
dt <- reactivePoll(5000, session, # training data
function() check_traindata_fresh(),
function() load_traindata())
vacs <- reactive({ return(dt()$vacs) }) # vacations
pivs <- reactive({ gen_piv(vacs()) }) # Period between vacations
cafets <- reactive({
if ( any(is.na(prev())) ) {
list_cafets <- levels(factor(dt()$freqs$site_nom))
} else {
list_cafets <- levels(factor(prev()$cantine_nom))
}
c("Tous", list_cafets)
})
periods <- reactive({ levels(pivs()$periode) }) # Name of the periods
years <- reactive({ # School years
levels(forcats::fct_rev(pivs()$annee))
})
selected_cafet <- reactive({ input$select_cafet })
selected_dates <- reactive({
pivs() %>%
dplyr::filter(periode == input$select_period &
annee == input$select_year) %>%
dplyr::select(`Début`, `Fin`)
})
out_filtered_view <- reactive({
filtered_view() %>%
# filtered <- filtered %>%
dplyr::mutate(Jour = lubridate::wday(Date, label = TRUE, abbr = FALSE),
Date = format(Date, "%d/%m/%Y")) %>%
dplyr::select(Date, Jour, everything()) %>%
dplyr::filter(Jour %in% c("lundi", "mardi", "jeudi", "vendredi"))
})
period_all <- reactive({ # Filtering all data
# Retreive parameters
date_start <- lubridate::ymd(selected_dates()[[1]])
date_end <- lubridate::ymd(selected_dates()[[2]])
week_days <- c(1,2,4,5) # Monday, Tuesday, Thursday and Friday
# Filter dates
filtered_prev <- prev() %>%
dplyr::mutate(Date = lubridate::as_date(date_str),
Source = dplyr::case_when(variable == "reel" ~ "prevision_frequentation",
variable == "prevision" ~ "prevision_commandes")) %>%
dplyr::select(Date, site_nom = cantine_nom, Source, Repas = output) %>%
dplyr::filter(Date >= date_start & Date <= date_end)
filtered_freqs <- dt()$freqs %>%
dplyr::mutate(Date = lubridate::as_date(date)) %>%
dplyr::filter(Date >= date_start & Date <= date_end) %>%
dplyr::select(Date, site_nom, reel, prevision) %>%
tidyr::pivot_longer(reel:prevision, names_to = "Source", values_to = "Repas") %>%
dplyr::mutate(Source = dplyr::case_when(Source == "reel" ~ "reel_frequentation",
Source == "prevision" ~ "reel_commandes"))
filtered <- dplyr::bind_rows(filtered_prev, filtered_freqs) %>%
dplyr::filter(format(Date, "%w") %in% week_days) %>%
dplyr::arrange(Date)
# Ensure not to have a similar file with the same name
file.remove(output_name)
my_sheets <- list()
# global statistics
global <- filtered %>%
dplyr::group_by(Date, Source) %>%
dplyr::summarise(Repas = sum(Repas, na.rm = TRUE)) %>%
mutate(Date = format(Date, "%a %d/%m/%Y")) %>%
tidyr::pivot_wider(names_from = Source, values_from = Repas)
my_sheets[[1]] <- global
# statistics by source
sources <- unique(filtered$Source)
for (i in 1:length(sources)) {
to_add <- filtered %>%
dplyr::filter(Source == sources[i]) %>%
mutate(Date = format(Date, "%a %d/%m/%Y")) %>%
tidyr::pivot_wider(names_from = Date, values_from = Repas) %>%
dplyr::select(-Source)
my_sheets[[length(my_sheets)+1]] <-to_add
}
names(my_sheets) <- c("global", sources)
return(my_sheets)
})
output$dwn_period_all <- downloadHandler(
filename = function() { paste0("Toutes_donnees_",
lubridate::ymd(selected_dates()[[1]]), "_",
lubridate::ymd(selected_dates()[[2]]),
".xlsx") },
content = function(file) { writexl::write_xlsx(period_all(), path = file) }
)
last_prev <- reactive ({
if (any(is.na(prev()))) {
max(dt()$freqs$date)
} else {
max(ymd(prev()$date_str))
}
})
piv_last_prev <- reactive({
pivs() %>%
dplyr::filter(last_prev() %within% lubridate::interval(`Début`, dplyr::lead(`Début`)))
})
merged_dt <- reactive({
merge_freqs_prevs(
freqs = prep_freqs(dt()$freqs),
prevs = prep_prevs(prev())
)
})
filtered_view <- reactive({
filter_merged(x = merged_dt(),
date_start = lubridate::ymd(selected_dates()[[1]]),
date_end = lubridate::ymd(selected_dates()[[2]]),
cafet = input$select_cafet)
})
# Reactive values for error computation -----------------------------------
all_errors <- reactive({
compute_errors(dt = merged_dt(), strikes = dt()$strikes) %>%
keep_dates_with_both_prevs_and_freqs()
})
error_date_range <- reactive({ all_errors() %>% get_dates_min_max() })
pivoted_errors_school <- reactive({ all_errors() %>% pivot_errors_to_plot() })
pivoted_errors_global <- reactive({
all_errors() %>%
filter_errors(global = TRUE) %>%
pivot_errors_to_plot()
})
error_means_school <- reactive({ pivoted_errors_school() %>% average_errors() })
error_means_global <- reactive({ pivoted_errors_global() %>% average_errors() })
# Navigation - bouton "Après" ---------------------------------------------
observeEvent(input$apres, {
period_rank <- which(periods() == input$select_period)
if (period_rank == 5) {
year_rank <- which(years() == input$select_year)
if (year_rank == 1) {
shinyalert::shinyalert("Attention",
paste("Les données ne sont pas préparées
pour des dates après l'année scolaire",
input$select_year, "."),
type = "error", html = TRUE)
} else {
new_year <- years()[year_rank - 1]
updateSelectInput(inputId = "select_period",
choices = periods(),
selected = "Ete-Toussaint")
updateSelectInput(inputId = "select_year",
choices = years(),
selected = new_year)
}
} else {
new_period <- periods()[period_rank + 1]
updateSelectInput(inputId = "select_period",
choices = periods(),
selected = new_period)
}
})
# Navigation - bouton "Avant" ---------------------------------------------
observeEvent(input$avant, {
period_rank <- which(periods() == input$select_period)
if (period_rank == 1) {
year_rank <- which(years() == input$select_year)
if (year_rank == length(years())) {
shinyalert::shinyalert("Attention",
paste("Les données ne sont pas préparées
pour des dates avant l'année scolaire",
input$select_year, "."),
type = "error", html = TRUE)
} else {
new_year <- years()[year_rank + 1]
updateSelectInput(inputId = "select_period",
choices = periods(),
selected = "Printemps-Ete")
updateSelectInput(inputId = "select_year",
choices = years(),
selected = new_year)
}
} else {
new_period <- periods()[period_rank - 1]
updateSelectInput(inputId = "select_period",
choices = periods(),