def setUp(self): # G is the example graph in Figure 1 from Batagelj and # Zaversnik's paper titled An O(m) Algorithm for Cores # Decomposition of Networks, 2003, # http://arXiv.org/abs/cs/0310049. With nodes labeled as # shown, the 3-core is given by nodes 1-8, the 2-core by nodes # 9-16, the 1-core by nodes 17-20 and node 21 is in the # 0-core. t1 = nx.convert_node_labels_to_integers(nx.tetrahedral_graph(), 1) t2 = nx.convert_node_labels_to_integers(t1, 5) G = nx.union(t1, t2) G.add_edges_from([(3, 7), (2, 11), (11, 5), (11, 12), (5, 12), (12, 19), (12, 18), (3, 9), (7, 9), (7, 10), (9, 10), (9, 20), (17, 13), (13, 14), (14, 15), (15, 16), (16, 13)]) G.add_node(21) self.G = G # Create the graph H resulting from the degree sequence # [0, 1, 2, 2, 2, 2, 3] when using the Havel-Hakimi algorithm. degseq = [0, 1, 2, 2, 2, 2, 3] H = nx.havel_hakimi_graph(degseq) mapping = {6: 0, 0: 1, 4: 3, 5: 6, 3: 4, 1: 2, 2: 5} self.H = nx.relabel_nodes(H, mapping)
def TetrahedralGraph(): """ Returns a tetrahedral graph (with 4 nodes). A tetrahedron is a 4-sided triangular pyramid. The tetrahedral graph corresponds to the connectivity of the vertices of the tetrahedron. This graph is equivalent to a wheel graph with 4 nodes and also a complete graph on four nodes. (See examples below). PLOTTING: The tetrahedral graph should be viewed in 3 dimensions. We chose to use the default spring-layout algorithm here, so that multiple iterations might yield a different point of reference for the user. We hope to add rotatable, 3-dimensional viewing in the future. In such a case, a string argument will be added to select the flat spring-layout over a future implementation. EXAMPLES: Construct and show a Tetrahedral graph :: sage: g = graphs.TetrahedralGraph() sage: g.show() # long time The following example requires networkx:: sage: import networkx as NX Compare this Tetrahedral, Wheel(4), Complete(4), and the Tetrahedral plotted with the spring-layout algorithm below in a Sage graphics array:: sage: tetra_pos = graphs.TetrahedralGraph() sage: tetra_spring = Graph(NX.tetrahedral_graph()) sage: wheel = graphs.WheelGraph(4) sage: complete = graphs.CompleteGraph(4) sage: g = [tetra_pos, tetra_spring, wheel, complete] sage: j = [] sage: for i in range(2): ....: n = [] ....: for m in range(2): ....: n.append(g[i + m].plot(vertex_size=50, vertex_labels=False)) ....: j.append(n) sage: G = graphics_array(j) sage: G.show() # long time """ import networkx G = networkx.tetrahedral_graph() return Graph(G, name="Tetrahedron", pos={ 0: (0, 0), 1: (0, 1), 2: (cos(3.5 * pi / 3), sin(3.5 * pi / 3)), 3: (cos(5.5 * pi / 3), sin(5.5 * pi / 3)) })
def classic_small_graphs(): petersen = nx.petersen_graph() tutte = nx.tutte_graph() maze = nx.sedgewick_maze_graph() tet = nx.tetrahedral_graph() g_list = [petersen, tutte, maze, tet] for n, g in enumerate(g_list): plt.subplot(221+n) nx.draw(g, with_labels=True, font_weight='bold') plt.show()
def practice(): Peterson = nx.petersen_graph() tutte = nx.tutte_graph() maze = nx.sedgewick_maze_graph() tet = nx.tetrahedral_graph() G = nx.random_tree(20) nx.draw(G, pos=nx.spring_layout(G), with_labels=True) #nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight='bold') plt.show()
def test_is_distance_regular(self): assert_true(nx.is_distance_regular(nx.icosahedral_graph())) assert_true(nx.is_distance_regular(nx.petersen_graph())) assert_true(nx.is_distance_regular(nx.cubical_graph())) assert_true(nx.is_distance_regular(nx.complete_bipartite_graph(3,3))) assert_true(nx.is_distance_regular(nx.tetrahedral_graph())) assert_true(nx.is_distance_regular(nx.dodecahedral_graph())) assert_true(nx.is_distance_regular(nx.pappus_graph())) assert_true(nx.is_distance_regular(nx.heawood_graph())) assert_true(nx.is_distance_regular(nx.cycle_graph(3))) # no distance regular assert_false(nx.is_distance_regular(nx.path_graph(4)))
def TetrahedralGraph(): """ Returns a tetrahedral graph (with 4 nodes). A tetrahedron is a 4-sided triangular pyramid. The tetrahedral graph corresponds to the connectivity of the vertices of the tetrahedron. This graph is equivalent to a wheel graph with 4 nodes and also a complete graph on four nodes. (See examples below). PLOTTING: The tetrahedral graph should be viewed in 3 dimensions. We chose to use the default spring-layout algorithm here, so that multiple iterations might yield a different point of reference for the user. We hope to add rotatable, 3-dimensional viewing in the future. In such a case, a string argument will be added to select the flat spring-layout over a future implementation. EXAMPLES: Construct and show a Tetrahedral graph :: sage: g = graphs.TetrahedralGraph() sage: g.show() # long time The following example requires networkx:: sage: import networkx as NX Compare this Tetrahedral, Wheel(4), Complete(4), and the Tetrahedral plotted with the spring-layout algorithm below in a Sage graphics array:: sage: tetra_pos = graphs.TetrahedralGraph() sage: tetra_spring = Graph(NX.tetrahedral_graph()) sage: wheel = graphs.WheelGraph(4) sage: complete = graphs.CompleteGraph(4) sage: g = [tetra_pos, tetra_spring, wheel, complete] sage: j = [] sage: for i in range(2): ... n = [] ... for m in range(2): ... n.append(g[i + m].plot(vertex_size=50, vertex_labels=False)) ... j.append(n) sage: G = sage.plot.graphics.GraphicsArray(j) sage: G.show() # long time """ import networkx G = networkx.tetrahedral_graph() return graph.Graph(G, name="Tetrahedron", pos = { 0 : (0, 0), 1 : (0, 1), 2 : (cos(3.5*pi/3), sin(3.5*pi/3)), 3 : (cos(5.5*pi/3), sin(5.5*pi/3))} )
def test_is_distance_regular(self): assert_true(nx.is_distance_regular(nx.icosahedral_graph())) assert_true(nx.is_distance_regular(nx.petersen_graph())) assert_true(nx.is_distance_regular(nx.cubical_graph())) assert_true(nx.is_distance_regular(nx.complete_bipartite_graph(3, 3))) assert_true(nx.is_distance_regular(nx.tetrahedral_graph())) assert_true(nx.is_distance_regular(nx.dodecahedral_graph())) assert_true(nx.is_distance_regular(nx.pappus_graph())) assert_true(nx.is_distance_regular(nx.heawood_graph())) assert_true(nx.is_distance_regular(nx.cycle_graph(3))) # no distance regular assert_false(nx.is_distance_regular(nx.path_graph(4)))
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()))
def test_tensor_product_classic_result(): K2 = nx.complete_graph(2) G = nx.petersen_graph() G = nx.tensor_product(G, K2) assert_true(nx.is_isomorphic(G, nx.desargues_graph())) G = nx.cycle_graph(5) G = nx.tensor_product(G, K2) assert_true(nx.is_isomorphic(G, nx.cycle_graph(10))) G = nx.tetrahedral_graph() G = nx.tensor_product(G, K2) assert_true(nx.is_isomorphic(G, nx.cubical_graph()))
def platonic(n): # n must be 4, 6, 8, 12 or 20 # returns the matrix for sp2 platonic solid, with alpha = 0 and beta = -1 n_int = int(n) if n_int == 4: s = nx.tetrahedral_graph() elif n_int == 6: s = nx.cubical_graph() elif n_int == 8: s = nx.octahedral_graph() elif n_int == 12: s = nx.dodecahedral_graph() elif n_int == 20: s = nx.icosahedral_graph() else: print("n must be equal to 4, 6, 8, 12 or 20") M = -nx.adjacency_matrix(s) return M.todense()
def test_tensor_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=tensor_product(null,null) assert_true(nx.is_isomorphic(G,null)) # null_graph X anything = null_graph and v.v. G=tensor_product(null,empty10) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(null,K3) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(null,K10) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(null,P3) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(null,P10) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(empty10,null) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(K3,null) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(K10,null) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(P3,null) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(P10,null) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(P5,K3) assert_equal(nx.number_of_nodes(G),5*3) G=tensor_product(K3,K5) assert_equal(nx.number_of_nodes(G),3*5) 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())) G = nx.erdos_renyi_graph(10,2/10.) H = nx.erdos_renyi_graph(10,2/10.) GH = tensor_product(G,H) for (u_G,u_H) in GH.nodes_iter(): for (v_G,v_H) in GH.nodes_iter(): if H.has_edge(u_H,v_H) and G.has_edge(u_G,v_G): 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)))
def test_tetrahedral(self): expected = True actual = is_planar(nx.tetrahedral_graph()) self.assertEqual(expected, actual)
# 典型的なグラフ操作 # subgraph(G, nbunch) - induce subgraph of G on nodes in nbunch # union(G1,G2) - graph union # disjoint_union(G1,G2) - graph union assuming all nodes are different # cartesian_product(G1,G2) - return Cartesian product graph # compose(G1,G2) - combine graphs identifying nodes common to both # complement(G) - graph complement # create_empty_copy(G) - return an empty copy of the same graph class # convert_to_undirected(G) - return an undirected representation of G # convert_to_directed(G) - return a directed representation of G petersen=nx.petersen_graph() # ピーターセングラフ 10個の頂点と15個の辺からなる無向グラフ。グラフ理論の様々な問題の例、あるいは反例としてよく使われる。 tutte=nx.tutte_graph() # Tutte グラフ maze=nx.sedgewick_maze_graph() tet=nx.tetrahedral_graph() # テトラへドラル K_5=nx.complete_graph(5) # 完全グラフ K_3_5=nx.complete_bipartite_graph(3,5) #完全二部グラフ 2部グラフのうち特に第1の集合に属するそれぞれの頂点から第2の集合に属する全ての頂点に辺が伸びているもの barbell=nx.barbell_graph(10,10) # lollipop=nx.lollipop_graph(10,20) # er=nx.erdos_renyi_graph(100,0.15) ws=nx.watts_strogatz_graph(30,3,0.1) ba=nx.barabasi_albert_graph(100,5) red=nx.random_lobster(100,0.9,0.9) nx.write_gml(red,"path.to.file") mygraph=nx.read_gml("path.to.file") # グラフの分析
def test_tetrahedral(): # Actual coefficient is 1 G = nx.tetrahedral_graph() assert_equal(average_clustering(G, trials=int(len(G) / 2)), nx.average_clustering(G))
import networkx as nx import matplotlib.pylab as plt from plot_multigraph import plot_multigraph graphs = [ ("bull", nx.bull_graph()), ("chvatal", nx.chvatal_graph()), ("cubical", nx.cubical_graph()), ("desargues", nx.desargues_graph()), ("diamond", nx.diamond_graph()), ("dodecahedral", nx.dodecahedral_graph()), ("frucht", nx.frucht_graph()), ("heawood", nx.heawood_graph()), ("house", nx.house_graph()), ("house_x", nx.house_x_graph()), ("icosahedral", nx.icosahedral_graph()), ("krackhardt_kite", nx.krackhardt_kite_graph()), ("moebius_kantor", nx.moebius_kantor_graph()), ("octahedral", nx.octahedral_graph()), ("pappus", nx.pappus_graph()), ("petersen", nx.petersen_graph()), ("sedgewick_maze", nx.sedgewick_maze_graph()), ("tetrahedral", nx.tetrahedral_graph()), ("truncated_cube", nx.truncated_cube_graph()), ("truncated_tetrahedron", nx.truncated_tetrahedron_graph()), ] plot_multigraph(graphs, 4, 5, node_size=50) plt.savefig('graphs/small.png')
def random(cls, number): #return nx.random_geometric_graph(number, 0.125) #return nx.petersen_graph() return nx.tetrahedral_graph()
'cubical': nx.cubical_graph(), # 3-connected planar 'desargues': nx.desargues_graph(), # 3-connected non-planar 'diamond': nx.diamond_graph(), # 2-connected planar 'dodecahedral': nx.dodecahedral_graph(), # 3-connected planar 'frucht': nx.frucht_graph(), # 3-connected planar 'heawood': nx.heawood_graph(), # 3-connected non-planar 'house': nx.house_graph(), # 2-connected planar 'house_x': nx.house_x_graph(), # 2-connected planar 'icosahedral': nx.icosahedral_graph(), # 5-connected planar 'krackhardt': nx.krackhardt_kite_graph(), # 1-connected planar 'moebius': nx.moebius_kantor_graph(), # non-planar 'octahedral': nx.octahedral_graph(), # 4-connected planar 'pappus': nx.pappus_graph(), # 3-connected non-planar 'petersen': nx.petersen_graph(), # 3-connected non-planar 'sedgewick': nx.sedgewick_maze_graph(), # 1-connected planar 'tetrahedral': nx.tetrahedral_graph(), # 3-connected planar 'truncated_cube': nx.truncated_cube_graph(), # 3-conn. planar 'truncated_tetrahedron': nx.truncated_tetrahedron_graph(), # 3-connected planar 'tutte': nx.tutte_graph() } # 3-connected planar for g_name, g in targets.items(): print g_name, is_planar(g) # g = nx.petersen_graph() # g = nx.frucht_graph() # g = nx.krackhardt_kite_graph() # g = nx.icosahedral_graph() # g = nx.tutte_graph() # print is_planarity(g)
def test_properties_named_small_graphs(self): G = nx.bull_graph() assert G.number_of_nodes() == 5 assert G.number_of_edges() == 5 assert sorted(d for n, d in G.degree()) == [1, 1, 2, 3, 3] assert nx.diameter(G) == 3 assert nx.radius(G) == 2 G = nx.chvatal_graph() assert G.number_of_nodes() == 12 assert G.number_of_edges() == 24 assert list(d for n, d in G.degree()) == 12 * [4] assert nx.diameter(G) == 2 assert nx.radius(G) == 2 G = nx.cubical_graph() assert G.number_of_nodes() == 8 assert G.number_of_edges() == 12 assert list(d for n, d in G.degree()) == 8 * [3] assert nx.diameter(G) == 3 assert nx.radius(G) == 3 G = nx.desargues_graph() assert G.number_of_nodes() == 20 assert G.number_of_edges() == 30 assert list(d for n, d in G.degree()) == 20 * [3] G = nx.diamond_graph() assert G.number_of_nodes() == 4 assert sorted(d for n, d in G.degree()) == [2, 2, 3, 3] assert nx.diameter(G) == 2 assert nx.radius(G) == 1 G = nx.dodecahedral_graph() assert G.number_of_nodes() == 20 assert G.number_of_edges() == 30 assert list(d for n, d in G.degree()) == 20 * [3] assert nx.diameter(G) == 5 assert nx.radius(G) == 5 G = nx.frucht_graph() assert G.number_of_nodes() == 12 assert G.number_of_edges() == 18 assert list(d for n, d in G.degree()) == 12 * [3] assert nx.diameter(G) == 4 assert nx.radius(G) == 3 G = nx.heawood_graph() assert G.number_of_nodes() == 14 assert G.number_of_edges() == 21 assert list(d for n, d in G.degree()) == 14 * [3] assert nx.diameter(G) == 3 assert nx.radius(G) == 3 G = nx.hoffman_singleton_graph() assert G.number_of_nodes() == 50 assert G.number_of_edges() == 175 assert list(d for n, d in G.degree()) == 50 * [7] assert nx.diameter(G) == 2 assert nx.radius(G) == 2 G = nx.house_graph() assert G.number_of_nodes() == 5 assert G.number_of_edges() == 6 assert sorted(d for n, d in G.degree()) == [2, 2, 2, 3, 3] assert nx.diameter(G) == 2 assert nx.radius(G) == 2 G = nx.house_x_graph() assert G.number_of_nodes() == 5 assert G.number_of_edges() == 8 assert sorted(d for n, d in G.degree()) == [2, 3, 3, 4, 4] assert nx.diameter(G) == 2 assert nx.radius(G) == 1 G = nx.icosahedral_graph() assert G.number_of_nodes() == 12 assert G.number_of_edges() == 30 assert (list( d for n, d in G.degree()) == [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]) assert nx.diameter(G) == 3 assert nx.radius(G) == 3 G = nx.krackhardt_kite_graph() assert G.number_of_nodes() == 10 assert G.number_of_edges() == 18 assert (sorted( d for n, d in G.degree()) == [1, 2, 3, 3, 3, 4, 4, 5, 5, 6]) G = nx.moebius_kantor_graph() assert G.number_of_nodes() == 16 assert G.number_of_edges() == 24 assert list(d for n, d in G.degree()) == 16 * [3] assert nx.diameter(G) == 4 G = nx.octahedral_graph() assert G.number_of_nodes() == 6 assert G.number_of_edges() == 12 assert list(d for n, d in G.degree()) == 6 * [4] assert nx.diameter(G) == 2 assert nx.radius(G) == 2 G = nx.pappus_graph() assert G.number_of_nodes() == 18 assert G.number_of_edges() == 27 assert list(d for n, d in G.degree()) == 18 * [3] assert nx.diameter(G) == 4 G = nx.petersen_graph() assert G.number_of_nodes() == 10 assert G.number_of_edges() == 15 assert list(d for n, d in G.degree()) == 10 * [3] assert nx.diameter(G) == 2 assert nx.radius(G) == 2 G = nx.sedgewick_maze_graph() assert G.number_of_nodes() == 8 assert G.number_of_edges() == 10 assert sorted(d for n, d in G.degree()) == [1, 2, 2, 2, 3, 3, 3, 4] G = nx.tetrahedral_graph() assert G.number_of_nodes() == 4 assert G.number_of_edges() == 6 assert list(d for n, d in G.degree()) == [3, 3, 3, 3] assert nx.diameter(G) == 1 assert nx.radius(G) == 1 G = nx.truncated_cube_graph() assert G.number_of_nodes() == 24 assert G.number_of_edges() == 36 assert list(d for n, d in G.degree()) == 24 * [3] G = nx.truncated_tetrahedron_graph() assert G.number_of_nodes() == 12 assert G.number_of_edges() == 18 assert list(d for n, d in G.degree()) == 12 * [3] G = nx.tutte_graph() assert G.number_of_nodes() == 46 assert G.number_of_edges() == 69 assert list(d for n, d in G.degree()) == 46 * [3] # Test create_using with directed or multigraphs on small graphs pytest.raises(nx.NetworkXError, nx.tutte_graph, create_using=nx.DiGraph) MG = nx.tutte_graph(create_using=nx.MultiGraph) assert sorted(MG.edges()) == sorted(G.edges())
def test_tetrahedral(): # Actual coefficient is 1 G = nx.tetrahedral_graph() assert (average_clustering(G, trials=int(len(G) / 2)) == nx.average_clustering(G))
def basic_operation_tutorial(): # Create a graph. G = nx.Graph() # Nodes. G.add_node(1) G.add_nodes_from([2, 3]) H = nx.path_graph(10) # Creates a graph. G.add_nodes_from(H) G.add_node(H) #print('G.nodes = {}.'.format(G.nodes)) print('G.nodes = {}.'.format(list(G.nodes))) # Edges. G.add_edge(1, 2) e = (2, 3) G.add_edge(*e) # Unpack edge tuple. G.add_edges_from([(1, 2), (1, 3)]) G.add_edges_from(H.edges) #print('G.edges = {}.'.format(G.edges)) print('G.edges = {}.'.format(list(G.edges))) # Remove all nodes and edges. G.clear() #-------------------- G.add_edges_from([(1, 2), (1, 3)]) G.add_node(1) G.add_edge(1, 2) G.add_node('spam') # Adds node 'spam'. G.add_nodes_from('spam') # Adds 4 nodes: 's', 'p', 'a', 'm'. G.add_edge(3, 'm') print('G.number_of_nodes() = {}.'.format(G.number_of_nodes())) print('G.number_of_edges() = {}.'.format(G.number_of_edges())) # Set-like views of the nodes, edges, neighbors (adjacencies), and degrees of nodes in a graph. print('G.adj[1] = {}.'.format(list(G.adj[1]))) # or G.neighbors(1). print('G.degree[1] = {}.'.format( G.degree[1])) # The number of edges incident to 1. # Report the edges and degree from a subset of all nodes using an nbunch. # An nbunch is any of: None (meaning all nodes), a node, or an iterable container of nodes that is not itself a node in the graph. print("G.edges([2, 'm']) = {}.".format(G.edges([2, 'm']))) print('G.degree([2, 3]) = {}.'.format(G.degree([2, 3]))) # Remove nodes and edges from the graph in a similar fashion to adding. G.remove_node(2) G.remove_nodes_from('spam') print('G.nodes = {}.'.format(list(G.nodes))) G.remove_edge(1, 3) # When creating a graph structure by instantiating one of the graph classes you can specify data in several formats. G.add_edge(1, 2) H = nx.DiGraph(G) # Creates a DiGraph using the connections from G. print('H.edges() = {}.'.format(list(H.edges()))) edgelist = [(0, 1), (1, 2), (2, 3)] H = nx.Graph(edgelist) #-------------------- # Access edges and neighbors. print('G[1] = {}.'.format(G[1])) # Same as G.adj[1]. print('G[1][2] = {}.'.format(G[1][2])) # Edge 1-2. print('G.edges[1, 2] = {}.'.format(G.edges[1, 2])) # Get/set the attributes of an edge using subscript notation if the edge already exists. G.add_edge(1, 3) G[1][3]['color'] = 'blue' G.edges[1, 2]['color'] = 'red' # Fast examination of all (node, adjacency) pairs is achieved using G.adjacency(), or G.adj.items(). # Note that for undirected graphs, adjacency iteration sees each edge twice. FG = nx.Graph() FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.375)]) for n, nbrs in FG.adj.items(): for nbr, eattr in nbrs.items(): wt = eattr['weight'] if wt < 0.5: print(f'({n}, {nbr}, {wt:.3})') # Convenient access to all edges is achieved with the edges property. for (u, v, wt) in FG.edges.data('weight'): if wt < 0.5: print(f'({u}, {v}, {wt:.3})') #-------------------- # Attributes. # Graph attributes. G = nx.Graph(day='Friday') print('G.graph = {}.'.format(G.graph)) G.graph['day'] = 'Monday' # Node attributes: add_node(), add_nodes_from(), or G.nodes. G.add_node(1, time='5pm') G.add_nodes_from([3], time='2pm') print('G.nodes[1] = {}.'.format(G.nodes[1])) G.nodes[1]['room'] = 714 print('G.nodes.data() = {}.'.format(G.nodes.data())) print('G.nodes[1] = {}.'.format( G.nodes[1])) # List the attributes of a node. print('G.nodes[1].keys() = {}.'.format(G.nodes[1].keys())) #print('G[1] = {}.'.format(G[1])) # G[1] = G.adj[1]. # Edge attributes: add_edge(), add_edges_from(), or subscript notation. G.add_edge(1, 2, weight=4.7) G.add_edges_from([(3, 4), (4, 5)], color='red') G.add_edges_from([(1, 2, {'color': 'blue'}), (2, 3, {'weight': 8})]) G[1][2]['weight'] = 4.7 G.edges[3, 4]['weight'] = 4.2 print('G.edges.data() = {}.'.format(G.edges.data())) print('G.edges[3, 4] = {}.'.format( G.edges[3, 4])) # List the attributes of an edge. print('G.edges[3, 4].keys() = {}.'.format(G.edges[3, 4].keys())) #-------------------- # Directed graphs. DG = nx.DiGraph() DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)]) print("DG.out_degree(1, weight='weight') = {}.".format( DG.out_degree(1, weight='weight'))) print("DG.degree(1, weight='weight') = {}.".format( DG.degree( 1, weight='weight'))) # The sum of in_degree() and out_degree(). print('DG.successors(1) = {}.'.format(list(DG.successors(1)))) print('DG.neighbors(1) = {}.'.format(list(DG.neighbors(1)))) # Convert G to undirected graph. #H = DG.to_undirected() H = nx.Graph(DG) #-------------------- # Multigraphs: Graphs which allow multiple edges between any pair of nodes. MG = nx.MultiGraph() #MDG = nx.MultiDiGraph() MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)]) print("MG.degree(weight='weight') = {}.".format( dict(MG.degree(weight='weight')))) GG = nx.Graph() for n, nbrs in MG.adjacency(): for nbr, edict in nbrs.items(): minvalue = min([d['weight'] for d in edict.values()]) GG.add_edge(n, nbr, weight=minvalue) print('nx.shortest_path(GG, 1, 3) = {}.'.format(nx.shortest_path(GG, 1, 3))) #-------------------- # Classic graph operations: """ subgraph(G, nbunch): induced subgraph view of G on nodes in nbunch union(G1,G2): graph union disjoint_union(G1,G2): graph union assuming all nodes are different cartesian_product(G1,G2): return Cartesian product graph compose(G1,G2): combine graphs identifying nodes common to both complement(G): graph complement create_empty_copy(G): return an empty copy of the same graph class to_undirected(G): return an undirected representation of G to_directed(G): return a directed representation of G """ #-------------------- # Graph generators. # Use a call to one of the classic small graphs: petersen = nx.petersen_graph() tutte = nx.tutte_graph() maze = nx.sedgewick_maze_graph() tet = nx.tetrahedral_graph() # Use a (constructive) generator for a classic graph: K_5 = nx.complete_graph(5) K_3_5 = nx.complete_bipartite_graph(3, 5) barbell = nx.barbell_graph(10, 10) lollipop = nx.lollipop_graph(10, 20) # Use a stochastic graph generator: er = nx.erdos_renyi_graph(100, 0.15) ws = nx.watts_strogatz_graph(30, 3, 0.1) ba = nx.barabasi_albert_graph(100, 5) red = nx.random_lobster(100, 0.9, 0.9) #-------------------- # Read a graph stored in a file using common graph formats, such as edge lists, adjacency lists, GML, GraphML, pickle, LEDA and others. nx.write_gml(red, './test.gml') mygraph = nx.read_gml('./test.gml')
node_color='firebrick', alpha=0.8, ) #%% #有向图 DG = nx.DiGraph() DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)]) print(DG.out_degree(1, weight='weight')) print(DG.degree(1, weight='weight')) print(list(DG.successors(1))) print(list(DG.neighbors(1))) #有向图和无向图的转换 #%% #其他生成图的方法 petersen = nx.petersen_graph() tutte = nx.tutte_graph() maze = nx.sedgewick_maze_graph() tet = nx.tetrahedral_graph() K_5 = nx.complete_graph(5) K_3_5 = nx.complete_bipartite_graph(3, 5) barbell = nx.barbell_graph(10, 10) lollipop = nx.lollipop_graph(10, 20) #%% plt.subplot(111) nx.draw(K_3_5, with_labels=True, node_color='firebrick', alpha=0.8) #%%
def small_graphs(): print("Make small graph") G = nx.make_small_graph( ["adjacencylist", "C_4", 4, [[2, 4], [1, 3], [2, 4], [1, 3]]]) draw_graph(G) G = nx.make_small_graph( ["adjacencylist", "C_4", 4, [[2, 4], [3], [4], []]]) draw_graph(G) G = nx.make_small_graph( ["edgelist", "C_4", 4, [[1, 2], [3, 4], [2, 3], [4, 1]]]) draw_graph(G) print("LCF graph") G = nx.LCF_graph(6, [3, -3], 3) draw_graph(G) G = nx.LCF_graph(14, [5, -5], 7) draw_graph(G) print("Bull graph") G = nx.bull_graph() draw_graph(G) print("Chvátal graph") G = nx.chvatal_graph() draw_graph(G) print("Cubical graph") G = nx.cubical_graph() draw_graph(G) print("Desargues graph") G = nx.desargues_graph() draw_graph(G) print("Diamond graph") G = nx.diamond_graph() draw_graph(G) print("Dodechaedral graph") G = nx.dodecahedral_graph() draw_graph(G) print("Frucht graph") G = nx.frucht_graph() draw_graph(G) print("Heawood graph") G = nx.heawood_graph() draw_graph(G) print("House graph") G = nx.house_graph() draw_graph(G) print("House X graph") G = nx.house_x_graph() draw_graph(G) print("Icosahedral graph") G = nx.icosahedral_graph() draw_graph(G) print("Krackhardt kite graph") G = nx.krackhardt_kite_graph() draw_graph(G) print("Moebius kantor graph") G = nx.moebius_kantor_graph() draw_graph(G) print("Octahedral graph") G = nx.octahedral_graph() draw_graph(G) print("Pappus graph") G = nx.pappus_graph() draw_graph(G) print("Petersen graph") G = nx.petersen_graph() draw_graph(G) print("Sedgewick maze graph") G = nx.sedgewick_maze_graph() draw_graph(G) print("Tetrahedral graph") G = nx.tetrahedral_graph() draw_graph(G) print("Truncated cube graph") G = nx.truncated_cube_graph() draw_graph(G) print("Truncated tetrahedron graph") G = nx.truncated_tetrahedron_graph() draw_graph(G) print("Tutte graph") G = nx.tutte_graph() draw_graph(G)
# [1,2,3,4] GH6.edges() # [((2,3),(3,4)] # Retourne un graphe avec des aretes qui sont soit dans G soit dans H mais pas les deux ##### Graphes classiques ##### petersen=nx.petersen_graph() petersen.nodes() #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] petersen.edges() #[(0, 1), (0, 4), (0, 5), (1, 2), (1, 6), (2, 3), (2, 7), (3, 8), (3, 4), (4, 9), (5, 8), (5, 7), (6, 8), (6, 9), (7, 9)] tutte=nx.tutte_graph() tutte.nodes() tutte.edges() maze=nx.sedgewick_maze_graph() maze.nodes() maze.edges() tet=nx.tetrahedral_graph() tet.nodes() #[0, 1, 2, 3] tet.edges() #[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)] #Remarque : il existe de nombreux generateurs de graphes