-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08_model_fitting_eir_prev_usage.R
90 lines (69 loc) · 2.46 KB
/
08_model_fitting_eir_prev_usage.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
library(zoo)
library(tidyverse)
library(readxl)
source("R/run_model.R")
##################################################################################################
# Run function
run <- function(init_EIR, usage, model_parameters){
# Time of reading data
time <- 6*365
model <- run_model(init_EIR = init_EIR, usage = usage,
model_parameters = model_parameters, t_max = 10*365)
prev <- rollmean(model$prev659, k=3*365, fill = NA, align='left')[time]
print(prev)
return (prev)
}
# Fitting method
bisection_fitting <- function(usage = 0.5, prevalence, model_parameters){
n <- 100
# Set initial conditions and start the algorithm
if (prevalence > 0.6 & usage > 0.4){
init_EIRs <- c(100, 8000)
} else if (prevalence > 0.6 & usage <= 0.4){
init_EIRs <- c(100, 7000)
} else {
init_EIRs <- c(0.01, 2000)
}
run_lower <- run(init_EIR = init_EIRs[1], usage = usage, model_parameters = model_parameters)
run_upper <- run(init_EIR = init_EIRs[2], usage = usage, model_parameters = model_parameters)
run_values <- c(run_lower - prevalence, run_upper - prevalence)
print (run_values)
if (sign(run_values[1]) == sign(run_values[2])){
stop("Incorrect initial range of EIRs")
}
for (i in 1:n){
print(i)
new_EIR <- sum(init_EIRs) / 2
# Check convergence
if ((init_EIRs[2] - init_EIRs[1])/2 < 1e-2){
print ("Converged!")
return (new_EIR)
}
new_value <- run(init_EIR = new_EIR, usage = usage, model_parameters = model_parameters) - prevalence
print(prevalence)
if (sign(new_value) == sign(run_values[1])){
init_EIRs[1] <- new_EIR
run_values[1] <- new_value
} else {
init_EIRs[2] <- new_EIR
run_values[2] <- new_value
}
}
print ("Not converged and reached iteration count.")
return (NULL)
}
model_parameters = read_excel(path="data/parameter_sweep_res.xlsx")
prevs <- c(1:8/10)
resistances <- unique(model_parameters$RESISTANCE)
fitted_EIRs <- matrix(nrow = length(prevs), ncol = length(resistances))
for (i in 1:length(prevs)){
for (j in 1:length(resistances)){
fitted_EIRs[i, j] <- bisection_fitting(usage = 0.5,
prevalence = prevs[i],
model_parameters = model_parameters[j,])
}
}
data <- data.frame(fitted_EIRs)
colnames(data) = c(0, 0.4, 0.8)
rownames(data) = prevs
saveRDS(data, "outputs/fitted_EIRs_prev_resistance.RDS")