def draw_graph(relationships): G = nx.Graph() add_edges(relationships, G) elarge = [(u, v) for (u, v, d) in G.edges(data=True)] # positions for all nodes pos = nx.spring_layout(G, k=1, seed=1) # nodes nx.draw_networkx_nodes(G, pos, node_size=90, node_color="k") # edges nx.draw_networkx_edges(G, pos, edgelist=elarge, width=0.1, edge_color="b") # labels nx.draw_networkx_labels(G, pos, font_size=0.3, font_family="sans-serif", font_color="w") # no_overwrite("output\\graph", ".pdf") no_overwrite("output\\graph", ".png")
def plot_MRF(adj_mat, thresh=0.01, ax=None): # Filter out subthreshold values in adj_mat adj_mat = np.where( np.abs(adj_mat) > thresh, adj_mat, np.zeros(adj_mat.shape)) # Create graph object G = nx.Graph(adj_mat) pos = nx.layout.circular_layout(G, scale=0.5) node_colors = [palette[n] for n in G.nodes] edge_colors = [v['weight'] for _, _, v, in G.edges(data=True)] vmin, vmax = min(edge_colors), max(edge_colors) cmap = plt.get_cmap() nx.draw_networkx_nodes(G, pos, ax=ax, node_color=node_colors, node_size=700) nx.draw_networkx_edges(G, pos, ax=ax, edge_color=edge_colors, edge_cmap=cmap, edge_vmin=vmin, edge_vmax=vmax, width=2.5) # Colourbar sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=vmax, vmax=vmin)) fig.colorbar(sm, orientation="horizontal", pad=0.01, ax=ax) nx.draw_networkx_labels(G, pos, ax=ax)
def draw_graph_labels(graph, nodes=[], colors=[]): # Draw the graph pos = graphviz_layout(graph, prog='neato') nx.draw_networkx_nodes(graph, pos, nodelist=graph.nodes(), node_color="blue") for i, x in enumerate(nodes): nx.draw_networkx_nodes(graph, pos, nodelist=x, node_color=colors[i]) nx.draw_networkx_edges(graph, pos, graph.edges(), edge_color="black") plt.axis('off') plt.show()
def AnimateEdge(G, pos, guest, host): # *NOTE* Unfortunately, this function calls library package methods # that add a very substantial amount of empirical time # since it must draw an edge to an animated graph # If the user does not care to see an animated graph, # then the user can choose not to do so when prompted # upon running the program. # Add an edge to the directed graph data structure G.add_edge(host, guest) # Draw a green arrow for that edge on the animation window nx.draw_networkx_edges(G, pos, edgelist=[(host, guest)], edge_color='g') # Provide negligible delay of 1 picosecond so that # animation window can be displayed plt.pause(0.000000000001)
def save_graph(graph, n, p): #initialze Figure plt.figure(num=None, figsize=(20, 20), dpi=80) plt.axis('off') fig = plt.figure(figsize=(50, 40)) pos = nx.circular_layout(graph) nx.draw_networkx_nodes(graph, pos) nx.draw_networkx_edges(graph, pos) nx.draw_networkx_labels(graph, pos) file_name = 'Q8_Assets/SmallWorld_N_' + str(n) + '_P_' + str(p) + '.pdf' plt.savefig(file_name, bbox_inches="tight") plt.close(fig) del fig
def save_graph(graph, n, p): #initialze Figure plt.figure(num=None, figsize=(20, 20), dpi=80) plt.axis('off') fig = plt.figure(figsize=(20, 15)) pos = nx.spring_layout(graph) nx.draw_networkx_nodes(graph, pos) nx.draw_networkx_edges(graph, pos) nx.draw_networkx_labels(graph, pos) file_name = 'Q7_Assets/ErdosRenyi_N_' + str(n) + '_P_' + str(p) + '.pdf' plt.savefig(file_name, bbox_inches="tight") plt.close(fig) del fig
def refresh(x): for i in range(1): lista_caminho_formiga = [] rota = [] for j in range(formiga): list_caminho = [] caminho(grafo, origem, destino, list_caminho) removeCiclo(list_caminho) lista_caminho_formiga.append(list_caminho) distanciaTotal = atualizaTaxaFeromonio(grafo, lista_caminho_formiga, coeficiente_evaporacao, lista_vertice) ax2.plot_date(lista_formigas, distanciaTotal) ax2.bar(lista_formigas, distanciaTotal, color='white', label='teste') ax2.plot(distanciaTotal, lw=0.02) # ax2.hist(distanciaTotal) print(distanciaTotal) for j in range(formiga): for k in range(len(lista_caminho_formiga[j]) - 1): rota.append((lista_caminho_formiga[j][k], lista_caminho_formiga[j][k + 1])) nx.draw_networkx_edges(mapa, pos, edgelist=rota, width=2, alpha=0.01, edge_color='black') nx.draw_networkx_edges(mapa, pos, edgelist=rota_total, width=2.7, alpha=0.0095, edge_color='w') ax2.set_title('Comportamento das Formigas') ax2.set_ylabel('Distância (KM)') ax2.set_xticks(lista_formigas) ax2.set_xticklabels(distanciaTotal) ax2.set_xlabel('Distância Percorrida até o destino (KM)')
def drawGraph(filename): location = latlong('latlong_us.txt') g = nx.Graph() with open(filename) as f: for line in f: src, dst = line.split('->') tmp = src.split(':')[1].split(',') src = tmp[0].replace(' ', '') + ',' + tmp[1].strip() tmp = dst.split(':')[1].split(',') dst = tmp[0].strip().replace(' ', '') + ',' + tmp[1].strip().split()[0] g.add_edge(src, dst) print len(g.nodes()) print len(g.edges()) pos = {} cnt = 0 for node in g.nodes(): cnt += 1 inx = None if location.has_key(node): inx = node else: for key in location.keys(): addr = node.split(',') if (addr[0] in key and addr[1] in key): inx = key if not inx: print node print "%d/%d" % (cnt, len(g.nodes())) raise pos[node] = (180-location[inx][1], location[inx][0]) #pos=nx.graphviz_layout(g,prog="fdp") #pos=nx.spring_layout(g) plt.figure(figsize=(10,8)) #plt.axis('off') plt.xticks([]), plt.yticks([]) nx.draw_networkx_nodes(g, pos = pos, node_color = 'red', node_size = 30, with_labels=False) nx.draw_networkx_edges(g,pos,alpha=0.4) plt.axis('equal') plt.show()
def get_concept_network(search_regex_string: str, min_count: int = 1, highlight_regex_string: str = "", nearest_neighbor_count: int = 0) -> str: """Extracts a network of words from vector data in an AI model.""" graph: Graph = Graph() w2v: Word2Vec = Word2Vec.load(Config.PANEGYRICI_LATINI_MODEL_PATH) search_regex: Pattern[str] = re.compile(search_regex_string) keys: List[str] = [x for x in w2v.wv.vocab if search_regex.match(x)] if not nearest_neighbor_count: # adjust the graph size depending on the given parameters to prevent bloating nearest_neighbor_count: int = max( int(100 * (min_count**2) / (1 + len(keys))), 2) keys = [ x for x in keys if all(y.isalpha() for y in x) and w2v.wv.vocab[x].count >= min_count ] edge_color: Tuple[float, float, float] = (0.6, 0.6, 0.6) add_edges(keys, w2v, nearest_neighbor_count, min_count, graph) pos: dict = nx.spring_layout(graph, k=0.7, iterations=100) pyplot.clf() pyplot.subplot() nx.draw(graph, pos, node_size=25, with_labels=True, alpha=1) colors: List[Tuple[float, float, float]] = [] highlight_regex: Pattern[str] = re.compile(highlight_regex_string) for edge in graph.edges: if highlight_regex_string and any( highlight_regex.match(x) for x in edge) and any(search_regex.match(x) for x in edge): colors.append((1, 0, 0)) else: colors.append(edge_color) nx.draw_networkx_edges(graph, pos, alpha=1, edge_color=colors) pyplot.savefig(fname=Config.NETWORK_GRAPH_TMP_PATH, format="svg", bbox_inches="tight") xml_string: str = open(Config.NETWORK_GRAPH_TMP_PATH).read() os.remove(Config.NETWORK_GRAPH_TMP_PATH) svg_string: str = re.findall(r"<svg[\s\S]*?svg>", xml_string)[0] return svg_string
def draw_graph_with_labels_training(GraphGenerationObject): # Draw the graph pos = graphviz_layout(GraphGenerationObject.Graph, prog='neato') nx.draw_networkx_nodes(GraphGenerationObject.Graph, pos, nodelist=GraphGenerationObject.learning_green_nodes, node_color="green") nx.draw_networkx_nodes(GraphGenerationObject.Graph, pos, nodelist=GraphGenerationObject.learning_red_nodes, node_color="red") nx.draw_networkx_nodes(GraphGenerationObject.Graph, pos, nodelist=GraphGenerationObject.blue_nodes, node_color="blue") nx.draw_networkx_labels(GraphGenerationObject.Graph, pos, nodelist=GraphGenerationObject.Graph.nodes()) nx.draw_networkx_edges(GraphGenerationObject.Graph, pos, GraphGenerationObject.Graph.edges(), edge_color="black") plt.axis('off') plt.show()
def visualize(forward_idx=0, backward_idx=0): plt.figure(figsize=figsize) plt.xlim(x_min - padding, x_max + padding) plt.ylim(y_min - padding, y_max + padding) plt.axis('equal') if title: plt.title(r"Computational graph for " + title, fontsize=font_size) # draw nodes nx.draw_networkx_nodes(G_forward, node_color="#a2c4fc", pos=nodes_layout, node_size=node_size) nx.draw_networkx_labels(G_forward, pos=nodes_layout, labels=node_labels, font_size=font_size) edges_kwargs = dict(pos=nodes_layout, connectionstyle="arc3,rad=-0.1", width=2) # draw forward edges nx.draw_networkx_edges(G_forward, edge_color=forward_color, alpha=0.5, **edges_kwargs) # draw backward edges nx.draw_networkx_edges(G_backward, edge_color=backward_color, alpha=0.5, **edges_kwargs) # draw labels def label_coordinates(v1, v2, norm_fraction=0.15, backward=False): v1 = np.array(v1) v2 = np.array(v2) center = 0.5 * (v1 + v2) if backward: d = v1 - v2 else: d = v2 - v1 norm = np.sqrt(d @ d) d /= norm shift = np.array([-d[1], d[0]]) * norm_fraction * norm if backward: shift = -shift angle = math.degrees(math.atan2(d[1], d[0])) if angle > 90: angle -= 180 elif angle < -90: angle += 180 return tuple(center + shift), angle active_forward_edges = [] for e, l in forward_edge_label[:forward_idx]: active_forward_edges.append(e) norm_fraction = 0.1 + 0.05 * len(l.split("\n")) # larger shift for multiline labels coords, angle = label_coordinates(nodes_layout[e[0]], nodes_layout[e[1]], norm_fraction=norm_fraction) plt.annotate(l, coords, color=forward_color, size=font_size, ha='center', rotation=angle, rotation_mode='anchor') # highlight forward edges nx.draw_networkx_edges(G_forward, edgelist=active_forward_edges, edge_color=forward_color, alpha=1, **edges_kwargs) active_backward_edges = [] for e, l in backward_edge_label[:backward_idx]: active_backward_edges.append(e) norm_fraction = 0.1 + 0.05 * len(l.split("\n")) # larger shift for multiline labels coords, angle = label_coordinates(nodes_layout[e[0]], nodes_layout[e[1]], norm_fraction=norm_fraction, backward=True) plt.annotate(l, coords, color=backward_color, size=font_size, ha='center', rotation=angle, rotation_mode='anchor') # highlight backward edges nx.draw_networkx_edges(G_backward, edgelist=active_backward_edges, edge_color=backward_color, alpha=1, **edges_kwargs) plt.show()
b = e[1] w = randint(1, 1) G.add_edge(int(e[0]), int(e[1]), weight=w) # print (a) # Drawing the graph node_pos = nx.spring_layout(G) edge_weight = nx.get_edge_attributes(G, 'weight') # Draw the nodes nx.draw_networkx(G, node_pos, node_color='grey', node_size=100) # Draw the edges nx.draw_networkx_edges(G, node_pos, edge_color='black') # Draw the edge labels nx.draw_networkx_edge_labels(G, node_pos, edge_color='red', edge_labels=edge_weight) # write to a file # nx.write_gml(G, "test_gml") # json_graph.node_link_data(G) # nx.write_edgelist(G,"test.edgeList") # print the adjacency list to terminal print("THE ADJACENCY LIST IS ") # try:
def solve(a, p, b): nitems = len(p) items = range(nitems) vertices = [[i, j] for i in range(b) for j in items] # Vertices are named (i,j), see lecture k = 0 for vertice in vertices: vertice.append(k) k += 1 G = nx.DiGraph() arcs = [] # List of tuples, i.e. [((i,j), (k,l),w), ((k,l), (u,v),0)] for i, j, x_1 in vertices: for k, l, x_2 in vertices: if (i == k and j == l): continue elif (i == k and l - j == 1): arcs.append((x_1, x_2, 0)) G.add_edge(x_1, x_2, weight=0) elif (i - k == -1 and j == l): arcs.append((x_1, x_2, 1)) G.add_edge(x_1, x_2, weight=1) # print(arcs) # G.add_nodes_from([0, 1, 2, 3, 4]) # G.add_weighted_edges_from([(1,2,3),(1,3,2)]) # G.add_edge('a', 'b', weight=0.6) # G.add_edge('a', 'c', weight=0.2) # G.add_edge('c', 'd', weight=0.1) # G.add_edge('c', 'e', weight=0.7) # G.add_edge('c', 'f', weight=0.9) # G.add_edge('a', 'd', weight=0.3) elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 0.5] esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] <= 0.5] # pos = nx.spring_layout(G) # positions for all nodes pos = nx.random_layout(G) # nodes nx.draw_networkx_nodes(G, pos, node_size=200) # edges nx.draw_networkx_edges(G, pos, edgelist=elarge, width=1) nx.draw_networkx_edges(G, pos, edgelist=esmall, width=1, alpha=0.5, edge_color='b', style='dashed') # labels nx.draw_networkx_labels(G, pos, font_size=3, font_family='sans-serif') # G.add_nodes_from(vertices) # print(G.number_of_nodes()) # G.add_edge(1, 2) # print the adjacency list # for line in nx.generate_adjlist(G): # print(line) # write edgelist to grid.edgelist # nx.write_edgelist(G, path="grid.edgelist", delimiter=":") # read edgelist from grid.edgelist # H = nx.read_edgelist(path="grid.edgelist", delimiter=":") # print(H) plt.axis('off') plt.show()
def sistemaColoniaFormiga(grafo, mapa, origem, destino, lista_vertice, coeficiente_evaporacao, iteracao, vel_iteracao, formiga): rota_total = [('AP', 'PA'), ('AC', 'RO'), ('RO', 'AM'), ('AM', 'AC'), ('RR', 'AM'), ('RR', 'PA'), ('PA', 'AM'), ('PA', 'TO'), ('RS', 'SC'), ('SC', 'PR'), ('PR', 'MS'), ('PR', 'SP'), ('SP', 'RJ'), ('RJ', 'MG'), ('MG', 'SP'), ('MS', 'MT'), ('MT', 'RO'), ('MT', 'PA'), ('MT', 'GO'), ('GO', 'DF'), ('DF', 'MG'), ('MG', 'GO'), ('GO', 'BA'), ('BA', 'TO'), ('TO', 'GO'), ('TO', 'MA'), ('MA', 'PI'), ('PI', 'TO'), ('BA', 'MG'), ('BA', 'ES'), ('BA', 'SE'), ('SE', 'AL'), ('AL', 'PE'), ('PE', 'PI'), ('PE', 'PB'), ('PI', 'CE'), ('CE', 'RN'), ('RN', 'PB'), ('PB', 'CE'), ('PB', 'PE'), ('PA', 'MA'), ('PI', 'BA'), ('MG', 'MS'), ('MS', 'GO'), ('MS', 'SP'), ('MG', 'ES'), ('RJ', 'ES')] pos = { 'AC': (53.71, 229.51), 'AL': (579.10, 233.28), 'AM': (133.96, 158.04), 'AP': (340.86, 60.23), 'BA': (505.12, 274.66), 'CE': (531.45, 160.55), 'DF': (387.83, 351.83), 'ES': (513.90, 390.02), 'GO': (382.24, 306.00), 'MA': (444.93, 161.80), 'MG': (453.71, 369.95), 'MT': (281.92, 283.47), 'MS': (293.21, 392.52), 'PA': (314.53, 163.06), 'PE': (551.52, 208.20), 'PB': (587.88, 198.17), 'PI': (488.82, 200.67), 'PR': (342.11, 467.76), 'RN': (577.85, 168.07), 'RO': (174.09, 262.12), 'RR': (194.15, 53.97), 'RS': (315.78, 544.25), 'RJ': (473.77, 437.66), 'SC': (374.71, 512.90), 'SE': (567.82, 249.58), 'SP': (383.49, 423.87), 'TO': (397.29, 237.04) } lista_formigas = [] for i in range(formiga): lista_formigas.append(str(i + 1)) im = Image.open('back.png') fig1 = plt.figure() fig1.set_facecolor('#CCCCCC') # ax3 = fig1.add_subplot(2,2,2) # plot do gráfico1 # ax3.set_title('Gráfico 2 das Formigas') # ax3.set_facecolor('#CCCCCC') # ax3.grid() # ax3.plot() ax2 = fig1.add_subplot(1, 2, 2) # plot do gráfico1 ax2.set_title('Gráfico 1 das Formigas ') ax2.set_facecolor('#CCCCCC') ax2.grid() ax2.plot() ax1 = fig1.add_subplot(1, 2, 1) # plot do mapa ax1.set_title('Mapa de Colônia') ax1.set_xticklabels([]) ax1.set_xlabel('Latitude') ax1.set_yticklabels([]) ax1.set_ylabel('Longitude') ax1.set_facecolor('#CCCCCC') ax1.plot() nx.draw_networkx_nodes(mapa, pos, node_color='#6986a3', alpha=0.8, node_size=100) nx.draw_networkx_nodes(mapa, pos, nodelist=[origem], node_color='green', node_size=150, alpha=0.9, label='Origem') nx.draw_networkx_nodes(mapa, pos, nodelist=[destino], node_color='red', node_size=150, alpha=0.9, label='Destino') nx.draw_networkx_edges(mapa, pos, width=1.5, alpha=0.9, edge_color='white') nx.draw_networkx_labels(mapa, pos, font_size=6, font_color='white') # nx.draw_networkx_edge_labels(mapa, pos, font_size=5) # EXIBE OS PESOS DAS ARESTAS def refresh(x): for i in range(1): lista_caminho_formiga = [] rota = [] for j in range(formiga): list_caminho = [] caminho(grafo, origem, destino, list_caminho) removeCiclo(list_caminho) lista_caminho_formiga.append(list_caminho) distanciaTotal = atualizaTaxaFeromonio(grafo, lista_caminho_formiga, coeficiente_evaporacao, lista_vertice) ax2.plot_date(lista_formigas, distanciaTotal) ax2.bar(lista_formigas, distanciaTotal, color='white', label='teste') ax2.plot(distanciaTotal, lw=0.02) # ax2.hist(distanciaTotal) print(distanciaTotal) for j in range(formiga): for k in range(len(lista_caminho_formiga[j]) - 1): rota.append((lista_caminho_formiga[j][k], lista_caminho_formiga[j][k + 1])) nx.draw_networkx_edges(mapa, pos, edgelist=rota, width=2, alpha=0.01, edge_color='black') nx.draw_networkx_edges(mapa, pos, edgelist=rota_total, width=2.7, alpha=0.0095, edge_color='w') ax2.set_title('Comportamento das Formigas') ax2.set_ylabel('Distância (KM)') ax2.set_xticks(lista_formigas) ax2.set_xticklabels(distanciaTotal) ax2.set_xlabel('Distância Percorrida até o destino (KM)') plt.legend(loc='lower left') plt.imshow(im) ani1 = gif.FuncAnimation(fig1, refresh, iteracao, interval=vel_iteracao, repeat=False) plt.tight_layout() plt.show()
def draw(self, node_type='', layout=''): """ Draw graph with vertices, edges, and faces labeled by colored nodes and their integer indices corresponding to the qubit indices for the surface code """ if not node_type in ['cycles', 'dict']: raise ValueError('node_type can be "cycles" or "dict"') if layout == 'spring': pos = nx.spring_layout(self.code_graph) if layout == 'spectral': pos = nx.spectral_layout(self.code_graph) if layout == 'planar': pos = nx.planar_layout(self.code_graph) if layout == 'shell': pos = nx.shell_layout(self.code_graph) if layout == 'circular': pos = nx.circular_layout(self.code_graph) if layout == 'spiral': pos = nx.spiral_layout(self.code_graph) if layout == 'random': pos = nx.random_layout(self.code_graph) # white nodes nx.draw_networkx_nodes(self.code_graph, pos, nodelist=list(self.alpha), node_color='c', node_size=500, alpha=0.3) # vertex nodes nx.draw_networkx_nodes(self.code_graph, pos, nodelist=list(self.sigma), node_color='b', node_size=500, alpha=0.6) # face nodes nx.draw_networkx_nodes(self.code_graph, pos, nodelist=list(self.phi), node_color='r', node_size=500, alpha=0.6) # edges nx.draw_networkx_edges(self.code_graph, pos, width=1.0, alpha=0.5) labels = {} if node_type == 'cycles': ''' label nodes the cycles of sigma, alpha, and phi ''' for node in self.alpha_dict: # stuff = self.alpha_dict[node] labels[node] = f'$e$({node})' for node in self.sigma_dict: # something = self.sigma_dict[node] labels[node] = f'$v$({node})' for node in self.phi_dict: # something2 = self.phi_dict[node] labels[node] = f'$f$({node})' nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12) if node_type == 'dict': ''' label nodes with v, e, f and indices given by node_dict corresponding to qubit indices of surface code ''' for node in self.alpha_dict: # stuff = self.alpha_dict[node] labels[node] = f'$e$({self.alpha_dict[node]})' for node in self.sigma_dict: # something = self.sigma_dict[node] labels[node] = f'$v$({self.sigma_dict[node]})' for node in self.phi_dict: # something2 = self.phi_dict[node] labels[node] = f'$f$({self.phi_dict[node]})' nx.draw_networkx_labels(self.code_graph, pos, labels, font_size=12) # plt.axis('off') # plt.savefig("labels_and_colors.png") # save as png plt.show() # display
# if p in dist: # dist[p] += 1 # else: # dist[p] = 1 # print('') # print("length #paths") # verts = dist.keys() # for d in sorted(verts): # print('%s %d' % (d, dist[d])) # print("radius: %d" % nx.radius(G)) # print("diameter: %d" % nx.diameter(G)) # print("eccentricity: %s" % nx.eccentricity(G)) # print("center: %s" % nx.center(G)) # print("periphery: %s" % nx.periphery(G)) # print("density: %s" % nx.density(G)) # #nx.draw(G, with_labels=True) plt.figure(3, figsize=(13, 7)) # nx.draw_networkx(DG, pos, with_labels=True, node_size = 80) nx.draw_networkx_nodes(DG, pos, node_size=20, node_color="blue") nx.draw_networkx_edges(DG, pos, alpha=0.4, width=0.5) nx.draw_networkx_labels(DG, pos, alpha=0.7, font_size=8) plt.axis('off') plt.show() # print(DG.nodes()) # print(len(DG.nodes()))