示例#1
0
def initialize():
    global g, nextg  #,nodlest

    # g = nx.karate_club_graph()
    g = nx.florentine_families_graph()
    # g=nx.path_graph(12)
    # g=nx.cycle_graph(12)
    # g=nx.petersen_graph()

    g.pos = graphviz_layout(g)
    # g.pos = nx.spring_layout(g)

    x = 2
    for i in g.nodes_iter():
        if i != g.nodes()[x]:
            g.node[i]['state'] = random()

            # Susceptibility coefficients chosen randomly:

            g.node[i]['alpha'] = random()

        else:
            g.node[i]['state'] = 1  #2*pi
            g.node[i]['alpha'] = 0.
    nextg = g.copy()
    def test_converge_to_betweenness(self):
        """percolation centrality: should converge to betweenness
        centrality when all nodes are percolated the same"""
        # taken from betweenness test test_florentine_families_graph
        G = nx.florentine_families_graph()
        b_answer =\
            {'Acciaiuoli':    0.000,
             'Albizzi':       0.212,
             'Barbadori':     0.093,
             'Bischeri':      0.104,
             'Castellani':    0.055,
             'Ginori':        0.000,
             'Guadagni':      0.255,
             'Lamberteschi':  0.000,
             'Medici':        0.522,
             'Pazzi':         0.000,
             'Peruzzi':       0.022,
             'Ridolfi':       0.114,
             'Salviati':      0.143,
             'Strozzi':       0.103,
             'Tornabuoni':    0.092}

        p_states = {k: 1.0 for k, v in b_answer.items()}
        p_answer = nx.percolation_centrality(G, states=p_states)
        for n in sorted(G):
            assert_almost_equal(p_answer[n], b_answer[n], places=3)

        p_states = {k: 0.3 for k, v in b_answer.items()}
        p_answer = nx.percolation_centrality(G, states=p_states)
        for n in sorted(G):
            assert_almost_equal(p_answer[n], b_answer[n], places=3)
示例#3
0
    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.D = nx.cycle_graph(3, create_using=nx.DiGraph())
        self.D.add_edges_from([(3, 0), (4, 3)])
    def test_florentine_families_graph(self):
        """Weighted betweenness centrality: 
        Florentine families graph"""
        G = nx.florentine_families_graph()
        b_answer = {
            "Acciaiuoli": 0.000,
            "Albizzi": 0.212,
            "Barbadori": 0.093,
            "Bischeri": 0.104,
            "Castellani": 0.055,
            "Ginori": 0.000,
            "Guadagni": 0.255,
            "Lamberteschi": 0.000,
            "Medici": 0.522,
            "Pazzi": 0.000,
            "Peruzzi": 0.022,
            "Ridolfi": 0.114,
            "Salviati": 0.143,
            "Strozzi": 0.103,
            "Tornabuoni": 0.092,
        }

        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_florentine_families_graph(self):
        """Weighted betweenness centrality: 
        Florentine families graph"""
        G=nx.florentine_families_graph()
        b_answer=\
             {'Acciaiuoli':    0.000,
              'Albizzi':       0.212,
              'Barbadori':     0.093,
              'Bischeri':      0.104,
              'Castellani':    0.055,
              'Ginori':        0.000,
              'Guadagni':      0.255,
              'Lamberteschi':  0.000,
              'Medici':        0.522,
              'Pazzi':         0.000,
              'Peruzzi':       0.022,
              'Ridolfi':       0.114,
              'Salviati':      0.143,
              'Strozzi':       0.103,
              'Tornabuoni':    0.092}

        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_florentine_families_graph(self):
        """Weighted betweenness centrality:
        Florentine families graph"""
        G = nx.florentine_families_graph()
        b_answer = {
            "Acciaiuoli": 0.000,
            "Albizzi": 0.212,
            "Barbadori": 0.093,
            "Bischeri": 0.104,
            "Castellani": 0.055,
            "Ginori": 0.000,
            "Guadagni": 0.255,
            "Lamberteschi": 0.000,
            "Medici": 0.522,
            "Pazzi": 0.000,
            "Peruzzi": 0.022,
            "Ridolfi": 0.114,
            "Salviati": 0.143,
            "Strozzi": 0.103,
            "Tornabuoni": 0.092,
        }

        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 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)])
