def process_degree_distribution(N, Pk, color, Psi, DPsi, symbol, label, count):
    report_times = scipy.linspace(0, 30, 3000)
    sums = 0 * report_times
    for cnt in range(count):
        G = generate_network(Pk, N)
        t, S, I, R = EoN.fast_SIR(G, tau, gamma, rho=rho)
        plt.plot(t, I * 1. / N, '-', color=color, alpha=0.1, linewidth=1)
        subsampled_I = EoN.subsample(report_times, t, I)
        sums += subsampled_I * 1. / N
    ave = sums / count
    plt.plot(report_times, ave, color='k')

    #Do EBCM
    N = G.order(
    )  #N is arbitrary, but included because our implementation of EBCM assumes N is given.
    t, S, I, R = EoN.EBCM_uniform_introduction(N,
                                               Psi,
                                               DPsi,
                                               tau,
                                               gamma,
                                               rho,
                                               tmin=0,
                                               tmax=10,
                                               tcount=41)
    plt.plot(t, I / N, symbol, color=color, markeredgecolor='k', label=label)

    for cnt in range(3):  #do 3 highlighted simulations
        G = generate_network(Pk, N)
        t, S, I, R = EoN.fast_SIR(G, tau, gamma, rho=rho)
        plt.plot(t, I * 1. / N, '-', color='k', linewidth=0.1)
示例#2
0
def process_degree_distribution(Gbig, Gsmall, color, Psi, DPsi, symbol):
    t, S, I, R = EoN.fast_SIR(Gsmall, tau, gamma, rho=rho)
    plt.plot(t, I * 1. / Gsmall.order(), ':', color=color)
    t, S, I, R = EoN.fast_SIR(Gbig, tau, gamma, rho=rho)
    plt.plot(t, I * 1. / Gbig.order(), color=color)
    N = Gbig.order(
    )  #N is arbitrary, but included because our implementation of EBCM assumes N is given.
    t, S, I, R = EoN.EBCM(N, lambda x: (1 - rho) * Psi(x), lambda x:
                          (1 - rho) * DPsi(x), tau, gamma, 1 - rho)
    I = EoN.subsample(report_times, t, I)
    plt.plot(report_times, I / N, symbol, color=color, markeredgecolor='k')
示例#3
0
def run_epidemics(G, tau, gamma, weight, num_init, perc_infec, full=False):
    '''
    '''
    time = None
    nodes = list(G.nodes())
    n_nodes = len(nodes)
    n_iter = 0
    
    while time is None:
        np.random.shuffle(nodes)

        full_data = EoN.fast_SIR(G, tau, gamma, initial_infecteds=nodes[0:num_init], 
        transmission_weight=weight, return_full_data=True)

        infec = full_data.I()
        recov = full_data.R()

        for i in range(infec.shape[0]):
            if infec[i] + recov[i] >= perc_infec * n_nodes:
                time = full_data.t()[i]
                break
        
        n_iter += 1
        
        if n_iter > 1000:
            print("Could not reach desired infection rate after 1000 iterations")
        
            return None
    
    if full is True:
        return full_data
    else:
        return full_data.get_statuses(time=time)
示例#4
0
def epidemy_with_recover(graph,
                         initial_nodes,
                         transmission_rate,
                         recovery_rate,
                         plot_tittle='',
                         return_full_data=False):

    if return_full_data:
        return EoN.fast_SIR(graph,
                            transmission_rate,
                            gamma=recovery_rate,
                            initial_infecteds=initial_nodes,
                            return_full_data=return_full_data)

    else:
        t, S, I, R = EoN.fast_SIR(graph,
                                  transmission_rate,
                                  gamma=recovery_rate,
                                  initial_infecteds=initial_nodes)
        max_time_index = 0
        biggest_number_infected = 0
        for i in range(0, len(I)):
            if I[i] > biggest_number_infected:
                print(f'Infectados:{I[i]} = Limiar:{biggest_number_infected}')
                biggest_number_infected = I[i]
                max_time_index = i

        t = t * 100

        plt.title(plot_tittle)

        plt.plot(t, I, label='Infectados')
        plt.plot(t, S, label='Suscetivel')
        plt.plot(t, R, label='Removidos')

        plt.hlines(I[max_time_index], t[0], t[max_time_index], colors='k')
        plt.vlines(t[max_time_index], I[0], I[max_time_index], colors='k')

    plt.xlim(0, max(t))
    plt.ylim(0, graph.number_of_nodes())
    plt.xticks([t[max_time_index]])
    plt.yticks([I[max_time_index]])

    plt.legend(loc='best')
    plt.show()
