def get_epidemic_si(graph, beta, perc_inf, infected_nodes): model_si = si.SIModel(graph) cfg_si = mc.Configuration() cfg_si.add_model_parameter("beta", beta) cfg_si.add_model_parameter("percentage_infected", perc_inf) cfg_si.add_model_parameter("Infected", infected_nodes) model_si.set_initial_status(cfg_si) iteration_si = model_si.iteration_bunch(50) trends_si = model_si.build_trends(iteration_si) viz_si = DiffusionTrend(model_si, trends_si) viz_si.plot()
def get_epidemic_sir(graph, beta, gamma, perc_inf, infected_nodes): model_sir = sir.SIRModel(graph) cfg_sir = mc.Configuration() cfg_sir.add_model_parameter("beta", beta) # infection cfg_sir.add_model_parameter("gamma", gamma) # recovery cfg_sir.add_model_parameter("percentage_infected", perc_inf) cfg_sir.add_model_parameter("Infected", infected_nodes) model_sir.set_initial_status(cfg_sir) iterations_sir = model_sir.iteration_bunch(100, node_status=True) trends_sir = model_sir.build_trends(iterations_sir) viz_sir = DiffusionTrend(model_sir, trends_sir) viz_sir.plot()
def get_epidemic_sis(graph, beta, lamb, perc_inf, infected_nodes): model_sis = sis.SISModel(graph) cfg_sis = mc.Configuration() cfg_sis.add_model_parameter("beta", beta) cfg_sis.add_model_parameter("lambda", lamb) cfg_sis.add_model_parameter("percentage_infected", perc_inf) cfg_sis.add_model_parameter("Infected", infected_nodes) model_sis.set_initial_status(cfg_sis) iteration_sis = model_sis.iteration_bunch(100) trends_sis = model_sis.build_trends(iteration_sis) viz_sis = DiffusionTrend(model_sis, trends_sis) viz_sis.plot()
def test_visualize(self): g = nx.erdos_renyi_graph(1000, 0.1) model = epd.SIRModel(g) config = mc.Configuration() config.add_model_parameter('beta', 0.001) config.add_model_parameter('gamma', 0.01) config.add_model_parameter("percentage_infected", 0.05) model.set_initial_status(config) iterations = model.iteration_bunch(200) trends = model.build_trends(iterations) # Visualization viz = DiffusionTrend(model, trends) viz.plot("diffusion.pdf") os.remove("diffusion.pdf")
def get_epidemic_threshold(graph, perc_inf, threshold, infected_nodes): model_threshold = thresh.ThresholdModel(graph) cfg_threshold = mc.Configuration() cfg_threshold.add_model_parameter("percentage_infected", perc_inf) cfg_threshold.add_model_parameter("Infected", infected_nodes) for node in graph.nodes(): cfg_threshold.add_node_configuration("threshold", node, threshold) model_threshold.set_initial_status(cfg_threshold) iteration_threshold = model_threshold.iteration_bunch(25) trends_threshold = model_threshold.build_trends(iteration_threshold) viz_threshold = DiffusionTrend(model_threshold, trends_threshold) viz_threshold.plot()
def test_visualize(self): g = nx.erdos_renyi_graph(1000, 0.1) model = sir.SIRModel(g) config = mc.Configuration() config.add_model_parameter('beta', 0.001) config.add_model_parameter('gamma', 0.01) config.add_model_parameter("percentage_infected", 0.05) model.set_initial_status(config) iterations = model.iteration_bunch(200) trends = model.build_trends(iterations) # Visualization viz = DiffusionTrend(model, trends) viz.plot("diffusion.pdf") os.remove("diffusion.pdf")
def diffusion_trend(ind): iterations, iterations_mitigations = evaluate.evaluate_individual( toolbox.compile(ind), m=model, traveler_set=travelers, mvc_set=minimal_vertex_cover, vert_avg_dist=vertex_average_distance, number_vertex_shortest=number_shortest_paths, Page_Rank=page_rank, Cluster_Coeff=cluster_coef, avg_degree=average_degree, short_dist=shortest_distances, avg_dist=average_distance, total_iterations=ITERATIONS, measure_every=MEASURE_EVERY, mitigations_per_measure=MITIGATIONS_PER_MEASURE, rollover=ROLLOVER, use_all=USE_ALL) trends = model.build_trends(iterations) # Visualization viz = DiffusionTrend(model, trends) viz.plot() viz = DiffusionPrevalence(model, trends) viz.plot() return iterations, trends
def visualize(model, trends, sub_dir): viz_img_name = model.get_name() for param, value in model.params['model'].items(): viz_img_name = f'{viz_img_name};{param}({str(value).replace(".", ",")})' if not os.path.exists('./viz/'): os.mkdir('./viz/') if not os.path.exists(f'./viz/{sub_dir}'): os.mkdir(f'./viz/{sub_dir}') DiffusionTrend(model, trends).plot(filename=f'./viz/{sub_dir}/{viz_img_name}.png')
def sis_model(net, graph_name): print '\nSIS MODEL SIMULATION - ' + graph_name + ' network' for_comparison = dict() degrees = [d for n, d in net.degree] mean_k = sum(degrees)/len(degrees) for state in ['ENDEMIC', 'FREE']: print 'MODEL CONFIGURATION - ' + state + ' STATE' if state == 'ENDEMIC': beta = float(raw_input('INFECTION PROBABILITY: ')) print 'MU HAS TO BE LESS THAN ' + str(beta*(mean_k+1)) mu = float(raw_input('RECOVERY PROBABILITY: ')) while mu >= (beta*(mean_k+1)): print 'ERROR! MU HAS TO BE LESS THAN ' + str(beta*(mean_k+1)) mu = float(raw_input('RECOVERY PROBABILITY: ')) else: print 'MU HAS TO BE GREATER THAN ' + str(beta*(mean_k+1)) mu = float(raw_input('RECOVERY PROBABILITY: ')) while mu <= beta*(mean_k+1): print 'ERROR! MU IS NOT GREATER THAN ' + str(beta*(mean_k+1)) mu = float(raw_input('RECOVERY PROBABILITY: ')) cfg = mc.Configuration() cfg.add_model_parameter('beta', beta) cfg.add_model_parameter('lambda', mu) cfg.add_model_parameter('percentage_infected', float(raw_input('PERCENTAGE INFECTED: '))) model_sis = sis.SISModel(net) model_sis.set_initial_status(cfg) model_sis.name = str(graph_name)+"-"+state.lower() print model_sis.name iterations = model_sis.iteration_bunch(200) trends_sis = model_sis.build_trends(iterations) viz = DiffusionTrend(model_sis, trends_sis) viz.plot('../../report/images/spreading/sis/diffusion_' + graph_name + '_' + state.lower() + '.pdf') for_comparison[state.lower() + '_state'] = [model_sis, trends_sis] viz = DiffusionTrendComparison([for_comparison['endemic_state'][0], for_comparison['free_state'][0]], [for_comparison['endemic_state'][1], for_comparison['free_state'][1]]) viz.plot('../../report/images/spreading/sis/diffusion_' + graph_name + '_comparison.pdf')
def simulate_spread(G, steps, threshold, infected_probability, simulation_beta, simulation_gamma, simulation_alpha, output): infected_nodes = [] exposed_nodes = [ node[0] for node in G.nodes(data=True) if node[1]['flaws'] > threshold ] # Take 1 at random and the rest with probability idx = np.random.choice(list(range(len(exposed_nodes))), size=1, replace=False)[0] infected_nodes.append(exposed_nodes.pop(idx)) infected_nodes_count = int(len(exposed_nodes) * infected_probability) if infected_nodes_count != 0: infected_idxs = np.random.choice(list(range(len(exposed_nodes))), infected_nodes_count) infected_nodes.extend(list(np.take(exposed_nodes, infected_idxs))) exposed_nodes = list(np.delete(exposed_nodes, infected_idxs)) susceptible_nodes = [ node for node_idx, node in enumerate(G.nodes()) if node_idx not in [*exposed_nodes, *infected_nodes] ] # Create model model = ep.SEIRModel(G) # Create configuration cfg = mc.Configuration() # Infection probability. cfg.add_model_parameter('beta', simulation_beta) # Infected -> Remove probability cfg.add_model_parameter('gamma', simulation_gamma) # Latent period cfg.add_model_parameter('alpha', simulation_alpha) # Set both infected and exposed nodes. # cfg.add_model_parameter('fraction_infected', 0.01) cfg.add_model_initial_configuration("Susceptible", susceptible_nodes) cfg.add_model_initial_configuration("Exposed", exposed_nodes) cfg.add_model_initial_configuration("Infected", infected_nodes) # Set the configuration model.set_initial_status(cfg) # Run multiple models trends = multi_runs(model, execution_number=10, iteration_number=steps, infection_sets=None, nprocesses=5) dt = DiffusionTrend(model, trends) dt.plot(filename=os.path.join(output, 'diffusion_trend.png')) dp = DiffusionPrevalence(model, trends) dp.plot(filename=os.path.join(output, 'diffusion_prevalence.png')) # Other run to show infected_nodes = list() for _ in range(10): model.reset() iterations = model.iteration_bunch(steps) for iteration in iterations: for k, v in iteration['status'].items(): if v == 3: infected_nodes.append(k) return Counter(infected_nodes)
def plot_trend(model, iterations): trends = model.build_trends(iterations) viz = DiffusionTrend(model, trends) p = viz.plot() plt.show()
def si_model(g, er_g, ba_g): print '\nSI MODEL SIMULATION' print 'MODEL CONFIGURATION' cfg = mc.Configuration() beta = float(raw_input('INFECTION RATE: ')) cfg.add_model_parameter('beta', beta ) cfg.add_model_parameter('percentage_infected', float(raw_input('PERCENTAGE INFECTED: '))) for_comparison = dict() for network in [g, er_g, ba_g]: model_si = si.SIModel(network) model_si.set_initial_status(cfg) iterations = model_si.iteration_bunch(200) trends_si = model_si.build_trends(iterations) if network is g: print 'Original graph' model_si.name = 'G' viz = DiffusionTrend(model_si, trends_si) viz.plot('../../report/images/spreading/si/diffusion.pdf') viz = DiffusionPrevalence(model_si, trends_si) viz.plot('../../report/images/spreading/si/prevalence.pdf') for_comparison['original_si'] = [model_si, trends_si] elif network is er_g: print 'ER graph' model_si.name = 'ER' viz = DiffusionTrend(model_si, trends_si) viz.plot('../../report/images/spreading/si/diffusion_er.pdf') viz = DiffusionPrevalence(model_si, trends_si) viz.plot('../../report/images/spreading/si/prevalence_er.pdf') for_comparison['er_si'] = [model_si, trends_si] else: print 'BA graph' model_si.name = 'BA' viz = DiffusionTrend(model_si, trends_si) viz.plot('../../report/images/spreading/si/diffusion_ba.pdf') viz = DiffusionPrevalence(model_si, trends_si) viz.plot('../../report/images/spreading/si/prevalence_ba.pdf') for_comparison['ba_si'] = [model_si, trends_si] viz = DiffusionTrendComparison([ for_comparison['original_si'][0], for_comparison['er_si'][0], for_comparison['ba_si'][0] ], [ for_comparison['original_si'][1], for_comparison['er_si'][1], for_comparison['ba_si'][1] ]) viz.plot("../../report/images/spreading/si/trend_comparison_beta{}.pdf".format(beta))
flight_data_col = ['Source', 'Destination'] flight_data_df = pd.read_csv('flight_data.csv', names=flight_data_col, skiprows=[0]) flight_data_df['Source'] = flight_data_df['Source'].astype("string") flight_data_df['Destination'] = flight_data_df['Destination'].astype("string") original_data = nx.from_pandas_edgelist(flight_data_df, source='Source', target='Destination', create_using=nx.DiGraph()) model = ep.ThresholdModel(original_data) config = mc.Configuration() config.add_model_parameter('fraction_infected', 0.10) threshold = 0.25 for i in original_data.nodes(): config.add_node_configuration("threshold", i, threshold) model.set_initial_status(config) iterations = model.iteration_bunch(200) trends = model.build_trends(iterations) viz = DiffusionTrend(model, trends) viz.plot("cascade_results_1.png")
config.add_model_parameter("gamma_t", 0.08) config.add_model_parameter("gamma_f", 0.04) config.add_model_parameter("omega_t", 0.001) config.add_model_parameter("omega_f", 0.0015) model.set_initial_status(config) iterations = model.iteration_bunch(15) json.dump(iterations, open("phase0.json", "w")) trends = model.build_trends(iterations) json.dump(trends, open("trends0.json", "w")) viz = TotalCasesTrend(model, trends) viz.plot(filename="total_cases0.pdf") viz = DiffusionTrend(model, trends) viz.normalized = False viz.plot(filename="trend0.pdf", statuses=[ 'Infected', 'Exposed', "Dead"]) viz = RtTrend(model, trends) viz.plot(filename="RTtrend0.pdf") #### Phase 1: Lockdown + mobility allowed at municipality level for the ones not subject to lookdown (hospitals) model.update_model_parameter("mobility", 0.005) model.set_mobility_limits("municipality") # Handling lethality/recovery rates #model.update_model_parameter("gamma_t", 0.08) #model.update_model_parameter("gamma_f", 0.1)
print('-----Plotting Results-----') #print(iterations) #print(trends) from ndlib.viz.mpl.DiffusionTrend import DiffusionTrend daydata = [] fig = () ax = () for n in range(0, executions): if (trends[n]['trends']['node_count'][0][-1] != (N - initialinfect)): daydata.append(N-trends[n]['trends']['node_count'][0][-1]) print(daydata) fig = plt.hist(daydata) stdev = np.std(daydata) mean = np.mean(daydata) plt.title("Infected at Day {}".format(iterations), fontsize = 24) plt.xlabel("Infected Population", fontsize = 24) plt.ylabel("Number of Simulations", fontsize = 24) plt.figtext(0.85, 0.80, 'Outbreaks: {:.0f}\nMean: {:.3f}\nStDev: {:.3f}'.format(len(daydata), mean, stdev), fontsize = 24, bbox = dict(boxstyle = 'round', facecolor = 'white')) plt.tight_layout() plt.savefig("Histogram4/(HIST)Patient 0 Test: {} Days Test, {} Days Total, {} Initial.png".format(itercount, iterations, initialinfect)) plt.clf() viz = DiffusionTrend(model, trends) name = ("Histogram4/(COUNT)Patient 0 Test: {} Days Test, {} Days Total, {} Initial.png".format(itercount, iterations, initialinfect)) viz.plot(filename = name, percentile = 90, itercount = executions, timereq = total_time)
def thr_model(g, er_g, ba_g): print '\nTHRESHOLD MODEL SIMULATION' print 'MODEL CONFIGURATION' cfg = mc.Configuration() cfg.add_model_parameter('percentage_infected', float(raw_input('PERCENTAGE INFECTED: '))) thr = float(raw_input('THRESHOLD: ')) for_comparison = dict() count = 0 labels = ['G', 'ER', 'BA'] for network in [g, er_g, ba_g]: model_thr = threshold.ThresholdModel(network) model_thr.name = labels[count] print model_thr.name count+=1 for i in network.nodes(): cfg.add_node_configuration("threshold", i, thr) model_thr.set_initial_status(cfg) iterations = model_thr.iteration_bunch(100) trends_thr = model_thr.build_trends(iterations) if network is g: viz = DiffusionTrend(model_thr, trends_thr) viz.plot("../../report/images/spreading/threshold/diffusion.pdf") for_comparison['original_thr'] = [model_thr, trends_thr] elif network is er_g: viz = DiffusionTrend(model_thr, trends_thr) viz.plot( "../../report/images/spreading/threshold/diffusion_er.pdf") for_comparison['er_thr'] = [model_thr, trends_thr] else: viz = DiffusionTrend(model_thr, trends_thr) viz.plot( "../../report/images/spreading/threshold/diffusion_ba.pdf") for_comparison['ba_thr'] = [model_thr, trends_thr] viz = DiffusionTrendComparison([for_comparison['original_thr'][0], for_comparison['er_thr'][0], for_comparison['ba_thr'][0]], [ for_comparison['original_thr'][1], for_comparison['er_thr'][1], for_comparison['ba_thr'][1]]) viz.plot("../../report/images/spreading/threshold/trend_comparison.pdf")
import networkx as nx import matplotlib.pyplot as plt import ndlib.models.ModelConfig as mc import ndlib.models.epidemics as ep from ndlib.viz.mpl.DiffusionTrend import DiffusionTrend data = open('flight_data.csv', 'r') graphType = nx.DiGraph() g = nx.parse_edgelist(data, delimiter=',', create_using=graphType, nodetype=str) model = ep.SISModel(g) #WE NEED TO FIGURE THE PARAMS OUT BELOW cfg = mc.Configuration() cfg.add_model_parameter('beta', 0.01) cfg.add_model_parameter('lambda', 0.005) cfg.add_model_parameter("fraction_infected", 0.05) model.set_initial_status(cfg) iterations = model.iteration_bunch(200) trends = model.build_trends(iterations) viz = DiffusionTrend(model, trends) viz.plot("diffusion.png")
def sir_model(g, er_g, ba_g, g_stat): print '\nSIR MODEL SIMULATION WITH GAMMA ' + g_stat.upper() + ' THAN BETA' print 'MODEL CONFIGURATION' beta = float(raw_input('INFECTION PROBABILITY: ')) gamma = float(raw_input('REMOVAL PROBABILITY: ')) if g_stat == 'smaller': while gamma >= beta: print 'ERROR! GAMMA HAS TO BE SMALLER THAN BETA!' gamma = float(raw_input('REMOVAL PROBABILITY: ')) else: while gamma <= beta: print 'ERROR! GAMMA HAS TO BE GREATER THAN BETA!' gamma = float(raw_input('REMOVAL PROBABILITY: ')) cfg = mc.Configuration() cfg.add_model_parameter('beta', beta) cfg.add_model_parameter('gamma', gamma) cfg.add_model_parameter('percentage_infected', float(raw_input('PERCENTAGE INFECTED: '))) for_comparison = dict() for network in [g, er_g, ba_g]: model_sir = sir.SIRModel(network) model_sir.set_initial_status(cfg) iterations = model_sir.iteration_bunch(200) trends_sir = model_sir.build_trends(iterations) if network is g: viz = DiffusionTrend(model_sir, trends_sir) viz.plot("../../report/images/spreading/sir/diffusion_" + g_stat + ".pdf") for_comparison['original_sir'] = [model_sir, trends_sir] elif network is er_g: viz = DiffusionTrend(model_sir, trends_sir) viz.plot("../../report/images/spreading/sir/diffusion_er_" + g_stat + ".pdf") for_comparison['er_sir'] = [model_sir, trends_sir] else: viz = DiffusionTrend(model_sir, trends_sir) viz.plot("../../report/images/spreading/sir/diffusion_ba_" + g_stat + ".pdf") for_comparison['ba_sir'] = [model_sir, trends_sir] viz = DiffusionTrendComparison([ for_comparison['original_sir'][0], for_comparison['er_sir'][0], for_comparison['ba_sir'][0] ], [ for_comparison['original_sir'][1], for_comparison['er_sir'][1], for_comparison['ba_sir'][1] ]) viz.plot("../../report/images/spreading/sir/trend_comparison_" + g_stat + ".pdf")
import matplotlib.pyplot as plt import networkx as nx import json import warnings n = 271269 # n nodes p = 0.007286 w = [p * n for i in range(n)] # w = p*n for all nodes g = expected_degree_graph(w) # configuration model largest_subgraph1 = max(nx.connected_component_subgraphs(g), key=len) pos = nx.spring_layout(largest_subgraph1, k=0.05) nx.draw(largest_subgraph1, pos=pos, cmap=plt.cm.PiYG, edge_color="black", linewidths=0.3, node_size=60, alpha=0.6, with_labels=False) nx.draw_networkx(largest_subgraph1, pos=pos) plt.savefig('graphfinal2.png') model = ep.SIRModel(largest_subgraph1) cfg = mc.Configuration() cfg.add_model_parameter('beta', 0.05) # infection rate cfg.add_model_parameter('gamma', 0.05) # recovery rate cfg.add_model_parameter("percentage_infected", 0.01) model.set_initial_status(cfg) iterations = model.iteration_bunch(200, node_status=True) trends = model.build_trends(iterations) viz = DiffusionTrend(model, trends) viz.plot() viz = DiffusionPrevalence(model, trends) viz.plot()