def SIS_process(G, degree_prob, tmax, tau, gamma): N = G.order() plt.figure(5) plt.clf() plt.figure(6) plt.clf() for index, starting_node in enumerate([x * N / 10. for x in range(10)]): plt.figure(5) t, S, I = EoN.fast_SIS(G, tau, gamma, initial_infecteds=[starting_node], tmax=tmax) #print(I[-1]) subt = scipy.linspace(0, tmax, 501) subI = EoN.subsample(subt, t, I) plt.plot(subt, subI) if I[-1] > 100: plt.figure(6) shift = EoN.get_time_shift(t, I, 1000) plt.plot(subt - shift, subI) plt.figure(5) plt.savefig('sw_SIS_epi_N{}_p{}_k{}_tau{}.pdf'.format(N, p, k, tau)) plt.figure(6) plt.savefig('sw_SIS_epi_N{}_p{}_k{}_tau{}_shifted.pdf'.format( N, p, k, tau))
def run_sis(original, attacked, budget, num_sim=numSim): """run SIS simulations on both graphs.""" graphs = {'original': original, 'attacked': attacked} rows = [] for name in graphs: G = graphs[name] numNode = G.order() print('Simulating SIS on {}'.format(name)) for ns in range(num_sim): if ns % 50 == 0: print("numSim: {}".format(ns)) #print("numSim: {}".format(ns)) S = [i for i in range(numNode) if G.nodes[i]['target']] SP = list(set(range(numNode)) - set(S)) if args.graph_type not in ['Airport', 'Protein', 'Brain']: sim = EoN.fast_SIS(graphs[name], TAU, GAMMA, tmax=TMAX, return_full_data=True) else: sim = EoN.fast_SIS(graphs[name], TAU, GAMMA, tmax=TMAX, transmission_weight='weight', return_full_data=True) ## average results over the last 10 steps inf_ratio_target = np.mean([ Counter(sim.get_statuses(S, i).values())['I'] / len(S) for i in range(-1, -11, -1) ]) #INF = [Counter(sim.get_statuses(S, i).values())['I'] / len(S) for i in range(TMAX)] #with open('tmp.p', 'wb') as fid: # pickle.dump(INF, fid) inf_ratio_bystander = np.mean([ Counter(sim.get_statuses(SP, i).values())['I'] / len(SP) for i in range(-1, -11, -1) ]) rows.append((name, inf_ratio_target, inf_ratio_bystander, budget)) return pd.DataFrame( rows, columns=['graph', 'ratio targets', 'ratio bystanders', 'budget'])
def simulate_process(graph_function, iterations, tmax, tcount, rho, kave, tau, gamma, symbol): Isum = scipy.zeros(tcount) report_times = scipy.linspace(0, tmax, tcount) for counter in range(iterations): G = graph_function() t, S, I = EoN.fast_SIS(G, tau, gamma, rho=rho, tmax=tmax) I = EoN.subsample(report_times, t, I) Isum += I plt.plot(report_times, Isum * 1. / (N * iterations), symbol)
def sim_and_plot(G, tau, gamma, rho, tmax, tcount, ax): t, S, I = EoN.fast_SIS(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, = EoN.SIS_heterogeneous_meanfield_from_graph(G, tau, gamma, rho=rho, tmax=tmax, tcount=tcount) ax.plot(t, I/N, '--') t, S, I = EoN.SIS_compact_pairwise_from_graph(G, tau, gamma, rho=rho, tmax=tmax, tcount=tcount) ax.plot(t, I/N) t, S, I = EoN.SIS_homogeneous_pairwise_from_graph(G, tau, gamma, rho=rho, tmax=tmax, tcount=tcount) ax.plot(t, I/N, '-.')
def times_infected(G, N): tmax = 1 tau = 0.9 # transmission rate gamma = 0.5 # recovery rate rho = 0.1 # random fraction of initially infected infected_hist = {} for i in range(len(G)): infected_hist[i] = 0 for iteration in range(N): print("Iteration - " + str(iteration) + ".....") sim = EoN.fast_SIS(G, tau, gamma, rho=rho, return_full_data=True) results = sim.get_statuses() for node in results: if results[node] == 'I': infected_hist[node] = infected_hist[node] + 1 return infected_hist
weight_sum = 0 inv_weight_sum = 0 for edge in G.edges(): G.edges[edge[0], edge[1]]['weight'] = G.degree(edge[0]) * G.degree(edge[1]) G.edges[edge[0], edge[1]]['inv_weight'] = 1. / (G.degree(edge[0]) * G.degree(edge[1])) #If networkx is older, use G.edge[edge[0]][edge[1]][... weight_sum += G.degree(edge[0]) * G.degree(edge[1]) inv_weight_sum += 1. / (G.degree(edge[0]) * G.degree(edge[1])) #first do it with weight, scaled so that average weight is 1. t, S, I = EoN.fast_SIS(G, G.number_of_edges() / weight_sum, gamma, rho=rho, transmission_weight='weight', tmax=10) plt.plot(t, I, label='weight') t, S, I = EoN.fast_SIS(G, G.number_of_edges() / inv_weight_sum, gamma, rho=rho, transmission_weight='inv_weight', tmax=10) plt.plot(t, I, label='inv_weight') plt.legend(loc='lower right') plt.savefig('SIS_weighted.png')
tcount = 1001 report_times = scipy.linspace(tmin, tmax, 21) #for simulations plt.figure(0) tau = 0.005 G = nx.complete_graph(N) t, S, I = complete_graph_lumped(N, tau, gamma, I0, tmin, tmax, tcount) plt.plot(t, I/N, label = 'Prediction') #now check with simulation obs_I = 0*report_times print("done with complete graph ODE. Now simulating") for counter in range(iterations): IC = random.sample(range(N),I0) t, S, I = EoN.fast_SIS(G, tau, gamma, initial_infecteds = IC, tmax = tmax) obs_I += EoN.subsample(report_times, t, I) plt.plot(report_times, obs_I*1./(iterations*N), 'o', label='Simulation') plt.axis(ymin=0, ymax=1) plt.xlabel('$t$') plt.ylabel('$[I]$') plt.legend() plt.savefig('fig2p11a.png') print("done with complete graph. Now star --- warning, this may be slow")
# # ## SIS # In[8]: #Now run for SIS. # Simulation is much slower so need smaller network N = 10**4 G = nx.barabasi_albert_graph(N, 5) #create a barabasi-albert graph # In[9]: # simulations for counter in range(iterations): t, S, I = EoN.fast_SIS(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='r', alpha=0.3) # Now compare with ODE predictions. # - Read in the degree distribution of G # - and 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. # # In[10]: #we expect a homogeneous model to perform poorly because the degree #distribution is very heterogeneous
kave = 20 gamma = 1. iterations = 200 tmax = 40 tau_c = gamma/kave rho = 0.05 tcount=1001 report_times = scipy.linspace(0,tmax,tcount) for tau, label in zip([0.9*tau_c, tau_c, 1.1*tau_c, 1.5*tau_c],['a', 'b', 'c', 'd']): plt.clf() Isum = scipy.zeros(len(report_times)) for counter in range(iterations): G = nx.configuration_model([kave]*N) t, S, I = EoN.fast_SIS(G, tau, gamma, tmax=tmax, rho=rho) I=I*1./N I = EoN.subsample(report_times, t, I) Isum += I plt.plot(report_times, Isum/iterations, color = 'grey', linewidth = 5, alpha=0.3) S0 = (1-rho)*N I0 = rho*N t, S, I = EoN.SIS_homogeneous_meanfield(S0, I0, kave, tau, gamma, tmin=0, tmax=tmax, tcount=tcount) plt.plot(t, I/N, '--') S0 = (1-rho)*N I0 = rho*N SI0 = (1-rho)*N*kave*rho
t0 = 2 t1 = 4 tmax = 8 gamma = 1 tau0 = 1 tau1 = 0.5 N = 100000 kave = 4 rho = 0.01 G = nx.fast_gnp_random_graph(N, kave / (N - 1.)) #times0, S0, I0, infection_time, recovery_time = EoN.fast_SIS(G, tau0, gamma, rho = rho, tmax = t0, return_full_data=True) sim = EoN.fast_SIS(G, tau0, gamma, rho=rho, tmax=t0, return_full_data=True) #the infected nodes are those that either were infected and never recovered #(which won't be in recovery_time) #or have been infected multiple times and their last infection was after #their last recovery infected = set(node for node in infection_time if node not in recovery_time or infection_time[node][-1] > recovery_time[node][-1]) times1, S1, I1, infection_time, recovery_time = EoN.fast_SIS( G, tau0, gamma, initial_infecteds=infected, tmin=t0, tmax=t1,
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] sim = EoN.fast_SIS(G, 1.0, 1.0, initial_infecteds=initial_infections, return_full_data=True, tmax=40) pos = {node: node for node in G} sim.set_pos(pos) sim.display(6, node_size=4) #display time 6 plt.savefig('SIS_2dgrid.png') plt.clf() sim.display(6, node_size=4, ts_plots=[]) #display time 6 plt.savefig('SIS_2dgrid_no_time_series.png')