示例#8
0
def _get_florentine_graph():
    graph = nx.florentine_families_graph()

    for s, t in graph.edges():
        graph.add_edge(s, t, weight=1)

    return graph
    def test_converge_to_betweenness(self):
        """percolation centrality: should converge to betweenness
        centrality when all nodes are percolated the same"""
        # taken from betweenness test test_florentine_families_graph
        G = nx.florentine_families_graph()
        b_answer = {
            "Acciaiuoli": 0.000,
            "Albizzi": 0.212,
            "Barbadori": 0.093,
            "Bischeri": 0.104,
            "Castellani": 0.055,
            "Ginori": 0.000,
            "Guadagni": 0.255,
            "Lamberteschi": 0.000,
            "Medici": 0.522,
            "Pazzi": 0.000,
            "Peruzzi": 0.022,
            "Ridolfi": 0.114,
            "Salviati": 0.143,
            "Strozzi": 0.103,
            "Tornabuoni": 0.092,
        }

        p_states = {k: 1.0 for k, v in b_answer.items()}
        p_answer = nx.percolation_centrality(G, states=p_states)
        for n in sorted(G):
            assert almost_equal(p_answer[n], b_answer[n], places=3)

        p_states = {k: 0.3 for k, v in b_answer.items()}
        p_answer = nx.percolation_centrality(G, states=p_states)
        for n in sorted(G):
            assert almost_equal(p_answer[n], b_answer[n], places=3)
    def test_florentine_families_graph(self):
        """Weighted betweenness centrality: 
        Florentine families graph"""
        G=nx.florentine_families_graph()
        b_answer=\
             {'Acciaiuoli':    0.000,
              'Albizzi':       0.212,
              'Barbadori':     0.093,
              'Bischeri':      0.104,
              'Castellani':    0.055,
              'Ginori':        0.000,
              'Guadagni':      0.255,
              'Lamberteschi':  0.000,
              'Medici':        0.522,
              'Pazzi':         0.000,
              'Peruzzi':       0.022,
              'Ridolfi':       0.114,
              'Salviati':      0.143,
              'Strozzi':       0.103,
              'Tornabuoni':    0.092}

        b=nx.betweenness_centrality(G,
                                          weight='weight',
                                          normalized=True)
        for n in sorted(G):
            assert_almost_equal(b[n],b_answer[n],places=3)
示例#11
0
    def test_converge_to_betweenness(self):
        """percolation centrality: should converge to betweenness
        centrality when all nodes are percolated the same"""
        # taken from betweenness test test_florentine_families_graph
        G = nx.florentine_families_graph()
        b_answer =\
            {'Acciaiuoli':    0.000,
             'Albizzi':       0.212,
             'Barbadori':     0.093,
             'Bischeri':      0.104,
             'Castellani':    0.055,
             'Ginori':        0.000,
             'Guadagni':      0.255,
             'Lamberteschi':  0.000,
             'Medici':        0.522,
             'Pazzi':         0.000,
             'Peruzzi':       0.022,
             'Ridolfi':       0.114,
             'Salviati':      0.143,
             'Strozzi':       0.103,
             'Tornabuoni':    0.092}

        p_states = {k: 1.0 for k, v in b_answer.items()}
        p_answer = nx.percolation_centrality(G, states=p_states)
        for n in sorted(G):
            assert_almost_equal(p_answer[n], b_answer[n], places=3)

        p_states = {k: 0.3 for k, v in b_answer.items()}
        p_answer = nx.percolation_centrality(G, states=p_states)
        for n in sorted(G):
            assert_almost_equal(p_answer[n], b_answer[n], places=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)])


        F = nx.florentine_families_graph()
        self.F = F
示例#13
0
    def test_node2vec_same_labels_are_returned(self):
        graph = nx.florentine_families_graph()
        node_ids = list(graph.nodes())

        embedding, labels = gc.embed.node2vec_embed(graph)

        for i in range(len(node_ids)):
            self.assertEqual(node_ids[i], labels[i])
