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
示例#2
0
    def test_generate_sparse6(self):
        # Checked against sage encoder
        assert_equal(nx.generate_sparse6(nx.empty_graph(0)), '>>sparse6<<:?')
        assert_equal(nx.generate_sparse6(nx.empty_graph(1)), '>>sparse6<<:@')
        assert_equal(nx.generate_sparse6(nx.empty_graph(5)), '>>sparse6<<:D')
        assert_equal(nx.generate_sparse6(nx.empty_graph(68)),
                     '>>sparse6<<:~?@C')
        assert_equal(nx.generate_sparse6(nx.empty_graph(258049)),
                     '>>sparse6<<:~~???~?@')

        G1 = nx.complete_graph(4)
        assert_equal(nx.generate_sparse6(G1, header=True),
                     '>>sparse6<<:CcKI')
        assert_equal(nx.generate_sparse6(G1, header=False), ':CcKI')

        # Padding testing
        assert_equal(nx.generate_sparse6(nx.path_graph(4), header=False),
                     ':Cdv')
        assert_equal(nx.generate_sparse6(nx.path_graph(5), header=False),
                     ':DaYn')
        assert_equal(nx.generate_sparse6(nx.path_graph(6), header=False),
                     ':EaYnN')
        assert_equal(nx.generate_sparse6(nx.path_graph(7), header=False),
                     ':FaYnL')
        assert_equal(nx.generate_sparse6(nx.path_graph(8), header=False),
                     ':GaYnLz')
示例#3
0
 def test_single_nodes(self):
     G = nx.path_graph(1)
     vpos = nx.shell_layout(G)
     assert(vpos[0].any() == False)
     G = nx.path_graph(3)
     vpos = nx.shell_layout(G, [[0], [1,2]])
     assert(vpos[0].any() == False)
示例#4
0
def test_set_edge_attributes_multi():
    graphs = [nx.MultiGraph(), nx.MultiDiGraph()]
    for G in graphs:
        # Test single value
        G = nx.path_graph(3, create_using=G)
        attr = 'hello'
        vals = 3
        nx.set_edge_attributes(G, vals, attr)
        assert_equal(G[0][1][0][attr], vals)
        assert_equal(G[1][2][0][attr], vals)

        # Test multiple values
        G = nx.path_graph(3, create_using=G)
        attr = 'hi'
        edges = [(0, 1, 0), (1, 2, 0)]
        vals = dict(zip(edges, range(len(edges))))
        nx.set_edge_attributes(G, vals, attr)
        assert_equal(G[0][1][0][attr], 0)
        assert_equal(G[1][2][0][attr], 1)

        # Test dictionary of dictionaries
        G = nx.path_graph(3, create_using=G)
        d = {'hi': 0, 'hello': 200}
        edges = [(0, 1, 0)]
        vals = dict.fromkeys(edges, d)
        nx.set_edge_attributes(G, vals)
        assert_equal(G[0][1][0]['hi'], 0)
        assert_equal(G[0][1][0]['hello'], 200)
        assert_equal(G[1][2][0], {})
示例#5
0
def test_set_node_attributes():
    graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
    for G in graphs:
        # Test single value
        G = nx.path_graph(3, create_using=G)
        vals = 100
        attr = 'hello'
        nx.set_node_attributes(G, vals, attr)
        assert_equal(G.nodes[0][attr], vals)
        assert_equal(G.nodes[1][attr], vals)
        assert_equal(G.nodes[2][attr], vals)

        # Test dictionary
        G = nx.path_graph(3, create_using=G)
        vals = dict(zip(sorted(G.nodes()), range(len(G))))
        attr = 'hi'
        nx.set_node_attributes(G, vals, attr)
        assert_equal(G.nodes[0][attr], 0)
        assert_equal(G.nodes[1][attr], 1)
        assert_equal(G.nodes[2][attr], 2)

        # Test dictionary of dictionaries
        G = nx.path_graph(3, create_using=G)
        d = {'hi': 0, 'hello': 200}
        vals = dict.fromkeys(G.nodes(), d)
        vals.pop(0)
        nx.set_node_attributes(G, vals)
        assert_equal(G.nodes[0], {})
        assert_equal(G.nodes[1]["hi"], 0)
        assert_equal(G.nodes[2]["hello"], 200)