def SIR_process(G, degree_prob, tau, gamma, tmax=10):
    N = G.order()
    plt.figure(2)
    plt.clf()
    plt.figure(3)
    plt.clf()
    plt.figure(5)
    plt.clf()
    for index, starting_node in enumerate([x * N / 100. for x in range(100)]):
        plt.figure(2)
        t, S, I, R = EoN.fast_SIR(G,
                                  tau,
                                  gamma,
                                  initial_infecteds=[starting_node])
        subt = scipy.linspace(0, t[-1], 101)
        subI, subR = EoN.subsample(subt, t, I, R)
        plt.plot(subt, subI)
        if R[-1] > 500:
            plt.figure(3)
            shift = EoN.get_time_shift(t, R, threshold)
            plt.plot(subt - shift, subI)
            plt.figure(5)
            plt.plot(subt - shift, subR)
    #t, S, I, R = EoN.EBCM(degree_prob, tau, gamma, rho)
    rho = 1. / N

    def psi(x):
        return sum(degree_prob[k] * x**k for k in degree_prob)

    def psiPrime(x):
        return sum(k * degree_prob[k] * x**(k - 1) for k in degree_prob)

    t, S, I, R = EoN.EBCM_uniform_introduction(N,
                                               psi,
                                               psiPrime,
                                               tau,
                                               gamma,
                                               rho,
                                               tmax=tmax)
    shift = EoN.get_time_shift(t, R, threshold)

    plt.figure(2)
    #plt.savefig('sw_SIR_epi_N{}_p{}_k{}_tau{}.pdf'.format(N,p,k,tau))
    plt.figure(3)
    plt.plot(t - shift, I, '--')
    plt.xlabel('$t$', fontsize=18)
    plt.ylabel('$I$', fontsize=18)
    #plt.set_xtick_labels(fontsize = 15)
    xmax = get_xmax(t - shift, I)
    plt.axis(xmax=xmax)
    plt.savefig('sw_SIR_epi_N{}_p{}_k{}_tau{}_shifted.pdf'.format(
        N, p, k, tau))
    plt.figure(5)
    plt.plot(t - shift, R, '--')
示例#6
0
def simulateGraph(clusteringAlg, params, full_data=False):
    record.print('\n')
    record.print(
        "building populace into graphs with the  {} clustering algorithm".
        format(clusteringAlg.__name__))
    start = time.time()

    graph = nx.Graph()
    clusterGroups(graph, 'sp_hh_id', homeInfectivity, clusterDenseGroup)
    record.print("{} weights of size {} have been added for {} homes".format(
        graph.size(), 1, len(popsByCategory['sp_hh_id'].keys())))

    clusterGroups(graph, 'work_id', workInfectivity, clusteringAlg, params)
    clusterGroups(graph, 'school_id', workInfectivity, clusteringAlg, params)

    stop = time.time()
    record.print(
        "The final graph finished in {} seconds. with properties:".format(
            (stop - start)))
    record.print("{edges: {}, nodes: }".format(graph.size()))
    return (graph)
    record.print("running event-based simulation")

    if full_data:
        simResult = EoN.fast_SIR(graph,
                                 globalInfectionRate,
                                 recoveryRate,
                                 rho=0.0001,
                                 transmission_weight='transmission_weight',
                                 return_full_data=True)
    else:
        simResult = EoN.fast_SIR(graph,
                                 globalInfectionRate,
                                 recoveryRate,
                                 rho=0.0001,
                                 transmission_weight='transmission_weight',
                                 return_full_data=False)
    stop = time.time()
    record.print("finished in {} seconds".format(stop - start))
    return simResult
