-
Notifications
You must be signed in to change notification settings - Fork 8
/
ArboMAP_forecast.Rmd
4404 lines (3705 loc) · 180 KB
/
ArboMAP_forecast.Rmd
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
---
params:
forecast_date:
label: "Date to run the forecast for, e.g. 2018-08-15"
value: "2018-08-15"
state_name:
label: "Name of state"
value: "South Dakota"
state_code:
label: "Two letter state abbreviation"
value: "SD"
predictor_var1:
label: "Name of the first environmental predictor variable"
value: "tmeanc"
predictor_var2:
label: "Name of the second environmental predictor variable"
value: "vpd"
mosquito_model:
label: "Mosquito model type"
value: "stratifiedMIGR"
input: select
choices: ["simpleratio", "AUC", "MIGR", "MII", "stratifiedMIGR", "stratifiedMII"]
mosquito_doy_start:
label: "Start of mosquito modelling period (day of year)"
value: 140
mosquito_doy_end:
label: "End of mosquito modelling period (day of year)"
value: 366
file_human:
label: "Human data file"
value: !r file.path("data_human", "simulated_human_data.csv")
input: file
file_mosquito:
label: "Mosquito pool data file"
value: !r file.path("data_mosquito", "simulated_mosquito_data.csv")
input: file
file_strata:
label: "Stratification file, leave as \"\" if no strata"
value: !r file.path("data_strata", "example_strata_SD.csv")
file_county_sf:
label: "Spatial data, either file location or command. Use \"create\" to download the census spatial data once and create a file in data_spatial folder. Use \"always_download\" to download census spatial data each time."
value: !r file.path("data_spatial", "sd_counties.RDS")
file_models:
label: "Modelling formulas file"
value: !r file.path("data_models", "models.txt")
input: file
folder_weather:
label: "Folder where weather/environmental data files are located"
value: "data_weather"
year_human_start:
label: "Start year of human data to use and this will also be the start year of modelling"
value: 2004
year_human_end:
label: "End year of human data to use. This will normally be the year before the current/forecast year."
value: 2017
year_mosquito_start:
label: "Start year of mosquito data to use"
value: 2004
year_mosquito_end:
label: "End year of mosquito data to use. This is normally the same year as the current/forecast year, or the last year of available mosquito information."
value: 2018
year_weather_start:
label: "Start year of weather/environmental data to use. This should be at least the year before the start of human data."
value: 2000
year_weather_end:
label: "End year of weather/environmental data to use. This is normally the same year as the current forecast year."
value: 2018
year_compare_vis1:
label: "Year to highlight as a comparison year in certain graphs"
value: 2012
year_compare_vis2:
label: "Second year to highlight as a comparison year in certain graphs"
value: 2017
create_appendix:
label: "Create a detailed appendix?"
value: TRUE
lag_length:
label: "Number of days of weather data to include in lags"
value: 121
case_trim_alpha:
label: "Remove temporal outliers from human cases"
value: 0.02
dev_settings:
label: "Developer settings, leave as \"!r list()\""
value: !r list()
title: "West Nile Virus Forecast Report for `r params$forecast_date` \n`r params$state_name`"
subtitle: "DEMO for Arbovirus Modeling and Prediction (ArboMAP): Synthetic Data \nNot for Epidemiological Use"
author: "Dawn M. Nekorchuk, Justin K. Davis, and Michael C. Wimberly \n([email protected]) \nGeography and Environmental Sustainability, University of Oklahoma"
date: "Report compiled on `r format(Sys.time(), '%B %d, %Y')`"
header-includes:
- \usepackage{pdflscape}
- \newcommand{\blandscape}{\begin{landscape}}
- \newcommand{\elandscape}{\end{landscape}}
- \usepackage{fancyhdr}
- \pagestyle{fancy}
output:
html_document:
toc: TRUE
toc_float: TRUE
number_sections: TRUE
pdf_document:
toc: TRUE
number_sections: TRUE
---
```{r setup, include=FALSE}
#VERSION
version_text = "4.5"
#knitr
options(warn=-1)
# replace NA with a dash in kable tables
opts <- options(knitr.kable.NA = "-")
```
```{r libraries, include=FALSE}
#make sure pacman is installed
if (!require("pacman")) install.packages("pacman", repos="http://cran.us.r-project.org"); library(pacman)
#load packages, install if not installed
pacman::p_load(
#data processing, tidyverse
dplyr, readr, tidyselect, rlang, tidyr,
tibble, stringr, glue, lubridate, purrr,
#add'l data processing
zoo,
#modeling & evaluation
mgcv, pROC, #splines, parallel are used but are base packages
#spatial, maps and graphs
tigris, sf, ggplot2, gridExtra,
viridis, ggrepel, forcats, ggpubr,
#report generation and interface
knitr, rmarkdown, shiny)
#Must use recent version of readr
if (packageVersion("readr") < "2.1"){
install.packages("readr", repos="http://cran.us.r-project.org")
}
#Must use recent version of Rcpp
if (packageVersion("Rcpp") < "1.0.7"){
install.packages("Rcpp", repos="http://cran.us.r-project.org")
}
# IF the user is trying to create a pdf,
# AND there is no LaTeX installation,
# THEN install tinytex
if (knitr::is_latex_output() &
Sys.which("pdflatex") == ""){
install.packages("tinytex", repos="http://cran.us.r-project.org")
tinytex::install_tinytex()
}
# [DEV] If warning about new TeX, need to run: tinytex::reinstall_tinytex()
# a test for this does not exist, but annual update script should take care of it
# [DEV] This may not play well if they are using xelatex or lualatex instead
# however, they need to set that in YAML headers too, so shouldn't be a problem here
#Single use functions are found in their section
# for convenience when reviewing/editing code
#for coloring text, that will work with EITHER pdf or html
#however, make sure color NAME is accepted in either
colorize <- function(x, color) {
if (knitr::is_latex_output()) {
pdf_color <- case_when(
color == "darkred" ~ "red",
color == "darkblue" ~ "blue",
TRUE ~ color
)
sprintf("\\textcolor{%s}{%s}", pdf_color, x)
} else if (knitr::is_html_output()) {
sprintf("<span style='color: %s;'>%s</span>", color, x)
} else x
}
#`r colorize("some words in red", "red")`
#https://bookdown.org/yihui/rmarkdown-cookbook/font-color.html
# [DEV] Notes on latex packages
# Used for rotating page to landscape (wide time series graph, optional for ref map)
# - \usepackage{pdflscape}
# - \newcommand{\blandscape}{\begin{landscape}}
# - \newcommand{\elandscape}{\end{landscape}}
# For nice headers and page formatting
# - \usepackage{fancyhdr}
# - \pagestyle{fancy}
```
<!-- Start of internals: data load, processing, forecast modeling, etc. -->
<!-- Code blocks: -->
<!-- dev_parameters: Checks for overrides from named list of dev parameters.
Only really accessible if rmd called from script. -->
<!-- data_load: Load all data - human, mosquito, environmental, spatial, models.
No data checks or processing here. -->
<!-- data_id_fields: add a standardized arbo_ID field based on names or fips code,
depending on fields in datasets. One or the other, not a mix -->
<!-- data_human_processing_dx: Process the human data, create diagnostics/stats -->
<!-- data_mosq_processing_dx: Process the mosquito data, create diagnostics/stats -->
<!-- mosquito_infection_model: run selected mosquito model to generate raw mir statistic -->
<!-- mir_imputation: Imputation of any missing mir statistics from unknown/no data, mir_stat sused in modeling -->
<!-- data_env_latest_history: processes the environment data
1) gets latest updated value for a day,
2) creates historical doy means -->
<!-- data_env_anomalization: calculates anomalies of environmental data via gam -->
<!-- data_combine: combine all data and format for passing off for regression -->
<!-- forecast_modeling: create the forecast models -->
<!-- Note on code comment flags: [V3]: this is what was done in version 3; [DEV] developer note; [DMN] note from Dawn Nekorchuk; DEV or <<>>: active development -->
```{r dev_parameters, echo=FALSE, include=FALSE}
#input is named list
#parameters available:
##DATA
# data_human: tbl of human case data (overrides file_human)
# data_mosquito: tbl of mosquito pool data (overrides file_mosquito)
# data_strata: tbl of strata (overrides file_stratification)
# data_weather: tbl of weather data (overrides folder_weather & processing)
# data_sf: sf object of counties for state (overrides file_county_sf)
# model_formulas: model formulas to run (overrides file_models)
##CACHED MODELS
# save_models: TRUE/FALSE: Will create a list of saved model objects (using rest of input params)
# models_cached: must be named list of model objects, named from modeling file to pattern match (output of save_models)
##REGRESSION
# mir_exactfit: T/F for how to handle missing MIR values in unknown years
# T - Original V3 with impute unknown MIR <- 0 and add exactfit
# F - using a MIR ~ total human cases linear model, no exactfit term.
# reg_function: "GAM" (hook for future possibility)
##SAVING (for extra research files)
#out_folder: "."
#out_name_base: "ArboMAP_forecast_"
#dev_write_output: write out a bunch of files into dev folder for testing and checking
##EVALUATION
#model_evaluation: TRUE/FALSE output model evaluation statistics
##REPORT
#highlight: list of counties to 'highlight' in report output.
# Needs to match names OR fips as in shapefile (depending on ID field used for arbo_ID)
#highlight_mask: T/F, whether to highlight (red outline, FALSE, default) or mask out rest of state (TRUE)
#NOTE: If not using dev parameter, do NOT include in list or instead set to NULL
# The test checks if the value is NULL. Not NA or "" or things like that.
# dev_settings itself is set to an empty list in default params above
##DATA
if (!is.null(params$dev_settings$data_human)){
#override data
data_human <- params$dev_settings$data_human
} else {
#load from file, data_load code block
data_human <- NULL
}
if (!is.null(params$dev_settings$data_mosquito)){
#override data
data_mosquito <- params$dev_settings$data_mosquito
} else {
#load from file, data_load code block
data_mosquito <- NULL
}
if (!is.null(params$dev_settings$data_strata)){
#override data
data_strata <- params$dev_settings$data_strata
} else {
#load from file, data_load code block
data_strata <- NULL
}
# RAW, as processing will still happen on override data, except for deduplication
if (!is.null(params$dev_settings$data_weather)){
#override data
data_env_raw <- params$dev_settings$data_weather
} else {
#load from file, data_load code block
data_env_raw <- NULL
}
if (!is.null(params$dev_settings$data_sf)){
#override data
data_sf <- params$dev_settings$data_sf
} else {
#load from file, data_load code block
data_sf <- NULL
}
if (!is.null(params$dev_settings$model_formulas)){
#override data
models_raw <- params$dev_settings$model_formulas
#create named list from tbl
model_formulas <- models_raw %>%
dplyr::pull(2, name = 1)
#just the model names for later use
model_names <- names(model_formulas)
} else {
#load from file, data_load code block
model_formulas <- NULL
}
##CACHED MODELS
if (!is.null(params$dev_settings$save_models)){
#use param given
save_models <- params$dev_settings$save_models
} else {
#default is FALSE
save_models <- FALSE
}
#models_cached testing and possible use is done inside of forecast regression section
if (!is.null(params$dev_settings$models_cached)){
#use param given
models_cached <- params$dev_settings$models_cached
} else {
models_cached <- NULL
}
##REGRESSION
if (!is.null(params$dev_settings$mir_exactfit)){
#use param given
mir_exactfit <- params$dev_settings$mir_exactfit
} else {
#default is FALSE
mir_exactfit <- FALSE
}
if (!is.null(params$dev_settings$reg_function)){
#use param given
reg_function <- params$dev_settings$reg_function
} else {
#default is the current and only way via mgcv bam
#this is being setup so that more may be added easily in the future [DMN]
reg_function <- "GAM"
}
##SAVING (for extra research files)
if (!is.null(params$dev_settings$out_folder)){
#use param given
out_folder <- params$dev_settings$out_folder
#create out_folder if necessary
dir.create(out_folder, recursive = TRUE)
} else {
out_folder <- "."
}
if (!is.null(params$dev_settings$out_name_base)){
#use param given
out_name_base <- params$dev_settings$out_name_base
} else {
#default
#out_name_base <- "ArboMAP_forecast_"
out_name_base <- paste0(params$mosquito_model, "_", Sys.time() %>% format("%Y%m%d%H%M"))
}
if (!is.null(params$dev_settings$dev_write_output)){
#use param given
dev_write_output <- params$dev_settings$dev_write_output
} else {
dev_write_output <- FALSE
}
##EVALUATION
if (!is.null(params$dev_settings$model_evaluation)){
#use param given
model_evaluation <- params$dev_settings$model_evaluation
} else {
#default is to not save extra files,
# only currently used in research comparing many models
model_evaluation <- FALSE
}
##REPORT
if (!is.null(params$dev_settings$highlight)){
#use param given
highlight <- params$dev_settings$highlight
#set flag to true
highlight_flag <- TRUE
} else {
#default is empty list (NULL)
highlight <- c()
highlight_flag <- FALSE
}
if (!is.null(params$dev_settings$highlight_mask)){
#use param given
highlight_mask <- params$dev_settings$highlight_mask
} else {
#default is FALSE
highlight_mask <- FALSE
}
## OTHER
#[V3] [DEV] imputemissingdistricts was hard coded as FALSE in v3 production code
# updated names and code, and added dev option for renamed impute_human_missing_districts, default = FALSE
# DEV This looks like it samples existing districts as data for the missing districts.
# I can't think of a time where this would be wanted. May be able to delete in future. [DMN]
if (!is.null(params$dev_settings$impute_human_missing_districts)){
#use param given
impute_human_missing_districts <- params$dev_settings$impute_human_missing_districts
} else {
#should stay FALSE unless you are very sure
impute_human_missing_districts <- FALSE
}
#Important references
#https://stackoverflow.com/questions/25407102/conditionally-display-a-block-of-text-in-r-markdown/46686678#46686678
#https://stackoverflow.com/questions/25240541/how-to-add-newpage-in-rmarkdown-in-a-smart-way
#https://stackoverflow.com/questions/25849814/rstudio-rmarkdown-both-portrait-and-landscape-layout-in-a-single-pdf
#https://bookdown.org/yihui/rmarkdown-cookbook/child-document.html
#https://yihui.org/knitr/
```
```{r data_load, echo=FALSE, include=FALSE, cache=FALSE}
#Loads data from file locations given in parameters
#Note: does NOT do any data checks
if (is.null(data_human)){
data_human <- readr::read_csv(params$file_human,
show_col_types = FALSE)
}
if (is.null(data_mosquito)){
data_mosquito <- readr::read_csv(params$file_mosquito,
show_col_types = FALSE)
}
if (is.null(data_strata)){
#if given a strata file, which is optional
if (!params$file_strata == ""){
data_strata <- readr::read_csv(params$file_strata,
show_col_types = FALSE)
}
}
if (is.null(data_sf)){
if (params$file_county_sf == "create"){
#if user set to "create" then we will download tigris shapefile and save for future use
#download tigris, internet required
data_sf <- tigris::counties(state = params$state_code, cb = TRUE)
#save out for use next time
#make folder if does not exist (if exists, just shows warning, suppressed)
dir.create("data_spatial", showWarnings = FALSE)
saveRDS(data_sf, file.path("data_spatial", paste0(params$state_code, "_counties.RDS")))
} else if (params$file_county_sf == "always_download"){
#if "always_download" then we will download tigris shapefile each time (no save), internet required
data_sf <- tigris::counties(state = params$state_code, cb = TRUE)
} else {
#read in file from params
data_sf <- readRDS(params$file_county_sf)
}
}#end is.null
if (is.null(model_formulas)){
models_raw <- readr::read_csv(params$file_models,
col_names = FALSE, show_col_types = FALSE,
quote = "\"")
#create named list from tbl
model_formulas <- models_raw %>%
dplyr::pull(2, name = 1)
#just the model names for later use
model_names <- names(model_formulas)
}
# Weather data
# Raw read in with prep for taking most recent value for day
# See data_weather_latest block for that processing
if (is.null(data_env_raw)){
# Reading in of data & file modified time
#get list of csv files (NOT in subfolders)
env_csv_files_raw <- list.files(path = params$folder_weather,
pattern="*.csv$",
full.names = TRUE, recursive = FALSE)
#keep the names of only csv files that are not empty
#not likely relevant here, however does no harm to check
file_condition <- sapply(env_csv_files_raw, function(x) {length(readr::count_fields(x, readr::tokenizer_csv())) > 1})
env_csv_files <- env_csv_files_raw[file_condition]
#read in all data files, and add the time the file was last modified
data_env_raw <- env_csv_files %>%
lapply(function(x) {
readr::read_csv(x, show_col_types = FALSE) %>%
#add last modified time
dplyr::mutate(file_time = file.info(x)$mtime)}) %>%
#bind list items into one dataset
dplyr::bind_rows()
}
#Record row count of data as read in
dx_mosq_nrow_0load <- nrow(data_mosquito)
dx_human_nrow_0load <- nrow(data_human)
dx_env_nrow_0load <- nrow(data_env_raw) #note PRE de-duplication
```
```{r map_dimensions_sizes, echo=FALSE, include=FALSE, cache=FALSE}
#Because this can be run for any state,
# different states have different dimensions
# and some are wider than tall and vice versa
# Calculating where reference map will be rotated, and
# appropriate maps sizes
#determine if spatial data is wider than it is tall
sf_box_dist <- data_sf %>%
#get bounding box with xmin, xmax, ymin, ymax
sf::st_bbox() %>%
#convert into sfc object
sf::st_as_sfc() %>%
#to turn into points
sf::st_cast("POINT") %>%
#calculate all distances between points
sf::st_distance()
#points:
#1: xmin, ymin,
#2: xmax, ymin
#3: xmax, ymax
#4: xmin, ymax
#5: point 1
# Want distance xmin to xmax, so can use distance between pts 1 & 2
# Want distance ymin to ymax, so can use distance between pts 1 & 4
#TRUE if wider (x distance > y distance), to be used with dynamic sizing/page orientation
sf_wider <- sf_box_dist[1,2] > sf_box_dist[1,4]
# apparently can't use ! in knitr headers, so making separate object for inverse
sf_taller <- !sf_wider
#aspect ratio is height/width
sf_asp_ratio <- sf_box_dist[1,4] / sf_box_dist[1,2]
#calculate width of reference map
# which will either be on a landscape or portrait page
# assuming US letter size paper
ref_map_width <- if (sf_wider){10} else {7}
ref_map_height <- ref_map_width * sf_asp_ratio #note returns units obj not numeric
#however, if the calc height is too tall to most likely fit on the page, recalculate
max_height_portrait <- 7
max_height_landscape <- 5
if (sf_taller &
ref_map_height > units::as_units(max_height_portrait)){
ref_map_height <- max_height_portrait
ref_map_width <- ref_map_height / sf_asp_ratio
} else if (sf_wider &
ref_map_height > units::as_units(max_height_landscape)){
ref_map_height <- max_height_landscape
ref_map_width <- ref_map_height / sf_asp_ratio
}
```
```{r data_id_fields, echo=FALSE, include=FALSE, cache=FALSE}
#ID fields:
# If FIPS field is in all, will use fips (FULL 5 character version)
# Else use original county/district name matching
# Accepted field names here, there will be preferred,
# but this gives some flexibility
# Processing happens after read in, will create "arbo_ID" used afterwards
# Processing includes wrangling fips to match across all files
# Each list in DESCENDING order of priority
# will only take the field that appears first
field_fips_accepted <- c("fips", "FIPS", "fips_code", "FIPS_CODE")
field_names_accepted <- c("county", "district", "parish", "Parish")
#ID Functions
confirm_id_fields <- function(fld_vector){
#Does any of the accepted fields (of a particular type)
# exist in all 3 or 4 datasets
# strata is OPTIONAL
if (!is.null(data_strata)){
#4 datasets
my_count <- sum(
any(fld_vector %in% names(data_human)),
any(fld_vector %in% names(data_mosquito)),
any(fld_vector %in% names(data_env_raw)),
any(fld_vector %in% names(data_strata))
)
#true/false
use_fld <- my_count == 4L
} else {
#3 datasets
my_count <- sum(
any(fld_vector %in% names(data_human)),
any(fld_vector %in% names(data_mosquito)),
any(fld_vector %in% names(data_env_raw))
)
#true/false
use_fld <- my_count == 3L
}
return(use_fld)
}
create_id_field <- function(my_tbl, fld_vector){
#the field names in the dataset that match the accepted names
# [[1]] takes the first
field_to_copy <- intersect(fld_vector, names(my_tbl))[[1]]
updated_tbl <- my_tbl %>%
#slight weirdness with dynamic field name in tidyverse
#using glue {{}}
#dplyr::mutate(arbo_ID = {{field_to_copy}})
#glue solution stopped working 2022-03-14? unknown reasons but only RHS
#using pseudo-base solution instead
dplyr::mutate(arbo_ID = .data[[field_to_copy]])
}
standarize_fips <- function(my_tbl, fips_vector = field_fips_accepted){
# Create new field arbo_ID which will be used for matching now on
arbo_tbl <- create_id_field(my_tbl, fips_vector)
# FIPS codes, while use numbers, should be considered text/string
# e.g. numerical math is meaningless
#1. convert to character
#2. convert to standard 5 character (2 state + 3 county) format
# if length 5, good
# if length 4, then full but probably read in as number and state has leading 0
# -> pad 0 in front
# if length 3 -> add state code
# if length 2, then county code but read as number and county has leading 0
# -> pad 0 in front to 3, and add state code
#grab state fips code from shp, as string
state_fips <- data_sf$STATEFP %>% unique() %>% as.character()
#attempt to handle possible read-ins and formats of fips codes in user data
arbo_tbl <- arbo_tbl %>%
dplyr::mutate(arbo_ID = as.character(arbo_ID),
arbo_ID = dplyr::case_when(
stringr::str_length(arbo_ID) == 4 ~ stringr::str_pad(arbo_ID, width = 5,
side = "left", pad = "0"),
stringr::str_length(arbo_ID) == 3 ~ paste0(.env$state_fips, arbo_ID),
stringr::str_length(arbo_ID) == 2 ~ paste0(.env$state_fips,
stringr::str_pad(arbo_ID, width = 3,
side = "left", pad = "0")),
TRUE ~ arbo_ID))
return(arbo_tbl)
}
simplifynames <- function(priornames=NULL) {
#ORIGINAL name matching
# convert to lower case
priornames <- tolower(priornames)
# remove spaces
priornames <- gsub(pattern=" ", replacement="", x=priornames, fixed=TRUE)
# remove other offending placename modifiers
priornames <- gsub(pattern="county", replacement="", x=priornames, fixed=TRUE)
priornames <- gsub(pattern="parish", replacement="", x=priornames, fixed=TRUE)
priornames <- gsub(pattern="par.", replacement="", x=priornames, fixed=TRUE)
priornames <- gsub(pattern="(zone)", replacement="", x=priornames, fixed=TRUE)
priornames <- gsub(pattern="lower", replacement="", x=priornames, fixed=TRUE)
priornames <- gsub(pattern="upper", replacement="", x=priornames, fixed=TRUE)
priornames <- gsub(pattern="southern", replacement="", x=priornames, fixed=TRUE)
priornames <- gsub(pattern="northern", replacement="", x=priornames, fixed=TRUE)
priornames <- gsub(pattern="saint", replacement="", x=priornames, fixed=TRUE)
priornames <- gsub(pattern="st", replacement="", x=priornames, fixed=TRUE)
priornames <- gsub(pattern=".", replacement="", x=priornames, fixed=TRUE)
# return names
return(priornames)
}
standarize_names <- function(my_tbl, names_vector = field_names_accepted){
#Create new field arbo_ID which will be used for matching now on
arbo_tbl <- create_id_field(my_tbl, names_vector)
#Use original name simplification
arbo_tbl <- arbo_tbl %>%
dplyr::mutate(arbo_ID = simplifynames(arbo_ID))
}
# Set up arbo_ID
if (confirm_id_fields(field_fips_accepted)){
# use fips as arbo_ID
id_as_fips <- TRUE
id_as_names <- FALSE
data_human <- standarize_fips(data_human)
data_mosquito <- standarize_fips(data_mosquito)
data_env_raw <- standarize_fips(data_env_raw)
if (!is.null(data_strata)){
data_strata <- standarize_fips(data_strata)
}
# data_sf will be dealt with separately, as it is standard format
#census shape: GEOID is 5 char FIPS code
data_sf <- data_sf %>%
dplyr::mutate(arbo_ID = GEOID)
} else if (confirm_id_fields(field_names_accepted)){
# use county names as arbo_ID
id_as_fips <- FALSE
id_as_names <- TRUE
data_human <- standarize_names(data_human)
data_mosquito <- standarize_names(data_mosquito)
data_env_raw <- standarize_names(data_env_raw)
if (!is.null(data_strata)){
data_strata <- standarize_names(data_strata)
}
# data_sf will be dealt with separately, as it is standard format
#census shape: NAME is county name
data_sf <- data_sf %>%
dplyr::mutate(arbo_ID = simplifynames(NAME))
}#end arbo_ID setup
#Create a crosswalk from arbo_ID to 'pretty' names (data_sf$NAME)
id_crosswalk <- data_sf %>%
sf::st_drop_geometry() %>%
dplyr::select(NAME, GEOID, arbo_ID) %>%
dplyr::rename(FIPS = GEOID)
#If county highlights (dev), then set up proper IDs here
if (highlight_flag){
#using names, need to crosswalk from user given name to simplename arbo_ID
# user given names MUST match shapefile standard name (NAME)
if (id_as_names){
highlight_ids <- id_crosswalk$arbo_ID[match(highlight, id_crosswalk$NAME)]
} else {
#if using fips, use as is
highlight_ids <- highlight
}
}
```
```{r data_dates, echo=FALSE, include=FALSE, cache=FALSE}
# Dates in data
# "date_obs" will become the standard date field name of the observed
# "date_epi" will become the standard date for modelling weeks (END date of epiweek)
# Filtering on years given in parameters
# Setting up week-related variables, in CDC epiweeks
##Functions
# epiwday borrowed from epidemiar, originally written by Chris Merkord, defaults changed here
epiwday <- function(x, system = "CDC") {
week_type <- match.arg(system, c("ISO", "CDC"))
if (week_type == "ISO") {
as.integer(lubridate::wday(x - 1))
} else if (week_type == "CDC") {
as.integer(lubridate::wday(x))
}
}
# make_date_yw borrowed from epidemiar, originally written by Chris Merkord, defaults changed here
make_date_yw <- function(year = 1970L, week = 1L, weekday = 7L, system = "CDC") {
#year: epidemiological year
#week: epidemiological week number (1--53).
#weekday: epidemiological weekday number (1--7). Day 1 is a Monday in
# the ISO-8601 WHO system and a Sunday in the CDC system. DEFAULT is LAST day of week (7)
#system: String indicating the standard (WHO ISO-8601 or CDC epiweeks) ["ISO" or "CDC"].
week_type <- match.arg(system, c("ISO", "CDC"))
lengths <- vapply(list(year, week, weekday), length, 1, USE.NAMES = FALSE)
if (min(lengths) == 0L) as.Date(integer(), lubridate::origin)
# recycle arguments
N <- max(lengths)
y <- rep_len(as.integer(year), N)
w <- rep_len(as.integer(week), N)
d <- rep_len(as.integer(weekday), N)
out <-
ifelse(
is.na(y) | is.na(w) | is.na(d), NA,
{
jan1 <- lubridate::make_date(y, 1, 1)
wday <- epiwday(jan1, week_type)
to_add <- ifelse(wday <= 4, 1, 8) - wday
wk1 <- jan1 + to_add
day1 <- wk1 + (w - 1) * 7
day1 + d - 1
}
)
as.Date(out, lubridate::origin)
}
# find last epiweek in a year: will be either 52 or 53
get_last_epiweek <- function(year){
#first pass, get epiweek of Dec 31 of the year
dec31 <- as.Date(paste0(year, "-12-31"), "%Y-%m-%d")
dec31_epiweek <- lubridate::epiweek(dec31)
# Dec 31 might fall into 1st week of following year
if (dec31_epiweek == 1){
#if so, then get epiweek of the week prior instead
prev_epiweek <- lubridate::epiweek(dec31 - lubridate::weeks(1))
return(prev_epiweek)
} else {return(dec31_epiweek)}
}
# Note: tryCatch not helpful b/c of as.Date return values
# > as.Date("2019-6-4")
# [1] "2019-06-04"
# > as.Date("2019-6-4", "%m/%d/%Y")
# [1] NA
# > as.Date("6/4/2019")
# [1] "0006-04-20"
# also note that tryCatch doesn't work inside mutate plain
# need rowwise or other solution to use that
# So below solution is not quite as robust as it could be,
# but it should be pretty good
data_human <- data_human %>%
#try old specified format first
#gives NA when given dates like "2019-6-4"
dplyr::mutate(date_obs = as.Date(date, format = "%m/%d/%Y"),
#test for NA and let as.Date guess this time
#MUST use ifelse, not if_else b/c that evaluates all
# and as.Date will throw error if given the old format without pattern
# however ifelse strips date format, so must cast it afterwards
# note: zoo package used for default origin for as.Date()
date_obs = as.Date(ifelse(is.na(date_obs),
as.Date(date),
date_obs)))
data_mosquito <- data_mosquito %>%
#try old specified format first
#gives NA when given dates like "2019-6-4"
dplyr::mutate(date_obs = as.Date(col_date, format = "%m/%d/%Y"),
#test for NA and let as.Date guess this time
#MUST use ifelse, not if_else b/c that evaluates all
# and as.Date will throw error if given the old format without pattern
# however ifelse strips date format, so must cast it afterwards
# note: zoo package used for default origin for as.Date()
date_obs = as.Date(ifelse(is.na(date_obs),
as.Date(col_date),
date_obs)))
## Filter data by year parameters
# More data may be present in the files than what we want to use
# e.g. incomplete year data
# Adds useful date parts as fields for use here and later
# Note: Epi year is used for filtering for consistency with using epiweeks
data_human <- data_human %>%
#year field for filtering
dplyr::mutate(#epi year
year_epi = lubridate::epiyear(date_obs),
#epiweek
week_epi = lubridate::epiweek(date_obs),
date_epi = make_date_yw(year = year_epi, week = week_epi, weekday = 7),
#also doy
doy = lubridate::yday(date_obs)) %>%
#filter year range from parameter input
dplyr::filter(year_epi >= params$year_human_start &
year_epi <= params$year_human_end)
data_mosquito <- data_mosquito %>%
#date fields for filtering (here and later in mosq modelling)
dplyr::mutate(year_cal = lubridate::year(date_obs),
#epi year and week
year_epi = lubridate::epiyear(date_obs),
week_epi = lubridate::epiweek(date_obs),
date_epi = make_date_yw(year = year_epi,
week = week_epi,
weekday = 7),
#also doy, used later in mosq modelling
doy = lubridate::yday(date_obs)) %>%
#filter year range from parameter input
dplyr::filter(year_epi >= params$year_mosquito_start &
year_epi <= params$year_mosquito_end)
#Note: doy filtering happens in code block data_mosq_processing_dx below
data_env_raw <- data_env_raw %>%
#filter year range from parameter input
#already has year field from GEE, however
# will ALSO have epi year
dplyr::mutate(date_obs = as.Date(paste(year, doy, sep = "-"),
"%Y-%j"),
#epi year and week
year_epi = lubridate::epiyear(date_obs),
week_epi = lubridate::epiweek(date_obs),
date_epi = make_date_yw(year = year_epi,
week = week_epi,
weekday = 7)) %>%
dplyr::filter(year_epi >= params$year_weather_start &
year_epi <= params$year_weather_end)
## Dates for forecasts and functions
# Now using CDC epiweeks (MMWR week)
# The date associated with the epiweek will be the LAST day of the epiweek
#Forecast week
#week of forecast, given by user
date_request <- as.Date(params$forecast_date, "%Y-%m-%d")
#epi week of requested date
epiweek_request <- lubridate::epiweek(date_request)
#epi year of requested date
epiyear_request <- lubridate::epiyear(date_request)
#ENDING date of the requested epi week
date_epiweek_request <- make_date_yw(year = epiyear_request,
week = epiweek_request,
weekday = 7)
#day of year of the ending date of the requested epiweek
doy_dt_epiwk_req <- lubridate::yday(date_epiweek_request)
#Modelling years
# Used to be separate parameter, but is really driven by other inputs
# To avoid confusion and mismatches years in strange ways,
# now being set internally
# Start year is the same of the start of human data.
# Can't model before human data, and to move modelling start, change start of human data
year_modeling_start <- params$year_human_start
# End year is the year of the forecast date
year_modeling_end <- epiyear_request
#Various other dates
#ending date of the FIRST epiweek in the MIN modelling year
date_min_model <- make_date_yw(year = year_modeling_start,
week = 1,
weekday = 7)
#ending date of LAST epiweek in the MAX modelling year
date_max_model <- make_date_yw(year = year_modeling_end,
week = get_last_epiweek(year_modeling_end), #could be 52 or 53
weekday = 7)
```
```{r data_human_processing_dx, echo=FALSE, include=FALSE, cache=FALSE}
## Human
#Record row count (in human_year_start through human_year_end)
data_human_range <- data_human
dx_human_nrow_1range <- nrow(data_human_range)
#Clean human data
# remove any with unmatched county info
# especially necessary for doing regression modeling
data_human <- data_human %>%
dplyr::filter(arbo_ID %in% unique(data_sf$arbo_ID),
#remove any without a good date
(!is.na(date_obs)))
#Record row count post cleaning
dx_human_nrow_2clean <- nrow(data_human)
#any rows unmatched
dx_human_unmatched <- data_human_range %>%
#let it match columns on its own
dplyr::anti_join(data_human) %>%
#file original date field to display in table
dplyr::select(arbo_ID, date)
#gather list of counties in cleaned human data
dx_human_counties <- data_human %>%
dplyr::pull(arbo_ID) %>% unique() %>% sort()
#min/max years of data actually PRESENT in the cleaned input data
# (within the user-supplied range of years to use in modeling)
# If set up normally, these should align, but it is not necessarily true
human_exists_yr_min <- min(data_human$year_epi, na.rm = TRUE)
human_exists_yr_max <- max(data_human$year_epi, na.rm = TRUE)
human_exists_yr_list <- data_human$year_epi %>% unique() %>% sort()
#are there years between requested start/end years that no data were observed for?
#NOTE: These may be zero-case years! (and therefore fine). Or potentially missing data.
human_yrs_missing <- setdiff(params$year_human_start:params$year_human_end,
human_exists_yr_list)
#[V3] [DEV] imputemissingdistricts was hard coded as FALSE in v3 production code
# updated names and code, and added dev option for renamed impute_human_missing_districts, default = FALSE