Пример #1
0
    def test_embeddedness(self):
        assert_equal(cb.cmty_embeddedness(gb),
                     {0:(3*4/float(3*4+1)),  1:2*3/float(2*3+1)})

        g = networkx.complete_graph(5)
        c = cmty.Communities({0:set(range(5))})
        assert_equal(c.cmty_embeddedness(g)[0],
                     1.0)

        g = networkx.path_graph(5)
        c = cmty.Communities({0:set(range(5))})
        assert_equal(c.cmty_embeddedness(g)[0],
                     1.0)

        # Singleton comm
        g = networkx.complete_graph(1)
        c = cmty.Communities({0:set(range(1))})
        assert_equal(c.cmty_embeddedness(g)[0],
                     0.0)

        # Empty comm
        g = networkx.complete_graph(0)
        c = cmty.Communities({0:set(range(0))})
        assert_equal(c.cmty_embeddedness(g)[0],
                     0.0)

        # Total embeddednesses
        ce = (4*3/(4*3+1.) * 4 + 3*2/(3*2+1.) * 3) / (4+3)
        assert_equal(cb.tot_embeddedness(gb), ce)
Пример #2
0
def test_cmty_graph():
    # Test cmty_graph:
    g = networkx.complete_graph(7)
    g.remove_edge(3, 5)
    g.remove_edge(1, 2)
    cmtys = cmty.Communities({0:set((0,1,2)), 1:set((3,4)), 'a':set((5,6))})
    cmty_graph = cmtys.cmty_graph(g)
    assert cmty_graph.node[0]['size'] == 3           # number of nodes
    assert cmty_graph.node[0]['weight'] == 2  # edges within cmty
    assert cmty_graph.node['a']['size'] == 2
    assert cmty_graph.node['a']['weight'] == 1
    assert cmty_graph[0][1]['weight'] == 6    # edges between
    assert cmty_graph[1]['a']['weight'] == 3
    assert cmty_graph['a'][0]['weight'] == 6

    # Test cmty_graph on directed graph:
    g = networkx.complete_graph(7, create_using=networkx.DiGraph())
    g.remove_edge(3, 5)
    g.remove_edge(1, 2)
    cmtys = cmty.Communities({0:set((0,1,2)), 1:set((3,4)), 'a':set((5,6))})
    cmty_graph = cmtys.cmty_graph(g)
    assert cmty_graph.node[0]['size'] == 3       # number of nodes
    assert cmty_graph.node[0]['weight'] == 5     # edges within cmty
    assert cmty_graph.node['a']['size'] == 2
    assert cmty_graph.node['a']['weight'] == 2
    assert cmty_graph[0][1]['weight'] == 6     # edges between
    assert cmty_graph[1][0]['weight'] == 6
    assert cmty_graph[1]['a']['weight'] == 3
    assert cmty_graph['a'][1]['weight'] == 4
    assert cmty_graph['a'][0]['weight'] == 6
    assert cmty_graph[0]['a']['weight'] == 6
Пример #3
0
 def test_complete_subgraph(self):
     # Subgraph of a complete graph is a complete graph
     K1 = nx.complete_graph(1)
     K3 = nx.complete_graph(3)
     K5 = nx.complete_graph(5)
     H = K5.subgraph([1, 2, 3])
     assert_true(nx.is_isomorphic(H, K3))
