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)
def test_profile_model(self): for g in get_graph(True): model = epd.ProfileModel(g) config = mc.Configuration() config.add_model_parameter('fraction_infected', 0.1) profile = 0.1 if isinstance(g, nx.Graph): nodes = g.nodes else: nodes = g.vs['name'] for i in nodes: config.add_node_configuration("profile", i, profile) model.set_initial_status(config) iterations = model.iteration_bunch(10) self.assertEqual(len(iterations), 10) model = epd.ProfileModel(g) config = mc.Configuration() config.add_model_parameter('fraction_infected', 0.1) config.add_model_parameter("blocked", 0.1) config.add_model_parameter("adopter_rate", 0.001) profile = 0.1 if isinstance(g, nx.Graph): nodes = g.nodes else: nodes = g.vs['name'] for i in nodes: config.add_node_configuration("profile", i, profile) model.set_initial_status(config) iterations = model.iteration_bunch(10, node_status=False) self.assertEqual(len(iterations), 10)
def test_comp_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) model1 = epd.SIRModel(g) config = mc.Configuration() config.add_model_parameter('beta', 0.02) config.add_model_parameter('gamma', 0.01) config.add_model_parameter("percentage_infected", 0.06) model1.set_initial_status(config) iterations = model1.iteration_bunch(1000) trends1 = model.build_trends(iterations) # Visualization viz = PhasePlaneComparison([model, model1], [trends, trends1], x="Susceptible", y="Infected") viz.plot("diffusion.pdf") os.remove("diffusion.pdf")
def test_multi(self): vm = MultiPlot() 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) viz = VisualizeDiffusion(model, iterations) p = viz.plot() vm.add_plot(p) 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) viz = VisualizeDiffusion(model, iterations) p1 = viz.plot() vm.add_plot(p1) m = vm.plot() self.assertIsInstance(m, Column)
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) model = pr.ProfileModel(g) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0.1) config.add_model_parameter("blocked", 0.1) config.add_model_parameter("adopter_rate", 0.001) 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, node_status=False) self.assertEqual(len(iterations), 10)
def test_prevalence_comparison(self): # Network topology g = nx.erdos_renyi_graph(1000, 0.1) # Model selection model = sir.SIRModel(g) # Model Configuration cfg = mc.Configuration() cfg.add_model_parameter('beta', 0.001) cfg.add_model_parameter('gamma', 0.02) cfg.add_model_parameter("percentage_infected", 0.01) model.set_initial_status(cfg) iterations = model.iteration_bunch(200) trends = model.build_trends(iterations) model1 = si.SIModel(g) cfg = mc.Configuration() cfg.add_model_parameter('beta', 0.001) cfg.add_model_parameter("percentage_infected", 0.01) model1.set_initial_status(cfg) iterations = model1.iteration_bunch(200) trends1 = model1.build_trends(iterations) viz = DiffusionPrevalenceComparison([model, model1], [trends, trends1]) viz.plot("prev_comparison.pdf") os.remove("prev_comparison.pdf")
def test_config(self): for g in get_graph(True): model = epd.ThresholdModel(g) config = mc.Configuration() config.add_model_parameter('fraction_infected', 0.1) config.add_model_initial_configuration("Infected", [1, 2, 3]) config.add_node_set_configuration("partial", {1: 1, 2: 2}) try: model.set_initial_status(config) except: pass if isinstance(g, nx.Graph): edges = list(g.edges) nodes = list(g.nodes) else: edges = [(g.vs[e.tuple[0]]['name'], g.vs[e.tuple[1]]['name']) for e in g.es] nodes = g.vs['name'] config.add_edge_set_configuration("partial", {e: 1 for e in edges[:10]}) try: model.set_initial_status(config) except: pass config.add_node_set_configuration("partial", {n: 1 for n in nodes}) config.add_edge_set_configuration("partial", {e: 1 for e in edges}) model.set_initial_status(config) for g in get_graph(): model = opn.MajorityRuleModel(g) config = mc.Configuration() config.add_model_parameter("percentage_infected", 0.2) try: model.set_initial_status(config) except: pass for g in get_graph(True): model = epd.IndependentCascadesModel(g) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0.1) try: model.set_initial_status(config) except: pass for g in get_graph(True): model = epd.ThresholdModel(g) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0.1) try: model.set_initial_status(config) except: pass
def test_edge_stochastic(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.EdgeStochastic(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.EdgeStochastic(triggering_status="Infected") model.add_rule("Susceptible", "Infected", c1) config = mc.Configuration() for e in g.edges(): config.add_edge_configuration("threshold", e, 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) # Predefined threshold 1/N model = gc.CompositeModel(g) model.add_status("Susceptible") model.add_status("Infected") c1 = cpm.EdgeStochastic(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)
def test_dyn_node_threshold(self): # Fixed Threshold dg = dn.DynGraph() for t in past.builtins.xrange(0, 3): g = nx.erdos_renyi_graph(200, 0.05) dg.add_interactions_from(g.edges(), t) model = gc.DynamicCompositeModel(dg) 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.execute_snapshots() self.assertEqual(len(iterations), 3) iterations = model.execute_iterations() trends = model.build_trends(iterations) self.assertEqual( len(trends[0]['trends']['status_delta'][1]), len([x for x in dg.stream_interactions() if x[2] == "+"])) # Ad-hoc Threshold model = gc.DynamicCompositeModel(dg) 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.execute_snapshots() self.assertEqual(len(iterations), 3) iterations = model.execute_iterations() trends = model.build_trends(iterations) self.assertEqual( len(trends[0]['trends']['status_delta'][1]), len([x for x in dg.stream_interactions() if x[2] == "+"]))
def test_config(self): g = nx.erdos_renyi_graph(99, 0.1) model = th.ThresholdModel(g) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0.1) config.add_model_initial_configuration("Infected", [1, 2, 3]) config.add_node_set_configuration("partial", {1: 1, 2: 2}) try: model.set_initial_status(config) except: pass config.add_edge_set_configuration("partial", {e: 1 for e in list(g.edges)[:10]}) try: model.set_initial_status(config) except: pass config.add_node_set_configuration("partial", {n: 1 for n in g.nodes}) config.add_edge_set_configuration("partial", {e: 1 for e in g.edges}) model.set_initial_status(config) g = nx.complete_graph(100) model = mrm.MajorityRuleModel(g) config = mc.Configuration() config.add_model_parameter("percentage_infected", 0.2) try: model.set_initial_status(config) except: pass g = nx.erdos_renyi_graph(1000, 0.1) model = ids.IndependentCascadesModel(g) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0.1) try: model.set_initial_status(config) except: pass g = nx.erdos_renyi_graph(1000, 0.1) model = th.ThresholdModel(g) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0.1) try: model.set_initial_status(config) except: pass
def test_compartment_add_node(self): g = nx.karate_club_graph() attr = {n: {"even": int(n % 2)} for n in g.nodes()} nx.set_node_attributes(g, attr) model = gc.CompositeModel(g) model.add_status("Susceptible") model.add_status("Infected") c2 = act.AddNode(probability=1, initial_status="Susceptible", copy_attributes=True) c1 = cpm.NodeStochastic(1, composed=c2) model.add_rule("Susceptible", "Susceptible", c1) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0) model.set_initial_status(config) iterations = model.iteration_bunch(6) nodes = [sum(n['node_count'].values()) for n in iterations] self.assertEqual(nodes, [34, 67, 133, 265, 529, 1057])
def func_obj(x, g): days = 30 sirSj = list() sirS = list() sirI = list() sirR = list() Igerado = list() Rgerado = list() # Ready CSV arq = open("casos_sj2.csv") sirSjCsv = csv.DictReader(arq, fieldnames=["S", "I", "R"]) i = 0 for row in sirSjCsv: sirSj.insert(i, { "S": int(row['S']), "I": int(row['I']), "R": int(row['R']) }) sirS.append(int(row['S'])) sirI.append(int(row['I'])) sirR.append(int(row['R'])) i += 1 # Model selection SIRModel = ep.SIRModel(g) # Model Configuration cfg = mc.Configuration() cfg.add_model_parameter('beta', 0.3) cfg.add_model_parameter('gamma', 0.05) cfg.add_model_parameter("fraction_infected", 0.008) SIRModel.set_initial_status(cfg) SIRModel.reset() cfg.add_model_parameter('beta', x[0]) cfg.add_model_parameter('gamma', x[1]) cfg.add_model_parameter("fraction_infected", 0.08) SIRModel.set_initial_status(cfg) iterations = SIRModel.iteration_bunch(days) #print(iterations) a = 0 Igerado.clear() Rgerado.clear() matriz_gerada = np.zeros((days, 3), dtype=np.int) for v in iterations: matriz_gerada[a][0] = v['node_count'][0] matriz_gerada[a][1] = v['node_count'][1] matriz_gerada[a][2] = v['node_count'][2] Igerado.append(v['node_count'][1]) Rgerado.append(v['node_count'][2]) a = a + 1 print(iterations) mseI = mean_squared_error(sirI, Igerado) mseR = mean_squared_error(sirR, Rgerado) rmseI = math.sqrt(mseI) rmseR = math.sqrt(mseR) f = (rmseI + rmseR) / 2 return f
def test_GeneralThresholdModel(self): for g in get_graph(True): model = epd.GeneralThresholdModel(g) config = mc.Configuration() config.add_model_parameter('fraction_infected', 0.1) threshold = 0.2 weight = 0.2 if isinstance(g, nx.Graph): nodes = g.nodes edges = g.edges else: nodes = g.vs['name'] edges = [(g.vs[e.tuple[0]]['name'], g.vs[e.tuple[1]]['name']) for e in g.es] for i in nodes: config.add_node_configuration("threshold", i, threshold) for e in edges: config.add_edge_configuration("weight", e, weight) 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)
def test_ICP(self): threshold = 0.1 for g in get_graph(True): model = epd.ICPModel(g) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0.1) if isinstance(g, nx.Graph): node_to_com = {n: random.choice([0, 1])for n in g.nodes()} for i in g.nodes(): config.add_node_configuration("com", i, node_to_com[i]) for e in g.edges: config.add_edge_configuration("threshold", e, threshold) else: node_to_com = {n: random.choice([0, 1]) for n in g.vs['name']} for i in g.vs['name']: config.add_node_configuration("com", i, node_to_com[i]) edges = [(g.vs[e.tuple[0]]['name'], g.vs[e.tuple[1]]['name']) for e in g.es] for e in edges: config.add_edge_configuration("threshold", e, threshold) config.add_model_parameter('permeability', 0.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)
def test_kertesz_model_predefined_blocked(self): for g in get_graph(True): model = epd.KerteszThresholdModel(g) config = mc.Configuration() config.add_model_parameter('adopter_rate', 0.4) predefined_blocked = [0, 1, 2, 3, 4, 5] config.add_model_initial_configuration("Blocked", predefined_blocked) config.add_model_parameter('percentage_infected', 0.1) threshold = 0.2 if isinstance(g, nx.Graph): nodes = g.nodes else: nodes = g.vs['name'] for i in nodes: config.add_node_configuration("threshold", i, threshold) model.set_initial_status(config) iteration = model.iteration() blocked = [ x for x, v in future.utils.iteritems(iteration['status']) if v == -1 ] self.assertEqual(blocked, predefined_blocked)
def simulate_sis_on_network(G): # Model Configuration cfg = mc.Configuration() cfg.add_model_parameter('beta', 0.05) cfg.add_model_parameter('lambda', 0.05) cfg.add_model_initial_configuration("Infected", random.sample(G.nodes, k=5)) # Model selection model = ep.SISModel(G) # Initialize the simulation model.set_initial_status(cfg) Si, Ii = [], [] for s in range(SIMULCOUNT): # Reset the model model.reset() # Simulation execution iterations = model.iteration_bunch(ITERCOUNT) # Collect results for figures S, I = [], [] for i in range(ITERCOUNT): iteration = iterations[i]['node_count'] S.append(iteration[0] / G.number_of_nodes()) I.append(iteration[1] / G.number_of_nodes()) Si.append(S) Ii.append(I) plot_spreading_figures(Si, Ii)
def get_voter_params(): print('\n\tInput Voter model parameters') fraction_infected = float(input('fraction_infected(initial)[0, 1]: ')) cfg = mc.Configuration() cfg.add_model_parameter('fraction_infected', fraction_infected) # 0.1 return cfg
def test_compartment_add_node_pa(self): g = nx.karate_club_graph() attr = {n: {"even": int(n % 2)} for n in g.nodes()} nx.set_node_attributes(g, attr) model = gc.CompositeModel(g) model.add_status("Susceptible") model.add_status("Infected") a1 = act.AddNode(probability=1, initial_status="Susceptible", copy_attributes=True, number_of_edges=4, model='PA') c1 = cmp.NodeStochastic(1) model.add_rule("Susceptible", "Susceptible", c1) model.add_action(a1) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0) model.set_initial_status(config) iterations = model.iteration_bunch(6) nodes = [sum(n['node_count'].values()) for n in iterations] self.assertEqual(nodes, [35, 36, 37, 38, 39, 40])
def test_arwhk_model(self): for g in get_graph(): model = opn.ARWHKModel(g) config = mc.Configuration() config.add_model_parameter("epsilon", 0.32) config.add_model_parameter("perc_stubborness", 0.2) config.add_model_parameter("option_for_stubbornness", 1) config.add_model_parameter("similarity", 1) weight = 0.2 if isinstance(g, nx.Graph): edges = g.edges nodes = g.nodes else: edges = [(g.vs[e.tuple[0]]['name'], g.vs[e.tuple[1]]['name']) for e in g.es] nodes = g.vs['name'] for e in edges: config.add_edge_configuration("weight", e, weight) for node in nodes: i = 0 vector = [] while i < 6: vector.append(np.random.randint(2)) i += 1 config.add_node_configuration("vector", node, vector) 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)
def addMethod(self): nxGraph = nx.DiGraph(self.graph) # Model selection model = ab.AlgorithmicBiasModel(nxGraph) # Model configuration config = mc.Configuration() config.add_model_parameter("epsilon", 0.32) config.add_model_parameter("gamma", 1) model.set_initial_status(config) for key in model.status: if key in self.seed: model.status[key] = 1 else: model.status[key] = 0.001 numOfIters = 100 trendArr = [] for i in range(0, numOfIters): iterations = model.iteration_bunch(1) trends = model.build_trends(iterations) di = model.status infectedTrend = np.sum(list(map(lambda x: di[x], di))) trendArr.append(infectedTrend) return trendArr print("added method")
def test_dyn_node_stochastic(self): dg = dn.DynGraph() for t in past.builtins.xrange(0, 3): g = nx.erdos_renyi_graph(200, 0.05) dg.add_interactions_from(g.edges(), t) model = gc.DynamicCompositeModel(dg) model.add_status("Susceptible") model.add_status("Infected") model.add_status("Removed") c1 = cpm.NodeStochastic(0.02, "Infected") c2 = cpm.NodeStochastic(0.01) c3 = cpm.NodeStochastic(0.5) model.add_rule("Susceptible", "Infected", c1) model.add_rule("Infected", "Removed", c2) model.add_rule("Infected", "Susceptible", c3) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0.1) model.set_initial_status(config) iterations = model.execute_snapshots() self.assertEqual(len(iterations), 3) iterations = model.execute_iterations() trends = model.build_trends(iterations) self.assertEqual( len(trends[0]['trends']['status_delta'][1]), len([x for x in dg.stream_interactions() if x[2] == "+"]))
def IC(G_df, S, iter_num=3): ''' Input: G_df: dataframe of edges ['followee','follower', 'prob'] S: seedset iter_num: Number of total IC steps mc_num: Number of Monte-Carlo simulations Output: list of activated nodes ''' g = nx.DiGraph() G = G_df[['followee', 'follower']].values weights = G_df['prob'].values g.add_edges_from(G, weights=weights) # Model configuration model = ep.IndependentCascadesModel(g) config = mc.Configuration() config.add_model_initial_configuration('Infected', S) # Edge configuration for e in g.edges: config.add_edge_configuration('threshold', e, 1) model.set_initial_status(config) iteration = model.iteration_bunch(iter_num) return iteration activated = [] for i in range(iter_num): activated += [k for k, v in iteration[i]['status'].items() if v == 1] return list(set(activated))
def execute_model(G, number_of_iterations, number_of_executions): """ Execute the TD model :return: df including model results) """ nodes = [] for node in G.nodes: nodes.append(node) df_mod_multi = pd.DataFrame(0, index=list(range(0, number_of_iterations)), columns=nodes) for infected_node in nodes: # print(infected_node) model = TDMethod(G) cfg_mod = mc.Configuration() cfg_mod.add_model_parameter('beta', 'individual betas') # infection rate infection_sets = [] infection_sets.append(infected_node) cfg_mod.add_model_initial_configuration("Infected", infection_sets) model.set_initial_status(cfg_mod) trends_multi = multi_runs(model, execution_number=number_of_executions, iteration_number=number_of_iterations, nprocesses=10) execution_list = list(range(0, number_of_executions)) for ex_n in execution_list: list_of_infected_nodes = trends_multi[ex_n]['trends']['node_count'][1] iterator_ifn = 0 for ifn in list_of_infected_nodes: df_mod_multi.at[iterator_ifn, infected_node] = df_mod_multi.at[iterator_ifn, infected_node] + ifn iterator_ifn = iterator_ifn + 1 df_mod_multi = df_mod_multi / number_of_executions return df_mod_multi
def model (net, frac_inf, threshold, iter): # Defines the model type, specification and implementation. # The function uses the network input in net as the main input # for the threshold model. Then the rest of parameters are # specified in the model configuration: # frac_inf: Initial fraction of infected nodes. # threshold: Fraction of active neighbours necessary to change # a node's state to active. # iter: Number of iterations to run from the dynamical process. # Model impolementation model = ep.ThresholdModel(net) # Model Configuration: initial conditions config = mc.Configuration() config.add_model_parameter('fraction_infected', frac_inf) for i in net.nodes(): config.add_node_configuration("threshold", i, threshold) model.set_initial_status(config) # Simulation execution iterations = model.iteration_bunch(iter) trends = model.build_trends(iterations) return [model, iterations, trends]
def indipendent_cascade_model(self): ''' Configuration and execution of the Indipendent Cascade Model algorithm, iteration is performed by itetration. Model execution is stopped when nodes are no longer influenced. ''' model = ids.IndependentCascadesModel(self.__year_graph) config = mc.Configuration() config.add_model_initial_configuration("Infected", self.__seed) for e in self.__year_graph.edges(): threshold = self.cascade_threshold(e) config.add_edge_configuration('threshold', e, threshold) model.set_initial_status(config) self.__influenced = dict() while True: iteration = model.iteration() if len(iteration.get('status')) == 0: break lst = [] for k in iteration.get('status'): if iteration.get('status')[k] == 1: lst.append(k) if len(lst) == 0: break self.__influenced['iteration {0}'.format( iteration.get('iteration'))] = lst
def tipping_model(self): ''' Configuration and execution of the Tipping Model algorithm, iteration is performed by iteration. Model execution is stopped when nodes are no longer influenced. ''' model = ids.ThresholdModel(self.__year_graph) config = mc.Configuration() config.add_model_initial_configuration("Infected", self.__seed) for n in self.__year_graph.nodes(): threshold = self.tipping_threshold(n) config.add_node_configuration('threshold', n, threshold) model.set_initial_status(config) self.__influenced = dict() while True: iteration = model.iteration() if len(iteration.get('status')) == 0: break self.__influenced['iteration {0}'.format( iteration.get('iteration'))] = [] for k in iteration.get('status'): if iteration.get('status')[k] == 1: self.__influenced['iteration {0}'.format( iteration.get('iteration'))].append(k)
def create_seir_model(graph, beta=0.01, gamma=0.005, alpha=0.05, infected=0.05): """ Susceptible 0 Infected 1 Exposed 2 Removed 3 beta - probability of transition from S to E gamma - probability of transition from E to I alpha - probability of transition from I to S infected - part of population infected at the begining """ model = seir.SEIRModel(g) # Model Configuration cfg = mc.Configuration() cfg.add_model_parameter('beta', beta) cfg.add_model_parameter('gamma', gamma) cfg.add_model_parameter('alpha', alpha) cfg.add_model_parameter("percentage_infected", infected) model.set_initial_status(cfg) return model
def test_compartment_swap_edge(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") a1 = act.SwapEdges(probability=1, number_of_swaps=1, copy_attributes=True, initial_status="Susceptible") c1 = cmp.NodeStochastic(0.5) model.add_rule("Susceptible", "Susceptible", c1) model.add_action(a1) config = mc.Configuration() config.add_model_parameter('percentage_infected', 0) model.set_initial_status(config) iterations = model.iteration_bunch(6) self.assertEqual(len(iterations), 6)
def test_save_file(self): def update(node, graph, status, attributes, constants): return 0 initial_status = {'status': 0} # Network definition g = nx.erdos_renyi_graph(n=10, p=0.5) # Model definition path = './test_output/' output_path = path + 'file' with self.assertRaises(ValueError): model = gc.ContinuousModel(g, save_file=5) model = gc.ContinuousModel(g, save_file=output_path) model.add_status('status') # Compartments condition = cpm.NodeStochastic(1) # Rules model.add_rule('status_1', update, condition) # Configuration config = mc.Configuration() model.set_initial_status(initial_status, config) # Simulation iterations = model.iteration_bunch(10, node_status=True, progress_bar=False) self.assertEqual(len(iterations), 10) self.assertTrue(os.path.isfile(output_path + '.npy')) os.remove(output_path + '.npy') os.rmdir(path)
def test_sznajd_model(self): g = nx.complete_graph(100) model = sm.SznajdModel(g) config = mc.Configuration() config.add_model_parameter("percentage_infected", 0.2) model.set_initial_status(config) iterations = model.iteration_bunch(10) self.assertEqual(len(iterations), 10)