Example #1
0
 def test_is_chordal(self):
     assert_false(nx.is_chordal(self.non_chordal_G))
     assert_true(nx.is_chordal(self.chordal_G))
     assert_true(nx.is_chordal(self.connected_chordal_G))
     assert_true(nx.is_chordal(nx.complete_graph(3)))
     assert_true(nx.is_chordal(nx.cycle_graph(3)))
     assert_false(nx.is_chordal(nx.cycle_graph(5)))
    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)])
Example #3
0
def test_directed_node_connectivity():
    G = nx.cycle_graph(10, create_using=nx.DiGraph()) # only one direction
    D = nx.cycle_graph(10).to_directed() # 2 reciprocal edges
    assert_equal(1, approx.node_connectivity(G))
    assert_equal(1, approx.node_connectivity(G, 1, 4))
    assert_equal(2,  approx.node_connectivity(D))
    assert_equal(2,  approx.node_connectivity(D, 1, 4))
 def test_global_parameters(self):
     b,c=nx.intersection_array(nx.cycle_graph(5))
     g=nx.global_parameters(b,c)
     assert_equal(list(g),[(0, 0, 2), (1, 0, 1), (1, 1, 0)])
     b,c=nx.intersection_array(nx.cycle_graph(3))
     g=nx.global_parameters(b,c)
     assert_equal(list(g),[(0, 0, 2), (1, 1, 0)])
Example #5
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)])
Example #6
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)])
Example #7
0
 def setUp(self):
     from networkx import convert_node_labels_to_integers as cnlti
     self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1,
                       ordering="sorted")
     self.cycle = nx.cycle_graph(7)
     self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
     self.neg_weights = nx.DiGraph()
     self.neg_weights.add_edge(0, 1, weight=1)
     self.neg_weights.add_edge(0, 2, weight=3)
     self.neg_weights.add_edge(1, 3, weight=1)
     self.neg_weights.add_edge(2, 3, weight=-2)
Example #8
0
    def test_periodic(self):
        G = nx.grid_2d_graph(0, 0, periodic=True)
        assert_equal(dict(G.degree()), {})

        for m, n, H in [(2, 2, nx.cycle_graph(4)), (1, 7, nx.cycle_graph(7)),
                        (7, 1, nx.cycle_graph(7)),
                        (2, 5, nx.circular_ladder_graph(5)),
                        (5, 2, nx.circular_ladder_graph(5)),
                        (2, 4, nx.cubical_graph()),
                        (4, 2, nx.cubical_graph())]:
            G = nx.grid_2d_graph(m, n, periodic=True)
            assert_true(nx.could_be_isomorphic(G, H))
Example #9
0
    def setUp(self):
        from networkx import convert_node_labels_to_integers as cnlti

        self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
        self.cycle = nx.cycle_graph(7)
        self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
        self.XG = nx.DiGraph()
        self.XG.add_weighted_edges_from(
            [
                ("s", "u", 10),
                ("s", "x", 5),
                ("u", "v", 1),
                ("u", "x", 2),
                ("v", "y", 1),
                ("x", "u", 3),
                ("x", "v", 5),
                ("x", "y", 2),
                ("y", "s", 7),
                ("y", "v", 6),
            ]
        )
        self.MXG = nx.MultiDiGraph(self.XG)
        self.MXG.add_edge("s", "u", weight=15)
        self.XG2 = nx.DiGraph()
        self.XG2.add_weighted_edges_from(
            [[1, 4, 1], [4, 5, 1], [5, 6, 1], [6, 3, 1], [1, 3, 50], [1, 2, 100], [2, 3, 100]]
        )

        self.XG3 = nx.Graph()
        self.XG3.add_weighted_edges_from([[0, 1, 2], [1, 2, 12], [2, 3, 1], [3, 4, 5], [4, 5, 1], [5, 0, 10]])

        self.XG4 = nx.Graph()
        self.XG4.add_weighted_edges_from(
            [[0, 1, 2], [1, 2, 2], [2, 3, 1], [3, 4, 1], [4, 5, 1], [5, 6, 1], [6, 7, 1], [7, 0, 1]]
        )
        self.MXG4 = nx.MultiGraph(self.XG4)
        self.MXG4.add_edge(0, 1, weight=3)
        self.G = nx.DiGraph()  # no weights
        self.G.add_edges_from(
            [
                ("s", "u"),
                ("s", "x"),
                ("u", "v"),
                ("u", "x"),
                ("v", "y"),
                ("x", "u"),
                ("x", "v"),
                ("x", "y"),
                ("y", "s"),
                ("y", "v"),
            ]
        )
    def setUp(self):
        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.C5 = nx.cycle_graph(5)

        self.T = nx.balanced_tree(r=2, h=2)

        self.Gb = nx.DiGraph()
        self.Gb.add_edges_from([(0, 1), (0, 2), (0, 4), (2, 1),
                                (2, 3), (4, 3)])