Пример #4
0
def test_white_harary_paper():
    # Figure 1b white and harary (2001)
    # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
    # A graph with high adhesion (edge connectivity) and low cohesion
    # (node connectivity)
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.remove_node(7)
    for i in range(4, 7):
        G.add_edge(0, i)
    G = nx.disjoint_union(G, nx.complete_graph(4))
    G.remove_node(G.order() - 1)
    for i in range(7, 10):
        G.add_edge(0, i)
    for flow_func in flow_funcs:
        kwargs = dict(flow_func=flow_func)
        # edge cuts
        edge_cut = nx.minimum_edge_cut(G, **kwargs)
        assert_equal(3, len(edge_cut), msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_edges_from(edge_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
        # node cuts
        node_cut = nx.minimum_node_cut(G, **kwargs)
        assert_equal(set([0]), node_cut, msg=msg.format(flow_func.__name__))
        H = G.copy()
        H.remove_nodes_from(node_cut)
        assert_false(nx.is_connected(H), msg=msg.format(flow_func.__name__))
Пример #5
0
def test_cartesian_product_null():
    null=nx.null_graph()
    empty10=nx.empty_graph(10)
    K3=nx.complete_graph(3)
    K10=nx.complete_graph(10)
    P3=nx.path_graph(3)
    P10=nx.path_graph(10)
    # null graph
    G=cartesian_product(null,null)
    assert_true(nx.is_isomorphic(G,null))
    # null_graph X anything = null_graph and v.v.
    G=cartesian_product(null,empty10)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(null,K3)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(null,K10)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(null,P3)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(null,P10)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(empty10,null)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(K3,null)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(K10,null)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(P3,null)
    assert_true(nx.is_isomorphic(G,null))
    G=cartesian_product(P10,null)
    assert_true(nx.is_isomorphic(G,null))
Пример #6
0
def Type2AlmostCompleteGraph(n, m):
    if (BinomialCoefficient(n - 2, 2) + 4 <= m) and (m <= BinomialCoefficient(n - 1, 2) + 1):
        first_candidate = nx.complete_graph(n - 2)
        remaining_edges = m - BinomialCoefficient(n - 2, 2)
        first_candidate.add_edge(n - 2, 0)
        first_candidate.add_edge(n - 2, 1)
        for vertex_index in range(remaining_edges - 2):
            first_candidate.add_edge(n - 1, vertex_index)
        first_coefficient = nx.average_clustering(first_candidate)

        second_candidate = nx.complete_graph(n - 2)
        second_candidate.add_edge(n - 2, n - 1)
        remaining_edges = m - BinomialCoefficient(n - 2, 2) - 1
        number_of_common_neighbors = remaining_edges / 2
        for vertex_index in range(number_of_common_neighbors):
            second_candidate.add_edge(vertex_index, n - 2)
            second_candidate.add_edge(vertex_index, n - 1)
        if (remaining_edges - 2 * number_of_common_neighbors) == 1:
            second_candidate.add_edge(vertex_index + 1, n - 2)
        second_coefficient = nx.average_clustering(second_candidate)

        if first_coefficient > second_coefficient:
            G = first_candidate.copy()
        else:
            G = second_candidate.copy()
        return G
Пример #7
0
def test_holme():

    for N in (5, 10, 15):
        for m in (1, 2, 3, 4):
            m0 = max(3, m+1)    # must reproduce logic of the model.
            g = HolmeGraph.get(N=N, m=m, Pt=1, m0=m0)
            assert_equal(g.number_of_edges(),   (N-m0)*m)

    for N in (5, 10, 15):
        for m in (1, 2, 3, 4):
            m0 = max(3, m+1)    # must reproduce logic of the model.
            g = HolmeGraph.get(N=N, m=m, Pt=.5, m0=m0)
            assert_equal(g.number_of_edges(),   (N-m0)*m)


    # Should return itself
    g0 = networkx.complete_graph(5)
    g = HolmeGraph.get(N=5, m=3, Pt=1, g0=g0)
    assert_equal(networkx.triangles(g), dict((i,4*3/2) for i in range(5)))

    # Test number of triangles created for new nodes.
    g0 = networkx.complete_graph(5)
    g = HolmeGraph.get(N=6, m=3, Pt=1, g0=g0)
    assert_equal(networkx.triangles(g)[5], 3)

    g0 = networkx.complete_graph(6)
    g = HolmeGraph.get(N=7, m=3, Pt=1, g0=g0)
    assert_equal(networkx.triangles(g)[6], 3)

    # Test number of triangles created for new nodes.
    def _make():
        g = HolmeGraph.get(N=6, m=3, m0=5, Pt=0)
        return networkx.triangles(g)
    sizes = [_make() for _ in range(10)]
    assert_true(any(_[5]==0 for _ in sizes))
Пример #8
0
    def test_sld(self):
        assert_equal(cb.cmty_scaledlinkdensities(gb),
                     {0:4,  1:3})

        g = networkx.complete_graph(5)
        c = cmty.Communities({0:set(range(5))})
        assert_equal(c.cmty_scaledlinkdensities(g)[0],   5)

        g = networkx.path_graph(5)
        c = cmty.Communities({0:set(range(5))})
        assert_equal(c.cmty_scaledlinkdensities(g)[0],   2)

        # Singleton comm
        g = networkx.complete_graph(1)
        c = cmty.Communities({0:set(range(1))})
        assert_equal(c.cmty_scaledlinkdensities(g)[0],   0.0)

        # Empty comm
        g = networkx.complete_graph(0)
        c = cmty.Communities({0:set(range(0))})
        assert_equal(c.cmty_scaledlinkdensities(g)[0],   0.0)

        # Total SLD
        ce = (4 * 4 + 3 * 3) / float(4+3)
        assert_equal(cb.tot_scaledlinkdensity(gb), ce)
Пример #9
0
def test_merge_graphs_adding_special_attributes():
    mother_dag = nx.complete_graph(4)
    new_dag = add_subgraph_specific_attributes_to_graph(
        mother_graph=mother_dag,
        children_graphs_with_attrs=[(nx.complete_graph(2), {'pair': True}),
                                    (nx.complete_graph(3), {'triple': True})]
    )
    for n in new_dag.nodes():
        print(n, new_dag.node[n])
    for s, t in new_dag.edges():
        print(s, t, new_dag[s][t])

    assert_true(new_dag.node[0]['pair'])
    assert_true(new_dag.node[0]['triple'])
    assert_true(new_dag.node[1]['pair'])
    assert_true(new_dag.node[1]['triple'])

    assert_true(new_dag[0][1]['pair'])
    assert_true(new_dag[0][1]['triple'])
    
    assert_true('triple' in new_dag[0][1])
    assert_false('pair' in new_dag[1][2])

    assert_false('pair' in new_dag[3])
    assert_false('triple' in new_dag[3])
Пример #10
0
def torrents_and_ferraro_graph():
    G = nx.convert_node_labels_to_integers(nx.grid_graph([5, 5]),
                                           label_attribute='labels')
    rlabels = nx.get_node_attributes(G, 'labels')
    labels = {v: k for k, v in rlabels.items()}

    for nodes in [(labels[(0, 4)], labels[(1, 4)]),
                  (labels[(3, 4)], labels[(4, 4)])]:
        new_node = G.order() + 1
        # Petersen graph is triconnected
        P = nx.petersen_graph()
        G = nx.disjoint_union(G, P)
        # Add two edges between the grid and P
        G.add_edge(new_node + 1, nodes[0])
        G.add_edge(new_node, nodes[1])
        # K5 is 4-connected
        K = nx.complete_graph(5)
        G = nx.disjoint_union(G, K)
        # Add three edges between P and K5
        G.add_edge(new_node + 2, new_node + 11)
        G.add_edge(new_node + 3, new_node + 12)
        G.add_edge(new_node + 4, new_node + 13)
        # Add another K5 sharing a node
        G = nx.disjoint_union(G, K)
        nbrs = G[new_node + 10]
        G.remove_node(new_node + 10)
        for nbr in nbrs:
            G.add_edge(new_node + 17, nbr)
        # Commenting this makes the graph not biconnected !!
        # This stupid mistake make one reviewer very angry :P
        G.add_edge(new_node + 16, new_node + 8)

    for nodes in [(labels[(0, 0)], labels[(1, 0)]),
                  (labels[(3, 0)], labels[(4, 0)])]:
        new_node = G.order() + 1
        # Petersen graph is triconnected
        P = nx.petersen_graph()
        G = nx.disjoint_union(G, P)
        # Add two edges between the grid and P
        G.add_edge(new_node + 1, nodes[0])
        G.add_edge(new_node, nodes[1])
        # K5 is 4-connected
        K = nx.complete_graph(5)
        G = nx.disjoint_union(G, K)
        # Add three edges between P and K5
        G.add_edge(new_node + 2, new_node + 11)
        G.add_edge(new_node + 3, new_node + 12)
        G.add_edge(new_node + 4, new_node + 13)
        # Add another K5 sharing two nodes
        G = nx.disjoint_union(G, K)
        nbrs = G[new_node + 10]
        G.remove_node(new_node + 10)
        for nbr in nbrs:
            G.add_edge(new_node + 17, nbr)
        nbrs2 = G[new_node + 9]
        G.remove_node(new_node + 9)
        for nbr in nbrs2:
            G.add_edge(new_node + 18, nbr)
    return G
Пример #11
0
    def test_bellman_ford(self):
        # single node graph
        G = nx.DiGraph()
        G.add_node(0)
        assert_equal(nx.bellman_ford(G, 0), ({0: None}, {0: 0}))
        assert_raises(KeyError, nx.bellman_ford, G, 1)

        # negative weight cycle
        G = nx.cycle_graph(5, create_using=nx.DiGraph())
        G.add_edge(1, 2, weight=-7)
        for i in range(5):
            assert_raises(nx.NetworkXUnbounded, nx.bellman_ford, G, i)
        G = nx.cycle_graph(5)  # undirected Graph
        G.add_edge(1, 2, weight=-3)
        for i in range(5):
            assert_raises(nx.NetworkXUnbounded, nx.bellman_ford, G, i)
        # no negative cycle but negative weight
        G = nx.cycle_graph(5, create_using=nx.DiGraph())
        G.add_edge(1, 2, weight=-3)
        assert_equal(nx.bellman_ford(G, 0), ({0: None, 1: 0, 2: 1, 3: 2, 4: 3}, {0: 0, 1: 1, 2: -2, 3: -1, 4: 0}))

        # not connected
        G = nx.complete_graph(6)
        G.add_edge(10, 11)
        G.add_edge(10, 12)
        assert_equal(
            nx.bellman_ford(G, 0), ({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1})
        )

        # not connected, with a component not containing the source that
        # contains a negative cost cycle.
        G = nx.complete_graph(6)
        G.add_edges_from([("A", "B", {"load": 3}), ("B", "C", {"load": -10}), ("C", "A", {"load": 2})])
        assert_equal(
            nx.bellman_ford(G, 0, weight="load"),
            ({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}),
        )

        # multigraph
        P, D = nx.bellman_ford(self.MXG, "s")
        assert_equal(P["v"], "u")
        assert_equal(D["v"], 9)
        P, D = nx.bellman_ford(self.MXG4, 0)
        assert_equal(P[2], 1)
        assert_equal(D[2], 4)

        # other tests
        (P, D) = nx.bellman_ford(self.XG, "s")
        assert_equal(P["v"], "u")
        assert_equal(D["v"], 9)

        G = nx.path_graph(4)
        assert_equal(nx.bellman_ford(G, 0), ({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3}))
        assert_equal(nx.bellman_ford(G, 3), ({0: 1, 1: 2, 2: 3, 3: None}, {0: 3, 1: 2, 2: 1, 3: 0}))

        G = nx.grid_2d_graph(2, 2)
        pred, dist = nx.bellman_ford(G, (0, 0))
        assert_equal(sorted(pred.items()), [((0, 0), None), ((0, 1), (0, 0)), ((1, 0), (0, 0)), ((1, 1), (0, 1))])
        assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
Пример #12
0
def test_strong_product_size():
    K5=nx.complete_graph(5)
    P5=nx.path_graph(5)
    K3 = nx.complete_graph(3)
    G=strong_product(P5,K3)
    assert_equal(nx.number_of_nodes(G),5*3)
    G=strong_product(K3,K5)
    assert_equal(nx.number_of_nodes(G),3*5)
Пример #13
0
def original_graph():
    romeos_family = nx.complete_graph(5)
    julias_family = nx.complete_graph(5)
    # The families clash <- aw, not good!
    family_fight = nx.disjoint_union(romeos_family, julias_family)
    # ... but Romeo and Julia make love nevertheless
    family_fight.add_edge(0, 9)
    return family_fight
Пример #14
0
def test_complete():
    """ In complete graphs each node is a dominating set.
        Thus the dominating set has to be of cardinality 1.
    """
    K4 = nx.complete_graph(4)
    assert_equal(len(nx.dominating_set(K4)), 1)
    K5 = nx.complete_graph(5)
    assert_equal(len(nx.dominating_set(K5)), 1)
Пример #15
0
    def test_subgraph_centrality_big_graph(self):
        g199 = nx.complete_graph(199)
        g200 = nx.complete_graph(200)

        comm199 = nx.subgraph_centrality(g199)
        comm199_exp = nx.subgraph_centrality_exp(g199)

        comm200 = nx.subgraph_centrality(g200)
        comm200_exp = nx.subgraph_centrality_exp(g200)
Пример #16
0
def test_white_harary_2():
    # Figure 8 white and harary (2001)
    # # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.add_edge(0,4)
    # kappa <= lambda <= delta
    assert_equal(3, min(nx.core_number(G).values()))
    assert_equal(1, nx.node_connectivity(G))
    assert_equal(1, nx.edge_connectivity(G))
Пример #17
0
def test_tensor_product_size():
    P5 = nx.path_graph(5)
    K3 = nx.complete_graph(3)
    K5 = nx.complete_graph(5)

    G = nx.tensor_product(P5, K3)
    assert_equal(nx.number_of_nodes(G), 5 * 3)
    G = nx.tensor_product(K3, K5)
    assert_equal(nx.number_of_nodes(G), 3 * 5)
Пример #18
0
def test_spanner_unweighted_disconnected_graph():
    """Test spanner construction on a disconnected graph."""
    G = nx.disjoint_union(nx.complete_graph(10), nx.complete_graph(10))

    spanner = nx.spanner(G, 4, seed=_seed)
    _test_spanner(G, spanner, 4)

    spanner = nx.spanner(G, 10, seed=_seed)
    _test_spanner(G, spanner, 10)
Пример #19
0
    def build_cnf(args):
        """Build a formula to check that a graph is a ramsey number lower bound

        Arguments:
        - `args`: command line options
        """
        G=_SimpleGraphHelper.obtain_graph(args)
        return SubgraphFormula(G,[networkx.complete_graph(args.k),
                                  networkx.complete_graph(args.s)])
Пример #20
0
def test_strong_product():
    null=nx.null_graph()
    empty1=nx.empty_graph(1)
    empty10=nx.empty_graph(10)
    K2=nx.complete_graph(2)
    K3=nx.complete_graph(3)
    K5=nx.complete_graph(5)
    K10=nx.complete_graph(10)
    P2=nx.path_graph(2)
    P3=nx.path_graph(3)
    P5=nx.path_graph(5)
    P10=nx.path_graph(10)
    # null graph
    G=strong_product(null,null)
    assert_true(nx.is_isomorphic(G,null))
    # null_graph X anything = null_graph and v.v.
    G=strong_product(null,empty10)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(null,K3)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(null,K10)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(null,P3)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(null,P10)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(empty10,null)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(K3,null)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(K10,null)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(P3,null)
    assert_true(nx.is_isomorphic(G,null))
    G=strong_product(P10,null)
    assert_true(nx.is_isomorphic(G,null))

    G=strong_product(P5,K3)
    assert_equal(nx.number_of_nodes(G),5*3)
    G=strong_product(K3,K5)
    assert_equal(nx.number_of_nodes(G),3*5)

    #No classic easily found classic results for strong product

    G = nx.erdos_renyi_graph(10,2/10.)
    H = nx.erdos_renyi_graph(10,2/10.)
    GH = strong_product(G,H)

    for (u_G,u_H) in GH.nodes_iter():
        for (v_G,v_H) in GH.nodes_iter():
            if (u_G==v_G and H.has_edge(u_H,v_H)) or \
               (u_H==v_H and G.has_edge(u_G,v_G)) or \
               (G.has_edge(u_G,v_G) and H.has_edge(u_H,v_H)):
                assert_true(GH.has_edge((u_G,u_H),(v_G,v_H)))
            else:
                assert_true(not GH.has_edge((u_G,u_H),(v_G,v_H)))
Пример #21
0
    def test_bellman_ford(self):
        # single node graph
        G = nx.DiGraph()
        G.add_node(0)
        assert_equal(nx.bellman_ford(G, 0), ({0: None}, {0: 0}))

        # negative weight cycle
        G = nx.cycle_graph(5, create_using = nx.DiGraph())
        G.add_edge(1, 2, weight = -7)
        assert_raises(nx.NetworkXUnbounded, nx.bellman_ford, G, 0)
        G = nx.cycle_graph(5)
        G.add_edge(1, 2, weight = -7)
        assert_raises(nx.NetworkXUnbounded, nx.bellman_ford, G, 0)

        # not connected
        G = nx.complete_graph(6)
        G.add_edge(10, 11)
        G.add_edge(10, 12)
        assert_equal(nx.bellman_ford(G, 0),
                     ({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
                      {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))

        # not connected, with a component not containing the source that
        # contains a negative cost cycle.
        G = nx.complete_graph(6)
        G.add_edges_from([('A', 'B', {'load': 3}),
                          ('B', 'C', {'load': -10}),
                          ('C', 'A', {'load': 2})])
        assert_equal(nx.bellman_ford(G, 0, weight = 'load'),
                     ({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0},
                      {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))

        # multigraph
        P, D = nx.bellman_ford(self.MXG,'s')
        assert_equal(P['v'], 'u')
        assert_equal(D['v'], 9)
        P, D = nx.bellman_ford(self.MXG4, 0)
        assert_equal(P[2], 1)
        assert_equal(D[2], 4)

        # other tests
        (P,D)= nx.bellman_ford(self.XG,'s')
        assert_equal(P['v'], 'u')
        assert_equal(D['v'], 9)

        G=nx.path_graph(4)
        assert_equal(nx.bellman_ford(G,0),
                     ({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3}))
        G=nx.grid_2d_graph(2,2)
        pred,dist=nx.bellman_ford(G,(0,0))
        assert_equal(sorted(pred.items()),
                     [((0, 0), None), ((0, 1), (0, 0)), 
                      ((1, 0), (0, 0)), ((1, 1), (0, 1))])
        assert_equal(sorted(dist.items()),
                     [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
Пример #22
0
 def setUp(self):
     self.null = nx.null_graph()
     self.P1 = cnlti(nx.path_graph(1), first_label=1)
     self.P3 = cnlti(nx.path_graph(3), first_label=1)
     self.P10 = cnlti(nx.path_graph(10), first_label=1)
     self.K1 = cnlti(nx.complete_graph(1), first_label=1)
     self.K3 = cnlti(nx.complete_graph(3), first_label=1)
     self.K4 = cnlti(nx.complete_graph(4), first_label=1)
     self.K5 = cnlti(nx.complete_graph(5), first_label=1)
     self.K10 = cnlti(nx.complete_graph(10), first_label=1)
     self.G = nx.Graph
Пример #23
0
def test_inter_community_edges_with_digraphs():
    G = nx.complete_graph(2, create_using = nx.DiGraph())
    partition = [{0}, {1}]
    assert_equal(inter_community_edges(G, partition), 2)

    G = nx.complete_graph(10, create_using = nx.DiGraph())
    partition = [{0}, {1, 2}, {3, 4, 5}, {6, 7, 8, 9}]
    assert_equal(inter_community_edges(G, partition), 70)

    G = nx.cycle_graph(4, create_using = nx.DiGraph())
    partition = [{0, 1}, {2, 3}]
    assert_equal(inter_community_edges(G, partition), 2)
Пример #24
0
    def test_is_eulerian(self):
        assert_true(is_eulerian(nx.complete_graph(5)))
        assert_true(is_eulerian(nx.complete_graph(7)))
        assert_true(is_eulerian(nx.hypercube_graph(4)))
        assert_true(is_eulerian(nx.hypercube_graph(6)))

        assert_false(is_eulerian(nx.complete_graph(4)))
        assert_false(is_eulerian(nx.complete_graph(6)))
        assert_false(is_eulerian(nx.hypercube_graph(3)))
        assert_false(is_eulerian(nx.hypercube_graph(5)))

        assert_false(is_eulerian(nx.petersen_graph()))
        assert_false(is_eulerian(nx.path_graph(4)))
Пример #25
0
    def setUp(self):
        try:
            global nx
            import networkx as nx
        except ImportError:
            raise SkipTest('networkx not available.')

        self.planar=[]
        self.planar.extend([nx.path_graph(5),
                            nx.complete_graph(4)])
        self.non_planar=[]
        self.non_planar.extend([nx.complete_graph(5),
                                nx.complete_bipartite_graph(3,3)])
Пример #26
0
 def setUp(self):
     self.path = nx.path_graph(7)
     self.directed_path = nx.path_graph(7, create_using=nx.DiGraph())
     self.cycle = nx.cycle_graph(7)
     self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
     self.gnp = nx.gnp_random_graph(30, 0.1)
     self.directed_gnp = nx.gnp_random_graph(30, 0.1, directed=True)
     self.K20 = nx.complete_graph(20)
     self.K10 = nx.complete_graph(10)
     self.K5 = nx.complete_graph(5)
     self.G_list = [self.path, self.directed_path, self.cycle,
         self.directed_cycle, self.gnp, self.directed_gnp, self.K10, 
         self.K5, self.K20]
Пример #27
0
def test_white_harary1():
    # Figure 1b white and harary (2001)
    # A graph with high adhesion (edge connectivity) and low cohesion
    # (node connectivity)
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.remove_node(7)
    for i in range(4,7):
        G.add_edge(0,i)
    G = nx.disjoint_union(G, nx.complete_graph(4))
    G.remove_node(G.order()-1)
    for i in range(7,10):
        G.add_edge(0,i)
    assert_equal(1, approx.node_connectivity(G))
Пример #28
0
 def test_contract_selfloop_graph(self):
     """Tests for node contraction when nodes have selfloops."""
     G = nx.cycle_graph(4)
     G.add_edge(0, 0)
     actual = nx.contracted_nodes(G, 0, 1)
     expected = nx.complete_graph([0, 2, 3])
     expected.add_edge(0, 0)
     expected.add_edge(0, 0)
     assert_edges_equal(actual.edges, expected.edges)
     actual = nx.contracted_nodes(G, 1, 0)
     expected = nx.complete_graph([1, 2, 3])
     expected.add_edge(1, 1)
     expected.add_edge(1, 1)
     assert_edges_equal(actual.edges, expected.edges)
Пример #29
0
    def test_parameters(self):
        for base in range(2, 5):
            for template in range(2, 5):
                parameters = ["cnfgen", "-q", "subgraph", "--complete", base, "--completeT", template]
                G = nx.complete_graph(base)
                T = nx.complete_graph(template)
                F = SubgraphFormula(G, [T])
                self.checkFormula(sys.stdin, F, parameters)

                parameters = ["cnfgen", "-q", "subgraph", "--complete", base, "--emptyT", template]
                G = nx.complete_graph(base)
                T = nx.empty_graph(template)
                F = SubgraphFormula(G, [T])
                self.checkFormula(sys.stdin, F, parameters)
Пример #30
0
def test_white_harary_1():
    # Figure 1b white and harary (2001)
    # # http://eclectic.ss.uci.edu/~drwhite/sm-w23.PDF
    # A graph with high adhesion (edge connectivity) and low cohesion
    # (vertex connectivity)
    G = nx.disjoint_union(nx.complete_graph(4), nx.complete_graph(4))
    G.remove_node(7)
    for i in range(4,7):
        G.add_edge(0,i)
    G = nx.disjoint_union(G, nx.complete_graph(4))
    G.remove_node(G.order()-1)
    for i in range(7,10):
        G.add_edge(0,i)
    assert_equal(1, nx.node_connectivity(G))
    assert_equal(3, nx.edge_connectivity(G))
Пример #31
0
from parse import write_input_file, validate_file
import networkx as nx
import random

if __name__ == '__main__':
  G_small = nx.complete_graph(24)
  for (u, v) in G_small.edges():
    G_small.edges[u,v]['weight'] = round(random.uniform(0.0, 100.0), 3)
  
  G_medium = nx.complete_graph(48)
  for (u, v) in G_medium.edges():
    G_medium.edges[u,v]['weight'] = round(random.uniform(0.0, 100.0), 3)
  
  G_large = nx.complete_graph(99)
  for (u, v) in G_large.edges():
    G_large.edges[u,v]['weight'] = round(random.uniform(0.0, 100.0), 3)
  
  write_input_file(G_small, "/Users/narenyenuganti/Desktop/170Proj/25.in")
  write_input_file(G_medium, "/Users/narenyenuganti/Desktop/170Proj/50.in")
  write_input_file(G_large, "/Users/narenyenuganti/Desktop/170Proj/100.in") 

  if (validate_file("/Users/narenyenuganti/Desktop/170Proj/25.in") == False): 
    raise Exception("incorrect format for 25.in")
  if (validate_file("/Users/narenyenuganti/Desktop/170Proj/50.in") == False): 
    raise Exception("incorrect format for 50.in")
  if (validate_file("/Users/narenyenuganti/Desktop/170Proj/100.in") == False): 
    raise Exception("incorrect format for 100.in")
Пример #32
0
def dummy_graph_data():
    return networkx.complete_graph(3)
Пример #33
0
def test_hamiltonian_path():
    from itertools import permutations
    G = nx.complete_graph(4)
    paths = [list(p) for p in hamiltonian_path(G, 0)]
    exact = [[0] + list(p) for p in permutations([1, 2, 3], 3)]
    assert_equal(sorted(paths), sorted(exact))
Пример #34
0
 def test_complete_graph(self):
     graph = nx.complete_graph(30)
     # this should return the entire graph
     mc = max_clique(graph)
     assert 30 == len(mc)
Пример #35
0
m = 22002

print "Creating Gnm Graph..."
gnm = nx.gnm_random_graph(n, m)
print len(gnm.nodes())
print len(gnm.edges())

#Real World Autonomous System Network
print "Reading Real-World graph..."
rw = nx.read_adjlist("oregon1_010331.txt.gz")
print len(rw.nodes())
print len(rw.edges())

#Graph with preferential attachment
print 'Creating preferential attachment graph...'
pag = nx.complete_graph(40)

new_node = 40  #labeling for first node to be added
num_edges = len(pag.edges())
edges = pag.edges()
while (len(pag.nodes()) < 10670):
    if len(pag.nodes()) % 100 == 0: print len(pag.nodes())
    for i in range(2):  #creating two new edges
        #get random edge from graph
        rand_edge = edges[randint(0, len(edges) - 1)]

        #get random endpoint from the selected edge
        node = rand_edge[randint(0, 1)]

        #make edge between node and endpoint
        pag.add_edge(new_node, node)
Пример #36
0
# Daniel Hammer


# Import the necessary package
import networkx as nx

n = 4

#def graph_caller(self, graph_name):
switcher = {
        "path": nx.path_graph(n),
        "complete": nx.complete_graph(n),
        "binomial tree": nx.binomial_tree(n),
        "circular ladder": nx.circular_ladder_graph(n),
        "cycle": nx.cycle_graph(n),
        "dorogovtsev": nx.dorogovtsev_goltsev_mendes_graph(n),
        "ladder": nx.ladder_graph(n),
        "star": nx.star_graph(n),
        "wheel": nx.wheel_graph(n),
        "margulis gabber galil": nx.margulis_gabber_galil_graph(n),
        "chordal cycle": nx.chordal_cycle_graph(n),
        "hypercube": nx.hypercube_graph(n),
        "mycielski": nx.mycielski_graph(n)
        }
#    return switcher.get(graph_name,"Invalid choice")


graph_name = input("Enter a graph name to generate\n")
print(graph_name)

#G = graph_caller(graph_name)
Пример #37
0
 def test_complete_graph(self):
     cg = nx.complete_graph(5)
     mcb = minimum_cycle_basis(cg)
     assert all([len(cycle) == 3 for cycle in mcb])
Пример #38
0
def test_interface_only_target():
    G = nx.complete_graph(5)
    for interface_func in [nx.minimum_node_cut, nx.minimum_edge_cut]:
        assert_raises(nx.NetworkXError, interface_func, G, t=3)
Пример #39
0
def test_all_simple_paths_cutoff():
    G = nx.complete_graph(4)
    paths = nx.all_simple_paths(G, 0, 1, cutoff=1)
    assert_equal(set(tuple(p) for p in paths), {(0, 1)})
    paths = nx.all_simple_paths(G, 0, 1, cutoff=2)
    assert_equal(set(tuple(p) for p in paths), {(0, 1), (0, 2, 1), (0, 3, 1)})
Пример #40
0
def test_hamiltonian__edge_path():
    from itertools import permutations
    G = nx.complete_graph(4)
    paths = hamiltonian_edge_path(G, 0)
    exact = [list(pairwise([0] + list(p))) for p in permutations([1, 2, 3], 3)]
    assert sorted(exact) == [p for p in sorted(paths)]
Пример #41
0
def barabasi_albert(nodos, m):
    m0 = m + 1
    t = nodos - m0
    G = nx.complete_graph(
        m0
    )  #Creamos el grafo con una distribucion inicial de m0 nodos con al menos un enlace cada nodo
    '''
    --------------------------------------------------------------------------------------------------------------------------------------------------
                                         PREPROCESAMIENTO
    --------------------------------------------------------------------------------------------------------------------------------------------------
    '''
    for i in range(m0, nodos):  #añadimos los N - n0 nodos restantes
        G.add_node(i)  # añadimos el nodo nuevo queremos conecar
        sumaGradosNodos = 0

        for nodo in range(0, i):
            sumaGradosNodos += G.degree(nodo)
        #Sumamos los grados de todos los nodos que forman la red en este momento, para posteriormente calcular formula de la probablidad de conexion
        probConexion = {
        }  #Creamos un diccionario donde guardar la probabilidad de cada nodo para crear una nueva conexion con el nodo i
        #Esto metodo es conocido como Conexion preferencial ya que se conectara con nodos que tenga mas conexiones
        #probConexion -> clave: id del nodo, valor: probalid

        gradosNodos = nx.degree(
            G)  #Sacamos la lista con los grados de cada nodo
        #Llenamos el diccionario con las probabilidades de cada nodos que hay hasta este momento con la formula:
        #Pi = ki / SUM kj
        #Pi es la probabilidad de que uno de los enlaces se conecte al nodo nuevo
        # donde ki es el grado del nodo existente
        #denominador suma de los grados de la red hasta este momento
        for j in range(0, i):
            probConexion[j] = (float)(gradosNodos[j]) / sumaGradosNodos
        '''
        PARA AGRERAR ARISTAS AL NUEVO NODO USAREMOS EL METODO DE PROBABILIDADES ACUMULADAS
        Implementaremos la idea de conexion preferencial mediante este metodo. 

        Se genera un numero aleatorio [0.0, 1)
        Usaremos una nueva metrica llamada probabilidad acumulada que es la suma de las probabilidades anteriores

        Con estos dos valores podremos implementar la conexion preferencial ya que cuato mayor sea la probabilidad 
        acumulada mas conexiones tendrá. Con una probabilidad acumulada alta la ventana de posibulidades para ser escogida es mayor, en caso 
        contrario si la probabilidad acumulada es baja la venta de posibilidades es mas pequeña haciendo que sea menos probable que se escoja ese 
        nodo. 

        Ejemplo: 
        probabilidades = [0.2, 0.3, 0.5]
        probabilidadAcumulada = [0.2, 0.5, 1.0]

        Numero aleatorio de [0.0, 1.0)
        n = 0.4

        ventanas: 
        0.2: [0.0, 0.2]
        0.5: [0.0, 0,5]
        1.0: [0.0, 1.0]

        Cuanto mas grande sea la ventana, mas probable es que el numero aleatorio caiga dentro de esa ventana 
        '''

        #Vamos a crear una lista de probabilidades acumuladas, la cual contendrá tuplas.
        #Cada tupla, tendra id del nodo y la probabilidad acumulada (id,probAcumulada)
        probAcumulada = []  #lista vacia
        aux = 0
        for idNodo, probabilidad in probConexion.items():
            nodo = (
                idNodo, aux + probabilidad
            )  #creamos un elemento de la lista con la informacion necesaria
            probAcumulada.append(nodo)

            aux += probabilidad  #actualizamos lo anterior con lo actaul para la siguiente iteracion

    #--------------------------------------------------------------------------------------------------------------------------------------------------
    #                                              CREACION DE CONEXIONES
    #--------------------------------------------------------------------------------------------------------------------------------------------------

    #Ahora hay que hacer m conexiones, m aristas, con m nodos. Basandonos en los datos extraidos anteriormente
        conexiones = 0
        nodosAdded = [
        ]  #Lista de nodos selccionados para conectarlos con el nuevo nodo

        while (conexiones < m):
            n = random.random()
            actual = 0

            while (
                    actual < i and probAcumulada[actual][1] < n
            ):  # No nos pasamos del nuevo nodo y la probabilidad acumulado es menor que la n, entonces pasamos al suiente nodo candidato
                actual += 1

            idDestino = probAcumulada[actual][
                0]  # extreamos el id del nodo seleccionado para formar la conexion

            #Vamos a comprobar si idDestino no tiene conexion con el nodo nuevo
            if idDestino not in nodosAdded:
                nodosAdded.append(
                    idDestino)  # lo metemos en la lista de nodos selecionados
                G.add_edge(i, idDestino)  #añadimos la conexional grafo
                conexiones += 1

    return G
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from sys import exit
from utils import *

DISCLAIMER = -1
rg = np.random.default_rng()

nvars = 2  # number of choice variants
# ----------------------------------------------------------
# community specification
# ----------------------------------------------------------

# specify community net
net = nx.complete_graph(200)
setattr(net, 'nvars', nvars)  # associte 'nvars' with 'net'

# set parameters of community actors
for n in net:
    net.nodes[n]['rho'] = 20
    if n == 0:
        net.nodes[n]['choice'] = 0
    else:
        net.nodes[n]['choice'] = DISCLAIMER

# set parameters of community channels
for channel in net.edges:
    alice = min(channel)
    if alice == 0:
        net.edges[channel]['a'] = 1.0
Пример #43
0
 def test_ignore_selfloops(self):
     G = nx.complete_graph(5)
     G.add_edge(3, 3)
     cycle = nx_app.greedy_tsp(G)
     assert len(cycle) - 1 == len(G) == len(set(cycle))
Пример #44
0
    def test_random_graph(self):
        seed = 42
        G = nx.gnm_random_graph(100, 20, seed)
        G = nx.gnm_random_graph(100, 20, seed, directed=True)
        G = nx.dense_gnm_random_graph(100, 20, seed)

        G = nx.watts_strogatz_graph(10, 2, 0.25, seed)
        assert len(G) == 10
        assert G.number_of_edges() == 10

        G = nx.connected_watts_strogatz_graph(10, 2, 0.1, tries=10, seed=seed)
        assert len(G) == 10
        assert G.number_of_edges() == 10
        pytest.raises(nx.NetworkXError,
                      nx.connected_watts_strogatz_graph,
                      10,
                      2,
                      0.1,
                      tries=0)

        G = nx.watts_strogatz_graph(10, 4, 0.25, seed)
        assert len(G) == 10
        assert G.number_of_edges() == 20

        G = nx.newman_watts_strogatz_graph(10, 2, 0.0, seed)
        assert len(G) == 10
        assert G.number_of_edges() == 10

        G = nx.newman_watts_strogatz_graph(10, 4, 0.25, seed)
        assert len(G) == 10
        assert G.number_of_edges() >= 20

        G = nx.barabasi_albert_graph(100, 1, seed)
        G = nx.barabasi_albert_graph(100, 3, seed)
        assert G.number_of_edges() == (97 * 3)

        G = nx.barabasi_albert_graph(100, 3, seed, nx.complete_graph(5))
        assert G.number_of_edges() == (10 + 95 * 3)

        G = nx.extended_barabasi_albert_graph(100, 1, 0, 0, seed)
        assert G.number_of_edges() == 99
        G = nx.extended_barabasi_albert_graph(100, 3, 0, 0, seed)
        assert G.number_of_edges() == 97 * 3
        G = nx.extended_barabasi_albert_graph(100, 1, 0, 0.5, seed)
        assert G.number_of_edges() == 99
        G = nx.extended_barabasi_albert_graph(100, 2, 0.5, 0, seed)
        assert G.number_of_edges() > 100 * 3
        assert G.number_of_edges() < 100 * 4

        G = nx.extended_barabasi_albert_graph(100, 2, 0.3, 0.3, seed)
        assert G.number_of_edges() > 100 * 2
        assert G.number_of_edges() < 100 * 4

        G = nx.powerlaw_cluster_graph(100, 1, 1.0, seed)
        G = nx.powerlaw_cluster_graph(100, 3, 0.0, seed)
        assert G.number_of_edges() == (97 * 3)

        G = nx.random_regular_graph(10, 20, seed)

        pytest.raises(nx.NetworkXError, nx.random_regular_graph, 3, 21)
        pytest.raises(nx.NetworkXError, nx.random_regular_graph, 33, 21)

        constructor = [(10, 20, 0.8), (20, 40, 0.8)]
        G = nx.random_shell_graph(constructor, seed)

        def is_caterpillar(g):
            """
            A tree is a caterpillar iff all nodes of degree >=3 are surrounded
            by at most two nodes of degree two or greater.
            ref: http://mathworld.wolfram.com/CaterpillarGraph.html
            """
            deg_over_3 = [n for n in g if g.degree(n) >= 3]
            for n in deg_over_3:
                nbh_deg_over_2 = [
                    nbh for nbh in g.neighbors(n) if g.degree(nbh) >= 2
                ]
                if not len(nbh_deg_over_2) <= 2:
                    return False
            return True

        def is_lobster(g):
            """
            A tree is a lobster if it has the property that the removal of leaf
            nodes leaves a caterpillar graph (Gallian 2007)
            ref: http://mathworld.wolfram.com/LobsterGraph.html
            """
            non_leafs = [n for n in g if g.degree(n) > 1]
            return is_caterpillar(g.subgraph(non_leafs))

        G = nx.random_lobster(10, 0.1, 0.5, seed)
        assert max(G.degree(n) for n in G.nodes()) > 3
        assert is_lobster(G)
        pytest.raises(nx.NetworkXError, nx.random_lobster, 10, 0.1, 1, seed)
        pytest.raises(nx.NetworkXError, nx.random_lobster, 10, 1, 1, seed)
        pytest.raises(nx.NetworkXError, nx.random_lobster, 10, 1, 0.5, seed)

        # docstring says this should be a caterpillar
        G = nx.random_lobster(10, 0.1, 0.0, seed)
        assert is_caterpillar(G)

        # difficult to find seed that requires few tries
        seq = nx.random_powerlaw_tree_sequence(10, 3, seed=14, tries=1)
        G = nx.random_powerlaw_tree(10, 3, seed=14, tries=1)
Пример #45
0
def complete_graph(n):

    return nx.complete_graph(n)
Пример #46
0
def test_cutoff_zero():
    G = nx.complete_graph(4)
    paths = nx.all_simple_paths(G, 0, 3, cutoff=0)
    assert_equal(list(list(p) for p in paths), [])
    paths = nx.all_simple_paths(nx.MultiGraph(G), 0, 3, cutoff=0)
    assert_equal(list(list(p) for p in paths), [])
Пример #47
0
 def test_reverse(self):
     G = nx.complete_graph(10)
     H = G.to_directed()
     HR = H.reverse()
     assert nx.is_isomorphic(H, HR)
     assert sorted(H.edges()) == sorted(HR.edges())
Пример #48
0
 def test_complete_graph(self):
     G = nx.complete_graph(10)
     independent_set, cliques = clique_removal(G)
     assert is_independent_set(G, independent_set)
     assert all(is_clique(G, clique) for clique in cliques)
Пример #49
0
 def test_complete_directed_graph(self):
     # see table 2 in Johnson's paper
     ncircuits = [1, 5, 20, 84, 409, 2365, 16064]
     for n, c in zip(range(2, 9), ncircuits):
         G = nx.DiGraph(nx.complete_graph(n))
         assert len(list(nx.simple_cycles(G))) == c
Пример #50
0
 def gen(self):
     #G.graph = nx.barabasi_albert_graph(G.NUM_NODES,5)
     G.graph = nx.complete_graph(G.NUM_NODES)
     for i in G.graph.edges_iter():
         channel = Store(name=i)
         G.edges.append(channel)
Пример #51
0
def create_pspace_network(number_of_node):
    net = nx.complete_graph(number_of_node)
    return net
Пример #52
0
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
l = [1, 2, 3]
G.add_nodes_from(l)
G = nx.complete_graph(10)
nx.draw(G)
plt.show()
Пример #53
0
def test_all_simple_edge_paths_cutoff():
    G = nx.complete_graph(4)
    paths = nx.all_simple_edge_paths(G, 0, 1, cutoff=1)
    assert {tuple(p) for p in paths} == {((0, 1),)}
    paths = nx.all_simple_edge_paths(G, 0, 1, cutoff=2)
    assert {tuple(p) for p in paths} == {((0, 1),), ((0, 2), (2, 1)), ((0, 3), (3, 1))}
Пример #54
0
    def test_not_connected(self):
        G = nx.complete_graph(6)
        G.add_edge(10, 11)
        G.add_edge(10, 12)
        assert_equal(nx.single_source_bellman_ford_path(G, 0), {
            0: [0],
            1: [0, 1],
            2: [0, 2],
            3: [0, 3],
            4: [0, 4],
            5: [0, 5]
        })
        assert_equal(dict(nx.single_source_bellman_ford_path_length(G, 0)), {
            0: 0,
            1: 1,
            2: 1,
            3: 1,
            4: 1,
            5: 1
        })
        assert_equal(nx.single_source_bellman_ford(G, 0), ({
            0: 0,
            1: 1,
            2: 1,
            3: 1,
            4: 1,
            5: 1
        }, {
            0: [0],
            1: [0, 1],
            2: [0, 2],
            3: [0, 3],
            4: [0, 4],
            5: [0, 5]
        }))
        assert_equal(nx.bellman_ford_predecessor_and_distance(G, 0), ({
            0: [None],
            1: [0],
            2: [0],
            3: [0],
            4: [0],
            5: [0]
        }, {
            0: 0,
            1: 1,
            2: 1,
            3: 1,
            4: 1,
            5: 1
        }))
        assert_equal(nx.goldberg_radzik(G, 0), ({
            0: None,
            1: 0,
            2: 0,
            3: 0,
            4: 0,
            5: 0
        }, {
            0: 0,
            1: 1,
            2: 1,
            3: 1,
            4: 1,
            5: 1
        }))

        # not connected, with a component not containing the source that
        # contains a negative cost cycle.
        G = nx.complete_graph(6)
        G.add_edges_from([('A', 'B', {
            'load': 3
        }), ('B', 'C', {
            'load': -10
        }), ('C', 'A', {
            'load': 2
        })])
        assert_equal(nx.single_source_bellman_ford_path(G, 0, weight='load'), {
            0: [0],
            1: [0, 1],
            2: [0, 2],
            3: [0, 3],
            4: [0, 4],
            5: [0, 5]
        })
        assert_equal(
            dict(nx.single_source_bellman_ford_path_length(G, 0,
                                                           weight='load')), {
                                                               0: 0,
                                                               1: 1,
                                                               2: 1,
                                                               3: 1,
                                                               4: 1,
                                                               5: 1
                                                           })
        assert_equal(nx.single_source_bellman_ford(G, 0, weight='load'), ({
            0: 0,
            1: 1,
            2: 1,
            3: 1,
            4: 1,
            5: 1
        }, {
            0: [0],
            1: [0, 1],
            2: [0, 2],
            3: [0, 3],
            4: [0, 4],
            5: [0, 5]
        }))
        assert_equal(
            nx.bellman_ford_predecessor_and_distance(G, 0, weight='load'),
            ({
                0: [None],
                1: [0],
                2: [0],
                3: [0],
                4: [0],
                5: [0]
            }, {
                0: 0,
                1: 1,
                2: 1,
                3: 1,
                4: 1,
                5: 1
            }))
        assert_equal(nx.goldberg_radzik(G, 0, weight='load'), ({
            0: None,
            1: 0,
            2: 0,
            3: 0,
            4: 0,
            5: 0
        }, {
            0: 0,
            1: 1,
            2: 1,
            3: 1,
            4: 1,
            5: 1
        }))
Пример #55
0
def test_invalid_auxiliary():
    G = nx.complete_graph(5)
    assert_raises(nx.NetworkXError, minimum_st_node_cut, G, 0, 3,
                  auxiliary=G)
Пример #56
0
 def test_reverse(self):
     G = nx.complete_graph(10)
     H = G.to_directed()
     HR = H.reverse()
     assert_true(nx.is_isomorphic(H, HR))
     assert_equal(sorted(H.edges()), sorted(HR.edges()))
Пример #57
0
import networkx as nx
import community
import matplotlib as plt

"""
G = nx.random_graphs.powerlaw_cluster_graph(300, 1, .4)

part = community.best_partition(G)
values = [part.get(node) for node in G.nodes()]

nx.draw_spring(G, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=False)
"""
degree_sum_dict = {}
community_dict = {0:{0,1},1:{2,3}}
data_graph = nx.complete_graph(4)
for key in community_dict:
    list = community_dict[key]
    sum = 0;
    for i in list:
        sum += data_graph.degree(i);
    degree_sum_dict[key] = sum

print degree_sum_dict
Пример #58
0
 def test_star(self):
     G = nx.star_graph(5)
     L = nx.line_graph(G)
     assert_true(nx.is_isomorphic(L, nx.complete_graph(5)))
Пример #59
0
            # flake8: noqa: C501
            for i in range(len(test_item[1])):
                device_name = test_set["test_devices"][i][0]
                device = test_set["test_devices"][i][1]
                type(device).properties = PropertyMock(return_value=Expando())
                type(device).properties.service = PropertyMock(
                    return_value=Expando())
                device.properties.service.executionWindows = (
                    device._properties.service.executionWindows)
                expected = bool(test_item[1][i])
                actual = device.is_available
                assert (
                    expected == actual
                ), f"device_name: {device_name}, test_date: {test_date}, expected: {expected}, actual: {actual}"


@pytest.mark.parametrize(
    "get_device_data, expected_graph",
    [
        (MOCK_GATE_MODEL_QPU_1, nx.DiGraph([(1, 2), (1, 3)])),
        (MOCK_GATE_MODEL_QPU_2, nx.complete_graph(30, nx.DiGraph())),
        (MOCK_DWAVE_QPU, nx.DiGraph([(1, 2), (2, 3)])),
    ],
)
def test_device_topology_graph_data(get_device_data, expected_graph, arn):
    mock_session = Mock()
    mock_session.get_device.return_value = get_device_data
    mock_session.region = RIGETTI_REGION
    device = AwsDevice(arn, mock_session)
    assert nx.is_isomorphic(device.topology_graph, expected_graph)
Пример #60
0
    def test_bellman_ford(self):
        # single node graph
        G = nx.DiGraph()
        G.add_node(0)
        assert_equal(nx.bellman_ford(G, 0), ({0: None}, {0: 0}))

        # negative weight cycle
        G = nx.cycle_graph(5, create_using=nx.DiGraph())
        G.add_edge(1, 2, weight=-7)
        assert_raises(nx.NetworkXError, nx.bellman_ford, G, 0)
        G = nx.cycle_graph(5)
        G.add_edge(1, 2, weight=-7)
        assert_raises(nx.NetworkXError, nx.bellman_ford, G, 0)

        # not connected
        G = nx.complete_graph(6)
        G.add_edge(10, 11)
        G.add_edge(10, 12)
        assert_equal(nx.bellman_ford(G, 0), ({
            0: None,
            1: 0,
            2: 0,
            3: 0,
            4: 0,
            5: 0
        }, {
            0: 0,
            1: 1,
            2: 1,
            3: 1,
            4: 1,
            5: 1
        }))

        # not connected, with a component not containing the source that
        # contains a negative cost cycle.
        G = nx.complete_graph(6)
        G.add_edges_from([('A', 'B', {
            'load': 3
        }), ('B', 'C', {
            'load': -10
        }), ('C', 'A', {
            'load': 2
        })])
        assert_equal(nx.bellman_ford(G, 0, weight='load'), ({
            0: None,
            1: 0,
            2: 0,
            3: 0,
            4: 0,
            5: 0
        }, {
            0: 0,
            1: 1,
            2: 1,
            3: 1,
            4: 1,
            5: 1
        }))

        # multigraph
        P, D = nx.bellman_ford(self.MXG, 's')
        assert_equal(P['v'], 'u')
        assert_equal(D['v'], 9)
        P, D = nx.bellman_ford(self.MXG4, 0)
        assert_equal(P[2], 1)
        assert_equal(D[2], 4)

        # other tests
        (P, D) = nx.bellman_ford(self.XG, 's')
        assert_equal(P['v'], 'u')
        assert_equal(D['v'], 9)

        G = nx.path_graph(4)
        assert_equal(nx.bellman_ford(G, 0), ({
            0: None,
            1: 0,
            2: 1,
            3: 2
        }, {
            0: 0,
            1: 1,
            2: 2,
            3: 3
        }))
        G = nx.grid_2d_graph(2, 2)
        pred, dist = nx.bellman_ford(G, (0, 0))
        assert_equal(sorted(pred.items()), [((0, 0), None), ((0, 1), (0, 0)),
                                            ((1, 0), (0, 0)),
                                            ((1, 1), (0, 1))])
        assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1),
                                            ((1, 0), 1), ((1, 1), 2)])