示例#6
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))
示例#7
0
    def setup(self):
        self.G = nx.path_graph(9)
        self.DG = nx.path_graph(9, create_using=nx.DiGraph())
        self.eview = nx.EdgeView

        def modify_edge(G, e, **kwds):
            G._adj[e[0]][e[1]].update(kwds)
        self.modify_edge = modify_edge
示例#8
0
 def test_average_shortest_path(self):
     l=nx.average_shortest_path_length(self.cycle)
     assert_almost_equal(l,2)
     l=nx.average_shortest_path_length(self.cycle,weighted=True)
     assert_almost_equal(l,2)
     l=nx.average_shortest_path_length(nx.path_graph(5))
     assert_almost_equal(l,2)
     l=nx.average_shortest_path_length(nx.path_graph(5),weighted=True)
     assert_almost_equal(l,2)
示例#9
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)))
示例#10
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
示例#11
0
def CreateGraph(data):
    n = len(data)
    G = nx.Graph()
    nx.path_graph(n, G)

    for row in range(n):
        for column in range(n):
            weight = data[row][column]
            if(weight != 0):
                G.add_edge(row, column, weight= weight)
    return G
示例#12
0
 def test_degree_graph(self):
     P3 = nx.path_graph(3)
     P5 = nx.path_graph(5)
     # silently ignore nodes not in P3
     assert_equal(dict(d for n, d in P3.degree(['A', 'B'])), {})
     # nbunch can be a graph
     assert_equal(sorted(d for n, d in P5.degree(P3)), [1, 2, 2])
     # nbunch can be a graph thats way to big
     assert_equal(sorted(d for n, d in P3.degree(P5)), [1, 1, 2])
     assert_equal(list(P5.degree([])), [])
     assert_equal(dict(P5.degree([])), {})
示例#13
0
def test_cartesian_product_classic():
    # test some classic product graphs
    P2 = nx.path_graph(2)
    P3 = nx.path_graph(3)
    # cube = 2-path X 2-path
    G=cartesian_product(P2,P2)
    G=cartesian_product(P2,G)
    assert_true(nx.is_isomorphic(G,nx.cubical_graph()))

    # 3x3 grid
    G=cartesian_product(P3,P3)
    assert_true(nx.is_isomorphic(G,nx.grid_2d_graph(3,3)))
示例#14
0
def test_average_connectivity():
    # figure 1 from:
    # Beineke, L., O. Oellermann, and R. Pippert (2002). The average 
    # connectivity of a graph. Discrete mathematics 252(1-3), 31-45
    # http://www.sciencedirect.com/science/article/pii/S0012365X01001807
    G1 = nx.path_graph(3)
    G1.add_edges_from([(1,3),(1,4)])
    assert_equal(nx.average_node_connectivity(G1),1)
    G2 = nx.path_graph(3)
    G2.add_edges_from([(1,3),(1,4),(0,3),(0,4),(3,4)])
    assert_equal(nx.average_node_connectivity(G2),2.2)
    G3 = nx.Graph()
    assert_equal(nx.average_node_connectivity(G3),0)
示例#15
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]
    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)])
示例#17
0
def test_sample_step():
    from score import SimpleDistanceEstimator as SDE
    import networkx as nx
    import choose
    import graphlearn3.test.transformutil as transformutil

    lsgg = util.test_get_grammar()
    graph = util._edenize_for_testing(nx.path_graph(4))
    graph.node[3]['label'] = '5'
    score_estimator = SDE().fit(util._edenize_for_testing(nx.path_graph(4)))
    graph,score= sample(graph, transformutil.no_transform(), lsgg, score_estimator, choose.Chooser(), n_steps=2, return_score=True)

    assert (0.000001 > abs(0.319274373045 - score)), score
    print("sambledestdone")