Example #11
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]
Example #12
0
def test_tensor_product_classic_result():
    K2 = nx.complete_graph(2)
    G = nx.petersen_graph()
    G = tensor_product(G,K2)
    assert_true(nx.is_isomorphic(G,nx.desargues_graph()))

    G = nx.cycle_graph(5)
    G = tensor_product(G,K2)
    assert_true(nx.is_isomorphic(G,nx.cycle_graph(10)))

    G = nx.tetrahedral_graph()
    G = tensor_product(G,K2)
    assert_true(nx.is_isomorphic(G,nx.cubical_graph()))
Example #13
0
    def test_from_numpy_matrix_type(self):
        A = np.matrix([[1]])
        G = nx.from_numpy_matrix(A)
        assert_equal(type(G[0][0]['weight']), int)

        A = np.matrix([[1]]).astype(np.float)
        G = nx.from_numpy_matrix(A)
        assert_equal(type(G[0][0]['weight']), float)

        A = np.matrix([[1]]).astype(np.str)
        G = nx.from_numpy_matrix(A)
        assert_equal(type(G[0][0]['weight']), str)

        A = np.matrix([[1]]).astype(np.bool)
        G = nx.from_numpy_matrix(A)
        assert_equal(type(G[0][0]['weight']), bool)

        A = np.matrix([[1]]).astype(np.complex)
        G = nx.from_numpy_matrix(A)
        assert_equal(type(G[0][0]['weight']), complex)

        A = np.matrix([[1]]).astype(np.object)
        assert_raises(TypeError, nx.from_numpy_matrix, A)

        G = nx.cycle_graph(3)
        A = nx.adj_matrix(G).todense()
        H = nx.from_numpy_matrix(A)
        assert_true(all(type(m) == int and type(n) == int for m, n in H.edges()))
        H = nx.from_numpy_array(A)
        assert_true(all(type(m) == int and type(n) == int for m, n in H.edges()))
Example #14
0
 def test_multigraph(self):
     """Tests the node boundary of a multigraph."""
     G = nx.MultiGraph(list(nx.cycle_graph(5).edges()) * 2)
     S = {0, 1}
     boundary = nx.node_boundary(G, S)
     expected = {2, 4}
     assert_equal(boundary, expected)
Example #15
0
 def test_multigraph(self):
     """Tests the edge boundary of a multigraph."""
     G = nx.MultiGraph(list(nx.cycle_graph(5).edges()) * 2)
     S = {0, 1}
     boundary = list(nx.edge_boundary(G, S))
     expected = [(0, 4), (0, 4), (1, 2), (1, 2)]
     assert_equal(boundary, expected)
Example #16
0
    def test_graph(self):
        g = nx.cycle_graph(10)
        G = nx.Graph()
        G.add_nodes_from(g)
        G.add_weighted_edges_from((u, v, u) for u, v in g.edges())

        # Dict of dicts
        dod = to_dict_of_dicts(G)
        GG = from_dict_of_dicts(dod, create_using=nx.Graph())
        assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
        assert_edges_equal(sorted(G.edges()), sorted(GG.edges()))
        GW = to_networkx_graph(dod, create_using=nx.Graph())
        assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
        assert_edges_equal(sorted(G.edges()), sorted(GW.edges()))
        GI = nx.Graph(dod)
        assert_equal(sorted(G.nodes()), sorted(GI.nodes()))
        assert_equal(sorted(G.edges()), sorted(GI.edges()))

        # Dict of lists
        dol = to_dict_of_lists(G)
        GG = from_dict_of_lists(dol, create_using=nx.Graph())
        # dict of lists throws away edge data so set it to none
        enone = [(u, v, {}) for (u, v, d) in G.edges(data=True)]
        assert_nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
        assert_edges_equal(enone, sorted(GG.edges(data=True)))
        GW = to_networkx_graph(dol, create_using=nx.Graph())
        assert_nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
        assert_edges_equal(enone, sorted(GW.edges(data=True)))
        GI = nx.Graph(dol)
        assert_nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
        assert_edges_equal(enone, sorted(GI.edges(data=True)))
