Beispiel #1
0
def get_seir_params():
    print('\n\tInput SEIR model parameters')
    beta = float(input('beta(infection probability)[0, 1]: '))
    gamma = float(input('gamma(removal probability)[0, 1]: '))
    alpha = float(input('alpha(latent period)[0, 1]: '))
    fraction_infected = float(input('fraction_infected(initial)[0, 1]: '))

    cfg = mc.Configuration()
    cfg.add_model_parameter('beta', beta)  # 0.01
    cfg.add_model_parameter('gamma', gamma)  # 0.005
    cfg.add_model_parameter('alpha', alpha)  # 0.05
    cfg.add_model_parameter("fraction_infected", fraction_infected)  # 0.05
    return cfg
Beispiel #2
0
def get_seis_params():
    print('\n\tInput SEIS model parameters')
    beta = float(input('beta(infection probability)[0, 1]: '))
    lambda_param = float(input('lambda(recovery probability)[0, 1]: '))
    alpha = float(input('alpha(latent period)[0, 1]: '))
    fraction_infected = float(input('fraction_infected(initial)[0, 1]: '))

    cfg = mc.Configuration()
    cfg.add_model_parameter('beta', beta)  # 0.01
    cfg.add_model_parameter('lambda', lambda_param)  # 0.005
    cfg.add_model_parameter('alpha', alpha)  # 0.05
    cfg.add_model_parameter("fraction_infected", fraction_infected)  # 0.05
    return cfg
Beispiel #3
0
 def create_model(self,model_type,network):
     if self.config["UI"].getboolean("verbose"):
         print("Qu: Creating model ...  ")
     # Model Selection
     if model_type == 'SIR':
         self._active_model = SICR_model.generate_model(self._active_network)
     else:
         self._active_model = 0
     # Model Configuration
     config = mc.Configuration()
     config.add_model_parameter("fraction_infected", 0.01)
     self._active_model.set_initial_status(config)
     return self._active_model
Beispiel #4
0
    def test_threshold_model(self):
        g = nx.erdos_renyi_graph(1000, 0.1)
        model = th.ThresholdModel(g)
        config = mc.Configuration()
        config.add_model_parameter('percentage_infected', 0.1)

        threshold = 0.2
        for i in g.nodes():
            config.add_node_configuration("threshold", i, threshold)

        model.set_initial_status(config)
        iterations = model.iteration_bunch(10)
        self.assertEqual(len(iterations), 10)
    def test_node_threshold(self):

        # Fixed Threshold
        g = nx.erdos_renyi_graph(1000, 0.1)
        model = gc.CompositeModel(g)

        model.add_status("Susceptible")
        model.add_status("Infected")

        c1 = cpm.NodeThreshold(0.1, triggering_status="Infected")
        model.add_rule("Susceptible", "Infected", c1)

        config = mc.Configuration()
        config.add_model_parameter('percentage_infected', 0.1)

        model.set_initial_status(config)
        iterations = model.iteration_bunch(10)
        self.assertEqual(len(iterations), 10)

        # Ad-hoc Threshold
        model = gc.CompositeModel(g)

        model.add_status("Susceptible")
        model.add_status("Infected")

        c1 = cpm.NodeThreshold(triggering_status="Infected")
        model.add_rule("Susceptible", "Infected", c1)

        config = mc.Configuration()

        for i in g.nodes():
            config.add_node_configuration("threshold", i,
                                          np.random.random_sample())

        config.add_model_parameter('percentage_infected', 0.1)

        model.set_initial_status(config)
        iterations = model.iteration_bunch(10)
        self.assertEqual(len(iterations), 10)
Beispiel #6
0
    def test_seis_model(self):
        for g in get_graph(True):
            model = epd.SEISModel(g)
            config = mc.Configuration()
            config.add_model_parameter('beta', 0.5)
            config.add_model_parameter('lambda', 0.2)
            config.add_model_parameter('alpha', 0.05)
            config.add_model_parameter("fraction_infected", 0.1)
            model.set_initial_status(config)
            iterations = model.iteration_bunch(10)
            self.assertEqual(len(iterations), 10)

        for g in get_directed_graph(True):
            model = epd.SEISModel(g)
            config = mc.Configuration()
            config.add_model_parameter('beta', 0.5)
            config.add_model_parameter('lambda', 0.8)
            config.add_model_parameter('alpha', 0.5)
            config.add_model_parameter("fraction_infected", 0.1)
            model.set_initial_status(config)
            iterations = model.iteration_bunch(10, node_status=False)
            self.assertEqual(len(iterations), 10)