示例#18
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)])


        F = nx.Graph() # Florentine families
        F.add_edge('Acciaiuoli','Medici')
        F.add_edge('Castellani','Peruzzi')
        F.add_edge('Castellani','Strozzi')
        F.add_edge('Castellani','Barbadori')
        F.add_edge('Medici','Barbadori')
        F.add_edge('Medici','Ridolfi')
        F.add_edge('Medici','Tornabuoni')
        F.add_edge('Medici','Albizzi')
        F.add_edge('Medici','Salviati')
        F.add_edge('Salviati','Pazzi')
        F.add_edge('Peruzzi','Strozzi')
        F.add_edge('Peruzzi','Bischeri')
        F.add_edge('Strozzi','Ridolfi')
        F.add_edge('Strozzi','Bischeri')
        F.add_edge('Ridolfi','Tornabuoni')
        F.add_edge('Tornabuoni','Guadagni')
        F.add_edge('Albizzi','Ginori')
        F.add_edge('Albizzi','Guadagni')
        F.add_edge('Bischeri','Guadagni')
        F.add_edge('Guadagni','Lamberteschi')    
        self.F = F
示例#19
0
 def test_shortest_path_target(self):
     answer = {0: [0, 1], 1: [1], 2: [2, 1]}
     sp = nx.shortest_path(nx.path_graph(3), target=1)
     assert_equal(sp, answer)
     # with weights
     sp = nx.shortest_path(nx.path_graph(3), target=1, weight='weight')
     assert_equal(sp, answer)
     # weights and method specified
     sp = nx.shortest_path(nx.path_graph(3), target=1, weight='weight',
                           method='dijkstra')
     assert_equal(sp, answer)
     sp = nx.shortest_path(nx.path_graph(3), target=1, weight='weight',
                           method='bellman-ford')
     assert_equal(sp, answer)
    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
示例#21
0
 def test_shortest_path_length_target(self):
     answer = {0: 1, 1: 0, 2: 1}
     sp = dict(nx.shortest_path_length(nx.path_graph(3), target=1))
     assert_equal(sp, answer)
     # with weights
     sp = nx.shortest_path_length(nx.path_graph(3), target=1,
                                  weight='weight')
     assert_equal(sp, answer)
     # weights and method specified
     sp = nx.shortest_path_length(nx.path_graph(3), target=1,
                                  weight='weight', method='dijkstra')
     assert_equal(sp, answer)
     sp = nx.shortest_path_length(nx.path_graph(3), target=1,
                                  weight='weight', method='bellman-ford')
     assert_equal(sp, answer)
示例#22
0
    def test_dijkstra_predecessor(self):
        G = nx.path_graph(4)
        assert_equal(
            nx.dijkstra_predecessor_and_distance(G, 0), ({0: [], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3})
        )
        G = nx.grid_2d_graph(2, 2)
        pred, dist = nx.dijkstra_predecessor_and_distance(G, (0, 0))
        assert_equal(
            sorted(pred.items()), [((0, 0), []), ((0, 1), [(0, 0)]), ((1, 0), [(0, 0)]), ((1, 1), [(0, 1), (1, 0)])]
        )
        assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])

        XG = nx.DiGraph()
        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),
            ]
        )
        (P, D) = nx.dijkstra_predecessor_and_distance(XG, "s")
        assert_equal(P["v"], ["u"])
        assert_equal(D["v"], 9)
 def test_P4(self):
     """Edge betweenness centrality: P4"""
     G=nx.path_graph(4)
     b=nx.edge_betweenness_centrality(G, weight='weight', normalized=False)
     b_answer={(0, 1):3,(1, 2):4, (2, 3):3}
     for n in sorted(G.edges()):
         assert_almost_equal(b[n],b_answer[n])
示例#24
0
def test_relatives_to_distance_dict():
	G = nx.DiGraph()
	G = nx.path_graph(10, create_using=G)
	x = G.relatives_to_distance_dict(5, 3)
	assert len(x) == 7
	assert x == {
		2: 3,
		3: 2,
		4: 1,
		5: 0,
		6: 1,
		7: 2,
		8: 3,
	}

	x = G.relatives_to_distance_dict([3, 4], 2)
	assert len(x) == 6
	assert x == {
		1: 2,
		2: 1,
		3: 0,
		4: 0,
		5: 1,
		6: 2,
	}
