Exemple #1
0
def SIRD(graph, dict_p, tmax = 100, IC = {}, node_seed=-1):
    for key in dict_p.keys():
        if key == 'inf_rate':
            inf_rate = dict_p['inf_rate']
        elif key == 'rec_rate':
            rec_rate = dict_p['rec_rate']
        elif key == 'death_rate':
            death_rate = dict_p['death_rate']
        elif key == 'N_init':
            N_init = dict_p['N_init']
    
    H = nx.DiGraph()  #the spontaneous transitions
    H.add_edge('Inf', 'Dead', rate = death_rate,weight_label='expose2infect_weight')
    H.add_edge('Inf', 'Rec', rate = rec_rate)
   
    J = nx.DiGraph()  #the induced transitions
    J.add_edge(('Inf', 'Sus'), ('Inf', 'Inf'), rate = inf_rate)
    if len(IC) == 0:
        set_node_status(graph, dict_p,node_seed=node_seed)
        IC = defaultdict(lambda:'Sus')
        for i in list(np.random.randint(dict_p['N'],size = math.ceil(N_init))):
            IC[i] = 'Inf'
      
    return_statuses = ['Sus', 'Inf', 'Rec', 'Dead']
    sim = EoN.Gillespie_simple_contagion(graph, H, J, IC, return_statuses, tmax=tmax, \
                                         return_full_data=True)
    return sim,dict_p
Exemple #2
0
def run_until_prev(input_net, H, J, initial_conditions,
                   prev_start_SD):
    net = input_net.copy()
    next_step_IC = initial_conditions
    t = None
    S = None
    E = None
    I = None
    R = None
    
    curr_prev = 0
    while (curr_prev < prev_start_SD):
        # Run for one time step ------------------------------------------------
        full_net_one_step = EoN.Gillespie_simple_contagion(net, H, J, next_step_IC, return_statuses, tmax = 1, return_full_data=True)    
        t_one_step = full_net_one_step.t()
        S_one_step = full_net_one_step.S()
        E_one_step = full_net_one_step.summary()[1]['E']
        I_one_step = full_net_one_step.I()
        R_one_step = full_net_one_step.R()

        # Concatenate results of the single time step --------------------------
        if ((t is None) and (S is None) and (E is None) and (I is None) and (R is None)):
            t = t_one_step
            S = S_one_step
            E = E_one_step
            I = I_one_step
            R = R_one_step
        else:
            t = np.concatenate((t, (t_one_step + t[-1])), axis=None)
            S = np.concatenate((S, S_one_step), axis=None)
            E = np.concatenate((E, E_one_step), axis=None)
            I = np.concatenate((I, I_one_step), axis=None)
            R = np.concatenate((R, R_one_step), axis=None)
        
        # Get prevalence -------------------------------------------------------
        curr_prev = (E[-1] + I[-1]) / N

        # Get initial conditions for next step of simulation -------------------
        nodes_one_step_final = full_net_one_step.get_statuses(list(range(N)), t_one_step[-1])
        next_step_IC = defaultdict(lambda: 'S')
        for node in range(N):
            status = nodes_one_step_final[node]
            next_step_IC[node] = status

    # Create complete returnable object of simulation --------------------------
    to_add = list()
    to_add.append(t)
    to_add.append(S)
    to_add.append(E)
    to_add.append(I)
    to_add.append(R)

    full_net = full_net_one_step

    last_time_step_dictionary = full_net.get_statuses(time=full_net.t()[-1])
    
    to_return = [last_time_step_dictionary, to_add, t[-1]]
    
    return to_return
