-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.R
1921 lines (1625 loc) · 75.5 KB
/
server.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
#--------------------------#
# Server Components
#--------------------------#
server <- function(input, output, session) {
packages_used <- c("av", "bslib", "cptcity", "countrycode",
"deSolve","dplyr","DT","ggplot2","htmltools",
"latex2exp","lattice","latticeExtra","leaflet",
"maps","markdown","plotly","purrr","rasterVis",
"readr","readxl","writexl","sf","shiny","shinyalert",
"shinybusy","shinyhelper","shinyjs","shinyBS",
"shinyvalidate","shinyWidgets","sp","stringr",
"terra","tidyverse","tinytex","here","rnaturalearth")
observe_helpers <- function (session = shiny::getDefaultReactiveDomain(),
help_dir = "helpfiles",
withMathJax = FALSE) {
shiny::observeEvent(eventExpr = session$input$`shinyhelper-modal_params`,
handlerExpr = {
params <- session$input$`shinyhelper-modal_params`
type <- params$type
size <- params$size
title <- params$title
label <- params$label
easyClose <- as.logical(params$easyClose)
fade <- as.logical(params$fade)
if (title == "")
title <- NULL
if (type == "markdown") {
file <- file.path(help_dir, params$content)
if (file.exists(file)) {
content <- shiny::includeMarkdown(file)
if (withMathJax) {
content <- shiny::withMathJax(content)
}
}
else {
title <- shiny::tags$strong("Helpfile Not Found")
content <- "Sorry, there doesn't seem to be a helpfile for this yet!"
}
}
else {
content <- shiny::HTML(params$content)
}
## HACK: fix the size of the seedDataDT helper
if (params$title == "Seed data template (for the Democratic Republic of Congo)") {
modal <- shiny::modalDialog(content, title = title,
size = "xl", easyClose = easyClose, fade = fade,
footer = shiny::modalButton(label))
} else {
modal <- shiny::modalDialog(content, title = title,
size = size, easyClose = easyClose, fade = fade,
footer = shiny::modalButton(label))
}
shiny::showModal(modal)
})
}
get_relevant_citation <- function(pkg) {
citation_info <- tryCatch(citation(pkg), error = function(e) NULL)
if (!is.null(citation_info)) {
citation_text <- capture.output(print(citation_info))
# Find the index of the "A BibTeX entry for LaTeX users is"
bibtex_index <- grep("A BibTeX entry for LaTeX users is", citation_text)
# Extract the relevant part
if (length(bibtex_index) > 0) {
relevant_part <- citation_text[2:(bibtex_index - 1)]
} else {
relevant_part <- citation_text[2:length(citation_text)]
}
relevant_part <- paste(relevant_part, collapse = "\n")
# Ensure proper HTML rendering
relevant_part <- gsub("<", "<", relevant_part)
relevant_part <- gsub(">", ">", relevant_part)
} else {
relevant_part <- "Citation information not available"
}
return(relevant_part)
}
# Get the relevant part of citations for all packages
package_citations <- lapply(packages_used, get_relevant_citation)
output$packageList <- renderUI({
packages <- packages_used
citations <- package_citations
panels <- lapply(seq_along(packages), function(i) {
bsCollapsePanel(
title = packages[i],
content = tags$div(style = "padding: 10px;", HTML(citations[[i]])),
style = "primary"
)
})
do.call(bsCollapse, c(id = "collapseExample", open = NULL, panels))
})
selectedCountryISO3C <-
reactive(countrycode(sourcevar = input$selectedCountry,
"country.name",
"iso3c"))
observe_helpers(help_dir = "helpfiles", withMathJax = TRUE)
iv <- InputValidator$new()
iv_alpha <- InputValidator$new()
iv_cropped <- InputValidator$new()
iv_seeddataupload <- InputValidator$new()
output$seedDataDT <- renderDT(read_csv(here("seeddata", "COD_InitialSeedData.csv")), server = FALSE)
# Non-spatial Modelling
# muValue
# iv$add_rule("muBirth", sv_required())
# iv$add_rule("muBirth", sv_gte(0))
#iv$add_rule("muBirth", sv_lte(0.1))
# iv$add_rule("muDeath", sv_required())
# iv$add_rule("muDeath", sv_gte(0))
#iv$add_rule("muDeath", sv_lte(0.1))
# Spatial Modelling
iv$add_rule("selectedCountry", sv_required())
iv_alpha$add_rule("alpha", sv_required())
iv_alpha$add_rule("alpha", sv_gte(0))
iv$add_rule("beta", sv_required())
iv$add_rule("beta", sv_gte(0))
iv$add_rule("gamma", sv_required())
iv$add_rule("gamma", sv_gte(0))
iv$add_rule("sigma", sv_required())
iv$add_rule("sigma", sv_gte(0))
iv$add_rule("delta", sv_required())
iv$add_rule("delta", sv_gte(0))
iv$add_rule("lambda", sv_required())
iv$add_rule("lambda", sv_integer())
iv$add_rule("lambda", sv_gt(0))
iv$add_rule("date", sv_required())
iv$add_rule("timestep", sv_required())
iv$add_rule("timestep", sv_integer())
iv$add_rule("timestep", sv_gt(0))
iv_cropped$add_rule("level1List", sv_required())
iv_seeddataupload$add_rule("seedData", sv_required())
iv_seeddataupload$add_rule("seedData", ~ if(is.null(fileInputs$smStatus) || fileInputs$smStatus == 'reset') "Required")
iv_alpha$condition(~ isTRUE(input$modelSelect == "SVEIRD"))
iv_cropped$condition(~ isTRUE(input$cropLev1))
iv_seeddataupload$condition(~ isTRUE(input$appMode == "Simulator"))
iv$add_validator(iv_alpha)
iv$add_validator(iv_cropped)
iv$add_validator(iv_seeddataupload)
#------------------------------------------#
## Visualizer Input Validators ----
#------------------------------------------#
# iv <- InputValidator$new()
iv_dataupload <- InputValidator$new()
iv_dataupload$add_rule("latLonData", sv_required())
iv_dataupload$add_rule("latLonData", ~ if(is.null(fileInputs$latLonStatus) || fileInputs$latLonStatus == 'reset') "Required")
iv_dataupload$add_rule("incidenceData", sv_required())
iv_dataupload$add_rule("incidenceData", ~ if(is.null(fileInputs$incidenceStatus) || fileInputs$incidenceStatus == 'reset') "Required")
iv_dataupload$condition(~ isTRUE(input$appMode == "Visualizer"))
iv$add_validator(iv_dataupload)
iv$enable()
iv_alpha$enable()
iv_cropped$enable()
iv_seeddataupload$enable()
iv_dataupload$enable()
observe({
if(iv$is_valid()){
shinyjs::enable(id = "go")
} else {
shinyjs::disable(id = "go")
}
})
# observeEvent(iv$is_valid(), {
# shinyjs::enable(id = "go")
# })
# Reset vital dynamics when not checked off
observe({
input$muValue
updateNumericInput(session, "muBirth", value = 0)
})
observe({
input$muValue
updateNumericInput(session, "muDeath", value = 0)
})
values <- reactiveValues()
values$allow_simulation_run <- TRUE
fileInputs <- reactiveValues(
smStatus = NULL,
latLonStatus = NULL,
incidenceStatus = NULL
)
# output$table <- renderTable(values$df)
susceptible <- reactive({
req(!is.null(input$selectedCountry) && input$selectedCountry != "")
createSusceptibleLayer(input$selectedCountry, input$agg)
})
#==========================================================================#
# World Pop Visualizer Components ----
#==========================================================================#
output$resetButton <- renderUI({ ## resetButton ----
if (!is.null(input$selectedCountry) && input$selectedCountry != ""){
actionButton(
inputId = "visReset",
label = "Reset Values",
class = "act-btn")
}
})
output$leafletMap <- renderLeaflet({
req(!is.null(input$selectedCountry))
susc <- susceptible()$Susceptible
level1Names <- NULL
createLeafletPlot(input$selectedCountry, level1Names, susc)
})
output$croppedLeafletMap <- renderLeaflet({
req(!is.null(input$selectedCountry) && !is.null(input$level1List))
req(input$selectedCountry == level1Country())
susc <- susceptible()$Susceptible
level1Names <- input$level1List
createLeafletPlot(input$selectedCountry, level1Names, susc)
})
output$terraOutputImage <- renderImage({ ## outputImage ----
validate(need(!is.null(input$selectedCountry), "Loading App...")) # catches UI warning
if (input$selectedCountry == ""){
list(src = "", width = 0, height = 0)
} else {
outfile <- tempfile(fileext = '.png')
# createBasePlot(input$selectedCountry, 1, FALSE) # print the susceptible plot to www/
# png(outfile, width = 800, height = 600)
png(outfile, width = 1024, height = 768)
createBasePlot(input$selectedCountry, susceptible()$Susceptible, TRUE) # print the susceptible plot direct to UI
dev.off()
# list(src = outfile, contentType = 'image/png', width = 800, height = 600, alt = "Base plot image not found")
list(src = outfile, contentType = 'image/png', width = 1024, height = 768, alt = "Base plot image not found")
}
}, deleteFile = TRUE)
createGeoFeatures <- function(incidenceData, palette_colors, bins) {
incidenceData %>%
pivot_longer(cols = -c(Location, Latitude, Longitude),
names_to = "date",
values_to = "cases") %>%
filter(cases != 0) %>%
mutate(
color = palette_colors[findInterval(cases, bins, rightmost.closed = TRUE)],
time = paste0(date, "T00:00:00.000Z"),
label = paste0(Location, " - Cases: ", cases)
) %>%
pmap(function(Longitude, Latitude, time, color, label, ...) {
list(
type = "Feature",
geometry = list(
type = "Point",
coordinates = list(Longitude, Latitude)
),
properties = list(
time = time,
color = color,
label = label
)
)
})
}
transPathDataToJSON <- function (incidenceData, pal) {
bins <- c(0, 5, 10, 25, 50, 100, 250, 1000, 10000)
palette_colors <- pal(length(bins) - 1)
features <- createGeoFeatures(incidenceData, palette_colors, bins)
geoJSONstring <- paste0(
'{"type": "FeatureCollection", "features": [',
paste0(
sapply(features, function(feature) {
paste0(
'{"type": "', feature$type, '", ',
'"geometry": {"type": "', feature$geometry$type, '", ',
'"coordinates": [', paste(feature$geometry$coordinates, collapse = ","), ']}, ',
'"properties": {"time": "', feature$properties$time, '", ',
'"color": "', feature$properties$color, '", ',
'"label": "', feature$properties$label, '"}}'
)
}), collapse = ","
),
']}'
)
}
output$transmission <- renderLeaflet({
req(!is.null(input$selectedCountry))
req(iv_dataupload$is_valid())
level1Names <- NULL
if(input$cropLev1 == TRUE){
if(!is.null(input$level1List) && !("" %in% input$level1List)){
level1Names <- input$level1List
}
}
inputISO <- countrycode(input$selectedCountry, origin = 'country.name', destination = 'iso3c') #Converts country name to ISO Alpha
gadmFileName <- paste0("gadm36_", toupper(inputISO), "_1_sp.rds") # name of the .rds file
gadmFolder <- "gadm/"
level1Identifier <- readRDS(paste0(gadmFolder, gadmFileName))
if(!is.null(level1Names)){
level1Identifier <- level1Identifier[which(level1Identifier$NAME_1 %in% level1Names), ]}
valueRange <- c(0, 5, 10, 25, 50, 100, 250, 1000, 10000)
ramp <- c(
'#617AEC',
'#0027E0',
'#0C81F8',
'#43CAFF',
'#7BEBC8',
'#DFF58D',
'#FFA044',
'#EE4F4D')
pal <- colorRampPalette(ramp)
incidenceData <- transPathData()
geoJson <- transPathDataToJSON(transPathData(), pal)
leaflet(
options = leafletOptions(zoomSnap = 0.25, zoomDelta=0.25)) %>%
addProviderTiles("Esri.WorldGrayCanvas") %>%
addPolygons(data = level1Identifier,
color = "#444444",
weight = 1.5,
smoothFactor = 1,
opacity = 1.0,
fillColor = "#F5F5F5",
fillOpacity = 0.75,
popup = paste(level1Identifier$NAME_1),
highlightOptions = highlightOptions(color = "white", weight = 2,
bringToFront = FALSE)) %>%
addLegend(pal = colorBin(palette = pal(9)[-1],
bins = valueRange,
domain = valueRange),
values = valueRange,
opacity = 0.75,
title = "Obs. persons",
position = "topright") %>%
htmlwidgets::onRender("
function(el, x) {
var map = this;
dataAsJson = JSON.parse(data);
addTimeDimensionToLeaflet(map, dataAsJson);
}
", data = geoJson)
})
#--------------------------------------------------------------------------#
# Proxy map for the leaflet plot to dynamically update the transmission
# path data
#--------------------------------------------------------------------------#
observe({
req(!is.null(input$transPathDate))
# which date (column of data) to plot
transDate <- input$transPathDate
plotData <- transPathData()
# To access a column inside the leafletProxy function the column name must
# be called directly (can't use a variable storing the column name) so we
# must set the column we want to a known name ("Current")
colnames(plotData)[colnames(plotData) == transDate] <- "Current"
labelText <- paste0(
"Location: ", plotData$Location, "<br/>",
"Count: ", plotData$Current, "<br/>") %>%
lapply(htmltools::HTML)
# To update the map, clear out the old markers and draw new ones using the
# data from the newly selected date
leafletProxy("transmission",
data = plotData) %>%
clearMarkers() %>%
addCircleMarkers(lng = ~Longitude,
lat = ~Latitude,
radius = ~Current^0.35*2,
weight = 1,
opacity = 1,
color = ~ifelse(Current > 0, "black", "transparent"),
fillColor = ~ifelse(Current > 0, colorPalette(Current), "transparent"),
fillOpacity = 0.8,
label = labelText)
})
output$lollipop <- renderPlotly({
req(iv_dataupload$is_valid())
p <- plotLolliChart(input$selectedCountry, input$incidenceData$datapath)
ggplotly(p)
})
output$timeSeriesOptions <- renderUI({
plotTitle <- paste0("Time-Series Graph of Incidence/Death in ")
if(input$selectedCountry %in% prependList) {
plotTitle <- paste0(plotTitle, "the ")
}
plotTitle <- paste0(plotTitle, input$selectedCountry)
plotOptionsMenuUI(
id = "timeSeriesMenu",
plotType = "Time-Series",
title = plotTitle,
xlab = "Date",
ylab = "Number of Persons",
colour = "#22031F",
includeFlip = FALSE,
includeGridlines = FALSE
)
})
output$timeSeries <- renderPlotly({
req(iv_dataupload$is_valid())
req(!is.null(input[["timeSeriesMenu-Colour"]]))
p <- plotTimeSeries(file = input$incidenceData$datapath,
input[["timeSeriesMenu-Title"]],
input[["timeSeriesMenu-Xlab"]],
input[["timeSeriesMenu-Ylab"]],
input[["timeSeriesMenu-Colour"]],
input[["timeSeriesMenu-TSstyle"]])
ggplotly(p)
})
#---------------------------------------------------------------------------#
# Combine the lat/long data with the observed infection into a single table #
#---------------------------------------------------------------------------#
transPathData <- reactive({
req(iv_dataupload$is_valid() && input$appMode == "Visualizer")
incidenceData <- openDataFile(input$incidenceData)
latLonData <- openDataFile(input$latLonData)
incidence <- as.data.frame(t(incidenceData))
incidenceCols <- incidence[2,]
incidence <- incidence[3:nrow(incidence),]
colnames(latLonData) <- c("Location", "Latitude", "Longitude")
colnames(incidence) <- incidenceCols
plotData <- cbind(latLonData, lapply(incidence, as.numeric))
})
#--------------------------------------------------------------------------#
# Checks to see that files have been uploaded (helper func) #
#--------------------------------------------------------------------------#
observeEvent(input$latLonData, {
fileInputs$latLonStatus <- 'uploaded'
})
observeEvent(input$incidenceData, {
fileInputs$incidenceStatus <- 'uploaded'
})
observeEvent({input$selectedCountry
input$appMode}, {
if(!is.null(input$selectedCountry) && input$selectedCountry != "" && input$appMode == "Visualizer") {
shinyjs::show(id = "maptabPanels")
} else {
shinyjs::hide(id = "maptabPanels")
}
fileInputs$latLonStatus <- 'reset'
fileInputs$incidenceStatus <- 'reset'
})
observeEvent({input$selectedCountry
input$appMode}, priority = 100, {
if(input$appMode == "Visualizer") {
updateTabsetPanel(inputId = "vizTabSet", selected = "Leaflet Plot")
}
})
observeEvent({input$cropLev1
input$selectedCountry
input$level1List
input$appMode}, priority = 100, {
if(input$cropLev1 == TRUE && input$appMode == "Visualizer" && !is.null(input$level1List)) {
showTab(inputId = 'vizTabSet', target = 'Leaflet Cropped Plot')
} else if((input$cropLev1 == FALSE && input$appMode == "Visualizer") || is.null(input$level1List)) {
hideTab(inputId = 'vizTabSet', target = 'Leaflet Cropped Plot')
updateTabsetPanel(inputId = "vizTabSet", selected = "Leaflet Plot")
}
})
observeEvent(input$visReset, {
updateCheckboxInput(
inputId = "cropLev1",
value = FALSE
)
updatePickerInput(
inputId = "selectedCountry",
selected = ""
)
fileInputs$latLonStatus <- 'reset'
fileInputs$incidenceStatus <- 'reset'
})
observe({
if(input$appMode == "Visualizer") {
if(iv_dataupload$is_valid()) {
showTab(inputId = 'vizTabSet', target = "Transmission Path")
showTab(inputId = 'vizTabSet', target = "Lollipop Chart")
showTab(inputId = 'vizTabSet', target = "Time-Series Graph")
} else {
hideTab(inputId = 'vizTabSet', target = "Transmission Path")
hideTab(inputId = 'vizTabSet', target = "Lollipop Chart")
hideTab(inputId = 'vizTabSet', target = "Time-Series Graph")
}
}
})
#==========================================================================#
# Model Simulation Components ----
#==========================================================================#
#--------------------------------------------------------------------------#
# Create a country plot cropped by level1Identifier and output to UI #
#--------------------------------------------------------------------------#
# observeEvent(input$go, {
# if(input$cropLev1 == TRUE){
# output$croppedOutputImage <- renderImage({
#
# outfile <- tempfile(fileext = '.png')
#
# png(outfile, width = 800, height = 600)
# createCroppedRaster(selectedCountry = input$selectedCountry, level1Region = input$level1List, rasterAgg = input$agg, directOutput = T)
# dev.off()
#
# list(src = outfile, contentType = 'image/png', width = 600, height = 400, alt = "Base plot image not found")
# }, deleteFile = TRUE)
# }
# })
#--------------------------------------------------------------------------#
# Output population base plot image to the app UI #
#--------------------------------------------------------------------------#
observeEvent(input$go, {
req(iv$is_valid())
output$outputImage <- renderImage({
outfile <- tempfile(fileext = '.png')
png(outfile, width = 768, height = 768)
if(input$cropLev1) {
req(input$level1List != "")
isolate(createCroppedRaster(selectedCountry = input$selectedCountry,
level1Region = input$level1List,
susceptible()$Susceptible,
directOutput = TRUE))
} else {
isolate(createBasePlot(selectedCountry = input$selectedCountry,
susceptible()$Susceptible,
directOutput = TRUE)) # print the susceptible plot direct to UI
}
dev.off()
list(src = outfile, contentType = 'image/png', width = 768, height = 768, alt = "Base plot image not found")
# The above line adjusts the dimensions of the base plot rendered in UI
}, deleteFile = TRUE)
})
#--------------------------------------------------------------------------#
# Output IDE equations image to the app UI #
#--------------------------------------------------------------------------#
observeEvent(input$go, {
req(iv$is_valid())
output$modelImg <- renderImage({
return(list(src= "www/ModelEquations.png",
height = 400,
contentType = "image/png"))
}, deleteFile = FALSE)
})
#--------------------------------------------------------------------------#
# Output flowchart image to the app UI #
#--------------------------------------------------------------------------#
observeEvent(input$go, {
req(iv$is_valid())
output$flowchartImg <- renderImage({
if (input$modelSelect == "SEIRD"){
return(list(src= "www/SEIRD.png",
height = 400,
contentType = "image/png"))
}
else if (input$modelSelect == "SVEIRD"){
return(list(src = "www/SVEIRD.png",
height = 400,
contentType = "image/png"))
}
}, deleteFile = FALSE)
})
#--------------------------------------------------------------------------#
# Reset all parameter sliders, country selection, etc. #
#--------------------------------------------------------------------------#
observeEvent(input$resetAll, {
shinyjs::reset("dashboard")
shinyjs::disable(id = "go")
values$allow_simulation_run <- FALSE
})
#--------------------------------------------------------------------------#
# Checks to see that a new file has been uploaded (helper func) #
#--------------------------------------------------------------------------#
coordinatePairsInsideCountry <- function(coordinates, countryISO3C, regionNames = NULL, debug = FALSE) {
points <- st_as_sf(coordinates, coords = c("lon", "lat"), crs = 4326)
country_filename <- file.path("gadm", paste0("gadm36_", countryISO3C, "_1_sp.rds"))
if (file.exists(country_filename)) {
print(paste("Loading country data from:", country_filename))
admin_boundaries <- readRDS(country_filename)
} else {
print(paste("Country data not found locally. Downloading", countryISO3C, "using geodata::gadm()"))
admin_boundaries <- gadm(country = countryISO3C, level = 1, resolution = 1, version = "latest", path = tempdir())
if (is.null(admin_boundaries)) {
stop("Country not found. Please check the ISO3C code.")
}
saveRDS(admin_boundaries, country_filename)
}
admin_boundaries <- st_as_sf(admin_boundaries)
if (!is.null(regionNames)) {
if (debug) {
print("Administrative regions available:")
print(admin_boundaries$NAME_1)
}
print("Checking specified regions")
regions <- terra::subset(admin_boundaries, admin_boundaries$NAME_1 %in% regionNames,
select = c("NAME_1", "geometry"))
if (nrow(regions) == 0) {
stop("No specified regions found in the country.")
}
areaPolygon <- regions %>%
st_union() %>%
st_cast("MULTIPOLYGON")
} else {
print("No regions specified, using entire country boundaries")
areaPolygon <- admin_boundaries %>%
st_union() %>%
st_cast("MULTIPOLYGON")
areaPolygon <- st_as_sf(areaPolygon)
}
areaPolygon <- st_transform(areaPolygon, st_crs(points))
intersections <- st_intersects(points, areaPolygon)
validPoints <- sapply(intersections, function(x) length(x) > 0)
if (debug) {
print(paste("Number of points:", nrow(points)))
print("Area of interest bounding box:")
print(st_bbox(areaPolygon))
print("Points coordinates:")
print(coordinates)
print("Results:")
print(validPoints)
}
return(validPoints)
}
validateAndCleanSeedData <- function(data) {
# This is so that I can collect all the err msgs for later
error_messages <- c()
numeric_cols <- c("lat", "lon", "InitialVaccinated", "InitialExposed",
"InitialInfections", "InitialRecovered", "InitialDead")
missing_cols <- setdiff(c("Location", numeric_cols), colnames(data))
if (length(missing_cols) > 0) {
error_messages <- c(error_messages,
paste0("Error: Missing columns: ", paste(missing_cols, collapse = ", ")))
}
if (any(is.na(data$Location) | data$Location == "")) {
error_messages <- c(error_messages,
"Error: 'Location' column cannot have empty cells or NA values.")
}
for (col in numeric_cols) {
if (any(data[[col]] == "" | is.na(suppressWarnings(as.numeric(data[[col]]))))) {
error_messages <- c(error_messages,
paste0("Error: '", col, "' column must contain only numbers and no empty cells."))
} else {
data[[col]] <- suppressWarnings(as.numeric(data[[col]]))
}
}
if (length(error_messages) > 0) {
for (msg in error_messages) {
showNotification(msg, type = "error", duration = NULL)
}
return(NULL)
}
coordinates <- data.frame(lat = data$lat, lon = data$lon)
validCoords <- coordinatePairsInsideCountry(coordinates, selectedCountryISO3C(), input$level1List, debug = FALSE)
if(all(!validCoords)) {
showNotification("Error: ALL coordinates are not within the country or selected areas.", type = "error", duration = NULL)
return(NULL)
} else if (any(!validCoords)) {
showNotification("SOME coordinates are not within the country or selected areas.", type = "warning", duration = NULL)
return(NULL)
}
return (data)
}
observeEvent(input$seedData, {
ext <- tools::file_ext(input$seedData$datapath)
if (ext == "xlsx") {
uploaded_data <- readxl::read_excel(input$seedData$datapath)
} else {
uploaded_data <- read.csv(input$seedData$datapath)
}
validated_data <- validateAndCleanSeedData(uploaded_data)
if (!is.null(validated_data)) {
# commenting this out has no effect, what is this for ?
# data(validated_data)
values$allow_simulation_run <- TRUE
fileInputs$smStatus <- 'uploaded'
} else {
fileInputs$smStatus <- 'reset'
}
})
#--------------------------------------------------------------------------#
# Check if all mandatory fields have a value #
#--------------------------------------------------------------------------#
# observe({
# mandatoryFilled <-
# vapply(fieldsMandatory,
# function(x) {
# !is.null(input[[x]]) && input[[x]] != ""
# },
# logical(1))
#
# mandatoryFilled <- all(mandatoryFilled)
#
# # enable/disable the submit button
# if (isolate(values$allow_simulation_run) == TRUE){
# shinyjs::toggleState(id = "go", condition = mandatoryFilled)
# }
# })
#--------------------------------------------------------------------------#
# highlight drop down item when hovering #
#--------------------------------------------------------------------------#
# observe({
# hoverDrop <-
# vapply(hoverDrop,
# function(x) {
# !is.null(input[[x]]) && input[[x]] != ""
# },
# logical(1))
# hoverDrop <- all(hoverDrop)
# # enable/disable the submit button
# if (isolate(values$allow_simulation_run) == TRUE){
# shinyjs::toggleClass(class = hoverDrop)
# }
# })
#--------------------------------------------------------------------------#
# This static ui field is in server since other dynamic ui elements need it#
#--------------------------------------------------------------------------#
output$countryDropdown <- renderUI({
pickerInput(
inputId = "selectedCountry",
label = strong("Country"),
choices = shortlist$Country,
multiple = FALSE,
selected = "Democratic Republic of Congo",
options = pickerOptions(
actionsBox = TRUE,
title = "Please select a country")
)
})
#--------------------------------------------------------------------------#
# Checkbox for Data Assimilation #
#--------------------------------------------------------------------------#
output$dataAssimCheckbox <- renderUI({
validate(need(!is.null(input$selectedCountry), ""))
if (!is.null(input$selectedCountry) && input$selectedCountry != ""){
checkboxInput(inputId = "dataAssim", label = strong("Include Bayesian data assimilation?"), value = FALSE)
}
})
#--------------------------------------------------------------------------#
# Create select box for choosing input country provinces #
#--------------------------------------------------------------------------#
output$Level1Ui <- renderUI({
req(!is.null(input$selectedCountry) && input$selectedCountry != "")
validate(need(input$cropLev1 == TRUE, "")) # catches UI warning
upperISO3C <- toupper(selectedCountryISO3C())
if (file.exists(paste0("gadm/", "gadm36_", upperISO3C, "_1_sp.rds"))){
level1Options <<- readRDS(paste0("gadm/", "gadm36_", upperISO3C, "_1_sp.rds"))$NAME_1
} else {
level1Options <<- raster::getData("GADM", download = TRUE, level = 1, country = upperISO3C)$NAME_1
}
selectizeInput(inputId = "level1List",
label = NULL,
choices = level1Options,
selected = c("Ituri", "Nord-Kivu"),
multiple = TRUE,
options = list(placeholder = "Select state(s)/province(s)"))
})
level1Country <- reactiveVal({
value = NULL
})
#--------------------------------------------------------------------------#
# Radio button for SEIRD vs SVEIRD Model #
#--------------------------------------------------------------------------#
output$modelRadio <- renderUI({
validate(need(!is.null(input$selectedCountry), "")) # catches UI warning
if (!is.null(input$selectedCountry) && input$selectedCountry != ""){
radioButtons(inputId = "modelSelect",
label = strong("Epidemic Model"),
choiceValues = list("SEIRD","SVEIRD"),
choiceNames = list("SEIRD","SVEIRD"),
selected = "SVEIRD", #character(0), #
inline = TRUE,
width = "1000px")
}
})
#--------------------------------------------------------------------------#
# Radio button for Deterministic vs Stochastic Model #
#--------------------------------------------------------------------------#
output$stochasticRadio <- renderUI({
validate(need(!is.null(input$selectedCountry), "")) # catches UI warning
if (!is.null(input$selectedCountry) && input$selectedCountry != ""){
radioButtons(inputId = "stochasticSelect",
label = strong("Model Stochasticity"),
choiceValues = list("Deterministic", "Stochastic"),
choiceNames = list("Deterministic", "Stochastic"),
selected = "Deterministic", #character(0), #
inline = TRUE,
width = "1000px")
}
})
#--------------------------------------------------------------------------#
# TODO: refactor numericInputs into single function #
#--------------------------------------------------------------------------#
output$alphaInput <- renderUI({
alphaValue <- 0.00015 # 0.2100
validate(need(!is.null(input$selectedCountry), "")) # catches UI warning
if (!is.null(input$selectedCountry) && input$selectedCountry != ""){
if(input$modelSelect == "SEIRD"){
if (input$selectedCountry == "Czech Republic"){
alphaValue <- as.numeric(filter(epiparms, ISONumeric == "CZE" & model == "SEIRD")[1,"alpha"])
} else if (input$selectedCountry == "Nigeria"){
alphaValue <- as.numeric(filter(epiparms, ISONumeric == "NGA" & model == "SEIRD")[1,"alpha"])
} else if (input$selectedCountry == "Uganda"){
alphaValue <- as.numeric(filter(epiparms, ISONumeric == "COD" & model == "SEIRD")[1,"alpha"])}
else if (input$selectedCountry == "Democratic Republic of Congo"){
alphaValue <- as.numeric(filter(epiparms, ISONumeric == "COD" & model == "SEIRD")[1,"alpha"])}
} else if (input$modelSelect == "SVEIRD"){
if (input$selectedCountry == "Czech Republic"){
alphaValue <- as.numeric(filter(epiparms, ISONumeric == "CZE" & model == "SVEIRD")[1,"alpha"])
} else if (input$selectedCountry == "Nigeria"){
alphaValue <- as.numeric(filter(epiparms, ISONumeric == "NGA" & model == "SVEIRD")[1,"alpha"])
}else if (input$selectedCountry == "Uganda"){
alphaValue <- as.numeric(filter(epiparms, ISONumeric == "COD" & model == "SVEIRD")[1,"alpha"])}
else if (input$selectedCountry == "Democratic Republic of Congo"){
alphaValue <- as.numeric(filter(epiparms, ISONumeric == "COD" & model == "SVEIRD")[1,"alpha"])}
}
numericInput(inputId = "alpha",
label = HTML(paste("Daily Vaccination Rate (α)")),
value = alphaValue, min = 0, max = 1, step = 0.00001)
}
})
#--------------------------------------------------------------------------#
# #
#--------------------------------------------------------------------------#
output$betaInput <- renderUI({
req(!is.null(input$modelSelect))
betaValue <- 0.055 # 0.00001
validate(need(!is.null(input$selectedCountry), "")) # catches UI warning
if (!is.null(input$selectedCountry) && input$selectedCountry != ""){
if(input$modelSelect == "SEIRD"){
if (input$selectedCountry == "Czech Republic"){
betaValue <- as.numeric(filter(epiparms, ISONumeric == "CZE" & model == "SEIRD")[1,"beta"])
} else if (input$selectedCountry == "Nigeria"){
betaValue <- as.numeric(filter(epiparms, ISONumeric == "NGA" & model == "SEIRD")[1,"beta"])}
else if (input$selectedCountry == "Uganda"){
betaValue <- as.numeric(filter(epiparms, ISONumeric == "COD" & model == "SEIRD")[1,"beta"])}
else if (input$selectedCountry == "Democratic Republic of Congo"){
betaValue <- as.numeric(filter(epiparms, ISONumeric == "COD" & model == "SEIRD")[1,"beta"])}
} else if (input$modelSelect == "SVEIRD"){
if (input$selectedCountry == "Czech Republic"){
betaValue <- as.numeric(filter(epiparms, ISONumeric == "CZE" & model == "SVEIRD")[1,"beta"])
} else if (input$selectedCountry == "Nigeria"){
betaValue <- as.numeric(filter(epiparms, ISONumeric == "NGA" & model == "SVEIRD")[1,"beta"])}
else if (input$selectedCountry == "Uganda"){
betaValue <- as.numeric(filter(epiparms, ISONumeric == "COD" & model == "SVEIRD")[1,"beta"])}
else if (input$selectedCountry == "Democratic Republic of Congo"){
betaValue <- as.numeric(filter(epiparms, ISONumeric == "COD" & model == "SVEIRD")[1,"beta"])}
}
numericInput(inputId = "beta",
label = HTML(paste("Daily Exposure Rate (β)")),
value = betaValue, min = 0, max = 1, step = 0.00001)
}
})
#--------------------------------------------------------------------------#
# #
#--------------------------------------------------------------------------#
output$gammaInput <- renderUI({