示例#25
0
 def test_path(self):
     G = nx.path_graph(10)
     assert_equal(list(nx.clustering(G).values()),
                  [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
     assert_equal(nx.clustering(G),
                  {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0,
                   5: 0.0, 6: 0.0, 7: 0.0, 8: 0.0, 9: 0.0})
示例#26
0
def degree_sequence_tree(deg_sequence):
    """
    Make a tree for the given degree sequence.

    A tree has #nodes-#edges=1 so
    the degree sequence must have
    len(deg_sequence)-sum(deg_sequence)/2=1
    """

    if not len(deg_sequence)-sum(deg_sequence)/2.0 == 1.0:
        raise networkx.NetworkXError,"Degree sequence invalid"

    G=empty_graph(0)
    # single node tree
    if len(deg_sequence)==1:
        return G
    deg=[s for s in deg_sequence if s>1] # all degrees greater than 1
    deg.sort(reverse=True)

    # make path graph as backbone
    n=len(deg)+2
    G=networkx.path_graph(n)
    last=n

    # add the leaves
    for source in range(1,n-1):
        nedges=deg.pop()-2
        for target in range(last,last+nedges):
            G.add_edge(source, target)
        last+=nedges
        
    # in case we added one too many 
    if len(G.degree())>len(deg_sequence): 
        G.remove_node(0)
    return G
示例#27
0
文件: graphs.py 项目: deong/merlin
def complete_lobster(n, edges, seed=None):
    if seed is not None:
        random.seed(seed)
    p1 = p2 = 1.0
    llen=n
    L=nx.path_graph(llen)
    L.name="random_lobster(%d,%s,%s)"%(n,p1,p2)
    # build caterpillar: add edges to path graph with probability p1
    current_node=llen-1
    for n in xrange(llen):
        if npr.random()<p1: # add fuzzy caterpillar parts
            current_node+=1
            L.add_edge(n,current_node)
            if random.random()<p2: # add crunchy lobster bits
                current_node+=1
                L.add_edge(current_node-1,current_node)

    g = nx.MultiDiGraph(L) # voila, un lobster!
    for node in g:
        # if it's a leaf node, add a self edge and an edge back to the spine
        if len(g.out_edges(node)) == 1:
            knee = g.in_edges(node)[0][0]
            knee_edges = sorted(g.in_edges(knee))
            spine = knee_edges[0][0]
            g.add_edge(node, spine)
        if len(g.out_edges(node)) == 2:
            g.add_edge(node, node)
    return g
示例#28
0
    def test_disconnecting_graph(self):
        """Tests that the closeness vitality of a node whose removal
        disconnects the graph is negative infinity.

        """
        G = nx.path_graph(3)
        assert_equal(nx.closeness_vitality(G, node=1), -float('inf'))
示例#29
0
 def test_path(self):
     G = nx.path_graph(10)
     assert_equal(list(nx.triangles(G).values()),
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
     assert_equal(nx.triangles(G),
                  {0: 0, 1: 0, 2: 0, 3: 0, 4: 0,
                   5: 0, 6: 0, 7: 0, 8: 0, 9: 0})
示例#30
0
def test_missing_source_edge_paths():
    with pytest.raises(nx.NetworkXError):
        G = nx.path_graph(4)
        list(nx.edge_disjoint_paths(G, 10, 1))
示例#31
0
def test_missing_target_node_paths():
    with pytest.raises(nx.NetworkXError):
        G = nx.path_graph(4)
        list(nx.node_disjoint_paths(G, 1, 10))
示例#32
0
 def test_bipartite_sets(self):
     G=nx.path_graph(4)
     X,Y=nx.bipartite_sets(G)
     assert_equal(X,set([0,2]))
     assert_equal(Y,set([1,3]))
示例#33
0
import networkx as nx
G = nx.Graph()
G.add_node(1)
H = nx.path_graph(10)
G.add_nodes_from(H)

G.add_edges_from([(1, 2), (1, 3)])
nx.draw(G, with_labels=True, font_weight='bold')

FG = nx.Graph()
FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)])
def makeDirectedPath(num_nodes):
    pdg = nx.path_graph(num_nodes, create_using=nx.DiGraph())
    for i in pdg.edges():
        pdg.edges[i[0], i[1]]['weight'] = weight = random.uniform(0, 1)
    return pdg
