def test_sedgewick(self): expected = True g = nx.sedgewick_maze_graph() for o in enumerate_dfs_ordering_naively(g): @spec_order(o) def func(g): return is_planar(g) actual = func(g) self.assertEqual(expected, actual)
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 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 generate_random_graph(): d = 1 class_map = {} G = nx.sedgewick_maze_graph() strG = nx.Graph() for s, t in G.edges: strG.add_edge(str(s), str(t)) G = strG for node in G.nodes(data=True): r = random.randint(0, d) node[1]['group'] = r class_map[node[0]] = r return G, class_map
gnx = nx.Graph() gnx.add_edge(0, 1) gnx.add_edge(1, 2) gnx.add_edge(1, 3) gnx.add_edge(4, 1) assert g.degree(0) == gnx.degree(0) assert g.degree(1) == gnx.degree(1) assert g.degree(4) == gnx.degree(4) diameter, center = g.diameter_center() assert (center in nx.center(gnx)) == True # Use network x to generate a random graph and replicate it as a custom graph. # Then check it returns the same value for some functions def verify_graph(nx_graph): g_gen = Graph() for edge in nx.edges(nx_graph): g_gen.add_edge(*edge) diameter, center = g_gen.diameter_center() assert (center in nx.center(nx_graph)) == True assert diameter == nx.diameter(nx_graph) verify_graph(nx.sedgewick_maze_graph()) verify_graph(nx.karate_club_graph())
import networkx as nx import pygraphviz as pgv from PIL import Image maze=nx.sedgewick_maze_graph() G=pgv.AGraph(strict=False,directed=True) G.add_nodes_from(maze.nodes()) G.add_edges_from(maze.edges()) G.layout(prog='dot') G.draw('file.png') Image.open('file.png').show()
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 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) #%%
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 t3(): mz = nx.sedgewick_maze_graph() showGraph(mz)
'chvatal': nx.chvatal_graph(), # 4-connected non-planar '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()
def test_sedgewick(self): expected = True actual = is_planar(nx.sedgewick_maze_graph()) self.assertEqual(expected, actual)
import networkx as nx import matplotlib.pyplot as plt from pprint import pprint from typing import List, Set, Dict, Tuple G = nx.random_lobster(6, 0.9, 0.9) G = nx.barabasi_albert_graph(8, 5) G = nx.watts_strogatz_graph(8, 3, 0.1) G = nx.erdos_renyi_graph(10, 0.15) G = nx.complete_bipartite_graph(3, 5) G = nx.dorogovtsev_goltsev_mendes_graph(2) G = nx.petersen_graph() G = nx.tutte_graph() G = nx.sedgewick_maze_graph() # cool # G = nx.tetrahedral_graph() # not cool G = nx.ladder_graph(8) G = nx.barbell_graph(5, 2) G = nx.turan_graph(10, 3) def g2d(g): return {k: {k1 for k1 in v} for k, v in g.adj.items()} #pprint(g2d(G)) #nx.draw_shell(G) #plt.show() # sorting nodes (with optional tails - additional strings for each node):
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)