示例#14
0
    def test_layout_umap_string_node_ids(self):
        graph = nx.florentine_families_graph()

        for s, t in graph.edges():
            graph.add_edge(s, t, weight=1)

        _, node_positions = layout_umap(graph=graph)

        self.assertEqual(len(node_positions), len(graph.nodes()))
示例#15
0
 def test_florentine_families_graph(self):
     G = nx.florentine_families_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
示例#16
0
 def test_florentine_families_graph(self):
     G = nx.florentine_families_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)
示例#17
0
    def test_node2vec_embed(self):
        g = nx.florentine_families_graph()

        for s, t in g.edges():
            g.add_edge(s, t, weight=1)

        embedding = gc.embed.node2vec_embed(g, random_seed=1)

        embedding2 = gc.embed.node2vec_embed(g, random_seed=1)

        np.testing.assert_array_equal(embedding[0], embedding2[0])
示例#18
0
    def test_remap_node_ids_unweighted_graph_raises_warning(self):
        with warnings.catch_warnings(record=True) as warnings_context_manager:
            graph = nx.florentine_families_graph()

            gus.remap_node_ids(graph)

            self.assertEqual(len(warnings_context_manager), 1)
            self.assertTrue(
                issubclass(warnings_context_manager[0].category, UserWarning))
            self.assertTrue("Graph has at least one unweighted edge" in str(
                warnings_context_manager[0].message))
示例#19
0
def socialnetwork_graphs():
    print("Social networks")
    print("karate club graph")
    G = nx.karate_club_graph()
    draw_graph(G)
    print("Davis Southern women bipartite graph ")
    G = nx.davis_southern_women_graph()
    draw_graph(G)
    print("Florentine families graph ")
    G = nx.florentine_families_graph()
    draw_graph(G)
示例#20
0
    def test_frustrated_hostile_edge(self):
        """Set up a graph where the frustrated edge should be hostile"""
        sampler = ExactSolver()

        S = nx.florentine_families_graph()

        # set all hostile
        nx.set_edge_attributes(S, -1, 'sign')

        # smoke test
        frustrated_edges, colors = dnx.structural_imbalance(S, sampler)
        self.check_bicolor(colors)
def florentine_family():
    # Using networkx to create florentine family graph
    MAG = nx.florentine_families_graph()
    MAG.add_node("Pucci")
    MAG = nx.DiGraph(MAG)
    D, p, counter, node_size = mag_get_d_p(MAG) #Getting the D and p values using Djikstra's list algorithm
    closeness = closeness_central(D, counter, node_size)    #cacluating closeness centrality
    print("\nNormalized Closeness centrality:", closeness)
    print("\nNormalized Betweenness centrality:", nx.betweenness_centrality(MAG, normalized = True))  #NEED TO BE DONE
    print("\nNormalized Degree Centrality:", nx.degree_centrality(MAG))
    print("\nNormalized Eigen-vector Centrality:", nx.eigenvector_centrality(MAG))
    nx.draw(MAG, with_labels=True)
    plt.show()
    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
    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
示例#24
0
def test_florentine_families():
    G = nx.florentine_families_graph()
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        errmsg = f"Assertion failed in function: {flow_func.__name__}"
        # edge disjoint paths
        edge_dpaths = list(
            nx.edge_disjoint_paths(G, 'Medici', 'Strozzi', **kwargs))
        assert are_edge_disjoint_paths(G, edge_dpaths), errmsg
        assert nx.edge_connectivity(G, 'Medici',
                                    'Strozzi') == len(edge_dpaths), errmsg
        # node disjoint paths
        node_dpaths = list(
            nx.node_disjoint_paths(G, 'Medici', 'Strozzi', **kwargs))
        assert are_node_disjoint_paths(G, node_dpaths), errmsg
        assert nx.node_connectivity(G, 'Medici',
                                    'Strozzi') == len(node_dpaths), errmsg