Beispiel #7
0
    def test_profile_model(self):
        g = nx.erdos_renyi_graph(1000, 0.1)
        model = pr.ProfileModel(g)
        config = mc.Configuration()
        config.add_model_parameter('percentage_infected', 0.1)

        profile = 0.1
        for i in g.nodes():
            config.add_node_configuration("profile", i, profile)

        model.set_initial_status(config)
        iterations = model.iteration_bunch(10)
        self.assertEqual(len(iterations), 10)
Beispiel #8
0
 def test_multiple_si_model(self):
     g = nx.erdos_renyi_graph(1000, 0.1)
     model = si.SIModel(g)
     config = mc.Configuration()
     config.add_model_parameter('beta', 0.01)
     config.add_model_parameter("percentage_infected", 0.1)
     model.set_initial_status(config)
     executions = ut.multi_runs(model,
                                execution_number=10,
                                iteration_number=50)
     self.assertEqual(len(executions), 10)
     iterations = model.iteration_bunch(10, node_status=False)
     self.assertEqual(len(iterations), 10)
Beispiel #9
0
 def test_multiple_si_model(self):
     for g in get_graph(True):
         model = epd.SIModel(g)
         config = mc.Configuration()
         config.add_model_parameter('beta', 0.01)
         config.add_model_parameter("fraction_infected", 0.1)
         model.set_initial_status(config)
         executions = ut.multi_runs(model,
                                    execution_number=10,
                                    iteration_number=50)
         self.assertEqual(len(executions), 10)
         iterations = model.iteration_bunch(10, node_status=False)
         self.assertEqual(len(iterations), 10)
Beispiel #10
0
def simulate_si_on_erdos_renyi():
    print('######################################')
    print('Simulating SI Model on Erdős-Rényi Graph...')
    print('######################################')
    g = nx.erdos_renyi_graph(1000, 0.15)
    model = si.SIModel(g)
    cfg = mc.Configuration()
    cfg.add_model_parameter('beta', 0.01)
    cfg.add_model_parameter("percentage_infected", 0.05)
    model.set_initial_status(cfg)
    iterations = model.iteration_bunch(200)
    trends = model.build_trends(iterations)
    draw_epidemic_plot(model, trends)
Beispiel #11
0
def simulate_si_on_barabasi_albert():
    print('######################################')
    print('Simulating SI Model on Barabasi-Albert Graph...')
    print('######################################')
    g = nx.barabasi_albert_graph(1000, 10)
    model = si.SIModel(g)
    cfg = mc.Configuration()
    cfg.add_model_parameter('beta', 0.01)
    cfg.add_model_parameter("percentage_infected", 0.05)
    model.set_initial_status(cfg)
    iterations = model.iteration_bunch(200)
    trends = model.build_trends(iterations)
    draw_epidemic_plot(model, trends)
Beispiel #12
0
 def test_initial_infected(self):
     g = nx.erdos_renyi_graph(1000, 0.1)
     model = sis.SISModel(g)
     config = mc.Configuration()
     config.add_model_parameter('beta', 0.5)
     config.add_model_parameter('lambda', 0.2)
     predefined_infected = [0, 1, 2, 3, 4, 5]
     config.add_model_initial_configuration("Infected", predefined_infected)
     model.set_initial_status(config)
     inft = [k for k, v in future.utils.iteritems(model.status) if v == 1]
     self.assertAlmostEqual(inft, predefined_infected)
     iterations = model.iteration_bunch(10)
     self.assertEqual(len(iterations), 10)
Beispiel #13
0
 def test_visualize_prevalence(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)
     viz = DiffusionPrevalence(model, trends)
     p = viz.plot()
     self.assertIsInstance(p, Figure)
Beispiel #14
0
    def test_seis_model(self):
        g = nx.erdos_renyi_graph(1000, 0.1)
        model = seis.SEISModel(g)
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.5)
        config.add_model_parameter('lambda', 0.2)
        config.add_model_parameter('alpha', 0.05)
        config.add_model_parameter("percentage_infected", 0.1)
        model.set_initial_status(config)
        iterations = model.iteration_bunch(10)
        self.assertEqual(len(iterations), 10)

        g = g.to_directed()
        model = seis.SEISModel(g)
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.5)
        config.add_model_parameter('lambda', 0.8)
        config.add_model_parameter('alpha', 0.5)
        config.add_model_parameter("percentage_infected", 0.1)
        model.set_initial_status(config)
        iterations = model.iteration_bunch(10, node_status=False)
        self.assertEqual(len(iterations), 10)