Exemple #3
0
def create_simulation(
    sim_name,
    sq_rate,
    qs_rate,
    it_rate,
    si_rate,
    population_size,
    initial_infection_number,
):
    matrix_size = int(round(population_size**(0.5)))
    G = nx.grid_2d_graph(matrix_size, matrix_size)

    initial_infections = [(randint(0, matrix_size), randint(0, matrix_size))
                          for _ in range(initial_infection_number)]

    H = nx.DiGraph()
    H.add_edge('Susc', 'Quar', rate=sq_rate)
    H.add_edge('Quar', 'Susc', rate=qs_rate)
    H.add_edge('Infe', 'Trea', rate=it_rate)
    H.add_edge('Trea', 'Quar', rate=0.05)

    J = nx.DiGraph()
    J.add_edge(('Infe', 'Susc'), ('Infe', 'Infe'), rate=si_rate)

    IC = defaultdict(lambda: 'Susc')
    for node in initial_infections:
        IC[node] = 'Infe'

    return_statuses = ['Susc', 'Infe', 'Trea', 'Quar']

    sim_kwargs = {
        'color_dict': {
            'Susc': '#5cb85c',
            'Infe': '#d9534f',
            'Trea': '#f0ad4e',
            'Quar': '#0275d8',
        },
        'pos': {node: node
                for node in G},
        'tex': False,
    }

    sim = EoN.Gillespie_simple_contagion(
        G,
        H,
        J,
        IC,
        return_statuses,
        tmax=150,
        return_full_data=True,
        sim_kwargs=sim_kwargs,
    )

    produce_visualization(sim_name, sim, population_size)
    convert_video(sim_name)
Exemple #4
0
    def run(self, t0, tmax, tsteps, state):
        G, IC = state

        H, J = self.transitions()

        rs = [o["name"] for o in self.observables]
        ig = EoN.Gillespie_simple_contagion(G, H, J, IC, rs, tmax = (tmax-t0), return_full_data=True)

        nettime, cols = ig.summary()
        nettraj = np.vstack(list(cols[o] for o in rs))
        nettime += t0

        t = np.linspace(t0, tmax, tsteps)
        if nettime.shape == (1,):
            ## can't interpolate if no transitions are possible
            traj = np.vstack(list(nettraj.T for _ in range(tsteps))).T
        else:
            traj = interp1d(nettime, nettraj, kind="previous", bounds_error=False,
                            fill_value=(nettraj[:,0], nettraj[:,-1]))(t)

        return (t, traj.T, (ig.G, ig.get_statuses(time=nettime[-1])))
Exemple #5
0
def run_SEIR(G,
             E2I_rate,
             trans_rate,
             recov_rate,
             init_seed_frac,
             initially_infected_nodes=None):

    N = G.number_of_nodes()

    H = nx.DiGraph()
    H.add_node("S")
    H.add_edge("E", "I", rate=E2I_rate)
    H.add_edge("I", "R", rate=recov_rate)

    J = nx.DiGraph()
    J.add_edge(("I", "S"), ("I", "E"), rate=trans_rate)
    IC = defaultdict(lambda: "S")

    if initially_infected_nodes is None:
        initially_infected_nodes = np.random.choice(
            N, np.round(N * init_seed_frac).astype(int), replace=False)
    for node in initially_infected_nodes:
        IC[node] = "E"

    return_statuses = ("S", "E", "I", "R")

    sim_data = EoN.Gillespie_simple_contagion(
        G,
        H,
        J,
        IC,
        return_full_data=True,
        return_statuses=return_statuses,
        tmax=float("Inf"),
    )
    return sim_data
J = nx.DiGraph()  #the induced transitions
J.add_edge(('Inf', 'Sus'), ('Inf', 'Inf'), rate = 2.0)

IC = defaultdict(lambda:'Sus')
for node in initial_infections:
    IC[node] = 'Inf'

return_statuses = ['Sus', 'Inf', 'Rec', 'Vac']

color_dict = {'Sus': '#009a80','Inf':'#ff2000', 'Rec':'gray','Vac': '#5AB3E6'}
pos = {node:node for node in G}
tex = False
sim_kwargs = {'color_dict':color_dict, 'pos':pos, 'tex':tex}

sim = EoN.Gillespie_simple_contagion(G, H, J, IC, return_statuses, tmax=total_simulation_days, return_full_data=True, sim_kwargs=sim_kwargs)

count = 0
while(count < total_simulation_days):
	t, S, E, I, R = EoN.Gillespie_simple_contagion(G, H, J, IC, return_statuses, tmax=count, sim_kwargs=sim_kwargs)
	new_infected_case = I[-1]
	diff = new_infected_case - previous_infected_case
	previous_infected_case = new_infected_case
	total_infected_case=total_infected_case+diff
	count=count+1