def makeDirectedPathOne(num_nodes):
    pdg = nx.path_graph(num_nodes, create_using=nx.DiGraph())
    for i in pdg.edges():
        pdg.edges[i[0], i[1]]['weight'] = 1
    return pdg
示例#36
0
 def test_is_bipartite(self):
     G=nx.path_graph(4)
     assert_true(nx.is_bipartite(G))
示例#37
0
def test_digraph_all_simple_paths_with_two_targets_cutoff():
    G = nx.path_graph(4, create_using=nx.DiGraph())
    G.add_edge(2, 4)
    paths = nx.all_simple_paths(G, 0, [3, 4], cutoff=3)
    assert {tuple(p) for p in paths} == {(0, 1, 2, 3), (0, 1, 2, 4)}
示例#38
0
 def setup(self):
     self.G = nx.path_graph(9)
     self.dv = nx.to_directed(self.G)
     self.MG = nx.path_graph(9, create_using=nx.MultiGraph())
     self.Mdv = nx.to_directed(self.MG)
示例#39
0
 def setup(self):
     self.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
     self.G.add_edge(4, 5)
     self.rv = nx.reverse_view(self.G)
示例#40
0
def test_all_simple_edge_paths_with_two_targets_in_line_emits_two_paths():
    G = nx.path_graph(4)
    paths = nx.all_simple_edge_paths(G, 0, [2, 3])
    assert {tuple(p)
            for p in paths} == {((0, 1), (1, 2)), ((0, 1), (1, 2), (2, 3))}
示例#41
0
def test_all_simple_edge_paths():
    G = nx.path_graph(4)
    paths = nx.all_simple_edge_paths(G, 0, 3)
    assert {tuple(p) for p in paths} == {((0, 1), (1, 2), (2, 3))}
示例#42
0
 def test_full_rary_tree_path(self):
     t = nx.full_rary_tree(1, 10)
     assert is_isomorphic(t, nx.path_graph(10))
示例#43
0
def test_all_simple_paths_empty():
    G = nx.path_graph(4)
    paths = nx.all_simple_paths(G, 0, 3, cutoff=2)
    assert list(paths) == []
示例#44
0
def test_all_simple_paths_source_target():
    G = nx.path_graph(4)
    paths = nx.all_simple_paths(G, 1, 1)
    assert list(paths) == []
示例#45
0
 def setup(self):
     self.DG = nx.path_graph(9, create_using=nx.DiGraph())
     self.uv = nx.to_undirected(self.DG)
     self.MDG = nx.path_graph(9, create_using=nx.MultiDiGraph())
     self.Muv = nx.to_undirected(self.MDG)
def test_difference_raise():
    G = nx.path_graph(4)
    H = nx.path_graph(3)
    pytest.raises(nx.NetworkXError, nx.difference, G, H)
    pytest.raises(nx.NetworkXError, nx.symmetric_difference, G, H)