Beispiel #15
0
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()
Beispiel #16
0
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')
Beispiel #17
0
    def test_algorithmic_bias_model(self):

        for g in get_graph():
            model = opn.AlgorithmicBiasModel(g, seed=0)
            config = mc.Configuration()
            config.add_model_parameter("epsilon", 0.32)
            config.add_model_parameter("gamma", 1)
            model.set_initial_status(config)
            iterations = model.iteration_bunch(10)
            self.assertEqual(len(iterations), 10)
            iterations = model.iteration_bunch(10, node_status=False)
            self.assertEqual(len(iterations), 10)

            _ = model.steady_state(max_iterations=100)
Beispiel #18
0
def siModel(filename):
	# Network topology
	g = nx.read_edgelist(filename, nodetype=int, data=(('weight',float),), create_using=nx.Graph())
	# Model selection
	model = si.SIModel(g)

	# Model Configuration
	cfg = mc.Configuration()
	cfg.add_model_parameter('beta', 0.34)
	cfg.add_model_parameter("percentage_infected", 0)
	model.set_initial_status(cfg)
	col=[]
	sus=[]
	inf=[]

	# Simulation execution
	iterations = model.iteration_bunch(4)

	for i in iterations:
	    iter_ind=i['iteration']
	    #c=i['node_count']
	    node_status_list=i['status']
	    #print("Iteration:",iter_ind)
	    #print(node_status_list)
	    listOfKeys = [key  for (key, value) in node_status_list.items() if value == 1]
	    #print(listOfKeys)
	    if(listOfKeys != []):
	    	inf.extend(listOfKeys)

	#print("infected nodes = ", inf)
	print("total nodes", len(g))
	print("infected nodes", len(inf))
	if(len(inf) > 5000):
		sys.exit()
	h = g.subgraph(inf)
	#print(len(h))

	edgesOfInfectedGraph = list(h.edges())
	f = open('DiffusionModel/InfectedGraph.txt', 'w')
	f.write(str(inf[0]) + '\n')
	for t in edgesOfInfectedGraph:
	    line = ' '.join(str(x) for x in t)
	    #print(line)
	    f.write(line + '\n')
	f.close()

	#nx.draw_spring(h, cmap = plt.get_cmap('jet'), node_size=100, with_labels= True)
	#plt.show()
	
	return inf[0], h
Beispiel #19
0
def simulate_cascade(graph_path, threshold):
    g = nx.read_weighted_edgelist(graph_path, delimiter=";")
    model = ep.ThresholdModel(g)
    config = mc.Configuration()
    seed_nodes = find_seeds(g)
    config.add_model_initial_configuration(
        "Infected", seed_nodes)  # only seed nodes start as infected
    for i in g.nodes():
        config.add_node_configuration(
            'threshold', i,
            threshold)  # set threshold to be the same for all nodes
    model.set_initial_status(config)
    iterations = model.iteration_bunch(50)  # execute 50 iterations
    return iterations
Beispiel #20
0
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()
Beispiel #21
0
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()
Beispiel #22
0
    def test_independent_cascade_model(self):
        g = nx.erdos_renyi_graph(1000, 0.1)
        model = ids.IndependentCascadesModel(g)
        config = mc.Configuration()
        config.add_model_parameter('percentage_infected', 0.1)
        threshold = 0.1
        for e in g.edges():
            config.add_edge_configuration("threshold", e, threshold)

        model.set_initial_status(config)
        iterations = model.iteration_bunch(10)
        self.assertEqual(len(iterations), 10)
        iterations = model.iteration_bunch(10, node_status=False)
        self.assertEqual(len(iterations), 10)
Beispiel #23
0
    def test_visualization(self):
        initial_status = {
            'status': 0,
        }

        def update(node, graph, status, attributes, constants):
            return -2

        # Network definition
        g = nx.erdos_renyi_graph(n=100, p=0.5)

        output_path = './test.gif'

        # Visualization config
        visualization_config = {
            'plot_interval': 1,
            'plot_variable': 'status',
            'show_plot': False,
            'plot_title': 'Example model',
            'animation_interval': 200,
            'plot_output': output_path
        }

        # Model definition
        model = gc.ContinuousModel(g, clean_status=True)
        model.add_status('status')

        # Compartments
        condition = cpm.NodeStochastic(1)

        # Rules
        model.add_rule('status', update, condition)

        # Configuration
        config = mc.Configuration()
        model.set_initial_status(initial_status, config)
        model.configure_visualization(visualization_config)

        # Simulation
        iterations = model.iteration_bunch(2, node_status=True)

        trends = model.build_trends(iterations)
        model.plot(trends, len(iterations), delta=True, delta_mean=True)

        ### Plots / data manipulation
        model.visualize(iterations)

        self.assertTrue(os.path.isfile(output_path))
        os.remove(output_path)