total_death=total_death + int(total_infected_case*0.02)  #percentage of death based on current data.. 
print("Current Infected People after vaccine: ", total_infected_case, "/", population*population)  ##Number of infected people without vaccine 
print("Total Death People after vaccine:", total_death, "/", population*population)

H.add_edge('E', 'I', rate=0.1809, weight_label='expose2infect_weight')
H.add_edge('I', 'R', rate=0.090)

J = nx.DiGraph()  # Transmissão induzida
J.add_edge(('I', 'S'), ('I', 'E'),
           rate=0.0933,
           weight_label='transmission_weight')
IC = defaultdict(lambda: 'S')

for node in range(50):
    IC[node] = 'I'
return_statuses = ('S', 'E', 'I', 'R')
print('Realizando a simulação de Gillespie')
t, S, E, I, R = EoN.Gillespie_simple_contagion(G,
                                               H,
                                               J,
                                               IC,
                                               return_statuses,
                                               tmax=float(150))

# Pega dados reais
result = pd.read_csv('arquivos/CovidCE.csv', sep=';')
# print(result)

# print(result.values.transpose()[0])
# print(result.values.transpose()[1])

# ----------------------------------
# Salva dados em csv Simulação_COVID
# ----------------------------------
Ob = np.array(0.065 * (R + I))
Ob = np.around(Ob)
J.add_edge(('II', 'RS'), ('II', 'RI'), rate = 0.2)
J.add_edge(('RI', 'SS'), ('RI', 'SI'), rate = 1)
J.add_edge(('RI', 'IS'), ('RI', 'II'), rate = 1)
J.add_edge(('RI', 'RS'), ('RI', 'RI'), rate = 1)
J.add_edge(('IS', 'SS'), ('IS', 'IS'), rate = 0.2)
J.add_edge(('IS', 'SI'), ('IS', 'II'), rate = 0.2)
J.add_edge(('IS', 'SR'), ('IS', 'IR'), rate = 0.2)
J.add_edge(('II', 'SS'), ('II', 'IS'), rate = 0.2)
J.add_edge(('II', 'SI'), ('II', 'II'), rate = 0.2)
J.add_edge(('II', 'SR'), ('II', 'IR'), rate = 0.2)
J.add_edge(('IR', 'SS'), ('IR', 'IS'), rate = 1)
J.add_edge(('IR', 'SI'), ('IR', 'II'), rate = 1)
J.add_edge(('IR', 'SR'), ('IR', 'IR'), rate = 1)


return_statuses = ('SS', 'SI', 'SR', 'IS', 'II', 'IR', 'RS', 'RI', 'RR')

initial_size = 700
IC = defaultdict(lambda: 'SS')
for node in range(initial_size):
    IC[node] = 'II'


t, SS, SI, SR, IS, II, IR, RS, RI, RR = EoN.Gillespie_simple_contagion(G, H, J, IC, return_statuses, 
                                        tmax = float('Inf'))    

plt.semilogy(t, IS+II+IR, '-.', label = 'Infected with disease 1')
plt.semilogy(t, SI+II+RI, '-.', label = 'Infected with disease 2') 

plt.legend()
plt.savefig('Cooperate.png')
return_statuses = ['Sus', 'Inf', 'Rec', 'Vac']

color_dict = {
    'Sus': '#009a80',
    'Inf': '#ff2000',
    'Rec': 'gray',
    'Vac': '#5AB3E6'
}
pos = {node: node for node in G}
tex = False
sim_kwargs = {'color_dict': color_dict, 'pos': pos, 'tex': tex}

sim = EoN.Gillespie_simple_contagion(G,
                                     H,
                                     J,
                                     IC,
                                     return_statuses,
                                     tmax=30,
                                     return_full_data=True,
                                     sim_kwargs=sim_kwargs)