示例#7
0
def epidemy_without_recover(graph,
                            initial_nodes,
                            transmission_rate,
                            plot_tittle='',
                            return_full_data=False):

    if return_full_data:
        return EoN.fast_SIR(graph,
                            transmission_rate,
                            gamma=0,
                            initial_infecteds=initial_nodes,
                            return_full_data=return_full_data)

    else:
        t, S, I, R = EoN.fast_SIR(graph,
                                  transmission_rate,
                                  gamma=0,
                                  initial_infecteds=initial_nodes)
        max_time_index = 0
        for i in range(0, len(I)):
            if I[i] > 0.9 * graph.number_of_nodes():
                print(
                    f'Infectados:{I[i]} = Limiar:{0.9*graph.number_of_nodes()}'
                )
                max_time_index = i
                break

        t = t * 100

        plt.plot(t, I, label=plot_tittle)
        #plt.plot(t, S, label='Suscetivel', color='b')

        #plt.hlines(I[max_time_index], t[0], t[max_time_index], colors='k')
        #plt.vlines(t[max_time_index], I[0], I[max_time_index], colors='k')

    #plt.xticks([t[max_time_index]])
    #plt.yticks([I[max_time_index]])

    plt.legend(loc='best')
def network_SIR_finalsize_lambda_sensitivity(G, mu, rho, lambda_min,
                                             lambda_max, nruns):
    #average_degree = 2 * G.number_of_edges() / G.number_of_nodes()
    #lc = mu / average_degree

    final_size = defaultdict(list)  # normalized attack rate

    for lambd in np.geomspace(lambda_min, lambda_max, nruns):

        for run in range(0, nruns):
            t, S, I, R = EoN.fast_SIR(G, tau=lambd, gamma=mu, rho=rho)

            final_size[lambd].append(R[-1] / G.number_of_nodes())

    return pd.DataFrame.from_dict(final_size)
def sim_and_plot(G, tau, gamma, rho, tmax, tcount, ax):
    t, S, I, R= EoN.fast_SIR(G, tau, gamma, rho = rho, tmax = tmax)
    report_times = scipy.linspace(0, tmax, tcount)
    I = EoN.subsample(report_times, t, I)
    ax.plot(report_times, I/N, color='grey', linewidth=5, alpha=0.3)
    
    t, S, I, R = EoN.SIR_heterogeneous_meanfield_from_graph(G, tau, gamma, rho=rho, 
                                                    tmax=tmax, tcount=tcount)
    ax.plot(t, I/N, '--')    
    t, S, I, R = EoN.SIR_compact_pairwise_from_graph(G, tau, gamma, rho=rho,
                                                    tmax=tmax, tcount=tcount)
    ax.plot(t, I/N)
 
    t, S, I, R = EoN.SIR_homogeneous_pairwise_from_graph(G, tau, gamma, rho=rho, 
                                                    tmax=tmax, tcount=tcount)
    ax.plot(t, I/N, '-.')
def run_sir(G, dt, sir_params, state):
    """
    Run simulation for time dt
    
    Parameters
    ----------
    sim_params : dict 
        Parameter for the fast_SIR
    state : State 
        state of SIR simulation
        
    Returns
    -------
    sim_data : simulation data
    state : dict
        the state object after running simulation for dt
    """
    sir_params["tmax"] = dt
    sim_data = EoN.fast_SIR(G,
                            return_full_data=True,
                            initial_infecteds=state.infected,
                            initial_recovereds=state.recovered +
                            state.isolated,
                            **sir_params)

    # Update node state
    node_state = sim_data.get_statuses(G.nodes(), dt)
    infected = [k for k, v in node_state.items() if v == "I"]
    recovered = [k for k, v in node_state.items() if v == "R"]
    state.infected = infected
    state.recovered = list(set(recovered) - set(state.isolated))

    # Update the transimission tree
    trans_tree = sim_data.transmission_tree()
    trans_tree_old = state.trans_tree
    if trans_tree_old is None:
        state.trans_tree = trans_tree
    else:
        base_t = state.t
        for eds in trans_tree.edges(data=True):
            tt = eds[2]["time"] + base_t
            trans_tree_old.add_edge(eds[0], eds[1], time=tt)
        state.trans_tree = trans_tree_old

    # Tick time

    return sim_data, state
