def opti(x): i = 0 aux = [0, 0, 0, 0] # Beta if type(self.beta_r) == list: aux[0] = x[i] i += 1 else: aux[0] = self.beta_r # Sigma if type(self.sigma_r) == list: aux[1] = x[i] i += 1 else: aux[1] = self.sigma_r # Gamma if type(self.gamma_r) == list: aux[2] = x[i] i += 1 else: aux[2] = self.gamma_r # Mu if type(self.mu_r) == list: aux[3] = x[i] i += 1 else: aux[3] = self.mu_r model = SEIR(self.P, self.eta, self.alpha, self.S0, self.E0, self.I0, self.R0, aux[0], aux[1], aux[2], aux[3]) model.integr(self.t0, self.T, self.h, True) return (objective_funct(Ir, tr, model.I, model.t, 'fro'))
def opti(x): i = 0 aux = [0, 0, 0, 0] # Beta if type(self.beta_r) == list: aux[0] = x[i] i += 1 else: aux[0] = self.beta_r # Sigma if type(self.sigma_r) == list: aux[1] = x[i] i += 1 else: aux[1] = self.sigma_r # Gamma if type(self.gamma_r) == list: aux[2] = x[i] i += 1 else: aux[2] = self.gamma_r # Mu if type(self.mu_r) == list: aux[3] = x[i] i += 1 else: aux[3] = self.mu_r ie = 0 ie = i def eta(t): eta = np.ones(self.P.shape[0]) for j in range(self.P.shape[0]): eta[j] = x[ie + j] return (eta) self.eta = eta ia = 0 ia = ie + self.P.shape[0] def alpha(t): alpha = np.zeros([self.P.shape[0], self.P.shape[0]]) for j in range(self.P.shape[0]): for k in range(self.P.shape[0]): alpha[j][k] = x[j + ia] * x[k + ia] return (alpha) self.alpha = alpha model = SEIR(self.P, eta, alpha, self.S0, self.E0, self.I0, self.R0, aux[0], aux[1], aux[2], aux[3]) model.integr(self.t0, self.T, self.h, True) self.eta = eta self.alpha = alpha return (objective_funct(Ir, tr, model.I, model.t, 'fro'))
def refineRW(self, I_r, tr, r0, Npoints, steps, err, obj_func='IN'): # Refine using Montecarlo - Markov Chain mesh = self.mesh(Npoints) if obj_func == 'IN': objective_function = self.objective_funct_I_Norm elif obj_func == 'IR': objective_function = self.objective_funct_I_rate results = [] for i in range(Npoints): # print("Mesh point number "+str(i)) aux = self.LocMinRW(I_r, tr, mesh[i][0], mesh[i][1], mesh[i][2], mesh[i][3], r0, steps, err, objective_function) results.append(aux) # print("Error: "+str(aux[-1])) self.paramsRW = np.array(results) optindex = np.where( self.paramsRW[:, 4] == np.amin(self.paramsRW[:, 4]))[0][0] self.optimalRW = self.paramsRW[optindex, :] self.errorRW = self.optimalRW[-1] # should define an exit protocol self.SEIR = SEIR(self.P, self.eta, self.alpha, self.S0, self.E0, self.I0, self.R0, self.optimalRW[0], self.optimalRW[1], self.optimalRW[2], self.optimalRW[3]) return self.optimalRW
def refineMH(self, I_r, tr, r0, Npoints, steps, err, obj_func='IN'): if obj_func == 'IN': objective_function = self.objective_funct_I_Norm elif obj_func == 'IR': objective_function = self.objective_funct_I_rate # find the optimal parameter using metropolis-hastings # desnity of phase space parameter for the optimizacion of calculeted infected vs. real infected mesh = self.mesh(Npoints) # tr=np.arange(I_r.shape[1]) results = [] for i in range(Npoints): aux = self.met_hast(I_r, tr, mesh[i][0], mesh[i][1], mesh[i][2], mesh[i][3], r0, steps, err, objective_function) results.append(aux) self.paramsMH = np.array(results) optindex = np.where( self.paramsMH[:, 4] == np.amin(self.paramsMH[:, 4]))[0][0] self.optimalMH = self.paramsMH[optindex, :] self.errorMH = self.optimalMH[-1] # should define an exit protocol self.SEIR = SEIR(self.P, self.eta, self.alpha, self.S0, self.E0, self.I0, self.R0, self.optimalMH[0], self.optimalMH[1], self.optimalMH[2], self.optimalMH[3]) return self.optimalMH
# error.append(objective_funct(Ir,tr,test.I,test.t,'fro')) # print(error) # outfile = "/home/sropert/sigmaerror4.csv" # #Gamma # for i in range(len(gamma)): # test = SEIR(P,eta,alpha,S0,E0,I0,R0,betaopt, sigmaopt, gamma[i],muopt) # test.integr(min(tr),max(tr),0.1,True) # error.append(objective_funct(Ir,tr,test.I,test.t,'fro')) # print(error) # outfile = "/home/sropert/gammaerror4.csv" #Mu for i in range(len(mu)): test = SEIR(P,eta,alpha,S0,E0,I0,R0,betaopt, sigmaopt, gammaopt,mu[i]) test.integr(min(tr),max(tr),0.1,True) error.append(objective_funct(Ir,tr,test.I,test.t,'fro')) print(error) outfile = "/home/sropert/muerror4.csv" np.savetxt(outfile, error, delimiter=",") #error 1: #mu = np.arange(1.8,2.2,0.002) #error 2: #mu = np.arange(1.98,2.02,0.0002)
def LocMinRW(self, I_r, tr, beta_i, sigma_i, gamma_i, mu_i, r0, steps, err, objective_funct): #print("Build SEIR") x = SEIR(self.P, self.eta, self.alpha, self.S0, self.E0, self.I0, self.R0, beta_i, gamma_i, sigma_i, mu_i) #print("RK4") if x.scikitsimport: x.integr(self.t0, self.T, self.h, True) else: #print("RK4") x.integr_RK4(self.t0, self.T, self.h, True) e_0 = objective_funct(I_r, tr, x.I, x.t, 2) e_o = e_0 params = [[beta_i, sigma_i, gamma_i, mu_i, e_o]] i = 0 k = 0 #print("Met-Hast") while i < steps: [b_p, s_p, g_p, m_p] = self.transition_model(x.beta, x.sigma, x.gamma, x.mu, r0) x_new = SEIR(self.P, self.eta, self.alpha, self.S0, self.E0, self.I0, self.R0, b_p, s_p, g_p, m_p) if x_new.scikitsimport: x_new.integr(self.t0, self.T, self.h, True) else: x_new.integr_RK4(self.t0, self.T, self.h, True) e_n = objective_funct(I_r, tr, x_new.I, x_new.t, 2) # Acceptance if (e_n / e_o < 1): x = x_new e_o = e_n params.append([b_p, s_p, g_p, m_p, e_n]) i += 1 k = 0 print("------------------") print(b_p, s_p, g_p, m_p) print(e_o, e_n) # print("time: "+str(end-start)) # print("Step "+str(i)) if (e_n < err): break k += 1 if k >= 100: break #sleep(0.01) # Dejo los params historicos por si hay que debuggear esta parte return params[-1]
def simulate_multi(state, comunas, params, qp=0, mov=0.2, tsim=300, tci=None, movfunct='sawtooth'): # params = beta sigma gamma mu # Movility function shape if movfunct == 'sawtooth': def f(t): return signal.sawtooth(t) elif movfunct == 'square': def f(t): return signal.square(t) if qp <= 0: def e_fun(t): return (1) elif tci is None: def e_fun(t): return ((1 - mov) / 2 * (f(np.pi / qp * t - np.pi)) + (1 + mov) / 2) else: def e_fun(t): if t < tci: return (1) else: return ((1 - mov) / 2 * (f(np.pi / qp * t - np.pi)) + (1 + mov) / 2) #Endpoint encuesta SECTR, no funcional aún # endpoint="http://192.168.2.223:5004/v1/get_movilidad_por_comuna" # r = requests.get(endpoint) #, params = {"w":"774508"}) # mydict = r.json() # OD=pd.DataFrame(mydict) #Endpoint encuensta ENE # endpoint="http://192.168.2.223:5004/v2/get_movilidad?month=1&year=2019" # r = requests.get(endpoint) #, params = {"w":"774508"}) # mydict = r.json() # info=pd.DataFrame(mydict) # Data csv encuenstra Sectra (funcional) path = "../Data/" OD = pd.read_csv(path + "Movilidad_diaria_comuna.csv", index_col=0) P = OD.filter(comunas) P = P.loc[comunas].to_numpy() endpoint = "http://192.168.2.220:8080/covid19/findComunaByIdState?idState=" + state + "&&comuna=" r = requests.get(endpoint) #, params = {"w":"774508"}) mydict = r.json() info = pd.DataFrame(mydict) comunas = info[info.description.isin(comunas)] init_dates = [] for i in comunas.cut: endpoint = "http://192.168.2.220:8080/covid19/getDatosMinSalSummary?state=" + state + "&comuna=" + i r = requests.get(endpoint) #, params = {"w":"774508"}) mydict = r.json() data = pd.DataFrame(mydict) data = data[data.data != 0] init_dates.append(dt.datetime.strptime(data.labels.iloc[0], '%d/%m')) init_date = max(init_dates).strftime('%d/%m') Ic = [] for i in comunas.cut: endpoint = "http://192.168.2.220:8080/covid19/getDatosMinSalSummary?state=" + state + "&comuna=" + i r = requests.get(endpoint) #, params = {"w":"774508"}) mydict = r.json() data = pd.DataFrame(mydict) init_i = data[data.labels == init_date].index if len(init_i) != 0: init_i = data[data.labels == init_date].index[0] if len(Ic) == 0: Ic = data[['labels', 'data']][init_i:].set_index('labels') Ic.rename(columns={'data': i}, inplace=True) else: Ic = Ic.join(data[['labels', 'data']][init_i:-1].set_index('labels'), on='labels') Ic.rename(columns={'data': i}, inplace=True) else: init_i = 0 if len(Ic) == 0: Ic = data[['labels', 'data']][init_i:].set_index('labels') Ic.rename(columns={'data': i}, inplace=True) else: Ic = Ic.join(data[['labels', 'data']][init_i:-1].set_index('labels'), on='labels') Ic.rename(columns={'data': i}, inplace=True) Ic = Ic.fillna(0) for i in (Ic.columns): for j in range(max(Ic.count()) - 1): if Ic[i].iloc[j + 1] < Ic[i].iloc[j]: Ic[i].iloc[j + 1] = Ic[i].iloc[j] tr = np.zeros(int(max(Ic.count()))) for i in range(1, int(max(Ic.count())), 1): diff = dt.datetime.strptime(Ic.index[i], '%d/%m') - dt.datetime.strptime( Ic.index[i - 1], '%d/%m') tr[i] = diff.days + tr[i - 1] Cn = np.zeros(Ic.shape) for i in range(Ic.shape[1]): Cn[0][i] = Ic.iloc[0][i] for j in range(1, Ic.shape[0], 1): Cn[j][i] = Ic.iloc[j][i] - Ic.iloc[j - 1][i] Ir = np.zeros(Ic.shape) for i in range(Ic.shape[1]): Ir[np.where(tr - 14 <= 0)[0], i] = Ic.iloc[np.where(tr - 14 <= 0)[0], i] for j in np.where(tr - 14 > 0)[0]: ind = np.where(tr - tr[j] + 14 < 0)[0] Ir[j, i] = Ic.iloc[j, i] - sum(Cn[0:ind[-1], i]) So = comunas.numPopulation.to_numpy() Ro = np.array([0, 0, 0, 0, 0]) Ir = Ic.transpose().to_numpy() Io = Ir[:, 0] Eo = 2 * Io S0 = So - Eo - Io E0 = Eo I0 = Io R0 = Ro h = 0.01 ia = 3 + P.shape[0] def alpha(t): alpha = np.zeros([P.shape[0], P.shape[0]]) for j in range(P.shape[0]): for k in range(P.shape[0]): alpha[j][k] = e_fun(t) * params[j + ia] * params[k + ia] return (alpha) def eta(t): eta = np.ones(P.shape[0]) for j in range(P.shape[0]): eta[j] = e_fun(t) * params[3 + j] return (eta) sim = SEIR(P, eta, alpha, S0, E0, I0, R0, params[0], params[1], params[2], params[3]) sim.integr(min(tr), tsim, h, True) return ({ 'S': sim.S, 'E': sim.E, 'I': sim.I, 'R': sim.R, 'tout': sim.t, 'init_date': init_date })