#Esto no maneja contagios complejos. Se asume que cuando un individuo cambia de estado, ha recibido una “transmisión” de un solo vecino o está cambiando de estado independientemente de los vecinos. Entonces esto es como SIS o SIR.
#EoN.Gillespie_simple_contagion(G, spontaneous_transition_graph, nbr_induced_transition_graph, IC, return_statuses, tmin=0, tmax=100, spont_kwargs=None, nbr_kwargs=None, return_full_data=False, sim_kwargs=None)
#spontaneous_transition_graph:contagios espontaneos, nbr_induced_transition_graph: transiciones inducidas por vecinos,  IC:establece el estado inicial de cada nodo en la red.

times, D = sim.summary()
#
#imes is a numpy array of times.  D is a dict, whose keys are the entries in
#return_statuses.  The values are numpy arrays giving the number in that
#status at the corresponding time.

newD = {
    'Sus+Vac': D['Sus'] + D['Vac'],
Exemple #10
0
def add_relaxation(input_net, H, J, initial_conditions,
                   t, S, E, I, R,
                   unfuse,
                   fused_edges_dict,
                   length_sim):
    net = input_net.copy()
    
    # If unfuse, perhaps tedious, but have not found a better way to do it: 
    # check every day for infectious persons in the graph. ---------------------
    if unfuse:
        next_step_IC = initial_conditions
        save_last_R = 0
        while not ((E[-1] == 0 and I[-1] == 0 and R[-1] == save_last_R)):
            save_last_R = R[-1]
            
            # Run for one time step --------------------------------------------
            full_net_one_step = EoN.Gillespie_simple_contagion(net, H, J, next_step_IC, return_statuses, tmax = 1, return_full_data=True)    
            t_one_step = full_net_one_step.t()
            S_one_step = full_net_one_step.S()
            E_one_step = full_net_one_step.summary()[1]['E']
            I_one_step = full_net_one_step.I()
            R_one_step = full_net_one_step.R()

            # Concatenate results of the single time step ----------------------
            t = np.concatenate((t, (t_one_step + t[-1])), axis=None)
            S = np.concatenate((S, S_one_step), axis=None)
            E = np.concatenate((E, E_one_step), axis=None)
            I = np.concatenate((I, I_one_step), axis=None)
            R = np.concatenate((R, R_one_step), axis=None)

            # Get list of nodes that are infectious at the end of this time step
            # as well as get initial conditions for next step of simulation ----
            nodes_one_step_final = full_net_one_step.get_statuses(list(range(N)), t_one_step[-1])
            next_step_IC = defaultdict(lambda: 'S')
            symptomatic_nodes = []
            for node in range(N):
                status = nodes_one_step_final[node]
                next_step_IC[node] = status
                if status == "I":
                    symptomatic_nodes.append(node)

            # Run unfuse method ------------------------------------------------
            net = unfuse_graph(input_graph=net, 
                               symptomatic_nodes=symptomatic_nodes, 
                               fused_edges_dict=fused_edges_dict, 
                               prob_unfuse=prob_unfuse)

        # Create complete returnable object of simulation ----------------------
        to_add = list()
        to_add.append(t)
        to_add.append(S)
        to_add.append(E)
        to_add.append(I)
        to_add.append(R)

        full_net = full_net_one_step
    else:
        full_net = EoN.Gillespie_simple_contagion(net, H, J, initial_conditions, return_statuses, tmax = length_sim, return_full_data=True)    
        t_net = full_net.t()
        S_net = full_net.S()
        E_net = full_net.summary()[1]['E']
        I_net = full_net.I()
        R_net = full_net.R()

        t = np.concatenate((t, (t_net + t[-1])), axis = None)
        S = np.concatenate((S, S_net), axis=None)
        E = np.concatenate((E, E_net), axis=None)
        I = np.concatenate((I, I_net), axis=None)
        R = np.concatenate((R, R_net), axis=None)

        to_add = list()
        to_add.append(t)
        to_add.append(S)
        to_add.append(E)
        to_add.append(I)
        to_add.append(R)
    
    last_time_step_dictionary = full_net.get_statuses(time=full_net.t()[-1])
    
    to_return = [last_time_step_dictionary, to_add]
    
    return to_return
Exemple #11
0
 returned_run_until_prev = run_until_prev(input_net=O, H=H, J=J, initial_conditions=IC,
                                          prev_start_SD=prev_start_SD)
 t_O = returned_run_until_prev[1][0]
 S_O = returned_run_until_prev[1][1]
 E_O = returned_run_until_prev[1][2]
 I_O = returned_run_until_prev[1][3]
 R_O = returned_run_until_prev[1][4]
 nodes_O_final = returned_run_until_prev[0]
 SD_day = returned_run_until_prev[2]
 SD_days.append(SD_day)
     
 # Next, run on the SD graph ------------------------------------------------
 SD_IC = defaultdict(lambda: 'S')
 for node in range(N):
     SD_IC[node] = nodes_O_final[node]
 full_SD = EoN.Gillespie_simple_contagion(SD, H, J, SD_IC, return_statuses, tmax = sd_to_easing, return_full_data=True)
 t_SD = full_SD.t()
 S_SD = full_SD.S()
 E_SD = full_SD.summary()[1]['E']
 I_SD = full_SD.I()
 R_SD = full_SD.R()
 nodes_SD_final = full_SD.get_statuses(list(range(N)), t_SD[-1])
 
 # Next, run on the added_frac_long_SD graph --------------------------------
 expanded_SD_IC = defaultdict(lambda: 'S')
 for node in range(N):
     expanded_SD_IC[node] = nodes_SD_final[node]
 full_expanded_SD = EoN.Gillespie_simple_contagion(added_frac_long_SD, H, J, expanded_SD_IC, return_statuses, tmax=easing_to_evictions, return_full_data=True)
 t_expanded_SD = full_expanded_SD.t()
 S_expanded_SD = full_expanded_SD.S()
 E_expanded_SD = full_expanded_SD.summary()[1]['E']
Exemple #12
0
H.add_node('S')
H.add_edge('E', 'I', rate=0.6,
           weight_label='expose2infect_weight')  #speed is 0.6*weight
H.add_edge('I', 'R', rate=0.01)

# Neighbor-dependent Transitions
J = nx.DiGraph()
J.add_edge(('I', 'S'), ('I', 'E'),
           rate=0.5,
           weight_label='transmission_weight')

## Set Initial Conditions
IC = defaultdict(lambda: 'S')

random_infected = random.sample(list(G.nodes), k=1)
for node in random_infected:
    IC[node] = 'I'

return_statuses = ('S', 'E', 'I', 'R')

epidemic = EoN.Gillespie_simple_contagion(G,
                                          H,
                                          J,
                                          IC,
                                          return_statuses,
                                          tmax=float('Inf'),
                                          return_full_data=True)

# Simple sample plotting
plt.plot(epidemic.t(), epidemic.I())
plt.savefig('epidemic_curve.png')
Exemple #13
0
    return scale

def return_to_susceptibility_weighting(G, node, **kwargs):
    scale = 1
    if G.node[node]['gender'] is 'F':
        scale *= 0.5
    return scale

H = nx.DiGraph()  #DiGraph showing possible transitions that don't require an interaction
H.add_edge('I', 'R', rate = 1.4, rate_function=recovery_weighting)   #I->R
H.add_edge('R', 'S', rate = 0.2, rate_function = return_to_susceptibility_weighting)   #R->S

J = nx.DiGraph()    #DiGraph showing transition that does require an interaction.
J.add_edge(('I', 'S'), ('I', 'I'), rate = 1, rate_fuction = transmission_weighting)  #IS->II

IC = defaultdict(lambda: 'S')
for node in range(200):
    IC[node] = 'I'

return_statuses = ('S', 'I', 'R')

age_cutoff = 18
t, S, I, R = EoN.Gillespie_simple_contagion(G, H, J, IC, return_statuses, tmax = 30,
                            spont_kwargs = {'age_cutoff':age_cutoff},
                            nbr_kwargs = {'age_cutoff':age_cutoff})

plt.plot(t, S, label = 'Susceptible')
plt.plot(t, I, label = 'Infected')
plt.plot(t, R, label = 'Recovered')
plt.legend()
plt.savefig('SIRS_heterogeneous.png')