示例#47
0
    def __init__(self,
                 n_sample,
                 n,
                 k=2,
                 mode='invariant',
                 type_graph='normal',
                 type_label='shortest_path',
                 transform_data=True):
        """
        Input:
          n_sample : number of samples
          n : number of nodes
          k : tensorization inside networks, 2 or 3
          mode : 'invariant' or 'equivariant'
          type_graphs:
            'normal': normal edge weights (symmetrized, with absolute value)
            'SBM': stochastic block model with K=sqrt(log(n))+1 communities
          type_label:
            'shortest_path': diameter (longest shortest path) if invariant, longest shortest path from each node if equivariant
            'eigen': second largest eigenvalue is invariant, second eigenvector if equivariant
        Data:
          self.equi (n_sample * n^k * b(k+2)): data, equivariant basis form
          self.label (n_sample if invariant, n_sample * n if equivariant)
        """
        self.n = n
        self.n_sample = n_sample
        self.mode = mode
        self.k = k

        if type_graph == 'normal':
            self.Ws = torch.randn(n_sample, n, n)
            for i in range(n_sample):
                self.Ws[i, :, :] = torch.abs(self.Ws[i, :, :] +
                                             self.Ws[i, :, :].t())
        elif type_graph == 'SBM':
            self.Ws, _ = torch.tensor(
                SBM(n_sample,
                    n,
                    K=int(np.sqrt(np.log(n))) + 1,
                    connectivity=(0.85, 4 * np.log(n) / n)))
        elif type_graph == 'special':
            choice = np.random.randint(5, size=n_sample)
            weights = torch.abs(
                torch.randn(n_sample, n,
                            n)) + 0.01  #*(torch.randn(n_sample))[:,None,None])
            self.Ws = torch.zeros(n_sample, n, n)
            for i in range(n_sample):
                weight = weights[i, :, :] + weights[i, :, :].t()
                if choice[i] == 0:
                    A = nx.complete_graph(n)
                elif choice[i] == 1:
                    A = nx.cycle_graph(n)
                elif choice[i] == 2:
                    A = nx.path_graph(n)
                elif choice[i] == 3:
                    A = nx.star_graph(n - 1)
                elif choice[i] == 4:
                    A = nx.wheel_graph(n)
                self.Ws[i, :, :] = torch.tensor(
                    nx.to_numpy_matrix(A)).float() * weight

        if mode == 'equivariant':
            self.label = torch.zeros(n_sample, n)
        else:
            self.label = torch.zeros(n_sample)
        for i in range(n_sample):
            if type_label == 'shortest_path':
                if mode == 'equivariant':
                    self.label[i, :] = torch.tensor(
                        np.max(dijkstra(self.Ws[i, :, :], directed=False),
                               axis=0))
                else:
                    self.label[i] = np.max(
                        dijkstra(self.Ws[i, :, :], directed=False))
            elif type_label == 'eigen':
                A = self.Ws[i, :, :].numpy()
                eig_values, eig_vec = eigh(A.dot(A), eigvals=[n - 1, n - 1])
                if mode == 'equivariant':
                    self.label[i, :] = torch.tensor(eig_vec).t()
                else:
                    self.label[i] = torch.tensor(eig_values)

        print('Create equivariant basis...')
        self.equi = transforminput(self.Ws, k)
        print('Done.')
示例#48
0
 def test_P3(self):
     G = nx.path_graph(3)
     self.test(G, 0, 2, [1])
示例#49
0
 def setup(self):
     self.G = nx.path_graph(9, create_using=nx.DiGraph())
     self.rv = nx.reverse_view(self.G)
示例#50
0
 def test_bipartite_density(self):
     G=nx.path_graph(5)
     X,Y=nx.bipartite_sets(G)
     density=float(len(G.edges()))/(len(X)*len(Y))
     assert_equal(nx.bipartite_density(G,X),density)
示例#51
0
 def setUp(self):
     self.null = nx.null_graph()
     self.P10 = cnlti(nx.path_graph(10), first_label=1)
     self.K10 = cnlti(nx.complete_graph(10), first_label=1)
示例#52
0
import networkx as nx
import matplotlib.pyplot as plt

G = nx.path_graph(5)

print(nx.dijkstra_path(G, 0, 4))

