Dear all,
I want to fit a SIR model with four transmission rates at four time periods, I tried to write the code, but it seems that the function integrate_ode_rk45 cannot deal with the function ‘sir’ because the type of ‘sir’ is real[,]. Could anyone help for correcting and improving the code. Thanks in advance. Pls see the code below.
functions {
real[,] sir(real ts, int n_days, int[] t_thre, real[,] y, real[] theta, real[] x_r, int[] x_i) {
real S[n_days] = y[1];
real I[n_days] = y[2];
real R[n_days] = y[3];
real N = x_i[1];
real beta1 = theta[1];
real beta2 = theta[2];
real beta3 = theta[3];
real beta4 = theta[4];
real gamma = theta[5];
int t_thre1 = t_thre[1];
int t_thre2 = t_thre[2];
int t_thre3 = t_thre[3];
int t_thre4 = t_thre[4];
real dS_dt[n_days];
real dI_dt[n_days];
real dR_dt[n_days];
for(i in 1:(t_thre1-1)){
dS_dt[i] = -beta1 * I[i] * S[i] / N;
dI_dt[i] = beta1 * I[i] * S[i] / N - gamma * I[i];
dR_dt[i] = gamma * I[i];
}
for(i in t_thre1:(t_thre2-1)){
dS_dt[i] = -beta2 * I[i] * S[i] / N;
dI_dt[i] = beta2 * I[i] * S[i] / N - gamma * I[i];
dR_dt[i] = gamma * I[i];
}
for(i in t_thre2:(t_thre3-1)){
dS_dt[i] = -beta3 * I[i] * S[i] / N;
dI_dt[i] = beta3 * I[i] * S[i] / N - gamma * I[i];
dR_dt[i] = gamma * I[i];
}
for(i in t_thre3:n_days){
dS_dt[i] = -beta4 * I[i] * S[i] / N;
dI_dt[i] = beta4 * I[i] * S[i] / N - gamma * I[i];
dR_dt[i] = gamma * I[i];
}
return {dS_dt, dI_dt, dR_dt};
}
}
data {
int<lower=1> n_days;
real y0[3];
real t0;
real ts[n_days];
int N;
int cases[n_days];
}
transformed data {
real x_r[0];
int x_i[1] = { N };
}
parameters {
real<lower=0> gamma;
real<lower=0> beta1;
real<lower=0> beta2;
real<lower=0> beta3;
real<lower=0> beta4;
real<lower=0> phi_inv;
}
transformed parameters{
real y[n_days, 3];
real phi = 1. / phi_inv;
{
real theta[5];
theta[1] = beta1;
theta[2] = beta2;
theta[3] = beta3;
theta[4] = beta4;
theta[5] = gamma;
y = integrate_ode_rk45(sir, y0, t0, ts, theta, x_r, x_i);
}
}
model {
//priors
beta1 ~ normal(2, 1); // how to determine the prior?
beta2 ~ normal(2, 1);
beta3 ~ normal(2, 1);
beta4 ~ normal(2, 1);
gamma ~ normal(0.4, 0.5);
phi_inv ~ exponential(5);
//sampling distribution
//col(matrix x, int n) - The n-th column of matrix x. Here the number of infected people
cases ~ neg_binomial_2(col(to_matrix(y), 2), phi);
}
generated quantities {
real recovery_time = 1 / gamma;
real pred_cases[n_days];
real S[n_days];
pred_cases = neg_binomial_2_rng(col(to_matrix(y), 2), phi);
S = col(to_matrix(y), 1);
}