print(nx.diameter(g2)) print("Center") print(nx.center(g2)) print("Girth") print(len(min(nx.cycle_basis(g2)))) print("k-vertex-connectivity") print(nx.node_connectivity(g2)) print("k-edge-connectivity") print(nx.edge_connectivity(g2)) #c nodes_color = [] for i in (g2.nodes()): #массив цветов вершин val = nx.greedy_color(g2).get(i) nodes_color.append(val) nx.draw_planar(g2, with_labels=True, node_color=nodes_color) plt.savefig("vertex_color.png") plt.clf() #d edges_color = [] for (v1, v2) in (g2.edges()): #массив цветов ребер val = nx.greedy_color(nx.line_graph(g2)).get((v1, v2)) if val == None: val = nx.greedy_color(nx.line_graph(g2)).get((v2, v1)) edges_color.append(val) nx.draw_planar(g2, with_labels=True, edge_color=edges_color) plt.savefig("edges_color.png") plt.clf() #e
def draw_planar(G): nx.draw_planar(G, with_labels=True) make_plot()
def main(): # Tasks 1 and 2 # Create a graph B = nx.Graph() G = nx.Graph() D = nx.Graph() # Add nodes from a list G.add_nodes_from("ABCDE") B.add_nodes_from("ABCDEFGHIJKLMNOP") B2 = B DFS = B DFS2 = B # Add edges from a list G.add_edges_from([('A','B'),('A','C'),('B','C'),('B','D'),('B','E'),('C','B'),\ ('C','D'),('C','E'),('D','B'),('D','C'),('D','E'),('E','B'),('E','C'),('E','D')]) B.add_edges_from([('A','B'),('A','F'),('A','E'),('B','C'),('B','F'),('C','D'),('C','G'), \ ('D','G'),('E','F'),('E','I'),('F','I'),('G','J'),('H','K'),('H','L'), \ ('I','J'),('I','M'),('K','L'),('K','O'),('L','P'),('M','N')]) # DFS print('\n\nDFS\n') # DFS Path from A to G print('\nDFS Path from A to G') print(dfs_path.dfs_path(DFS, 'A', 'G')) # DFS trees DFS = nx.dfs_tree(DFS, 'A') DFS2 = nx.dfs_tree(DFS2, 'H') plt.subplot(121) nx.draw_planar(DFS, with_labels=True, font_weights='bold') plt.subplot(122) nx.draw_planar(DFS2, with_labels=True, font_weights='bold') plt.show() # DFS Tree Printout print('\nDFS Tree from A') print(nx.dfs_successors(DFS, 'A')) print('\nDFS Tree from H') print(nx.dfs_successors(DFS2, 'H')) # BFS print('\n\nBFS\n') # BFS Path from A to G print('\nBFS Path from A to G') print(bfs_path.bfs_path(B, 'A', 'G')) # BFS trees B = nx.bfs_tree(B, 'A') B2 = nx.bfs_tree(B2, 'H') plt.subplot(121) nx.draw_planar(B, with_labels=True, font_weights='bold') plt.subplot(122) nx.draw_planar(B2, with_labels=True, font_weights='bold') plt.show() # BFS Tree Printout print('\nBFS Tree from A') print(nx.dfs_successors(B, 'A')) print('\nBFS Tree from H') print(nx.dfs_successors(B2, 'H')) # Task 3 print('\nDiGraph\n') Di = nx.DiGraph() Di.add_nodes_from(range(1, 13)) Di.add_edges_from([(1, 3), (2, 1), (3, 2), (3, 5), (4, 1), (4, 2), (4, 12), (5, 6), (5, 8), (6, 8), (6, 7), (6, 10), (7, 10), (8, 9), (8, 10), (9, 5), (9, 11), (10, 9), (10, 11), (11, 12)]) #pos = nx.planar_layout(Di) nx.draw_spring(Di, arrows=True, with_labels=True, font_weight='bold') plt.show() # Counting the number of SCC in the Digraph print("\nNumber of Strongly Connected Components: ") print(nx.number_strongly_connected_components(Di)) # Display SCC print("\nStrongly Connect Components: ") comp = nx.strongly_connected_components(Di) for c in comp: print(c, '\n') # Find the DAG of a graph A = nx.DiGraph() A = nx.condensation(Di) # Display resulting DAG print('\nDAG: ') print(A.nodes(data=True)) nx.draw_spring(A, with_labels=True, font_weight='bold') plt.show() # Verify that new 'meta graph' is a DAG print("\nDigraph is now a DAG: ") print(nx.is_directed_acyclic_graph(A)) # Topological sort of DAG nodes print("\nTopological Order: ") print(list(list(nx.topological_sort(A)))) # Task 4 # DijkstraAlgo # Build Graph from Dijkstra and Kruskal D.add_nodes_from("ABCDEFGHI") D.add_weighted_edges_from([('A', 'B', 22), ('A', 'C', 9), ('A', 'D', 12), ('B', 'H', 34), ('B', 'F', 36), ('B', 'C', 35), ('B', 'A', 22), ('C', 'A', 9), ('C', 'D', 4), ('C', 'E', 65), ('C', 'F', 42), ('C', 'B', 35), ('D', 'A', 12), ('D', 'C', 4), ('D', 'E', 33), ('D', 'I', 30), ('E', 'C', 65), ('E', 'D', 33), ('E', 'F', 18), ('E', 'G', 23), ('F', 'B', 36), ('F', 'C', 42), ('F', 'E', 18), ('F', 'G', 39), ('F', 'H', 24), ('G', 'E', 23), ('G', 'F', 39), ('G', 'H', 25), ('G', 'I', 21), ('H', 'B', 34), ('H', 'F', 24), ('H', 'G', 35), ('H', 'I', 19), ('I', 'D', 30), ('I', 'G', 21), ('I', 'H', 19)]) # Dijkstra's Algorithm print('\n\nDijkstra\'s Algorithm') pred, dist = nx.dijkstra_predecessor_and_distance(D, 'A') print('\nDijkstra\'s Algorithm Graph') print(sorted(pred.items())) print('\nDijkstra\'s Algorithm Distance') print(sorted(dist.items())) print( '\nDijkstra\'s Algorithm shortest path from source node to target node' ) print(nx.dijkstra_path(D, 'A', 'I')) # kruskal's Algorithm print('\n\nKruskal\'s Algorithm') print('\nMinimum Spanning Tree') T = nx.minimum_spanning_tree(D, algorithm='kruskal') nx.draw_spring(T, with_labels=True, font_weights='bold') plt.show() print(sorted(T.edges(data=True)))
import networkx as nx import matplotlib.pyplot as plt g = nx.Graph() g.add_edges_from([(0, 1), (0, 9), (1, 2), (1, 3), (1, 9), (2, 3), (3, 4), (3, 5), (3, 9), (4, 5), (5, 6), (5, 7), (5, 9), (6, 7), (7, 8), (7, 9), (8, 9)]) nx.draw_planar(g, labels=None) plt.show() print(g.edges)
import networkx as nx import matplotlib.pyplot as plt triangle_graph = nx.from_edgelist([(1, 2), (2, 3), (3, 1)], create_using=nx.DiGraph) nx.draw_planar(triangle_graph, with_labels=True, node_size=1000, node_color="#ffff8f", width=0.8, font_size=14) plt.show() # Reference: https://networkx.org/nx-guides/content/algorithms/dag/index.html
import networkx as nx import matplotlib.pyplot as plt gaf = nx.Graph() for i in range(int(input())): gaf.add_edge(*map(int, input().strip().split(' '))) print(gaf.edges()) nx.draw_planar(gaf, labels=None, font_size=12, font_color='k', font_family='sans-serif', font_weight='normal', alpha=1.0, bbox=None, ax=None) plt.show()
edges.append((vertex1, vertex2)) print("Want to enter another vertex? Y/N") counter = input(" >>>") if (counter != 'Y'): break edges # In[17]: #Graph Initialisation(Will be converted into an interface later) G = nx.Graph() G.add_nodes_from(vertices) G.add_edges_from(edges) #Draws our PTP Graph plt.subplot(111) nx.draw_planar(G, with_labels=True) plt.show() # In[18]: # Conversion to directed H = G.to_directed() # In[14]: # Get all triangles all_cycles = list(nx.simple_cycles(H)) all_triangles = [] for cycle in all_cycles: if (len(cycle) == 3): all_triangles.append(cycle)
def draw2(self): G = self.nx_graph() G.remove_node(0) nx.draw_planar(G, with_labels=True) plt.show()
for v in visitedResult: for i in range(len(v) - 1): G[v[i]][v[i + 1]]['color'] = 'blue' for i in range(len(pathResult) - 1): G[pathResult[i]][pathResult[i + 1]]['color'] = 'red' red_patch = mpatches.Patch(color='red', label='Đường đi') blue_patch = mpatches.Patch(color='blue', label='Đã duyệt qua') grey_patch = mpatches.Patch(color='grey', label='Chưa duyệt qua') plt.legend(handles=[red_patch, blue_patch, grey_patch]) edge_colors = [G[e[0]][e[1]]['color'] for e in G.edges()] nx.draw_planar(G, with_labels=True, edge_color=edge_colors, arrows=True, arrowsize=15, node_color='pink') plt.savefig("[Output] BFS_Graph.png") plt.show() sys.stdout.close() sys.stdout = orig_stdout #----------------------------------------DFS-------------------------------------# sys.stdout = open('[Output] DFS_StepByStep.txt', 'wt') print("DFS Step By Step") def DFS_Path(graph, start, end, step): stack = [(start, [start])] visited = []
with open('input.txt') as file: for line in file: input_data = line.replace('\n', '') input_data = input_data.split(',') if input_data[0] not in countries: countries.append(input_data[0]) if input_data[1] not in countries: countries.append(input_data[1]) if input_data[1] == 'VA': edges.append((input_data[0], input_data[1], int(input_data[2]))) if int(input_data[2]) != 0: edges.append((input_data[0], input_data[1], int(input_data[2]))) Full_graph = nx.Graph() Full_graph.add_nodes_from(countries) Full_graph.add_weighted_edges_from(edges, weight="weight") nx.draw_planar(Full_graph, with_labels=True, font_weight='bold') plt.show() Main_graph = Full_graph.subgraph(max(nx.connected_components(Full_graph))) print("b", file=main) print("Number of nodes:", Full_graph.number_of_nodes(), file=main) print("Number of edges:", Full_graph.number_of_edges(), file=main) print("Diameter:", nx.algorithms.distance_measures.diameter(Main_graph), file=main) print("Radius", nx.algorithms.distance_measures.radius(Main_graph), file=main) print("Center:", nx.center(Main_graph), file=main) print("Girth:", min(nx.algorithms.minimum_cycle_basis(Main_graph)), file=main) maximum_degree = 0 minimum_degree = 100 for i in Main_graph.nodes: if Main_graph.degree[i] > maximum_degree:
if levels[i] > levels[s]: tree[s][i] = 0 return tree, levels # Driver code # Create a graph given in # the above diagram g = Graph() g.addEdge(1, 2) g.addEdge(1, 3) g.addEdge(2, 3) g.addEdge(2, 4) g.addEdge(4, 5) g.addEdge(4, 6) g.addEdge(4, 7) g.addEdge(5, 6) g.addEdge(6, 7) tree5, levels5 = g.BFS(3) # https://stackoverflow.com/questions/52763876/create-a-weighted-networkx-digraph-from-python-dict-of-dicts-descripton for k, d in tree5.items(): for ik in d: #d[ik] = {'weight': 6} pass nxgraph = nx.DiGraph(tree5) nx.draw_planar(nxgraph, with_labels=True) # nx.draw_networkx_edge_labels(nxgraph, pos=nx.spring_layout(nxgraph)) plt.show() print()
print(nx.algorithms.tree.is_forest(G=circuit)) residential = nx.algorithms.cut_size(G=circuit, S={i for i in range(1, 6)}, T={j for j in range(14, 16)}) print(residential) print(nx.algorithms.is_directed_acyclic_graph(G=circuit)) branching = nx.algorithms.dag_to_branching(G=circuit) nx.draw_planar(G=branching, with_labels=True, node_color='g', node_size=800, font_size=14, width=0.8) plt.show() print('\n', nx.algorithms.maximum_branching(G=circuit)) print('\n') print(nx.is_tree(circuit), '\n') print(nx.is_forest(circuit), '\n') print(nx.is_directed_acyclic_graph(circuit), '\n') print(nx.is_arborescence(circuit), '\n') print(nx.is_branching(circuit))
def plot_single_directed(reader: MBoxReader, id: int = False, showtitle: bool = False) -> None: """ Plot a directed graph from a single email, as determined by `id`. If `showtitle` is `True`, render the plot with a email subject and date as title. Usage: reader = MboxReader('path-to-mbox.mbox') plot_single_directed(reader, 300) plots the 300th email from the mbox Args: reader (MBoxReader): A `MBoxReader` object id (int, optional): `id` of the email in the `MBoxReader`. Defaults to False. showtitle (bool, optional): If `True`, render the plot with a email subject and date as title. Defaults to False. """ len_reader = len(reader) if not id: email = reader.mbox[len_reader - 1] else: email = reader.mbox[id] emailmsg = extract_meta(email) subject = textwrap.fill(emailmsg.subject, 40) sender = emailmsg.sender.name if len( emailmsg.sender.name) != 0 else emailmsg.sender.email.split('@')[0] plt.figure(figsize=(9, 6)) G = nx.DiGraph(name='Single Email Flow') for recipient in emailmsg.recipients: rec = recipient.name G.add_edge(sender, rec if len(rec) != 0 else recipient.email, message=subject, color='darkorchid', weight=3) for cc in emailmsg.cc: ccc = cc.name G.add_edge(sender, ccc if len(ccc) != 0 else cc.email, message='cc', color='lightsteelblue', weight=2) colors = nx.get_edge_attributes(G, 'color').values() weights = nx.get_edge_attributes(G, 'weight').values() edge_labels = nx.get_edge_attributes(G, 'message') pos = nx.planar_layout(G) # nx.draw_spectral(G,node_size=0, alpha=0.8, edge_color=colors, width=list(weights), font_size=8, with_labels=True) nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, font_size=6, label_pos=0.5) nx.draw_planar(G, node_size=0, alpha=1, edge_color=colors, width=list(weights), font_size=8, font_weight='bold', with_labels=True, verticalalignment='bottom') if showtitle: font = { "fontname": "Helvetica", "color": "k", "fontweight": "bold", "fontsize": 8 } plt.title(subject + '\n Delivery date: ' + emailmsg.date.strftime("%m/%d/%Y"), fontdict=font) plt.tight_layout(pad=0.5) plt.axis('off') plt.show()
path_edges = [] for y in range(0,len(x)-1): if [x[y],x[y+1]] in edgeList: path_edges.append([x[y],x[y+1]]) else: path_edges.append([x[y+1],x[y]]) left = np.asarray(path_edges)[:,0] right = np.asarray(path_edges)[:,1] if len(set(list(left))) == len(list(left)) and len(set(list(right))) == len(list(right)): # no collider on path so path is active d_connected = 1 else: d_connected = 0 # colliders on path so path is inactive if d_connected == 0: output_string = "node " + str(source) + " and node " + str(destination) + " are d-separated" else: output_string = "node " + str(source) + " and node " + str(destination) + " are d-connected" plt.title(output_string) nx.draw_planar(G, with_labels=True, font_weight='bold',node_size=400) plt.show()
driver_sigma=args.ds, ) from traffic.make_env import make_env env = make_env(args.exp_name, **env_kwargs) obs_dim = env.observation_space.low.size action_dim = env.action_space.n label_num = env.label_num label_dim = env.label_dim from graph_builder_multi import MultiTrafficGraphBuilder gb = MultiTrafficGraphBuilder( input_dim=4, node_num=env.max_veh_num + 1, ego_init=torch.tensor([0., 1.]), other_init=torch.tensor([1., 0.]), ) obs = env.reset() obs_batch = torch.tensor([obs]) valid_mask = gb.get_valid_node_mask(obs_batch) print('valid_mask: ', valid_mask) x, edge_index = gb(obs_batch) print('x: ', x) print('edge_index: ', edge_index) data = Data(x=x, edge_index=edge_index) ng = pyg_utils.to_networkx(data) networkx.draw_planar(ng) plt.show()
df1 = pd.read_csv('Prueba.csv', sep=';') df1.describe() g= nx.DiGraph() for row in range(len(df1)): g.add_edge(df1.loc[row,"origen"],df1.loc[row,"destino"]) g.nodes(data=True) """BOG APARECE CON UN ESPACIO ADICIONAL""" #PARA GRAFICAR EL NODO EN FORMA DE CIRCULO nx.draw_circular(g, node_color="lightblue", edge_color="gray", font_size=24, width=2, with_labels=True, node_size=3500 ) nx.draw_planar(g,node_color="lightblue", edge_color="gray", font_size=24, width=2, with_labels=True, node_size=3500) nx.draw_spectral(g,node_color="lightblue", edge_color="gray", font_size=24, width=2, with_labels=True, node_size=3500)
def vis_causal_net(adata, key='RDI', layout='circular', top_n_edges=10, edge_color='gray', figsize=(6, 6)): """Visualize inferred causal regulatory network This plotting function visualize the inferred causal regulatory network inferred from Scribe. Arguments --------- adata: `Anndata` Annotated Data Frame, an Anndata object. key: `str` (default: `RDI`) The key points to the type of causal network to be used for network visualization. layout: `str` (Default: circular) A string determines the graph layout function supported by networkx. Currently supported layouts include circular, kamada_kawai, planar, random, spectral, spring and shell. top_n_edges: 'int' (default 10) Number of top strongest causal regulation to visualize. edge_color: `str` (Default: gray) The color for the graph edge. figsize: `tuple` (Default: (6, 6)) The tuple of the figure width and height. Returns ------- A figure created by nx.draw and matplotlib. """ if 'causal_net' not in adata.uns.keys(): raise ( 'causal_net is not a key in uns slot. Please first run causal network inference with Scribe.' ) df_mat = adata.uns['causal_net'][key] ind_mat = np.where(df_mat.values - df_mat.T.values < 0) tmp = np.where(df_mat.values - df_mat.T.values < 0) for i in range(len(tmp[0])): df_mat.iloc[tmp[0][i], tmp[1][i]] = np.nan df_mat = df_mat.stack().reset_index() df_mat.columns = ['source', 'target', 'weight'] if top_n_edges is not None: ind_vec = np.argsort(-df_mat.loc[:, 'weight']) df_mat = df_mat.loc[ind_vec[:top_n_edges], :] G = nx.from_pandas_edgelist(df_mat, source='source', target='target', edge_attr='weight', create_using=nx.DiGraph()) G.nodes() W = [] for n, nbrs in G.adj.items(): for nbr, eattr in nbrs.items(): W.append(eattr['weight']) options = { 'width': 300, 'arrowstyle': '-|>', 'arrowsize': 1000, } plt.figure(figsize=figsize) if layout is None: nx.draw(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options=options) elif layout is "circular": nx.draw_circular(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options=options) elif layout is "kamada_kawai": nx.draw_kamada_kawai(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options=options) elif layout is "planar": nx.draw_planar(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options=options) elif layout is "random": nx.draw_random(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options=options) elif layout is "spectral": nx.draw_spectral(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options=options) elif layout is "spring": nx.draw_spring(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options=options) elif layout is "shell": nx.draw_shell(G, with_labels=True, node_color='skyblue', node_size=100, edge_color=edge_color, width=W / np.max(W) * 5, edge_cmap=plt.cm.Blues, options=options) else: raise ('layout', layout, ' is not supported.') plt.show()
def generateGraph (numberCode, colors): G = nx.Graph() for i in range(0,(len(numberCode[0]) )): G.add_edge(numberCode[0][i], numberCode[colors[0]+1][i], color='r', weight=2) G.add_edge(numberCode[0][i], numberCode[colors[1]+1][i], color='g', weight=2) G.add_edge(numberCode[0][i], numberCode[colors[2]+1][i], color='b', weight=2) #print(numberCode[0][i], numberCode[colors[0]+1][i], numberCode[colors[1]+1][i], numberCode[colors[2]+1][i]) return G numberCode = generateNumberCode(letterCode) print(numberCode) G = generateGraph(numberCode, colors) labels = {0:0} edges = G.edges() colors = [G[u][v]['color'] for u,v in edges] weights = [G[u][v]['weight'] for u,v in edges] nx.draw_planar(G, with_labels=labels, edges=edges, edge_color=colors, width=weights) plt.figure() nx.draw_spring(G, with_labels=labels, edges=edges, edge_color=colors, width=weights) plt.figure() nx.draw_shell(G, with_labels=labels, edges=edges, edge_color=colors, width=weights) plt.figure() nx.draw_spectral(G, with_labels=labels, edges=edges, edge_color=colors, width=weights) plt.figure() nx.draw_kamada_kawai(G, with_labels=labels, edges=edges, edge_color=colors, width=weights) plt.show()
import math import matplotlib.pyplot as plt import networkx as nx graph = nx.Graph() graph.add_edge('y', 'x', function=math.cos) graph.add_node(math.cos) nx.draw_planar(G=graph) plt.show()
'''Reads all component configuration parameters from the given config directory. Keyword arguments: config_dir -- absolute path to a component configuration directory ''' monitor_config_params = ConfigUtils.get_config_params(config_dir) return monitor_config_params def __get_component_graph( self, component_config: Sequence[ComponentMonitorConfig]) -> nx.DiGraph: '''Creates a directed networkx graph from the given configuration parameters, such that the graph nodes represent components and the edges represent dependencies between the components (an arrow from component A to component B means that A depends on B). ''' network = nx.DiGraph() for component in component_config: network.add_node(component.component_name) for dependency in component.component_dependencies: network.add_edge(component.component_name, dependency) return network if __name__ == '__main__': config_file = 'config/component_monitoring_config.yaml' component_network = ComponentNetwork(config_file) nx.draw_planar(component_network.network, with_labels=True) plt.show()
import matplotlib.pyplot as plt import networkx as nx graph = nx.Graph() edge = [('a', 'b', 0.3), ('b', 'c', 0.9), ('a', 'c', 0.5), ('c', 'd', 1.2)] graph.add_weighted_edges_from(edge) nx.draw_planar(G=graph, with_labels=True, node_color='y', node_size=800, font_size=14, width=0.8) plt.show() print(nx.dijkstra_path(G=graph, source='a', target='d')) # Reference: # 1.https://networkx.org/documentation/stable/reference/introduction.html#algorithms
import networkx as nx import matplotlib.pyplot as plt vertices = ['A', 'B', 'C', 'D', 'E'] edges = [('A', 'B'), ('B', 'C'), ('B', 'D'), ('C', 'E'), ('E', 'D'), ('D', 'C')] directed_graph = nx.DiGraph() directed_graph.add_nodes_from(vertices) directed_graph.add_edges_from(edges) nx.draw(G=directed_graph) nx.draw_planar(G=directed_graph) plt.show()