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 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 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 demo_pytorch_computational_graph( t, init_gradient=None, figsize=(12, 6), padding=40 ): import torch import networkx as nx import numpy as np import matplotlib.pyplot as plt if init_gradient is None: init_gradient = torch.tensor(1.0) G_forward = nx.DiGraph() # for layout G = nx.MultiDiGraph() stack = [(t.grad_fn, t.grad_fn(init_gradient))] node_labels = {} while stack: node, outer_gradient = stack.pop() node_id = str(id(node)) + node.name() node_labels[node_id] = node.name() for n, n_outer_gradient in zip(node.next_functions, outer_gradient): if n[0] is not None: n_id = str(id(n[0])) + n[0].name() node_labels[n_id] = n[0].name() G_forward.add_edge(n_id, node_id) G.add_edge(node_id, n_id, label=n_outer_gradient.item()) stack.append((n[0], n[0](n_outer_gradient))) # place nodes left-to-right # "regular" top-to-bottom layout nodes_layout = nx.nx_pydot.graphviz_layout(G_forward, prog='dot') # make right-to-left from top-to-bottom nodes_layout = {k: (-v[1], v[0]) for k, v in nodes_layout.items()} # visualize x_min = min([c[0] for c in nodes_layout.values()]) x_max = max([c[0] for c in nodes_layout.values()]) y_min = min([c[1] for c in nodes_layout.values()]) y_max = max([c[1] for c in nodes_layout.values()]) plt.figure(figsize=figsize) plt.xlim(x_min - padding, x_max + padding) plt.ylim(y_min - padding, y_max + padding) # draw nodes nx.draw_networkx_nodes(G, node_color="#a2c4fc", pos=nodes_layout) nx.draw_networkx_labels(G, pos=nodes_layout, labels=node_labels) # draw edges for e in G.edges: l = G.edges[e]["label"] current_multiplicity = e[2] coords = tuple(0.5 * (np.array(nodes_layout[e[0]]) + np.array(nodes_layout[e[1]])) - 10 * current_multiplicity) plt.annotate(l, coords, color="r", ha='center') # hacky arrows plt.annotate( "", xy=nodes_layout[e[1]], xycoords='data', xytext=nodes_layout[e[0]], textcoords='data', arrowprops=dict( arrowstyle="simple", color="r", alpha=0.5, shrinkA=10, shrinkB=10, connectionstyle="arc3,rad={}".format(-0.1*(1 + current_multiplicity)) ), )
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()
# print("Source : %s / Destination : %s" % (u, v)) print(list(G.nodes())) #for u, v, action in G.edges(data='action'): # if action is not None: # print("(%s) [%s] (%s)" % (u, action, v)) color_map = [] for n in G.nodes(): if G.nodes[n]['parti'] == 'author': color_map.append('red') else: color_map.append('blue') options = { 'node_color': color_map, 'node_size': 50, 'line_color': 'grey', 'linewidths': 0, 'width': 0.1, } pos = nx.spring_layout(G) nx.draw(G, pos, font_size=16, with_labels=False, **options) for p in pos: # raise text positions pos[p][1] += 0.07 nx.draw_networkx_labels(G, pos) plt.show()
print(pca.explained_variance_ratio_) print(1 - sum(pca.explained_variance_ratio_)) data_inv = pca.inverse_transform(pcad) print(abs(sum(sum(data - data_inv)))) for i in range(1, 5): pca = PCA(n_components=i) pca.fit(data) print(sum(pca.explained_variance_ratio_) * 100, '%') # Network Mining G = nx.read_gml('lesmiserables.gml') pos = nx.spring_layout(G) nx.draw(G, pos, node_size=0, edge_color='b', alpha=.2) nx.draw_networkx_labels(G, pos, edge_color='b', alpha=.2, font_size=10) show() ''' Gt = G.copy() dn = nx.degree(Gt) for n in Gt.nodes(): if dn[n] <= 10: Gt.remove_node(n) pos = nx.spring_layout(Gt) nx.draw(Gt, pos, node_size=0, edge_color='b', alpha=.2) nx.draw_networkx_labels(Gt, pos, edge_color='b', alpha=.2, font_size=10) show() '''
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
pheromone = [[0 for i in range(no_of_cities)] for j in range(no_of_cities)] ants = [Ant(randint(0, no_of_cities - 1), [], 0) for i in range(no_of_ants)] for i in range(no_of_cities): for j in range(no_of_cities): if i != j and distances[i][j] == 0: distances[i][j] = randint(1, 20) distances[j][i] = distances[i][j] # plot graph graph = networkx.from_numpy_matrix(numpy.array(distances)) print(distances) pos = nx.shell_layout(graph) nx.draw_networkx_nodes(graph, pos, node_size=80) nx.draw_networkx_labels(graph, pos, font_size=13, font_family='sans-serif') labels = nx.get_edge_attributes(graph, 'weight') nx.draw_networkx_edge_labels(graph, pos, edge_labels=labels, label_pos=0.61) nx.draw(graph, pos) plt.axis('off') plt.show() print() # assign ants to cities for i in range(no_of_ants): ants[i].visitedCitiesSet.append(ants[i].currentCity) # start process
# 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()))