Beispiel #24
0
    def test_bare_model(self):
        def initial_addiction(node, graph, status, constants):
            addiction = 0
            return addiction

        def initial_self_confidence(node, graph, status, constants):
            self_confidence = 1
            return self_confidence

        initial_status = {
            'addiction': initial_addiction,
            'self_confidence': initial_self_confidence
        }

        def craving_model(node, graph, status, attributes, constants):
            current_val = status[node]['addiction']
            return min(current_val + 0.1, 1)

        def self_confidence_impact(node, graph, status, attributes, constants):
            return max(status[node]['self_confidence'] - 0.25, 0)

        # Network definition
        g = nx.erdos_renyi_graph(n=1000, p=0.1)

        # Model definition
        addiction_model = gc.ContinuousModel(g)
        addiction_model.add_status('addiction')
        addiction_model.add_status('self_confidence')

        # Compartments
        condition = cpm.NodeNumericalVariable('addiction',
                                              var_type=NumericalType.STATUS,
                                              value=1,
                                              op='<')

        # Rules
        addiction_model.add_rule('addiction', craving_model, condition)
        addiction_model.add_rule('self_confidence', self_confidence_impact,
                                 condition)

        # Configuration
        config = mc.Configuration()
        addiction_model.set_initial_status(initial_status, config)

        # Simulation
        iterations = addiction_model.iteration_bunch(50,
                                                     node_status=True,
                                                     progress_bar=False)
        self.assertEqual(len(iterations), 50)
Beispiel #25
0
    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")
Beispiel #26
0
    def test_kertesz_model(self):
        g = nx.complete_graph(100)
        model = ks.KerteszThresholdModel(g)
        config = mc.Configuration()
        config.add_model_parameter('adopter_rate', 0.4)
        config.add_model_parameter('percentage_blocked', 0.1)
        config.add_model_parameter('percentage_infected', 0.1)

        threshold = 0.2
        for i in g.nodes():
            config.add_node_configuration("threshold", i, threshold)

        model.set_initial_status(config)
        iterations = model.iteration_bunch(10)
        self.assertEqual(len(iterations), 10)
Beispiel #27
0
    def test_phaseplane(self):
        g = nx.barabasi_albert_graph(1000, 3)
        model = epd.SIRModel(g)
        config = mc.Configuration()
        config.add_model_parameter('beta', 0.05)
        config.add_model_parameter('gamma', 0.09)
        config.add_model_parameter("percentage_infected", 0.02)
        model.set_initial_status(config)
        iterations = model.iteration_bunch(1000)
        trends = model.build_trends(iterations)

        # Visualization
        viz = PhasePlane(model, trends, x="Susceptible", y="Infected")
        viz.plot("diffusion.pdf")
        os.remove("diffusion.pdf")
    def test_edge_num_attribute(self):

        g = nx.karate_club_graph()
        attr = {(u, v): {"even": int((u + v) % 10)} for (u, v) in g.edges()}
        nx.set_edge_attributes(g, attr)

        model = gc.CompositeModel(g)
        model.add_status("Susceptible")
        model.add_status("Infected")

        c = cpm.EdgeNumericalAttribute("even", value=0, op="==", probability=1)
        model.add_rule("Susceptible", "Infected", c)

        config = mc.Configuration()
        config.add_model_parameter('percentage_infected', 0.1)

        model.set_initial_status(config)
        iterations = model.iteration_bunch(10)
        self.assertEqual(len(iterations), 10)

        model = gc.CompositeModel(g)
        model.add_status("Susceptible")
        model.add_status("Infected")

        c = cpm.EdgeNumericalAttribute("even",
                                       value=[3, 10],
                                       op="IN",
                                       probability=1)
        model.add_rule("Susceptible", "Infected", c)

        config = mc.Configuration()
        config.add_model_parameter('percentage_infected', 0.1)

        model.set_initial_status(config)
        iterations = model.iteration_bunch(10)
        self.assertEqual(len(iterations), 10)
Beispiel #29
0
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()
Beispiel #30
0
def simulate_SIS(G, timesteps, beta, lambda_, initial_nodes): ##GVA index
    model = sis(G)
    
    cfg = mc.Configuration()
    infected_nodes = initial_nodes
    cfg.add_model_initial_configuration("Infected", infected_nodes)
    cfg.add_model_parameter('beta', beta)
    cfg.add_model_parameter('lambda', lambda_)
    
    model.set_initial_status(cfg)
    iterations = model.iteration_bunch(timesteps)
    
    trends = model.build_trends(iterations)
    
    return trends, iterations, model