示例#25
0
def test(graph="barbell", algorithm="o_fl", k=-1, v=False, kmin=3, kmax=5):
    """Runs a quic demo
       graph = 'karate', 'barbell', 'women', 'florentine'
         if not a specific graph it will be used as a seed for a random graph
       
       algorithm as
         'fl' = async fluid detection, requires k
         'o_fl' = optimizing fl, requires kmin and kmax
         'gn' = garvin_newman
       
       k = number of communities to look for if applicable
       v = verbose flag
    """
    #generate demo graph
    G = 0
    if graph == "karate":
        G = nx.karate_club_graph()
    elif graph == "barbell":
        G = nx.barbell_graph(5, 1)
    elif graph == "women":
        G = nx.davis_southern_women_graph()
    elif graph == "florentine":
        G = nx.florentine_families_graph()
    else:
        G = nx.planted_partition_graph(5, 10, .85, .1, seed=graph)
    #switch on algorithm
    bestcom = 0

    if algorithm == "fl":
        if k != -1:
            bestcom = async_fluid(G, k)
        else:
            bestcom = async_fluid(G)
    elif algorithm == "o_fl":  #optimized fl
        bestcom = opt_async_fluid(G, kmin, kmax)
    elif algorithm == "gn":
        bestcom = girvan_newman(G, v)

    #Label the data and export in gephi readable format
    comlabel = 1
    for c in bestcom:
        for n in c:
            G.node[n]['community'] = str(comlabel)
        comlabel += 1

    rw.write_file(G, "test.gexf")
示例#26
0
    def test_node2vec_embedding_unweighted_florentine_graph_correct_shape_is_returned(
        self, ):
        graph = nx.florentine_families_graph()

        model = gc.embed.node2vec_embed(graph)
        model_matrix: np.ndarray = model[0]
        vocab_list = model[1]
        self.assertIsNotNone(model)
        self.assertIsNotNone(model[0])
        self.assertIsNotNone(model[1])

        # model matrix should be 34 x 128
        self.assertEqual(model_matrix.shape[0], 15)
        self.assertEqual(model_matrix.shape[1], 128)

        # vocab list should have exactly 34 elements
        self.assertEqual(len(vocab_list), 15)
示例#27
0
class TestGirvanNewman(unittest.TestCase):

    Gs = [
        lecture_graph(),
        nx.florentine_families_graph(),
        nx.karate_club_graph()
    ]

    def test_compare_our_girvan_newman_with_networkx(self):
        """Compare the output of our girvan newman algorithm with netwrokx's

        The output might not by the same in some cases (non-exhaustive list):
            - if the graph has two pair of edges with the same edge betweeness
            (happens a lot with symetric graphs)
        """
        for G in TestGirvanNewman.Gs:
            # create iterators
            our_it = our_girvan_newman(G)
            nx_it = nx_girvan_newman(G)

            # for every level of communities
            while True:
                try:
                    our_communities = next(our_it)
                    nx_communities = next(nx_it)
                    self.assertEqual(our_communities, nx_communities)
                except StopIteration:
                    break

    def test_compare_our_edge_betweenness_centrality_with_networkx(self):
        """Compare the output of our edge betweenness centrality algorithm with netwrokx's
        """
        for G in TestGirvanNewman.Gs:
            our_edge_betweenness = our_edge_betweenness_centrality(G)
            # we can only handle non normalized edge betweeness
            # (because for gw it's doesnt matter)
            nx_edge_betweenness = nx_edge_betweenness_centrality(
                G, normalized=False)

            side_by_side = zip(our_edge_betweenness.items(),
                               nx_edge_betweenness.items())

            for (our_pair, our_value), (nx_pair, nx_value) in side_by_side:
                self.assertEqual(our_pair, nx_pair)
                self.assertAlmostEqual(our_value, nx_value, places=6)
示例#28
0
    def test_layout_umap_int_node_ids(self):
        graph = nx.florentine_families_graph()
        graph_int_node_ids = nx.Graph()
        ids_as_ints = dict()

        for s, t in graph.edges():
            if s not in ids_as_ints:
                ids_as_ints[s] = int(len(ids_as_ints.keys()))

            if t not in ids_as_ints:
                ids_as_ints[t] = int(len(ids_as_ints.keys()))

            graph_int_node_ids.add_edge(ids_as_ints[s],
                                        ids_as_ints[t],
                                        weight=1)

        _, node_positions = layout_umap(graph=graph_int_node_ids)

        self.assertEqual(len(node_positions), len(graph.nodes()))
    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)