Example #17
0
def test_multigraph():
    G = nx.cycle_graph(4)
    M = nx.MultiGraph(G.edges())
    M.add_edges_from(G.edges())
    M.remove_edge(1, 2)
    A, B = kernighan_lin_bisection(M)
    assert_partition_equal([A, B], [{0, 1}, {2, 3}])
Example #18
0
 def test_undirected_edge_contraction(self):
     """Tests for edge contraction in an undirected graph."""
     G = nx.cycle_graph(4)
     actual = nx.contracted_edge(G, (0, 1))
     expected = nx.complete_graph(3)
     expected.add_edge(0, 0)
     assert_true(nx.is_isomorphic(actual, expected))
 def test_C4(self):
     """Edge betweenness centrality: C4"""
     G=nx.cycle_graph(4)
     b=nx.edge_betweenness_centrality(G, weight='weight', normalized=False)
     b_answer={(0, 1):2,(0, 3):2, (1, 2):2, (2, 3): 2}
     for n in sorted(G.edges()):
         assert_almost_equal(b[n],b_answer[n])
Example #20
0
def test_directed_edge_connectivity():
    G = nx.cycle_graph(10, create_using=nx.DiGraph()) # only one direction
    D = nx.cycle_graph(10).to_directed() # 2 reciprocal edges
    for flow_func in flow_funcs:
        assert_equal(1, nx.edge_connectivity(G, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
        assert_equal(1, local_edge_connectivity(G, 1, 4, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
        assert_equal(1, nx.edge_connectivity(G, 1, 4, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
        assert_equal(2, nx.edge_connectivity(D, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
        assert_equal(2, local_edge_connectivity(D, 1, 4, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
        assert_equal(2, nx.edge_connectivity(D, 1, 4, flow_func=flow_func),
                     msg=msg.format(flow_func.__name__))
Example #21
0
    def test_nonexistent_edge(self):
        """Tests that attempting to contract a non-existent edge raises an
        exception.

        """
        G = nx.cycle_graph(4)
        nx.contracted_edge(G, (0, 2))
Example #22
0
def test_cycle_graph():
    G = nx.cycle_graph(5)
    solution = [{0, 2}, {0, 3}, {1, 3}, {1, 4}, {2, 4}]
    cuts = list(nx.all_node_cuts(G))
    assert_true(len(solution) == len(cuts))
    for cut in cuts:
        assert_true(cut in solution)
Example #23
0
    def test_valid_not_path(self):
        G = nx.cycle_graph(4)
        G.add_edge(0, 4)
        G.add_edge(1, 4)
        G.add_edge(5, 2)

        assert_true(nx.is_perfect_matching(G, {(1, 4), (0, 3), (5, 2)}))
Example #24
0
def test_biconnected_component_subgraphs_cycle():
    G=nx.cycle_graph(3)
    G.add_cycle([1,3,4,5])
    G.add_edge(1,3,eattr='red')  # test copying of edge data
    G.node[1]['nattr']='blue'
    G.graph['gattr']='green'
    Gc = set(biconnected.biconnected_component_subgraphs(G))
    assert_equal(len(Gc),2)
    g1,g2=Gc
    if 0 in g1:
        assert_true(nx.is_isomorphic(g1,nx.Graph([(0,1),(0,2),(1,2)])))
        assert_true(nx.is_isomorphic(g2,nx.Graph([(1,3),(1,5),(3,4),(4,5)])))
        assert_equal(g2[1][3]['eattr'],'red')
        assert_equal(g2.node[1]['nattr'],'blue')
        assert_equal(g2.graph['gattr'],'green')
        g2[1][3]['eattr']='blue'
        assert_equal(g2[1][3]['eattr'],'blue')
        assert_equal(G[1][3]['eattr'],'red')
    else:
        assert_true(nx.is_isomorphic(g1,nx.Graph([(1,3),(1,5),(3,4),(4,5)])))
        assert_true(nx.is_isomorphic(g2,nx.Graph([(0,1),(0,2),(1,2)])))
        assert_equal(g1[1][3]['eattr'],'red')
        assert_equal(g1.node[1]['nattr'],'blue')
        assert_equal(g1.graph['gattr'],'green')
        g1[1][3]['eattr']='blue'
        assert_equal(g1[1][3]['eattr'],'blue')
        assert_equal(G[1][3]['eattr'],'red')
Example #25
0
def test_annotator():
    # making graph
    graph = nx.cycle_graph(5)
    graph.add_edge(3, 6)
    for n, d in graph.nodes(data=True):
        d['label'] = 'X'

    # annotate
    a = Annotator()
    graph = a.transform([graph], part_name='name', part_id='id').next()

    # test annotation
    cyc = 0
    other = 0
    ids = set()
    for n, d in graph.nodes(data=True):
        ids.add(d['id'][0])  # unpack because list unhashable
        if d['name'] == ['XXXXX']:
            cyc += 1
        if d['name'] == ['X']:
            other += 1

    assert cyc == 5
    assert other == 1
    assert len(ids) == 2
Example #26
0
def draw_network(request):
    G = nx.cycle_graph(24)
    pos = nx.spring_layout(G, iterations=200)
    nx.draw(G, pos, node_color=range(24), node_size=800, cmap=plt.cm.Blues)
    response =  HttpResponse(mimetype='image/png')
    plt.savefig(response, format='png')
    return response
    def test_cycle_graph(self):
        """Tests that the cycle graph on five vertices is strongly
        regular.

        """
        G = nx.cycle_graph(5)
        assert_true(is_strongly_regular(G))
def main():
    args = parse_arguments()
    # Generate graph for given parameters

    if args.cycle:
        graph = networkx.cycle_graph(args.vertices)
        graph = networkx.path_graph(args.vertices)
    elif args.star:
        graph = networkx.star_graph(args.vertices)
    elif args.wheel:
        graph = networkx.wheel_graph(args.vertices)
    elif args.ladder:
        graph = networkx.ladder_graph(args.vertices)
    elif args.fill_rate:
        if args.fill_rate > 50.0:
            graph = networkx.gnp_random_graph(args.vertices, args.fill_rate / 100.0, None, args.directed)
        else:
            graph = networkx.fast_gnp_random_graph(args.vertices, args.fill_rate / 100.0, None, args.directed)
    else:
        graph = networkx.gnm_random_graph(args.vertices, args.edges, None, args.directed)

    # Print generated graph
    print("{} {}".format(graph.number_of_nodes(), graph.number_of_edges()))
    for edge in graph.edges():
        print("{} {}".format(edge[0] + 1, edge[1] + 1))

    # Export generated graph to .png
    if args.image_path:
        export_to_png(graph, args.image_path)
 def test_C4(self):
     """Edge betweenness centrality: C4"""
     G=networkx.cycle_graph(4)
     b=edge_current_flow_subset(G,G.nodes(),G.nodes(),normalized=True)
     b_answer=edge_current_flow(G,normalized=True)
     for n in sorted(G.edges()):
         assert_almost_equal(b[n],b_answer[n])
Example #30
0
 def test_cycle(self):
     C = nx.cycle_graph(7)
     assert nx.astar_path(C, 0, 3) == [0, 1, 2, 3]
     assert nx.dijkstra_path(C, 0, 4) == [0, 6, 5, 4]
Example #31
0
 def test_cycle(self):
     n = 5
     G = nx.cycle_graph(n, create_using=nx.DiGraph())
     assert nx.dominance_frontiers(G, 0) == {i: set() for i in range(n)}
Example #32
0
def test_articulation_points_cycle():
    G = nx.cycle_graph(3)
    G.add_cycle([1, 3, 4])
    pts = set(biconnected.articulation_points(G))
    assert_equal(pts, set([1]))
def test_articulation_points_cycle():
    G = nx.cycle_graph(3)
    G.add_cycle([1, 3, 4])
    pts = set(nx.articulation_points(G))
    assert_equal(pts, {1})
Example #34
0
 def test_unweighted_digraph(self):
     G = nx.DiGraph(nx.cycle_graph(3))
     vitality = nx.closeness_vitality(G)
     assert vitality == {0: 4, 1: 4, 2: 4}
Example #35
0
 def setup_class(cls):
     cls.BB = nx.barbell_graph(4, 0)
     cls.square = nx.cycle_graph(4)
     cls.tri = nx.cycle_graph(3)
Example #36
0
import numpy as np
import networkx
import scipy
import BankNetwork
import RiskyAssets
import importlib
import matplotlib.pyplot as plt
import time
importlib.reload(BankNetwork)

testgraph = networkx.powerlaw_cluster_graph(10000, 100, 0.1)
adjacency = networkx.to_numpy_matrix(testgraph)
# networkx.draw(testgraph)

cycle = networkx.cycle_graph(10)
networkx.draw(cycle)

star = networkx.star_graph(10)
networkx.draw(star)

complete = networkx.complete_graph(10)
networkx.draw(complete)
a = networkx.to_numpy_matrix(complete)


def vec_gene(v):
    """
    Generate submatrix from vector used in the construction of the expanded adjacency matrix
    Args:
        v (numpy.ndarray) : the generating vector
    Returns:
Example #37
0
#! python
"""
Draw a graph with matplotlib, color by degree.
You must have matplotlib for this to work.
"""
__author__ = """Aric Hagberg ([email protected])"""

try:
    import matplotlib.pyplot as plt
except:
    raise 
import networkx as nx


G=nx.cycle_graph(24)
pos=nx.spring_layout(G,iterations=200)
nx.draw(G,pos,node_color=range(24),node_size=800,cmap=plt.cm.Blues)
plt.savefig("node_colormap.png") # save as png
plt.show() # display
def test_biconnected_components_cycle():
    G = nx.cycle_graph(3)
    G.add_cycle([1, 3, 4])
    answer = [{0, 1, 2}, {1, 3, 4}]
    assert_components_equal(list(nx.biconnected_components(G)), answer)
def test_is_biconnected():
    G = nx.cycle_graph(3)
    assert_true(nx.is_biconnected(G))
    G.add_cycle([1, 3, 4])
    assert_false(nx.is_biconnected(G))
Example #40
0
 def test_not_connected(self):
     G = nx.cycle_graph(4)
     G.add_cycle([5, 6, 7])
     assert_false(nx.is_distance_regular(G))
Example #41
0
 def test_unweighted(self):
     G = nx.cycle_graph(3)
     vitality = nx.closeness_vitality(G)
     assert vitality == {0: 2, 1: 2, 2: 2}
Example #42
0
def test_biconnected_components_cycle():
    G = nx.cycle_graph(3)
    G.add_cycle([1, 3, 4])
    pts = set(map(frozenset, biconnected.biconnected_components(G)))
    assert_equal(pts, set([frozenset([0, 1, 2]), frozenset([1, 3, 4])]))
Example #43
0
def generate_cycle():
    return nx.cycle_graph(random.randint(5, 15))
Example #44
0
 def test_cycle(self):
     G = nx.cycle_graph(100, create_using=nx.DiGraph())
     ok_(nx.is_semiconnected(G))
     G = nx.path_graph(100, create_using=nx.DiGraph())
     G.add_edge(0, 99)
     ok_(nx.is_semiconnected(G))
Example #45
0
 def test_cycle(self):
     G = nx.cycle_graph(3)
     assert_false(nx.is_simple_path(G, [0, 1, 2, 0]))
Example #46
0
 def test_cycle(self):
     n = 5
     G = nx.cycle_graph(n, create_using=nx.DiGraph())
     assert nx.immediate_dominators(
         G, 0) == {i: max(i - 1, 0)
                   for i in range(n)}
Example #47
0
 def test_degree_seq_c4(self):
     G = networkx.cycle_graph(4)
     degree_start = sorted(G.degree().values())
     G = double_edge_swap(G, 1, 100)
     degseq = sorted(G.degree().values())
     assert_true(degree_start == degseq)
Example #48
0
def simulate_series(simulation_data):
    disease_params = simulation_data    
    #disease_params['order'] = 1
    simulation_data['G']     = simulation_data['network_n'] # genes
    
    simulation_data['S'] = simulation_data['P']
    simulation_data['patients_number'] = simulation_data['S']    

    # make network
    if(simulation_data['network_type'] == 'BA'):
        g = nx.barabasi_albert_graph(simulation_data['network_n'], simulation_data['network_m'])
    elif(simulation_data['network_type'] == 'ER'):
        g = nx.erdos_renyi_graph(simulation_data['network_n'], simulation_data['network_p'])  
    elif(simulation_data['model'] == '2D'):
        g = nx.grid_2d_graph(simulation_data['network_x'], simulation_data['network_y'], periodic = True)
    elif(simulation_data['model']  == 'CYC'):
        g = nx.cycle_graph(simulation_data['network_n'])
    elif(simulation_data['model']  == 'REG'):
        g = nx.random_regular_graph(simulation_data['network_d'], simulation_data['network_n'])

    #neighbors_dict = all_neighbors_order(g, simulation_params['order'])
    colored_graph = color_nodes_order(g, disease_params['D'], disease_params['p'], disease_params['order'])
    #colored_graph = color_nodes_order(g, disease_params['D'], disease_params['p'], disease_params['order'])
    
    g_strip = g.copy()
        
    solitary = [ n for n,d in g_strip.degree_iter() if d == 0 ]
    g_strip.remove_nodes_from(solitary)                       
    layout = nx.spring_layout(g_strip)
    
    result = {}
    #result['layout'] = layout
    #result['g'] = g
    #result['g_strip'] = g_strip
 
    for disease_params['rho_0'] in disease_params['rho_0_list']:
        result[str(disease_params['rho_0'])] = {}

        result_disease = simulate_artificial_disease(disease_params, simulation_data, colored_graph, colored_graph)
        collective_genes = get_collective_gene_expression(simulation_data, result_disease['expressed_genes_under'], result_disease['expressed_genes_over'], result_disease['phenotype_table'], mode = 'normal')        
        filtered = collective_genes['flt']
        
        for flt in simulation_data['f_list'] :
            #result[str(disease_params['rho_0'])][str(flt)] = {}
            
            tmp_result = {}
            
            tmp_result['extracted_genes']      = list(set(filtered['dis_over_flt_' + str(flt)]))
            tmp_result['disease_genes']        = list(set(filtered['dis_under_flt_' + str(flt)]))
            tmp_result['true_poositive_genes'] = list(set(filtered['dis_under_flt_' + str(flt)]) & set(filtered['dis_over_flt_' + str(flt)]))
            tmp_result['disease_params'] = disease_params
            
            tmp_result['layout'] = layout
            tmp_result['g'] = g
            tmp_result['g_strip'] = g_strip
            
            tmp_result['rho_0'] = disease_params['rho_0']
            tmp_result['flt'] = flt
            
            
            result[str(disease_params['rho_0'])][str(flt)] = tmp_result
            
    return result
Example #49
0
def test_shortest_simple_paths_directed():
    G = nx.cycle_graph(7, create_using=nx.DiGraph())
    paths = nx.shortest_simple_paths(G, 0, 3)
    assert_equal([path for path in paths], [[0, 1, 2, 3]])
Example #50
0
 def test_cycle_numpy(self):
     dist = nx.floyd_warshall_numpy(nx.cycle_graph(7))
     assert_equal(dist[0, 3], 3)
     assert_equal(dist[0, 4], 3)
 def test_negative_weight_cycle(self):
     G = nx.cycle_graph(5, create_using=nx.DiGraph())
     G.add_edge(1, 2, weight=-7)
     for i in range(5):
         pytest.raises(nx.NetworkXUnbounded,
                       nx.single_source_bellman_ford_path, G, i)
         pytest.raises(nx.NetworkXUnbounded,
                       nx.single_source_bellman_ford_path_length, G, i)
         pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford,
                       G, i)
         pytest.raises(nx.NetworkXUnbounded,
                       nx.bellman_ford_predecessor_and_distance, G, i)
         pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, i)
     G = nx.cycle_graph(5)  # undirected Graph
     G.add_edge(1, 2, weight=-3)
     for i in range(5):
         pytest.raises(nx.NetworkXUnbounded,
                       nx.single_source_bellman_ford_path, G, i)
         pytest.raises(nx.NetworkXUnbounded,
                       nx.single_source_bellman_ford_path_length, G, i)
         pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford,
                       G, i)
         pytest.raises(nx.NetworkXUnbounded,
                       nx.bellman_ford_predecessor_and_distance, G, i)
         pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, i)
     G = nx.DiGraph([(1, 1, {"weight": -1})])
     pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford_path,
                   G, 1)
     pytest.raises(nx.NetworkXUnbounded,
                   nx.single_source_bellman_ford_path_length, G, 1)
     pytest.raises(nx.NetworkXUnbounded, nx.single_source_bellman_ford, G,
                   1)
     pytest.raises(nx.NetworkXUnbounded,
                   nx.bellman_ford_predecessor_and_distance, G, 1)
     pytest.raises(nx.NetworkXUnbounded, nx.goldberg_radzik, G, 1)
     # no negative cycle but negative weight
     G = nx.cycle_graph(5, create_using=nx.DiGraph())
     G.add_edge(1, 2, weight=-3)
     assert nx.single_source_bellman_ford_path(G, 0) == {
         0: [0],
         1: [0, 1],
         2: [0, 1, 2],
         3: [0, 1, 2, 3],
         4: [0, 1, 2, 3, 4],
     }
     assert nx.single_source_bellman_ford_path_length(G, 0) == {
         0: 0,
         1: 1,
         2: -2,
         3: -1,
         4: 0,
     }
     assert nx.single_source_bellman_ford(G, 0) == (
         {
             0: 0,
             1: 1,
             2: -2,
             3: -1,
             4: 0
         },
         {
             0: [0],
             1: [0, 1],
             2: [0, 1, 2],
             3: [0, 1, 2, 3],
             4: [0, 1, 2, 3, 4]
         },
     )
     assert nx.bellman_ford_predecessor_and_distance(G, 0) == (
         {
             0: [],
             1: [0],
             2: [1],
             3: [2],
             4: [3]
         },
         {
             0: 0,
             1: 1,
             2: -2,
             3: -1,
             4: 0
         },
     )
     assert nx.goldberg_radzik(G, 0) == (
         {
             0: None,
             1: 0,
             2: 1,
             3: 2,
             4: 3
         },
         {
             0: 0,
             1: 1,
             2: -2,
             3: -1,
             4: 0
         },
     )
Example #52
0
 def test_without_self_loops(self):
     """Tests for node contraction without preserving self-loops."""
     G = nx.cycle_graph(4)
     actual = nx.contracted_nodes(G, 0, 1, self_loops=False)
     expected = nx.complete_graph(3)
     assert_true(nx.is_isomorphic(actual, expected))
    def setup(self):
        """Creates some graphs for use in the unit tests."""
        cnlti = nx.convert_node_labels_to_integers
        self.grid = cnlti(nx.grid_2d_graph(4, 4),
                          first_label=1,
                          ordering="sorted")
        self.cycle = nx.cycle_graph(7)
        self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
        self.XG = nx.DiGraph()
        self.XG.add_weighted_edges_from([
            ("s", "u", 10),
            ("s", "x", 5),
            ("u", "v", 1),
            ("u", "x", 2),
            ("v", "y", 1),
            ("x", "u", 3),
            ("x", "v", 5),
            ("x", "y", 2),
            ("y", "s", 7),
            ("y", "v", 6),
        ])
        self.MXG = nx.MultiDiGraph(self.XG)
        self.MXG.add_edge("s", "u", weight=15)
        self.XG2 = nx.DiGraph()
        self.XG2.add_weighted_edges_from([
            [1, 4, 1],
            [4, 5, 1],
            [5, 6, 1],
            [6, 3, 1],
            [1, 3, 50],
            [1, 2, 100],
            [2, 3, 100],
        ])

        self.XG3 = nx.Graph()
        self.XG3.add_weighted_edges_from([[0, 1, 2], [1, 2, 12], [2, 3, 1],
                                          [3, 4, 5], [4, 5, 1], [5, 0, 10]])

        self.XG4 = nx.Graph()
        self.XG4.add_weighted_edges_from([
            [0, 1, 2],
            [1, 2, 2],
            [2, 3, 1],
            [3, 4, 1],
            [4, 5, 1],
            [5, 6, 1],
            [6, 7, 1],
            [7, 0, 1],
        ])
        self.MXG4 = nx.MultiGraph(self.XG4)
        self.MXG4.add_edge(0, 1, weight=3)
        self.G = nx.DiGraph()  # no weights
        self.G.add_edges_from([
            ("s", "u"),
            ("s", "x"),
            ("u", "v"),
            ("u", "x"),
            ("v", "y"),
            ("x", "u"),
            ("x", "v"),
            ("x", "y"),
            ("y", "s"),
            ("y", "v"),
        ])
Example #54
0
import seaborn
import itertools

######################################################################
# The Heisenberg Hamiltonian is defined as
#
# .. math:: \hat{H} \ = \ \displaystyle\sum_{(i, j) \in E} X_i X_j \ + \ Z_i Z_j \ + \ Y_i Y_j,
#
# where :math:`X_i`, :math:`Y_i` and :math:`Z_i` are the Pauli gates
# acting on the :math:`i`-th qubit. In addition, :math:`E` is the set of
# edges in the graph :math:`G \ = \ (V, \ E)` describing the interactions
# between the qubits. In this demonstration, we define the interaction graph to
# be the cycle graph:
#

interaction_graph = nx.cycle_graph(4)
nx.draw(interaction_graph)

######################################################################
# With this, we can calculate the matrix representation of the Heisenberg
# Hamiltonian in the computational basis:
#


def create_hamiltonian_matrix(n, graph):

    matrix = np.zeros((2**n, 2**n))

    for i in graph.edges:
        x = y = z = 1
        for j in range(0, n):
            row += str(ising_model[1][(i, j)]) + '\t'
    print(row)

input()
print("\nEmbedding logical problem into physical layout ...")

# Construct logical problem graph
prob_graph = nx.Graph()
prob_graph.add_edges_from([(1, 2), (2, 3), (1, 3)])

# Construct an embedding
embedding = {1: [1], 2: [2], 3: [3, 4]}

# Map our Ising model onto the embedding
qubits = list(i for x in embedding.values() for i in x)
target = nx.cycle_graph(qubits)
th, tJ = dwave.embedding.embed_ising(ising_model[0], ising_model[1], embedding,
                                     target)

print("\nQMI (unscaled):\n")

for i in range(1, 5):
    row = ''
    for j in range(1, 5):
        if j == i:
            row += str(th[i]) + '\t'
        elif (i, j) in tJ:
            row += str(tJ[(i, j)]) + '\t'
        else:
            row += str(0) + '\t'
    print(row)
Example #56
0
 def test_dumbbell(self):
     G = nx.cycle_graph(100, create_using=nx.DiGraph())
     G.add_edges_from((i + 100, (i + 1) % 100 + 100) for i in range(100))
     ok_(not nx.is_semiconnected(G))  # G is disconnected.
     G.add_edge(100, 99)
     ok_(nx.is_semiconnected(G))
Example #57
0
import networkx as nx
import matplotlib.pyplot as plt
import numpy

numpy.random.seed(11)

G = nx.cycle_graph(8)
E = nx.complete_bipartite_graph(4, 3)

fig, myax = plt.subplots()
nx.draw(G, ax=myax, with_labels=True)
nx.draw(E, ax=myax, node_color="y", with_labels=True)
plt.show()
Example #58
0
     rows = int(input("Number of rows: "))
     cols = int(input("Number of cols: "))
     G = nx.grid_2d_graph(rows, cols)
     pos = nx.spectral_layout(G)
     break
 elif mode == 4:
     nodes = int(input("Number of generations (<= 5): "))
     if nodes > 5:
         print("Invalid input! Please execute script again.")
         sys.exit()
     G = nx.dorogovtsev_goltsev_mendes_graph(nodes)
     pos = nx.spring_layout(G, k=1, iterations=100)
     break
 elif mode == 5:
     nodes = int(input("Number of nodes: "))
     G = nx.cycle_graph(nodes)
     pos = nx.circular_layout(G)
     break
 elif mode == 6:
     nodes = int(input("Number of nodes: "))
     G = nx.circular_ladder_graph(nodes)
     pos = nx.spring_layout(G, k=1, iterations=100)
     break
 elif mode == 7:
     nodesK = int(input("Number of nodes in candy: "))
     nodesP = int(input("Number of nodes in stick: "))
     G = nx.lollipop_graph(nodesK, nodesP)
     pos = nx.spring_layout(G, k=1, iterations=100)
     break
 elif mode == 8:
     nodes = int(input("Number of nodes: "))
Example #59
0
# needs mayavi2
# run with ipython -wthread
import networkx as nx
import numpy as np
from mayavi import mlab

# some graphs to try
#H=nx.krackhardt_kite_graph()
#H=nx.Graph();H.add_edge('a','b');H.add_edge('a','c');H.add_edge('a','d')
#H=nx.grid_2d_graph(4,5)
H = nx.cycle_graph(20)

# reorder nodes from 0,len(G)-1
G = nx.convert_node_labels_to_integers(H)
# 3d spring layout
pos = nx.spring_layout(G, dim=3)
# numpy array of x,y,z positions in sorted node order
xyz = np.array([pos[v] for v in sorted(G)])
# scalar colors
scalars = np.array(G.nodes()) + 5

mlab.figure(1, bgcolor=(0, 0, 0))
mlab.clf()

pts = mlab.points3d(xyz[:, 0],
                    xyz[:, 1],
                    xyz[:, 2],
                    scalars,
                    scale_factor=0.1,
                    scale_mode='none',
                    colormap='Blues',
 def setUp(self):
     self.P4 = nx.path_graph(4)
     self.K3 = nx.complete_bipartite_graph(3,3)
     self.C4 = nx.cycle_graph(4)
     self.davis = nx.davis_southern_women_graph()
     self.top_nodes = [n for n,d in self.davis.nodes(data=True) 
                       if d['bipartite']==0]