nx.draw(G, with_labels=True)
plt.savefig('DijkstraPath.png')
plt.show()
示例#53
0
def get_connectivity_graph(qubits, topology='grid', param=None):
    attempt = 0
    while attempt < 10:
        if topology == 'grid':
            # assume square grid
            side = int(np.sqrt(qubits))
            G = nx.grid_2d_graph(side, side)
        elif topology == 'erdosrenyi':
            if param == None:
                print("Erdos Renyi graph needs parameter p.")
            G = nx.fast_gnp_random_graph(qubits, param)
        elif topology == 'turan':
            if param == None:
                print("Turan graph needs parameter r.")
            G = nx.turan_graph(qubits, param)
        elif topology == 'regular':
            if param == None:
                print("d-regular graph needs parameter d.")
            G = nx.random_regular_graph(param, qubits)
        elif topology == 'cycle':
            G = nx.cycle_graph(qubits)
        elif topology == 'wheel':
            G = nx.wheel_graph(qubits)
        elif topology == 'complete':
            G = nx.complete_graph(qubits)
        elif topology == 'hexagonal':
            # assume square hexagonal grid, node = 2(m+1)**2-2
            side = int(np.sqrt((qubits + 2) / 2)) - 1
            G = nx.hexagonal_lattice_graph(side, side)
        elif topology == 'path':
            G = nx.path_graph(qubits)
        elif topology == 'ibm_falcon':
            # https://www.ibm.com/blogs/research/2020/07/qv32-performance/
            # 27 qubits
            G = nx.empty_graph(27)
            G.name = "ibm_falcon"
            G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 4), (3, 5), (5, 6),
                              (6, 7), (7, 8), (8, 9), (8, 10), (10, 11),
                              (1, 12), (6, 13), (11, 14), (12, 15), (15, 16),
                              (16, 17), (17, 18), (17, 19), (19, 20), (13, 20),
                              (20, 21), (21, 22), (22, 23), (22, 24), (24, 25),
                              (14, 25), (25, 26)])
        elif topology == 'ibm_penguin':
            # 20 qubits
            G = nx.empty_graph(20)
            G.name = "ibm_penguin"
            G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 4), (0, 5), (5, 6),
                              (6, 7), (7, 8), (8, 9), (4, 9), (5, 10),
                              (10, 11), (11, 12), (7, 12), (12, 13), (13, 14),
                              (9, 14), (10, 15), (15, 16), (16, 17), (17, 18),
                              (18, 19), (14, 19)])
        elif topology == '1express':  # path with express channels
            G = nx.convert_node_labels_to_integers(nx.path_graph(qubits))
            G.add_edges_from([(s, s + param)
                              for s in range(0, qubits - param, param // 2)])
        elif topology == '2express':  # grid with express channels
            side = int(np.sqrt(qubits))
            G = nx.convert_node_labels_to_integers(nx.grid_2d_graph(
                side, side))
            G.add_edges_from([
                (s, s + param) for x in range(side)
                for s in range(x * side, x * side + side - param, param // 2)
            ])  # rows
            G.add_edges_from([
                (s, s + param * side) for y in range(side)
                for s in range(y, y + side * (side - param), param // 2 * side)
            ])  # cols
        else:
            print("Topology %s not recognized; use empty graph instead." %
                  topology)
            G = nx.empty_graph(qubits)
        if nx.is_connected(G) or nx.is_empty(G):
            break
        else:
            attempt += 1

    return nx.convert_node_labels_to_integers(G)
示例#54
0
 def test_spring_fixed_without_pos(self):
     G = nx.path_graph(4)
     pytest.raises(ValueError, nx.spring_layout, G, fixed=[0])
     pos = {0: (1, 1), 2: (0, 0)}
     pytest.raises(ValueError, nx.spring_layout, G, fixed=[0, 1], pos=pos)
     nx.spring_layout(G, fixed=[0, 2], pos=pos)  # No ValueError
示例#55
0
 def test_unrecognized_method(self):
     G = nx.path_graph(4)
     pytest.raises(nx.NetworkXError,
                   nx.spectral_ordering,
                   G,
                   method="unknown")
示例#56
0
 def test_graph(self):
     G = nx.path_graph(4)
     H = loads(dumps(G))
     nx.is_isomorphic(G, H)
示例#57
0
def test_all_simple_paths_corner_cases():
    assert list(nx.all_simple_paths(nx.empty_graph(2), 0, 0)) == []
    assert list(nx.all_simple_paths(nx.empty_graph(2), 0, 1)) == []
    assert list(nx.all_simple_paths(nx.path_graph(9), 0, 8, 0)) == []
示例#58
0
    def test_others(self):
        (P, D) = nx.bellman_ford(self.XG, 's')
        assert_equal(P['v'], 'u')
        assert_equal(D['v'], 9)
        (P, D) = nx.goldberg_radzik(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.goldberg_radzik(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
        }))
        assert_equal(nx.goldberg_radzik(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)])
        pred, dist = nx.goldberg_radzik(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)])
示例#59
0
 def test_bipartite_color(self):
     G=nx.path_graph(4)
     c=nx.bipartite_color(G)
     assert_equal(c,{0: 1, 1: 0, 2: 1, 3: 0})
 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]