def test_egonet_splitter(): """ Test the Ego Net splitter procedure. """ graph = nx.newman_watts_strogatz_graph(100, 5, 0.3) model = EgoNetSplitter() model.fit(graph) memberships = model.get_memberships() indices = [k for k, v in memberships.items()].sort() nodes = [node for node in graph.nodes()].sort() assert graph.number_of_nodes() == len(memberships) assert indices == nodes assert type(memberships) == dict graph = nx.newman_watts_strogatz_graph(150, 5, 0.3) model = EgoNetSplitter() model.fit(graph) memberships = model.get_memberships() indices = [k for k, v in memberships.items()].sort() nodes = [node for node in graph.nodes()].sort() assert graph.number_of_nodes() == len(memberships) assert indices == nodes assert type(memberships) == dict # Test weighted graph graph = nx.les_miserables_graph() graph = nx.convert_node_labels_to_integers(graph) model = EgoNetSplitter(weight='weight') model.fit(graph) memberships = model.get_memberships() indices = [k for k, v in memberships.items()].sort() nodes = [node for node in graph.nodes()].sort() assert graph.number_of_nodes() == len(memberships) assert indices == nodes assert type(memberships) == dict # Force unweighted graph = nx.les_miserables_graph() graph = nx.convert_node_labels_to_integers(graph) model = EgoNetSplitter(weight=None) model.fit(graph) memberships = model.get_memberships() indices = [k for k, v in memberships.items()].sort() nodes = [node for node in graph.nodes()].sort() assert graph.number_of_nodes() == len(memberships) assert indices == nodes assert type(memberships) == dict
def prepare_data( ) -> Tuple[PropagationModel, Dict[str, Tuple[str, ...]], MultilayerNetwork]: """Sets up data needed to perform tests.""" # init propagation model and set transitions with probabilities model = PropagationModel() phenomenas = { "ill": ("S", "I", "R"), "aware": ("UA", "A"), "vacc": ("UV", "V"), } for l, p in phenomenas.items(): model.add(l, p) model.compile(background_weight=0) # init multilayer network from nx predefined network network = MultilayerNetwork() network.load_layer_nx(nx.les_miserables_graph(), [*phenomenas.keys()]) model.set_transition_fast("ill.S", "ill.I", ("vacc.UV", "aware.UA"), 0.9) model.set_transition_fast("ill.S", "ill.I", ("vacc.V", "aware.A"), 0.05) model.set_transition_fast("ill.S", "ill.I", ("vacc.UV", "aware.A"), 0.2) model.set_transition_fast("ill.I", "ill.R", ("vacc.UV", "aware.UA"), 0.1) model.set_transition_fast("ill.I", "ill.R", ("vacc.V", "aware.A"), 0.7) model.set_transition_fast("ill.I", "ill.R", ("vacc.UV", "aware.A"), 0.3) model.set_transition_fast("vacc.UV", "vacc.V", ("aware.A", "ill.S"), 0.03) model.set_transition_fast("vacc.UV", "vacc.V", ("aware.A", "ill.I"), 0.01) model.set_transition_fast("aware.UA", "aware.A", ("vacc.UV", "ill.S"), 0.05) model.set_transition_fast("aware.UA", "aware.A", ("vacc.V", "ill.S"), 1) model.set_transition_fast("aware.UA", "aware.A", ("vacc.UV", "ill.I"), 0.2) return model, phenomenas, network
def setup_class(cls): G = nx.Graph() G.add_edge(0, 1, weight=3) G.add_edge(0, 2, weight=2) G.add_edge(0, 3, weight=6) G.add_edge(0, 4, weight=4) G.add_edge(1, 3, weight=5) G.add_edge(1, 5, weight=5) G.add_edge(2, 4, weight=1) G.add_edge(3, 4, weight=2) G.add_edge(3, 5, weight=1) G.add_edge(4, 5, weight=4) cls.G = G cls.exact_weighted = {0: 4.0, 1: 0.0, 2: 8.0, 3: 6.0, 4: 8.0, 5: 0.0} cls.K = nx.krackhardt_kite_graph() cls.P3 = nx.path_graph(3) cls.P4 = nx.path_graph(4) cls.K5 = nx.complete_graph(5) cls.C4 = nx.cycle_graph(4) cls.T = nx.balanced_tree(r=2, h=2) cls.Gb = nx.Graph() cls.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)]) cls.F = nx.florentine_families_graph() cls.LM = nx.les_miserables_graph() cls.D = nx.cycle_graph(3, create_using=nx.DiGraph()) cls.D.add_edges_from([(3, 0), (4, 3)])
def setUp(self): G = nx.Graph() G.add_edge(0, 1, weight=3) G.add_edge(0, 2, weight=2) G.add_edge(0, 3, weight=6) G.add_edge(0, 4, weight=4) G.add_edge(1, 3, weight=5) G.add_edge(1, 5, weight=5) G.add_edge(2, 4, weight=1) G.add_edge(3, 4, weight=2) G.add_edge(3, 5, weight=1) G.add_edge(4, 5, weight=4) self.G = G self.exact_weighted = {0: 4.0, 1: 0.0, 2: 8.0, 3: 6.0, 4: 8.0, 5: 0.0} self.K = nx.krackhardt_kite_graph() self.P3 = nx.path_graph(3) self.P4 = nx.path_graph(4) self.K5 = nx.complete_graph(5) self.C4 = nx.cycle_graph(4) self.T = nx.balanced_tree(r=2, h=2) self.Gb = nx.Graph() self.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)]) self.F = nx.florentine_families_graph() self.LM = nx.les_miserables_graph() self.D = nx.cycle_graph(3, create_using=nx.DiGraph()) self.D.add_edges_from([(3, 0), (4, 3)])
def test_les_miserables_graph_cutset(self): G = nx.les_miserables_graph() nx.set_edge_attributes(G, 1, "capacity") for flow_func in flow_funcs: T = nx.gomory_hu_tree(G, flow_func=flow_func) assert nx.is_tree(T) for u, v in combinations(G, 2): cut_value, edge = self.minimum_edge_weight(T, u, v) assert nx.minimum_cut_value(G, u, v) == cut_value
def test_les_miserables_graph_cutset(self): G = nx.les_miserables_graph() nx.set_edge_attributes(G, 1, 'capacity') for flow_func in flow_funcs: T = nx.gomory_hu_tree(G, flow_func=flow_func) assert_true(nx.is_tree(T)) for u, v in combinations(G, 2): cut_value, edge = self.minimum_edge_weight(T, u, v) assert_equal(nx.minimum_cut_value(G, u, v), cut_value)
def setUp(self): self.K = nx.krackhardt_kite_graph() self.P3 = nx.path_graph(3) self.P4 = nx.path_graph(4) self.K5 = nx.complete_graph(5) self.C4 = nx.cycle_graph(4) self.T = nx.balanced_tree(r=2, h=2) self.Gb = nx.Graph() self.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)]) F = nx.florentine_families_graph() self.F = F self.LM = nx.les_miserables_graph()
def setUp(self): self.K = nx.krackhardt_kite_graph() self.P3 = nx.path_graph(3) self.P4 = nx.path_graph(4) self.K5 = nx.complete_graph(5) self.C4 = nx.cycle_graph(4) self.T = nx.balanced_tree(r=2, h=2) self.Gb = nx.Graph() self.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)]) F = nx.florentine_families_graph() self.F = F self.LM = nx.les_miserables_graph()
def setUp(self) -> None: """Sets up testing parameters and performs simulation.""" self.exp_M = nx.les_miserables_graph() self.exp_beta = 0.1 self.exp_I = 0.05 self.exp_name = "".join(random.choices(string.ascii_letters, k=5)) self.out_dir = "".join(random.choices(string.ascii_letters, k=5)) ( self.list_S, self.list_I, self.list_iter, self.nodes_infected, self.par, ) = FlatSpreading.si_diffusion(self.exp_M, self.exp_I, self.exp_beta, name=self.exp_name)
def setup_class(cls): cls.K = nx.krackhardt_kite_graph() cls.P3 = nx.path_graph(3) cls.P4 = nx.path_graph(4) cls.K5 = nx.complete_graph(5) cls.C4 = nx.cycle_graph(4) cls.T = nx.balanced_tree(r=2, h=2) cls.Gb = nx.Graph() cls.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)]) F = nx.florentine_families_graph() cls.F = F cls.LM = nx.les_miserables_graph() # Create random undirected, unweighted graph for testing incremental version cls.undirected_G = nx.fast_gnp_random_graph(n=100, p=0.6, seed=123) cls.undirected_G_cc = nx.closeness_centrality(cls.undirected_G)
def test_compute_multiplexing_coefficient(self) -> None: """Tests if multiplexing coefficient is computed correctly.""" network = MultilayerNetwork() names = ["a", "b"] network.load_layer_nx(nx.les_miserables_graph(), names) mcf = network._compute_multiplexing_coefficient() self.assertEqual( mcf, 1, "Multiplexing coefficient for multpilex network should be 1", ) mcf = self.network._compute_multiplexing_coefficient() self.assertAlmostEqual( mcf, 0.733, 2, 'Multiplexing coefficient for "florentine" network should be ' "almost 0.73", )
def test_load_layer_nx(self) -> None: """Checks if creating MLN is correct by load_layer_nx func.""" network = MultilayerNetwork() names = ["a", "b"] network.load_layer_nx(nx.les_miserables_graph(), names) self.assertTrue( network.layers["a"].nodes == network.layers["b"].nodes, 'Nodes of layer "a" and "b" should be equal!', ) self.assertTrue( network.layers["a"].edges == network.layers["b"].edges, 'Edges of layer "a" and "b" should be equal!', ) self.assertFalse( network.layers["a"] == network.layers["b"], 'Network in layer "a" should be a diffeereent object than in "b"!', ) self.assertEqual( network.layers["a"].nodes["Napoleon"]["status"], None, "Node should have None in status attr", )
import networkx as nx from network_diffusion.multilayer_network import MultilayerNetwork from network_diffusion.propagation_model import PropagationModel from network_diffusion.multi_spreading import MultiSpreading from os import getcwd # first example # initialise multilayer network from nx prefedined network network = MultilayerNetwork() names = ['illness', 'awareness', 'vaccination'] network.load_layer_nx(nx.les_miserables_graph(), names) # initialise propagation model and set possible transitions with probabilities model = PropagationModel() phenomenas = [('S', 'I', 'R'), ('UA', 'A'), ('UV', 'V')] for l, p in zip(names, phenomenas): model.add(l, p) model.compile(background_weight=0.005) model.set_transition('illness.S', 'illness.I', ['vaccination.UV', 'awareness.UA'], 0.9) model.set_transition('illness.S', 'illness.I', ['vaccination.V', 'awareness.A'], 0.05) model.set_transition('illness.S', 'illness.I', ['vaccination.UV', 'awareness.A'], 0.2) model.set_transition('illness.I', 'illness.R', ['vaccination.UV', 'awareness.UA'], 0.1) model.set_transition('illness.I', 'illness.R', ['vaccination.V', 'awareness.A'], 0.7) model.set_transition('illness.I', 'illness.R',
fig, ax = plt.subplots(3, 4, figsize=(15,12)) G = nx.scale_free_graph(50) nx.draw(nx.complete_graph(50), ax=ax[0,0]) nx.draw(nx.star_graph(50), ax=ax[0,1]) nx.draw(nx.circular_ladder_graph(50), ax=ax[0,2]) nx.draw(nx.ladder_graph(50), ax=ax[0,3]) nx.draw(nx.path_graph(50), ax=ax[1,0]) nx.draw(nx.wheel_graph(50), ax=ax[1,1]) nx.draw(nx.erdos_renyi_graph(50, 0.3), ax=ax[1,2]) nx.draw(nx.barabasi_albert_graph(50, 5), ax=ax[1,3]) nx.draw(nx.random_powerlaw_tree(10), ax=ax[2,0]) nx.draw(nx.scale_free_graph(50), ax=ax[2,1]) nx.draw(nx.karate_club_graph(), ax=ax[2,2]) nx.draw(nx.les_miserables_graph(), ax=ax[2,3]) # %% [markdown] # ## Network Statistics # Calculate basic network statistics # %% # import an edgelist as a weighted directed graph filepath = r"data/sample.edgelist" G = nx.read_edgelist(filepath, create_using=nx.DiGraph,data=(('weight', int),), delimiter=' ') # %% [markdown] # This is a fairly large network # %%
def les_miserables(): G = nx.les_miserables_graph() print("les_miserables_graph => |V| =", G.number_of_nodes()) return G
def test_les_miserables_graph(self): """Weighted betweenness centrality: Les Miserables graph""" G = nx.les_miserables_graph() b_answer = { "Napoleon": 0.000, "Myriel": 0.177, "MlleBaptistine": 0.000, "MmeMagloire": 0.000, "CountessDeLo": 0.000, "Geborand": 0.000, "Champtercier": 0.000, "Cravatte": 0.000, "Count": 0.000, "OldMan": 0.000, "Valjean": 0.454, "Labarre": 0.000, "Marguerite": 0.009, "MmeDeR": 0.000, "Isabeau": 0.000, "Gervais": 0.000, "Listolier": 0.000, "Tholomyes": 0.066, "Fameuil": 0.000, "Blacheville": 0.000, "Favourite": 0.000, "Dahlia": 0.000, "Zephine": 0.000, "Fantine": 0.114, "MmeThenardier": 0.046, "Thenardier": 0.129, "Cosette": 0.075, "Javert": 0.193, "Fauchelevent": 0.026, "Bamatabois": 0.080, "Perpetue": 0.000, "Simplice": 0.001, "Scaufflaire": 0.000, "Woman1": 0.000, "Judge": 0.000, "Champmathieu": 0.000, "Brevet": 0.000, "Chenildieu": 0.000, "Cochepaille": 0.000, "Pontmercy": 0.023, "Boulatruelle": 0.000, "Eponine": 0.023, "Anzelma": 0.000, "Woman2": 0.000, "MotherInnocent": 0.000, "Gribier": 0.000, "MmeBurgon": 0.026, "Jondrette": 0.000, "Gavroche": 0.285, "Gillenormand": 0.024, "Magnon": 0.005, "MlleGillenormand": 0.036, "MmePontmercy": 0.005, "MlleVaubois": 0.000, "LtGillenormand": 0.015, "Marius": 0.072, "BaronessT": 0.004, "Mabeuf": 0.089, "Enjolras": 0.003, "Combeferre": 0.000, "Prouvaire": 0.000, "Feuilly": 0.004, "Courfeyrac": 0.001, "Bahorel": 0.007, "Bossuet": 0.028, "Joly": 0.000, "Grantaire": 0.036, "MotherPlutarch": 0.000, "Gueulemer": 0.025, "Babet": 0.015, "Claquesous": 0.042, "Montparnasse": 0.050, "Toussaint": 0.011, "Child1": 0.000, "Child2": 0.000, "Brujon": 0.002, "MmeHucheloup": 0.034, } b = nx.betweenness_centrality(G, weight="weight", normalized=True) for n in sorted(G): assert almost_equal(b[n], b_answer[n], places=3)
import matplotlib.pyplot as plt import networkx as nx from hc_embedding import draw_hce if __name__ == '__main__': graphs = [ nx.karate_club_graph(), nx.davis_southern_women_graph(), nx.les_miserables_graph(), nx.florentine_families_graph(), nx.powerlaw_cluster_graph(250, 1, 0.001), ] labels = [ "Karate", "Davis Southern Women", "Les Miserables", "Florentine Families", "Power Law Cluster", ] for G, title in zip(graphs, labels): draw_hce(G, title) plt.savefig(f"{title.lower().replace(' ', '_')}_test.png") plt.close()
def test_les_miserables_graph(self): """Weighted betweenness centrality: Les Miserables graph""" G = nx.les_miserables_graph() b_answer = \ {'Napoleon': 0.000, 'Myriel': 0.177, 'MlleBaptistine': 0.000, 'MmeMagloire': 0.000, 'CountessDeLo': 0.000, 'Geborand': 0.000, 'Champtercier': 0.000, 'Cravatte': 0.000, 'Count': 0.000, 'OldMan': 0.000, 'Valjean': 0.454, 'Labarre': 0.000, 'Marguerite': 0.009, 'MmeDeR': 0.000, 'Isabeau': 0.000, 'Gervais': 0.000, 'Listolier': 0.000, 'Tholomyes': 0.066, 'Fameuil': 0.000, 'Blacheville': 0.000, 'Favourite': 0.000, 'Dahlia': 0.000, 'Zephine': 0.000, 'Fantine': 0.114, 'MmeThenardier': 0.046, 'Thenardier': 0.129, 'Cosette': 0.075, 'Javert': 0.193, 'Fauchelevent': 0.026, 'Bamatabois': 0.080, 'Perpetue': 0.000, 'Simplice': 0.001, 'Scaufflaire': 0.000, 'Woman1': 0.000, 'Judge': 0.000, 'Champmathieu': 0.000, 'Brevet': 0.000, 'Chenildieu': 0.000, 'Cochepaille': 0.000, 'Pontmercy': 0.023, 'Boulatruelle': 0.000, 'Eponine': 0.023, 'Anzelma': 0.000, 'Woman2': 0.000, 'MotherInnocent': 0.000, 'Gribier': 0.000, 'MmeBurgon': 0.026, 'Jondrette': 0.000, 'Gavroche': 0.285, 'Gillenormand': 0.024, 'Magnon': 0.005, 'MlleGillenormand': 0.036, 'MmePontmercy': 0.005, 'MlleVaubois': 0.000, 'LtGillenormand': 0.015, 'Marius': 0.072, 'BaronessT': 0.004, 'Mabeuf': 0.089, 'Enjolras': 0.003, 'Combeferre': 0.000, 'Prouvaire': 0.000, 'Feuilly': 0.004, 'Courfeyrac': 0.001, 'Bahorel': 0.007, 'Bossuet': 0.028, 'Joly': 0.000, 'Grantaire': 0.036, 'MotherPlutarch': 0.000, 'Gueulemer': 0.025, 'Babet': 0.015, 'Claquesous': 0.042, 'Montparnasse': 0.050, 'Toussaint': 0.011, 'Child1': 0.000, 'Child2': 0.000, 'Brujon': 0.002, 'MmeHucheloup': 0.034} b = nx.betweenness_centrality(G, weight='weight', normalized=True) for n in sorted(G): assert_almost_equal(b[n], b_answer[n], places=3)
def test_les_miserables_graph(self): """Weighted betweenness centrality: Les Miserables graph""" G = nx.les_miserables_graph() b_answer = \ {'Napoleon': 0.000, 'Myriel': 0.177, 'MlleBaptistine': 0.000, 'MmeMagloire': 0.000, 'CountessDeLo': 0.000, 'Geborand': 0.000, 'Champtercier': 0.000, 'Cravatte': 0.000, 'Count': 0.000, 'OldMan': 0.000, 'Valjean': 0.454, 'Labarre': 0.000, 'Marguerite': 0.009, 'MmeDeR': 0.000, 'Isabeau': 0.000, 'Gervais': 0.000, 'Listolier': 0.000, 'Tholomyes': 0.066, 'Fameuil': 0.000, 'Blacheville': 0.000, 'Favourite': 0.000, 'Dahlia': 0.000, 'Zephine': 0.000, 'Fantine': 0.114, 'MmeThenardier': 0.046, 'Thenardier': 0.129, 'Cosette': 0.075, 'Javert': 0.193, 'Fauchelevent': 0.026, 'Bamatabois': 0.080, 'Perpetue': 0.000, 'Simplice': 0.001, 'Scaufflaire': 0.000, 'Woman1': 0.000, 'Judge': 0.000, 'Champmathieu': 0.000, 'Brevet': 0.000, 'Chenildieu': 0.000, 'Cochepaille': 0.000, 'Pontmercy': 0.023, 'Boulatruelle': 0.000, 'Eponine': 0.023, 'Anzelma': 0.000, 'Woman2': 0.000, 'MotherInnocent': 0.000, 'Gribier': 0.000, 'MmeBurgon': 0.026, 'Jondrette': 0.000, 'Gavroche': 0.285, 'Gillenormand': 0.024, 'Magnon': 0.005, 'MlleGillenormand': 0.036, 'MmePontmercy': 0.005, 'MlleVaubois': 0.000, 'LtGillenormand': 0.015, 'Marius': 0.072, 'BaronessT': 0.004, 'Mabeuf': 0.089, 'Enjolras': 0.003, 'Combeferre': 0.000, 'Prouvaire': 0.000, 'Feuilly': 0.004, 'Courfeyrac': 0.001, 'Bahorel': 0.007, 'Bossuet': 0.028, 'Joly': 0.000, 'Grantaire': 0.036, 'MotherPlutarch': 0.000, 'Gueulemer': 0.025, 'Babet': 0.015, 'Claquesous': 0.042, 'Montparnasse': 0.050, 'Toussaint': 0.011, 'Child1': 0.000, 'Child2': 0.000, 'Brujon': 0.002, 'MmeHucheloup': 0.034} b = nx.betweenness_centrality(G, weight='weight', normalized=True) for n in sorted(G): assert_almost_equal(b[n], b_answer[n], places=3)