示例#30
0
def test_florentine_families():
    G = nx.florentine_families_graph()
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge disjoint paths
        edge_dpaths = list(
            nx.edge_disjoint_paths(G, 'Medici', 'Strozzi', **kwargs))
        assert are_edge_disjoint_paths(G, edge_dpaths), msg.format(
            flow_func.__name__)
        assert nx.edge_connectivity(G, 'Medici',
                                    'Strozzi') == len(edge_dpaths), msg.format(
                                        flow_func.__name__)
        # node disjoint paths
        node_dpaths = list(
            nx.node_disjoint_paths(G, 'Medici', 'Strozzi', **kwargs))
        assert are_node_disjoint_paths(G, node_dpaths), msg.format(
            flow_func.__name__)
        assert nx.node_connectivity(G, 'Medici',
                                    'Strozzi') == len(node_dpaths), msg.format(
                                        flow_func.__name__)
示例#31
0
def test_florentine_families():
    G = nx.florentine_families_graph()
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge disjoint paths
        edge_dpaths = list(nx.edge_disjoint_paths(G, 'Medici', 'Strozzi', **kwargs))
        assert_true(are_edge_disjoint_paths(G, edge_dpaths), msg=msg.format(flow_func.__name__))
        assert_equal(
            nx.edge_connectivity(G, 'Medici', 'Strozzi'),
            len(edge_dpaths),
            msg=msg.format(flow_func.__name__),
        )
        # node disjoint paths
        node_dpaths = list(nx.node_disjoint_paths(G, 'Medici', 'Strozzi', **kwargs))
        assert_true(are_node_disjoint_paths(G, node_dpaths), msg=msg.format(flow_func.__name__))
        assert_equal(
            nx.node_connectivity(G, 'Medici', 'Strozzi'),
            len(node_dpaths),
            msg=msg.format(flow_func.__name__),
        )
示例#32
0
class TestBetweennessCentrality(unittest.TestCase):

    Gs = [
        lecture_graph(),
        nx.florentine_families_graph(),
        nx.karate_club_graph(),
        nx.read_edgelist("subgraph.gz")
    ]

    def test_compare_our_betweenness_centrality_with_networkx(self):
        """Compare the output of our betweenness centrality algorithm with networkx's
        """
        for G in TestBetweennessCentrality.Gs:
            our_bc = bc.betweenness_centrality(G)
            nx_bc = nx.betweenness_centrality(G)

            side_by_side = zip(our_bc.items(), nx_bc.items())

            for (our_pair, our_value), (nx_pair, nx_value) in side_by_side:
                self.assertEqual(our_pair, nx_pair)
                self.assertAlmostEqual(our_value, nx_value, places=6)
示例#33
0
def initialize():
    global g, nextg

    # g=nx.Graph()
    # g.add_edges_from([(0,1),(1,2),(2,0),(2,3)])

    # g = nx.karate_club_graph()
    # g=nx.path_graph(12)
    # g=nx.cycle_graph(12)
    # g=nx.petersen_graph()
    g = nx.florentine_families_graph()

    # g.pos = nx.spring_layout(g)
    g.pos = graphviz_layout(g)

    for i in g.nodes_iter():
        if i != g.nodes()[0]:
            g.node[i]['state'] = random()  #0.41
        else:
            g.node[i]['state'] = 1.
    nextg = g.copy()
