forked from CHAD-Analytics/CHAD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglobal.R
3814 lines (3169 loc) · 200 KB
/
global.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
##################
##### Global #####
##################
# Layout
##############################################################################################################################################
# The global introduces all libraries, functions, datasets, and formatting that is necessary to pass through the server.
# First: The libraries are loaded which have built in functions are used throughout the app.
# Second: We load data from https://github.com/treypujats/COVID19/tree/master/covid19/data , usafacts.org , and covid19.healthdata.org
# The github data has static information on on all air force bases, US counties, and US hospitals.
# The usafacts data has dynamic information that is updated daily reporting the number of cases and number of deaths daily.
# The IHME provides projection data of the pandemic
# After loading the data, we format headers, establish data tables for printing, and do any static changes to the dataset for the app.
# Third: Functions are used to execute the tasks in the server. Functions in the global are not dynamic, but they take in dynamic inputs
# Global functions are used to calculate statistics, make data tables, plot graphs, and create visuals.
##############################################################################################################################################
# Step One
###################################################################################################################################################
#Loads in all necessary packages for the shiny app
library(stringr)
library(stringi)
library(markdown)
library(plyr)
library(dplyr)
library(ggplot2)
library(tidyr)
library(shinydashboard)
library(shiny)
library(geosphere)
library(scales)
library(googleVis)
library(usmap)
library(data.table)
library(jsonlite)
library(splitstackshape)
library(DT)
library(mapproj)
library(viridis)
library(tidyverse)
library(zoo) #used for rollsum function
library(rmarkdown)
library(rvest)
library(maps)
library(tm)
library(sf)
library(ggrepel)
library(tigris)
library(plotly)
# Step Two
###################################################################################################################################################
#Define Variables and load in data up front if necessary.
#This data updates daily with CovidConfirmedCases and CovidDeaths. These numbers are updated every day.
#The static data (countyinfo, hospitalinfo, AFBaseLocations) is used to for lat and long coordinates to measure distance.
#Hospital Data allows us to determine the bed capacity of all hospitals in the nation
#AFBaseLocations provide names and coordinates of base.
#CountyInfo is used to measure population of a county and coordinates.
#CovidConfirmedCases <- as.data.frame(data.table::fread("https://usafactsstatic.blob.core.windows.net/public/data/covid-19/covid_confirmed_usafacts.csv"))
CovidConfirmedCases <- as.data.frame(data.table::fread("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_US.csv"))
#CovidConfirmedCases<-CovidConfirmedCases[colSums(!is.na(CovidConfirmedCases)) > 0]
CovidConfirmedCases<-CovidConfirmedCases[colSums(!is.na(CovidConfirmedCases)) > 0]
CountyInfo <- as.data.frame(data.table::fread("https://github.com/treypujats/CHAD/raw/master/data/countyinfo.rda"))
HospitalInfo <- as.data.frame(data.table::fread("https://github.com/treypujats/CHAD/blob/master/data/hospitalinfo.rda?raw=true"))
#CovidDeaths<-as.data.frame(data.table::fread("https://usafactsstatic.blob.core.windows.net/public/data/covid-19/covid_deaths_usafacts.csv"))
CovidDeaths<-as.data.frame(data.table::fread("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_US.csv"))
HospUtlzCounty <- read.csv("https://github.com/treypujats/CHAD/raw/master/data/county_hospitals.csv")
CountyHospRate <- read.csv("https://github.com/treypujats/CHAD/raw/master/data/CountyHospRateCalc.csv")
#himd <- as.data.frame(data.table::fread("https://github.com/treypujats/COVID19/blob/master/covid19/data/himd.rda?raw=true"))
#cimd <- as.data.frame(data.table::fread("https://github.com/treypujats/COVID19/blob/master/covid19/data/cimd.rda?raw=true"))
#AFBaseLocations <- as.data.frame(data.table::fread("https://github.com/treypujats/COVID19/raw/master/covid19/data/baseinfo.rda"))
#Updated data frames to read in
githubURL <- "https://github.com/treypujats/CHAD/blob/master/data/cimd.RData?raw=true"
load(url(githubURL))
githubURL <- "https://github.com/treypujats/CHAD/blob/master/data/himd.RData?raw=true"
load(url(githubURL))
githubURL <- "https://github.com/treypujats/CHAD/blob/master/data/baseinfo_new.RData?raw=true"
load(url(githubURL))
######################### ADDED TO MAKE JHU DATA FRAME LOOK LIKE EXISTING DATA FRAMEs#################################
#Updating data frames to ensure they are filled and match the data we reference later in the scripts
#colnames(CovidConfirmedCases)[1]<-"CountyFIPS"
# Keep county fips code and all cases data
CovidConfirmedCases<-CovidConfirmedCases[,c(5, 12:ncol(CovidConfirmedCases))]
colnames(CovidConfirmedCases)[1]<-"CountyFIPS"
CovidDeaths<-CovidDeaths[,c(5, 13:ncol(CovidDeaths))]
colnames(CovidDeaths)[1]<-"CountyFIPS"
#Get state infomration based on county fips code
StateInfo<-fips_codes[c(5,1,2,4)]
#combine state and county codes to get CountyFIPS code
StateInfo$county_code <- paste(StateInfo$state_code,StateInfo$county_code, sep="")
#make countyFIPS code a numeric value
StateInfo[, c(3,4)] <- sapply(StateInfo[, c(3,4)], as.numeric)
#names for headers
colnames(StateInfo)[1:4]<-c("County Name", "State","stateFIPS","CountyFIPS")
CovidConfirmedCases<-merge(StateInfo,CovidConfirmedCases,by = "CountyFIPS")
CovidDeaths<-merge(StateInfo,CovidDeaths,by = "CountyFIPS")
#################################END JHU DATA PREP############################################
colnames(CovidDeaths)[1]<-"CountyFIPS"
HospitalInfo$BEDS <- ifelse(HospitalInfo$BEDS < 0, 0, HospitalInfo$BEDS)
CovidConfirmedCases[is.na(CovidConfirmedCases)]<-0
CovidDeaths[is.na(CovidDeaths)]<-0
colnames(CovidConfirmedCases)[1]<-"CountyFIPS"
#Read in IHME data for projecting data in the future
temp <- tempfile()
download.file("https://ihmecovid19storage.blob.core.windows.net/latest/ihme-covid19.zip", temp, mode="wb")
zipdf <- unzip(temp, list = TRUE)
csv_file <- zipdf$Name[2]
IHME_Model <- read.table(unz(temp, csv_file), header = T, sep = ",")
unlink(temp)
IHME_Model$date <- as.Date(IHME_Model$date, format = "%Y-%m-%d")
StateList <- data.frame(state.name, state.abb)
IHME_Model <- merge(IHME_Model, StateList, by.x = names(IHME_Model)[1], by.y = names(StateList)[1])
names(IHME_Model)[names(IHME_Model)=="state.abb"] <- "State"
#From Columbia U, These files contain 42 day projections which they update on Sunday evenings.
#https://github.com/shaman-lab/COVID-19Projection/tree/master/
#CU40PSD<-read.csv("https://raw.githubusercontent.com/shaman-lab/COVID-19Projection/master/Projection_April19/Projection_60contact.csv")
#CU30PSD<-read.csv("https://raw.githubusercontent.com/shaman-lab/COVID-19Projection/master/Projection_April19/Projection_70contact.csv")
#CU20PSD<-read.csv("https://raw.githubusercontent.com/shaman-lab/COVID-19Projection/master/Projection_April19/Projection_80contact.csv")
#CU00PSD<-read.csv("https://raw.githubusercontent.com/shaman-lab/COVID-19Projection/master/Projection_April19/Projection_nointerv.csv")
CU40PSD<-read.csv("https://raw.githubusercontent.com/shaman-lab/COVID-19Projection/master/Projection_April19/bed_60contact.csv")
CU30PSD<-read.csv("https://raw.githubusercontent.com/shaman-lab/COVID-19Projection/master/Projection_April19/bed_70contact.csv")
CU20PSD<-read.csv("https://raw.githubusercontent.com/shaman-lab/COVID-19Projection/master/Projection_April19/bed_80contact.csv")
CU00PSD<-read.csv("https://raw.githubusercontent.com/shaman-lab/COVID-19Projection/master/Projection_April19/bed_nointerv.csv")
CU40PSD<-CU40PSD %>% separate(county,c("County","State"))
CU30PSD<-CU30PSD %>% separate(county,c("County","State"))
CU20PSD<-CU20PSD %>% separate(county,c("County","State"))
CU00PSD<-CU00PSD %>% separate(county,c("County","State"))
CU40PSD<-subset(CU40PSD, select=-c(hosp_need_2.5,hosp_need_97.5,ICU_need_2.5,ICU_need_25,ICU_need_50,ICU_need_75,ICU_need_97.5,
vent_need_2.5,vent_need_25,vent_need_50,vent_need_75,vent_need_97.5,death_2.5,death_97.5))
CU30PSD<-subset(CU30PSD, select=-c(hosp_need_2.5,hosp_need_97.5,ICU_need_2.5,ICU_need_25,ICU_need_50,ICU_need_75,ICU_need_97.5,
vent_need_2.5,vent_need_25,vent_need_50,vent_need_75,vent_need_97.5,death_2.5,death_97.5))
CU20PSD<-subset(CU20PSD, select=-c(hosp_need_2.5,hosp_need_97.5,ICU_need_2.5,ICU_need_25,ICU_need_50,ICU_need_75,ICU_need_97.5,
vent_need_2.5,vent_need_25,vent_need_50,vent_need_75,vent_need_97.5,death_2.5,death_97.5))
CU00PSD<-subset(CU00PSD, select=-c(hosp_need_2.5,hosp_need_97.5,ICU_need_2.5,ICU_need_25,ICU_need_50,ICU_need_75,ICU_need_97.5,
vent_need_2.5,vent_need_25,vent_need_50,vent_need_75,vent_need_97.5,death_2.5,death_97.5))
Front<-'https://covid-19.bsvgateway.org/forecast/us/files/'
Middle<-'/confirmed/'
End<-'_confirmed_quantiles_us.csv'
Date<-Sys.Date()-4 #Have to adjust the integer value based on the date of the most recent forecast file
ReadIn<-paste0(Front,Date,Middle,Date,End)
LANL_Data<-read.csv(ReadIn)
LANL_Data<-subset(LANL_Data, select=-c(simple_state,q.01,q.025,q.05,q.10,q.15,q.20,q.30,q.35,q.40,q.45,q.55,q.60,q.65,q.70,q.80,q.85,q.90,q.95,q.975,q.99,truth_confirmed,fcst_date))
LANL_Data <- merge(LANL_Data, StateList, by.x = names(LANL_Data)[6], by.y = names(StateList)[1])
names(LANL_Data)[names(LANL_Data)=="state.abb"] <- "State"
#Create list of hospitals, bases, and counties.
BaseList<-sort(AFBaseLocations$Base, decreasing = FALSE)
HospitalList <- HospitalInfo$NAME
CountyList <- CountyInfo$County
MAJCOMList <- sort(unique(AFBaseLocations$`Major Command`), decreasing = FALSE)
MAJCOMList<-c("All",'Active Duty',MAJCOMList)
#Calculate county case doubling rate for most recent day
CovidConfirmedCases <- dplyr::filter(CovidConfirmedCases, CountyFIPS != 0)
CovidConfirmedCases <- head(CovidConfirmedCases,-1)
#Get rid of days with incorrect cumulative reporting of zeros after reported cases have been seen
for (i in 6:(ncol(CovidConfirmedCases))){
CovidConfirmedCases[,i] = ifelse(CovidConfirmedCases[,i] < CovidConfirmedCases[,(i-1)],
CovidConfirmedCases[,(i-1)],
CovidConfirmedCases[,i])
}
currCount = 0
v <- rep(0, as.numeric(ncol(CovidConfirmedCases)))
for (i in 1:nrow(CovidConfirmedCases)){
j = 0
cases = CovidConfirmedCases[i,ncol(CovidConfirmedCases)]
if (cases != 0){
while (cases/2 < CovidConfirmedCases[i,ncol(CovidConfirmedCases)-j])
{
j = j + 1
}
days = j
}
else{
days = 0
}
v[i] <- days
}
CovidConfirmedCasesRate <- cbind(CovidConfirmedCases,v)
######################Data Specific to plotting counties and states as choropleth
#Input the Included Counties as factors
# PlottingCountyData<- read.csv("https://usafactsstatic.blob.core.windows.net/public/data/covid-19/covid_confirmed_usafacts.csv",
# header = TRUE, stringsAsFactors = FALSE)
# PlottingCountyData$county <- tolower(gsub("([A-Za-z]+).*", "\\1", PlottingCountyData$County.Name))
# PlottingCountyData$county <- gsub("^(.*) parish, ..$","\\1", PlottingCountyData$county)
# #Creating state name in addition to state abb
# PlottingCountyData<-PlottingCountyData %>%
# mutate(state_name = tolower(state.name[match(State, state.abb)]))
# #Calling in county data to merge and match, that way we have the correct coordinates when creating the map.
# county_df <- map_data("county")
# names(county_df) <- c("long", "lat", "group", "order", "state_name", "county")
# county_df$state <- state.abb[match(county_df$state_name, tolower(state.name))]
# county_df$state_name <- NULL
# #Calling in state data so we can map it correctly
# state_df <- map_data("state", projection = "albers", parameters = c(39, 45))
# colnames(county_df)[6]<-"State"
#Input the Included Counties as factors
PlottingCountyData<- read.csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_US.csv",
header = TRUE, stringsAsFactors = FALSE)
PlottingCountyData <- PlottingCountyData<-PlottingCountyData[colSums(!is.na(PlottingCountyData)) > 0]
# stopwords = "County" #Your stop words file
# x = PlottingCountyData$County.Name #Company column data
# x = removeWords(x,stopwords) #Remove stopwords
#
# df$company_new <- x #Add the list as new column and check
# PlottingCountyData$county <- tolower(removeWords(PlottingCountyData$County.Name,"County"))
# PlottingCountyData$county <-gsub(" ", "" ,PlottingCountyData$county)
# PlottingCountyData$county <- gsub("^(.*) parish, ..$","\\1", PlottingCountyData$county)
#
# #Creating state name in addition to state abb
# PlottingCountyData<-PlottingCountyData %>%
# mutate(state_name = tolower(state.name[match(State, state.abb)]))
PlottingCountyData<-data.frame(PlottingCountyData[,5],rev(PlottingCountyData)[,1])
colnames(PlottingCountyData)<-c("GEOID","Cases")
#Calling in county data to merge and match, that way we have the correct coordinates when creating the map.
county_df<-counties(state = NULL, cb = TRUE, resolution = "5m")
#######################Create National Data table on summary page
NationalDataTable<-CovidConfirmedCases
NationalDataTable$State<-as.factor(NationalDataTable$State)
NationalDataTable<-NationalDataTable[,-c(1,2,4)]
NationalDataTable<-aggregate(.~State, NationalDataTable, sum)
RateofCovidChange<-rev(NationalDataTable)[c(1:7)]
RateofCovidChange<-ceiling(rowSums(RateofCovidChange[1:6]-RateofCovidChange[2:7])/6)
NationalDeathTable<-CovidDeaths
NationalDeathTable$State<-as.factor(NationalDeathTable$State)
NationalDeathTable<-NationalDeathTable[,-c(1,2,4)]
NationalDeathTable<-aggregate(.~State, NationalDeathTable, sum)
RateofDeathChange<-rev(NationalDeathTable)[c(1:7)]
RateofDeathChange<-ceiling(rowSums(RateofDeathChange[1:6]-RateofDeathChange[2:7])/6)
NationalDataTable<-data.frame(NationalDataTable$State, NationalDataTable[,length(NationalDataTable)],RateofCovidChange, NationalDeathTable[,length(NationalDeathTable)], RateofDeathChange)
colnames(NationalDataTable)<-c("State","Total Cases","Average New Cases Per Day", "Total Deaths","Average New Deaths Per Day")
NationalDataTable$`Cases Per 100,000 People`<-c(731545,4903185,3017825,7278717,39512223,5758736,3565287,705749,973764,21477737,10617423,1415872,3155070,1787065,12671821,6732219,2913314,4467673,4648794,6949503,6045680,1344212,9986857,5639632,6137428,2976149,1068778,10488084,762062,1934408,1359711,8882190,2096829,3080156,19453561,11689100,3956971,4217737,12801989,1059361,5148714,884659,6833174,28995881,3205958,8535519,623989,7614893,5822434,1792147,578759)
NationalDataTable$`Cases Per 100,000 People`<-round(NationalDataTable$`Total Cases`/(NationalDataTable$`Cases Per 100,000 People`/100000))
# beds <- read.csv('beds.csv')
# pops <- read.csv('pops.csv')
# source('acme_support.R')
##########################################################################################################
##########################################################################################################
##########################################################################################################
############################################################################################################################################
#Use army models to create projections for the local area around the base
#Establish function for army SEIAR model. This allows us to pass though a simple function to gather all statistics when we plot
SEIAR_Model_Run<-function(num_init_cases, Pop.At.Risk, incub_period, latent_period,
doubling, recovery_days, social_rate, hospital_rate,
icu_rate, ventilated_rate, hospital_dur, icu_dur, ventilated_dur, n_days,
secondary_cases = 2.5, distribution_e_to_a = 0.5){
###DEFINING COMPARTMENTS OF THE MODEL
total_infections <- num_init_cases / (hospital_rate/100)
I <- total_infections
S <- (Pop.At.Risk - I)
E <- (total_infections*secondary_cases) * distribution_e_to_a #Assuming that each infectious person will generate 2.5 secondary cases
A <- (total_infections*secondary_cases) * (1-distribution_e_to_a) ##Distributing the secondary cases between the E and A compartments
R <- 0
###DEFINING PARAMETERS
intrinsic_growth_rate <- 2 ^(1 / doubling) -1
sigma <- 1/latent_period #Latent period (approx 2 days)
gamma_1 <- 1/(incub_period - latent_period)
gamma_2 <- 1/(recovery_days - latent_period - (incub_period - latent_period))
beta <- (intrinsic_growth_rate + (1/recovery_days)) / S * (1-social_rate/100)
r_t <- beta / (1/recovery_days) * S
r_0 <- r_t / (1 - social_rate/100)
doubling_time_t <- 1 / log2(beta*S - (1/recovery_days) + 1)
###ITERATIVE LISTING OF MODEL
myList <- list()
myList$total_infections <- total_infections
myList$S <- S
myList$E <- E
myList$A <- A
myList$I <- I
myList$R <- R
myList$intrinsic_growth_rate <- intrinsic_growth_rate
myList$sigma <- sigma
myList$gamma_1 <- gamma_1
myList$gamma_2 <- gamma_2
myList$beta <- beta
myList$r_t <- r_t
myList$r_0 <- r_0
myList$doubling_time_t <- doubling_time_t
#initial values
N = S + E + A + I + R
hos_add <- ((A+I) * hospital_rate/100)
hos_cum <- ((A+I) * hospital_rate/100)
icu_add <- (hos_add * icu_rate/100)
icu_cum <- (hos_cum * icu_rate/100)
#create the data frame
sir_data <- data.frame(t = 1,
S = S,
E = E,
A = A,
I = I,
R = R,
hos_add = hos_add,
hos_cum = hos_cum,
icu_add = hos_add * icu_rate/100,
icu_cum = hos_cum * icu_rate/100,
vent_add = icu_add * ventilated_rate/100,
vent_cum = icu_cum * ventilated_rate/100,
Id = 0
)
for(i in 2:n_days){
y <- seiar(S,E,A,I,R, beta, sigma, gamma_1, gamma_2, N)
S <- y$S
E <- y$E
A <- y$A
I <- y$I
R <- y$R
#calculate new infections
Id <- (sir_data$S[i-1] - S)
#portion of the the newly infected that are in the hospital, ICU, and Vent
hos_add <- Id * hospital_rate/100
hos_cum <- sir_data$hos_cum[i-1] + hos_add
icu_add <- hos_add * icu_rate/100
icu_cum <- sir_data$icu_cum[i-1] + icu_add
vent_add <- icu_add * ventilated_rate/100
vent_cum <- sir_data$vent_cum[i-1] + vent_add
temp <- data.frame(t = i,
S = S,
E = E,
A = A,
I = I,
R = R,
hos_add = hos_add,
hos_cum = hos_cum,
icu_add = icu_add,
icu_cum = icu_cum,
vent_add = vent_add,
vent_cum = vent_cum,
Id = Id
)
sir_data <- rbind(sir_data,temp)
}
#doing some weird stuff to get a rolling sum of hospital impacts based on length of stay (los)
if(n_days > hospital_dur){
h_c <- rollsum(sir_data$hos_add,hospital_dur)
sir_data$hos_cum <- c(sir_data$hos_cum[1:(n_days - length(h_c))],h_c)
}
if(n_days > icu_dur){
i_c <- rollsum(sir_data$icu_add,icu_dur)
sir_data$icu_cum <- c(sir_data$icu_cum[1:(n_days - length(i_c))],i_c)
}
if(n_days > ventilated_dur){
v_c <- rollsum(sir_data$vent_add,ventilated_dur)
sir_data$vent_cum <- c(sir_data$vent_cum[1:(n_days - length(v_c))],v_c)
}
#write.csv(sir_data, file = 'test.csv') # for testing
h_m <- round(max(sir_data$hos_cum), 0)
i_m <- round(max(sir_data$icu_cum), 0)
v_m <- round(max(sir_data$vent_cum), 0)
myList$sir <- sir_data
myList$hos_max <- h_m
myList$icu_max <- i_m
myList$vent_max <- v_m
h_m <- sir_data$t[which.max(sir_data$hos_cum)][1]
i_m <- sir_data$t[which.max(sir_data$icu_cum)][1]
v_m <- sir_data$t[which.max(sir_data$vent_cum)][1]
myList$hos_t_max <- h_m
myList$icu_t_max <- i_m
myList$vent_t_max <- v_m
h_m <- round(max(sir_data$hos_add), 0)
i_m <- round(max(sir_data$icu_add), 0)
v_m <- round(max(sir_data$vent_add), 0)
myList$hos_add <- h_m
myList$icu_add <- i_m
myList$vent_add <- v_m
return(myList)
}
seiar<-function(S,E,A,I,R, beta, sigma, gamma_1, gamma_2, N){
Sn <- (-beta * S * (A + I)) + S
En <- ((beta * S * (A + I)) - (sigma * E)) + E
An <- ((sigma * E) - (gamma_1 * A)) + A
In <- ((gamma_1 * A) - (gamma_2 * I)) + I
Rn <- (gamma_2 * I) + R
if(Sn < 0) Sn = 0
if(En < 0) En = 0
if(An < 0) An = 0
if(In < 0) In = 0
if(Rn < 0) Rn = 0
scale = N / (Sn + En + An + In + Rn)
myListSIR <- list()
myListSIR$S <- (Sn * scale)
myListSIR$E <- (En * scale)
myListSIR$A <- (An * scale)
myListSIR$I <- (In * scale)
myListSIR$R <- (Rn * scale)
return(myListSIR)
}
#######################################################
############### Helper Functions ######################
#######################################################
GetCounties<-function(base,radius){
#Find counties in radius
baseDF = dplyr::filter(AFBaseLocations, Base == base)
CountyInfo$DistanceMiles = cimd[,as.character(base)]
IncludedCounties<-dplyr::filter(CountyInfo, DistanceMiles <= radius | FIPS == baseDF$FIPS)
IncludedCounties
}
GetHospitals<-function(base,radius){
#Find number of hospitals in radius
HospitalInfo$DistanceMiles = himd[,as.character(base)]
IncludedHospitals<-dplyr::filter(HospitalInfo, (DistanceMiles <= radius))
IncludedHospitals<-dplyr::filter(IncludedHospitals, (TYPE=="GENERAL ACUTE CARE") | (TYPE=="CRITICAL ACCESS"))
IncludedHospitals
}
###################################################################################################################################################
# Statistics for Local Health Page -------------------------------------------------------------------------------------------------------------------------------------
CalculateCounties<-function(IncludedCounties){
#Get the total population in the selected region
TotalPopulation <- sum(IncludedCounties$Population)
TotalPopulation
}
CalculateCovid<-function(IncludedCounties){
#Get total confirmed cases in the selected region
CovidCounties<-subset(CovidConfirmedCases, CountyFIPS %in% IncludedCounties$FIPS)
sum(rev(CovidCounties)[,1])
}
CalculateCovid1000<-function(IncludedCounties){
#Get total confirmed cases in the selected region
CovidCounties<-subset(CovidConfirmedCases, CountyFIPS %in% IncludedCounties$FIPS)
#<<<<<<< HEAD
(sum(rev(CovidCounties)[,1]))/(sum(IncludedCounties$Population))*1000
#=======
ceiling((sum(rev(CovidCounties)[,1]))/(sum(IncludedCounties$Population))*1000)
#>>>>>>> 8b35c79f282f7aeef240f33b22273dce0dd9da15
}
CalculateDeaths<-function(IncludedCounties){
#Get total deaths in the selected region
CovidCountiesDeath<-subset(CovidDeaths, CountyFIPS %in% IncludedCounties$FIPS)
sum(rev(CovidCountiesDeath)[,1])
}
HospitalIncreases<-function(IncludedCounties){
#Find hospitals in selected region
hospCounty <- subset(HospUtlzCounty, fips %in% IncludedCounties$FIPS)
#Calculate total beds and weighted average utilization
TotalBeds<-sum(hospCounty$num_staffed_beds)
hospCounty$bedsUsed <- hospCounty$bed_utilization * hospCounty$num_staffed_beds
totalUsedBeds <- sum(hospCounty$bedsUsed)
baseUtlz <- totalUsedBeds/TotalBeds
#Get COVID cases and county demographic hospitalization rates
CovidCounties<-subset(CovidConfirmedCases, CountyFIPS %in% IncludedCounties$FIPS)
CovidCountiesHospRate <- subset(CountyHospRate, FIPS %in% IncludedCounties$FIPS)
#Estimate current hospital utilization
TotalHospital<-sum(CovidCounties[,length(CovidCounties)]*CovidCountiesHospRate$HospRate)
NotHospital<-sum(CovidCounties[,(length(CovidCounties)-5)]*CovidCountiesHospRate$HospRate)
StillHospital<-ceiling((TotalHospital-NotHospital))
Utilz<- round(((StillHospital)/TotalBeds+baseUtlz)*100,0)
paste(Utilz," %", sep = "")
}
CaseDblRate <- function(IncludedCounties){
#Find counties in radius
CovidCountiesCases<-subset(CovidConfirmedCases, CountyFIPS %in% IncludedCounties$FIPS)
#Compute cumlative cases and deaths in selected counties
CumDailyCovid<-colSums(CovidCountiesCases[,5:length(CovidCountiesCases)])
j = 0
cases = CumDailyCovid[length(CumDailyCovid)]
if (cases != 0){
while (cases/2 < CumDailyCovid[length(CumDailyCovid)-j])
{
j = j + 1
}
days = j
}else{
days = 0
}
v <- days
}
Estimate_Rt <- function(IncludedCounties){
#Find counties in radius
CovidCountiesCases<-subset(CovidConfirmedCases, CountyFIPS %in% IncludedCounties$FIPS)
#Compute cumlative cases and deaths in selected counties
CumDailyCovid<-colSums(CovidCountiesCases[,5:length(CovidCountiesCases)])
#5-day and 14-day averages
len = length(CumDailyCovid)
cases5day = CumDailyCovid[len] - CumDailyCovid[len-5]
cases14day = CumDailyCovid[len] - CumDailyCovid[len-14]
avg5 = cases5day/5
avg14 = cases14day/14
if (avg14 == 0){
Rt = "Undefined for Region"
} else{
Rt = round(avg5/avg14,2)
}
}
###############################################################
###############################################################
CalculateCHIMEPeak<-function(IncludedCounties, ChosenBase, ChosenRadius, SocialDistance, ProjectedDays, StatisticType){
if (StatisticType == "Hospitalizations") {
BaseState<-dplyr::filter(AFBaseLocations, Base == ChosenBase)
#Get data for counties with covid cases. We want number of cases, the rate of the cases and maybe other data.
#We include State, county, population in those counties, cases, fatalities, doubling rate
CovidCounties<-subset(CovidConfirmedCases, CountyFIPS %in% IncludedCounties$FIPS)
HistoricalData<-colSums(CovidCounties[,5:length(CovidCounties)])
HistoricalDates<-seq(as.Date("2020-01-22"), length=length(HistoricalData), by="1 day")
HistoricalData<-data.frame(HistoricalDates, HistoricalData*.21, HistoricalData*.15, HistoricalData*.27)
colnames(HistoricalData)<-c("ForecastDate", "Expected Daily Cases","Minimum Daily Cases","Maximum Daily Cases")
DeathCounties<-subset(CovidDeaths, CountyFIPS %in% IncludedCounties$FIPS)
CaseRate <- subset(CovidConfirmedCasesRate, CountyFIPS %in% IncludedCounties$FIPS)
CountyDataTable<-cbind(IncludedCounties,rev(CovidCounties)[,1],rev(DeathCounties)[,1],rev(CaseRate)[,1])
CountyDataTable<-data.frame(CountyDataTable$State,CountyDataTable$County,CountyDataTable$Population, rev(CountyDataTable)[,3], rev(CountyDataTable)[,2],rev(CountyDataTable)[,1])
colnames(CountyDataTable)<-c("State","County","Population","Total Confirmed Cases","Total Fatalities", "Case Doubling Rate (days)" )
#Cleaning it up to input into the SEIAR model, we include countyFIPS, CountyName, State, State FIPS, number of cases, population, and doubling rate
#We take the data and create a dataframe called SIR inputs. It checks out by total cases, total population, and average doubling rate
ActiveCases<-rev(CovidCounties)[1:7]
ActiveCases<-data.frame(CovidCounties[,1:4],ActiveCases[,1], IncludedCounties$Population, CountyDataTable$`Case Doubling Rate (days)`)
colnames(ActiveCases)<-c("CountyFIPS","CountyName","State","StateFIPS","CurrentCases", "Population", "Doubling Rate")
SIRinputs<-data.frame(sum(ActiveCases$CurrentCases),sum(ActiveCases$Population), mean(ActiveCases$`Doubling Rate`))
colnames(SIRinputs)<-c("cases","pop","doubling")
####################################################################################
#Mean Estimate
#Next we use the calculated values, along with estimated values from the Estimated Values.
#The only input we want from the user is the social distancing rate. For this example, we just use 0.5
cases<-SIRinputs$cases
pop<-SIRinputs$pop
doubling<-8
#Established Variables at the start for every county or populations
Ro<-2.5
incubationtime<-5
latenttime<-2
recoverydays<-14
socialdistancing<-SocialDistance
hospitalizationrate<-5
icurate<-6
ventilatorrate<-3
hospitaltime<-3.5
icutime<-4
ventilatortime<-7
daysforecasted<-ProjectedDays
#Now we throw the values above into the SEIAR model, and we create dates for the number of days we decided to forecast as well (place holder for now).
#With the outputs, we grab the daily hospitalized people and the cumulative hospitalizations. Then we name the columns
SEIARProj<-SEIAR_Model_Run(cases, pop, incubationtime, latenttime,doubling,recoverydays,
socialdistancing,hospitalizationrate, icurate,ventilatorrate,hospitaltime,icutime,
ventilatortime,daysforecasted,Ro, .5)
MyDates<-seq(Sys.Date()-(length(CovidCounties)-80), length=daysforecasted, by="1 day")
DailyData<-data.frame(MyDates, SEIARProj$sir$hos_add)
TotalData<-data.frame(MyDates, SEIARProj$sir$hos_cum)
colnames(DailyData)<-c("ForecastDate", "Expected Daily Cases")
colnames(TotalData)<-c("ForecastDate", "Total Daily Cases")
DailyData<-DailyData[-1,]
DailyData<- dplyr::filter(DailyData, ForecastDate >= Sys.Date())
Peak<-which.max(DailyData$`Expected Daily Cases`)
Peak<-DailyData[Peak,2]
round(Peak)
} else {
BaseState<-dplyr::filter(AFBaseLocations, Base == ChosenBase)
#Get data for counties with covid cases. We want number of cases, the rate of the cases and maybe other data.
#We include State, county, population in those counties, cases, fatalities, doubling rate
CovidCounties<-subset(CovidConfirmedCases, CountyFIPS %in% IncludedCounties$FIPS)
CovidDeathsHist<-subset(CovidDeaths, CountyFIPS %in% IncludedCounties$FIPS)
HistoricalData<-colSums(CovidDeathsHist[,5:length(CovidDeathsHist)])
HistoricalDates<-seq(as.Date("2020-01-22"), length=length(HistoricalData), by="1 day")
HistoricalData<-data.frame(HistoricalDates, HistoricalData, HistoricalData, HistoricalData)
colnames(HistoricalData)<-c("ForecastDate", "Expected Fatalities","Lower Estimate","Upper Estimate")
DeathCounties<-subset(CovidDeaths, CountyFIPS %in% IncludedCounties$FIPS)
CaseRate <- subset(CovidConfirmedCasesRate, CountyFIPS %in% IncludedCounties$FIPS)
CountyDataTable<-cbind(IncludedCounties,rev(CovidCounties)[,1],rev(DeathCounties)[,1],rev(CaseRate)[,1])
CountyDataTable<-data.frame(CountyDataTable$State,CountyDataTable$County,CountyDataTable$Population, rev(CountyDataTable)[,3], rev(CountyDataTable)[,2],rev(CountyDataTable)[,1])
colnames(CountyDataTable)<-c("State","County","Population","Total Confirmed Cases","Total Fatalities", "Case Doubling Rate (days)" )
#Cleaning it up to input into the SEIAR model, we include countyFIPS, CountyName, State, State FIPS, number of cases, population, and doubling rate
#We take the data and create a dataframe called SIR inputs. It checks out by total cases, total population, and average doubling rate
ActiveCases<-rev(CovidCounties)[1:7]
ActiveCases<-data.frame(CovidCounties[,1:4],ActiveCases[,1], IncludedCounties$Population, CountyDataTable$`Case Doubling Rate (days)`)
colnames(ActiveCases)<-c("CountyFIPS","CountyName","State","StateFIPS","CurrentCases", "Population", "Doubling Rate")
SIRinputs<-data.frame(sum(ActiveCases$CurrentCases),sum(ActiveCases$Population), mean(ActiveCases$`Doubling Rate`))
colnames(SIRinputs)<-c("cases","pop","doubling")
####################################################################################
#Mean Estimate
#Next we use the calculated values, along with estimated values from the Estimated Values.
#The only input we want from the user is the social distancing rate. For this example, we just use 0.5
cases<-SIRinputs$cases
pop<-SIRinputs$pop
doubling<-8
#Established Variables at the start for every county or populations
Ro<-2.5
incubationtime<-5
latenttime<-2
recoverydays<-14
socialdistancing<-SocialDistance
hospitalizationrate<-5
icurate<-6
ventilatorrate<-3
hospitaltime<-3.5
icutime<-4
ventilatortime<-7
daysforecasted<-ProjectedDays
#Now we throw the values above into the SEIAR model, and we create dates for the number of days we decided to forecast as well (place holder for now).
#With the outputs, we grab the daily hospitalized people and the cumulative hospitalizations. Then we name the columns
SEIARProj<-SEIAR_Model_Run(cases, pop, incubationtime, latenttime,doubling,recoverydays,
socialdistancing,hospitalizationrate, icurate,ventilatorrate,hospitaltime,icutime,
ventilatortime,daysforecasted,Ro, .5)
MyDates<-seq(Sys.Date()-(length(CovidCounties)-80), length=daysforecasted, by="1 day")
DailyData<-data.frame(MyDates, SEIARProj$sir$hos_add)
TotalData<-data.frame(MyDates, SEIARProj$sir$hos_cum)
colnames(DailyData)<-c("ForecastDate", "Expected Fatalities")
colnames(TotalData)<-c("ForecastDate", "Total Daily Cases")
DailyData$`Expected Fatalities` <- round(DailyData$`Expected Fatalities`*(.25/5.5),0)
DailyData<-DailyData[-1,]
DailyData$`Expected Fatalities`<-cumsum(DailyData$`Expected Fatalities`)
DailyData<- dplyr::filter(DailyData, ForecastDate >= Sys.Date())
max(DailyData$`Expected Fatalities`)
}
}
# CalculateCHIMEMinMax<-function(IncludedCounties, ChosenBase, ChosenRadius, SocialDistance, ProjectedDays){
# BaseState<-dplyr::filter(AFBaseLocations, Base == ChosenBase)
# #Get data for counties with covid cases. We want number of cases, the rate of the cases and maybe other data.
# #We include State, county, population in those counties, cases, fatalities, doubling rate
# CovidCounties<-subset(CovidConfirmedCases, CountyFIPS %in% IncludedCounties$FIPS)
# HistoricalData<-colSums(CovidCounties[,5:length(CovidCounties)])
# HistoricalDates<-seq(as.Date("2020-01-22"), length=length(HistoricalData), by="1 day")
# HistoricalData<-data.frame(HistoricalDates, HistoricalData*.21, HistoricalData*.15, HistoricalData*.27)
# colnames(HistoricalData)<-c("ForecastDate", "Expected Daily Cases","Minimum Daily Cases","Maximum Daily Cases")
#
# DeathCounties<-subset(CovidDeaths, CountyFIPS %in% IncludedCounties$FIPS)
# CaseRate <- subset(CovidConfirmedCasesRate, CountyFIPS %in% IncludedCounties$FIPS)
# CountyDataTable<-cbind(IncludedCounties,rev(CovidCounties)[,1],rev(DeathCounties)[,1],rev(CaseRate)[,1])
# CountyDataTable<-data.frame(CountyDataTable$State,CountyDataTable$County,CountyDataTable$Population, rev(CountyDataTable)[,3], rev(CountyDataTable)[,2],rev(CountyDataTable)[,1])
# colnames(CountyDataTable)<-c("State","County","Population","Total Confirmed Cases","Total Fatalities", "Case Doubling Rate (days)" )
#
# #Cleaning it up to input into the SEIAR model, we include countyFIPS, CountyName, State, State FIPS, number of cases, population, and doubling rate
# #We take the data and create a dataframe called SIR inputs. It checks out by total cases, total population, and average doubling rate
# ActiveCases<-rev(CovidCounties)[1:7]
# ActiveCases<-data.frame(CovidCounties[,1:4],ActiveCases[,1], IncludedCounties$Population, CountyDataTable$`Case Doubling Rate (days)`)
# colnames(ActiveCases)<-c("CountyFIPS","CountyName","State","StateFIPS","CurrentCases", "Population", "Doubling Rate")
# SIRinputs<-data.frame(sum(ActiveCases$CurrentCases),sum(ActiveCases$Population), mean(ActiveCases$`Doubling Rate`))
# colnames(SIRinputs)<-c("cases","pop","doubling")
#
#
# ####################################################################################
# #Mean Estimate
#
# #Next we use the calculated values, along with estimated values from the Estimated Values.
# #The only input we want from the user is the social distancing rate. For this example, we just use 0.5
# cases<-SIRinputs$cases
# pop<-SIRinputs$pop
# doubling<-8
#
# #Established Variables at the start for every county or populations
# Ro<-2.5
# incubationtime<-5
# latenttime<-2
# recoverydays<-14
# socialdistancing<-SocialDistance
# hospitalizationrate<-5
# icurate<-6
# ventilatorrate<-3
# hospitaltime<-3.5
# icutime<-4
# ventilatortime<-7
# daysforecasted<-ProjectedDays
#
#
# #Now we throw the values above into the SEIAR model, and we create dates for the number of days we decided to forecast as well (place holder for now).
# #With the outputs, we grab the daily hospitalized people and the cumulative hospitalizations. Then we name the columns
# SEIARProj<-SEIAR_Model_Run(cases, pop, incubationtime, latenttime,doubling,recoverydays,
# socialdistancing,hospitalizationrate, icurate,ventilatorrate,hospitaltime,icutime,
# ventilatortime,daysforecasted,Ro, .5)
#
# MyDates<-seq(Sys.Date()-(length(CovidCounties)-80), length=daysforecasted, by="1 day")
# DailyData<-data.frame(MyDates, SEIARProj$sir$hos_add)
# TotalData<-data.frame(MyDates, SEIARProj$sir$hos_cum)
# colnames(DailyData)<-c("ForecastDate", "Expected Daily Cases")
# colnames(TotalData)<-c("ForecastDate", "Total Daily Cases")
# DailyData<-DailyData[-1,]
# DailyData<- dplyr::filter(DailyData, ForecastDate >= Sys.Date())
#
# Peak<-which.max(DailyData$`Expected Daily Cases`)
# Max<-DailyData[Peak,4]
# Min<-DailyData[Peak,3]
# paste("(Min: ", Min, ", Max: ", Max, ")")
#
# }
CalculateIHMEPeak<-function(ChosenBase, IncludedHospitals, radius, StatisticType){
if (StatisticType == "Hospitalizations") {
#Creating the stats and dataframes determined by the base we choose to look at.
BaseState<-dplyr::filter(AFBaseLocations, Base == ChosenBase)
IHME_State <- dplyr::filter(IHME_Model, State == toString(BaseState$State[1]))
TotalBedsCounty <- sum(IncludedHospitals$BEDS)
#Get regional and state populations
CountyInfo$DistanceMiles = cimd[,as.character(ChosenBase)]
IncludedCounties <- dplyr::filter(CountyInfo, DistanceMiles <= radius)
StPopList <- dplyr::filter(CountyInfo, State == toString(BaseState$State[1]))
RegPop <- sum(IncludedCounties$Population)
StPop <- sum(StPopList$Population)
# Use Population ratio to scale IHME
PopRatio <- RegPop/StPop
# Get total hospital bed number across state
IncludedHospitalsST <- dplyr::filter(HospitalInfo, STATE == toString(BaseState$State[1]))
TotalBedsState <- sum(IncludedHospitalsST$BEDS)
# Calculate bed ratio
BedProp <- TotalBedsCounty/TotalBedsState
# Apply ratio's to IHME data
IHME_Region <- IHME_State
IHME_Region$allbed_mean = round(IHME_State$allbed_mean*PopRatio)
IHME_Data<-data.frame(IHME_Region$date,IHME_Region$allbed_mean)
PeakDate<-which.max(IHME_Data$IHME_Region.allbed_mean)
Peak<-IHME_Data[PeakDate,2]
round(Peak)
} else {
BaseState<-dplyr::filter(AFBaseLocations, Base == ChosenBase)
IHME_State <- dplyr::filter(IHME_Model, State == toString(BaseState$State[1]))
TotalBedsCounty <- sum(IncludedHospitals$BEDS)
MyCounties<-GetCounties(ChosenBase, radius)
#Get regional and state populations
CovidCounties<-subset(CovidConfirmedCases, CountyFIPS %in% MyCounties$FIPS)
CovidDeathsHist<-subset(CovidDeaths, CountyFIPS %in% MyCounties$FIPS)
HistoricalData<-colSums(CovidDeathsHist[,5:length(CovidDeathsHist)])
HistoricalDates<-seq(as.Date("2020-01-22"), length=length(HistoricalData), by="1 day")
HistoricalData<-data.frame(HistoricalDates, HistoricalData, HistoricalData, HistoricalData)
colnames(HistoricalData)<-c("ForecastDate", "Expected Fatalities", "Lower Estimate","Upper Estimate")
StPopList <- dplyr::filter(CountyInfo, State == toString(BaseState$State[1]))
RegPop <- sum(MyCounties$Population)
StPop <- sum(StPopList$Population)
# Use Population ratio to scale IHME
PopRatio <- RegPop/StPop
# Get total hospital bed number across state
IncludedHospitalsST <- dplyr::filter(HospitalInfo, STATE == toString(BaseState$State[1]))
TotalBedsState <- sum(IncludedHospitalsST$BEDS)
# Calculate bed ratio
BedProp <- TotalBedsCounty/TotalBedsState
# Apply ratio's to IHME data
IHME_Region <- IHME_State
IHME_Region$deaths_mean = round(IHME_State$totdea_mean*PopRatio)
IHME_Region$deaths_lower = round(IHME_State$totdea_lower*PopRatio)
IHME_Region$deaths_upper = round(IHME_State$totdea_upper*PopRatio)
IHME_Region<-data.frame(IHME_Region$date, IHME_Region$deaths_mean, IHME_Region$deaths_lower, IHME_Region$deaths_upper)
colnames(IHME_Region)<-c("ForecastDate", "Expected Fatalities", "Lower Estimate","Upper Estimate")
max(IHME_Region$`Expected Fatalities`)
}
}
# CalculateIHMEMinMax<-function(ChosenBase, IncludedHospitals, radius){
#
# #Creating the stats and dataframes determined by the base we choose to look at.
# BaseState<-dplyr::filter(AFBaseLocations, Base == ChosenBase)
# IHME_State <- dplyr::filter(IHME_Model, State == toString(BaseState$State[1]))
# TotalBedsCounty <- sum(IncludedHospitals$BEDS)
#
# #Get regional and state populations
# CountyInfo$DistanceMiles = cimd[,as.character(ChosenBase)]
# IncludedCounties <- dplyr::filter(CountyInfo, DistanceMiles <= radius)
# StPopList <- dplyr::filter(CountyInfo, State == toString(BaseState$State[1]))
# RegPop <- sum(IncludedCounties$Population)
# StPop <- sum(StPopList$Population)
#
# # Use Population ratio to scale IHME
# PopRatio <- RegPop/StPop
#
# # Get total hospital bed number across state
# IncludedHospitalsST <- dplyr::filter(HospitalInfo, STATE == toString(BaseState$State[1]))
# TotalBedsState <- sum(IncludedHospitalsST$BEDS)
#
# # Calculate bed ratio
# BedProp <- TotalBedsCounty/TotalBedsState
#
# # Apply ratio's to IHME data
# IHME_Region <- IHME_State
# IHME_Data<-data.frame(IHME_Region$date,IHME_Region$allbed_mean*PopRatio, IHME_Region$allbed_lower*PopRatio, IHME_Region$allbed_upper*PopRatio)
# colnames(IHME_Data)<-c("Date", "Mean", "Lower", "Upper")
#
# PeakDate<-which.max(IHME_Data$Mean)
# Max<-round(IHME_Data[PeakDate,4])
# Min<-round(IHME_Data[PeakDate,3])
# paste("Min:", Min, ", Max:", Max)
# }
##########################################################################################################
##########################################################################################################
##########################################################################################################
# Create Charts for plotting lines showing trends among the virus ------------------------------------------------------------------------------------------------------------------
#Create charts for Local Health Tab
#This function creates the dataframe for plotting daily cases, deaths, estimated hospitalizations in selected region
CovidCasesPerDayChart<-function(IncludedCounties){
#Get cases and deaths in selected region
CovidCountiesCases<-subset(CovidConfirmedCases, CountyFIPS %in% IncludedCounties$FIPS)
CovidCountiesDeath<-subset(CovidDeaths, CountyFIPS %in% IncludedCounties$FIPS)
#Find Daily new cases
DailyNewCases <- CovidCountiesCases[,6:length(CovidCountiesCases)] -
CovidCountiesCases[,5:(length(CovidCountiesCases)-1)]
DailyNewCasesT <- colSums(DailyNewCases)
#Find New Deaths
DailyNewDeaths <- CovidCountiesDeath[,6:length(CovidCountiesDeath)] -
CovidCountiesDeath[,5:(length(CovidCountiesDeath)-1)]
DailyNewDeathsT <- colSums(DailyNewDeaths)
#Clean up the dataset to prepare for plotting
#ForecastDate<- seq(as.Date("2020-1-23"), length=length(DailyNewCases), by="1 day")
ForecastDate<- seq(as.Date("2020-1-22"), length=length(DailyNewCases), by="1 day")
Chart1Data<-cbind.data.frame(ForecastDate,DailyNewCasesT,DailyNewDeathsT)
colnames(Chart1Data)<-c("ForecastDate","New Cases","New Fatalities")
Chart1DataSub <- melt(data.table(Chart1Data), id=c("ForecastDate"))
}
#Begin function to create chart of new cases for COVID-19 is a specified region around a specified base
CovidCasesCumChart<-function(IncludedCounties){
#Find counties in radius
CovidCountiesCases<-subset(CovidConfirmedCases, CountyFIPS %in% IncludedCounties$FIPS)
CovidCountiesDeath<-subset(CovidDeaths, CountyFIPS %in% IncludedCounties$FIPS)
#Compute cumlative cases and deaths in selected counties
CumDailyCovid<-colSums(CovidCountiesCases[,5:length(CovidCountiesCases)])
CumDailyDeaths<-colSums(CovidCountiesDeath[5:length(CovidCountiesDeath)])
#Clean up the dataset to get ready to plot it
#ForecastDate<- seq(as.Date("2020-1-23"), length=length(CumDailyCovid), by="1 day")
ForecastDate<- seq(as.Date("2020-1-22"), length=length(CumDailyCovid), by="1 day")
Chart2Data<-cbind.data.frame(ForecastDate,CumDailyCovid,CumDailyDeaths)
colnames(Chart2Data)<-c("ForecastDate","Total Cases","Total Fatalities")
Chart2DataSub <- melt(data.table(Chart2Data), id=c("ForecastDate"))
}
#Create charts for projecting local health data
##########################################################################################################
##########################################################################################################
##########################################################################################################
PlotOverlay<-function(ChosenBase, IncludedCounties, IncludedHospitals, SocialDistance,ModelIDList, DaysProjected, StatisticType){