示例#11
0
t0 = 2
t1 = 4
tmax = 8

gamma = 1
tau0 = 1
tau1 = 0.5

N = 1000000
kave = 4
rho = 0.001

G = nx.fast_gnp_random_graph(N, kave / (N - 1.))

times0, S0, I0, R0, infection_time, recovery_time = EoN.fast_SIR(
    G, tau0, gamma, rho=rho, tmax=t0, return_full_data=True)

infected, recovered = get_affected_nodes_at_end(infection_time, recovery_time)

times1, S1, I1, R1, infection_time, recovery_time = EoN.fast_SIR(
    G,
    tau0,
    gamma,
    initial_infecteds=infected,
    initial_recovereds=recovered,
    tmin=t0,
    tmax=t1,
    return_full_data=True)

infected, recovered = get_affected_nodes_at_end(infection_time, recovery_time)
示例#12
0
iterations = 200
rho = 0.05
tmax = 15
tcount = 1001

report_times = scipy.linspace(0, tmax, tcount)
ax1 = plt.gca()  #axes([0.1,0.1,0.9,0.9])
ax2 = plt.axes([0.44, 0.45, 0.4, 0.4])

for kave, ax in zip((50, 5), (ax1, ax2)):
    tau = 2 * gamma / kave
    Isum = scipy.zeros(tcount)

    for counter in range(iterations):
        G = nx.configuration_model(N * [kave])
        t, S, I, R = EoN.fast_SIR(G, tau, gamma, tmax=tmax, rho=rho)
        I = I * 1. / N
        I = EoN.subsample(report_times, t, I)
        Isum += I
    ax.plot(report_times,
            Isum / iterations,
            color='grey',
            linewidth=5,
            alpha=0.3)

    S0 = (1 - rho) * N
    I0 = rho * N
    R0 = 0

    t, S, I, R = EoN.SIR_homogeneous_meanfield(S0,
                                               I0,
示例#13
0
            for edge in G.edges():
                G.edges[edge[0], edge[1]]['weight'] = G.nodes[
                    edge[0]]['safety'] * G.nodes[edge[1]]['safety']
                weight_sum += G.nodes[edge[0]]['safety'] * G.nodes[
                    edge[1]]['safety']

            tmax = 20
            iterations = 1  #run 5 simulations
            tau = 0.1  #transmission rate
            gamma = 1.0  #recovery rate
            rho = 0.01  #random fraction initially infected

            sim = EoN.fast_SIR(G,
                               G.number_of_edges() / weight_sum,
                               gamma,
                               rho=rho,
                               transmission_weight='weight',
                               tmax=tmax,
                               return_full_data=True)
            # ani = sim.animate(ts_plots=['I', 'SIR'])
            # filename = "smallworld_animation_for_comparison.mp4"
            # ani.save(filename, extra_args=['-vcodec', 'libx264'])
            # plt.figure()
            # plt.suptitle('Safety Skew ' + str(avg_safety))

            plt.subplot(len(safety_generator_list) + 1, 2, 3 + 2 * s)
            plt.title('Total Infections; Safety = ' + str(avg_safety))
            plt.xlabel('$t$')
            # plt.ylabel('Number infected')
            plt.plot(sim.t(),
                     sim.I(),
示例#14
0
def simulation(G, tau, gamma, rho, max_time, number_infected_before_release, release_number, background_inmate_turnover,
               stop_inflow_at_intervention, p, death_rate, percent_infected, percent_recovered, social_distance,
               social_distance_tau, initial_infected_list):
    """Runs a simulation on SIR model.

    Args:
        G: Networkx graph
        tau: transmission rate
        gamma: recovery rate
        rho: percent of inmates that are initially infected
        max_time: # of time steps to run simulation
        number_infected_before_release: number of infected at which to perform release on next integer time
        release_number: # of inmates to release at release intervention
        background_inmate_turnover: background # of inmates added/released at each time step
        stop_inflow_at_intervention: should we stop the background inflow of inmates at intervention time?
        p: probability of contact between inmate and other inmates
        death_rate: percent of recovered inmates that die
        percent_infected: percent of general population that is infected
        percent_recovered: percent of general population that is recovered
        social_distance: boolean flag, if we lower transmission rate after major release
        social_distance_tau: new transmission rate after major release
        initial_infected_list: sets node numbers of initial infected (default is 0, this parameter is arbitrary)

    Returns:
        t: array of times at which events occur
        S: # of susceptible inmates at each time
        I: # of infected inmates at each time
        R: # of recovered inmates at each time
        D: # of dead inmates at each time step
    """
    print('Starting simulation...')
    release_occurred = False
    background_release_number = background_inmate_turnover
    data_list = []
    recovered_list = []
    delta_recovered_list = []

    # Check we are using initial_infected_list
    if initial_infected_list is not None:
        print('Using initial infected list to set initial infected.')
        infected_list = initial_infected_list.copy()
    else:  # Choose random initial infections based on rho
        print('Using rho to set initial infected.')
        infected_list = list(np.random.choice(list(G.nodes), int(np.ceil(rho * len(G.nodes))), replace=False))

    # Loop over time
    for i in range(max_time):
        # Run 1 time unit of simulation
        data = EoN.fast_SIR(G, tau, gamma, initial_infecteds=infected_list, initial_recovereds=recovered_list,
                            tmin=i, tmax=i + 1, return_full_data=True)
        data_list.append(data)

        # Update infected and recovered inmate lists
        infected_list, recovered_list = get_infected(data, i + 1), get_recovered(data, i + 1)

        # Check if release condition has been met
        if not release_occurred and len(infected_list) >= number_infected_before_release:
            background_inmate_turnover, r_n, tau = enact_interventions(background_inmate_turnover,
                                                                       background_release_number, i + 1,
                                                                       infected_list, release_number,
                                                                       social_distance,
                                                                       social_distance_tau,
                                                                       stop_inflow_at_intervention,
                                                                       tau)
            release_occurred = True
        else:  # If not, use background release rate
            r_n = background_release_number

        # Add and release inmates
        G, infected_list, recovered_list, delta_recovered = recalibrate_graph(G, infected_list, recovered_list,
                                                                              background_inmate_turnover, r_n, p,
                                                                              percent_infected, percent_recovered,
                                                                              death_rate)

        # Track the number of recovered inmates added or released at each time step
        delta_recovered_list.append(delta_recovered)

    # Process raw data into t, S, I, R, D arrays
    t, S, I, R, D = process_data(data_list, delta_recovered_list, death_rate)

    print('Simulation completed.\n')
    return t, S, I, R, D
示例#15
0
文件: eon.py 项目: cesarr/SIRsims
tau = 0.3  # transmission rate
gamma = 1.0  # recovery rate
#tau = 3   # transmission rate
#gamma = 1.0 # recovery rate
print("tau= %f, gamma= %f" % (tau, gamma))

kave = 120  # expected number of partners
print("generating graph G with {} nodes".format(N))
G = nx.fast_gnp_random_graph(N, kave / (N - 1))  #Erdo’’s-Re’nyi graph
nb_edges = len(G.edges)
print("Initial number of infected: %f, fraction infected: %f" % (rho * N, rho))
print("graph has {} edges".format(nb_edges))

print("doing event-based simulation")
t = time.time()
t1, S1, I1, R1 = EoN.fast_SIR(G, tau, gamma, rho=rho)
elapsed_time = time.time() - t
print("Total time to compute: ", elapsed_time, " sec")

#print("doing Gillespie simulation")
#t2, S2, I2, R2 = EoN.Gillespie_SIR(G, tau, gamma, rho=rho)

print("done with simulations, now plotting")
plt.plot(t1, I1, label="fast_SIR")
#plt.plot(t2, I2, label = "Gillespie_SIR")
plt.plot(t1, R1)
#plt.plot(t2, R2)
plt.plot(t1, S1)
#plt.plot(t2, S2)
plt.xlabel("$t$")
plt.xlabel("Number infected")
import networkx as nx
import EoN
import matplotlib.pyplot as plt
G = nx.grid_2d_graph(100, 100)  #each node is (u,v) where 0<=u,v<=99
#we'll initially infect those near the middle
initial_infections = [(u, v) for (u, v) in G if 45 < u < 55 and 45 < v < 55]
pos = {node: node for node in G}
sim_kwargs = {'pos': pos}
sim = EoN.fast_SIR(G,
                   2.0,
                   1.0,
                   initial_infecteds=initial_infections,
                   tmax=40,
                   return_full_data=True,
                   sim_kwargs=sim_kwargs)

ani = sim.animate(ts_plots=['I', 'SIR'], node_size=4)
ani.save('SIR_2dgrid.mp4', fps=5, extra_args=['-vcodec', 'libx264'])
示例#17
0
                a * maximum
            )  # NOTE: Shouldn't this use len(L) instead of maximum????

            for x in range(a):
                edge = random.choice(L)
                G.add_edge(edge[0], edge[1])
                edges3.append(edge)
                L.remove(edge)

            tmax = 40
            print('finished')

            SIR = EoN.fast_SIR(G,
                               tau,
                               gamma,
                               initial_infecteds=random.sample(
                                   list(range(maximum)),
                                   math.floor(rho * maximum)),
                               tmax=tmax,
                               return_full_data=True)
            SIR.display(time=5)
            plt.show()

            for c in edges3:
                G.remove_edge(c[0], c[1])

            t, d = SIR.summary()
            max_infected = max(d['I'])
            total_infected = max(d['R'])
            time_to_peak = t[np.where(d['I'] == max(d['I']))]
            print('max infected= ', max_infected)
            print('total infected= ', total_infected)
示例#18
0
#function to create homogeneous group
def groupCitizens(graph, citizens, weight):
    groupSize = len(citizens)
    for i in range(groupSize):
        for j in range(i):
            graph.add_edge(citizens[j],citizens[i],transmission_weight = weight)


#link population in the same households
citizenHouses = list(zip(citizens,houseNumbers))
for i in range(houseHolds):
    house = list(zip(*list(filter(lambda x: (x[1]==i),citizenHouses))))[0]
    groupCitizens(graph, house, houseInfectivity)

#link population in the same work environmen
assignmentGroups = list(zip(citizens, assignments))
for i in range(environmentCount):
    environmentGroup = list(zip(*list(filter(lambda x:(x[1]==i),assignmentGroups))))[0]
    groupCitizens(graph, environmentGroup, workInfectivity)

nx.draw(graph)
plt.show()
for i in range(epidemicSims):
    t,S,I,R = EoN.fast_SIR(graph, globalInfectionRate, recoveryRate, rho = 0.01, transmission_weight ='transmission_weight')
    plt.plot(t,R)
    plt.plot(t,I)
    plt.plot(t,S)
plt.xlabel("time")
plt.ylabel("citizens")
plt.show()
示例#19
0
    #creats node for each student in the school#
    for x in range(students):
        G.add_node(x)
    time=0

    infected=[]
    recovered=[]

    #this is where the 'school day' starts#
    for period in range(periods*days):


        if (period/periods==int(period/periods)) and (counter!=0):
            
            SIR=EoN.fast_SIR(G, 0, gamma, tmin=tmin, tmax = 16, initial_infecteds=infected, initial_recovereds=recovered, return_full_data=True)
            t,d=SIR.summary()
        
        
            time += 16
            node_stats=list(SIR.get_statuses(nodelist=None, time=32).values())

            #creates list of infecteds and recoverds after each iteration to feed into the next#
            final_infected=[]
            for i in range(len(node_stats)):
                if node_stats[i]=='I':
                    infected.append(i)
                    final_infected.append(i)
                elif node_stats[i]=='R':
                    recovered.append(i)
        
示例#20
0
    groupCitizens(graph, house, houseInfectivity)

#link population in the same work environmen
assignmentGroups = list(zip(citizens, assignments))
for i in range(environmentCount):
    environmentGroup = list(
        zip(*list(filter(lambda x: (x[1] == i), assignmentGroups))))[0]
    groupCitizens(graph, environmentGroup, workInfectivity)

end = time.time()
printAndRecord(end - start)
start = time.time()
#for i in range(epidemicSims):
node_investigation = EoN.fast_SIR(graph,
                                  globalInfectionRate,
                                  recoveryRate,
                                  rho=0.01,
                                  transmission_weight='transmission_weight',
                                  return_full_data=True)
plt.plot(node_investigation.summary(students)[1]['I'],
         label="infected students")
plt.plot(node_investigation.summary(working)[1]['I'], label="infected workers")
plt.plot(node_investigation.summary(unemployed)[1]['I'],
         label="infected unemployed")
plt.legend()
plt.show()
#plt.plot(t,R)
#plt.plot(t,I)
#plt.plot(t,S)
#plt.show()
end = time.time()
printAndRecord(end - start)
示例#21
0
            L = [edge for edge in L if edge not in edges]

            edge_list = random.sample(L, math.floor(a * total_pop))
            G.add_edges_from(edge_list)

            edge_list = random.sample(L, math.floor(a * total_pop))
            G.add_edges_from(edge_list)

            started = False

            for i in range(iterations):
                #Running the simulation
                sim = e.fast_SIR(G,
                                 tau,
                                 gamma,
                                 initial_infecteds=infecteds,
                                 initial_recovereds=recovereds,
                                 tmax=time_reading,
                                 return_full_data=True)

                statuses = list(sim.get_statuses(time=time_reading).values())
                #sim.display(time=time_reading)
                #plt.show()
                infecteds = []
                recovereds = []
                #Storing infected and recovered node info for next graph
                for j in range(len(statuses)):
                    if statuses[j] == 'I':
                        infecteds.append(j)
                    if statuses[j] == 'R':
                        recovereds.append(j)
示例#22
0
import EoN
import networkx as nx
import matplotlib.pyplot as plt

from collections import defaultdict

N = 1000
gamma = 1
tau = 1.5 / N
G = nx.complete_graph(N)
iterations = 10000
binwidth = 10

H = defaultdict(int)
for counter in range(iterations):
    t, S, I, R = EoN.fast_SIR(G, tau, gamma)
    H[binwidth * (R[-1] / binwidth)] = H[binwidth *
                                         (R[-1] / binwidth)] + 1. / iterations

fig = plt.figure(1)
main = plt.axes()

main.bar(*zip(*H.items()), width=binwidth, linewidth=0)
main.axis(xmax=1000, ymax=0.7)
plt.xlabel('Final Epidemic Size')
plt.ylabel('Frequency')

inset = plt.axes([0.3, 0.3, 0.5, 0.5])
inset.bar(*zip(*H.items()), width=binwidth, linewidth=0)
inset.axis(xmin=300, xmax=900, ymin=0, ymax=0.03)
示例#23
0
                            groups[day].append(list(new_class))
                            group_students = list(
                                set(group_students).difference(set(new_class))
                            )  # Removes nodes, as they are added to classes to prevent node being present in multiple classes.
                            # Creates complete graph for each class
                            for student_1 in groups[day][class_x]:
                                for student_2 in groups[day][class_x]:
                                    G.add_edge(student_1, student_2)

                        # Running the simulation
                        if started == False:
                            started = True
                            sim = e.fast_SIR(G,
                                             tau,
                                             gamma,
                                             rho=rho,
                                             initial_recovereds=recovered,
                                             return_full_data=True,
                                             tmax=time_reading)

                        else:
                            sim = e.fast_SIR(G,
                                             tau,
                                             gamma,
                                             initial_infecteds=infected,
                                             initial_recovereds=recovered,
                                             return_full_data=True,
                                             tmax=time_reading)

                        # Runs simulation
                        # Retrieves node statuses as given time of 'time_reading'
import random

N = 10**6
tau = 1.
gamma = 1.
colors = [
    '#5AB3E6', '#FF2000', '#009A80', '#E69A00', '#CD9AB3', '#0073B3', '#F0E442'
]
kave = 5

G = nx.fast_gnp_random_graph(N, kave / (N - 1.))

initial_infecteds = random.sample(range(N), int(0.01 * N))

print('simulating')
t, S, I, R = EoN.fast_SIR(G, tau, gamma, initial_infecteds=initial_infecteds)
report_times = scipy.linspace(0, 10, 101)

S, I, R = EoN.subsample(report_times, t, S, I, R)

plt.plot(report_times, S, color=colors[1], label='simulation')
plt.plot(report_times, I, color=colors[1])
plt.plot(report_times, R, color=colors[1])

print('doing ODE models')
t, S, I, R = EoN.SIR_effective_degree_from_graph(
    G, tau, gamma, initial_infecteds=initial_infecteds, tmax=10, tcount=51)
plt.plot(t, S, color=colors[2], dashes=[6, 6], label='effective degree')
plt.plot(t, I, color=colors[2], dashes=[6, 6])
plt.plot(t, R, color=colors[2], dashes=[6, 6])
G = nx.grid_2d_graph(population,population) #each node is (u,v) where 0<=u,v<=99
#we'll initially infect those near the middle
initial_infections = [(u,v) for (u,v) in G if 545<u<555 and 545<v<555]  #Cluster of population usually at middle

##-----------------------------------Without Vaccine---------------------------------------------------
#Transmission and Death rate is from here https://www.worldometers.info/coronavirus/
trans_rate = 4.0
recovery_rate = 0.3
total_simulation_days = 15 #30days without vaccine and 30 days with vaccine = 60days sim
death_rate = 0.02
print("Duration: ",total_simulation_days)
print("Module SIR: TransRate: ", trans_rate,", DeathRate: ", death_rate, "%, RecoveryRate: ", recovery_rate, "%")

pos = {node:node for node in G}
sim_kwargs = {'pos': pos}
sim = EoN.fast_SIR(G, trans_rate, recovery_rate, initial_infecteds = initial_infections,
               tmax = total_simulation_days, return_full_data=True, sim_kwargs = sim_kwargs)

count = 1
total_death = 0
total_infected_case = 0
previous_infected_case = 0
new_infected_case = 0

while(count < total_simulation_days):
	t, S, I, R= EoN.fast_SIR(G, trans_rate, recovery_rate, initial_infecteds = initial_infections,
	               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
示例#26
0
N = 10**5
G = nx.barabasi_albert_graph(N, 5)  #create a barabasi-albert graph

# In[5]:

tmax = 20
iterations = 5  #run 5 simulations
tau = 0.1  #transmission rate
gamma = 1.0  #recovery rate
rho = 0.005  #random fraction initially infected

# In[6]:

# Simulations and Models
for counter in range(iterations):  #run simulations
    t, S, I, R = EoN.fast_SIR(G, tau, gamma, rho=rho, tmax=tmax)
    if counter == 0:
        plt.plot(t, I, color='k', alpha=0.3, label='Simulation')
    plt.plot(t, I, color='k', alpha=0.3)
# plot the Pref mix EBCM
t, S, I, R = EoN.EBCM_pref_mix_from_graph(G, tau, gamma, rho=rho, tmax=tmax)
plt.plot(t, I, label='Pref mix EBCM', linewidth=5, dashes=[4, 2, 1, 2, 1, 2])
plt.xlabel('$t$')
plt.ylabel('Number infected')
plt.legend()

# Now compare with ODE predictions.
#
# - Read in the degree distribution of G
# - use rho to initialize the various model equations.
# - There are versions of these functions that allow you to specify the initial conditions rather than starting from a graph.