示例#34
0
def generate_networks(io_h):
    # Dictionary for storing networks with names for dataset
    list_of_networks = {}
    n_nodes = 1000
    n_edges = np.arange(1, 5, 1)
    connection_probs = np.arange(0.5, 0.7, 0.1)

    processed_networks = io_h.get_ignore_list()

    print('Generating Famous social networks')
    # Append famous social networks to list
    n_name = 'kartae_club'
    if n_name not in processed_networks:
        list_of_networks[n_name] = nx.karate_club_graph()
    n_name = 'davis_southern_women_graph'
    if n_name not in processed_networks:
        list_of_networks[n_name] = nx.davis_southern_women_graph()
    n_name = 'florentine_families_graph'
    if n_name not in processed_networks:
        list_of_networks[n_name] = nx.florentine_families_graph()

    print('Generating Barabasi network')
    for connection in n_edges:
        # Append Barabasi Graph
        n_name = '_'.join(['barabasi_albert_graph', str(connection)])
        if n_name not in processed_networks:
            print('Generating ', n_name)
            list_of_networks[n_name] = nx.barabasi_albert_graph(
                n_nodes, connection)

    print('Generating Random Networks')
    # Generate random networks with connection probabilities
    for con_prob in connection_probs:
        n_name = '_'.join(['erdos_renyi_graph', '{:.1f}'.format(con_prob)])
        if n_name not in processed_networks:
            print('Generating {}'.format(n_name))
            list_of_networks[n_name] = nx.erdos_renyi_graph(n_nodes, con_prob)
    print('Finished Generating Networks')
    return list_of_networks
示例#35
0
import networkx as nx
import matplotlib.pylab as plt
from plot_multigraph import plot_multigraph

graphs = [
  ('karate_club_graph', nx.karate_club_graph()),
  ('davis_southern_women_graph', nx.davis_southern_women_graph()),
  ('florentine_families_graph', nx.florentine_families_graph()),
]

plot_multigraph(graphs, 2, 2, node_size=50)
plt.savefig('graphs/social.png')
示例#36
0
	def __init__(self):
		BaseGraph.__init__(self)
		self.structure = nx.florentine_families_graph()
示例#37
0
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()
示例#38
0
#Note that module.py needs to be imported in order to run this

from  __future__ import division
import module
import math
import networkx as nx
from numpy import mean
from numpy import std
from pybrain.optimization import CMAES
import time
start_time = time.time()

zac = nx.karate_club_graph()
#print module.rec_number(zac,0), module.rec_number(zac,1), module.rec_number(zac,2)

er = nx.florentine_families_graph()
countess = 0
def graph_function(p):
	if(p[0]<0): p[0] = p[0]*(-1)
	if(p[1]<0): p[1] = p[1]*(-1)
	if(p[2]<0): p[2] = p[2]*(-1)

	q = p[0] + p[1] + p[2]
	p[3] = p[4] = p[5] = p[6] = 0
	p[0] = p[0]/q
	p[1] = p[1]/q
	p[2] = p[2]/q

	nodes = 20
	edges = 50
	simulations = 10
示例#39
0
 def test_voterank_centrality_2(self):
     G = nx.florentine_families_graph()
     d = nx.voterank(G, 4)
     exact = ["Medici", "Strozzi", "Guadagni", "Castellani"]
     assert exact == d
示例#40
0
 def test_voterank_centrality_2(self):
     G = nx.florentine_families_graph()
     d = nx.voterank(G, 4)
     exact = ['Medici', 'Strozzi', 'Guadagni', 'Castellani']
     assert_equal(exact, d)
def utest1():
    G = NX.florentine_families_graph()
    AM = NX.to_numpy_matrix(G).tolist()
    write_jsongraph("gd1.json", adjmatrix_tojson(AM))
__author__ = 'irelos'

from DiffusionModels import con_time_SI


# test default function
import networkx
import random

# test one sources case, default setting
g = networkx.florentine_families_graph()
source = [g.nodes()[0]]
res = con_time_SI(g, source)
print res

#test three sources case, default setting
g = networkx.florentine_families_graph()
source = [g.nodes()[0],g.nodes()[1],g.nodes()[2]]
res = con_time_SI(g, source, 0, 0, True, random.random)
print res


#test two sources case, heterogeneous model
g = networkx.florentine_families_graph()
source = [g.nodes()[0],g.nodes()[1]]
for edg in g.edges():
    g.edge[edg[0]][edg[1]]['q'] = 0
    g.edge[edg[0]][edg[1]]['p'] = 1
res = con_time_SI(g, source,1, 0.5, False, random.uniform,'q','p')
print res