-
Notifications
You must be signed in to change notification settings - Fork 0
/
model_class.R
1645 lines (1164 loc) · 71.6 KB
/
model_class.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
#------------------------------------------------------------------------------#
# Code for the paper: Reopening California
# Seeking Robust, Non-Dominated COVID-19 Exit Strategies.
#
# Author: Pedro Nascimento de Lima
# Copyright (C) 2021 by The RAND Corporation
# See LICENSE.txt and README.txt for information on usage and licensing
#------------------------------------------------------------------------------#
#### COVID-19 Model Class AMSH ---------------------------------------------####
#------------------------------------------------------------------------------#
# Authors: Raffaele Vardavas, Pedro Nascimento de Lima
# Purpose: This File contains the c19model2 functions.
# Creation Date: May 2020
#------------------------------------------------------------------------------#
#' C19 Model 4 Function
#'
#' @param inputs inputs object created with the get_augmented_inputs () and prepare_inputs() functions
#' @param level use "state" as default.
#'
#' @return a c19model object
#' @export
#'
#' @examples
#'\dontrun{
#'model = get_augmented_inputs(...) %>%
#' prepare_inputs(...) %>%
#' c19model_vamshi4s(., level = "state")
#'}
#'
c19model_vamshi4s = function(inputs, level) {
model = inputs %>%
uniformize_inputs_level(.,level = level) %>%
set_capacities(.)
# Initiate Covid-19 model as an empty class.
# Defining the model geographic level:
model$level = level
model$model_fn = model_function.c19model_vamshi4s
model$set_calibrated_stocks = set_calibrated_stocks.c19model_vamshi4s
model$set_initial_stocks = set_initial_stocks.c19model_vamshi4s
model$set_computed_params = set_computed_params.c19model_vamshi4s
model$pre_compute = pre_compute_function.c19model_vamshi4s
model$verify_input_parameters = verify_input_parameters.c19model_vamshi4s
model$set_stocks_positions = set_stocks_positions.c19model_vamshi4s
model$model_name = "c19model_vamshi4s"
model$status = "uncalibrated"
# Uniformize Inputs according to the intended level:
class(model) = c("c19model_vamshi4s", "c19model")
model
}
# use this in a near future:
set_calibrated_stocks.c19model_vamshi4s = function(model, run_id) {
cal_results = model$cal_results %>%
filter(RunID == run_id) %>%
filter(time == max(time))
stocks_list = c(
RB = unname(cal_results[,model$spos$RB+1]),
S = unname(cal_results[,model$spos$S+1]),
V = unname(cal_results[,model$spos$V+1]),
E = unname(cal_results[,model$spos$Ev+1]),
Ev = unname(cal_results[,model$spos$E+1]),
P = unname(cal_results[,model$spos$P+1]),
Pv = unname(cal_results[,model$spos$Pv+1]),
ISm = unname(cal_results[,model$spos$ISm+1]),
YSm = unname(cal_results[,model$spos$YSm+1]),
ISs = unname(cal_results[,model$spos$ISs+1]),
YSs = unname(cal_results[,model$spos$YSs+1]),
H = unname(cal_results[,model$spos$H+1]),
ICU = unname(cal_results[,model$spos$ICU+1]),
IA = unname(cal_results[,model$spos$IA+1]),
IAv = unname(cal_results[,model$spos$IAv+1]),
YA = unname(cal_results[,model$spos$YA+1]),
YAv = unname(cal_results[,model$spos$YAv+1]),
D = unname(cal_results[,model$spos$D+1]),
RS = unname(cal_results[,model$spos$RS+1]),
RA = unname(cal_results[,model$spos$RA+1]),
RAv = unname(cal_results[,model$spos$RAv+1]),
CumulativeRealCases = unname(cal_results[,model$spos$CumulativeRealCases+1]),
CumulativePositiveTests = unname(cal_results[,model$spos$CumulativePositiveTests+1]),
CumulativeTotalTests = unname(cal_results[,model$spos$CumulativeTotalTests+1]),
CumulativeReportedRecovered = unname(cal_results[,model$spos$CumulativeReportedRecovered+1]),
CumulativeReportedDeaths = unname(cal_results[,model$spos$CumulativeReportedDeaths+1]),
CumulativeVaccinated = unname(cal_results[,model$spos$CumulativeVaccinated+1]),
TestingCapacity = cal_results$TestingCapacity,
BedsCapacity = cal_results$BedsCapacity,
VentilatorCapacity = cal_results$VentilatorCapacity,
TreatmentEfficacy = cal_results$TreatmentEfficacy,
#Initialize at NPI Level 3 - which is the current NPI level.
NPIStock = cal_results$NPIStock,
VaccineStock = cal_results$VaccineStock
)
model$init_stocks = unlist(stocks_list)
### Making sure all stocks are positive:
#model$init_stocks = model$init_stocks + 1e-10
model
}
#----------------------------------------------------------------------------------------#
# Function: Set Initial Stocks
# Purpose: Sets the Value of Initial Stocks
# Creation Date: May 2020
#----------------------------------------------------------------------------------------#
set_initial_stocks.c19model_vamshi4s = function(model, initial_exposed) {
# Defining Initial Conditions for Each Stock:
stocks_list = c(
RB = model$compartment$PopulationShareInLocation * 0,
S = model$compartment$PopulationShareInLocation * (1-initial_exposed),
V = rep(0, length(model$compartment$PopulationShareInLocation)), # model$compartment$PopulationShareInLocation, # TODO: Testing
E = model$compartment$PopulationShareInLocation * (1/3) * initial_exposed,
Ev = model$compartment$PopulationShareInLocation * 0,
P = model$compartment$PopulationShareInLocation * (1/3) * initial_exposed,
Pv = model$compartment$PopulationShareInLocation * 0,
ISm = model$compartment$PopulationShareInLocation * 0,
YSm = model$compartment$PopulationShareInLocation * 0,
ISs = model$compartment$PopulationShareInLocation * 0,
YSs = model$compartment$PopulationShareInLocation * 0,
H = model$compartment$PopulationShareInLocation * 0,
ICU = model$compartment$PopulationShareInLocation * 0,
IA = model$compartment$PopulationShareInLocation * (1/3) * initial_exposed,
IAv = model$compartment$PopulationShareInLocation * 0,
YA = model$compartment$PopulationShareInLocation * 0,
YAv = model$compartment$PopulationShareInLocation * 0,
D = model$compartment$PopulationShareInLocation * 0,
RS = model$compartment$PopulationShareInLocation * 0,
RA = model$compartment$PopulationShareInLocation * 0,
RAv = model$compartment$PopulationShareInLocation * 0,
CumulativeRealCases = model$compartment$PopulationShareInLocation * 0,
CumulativePositiveTests = model$compartment$PopulationShareInLocation * 0,
CumulativeTotalTests = model$compartment$PopulationShareInLocation * 0,
CumulativeReportedRecovered = model$compartment$PopulationShareInLocation * 0,
CumulativeReportedDeaths = model$compartment$PopulationShareInLocation * 0,
CumulativeVaccinated = model$compartment$PopulationShareInLocation * 0,
TestingCapacity = model$capacities$MinTestingCapacity[model$capacities$LocationID == model$location$LocationID],
BedsCapacity = model$capacities$MinBedsCapacity[model$capacities$LocationID == model$location$LocationID],
VentilatorCapacity = model$capacities$MinVentilatorCapacity[model$capacities$LocationID == model$location$LocationID],
TreatmentEfficacy = 0,
NPIStock = 1,
VaccineStock = 0
)
### Testing Multiplying Stock by big number to gain some precision.
model$init_stocks = unlist(stocks_list)
### Making sure all stocks are positive:
#model$init_stocks = model$init_stocks + 1e-10
model
}
#----------------------------------------------------------------------------------------#
# Function: Set Computed Parameters
# Purpose: Computes model parameters based on scenarios input data.frame
# Creation Date: May 2020
#----------------------------------------------------------------------------------------#
set_computed_params.c19model_vamshi4s = function(model) {
new_scenarios = within(data = as.data.frame(model$scenarios), {
##############################################################################################
### ###
### Rate from non infectious incumbation to infectious incubation phase ###
### ###
##############################################################################################
nu = 1 / (d.incum * incum.non.infec.proportion)
##############################################################################################
### ###
### Rates to first sympotoms
### ###
##############################################################################################
d.to.first.sym = (d.incum * (1 - incum.non.infec.proportion))
##############################################################################################
### ###
### Rates to secondary phases mild sympotoms and anymptomatic
### ###
##############################################################################################
gammaA = Asym.prop / d.to.first.sym
gammaS = (1 - Asym.prop) / d.to.first.sym
##############################################################################################
### ###
### Vaccination
### ###
##############################################################################################
behavioral.increase.mixing = behavioral.increase.mixing
v.rate = v.rate
vacc.trans.efficacy = trans.efficacy.factor * vacc.overall.efficacy
Asym.prop.vacc = 1 - (1 - vacc.overall.efficacy) * (1 - Asym.prop) / (1 - vacc.trans.efficacy)
gammaAv = Asym.prop.vacc / d.to.first.sym
gammaSv = (1 - Asym.prop.vacc) / d.to.first.sym
##############################################################################################
### ###
### Rates to develop severe symptoms or recover without developing severe sympotoms.
### ###
##############################################################################################
upsilon = Severe.prop / d.sym.mild
xi.m = 1 / d.sym.mild - upsilon
##############################################################################################
### ###
### Rates to access the hospital if it is not at Capacity
### ###
##############################################################################################
h = 1 / d.to.hos
h.star = tested.multi.rate.access.to.hospital * h # faster rate for those tested first.
##############################################################################################
### ###
### ICU dwelling time
### ###
##############################################################################################
d.icu = d.hos * d.icu.mult
##############################################################################################
### ###
### Rates to access ICU and to either die in the ICU or exit ICU.
### ###
##############################################################################################
# Rates of death and recovery for those hospitalized.
chi = Critical.prop / (d.hos - Critical.prop * d.icu)
mu.ICU = Die.in.icu.prop / d.icu
xi.ICU = (1 - Die.in.icu.prop) / d.icu
##############################################################################################
### ###
### Rates to exit the Hospital either due to death (not in ICU) or Recover
### ###
##############################################################################################
# Rate of Death while hospitalized but not in ICU (including because the ICU is at capacity)
mu.H = (1 - A.icu) * chi #+ (Die.in.hos.prop - A.icu * Critical.prop * Die.in.icu.prop) /
#((d.hos - A.icu * Critical.prop * d.icu) * (1 - A.icu *Critical.prop))
xi.H = (1 - Critical.prop) / (d.hos - A.icu * Critical.prop * d.icu) - mu.H
#chi = A.icu * chi
##############################################################################################
### ###
### Rates of Death and Decovery for those with Severe sympotoms but not hospitalized
### ###
##############################################################################################
## Death rates for those with severe sympotoms that do not get hospitalized.
d.to.death.if.not.hos = (d.to.hos + d.hos - Critical.prop * d.icu)
xi.s = (1 - A * Hosp.prop) * (1 - Critical.prop) / d.to.death.if.not.hos
mu.s = (1 - A * Hosp.prop) * Critical.prop / d.to.death.if.not.hos
##############################################################################################
### Rate to recovery for those asympotomatic
### ###
##############################################################################################
xi.A = 1 / d.asym
##############################################################################################
### ###
### R0 and the time scales
### ###
##############################################################################################
# dummy parameters to express R0.
a = mu.H + xi.H
b = xi.m + upsilon
c = A * h + mu.H + xi.s
## Calculate tau to get R0 from growth rate
num1 = a * (gammaA * b * c + xi.A * (b * c + 1 * gammaS * c + upsilon * 1 * gammaS))
num2 = xi.A * A * h * upsilon * 1 * gammaS
den = xi.A * (gammaA + gammaS) * a * b * c
tau.inf = (num1 + num2) / den
tau.exp = 1 / nu
tau = tau.exp + tau.inf
## Calculate tau.eff to get cbeta
num1 = a * (gammaA * b * c + xi.A * (b * c + m.Sm * gammaS * c + upsilon * m.Ss * gammaS))
num2 = xi.A * A * h * upsilon * m.h * gammaS
den = xi.A * (gammaA + gammaS) * a * b * c
tau.eff = (num1 + num2) / den
})
##############################################################################################
### ###
### Output
### ###
##############################################################################################
model$scenarios = new_scenarios
model
}
#----------------------------------------------------------------------------------------#
# Function: Verify Model Parameters.
# Purpose: Checks model parameters consistency
# Creation Date: May 2020
#----------------------------------------------------------------------------------------#
verify_input_parameters.c19model_vamshi4s = function(model) {
# verify Parametrers
within(data = as.data.frame(model$scenarios), {
verify.out <- c(
"Vaccination Behaviorral Mixing Increase" = behavioral.increase.mixing,
"Vaccination transmission efficacy" = vacc.trans.efficacy,
"Vaccination rate" = v.rate,
"E duration" = 1 / nu,
"P duration" = 1 / (gammaA + gammaS),
"Prop asymp" = gammaA / (gammaA + gammaS),
"Prop asymp vaccinated" = gammaAv / (gammaAv + gammaSv),
"Sympotomatic mild duration" = 1 / (upsilon + zetaS + xi.m),
"Proportion getting severe" = upsilon / (upsilon + zetaS + xi.m),
"Sympotomatic to Hospitalized duration" = 1 / h,
"Hospital duration" = (1-Critical.prop)*1/(xi.H+mu.H)+A.icu*(Critical.prop)*d.icu,
"Mortality of non Hosp" = mu.H / (mu.H + zetaS + xi.s),
"Mortality of Hosp" = (1-Critical.prop)*mu.H / (mu.H + xi.H) + Critical.prop*mu.ICU / (mu.ICU + xi.ICU),
"Mortality of ICU" = mu.ICU / (mu.ICU + xi.ICU),
"IA duration" = 1 / xi.A,
"IA to tested duration" = 1 / zetaA,
"generation time scale" = tau,
"modified time scale for R0" = tau.eff
)
})
}
pre_compute_function.c19model_vamshi4s = function(model, run_id){
# Substitute New Parameters:
pc = list()
# spmin is a smooth pmin function:
# exponential smooth min (k = 32); see https://www.iquilezles.org/www/articles/smin/smin.htm
pc$spmin<- function(a,b,k=320){
res = exp( -k*a ) + exp( -k*b )
res= pmin(res,1)
return (-log( res )/k)
}
pc$spmax<- function(a,b,k=320){
res = exp( k*a ) + exp( k*b )
return (log( res )/k)
}
### Start of Vaccination:
pc$vaccination_start_date = lubridate::as_date("2021-01-01")
pc$delta_t.vacc = 20
pc$vacc_approved_for = c(0.1, rep(1, length(model$compartment$PopulationShareInLocation)-1)) # c(0.1,1,1,1,1,1,1)
# Comes from the Experimental Design
pc$prob_seek_vaccination = ifelse(exists("prob_seek_vaccination", where = model$params), model$params$prob_seek_vaccination, 1/2)
# Comes from the Experimental Design
pc$vacc_on_demand = ifelse(exists("vacc_on_demand", where = model$params), model$params$vacc_on_demand, T)
### Vaccination strategy Definition:
frailty_vector = model$subpopulation$VaccPriority
frailty_vector = frailty_vector / sum(frailty_vector)
mixing_no_intervention_criteria_vector = safe_division(rowSums(model$cbetamatrices[[1]]), model$compartment$PopulationShareInLocation)
mixing_no_intervention_criteria_vector = mixing_no_intervention_criteria_vector / sum(mixing_no_intervention_criteria_vector)
mixing_essential_workers_criteria_vector = safe_division(rowSums(model$cbetamatrices[[4]]), model$compartment$PopulationShareInLocation)
mixing_essential_workers_criteria_vector = mixing_essential_workers_criteria_vector / sum(mixing_essential_workers_criteria_vector)
frailty_vector_sequential = 10^rank(frailty_vector)
mixing_essential_workers_vector_sequential = 10^rank(mixing_essential_workers_criteria_vector*pc$vacc_approved_for)
# Think about how to use the eigenvectors:
eigen = eigen(model$cbetamatrices[[1]])
abs_eigen_vector = abs(eigen$vectors[,which.max(eigen$values)])
vacc_criteria = abs_eigen_vector / sum(abs_eigen_vector)
if(!exists("vaccination_strategy_name", where = model$params)) {
#Change to Something Sensible:
vaccination_strategy_name = "ACIP"
} else {
vaccination_strategy_name = as.character(model$params$vaccination_strategy_name)
}
## Implement allocation efficiency adjustment.
pc$V.strategy = switch(vaccination_strategy_name,
"Proportional" = model$compartment$PopulationShareInLocation,
"ACIP" = model$subpopulation$ACIPVaccPriority,
"Frailty-Based" = frailty_vector,
"Frailty-Based-Sequential" = frailty_vector_sequential,
"Mixing-Based-No-Intervention" = mixing_no_intervention_criteria_vector,
"Mixing-Based-Essential-Workers" = mixing_essential_workers_criteria_vector,
"Mixing-Based-Essential-Workers-Sequential" = mixing_essential_workers_vector_sequential,
"No Vaccine" = model$compartment$PopulationShareInLocation * 0
)
### Start of Treatment Improvement
# If Date is greater than the day in which this remdesevir study was published,
# start improving treatments:
# https://www.nejm.org/doi/full/10.1056/NEJMoa2007764
pc$treatment_improvement_start_date = lubridate::as_date("2020-05-22")
##############################################################################################
### ###
### Adaptive Strategies Flags
### ###
##############################################################################################
# Check which NPI Policies Should be Evaluated
pc$evaluate_fixed_npis = exists("npi_type", where = model$params) & exists("fixed_npi", where = model$params)
pc$evaluate_intermittent_npis = exists("npi_type", where = model$params) & exists("base_npi", where = model$params) & exists("max_npi", where = model$params) & exists("npi_period", where = model$params)
pc$evaluate_adaptive_npis = exists("npi_type", where = model$params) & exists("LevelOfCaution", where = model$params)
pc$evaluate_adaptive_time_based_npis = pc$evaluate_adaptive_npis & exists("TransitionDate", where = model$params) & exists("NewLevelOfCautionMultiplier", where = model$params)
pc$evaluate_adaptive_vacc_based_npis = pc$evaluate_adaptive_npis & exists("AdaptiveCautionRelaxationRate", where = model$params) & exists("AdaptiveCautionMidpoint", where = model$params) & exists("reopening_criteria", where = model$params)
pc$evaluate_immunity_npi_threshold = exists("reopening_immunity_threshold", where = model$params) & exists("reopening_criteria", where = model$params)
##############################################################################################
### ###
### Seasonality
### ###
##############################################################################################
# Below is the function for seasonality - it will be replaced.
pc$seasonal_function = function(seas, t) {
(seas * (1 - (sin(3.14 * (t+seas_shift) / 365)) ^ 2) + 1)
}
# Compute Seasonal Factor for Today:
# First, Compute a Baseline seasonal factor reference:
initial_t = as.integer(model$start_date - lubridate::as_date("2019-12-15"))
max_ts_t = as.integer(model$max_ts_date - lubridate::as_date("2020-12-15"))
# t_model = t + initial_t - 1
t_model = model$time + initial_t - 1
pc$seasonal_factors = pc$seasonal_function(model$params$seas, t_model) / mean(pc$seasonal_function(model$params$seas, initial_t:max_ts_t))
pc$baseline_seasonal_factor = mean(pc$seasonal_function(model$params$seas, initial_t:max_ts_t))
## Computting the Aggregate CB
## Any exogenous influence on transmission should be defined below:
pc$transmissibility_multiplier = ifelse(exists("PercentChangeInTransmissibility", where = model$params), (1+model$params$PercentChangeInTransmissibility),1)
# Changing Age-dependent Parameters:
# CHange Vaccine Efficacy if it is an experimental parameter:
# Assume efficiency factors are present.
# Computing parameters that rely on multipliers that may or may not be supplied:
# We might want to generalize this for any parameter, but one needs to be careful
# since there are parameters that are computed in the set_computed_params
# mult.trans.efficacy.factor
mult.trans.efficacy.factor = ifelse(exists("mult.trans.efficacy.factor", where = model$params), model$params$mult.trans.efficacy.factor,1)
vacc.trans.efficacy = mult.trans.efficacy.factor * model$params$trans.efficacy.factor * model$params$vacc.overall.efficacy
pc$Asym.prop.vacc = 1 - (1 - model$params$vacc.overall.efficacy) * (1 - model$params$Asym.prop) / (1 - vacc.trans.efficacy)
# mult.vrate
mult.v.rate = ifelse(exists("mult.v.rate", where = model$params), model$params$mult.v.rate,1)
pc$v.rate = model$params$v.rate * mult.v.rate
# Behavioral increase in mixing: mult.behavioral.increase.mixing
mult.behavioral.increase.mixing = ifelse(exists("mult.behavioral.increase.mixing", where = model$params), model$params$mult.behavioral.increase.mixing,1)
pc$behavioral.increase.mixing = model$params$behavioral.increase.mixing * mult.behavioral.increase.mixing
# Willingness to Vaccinate:
mult.V.will.factor = ifelse(exists("mult.V.will.factor", where = model$params), model$params$mult.V.will.factor,1)
pc$V.will.factor = model$params$V.will.factor * mult.V.will.factor
# Months of Immunity Duration
mult.MonthsOfImmunityDuration = ifelse(exists("mult.MonthsOfImmunityDuration", where = model$params), model$params$mult.MonthsOfImmunityDuration,1)
pc$MonthsOfImmunityDuration = model$params$MonthsOfImmunityDuration * mult.MonthsOfImmunityDuration
# Compute start of the simulation run:
pc$initial_time = Sys.time()
# Return Pre-computed objects
model$pc = pc
# Return Model
model
}
#----------------------------------------------------------------------------------------#
# Function: Model Function
# Purpose: This function contains the model equations, and represent the actual ODE model.
# Creation Date: May 2020
#----------------------------------------------------------------------------------------#
#' @importFrom utils tail
model_function.c19model_vamshi4s = function(time, stocks, params, model, run_id) {
# Substituting timeseries Nans with zeros:
# Exporting Time Series Objects
if (length(time) == 1) {
# Here I select the Timeseries object using the row number. This could be changed so that the time series is selected using a date.
if(time < nrow(model$timeseries)) {
ts = list(ts = model$timeseries[as.integer(time),])
} else {
ts = list(ts = tail(model$timeseries, 1))
}
} else {
browser()
ts = list()
}
t = list(t = time)
with(
as.list(c(params, model, stocks, ts, t)),
{
# All stocks are positive values:
# stocks = abs(stocks)
##############################################################################################
### ###
### Unpacking Stocks
### ###
##############################################################################################
RB = stocks[spos$RB]
S = stocks[spos$S]
V = stocks[spos$V]
E = stocks[spos$E]
Ev = stocks[spos$Ev]
P = stocks[spos$P]
Pv = stocks[spos$Pv]
ISm = stocks[spos$ISm]
YSm = stocks[spos$YSm]
ISs = stocks[spos$ISs]
YSs = stocks[spos$YSs]
H = stocks[spos$H]
ICU = stocks[spos$ICU]
IA = stocks[spos$IA]
IAv = stocks[spos$IAv]
YA = stocks[spos$YA]
YAv = stocks[spos$YAv]
D = stocks[spos$D]
RS = stocks[spos$RS]
RA = stocks[spos$RA]
RAv = stocks[spos$RAv]
CumulativeRealCases = stocks[spos$CumulativeRealCases]
CumulativePositiveTests = stocks[spos$CumulativePositiveTests]
CumulativeTotalTests = stocks[spos$CumulativeTotalTests]
CumulativeReportedRecovered = stocks[spos$CumulativeReportedRecovered]
CumulativeReportedDeaths = stocks[spos$CumulativeReportedDeaths]
CumulativeVaccinated = stocks[spos$CumulativeVaccinated]
TestingCapacity = stocks[spos$TestingCapacity]
BedsCapacity = stocks[spos$BedsCapacity]
VentilatorCapacity = stocks[spos$VentilatorCapacity]
TreatmentEfficacy = stocks[spos$TreatmentEfficacy]
NPIStock = stocks[spos$NPIStock]
VaccineStock = stocks[spos$VaccineStock]
##############################################################################################
### ###
### Verification Browser
### ###
##############################################################################################
# if(any(is.nan(stocks))) {
# browser()
# }
#
# if(any(stocks<0)) {
# browser()
# }
# if(ts$Date == lubridate::as_date("2020-03-01")){
# browser()
# }
##############################################################################################
### ###
### Portfolios
### ###
##############################################################################################
date = floor(t) + start_date - 1
# NPI Portfolio is defined by the NPI Stock continuous variable:
npi_portfolio = unname(round(NPIStock, digits = 0))
# The Target NPI Portfolio is the variable used to Change the NPI stock. By default, it comes from the timeseries:
# The target portfolio can change following the NPi strategies rules later:
target_npi_portfolio = ts$PortfolioID
##############################################################################################
### ###
### Option 0 - Fixed NPIs
### ###
##############################################################################################
# Check if all parameters for intermittent NPIs are in place:
# Uncomment if You want to run Periodic NPIs:
if(pc$evaluate_fixed_npis) {
if(as.character(npi_type) == "fixed") {
target_npi_portfolio = fixed_npi
}
}
##############################################################################################
### ###
### Option 1 - Intervention Schedule Originally used in the COVID-19 State Policy Tool
### ###
##############################################################################################
#
# npi_portfolio = if(!exists("intervention_schedule") || date <= calibration_date) {
#
# ts$PortfolioID
#
# } else {
#
# # There is an intervention schedule and we are simulating the future:
# tentative_npi = intervention_schedule %>%
# mutate(Passed = date >= ChangeDates) %>%
# filter(Passed) %>%
# filter(ChangeDates == max(ChangeDates))
#
# # If this doesnt return any date, then use the final time series object, otherwise, use the portfolio id coming from the past timeseries.
# ifelse(nrow(tentative_npi) == 1, as.integer(tentative_npi$SimulatedPortfolioID), ts$PortfolioID)
#
# }
##############################################################################################
### ###
### Option 2 - Intermittent NPIs varying according to some periodicity
### ###
##############################################################################################
# Check if all parameters for intermittent NPIs are in place:
# Uncomment if You want to run Periodic NPIs:
if(pc$evaluate_intermittent_npis) {
if(date >= lubridate::as_date(periodic_npi_start_date)) {
if(as.character(npi_type) == "periodic") {
target_npi_portfolio = base_npi + (max_npi - base_npi) * (round(t / npi_period) %% 2)
}
}
}
##############################################################################################
### ###
### Option 3 - Adaptive NPIs:
### ###
##############################################################################################
# Computing the Non-susceptible population - this is used in the adaptive-imunity-based npi strategies
# and in the reopening condition.
if(pc$evaluate_adaptive_npis) {
KnownPrevalence = sum(YSs + YSm + YA + ICU + H + YAv)
# First, try to evaluate time-based adaptive NPIs:
if(pc$evaluate_adaptive_time_based_npis) {
if(npi_type == "adaptive-time-based") {
if(date > lubridate::as_date(TransitionDate)) {
target_npi_portfolio = round(min(KnownPrevalence * 1000 * LevelOfCaution * NewLevelOfCautionMultiplier, 5), digits = 0) + 1
} else {
target_npi_portfolio = round(min(KnownPrevalence * 1000 * LevelOfCaution, 5), digits = 0) + 1
}
}
}
# Then, try to evaluate immunity-based adaptive npis:
if(pc$evaluate_adaptive_vacc_based_npis) {
if(npi_type == "adaptive-vacc-based") {
# The immunity multiplier follows a logistic curve (reversed S-shaped) where:
# Values range between 0 and 1.
# AdaptiveCautionMidpoint [Should be between ~0.3 and a herd immunity threshold] determines the point at which the multiplier is equal to 0.5 (that is, level of caution is halved).
# AdaptiveCautionRelaxationRate determines how fast we relax our NPIs based on vaccination. [10 ~ 40]
cumulative_vaccinated_metric = ifelse(reopening_criteria=="All Population",sum(CumulativeVaccinated),(sum(CumulativeVaccinated[model$subpopulation$OldChronic])/sum(model$compartment$PopulationShareInLocation[model$subpopulation$OldChronic])))
vacc_multiplier = 1-(1/(1+exp(-1*AdaptiveCautionRelaxationRate*(cumulative_vaccinated_metric-AdaptiveCautionMidpoint))))
target_npi_portfolio = round(min(KnownPrevalence * 1000 * LevelOfCaution * vacc_multiplier, 5), digits = 0) + 1
}
}
}
# Formulation with the non-susceptible:
all_population_non_susceptible = 1-sum(S)
old_and_frail_non_susceptible = 1-(sum(S[model$subpopulation$OldChronic])/sum(model$compartment$PopulationShareInLocation[model$subpopulation$OldChronic]))
# Formulation using the vaccinated:
all_population_vaccinated = sum(CumulativeVaccinated)
old_and_frail_vaccinated = (sum(CumulativeVaccinated[model$subpopulation$OldChronic])/sum(model$compartment$PopulationShareInLocation[model$subpopulation$OldChronic]))
##############################################################################################
### ###
### Option 4 - Reopen After Immunization threshold:
### ###
##############################################################################################
if(pc$evaluate_immunity_npi_threshold) {
# Using the non-susceptible:
#criteria_metric_to_reopen = ifelse(reopening_criteria=="All Population",all_population_non_susceptible,old_and_frail_non_susceptible)
# Or using the vaccinated:
criteria_metric_to_reopen = ifelse(reopening_criteria=="All Population",all_population_vaccinated,old_and_frail_vaccinated)
if(criteria_metric_to_reopen > reopening_immunity_threshold) {
reopening_criteria_met = 1
target_npi_portfolio = 1
} else {
reopening_criteria_met = 0
# Target portfolio is unchanged.
}
} else {
reopening_criteria_met = 0
}
##############################################################################################
### ###
### Calculate the c * beta Infectivity and the effective R.
### ###
##############################################################################################
# Original cbeta formula without calibration factor:
# These calculations could also be done outside the model with some effort:
cbeta_no_intervention = k * model$cbetamatrices[[1]]
cbeta_from_highest_intervention = k * model$cbetamatrices[[ts$MaxPortfolioID]]
calibrated_cbeta_highest_intervention <- cbeta_no_intervention/((npi.cal.factor*((cbeta_no_intervention/cbeta_from_highest_intervention)-1))+1)
calibrated_cbeta_highest_intervention[is.nan(calibrated_cbeta_highest_intervention)] <- 0
# Computing the CBeta for the ceiling:
floor_npi = max(floor(NPIStock),1)
ceiling_npi = min(ceiling(NPIStock),6)
c_weight = NPIStock - floor(NPIStock)
cbeta_with_intervention_c <- k * model$cbetamatrices[[ceiling_npi]]
cbeta_with_intervention_f <- k * model$cbetamatrices[[floor_npi]]
# For the Ceiling CBETA:
calibrated_cbeta_with_intervention_f <- cbeta_no_intervention/((npi.cal.factor*((cbeta_no_intervention/cbeta_with_intervention_f)-1))+1)
calibrated_cbeta_with_intervention_f[is.nan(calibrated_cbeta_with_intervention_f)] <- 0
cbeta_f = calibrated_cbeta_highest_intervention * behavioral.adaptation.factor + (1-behavioral.adaptation.factor) * calibrated_cbeta_with_intervention_f
# For the Floor CBETA:
calibrated_cbeta_with_intervention_c <- cbeta_no_intervention/((npi.cal.factor*((cbeta_no_intervention/cbeta_with_intervention_c)-1))+1)
calibrated_cbeta_with_intervention_c[is.nan(calibrated_cbeta_with_intervention_c)] <- 0
cbeta_c = calibrated_cbeta_highest_intervention * behavioral.adaptation.factor + (1-behavioral.adaptation.factor) * calibrated_cbeta_with_intervention_c
cbeta = cbeta_c * c_weight + cbeta_f * (1-c_weight)
cbeta = matrix(pmax(0,cbeta),nrow=nrow(cbeta),ncol=ncol(cbeta))
##############################################################################################
### ###
### Seasonality
### ###
##############################################################################################
# # Below is the function for seasonality - it will be replaced.
# seasonal_function = function(seas, t) {
# (seas * (1 - (sin(3.14 * t / 365)) ^ 2) + (1 - seas))
# }
#
# # Compute Seasonal Factor for Today:
#
# # First, Compute a Baseline seasonal factor reference:
#
# initial_t = as.integer(start_date - lubridate::as_date("2020-01-01"))
#
# max_ts_t = as.integer(max_ts_date - lubridate::as_date("2020-01-01"))
#
# t_model = t + initial_t - 1
#
# seasonal_factor = seasonal_function(seas, t_model) / mean(seasonal_function(seas, initial_t:max_ts_t))
#
# browser()
# Options to use the seasonal factor:
# A - Linear Interpolation at any point in time.
# seasonal_factor = pc$seasonal_factors[which(floor(t)==time)] * (1-((t-floor(t)))) + (t-floor(t)) * pc$seasonal_factors[which(ceiling(t)==time)]
# B - Without Linear interpolation:
seasonal_factor = pc$seasonal_factors[which(floor(t)==time)]
# C - Computing the seasonal factor on the fly:
#seasonal_factor = pc$seasonal_function(seas, t) / pc$baseline_seasonal_factor
# Cbeta with Seasonality computed internally:
cbeta = cbeta * seasonal_factor * pc$transmissibility_multiplier
##############################################################################################
### ###
### Transmission Process
### ###
##############################################################################################
# Transmission from the Susceptible:
# Adding a pmin to ensure S_to_E is never greater than S:
#TODO: Check this formula with Raff:
S_to_E = cbeta %*% ((P + m.Sm * ISm + m.Ss * ISs +
m.tSm * YSm + m.tSs * YSs +
m.h * (H + ICU) + IA + m.tA * YA +
pc$behavioral.increase.mixing * (Pv + IAv + m.tA * YAv)) *
S)
# Asymptomatic infections:
prop_asymp_infections = safe_division(sum(cbeta %*% ((P + IA + pc$behavioral.increase.mixing * (Pv + IAv)) * S)), sum(S_to_E))
# Susceptibles are never completely depleted:
conf_susceptibles = 0.8
S_to_E = pc$spmin(S_to_E, S*conf_susceptibles)
##############################################################################################
### ###
### Transmission Process for the Vaccinated
### ###
##############################################################################################
if(date >= (pc$vaccination_start_date + 1)) {
V_to_Ev = (1-vacc.trans.efficacy) * pc$behavioral.increase.mixing *
cbeta %*% ((P + m.Sm * ISm + m.Ss * ISs +
m.tSm * YSm + m.tSs * YSs +
m.h * (H + ICU) + IA + m.tA * YA +
pc$behavioral.increase.mixing * (Pv + m.Sm * IAv + m.tA * YAv)) *
V)
} else {
V_to_Ev = rep(0,length(compartment$PopulationShareInLocation))
}
# V to Ev is always positive.
V_to_Ev = abs(V_to_Ev)