def test_from_nx_map(self): g = nx.tutte_graph() vals = {n: np.random.random() for n in g.nodes} e = Extended.from_nx(g, vals) assert len(e.simplices) == len(g.nodes) + len(g.edges) assert set(vals.values()) == set(e.f.values())
def test_tutte(): G = nx.tutte_graph() for flow_func in flow_funcs: assert_equal(3, nx.node_connectivity(G, flow_func=flow_func), msg=msg.format(flow_func.__name__)) assert_equal(3, nx.edge_connectivity(G, flow_func=flow_func), msg=msg.format(flow_func.__name__))
def main(): #G = nx.Graph() G = nx.tutte_graph() #petersen_graph() print G.edges() #draw G nx.draw(G) plt.show()
def test_from_nx_weights(self): g = nx.tutte_graph() vals = {n: np.random.random() for n in g.nodes} nx.set_node_attributes(g, vals, "weight_str") e = Extended.from_nx(g, "weight_str") assert len(e.simplices) == len(g.nodes) + len(g.edges) assert set(vals.values()) == set(e.f.values())
def load_simple_example(): ''' Ucitava gotov jednostavan graf... :return: - vraca neusmeren afinitetan graf ''' g = nx.tutte_graph() # g = nx.gnp_random_graph(num, 0.06) make_affinity(g) return g
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 __init__(self): #generates all maps for i in range(0, 10): print('Generating map', i) graph = nx.tutte_graph() self.map_queue.append(graph) print('\nAll maps generated.\nStarting search protocols...') # generates astar path for each map while self.map_queue: print('\nGetting map...') curr_map = self.map_queue.popleft() # random source and target for each graph length = len(curr_map.nodes) source = randint(0, 1000) % length target = randint(0, 1000) % length while (source == target): target = randint(0, 1000) % length print('Finding best path...') curr_map = nx.astar_path(curr_map, source, target) curr_cost = len(curr_map) print('Setting delivery routes...') self.delivery_route_queue.append(curr_map) self.delivery_costs_queue.append(curr_cost) print('\nAll delivery routes found. \nStarting delivery...\n') while self.delivery_route_queue: curr_map = self.delivery_route_queue.popleft() print('Delivery route: ', curr_map) if self.delivery_costs_queue: cost = self.delivery_costs_queue.popleft() print('Delivery complete with time:', cost, 'min\n')
# [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
# グラフジェネレーターとグラフオペレータ # 典型的なグラフ操作 # 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 plot_graph(graph=nx.tutte_graph(), layout=nx.kamada_kawai_layout): """ Make plotly visualization of networkx graph. node_size -> betweeness centrality node_color -> closeness centrality """ b_cents = nx.betweenness_centrality(graph) c_cents = nx.closeness_centrality(graph) d_cents = graph.degree() edge_x = [] edge_y = [] pos = layout(graph) for edge in graph.edges: x0, y0 = pos[edge[0]] x1, y1 = pos[edge[1]] edge_x.append(x0) edge_x.append(x1) edge_x.append(None) edge_y.append(y0) edge_y.append(y1) edge_y.append(None) edge_trace = go.Scatter( x=edge_x, y=edge_y, line=dict(width=0.5, color='#888'), hoverinfo='none', mode='lines') node_x = [] node_y = [] node_texts = [] node_degrees = [] node_closenesses = [] node_betweenesses = [] for node in graph.nodes(): x, y = pos[node] node_x.append(x) node_y.append(y) node_degree = d_cents[node] node_closeness = c_cents[node] node_betweeness = b_cents[node] node_degrees.append(node_degree) node_closenesses.append(node_closeness) node_betweenesses.append(node_betweeness) node_text = str(node) + "<br>Degree: " + str(node_degree) node_texts.append(node_text) node_trace = go.Scatter( x=node_x, y=node_y, mode='markers', hoverinfo='text', marker=dict( opacity=1, showscale=True, colorscale='Jet', reversescale=False, color=[], size=[], colorbar=dict( thickness=15, title='Closeness', xanchor='left', titleside='right' ), line=dict( width=1, color='Black' ), ) ) node_degrees = np.array(node_degrees) node_closenesses = np.array(node_closenesses) node_betweenesses = np.array(node_betweenesses) size_scaler = MMS(feature_range=(7.5, 17.5)) node_betweenesses = size_scaler.fit_transform(node_betweenesses.reshape(-1,1)).ravel() node_trace.marker.color = node_closenesses node_trace.marker.size = node_betweenesses node_trace.text = node_texts fig = go.Figure( data=[ edge_trace, node_trace ], layout=go.Layout( autosize=True, titlefont_size=16, showlegend=False, hovermode='closest', margin=dict(b=20,l=5,r=5,t=40), xaxis=dict(showgrid=False, zeroline=False, showticklabels=False), yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)) ) iplot(fig)
import networkx import mv g = networkx.tutte_graph() print mv.matching_from_networkx(g)
def __draw(g, ax=None, title=None, pos=None): if not ax: ax = plt.gca() nx.draw_networkx(g, pos=pos, ax=ax, node_color='g', with_labels=False, node_size=20) if pos: pts = pos.values() pts += [[100, 100], [100, -100], [-100, 0]] voronoi_plot_2d(Voronoi(pts), ax=ax, show_vertices=False, line_alpha=0.25) if title: ax.set_title(title) ax.set_xlim([-1.2, 1.2]) ax.set_ylim([-1.2, 1.2]) ax.set_axis_off() ax.set_aspect('equal') if __name__ == '__main__': fname, g = 'tutte3.png', nx.tutte_graph() fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4)) te = tutte_embedding(g) __draw(g, ax1, 'ordinary Tutte\'s embedding', te.pos()) __draw(g, ax2, 'centroidal Voronoi relaxation', te.rpos()) # plt.savefig(fname, bbox_inches='tight') plt.tight_layout() plt.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 generate_tutte(params={}): G = nx.tutte_graph() return G, None
def test_tutte(self): expected = True actual = is_planar(nx.tutte_graph()) self.assertEqual(expected, actual)
from __future__ import division import itertools from utils import weightify, connect_db from random import uniform from networkx import tutte_graph from rules import ant_system_update from ants import ProportionalAnt graph = tutte_graph() start, end = 44, 33 generations, max_steps = 250, 25 agents_list = [5, 10, 15, 50, 100] learning_rate = 0.01 if __name__ == '__main__': db = connect_db('alos-experiment2b') weightify(graph, uniform, 0, 1) for agents in agents_list: # Database setup name = '{0}_{1}' collection_agents = db[name.format('agents', agents)] collection_pheromones = db[name.format('pheromones', agents)] for i in range(generations):
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 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')
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)
import networkx as nx graph = nx.tutte_graph() req_node = 7 queue = [0] done = [] found_node = None while len(done) < len(graph.nodes): for i in queue: if i == req_node: found_node = i break else: for a in graph.adj[i]: if a not in queue and a not in done: queue.append(a) queue.remove(i) done.append(i) if found_node is not None: break print(found_node)
def test_tutte(): G = nx.tutte_graph() assert_equal(3, nx.node_connectivity(G)) assert_equal(3, nx.edge_connectivity(G))
'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) # from matplotlib import pyplot as plt # nx.draw_networkx(g) # plt.show()
with_labels=False, node_size=20) pts = nx.get_node_attributes(g, 'coord').values() pts += [[100, 100], [100, -100], [-100, 0]] voronoi_plot_2d(Voronoi(pts), ax=ax, show_vertices=False, line_alpha=0.25) ax.set_xlim([-1.2, 1.2]) ax.set_ylim([-1.2, 1.2]) ax.set_title(title) ax.set_axis_off() ax.set_aspect('equal') if __name__ == '__main__': title, g = 'tutte2', nx.tutte_graph() fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(8, 4)) c = get_cycle(g, 21) fix_outer_cycle_pos(g, c) pos = fix_all_pos(g) draw(g, ax1, 'ordinary Tutte\'s embedding') pos = relax(pos, c) for v, coord in enumerate(pos): g.node[v]['coord'] = coord draw(g, ax2, 'centroidal Voronoi relaxation') # plt.tight_layout() # plt.show() plt.savefig(title + '.png', bbox_inches='tight')
def test_tutte(): G = nx.tutte_graph() for flow_func in flow_funcs: errmsg = f"Assertion failed in function: {flow_func.__name__}" assert 3 == nx.node_connectivity(G, flow_func=flow_func), errmsg assert 3 == nx.edge_connectivity(G, flow_func=flow_func), errmsg