def colorProt(graph0, strategy=None): # coloring protocol n = graph0.number_of_nodes() graph = nx.convert_node_labels_to_integers(graph0, first_label=1) # sometimes the default strategy cannot come up with a minimum coloring # https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.coloring.greedy_color.html if strategy != None: min_coloring = nx.greedy_color(graph, strategy) else: min_coloring = nx.greedy_color(graph) colors = [min_coloring.get(color) for color in min_coloring] plt.figure(1) nx.draw(graph, node_size=1000, font_size=20, with_labels=True, node_color=[min_coloring.get(node) for node in graph.nodes()], cmap=plt.cm.Set1, vmax=8) plt.show() #plt.savefig("./img_coloring/graph-"+str(k)+".png", format="PNG", transparent = True) A = nx.to_numpy_array(graph, nodelist=sorted(graph.nodes())) adm = admissible(A)[0] test = np.zeros(2**n) for color in set(colors): pos = [k for (k, v) in min_coloring.items() if v == color] mu = np.sum([ 3**(n - x) for x in pos ]) # these are the settings we want to construct the test vectors from # graph node has to start at 1; otherwise replace x by x+1 pauli = intToPauli(mu, n) meas = rspan(localCommutator(A))[mu] bit_converter = 2**np.arange(n - 1, -1, -1) testvec = (meas.dot(bit_converter)).astype(int) testvec2 = list(set(testvec)) rank = len(testvec2) gen = int(log((2**n) / rank, 2)) print('{}: rank = {}, # subgroup gen = {}, admissible? {} {}'.format( pauli, rank, gen, pauli in [x[1] for x in adm], [x[1] for x in adm if set(x[0]).issubset(testvec2) == True])) testmat = [0] * (2**n) for x in testvec2: testmat[x] = 1 test += testmat print(test[1:]) print('nu = {}'.format(1 - Fraction(np.amax(test[1:]) / len(set(colors))).limit_denominator())) return ()
def color_counter(graph): """interprets a coloring on a graph as a meshing.""" color = nx.greedy_color(graph) i = 0 for key, value in color.iteritems(): i = max(i, value) return i + 1
def label_nodes(self, theta_e, theta_b): nodes, edges, sd, ed, bd = self.graph # valid_edge_idx = np.logical_and(np.logical_and( # sd < 2*self.field.sample_distance, # ed < theta_e # ), bd < theta_b) valid_edge_idx = np.logical_and.reduce( (bd < theta_b, ed < theta_e, sd < 1.5 * self.field.sample_distance)) self.labels_ = label_graph(nodes, edges[valid_edge_idx]) C = nx.Graph() C.add_nodes_from(np.arange(self.labels_.max() + 1)) for i in range(1, self.close_samples_dist.shape[1]): edges = self.close_samples_idx[:, [0, i]] C.add_edges_from(self.labels_[edges]) lbl_dict = nx.greedy_color(C) new_lbl = np.full_like(self.labels_, -1, "i") for src, dst in lbl_dict.items(): k = self.labels_ == src new_lbl[k] = dst #print(f"{new_lbl.max()} labels for MRF") self.labels_ = new_lbl
def greedy_coloring(network, lb, boxing=False, pso_position=False, strategy='random_sequential'): # To achieve boxing, the original problem is mapped to the famous graph coloring problem. # This means that we color the dual graph of the original network. dual_graph = network.dual_network(lb) # coloring via networkx: Returns a dictionary with keys representing nodes and values representing corresponding coloring. dual_colors = nx.greedy_color(dual_graph, strategy=strategy) # TODO: kipróbálni a networkx többi stratégiáját. esetleg beállítani paraméternek. inved_dual_colors = network.invert_dict_list(dual_colors) # returns {color:list_of_nodes} boxes = [] for color in inved_dual_colors.keys(): boxes.append(set(inved_dual_colors[color])) # Recovering coloring for individual nodes, if needed if pso_position: color_map = [None] * network.graph.number_of_nodes() # returns [None,None,...] the aprropriate times for n in dual_colors: # the keys of dual_colors are the IDs of nodes color_map[n] = dual_colors[n] return color_map if boxing: return len(boxes) else: return boxes
def color_map(gdf, districting): # Takes a few seconds # block : distr num inv_map = { block: k for k, district in districting.items() for block in district } gdf['district'] = pd.Series(inv_map) shapes = [] for name, group in gdf.groupby('district'): shapes.append(group.geometry.unary_union) shape_series = gpd.GeoSeries(shapes) G = Queen(shapes).to_networkx() color_series = pd.Series(nx.greedy_color(G)) n_colors = len(set(color_series.values)) cmap = LSC.from_list( "", ["red", "lime", "dodgerblue", 'yellow', 'darkviolet', 'chocolate'][:n_colors]) map_gdf = gpd.GeoDataFrame({ 'geometry': shape_series, 'color': color_series }) ax = map_gdf.plot(column='color', figsize=(15, 15), cmap=cmap, edgecolor='black', lw=.5) gdf.plot(ax=ax, facecolor='none', edgecolor='white', lw=.05) ax.axis('off') return map_gdf
def colour_communities(graph, communities, other_label='sattelites'): """ Colours communities using a predefined colour palette. :param graph: :param communities: :return: """ palette = ['#4369A7', '#E9B83F', '#4BAC7C', '#D54E74', '#786D9B', '#F0C77F', '#A2B9EE', '#9EDEA8', '#EF8FB1', '#B099E2'] other_color = '#969696' block = community_blocks(graph, communities) block_moralised = block.copy() for node_a, adjacency_a in sorted(block.adjacency()): for node_b, adjacency_b in sorted(block.adjacency()): if (node_a, node_b) in block.edges or not adjacency_a or not adjacency_b: continue else: joint_adjacency = adjacency_a.keys() & adjacency_b.keys() if joint_adjacency and (node_a, node_b) not in block_moralised.edges: block_moralised.add_edge(node_a, node_b) # Colour the graph using greedy algorithm colors = nx.greedy_color(block_moralised, strategy="largest_first") color_map = {k: palette[v % len(palette)] for k, v in colors.items()} if other_label is not None: color_map[other_label] = other_color return color_map
def greedy(graph, strategy): """ Returns the coloring of a graph using a greedy strategy. see https://networkx.github.io/documentation/development/reference/generated/networkx.algorithms.coloring.greedy_color.html for possible strategies. """ greedy = nx.greedy_color(graph, strategy) return greedy
def task_c(G): # we can't use less, than 4 colors because of the clique maximum ['BY', 'PL', 'RU', 'UA'] res_file = open('vertex_coloring.txt', 'w') gr = maximum_connected_component(G) coloring = nx.greedy_color(gr, strategy="DSATUR") for k, v in coloring.items(): string = str(k) + ":" + str(v) + "\n" res_file.write(string) res_file.close()
def coloring_set_batch_generate(graph, iterations): colorings = [] independent_sets = [] for _ in range(0, iterations): coloring = nx.greedy_color(graph, strategy="random_sequential") colorings.append(coloring) independent_sets.append( Utilities.reversible_uniq_dict(coloring).reversed()) return colorings, independent_sets
def get_map_coloring_groups(self): coloring_dict = networkx.greedy_color(self.graph.to_undirected()) grouping_dict = {} for node in coloring_dict: if not coloring_dict[node] in grouping_dict: grouping_dict[coloring_dict[node]] = [] grouping_dict[coloring_dict[node]].append(node) return list(grouping_dict.values())
def solve_it(input_data): # Modify this code to run your optimization algorithm # parse the input lines = input_data.split('\n') first_line = lines[0].split() node_count = int(first_line[0]) edge_count = int(first_line[1]) edges = [] for i in range(1, edge_count + 1): line = lines[i] parts = line.split() edges.append((int(parts[0]), int(parts[1]))) G = nx.Graph() G.add_edges_from(edges) greedy_result = nx.greedy_color(G) greedy_result = pd.DataFrame(list( greedy_result.items())).set_index(0)[1].sort_index() greedy_color_size = len(greedy_result.unique()) max_fc_graph = find_max_full_graph(G) try: print( " --------node size : %s; greedy size :%s; max_fc_graph_size:%s----------" % (node_count, greedy_color_size, len(max_fc_graph))) max_value = greedy_color_size - 2 results = [] final_result = None while max_value > 0: result = model_optimize(edges, node_count, max_value, max_fc_graph) results.append(result) info = result.copy() info["nodes"] = None print("%s" % (info)) max_value = min(max_value, result["color_size"]) - 1 if result["status"] == "optimal" or result["status"] == "feasible": final_result = result else: break solution = final_result["nodes"].tolist() color_size = final_result["color_size"] except Exception as e: print(e) color_size = greedy_color_size solution = greedy_result # prepare the solution in the specified output format output_data = str(color_size) + ' ' + str(0) + '\n' output_data += ' '.join(map(str, solution)) return output_data
def run(self, mode='write', debug=False): if mode not in ('write', 'return'): raise ValueError('Invalid mode') num_tiles = len(self.aligner.positions) all_images = [] if debug: node_colors = nx.greedy_color(self.aligner.neighbors_graph) num_colors = max(node_colors.values()) + 1 if num_colors > 3: raise ValueError("neighbor graph requires more than 3 colors") for channel in self.channels: if self.verbose: print(' Channel %d:' % channel) if not debug: mosaic_image = np.zeros(self.shape, self.dtype) else: mosaic_image = np.zeros(self.shape + (3, ), np.float32) for tile, position in enumerate(self.aligner.positions): if self.verbose: sys.stdout.write('\r merging tile %d/%d' % (tile + 1, num_tiles)) sys.stdout.flush() tile_image = self.aligner.reader.read(c=channel, series=tile) tile_image = self.correct_illumination(tile_image, channel) if debug: color_channel = node_colors[tile] rgb_image = np.zeros(tile_image.shape + (3, ), tile_image.dtype) rgb_image[:, :, color_channel] = tile_image tile_image = rgb_image func = pastefunc_blend if not debug else np.add paste(mosaic_image, tile_image, position, func=func) if debug: np.clip(mosaic_image, 0, 1, out=mosaic_image) w = int(1e6) mi_flat = mosaic_image.reshape(-1, 3) for p in np.arange(0, mi_flat.shape[0], w, dtype=int): mi_flat[p:p + w] = skimage.exposure.adjust_gamma( mi_flat[p:p + w], 1 / 2.2) if self.verbose: print() if mode == 'write': filename = self.filename_format.format(channel=channel) self.filenames.append(filename) if self.verbose: print(" writing %s" % filename) with warnings.catch_warnings(): warnings.filterwarnings('ignore', r'.* is a low contrast image', UserWarning, '^skimage\.io') skimage.io.imsave(filename, mosaic_image) elif mode == 'return': all_images.append(mosaic_image) if mode == 'return': return all_images
def Greedy_color(grafo): tiempo=[] for i in range(30): tiempo_inicial = dt.datetime.now() for j in range(1000): nx.greedy_color(grafo) tiempo_final = dt.datetime.now() tiempo_ejecucion = (tiempo_final - tiempo_inicial).total_seconds() tiempo.append(tiempo_ejecucion) media=nup.mean(tiempo) desv=nup.std(tiempo) mediana=nup.median(tiempo) datos["algoritmo"].append("greedy_color") datos["grafo"].append(grafo.name) datos["cant_vertice"].append(grafo.number_of_nodes()) datos["cant_arista"].append(grafo.number_of_edges()) datos["media"].append(media) datos["desv"].append(desv) datos["mediana"].append(mediana) return datos
def gca(G, l_B): #calculate distances between every vertex in G p = dict(nx.all_pairs_shortest_path_length(G, l_B)) #add infs to p for i in G.nodes: for j in set(G.nodes).difference(set(p[i].keys())): p[i][j] = np.inf #construct G' Gp = nx.Graph() Gp.add_nodes_from(G.nodes) Gp.add_edges_from([(i, j) for i in G.nodes for j in p[i].keys() if p[i][j] > l_B]) c = nx.greedy_color(Gp) ''' #relabel the nodes #node_order = np.random.permutation(Gp.nodes) #order_dict = {i:j for i, j in zip(Gp.nodes, node_order)} #Gp = nx.relabel_nodes(Gp, order_dict) #construct neighbor dict for Gp #Gp_neighbor_dict = {i:list(Gp.neighbors(i)) for i in Gp.nodes} #i:[] for lone nodes c = {} #coloring dictionary of node:color c[0] = 0 #default for i in range(1, len(Gp.nodes)): possible_colors = set(range(i + 1)) excluded_colors = set([c[j] for j in set(range(i)).intersection(Gp_neighbor_dict[i])]) c[i] = min(possible_colors.difference(excluded_colors)) create the transformed graph ''' newG = nx.Graph() #add nodes new_nodes = list(set(c.values())) newG.add_nodes_from(new_nodes) #add edges #get inv_c, color:[nodes] inv_c = {i:[j for j in Gp.nodes if c[j] == i] for i in c.values()} #get inv_neigh, color:[neighbors of nodes with this color IN G NOT IN Gp] #construct neighbor dict for G G_neighbor_dict = {i:list(G.neighbors(i)) for i in G.nodes} inv_neigh = {i: [l for k in [list(G_neighbor_dict[j]) for j in inv_c[i]] for l in k] for i in c.values()} for i in new_nodes: #get nodes in for j in set(new_nodes).difference(set([i])): for k in inv_c[i]: if k in inv_neigh[j]: newG.add_edge(i, j) break return newG
def draw_graph(): c = nx.greedy_color(G) # словарь вершина : цифра (номер цвета) pos = nx.circular_layout(G) nx.draw_networkx_nodes(G, pos=pos, nodelist=[j for j in c], node_color=[colours[c[i]] for i in c]) nx.draw_networkx_edges(G, pos) nx.draw_networkx_labels(G, pos) plt.savefig('graph.png') plt.show() plt.close()
def GreedyGraphColoring(graph, M=3): G = graph #d = nx.coloring.equitable_color(G, num_colors=M) #s = nx.algorithms.coloring.equitable_coloring.is_equitable(G, d) #s = nx.greedy_color(G, num_colors=M) colour_map = nx.greedy_color(graph, strategy='largest_first', interchange=False) data = list(colour_map.items()) an_array = np.array(data) colour_map = an_array[:, 1] return colour_map
def greedy_color(nombre): # Para grafo Simpe No dirigido Aciclico df = pd.read_csv(nombre, header=None) b = nx.from_pandas_adjacency(df, create_using=nx.Graph()) for i in range(30): # Ejecutar las 50 corridas inicio = datetime.datetime.now() for key in range(50): nx.greedy_color(b) #, source=0, target=3) final = datetime.datetime.now() tiempos.append((final - inicio).total_seconds()) # Guardo los tiempos de las corridas media=np.mean(tiempos) desv=np.std(tiempos) mediana=np.median(tiempos) nodos=nx.number_of_nodes(b) arcos=nx.number_of_edges(b) salvar=[] salvar.append(media) salvar.append(desv) salvar.append(mediana) salvar.append(nodos) salvar.append(arcos) # return salvar
def solve_problem(self): if self.G == None: print('Import a problem!!!!!') return self.periods_solutions = nx.greedy_color(self.G, strategy='DSATUR') table = PrettyTable() table.field_names = ['Exam', 'Period'] table.add_rows([[exam, period] for exam, period in self.periods_solutions.items()]) print(table) self.P = max(self.periods_solutions.values()) + 1 print('Dsatur:Periods Used:{}'.format(self.P)) print('Period Number:{}-Invalid'.format( self.P)) if self.P < datasets[self.problem_name] else print( 'Period Number:{}-Valid'.format(self.P))
def features(g: nx.Graph) -> np.array: """ calculates feature matrix, where each row is a feature vector for a specific node""" def average(x): if len(x) == 0: return 0 return sum(x) / len(x) def chi2(obs, exp): if exp == 0: return 0 return ((obs - exp)**2) / exp deg = dict(g.degree) avg_deg = average(deg.values()) lcc = nx.clustering(g) avg_lcc = average(lcc.values()) eigencentrality = nx.algorithms.centrality.eigenvector_centrality_numpy(g) greedy_coloring = nx.greedy_color(g) greedy_chr_nmbr = len(set(greedy_coloring.values())) def f(v): """ calculates the feature vector """ # assert type(v) == type(next(g.__iter__())), "possibly there was passed a wrong type of node" return np.array([ # graph-theoretical features g.number_of_nodes(), # F1: n, number of nodes g.number_of_edges(), # F2: m, number of edges deg[v], # F3: vertex degree lcc[v], # F4: lcc, local clustering coefficient of node v eigencentrality[v], # F5: eigencentrality # stat. features chi2(deg[v], avg_deg), # F6: chi2 of vertex deg average([chi2(deg[u], avg_deg) for u in g.neighbors(v) ]), # F7: average chi2 of deg of neighbours chi2(lcc[v], avg_lcc), # F8: chi2 of lcc of vertex average([chi2(lcc[u], avg_lcc) for u in g.neighbors(v) ]), # F9: average chi2 of lcc of neighbours len({greedy_coloring[u] for u in g.neighbors(v)}) / greedy_chr_nmbr # F10: estimate for local chromatic density ]) return np.array([f(v) for v in g.nodes])
def propagate(G, eps=1e-3, max_iter=1000, weight_label='weight', bias_label='bias'): """Propagate neural network signals until an energy minimum is achieved""" index = {node: i for (i, node) in enumerate(G.nodes())} A = nx.adjacency_matrix(G, weight=weight_label) b = np.array([data[bias_label] for node, data in G.nodes(data=True)]) logging.info('propagate: building schedule') coloring = collections.defaultdict(list) for node, color in nx.greedy_color(G).iteritems(): coloring[color].append(index[node]) x = 1e-6 * np.random.uniform(-1.0, 1.0, size=A.shape[0]) err = eps + 1 i = 0 e1 = None logging.info('propagate: iteration/error/energy') while err > eps: for group in coloring.itervalues(): x[group] = -1.0 + 2.0 / (1.0 + np.exp(-A[group, :].dot(x) - b[group])) e2 = -0.5 * x.dot(A.dot(x)) - x.dot(b) if e1: err = e1 - e2 e1 = e2 i += 1 logging.info('propagate: {0: 4d}/{1:.2e}/{2:.2e}'.format(i, err, e1)) if i > max_iter: logging.warning( 'Exceeded maximum number of iterations ({0}) with error {1}>{2}' .format(max_iter, err, eps)) return x, index return x, index
def propagate(G, eps=1e-3, max_iter=1000, weight_label='weight', bias_label='bias'): """Propagate neural network signals until an energy minimum is achieved""" index = {node: i for (i, node) in enumerate(G.nodes())} A = nx.adjacency_matrix(G, weight=weight_label) b = np.array([data[bias_label] for node, data in G.nodes(data=True)]) logging.info('propagate: building schedule') coloring = collections.defaultdict(list) for node, color in nx.greedy_color(G).iteritems(): coloring[color].append(index[node]) x = 1e-6*np.random.uniform(-1.0, 1.0, size=A.shape[0]) err = eps + 1 i = 0 e1 = None logging.info('propagate: iteration/error/energy') while err > eps: for group in coloring.itervalues(): x[group] = -1.0 + 2.0/(1.0 + np.exp(-A[group,:].dot(x) - b[group])) e2 = -0.5*x.dot(A.dot(x)) - x.dot(b) if e1: err = e1 - e2 e1 = e2 i += 1 logging.info('propagate: {0: 4d}/{1:.2e}/{2:.2e}'.format(i, err, e1)) if i>max_iter: logging.warning( 'Exceeded maximum number of iterations ({0}) with error {1}>{2}'.format( max_iter, err, eps)) return x, index return x, index
G = nx.Graph() with open("input/" + inputfile) as fp: line = fp.readline() while line: # print(line); if line[0] == 'e': tokens = line.strip().split(" ") G.add_edge(tokens[1], tokens[2]) line = fp.readline() coloring = nx.greedy_color(G, 'largest_first') # print(coloring) chromatic_number = max(coloring.values()) plt.subplot(121) # nx.draw(G, node_color=range(chromatic_number), cmap=plt.cm.Blues) # print(G.nodes() node_colors = [coloring[x] for x in G.nodes()] labels = {} for node in G.nodes(): labels[node] = node print(node_colors) nx.draw(G, labels=labels, cmap=plt.cm.gist_rainbow,
import networkx as nx def c(d): s = set() for k in d: s.add(d[k]) return len(s) print "Star Graph with 5 vertices ", c(nx.greedy_color(nx.star_graph(5))) print "Complete Graph with 5 vertices ", c( nx.greedy_color(nx.complete_graph(5)))
max_bc = 0 max_bc_node = -1 for node, node_bc in bc.items(): # sys.stdout.write("{}: {}\n".format(node, node_bc)) if node_bc > max_bc: max_bc = node_bc max_bc_node = node sys.stdout.write("Node {} with max bc = {}\n".format(max_bc_node, max_bc)) sys.stdout.write("TF = {}\n".format(max_bc * num_nodes * (num_nodes - 1))) max_pl = 0 for node_num in range(num_nodes): tf = 0 p = nx.shortest_path(G) for src in p: for dst in p[src]: if src != dst: path = p[src][dst] if len(path) > max_pl: max_pl = len(path) # sys.stdout.write("Path from {} to {}: ".format(src, dst)) # print(p[src][dst]) if node_num in path and node_num != path[ -1] and node_num != path[0]: # print ("included node {}".format(node_num)) tf += 1 print("TF of node {} = {}".format(node_num, tf)) print("Max PL = {}".format(max_pl)) gc = nx.greedy_color(G)
def color_graph(G): return nx.greedy_color(G)
# b) print("b) |V| = ", G_.number_of_nodes(), ", |E| = ", G_.number_of_edges(), ", min_degree(G) = ", min(val for (node, val) in G.degree()), ", max_degree(G) = ", max(val for (node, val) in G.degree()), ", rad(G) = ", nx.radius(G), ", diam(G) = ", nx.diameter(G), ", girth(G) = ", len(min(nx.cycle_basis(G))), ", center(G) = ", nx.center(G), ", k_node_connectivity = ", nx.node_connectivity(G), ", k_edge_connectivity = ", nx.edge_connectivity(G)) print() # c) Minimum vertex coloring print("c) Colors:", max(nx.greedy_color(G).values()) + 1, ", Z =", nx.greedy_color(G)) print() # d) Minimum edge coloring print("d) Colors:", max(nx.greedy_color(nx.line_graph(G)).values()) + 1, ", E =", nx.greedy_color(nx.line_graph(G))) print() # e) Maximum clique print("e) Q =", clique.max_clique(G)) print() # f) Maximum stable set print("f) S =", independent_set.maximum_independent_set(G)) print()
def get_graph(Mat_D, Threshold, percentageConnections=False, complet=False): import scipy.io as sio import numpy as np import networkx as nx import pandas as pd import os Data = sio.loadmat(Mat_D) matX = Data['Correlation'] #[:tamn,:tamn] labels = Data['labels'] print(np.shape(matX)) print(np.shape(labels)) print(np.min(matX), np.max(matX)) if percentageConnections: if percentageConnections > 0 and percentageConnections < 1: for i in range(-100, 100): per = np.sum(matX > i / 100.) / np.size(matX) if per <= Threshold: Threshold = i / 100. break print(Threshold) else: print('The coefficient is outside rank') #Lista de conexion del grafo row, col = np.shape(matX) e = [] for i in range(1, row): for j in range(i): if complet: e.append((labels[i], labels[j], matX[i, j])) else: if matX[i, j] > Threshold: e.append((labels[i], labels[j], matX[i, j])) print(np.shape(e)[0], int(((row - 1) * row) / 2)) #Generar grafo G = nx.Graph() G.add_weighted_edges_from(e) labelNew = list(G.nodes) #Metricas por grafo (ponderados) Dpc = nx.degree_pearson_correlation_coefficient(G, weight='weight') cluster = nx.average_clustering(G, weight='weight') #No ponderados estra = nx.estrada_index(G) tnsity = nx.transitivity(G) conNo = nx.average_node_connectivity(G) ac = nx.degree_assortativity_coefficient(G) #Metricas por nodo tam = 15 BoolCenV = False BoolLoad = False alpha = 0.1 beta = 1.0 katxCN = nx.katz_centrality_numpy(G, alpha=alpha, beta=beta, weight='weight') bcen = nx.betweenness_centrality(G, weight='weight') av_nd = nx.average_neighbor_degree(G, weight='weight') ctr = nx.clustering(G, weight='weight') ranPaN = nx.pagerank_numpy(G, weight='weight') Gol_N = nx.hits_numpy(G) Dgc = nx.degree_centrality(G) cl_ce = nx.closeness_centrality(G) cluster_Sq = nx.square_clustering(G) centr = nx.core_number(G) cami = nx.node_clique_number(G) camiN = nx.number_of_cliques(G) trian = nx.triangles(G) colorG = nx.greedy_color(G) try: cenVNum = nx.eigenvector_centrality_numpy(G, weight='weight') tam = tam + 1 BoolCenV = True except TypeError: print( "La red es muy pequeña y no se puede calcular este parametro gil") except: print('NetworkXPointlessConcept: graph null') if Threshold > 0: carga_cen = nx.load_centrality(G, weight='weight') #Pesos positivos BoolLoad = True tam = tam + 1 #katxC=nx.katz_centrality(G, alpha=alpha, beta=beta, weight='weight') #cenV=nx.eigenvector_centrality(G,weight='weight') #cenV=nx.eigenvector_centrality(G,weight='weight') #Golp=nx.hits(G) #Gol_si=nx.hits_scipy(G) #ranPa=nx.pagerank(G, weight='weight') #ranPaS=nx.pagerank_scipy(G, weight='weight') matrix_datos = np.zeros((tam, np.shape(labelNew)[0])) tam = 15 print(np.shape(matrix_datos)) lim = np.shape(labelNew)[0] for i in range(lim): roi = labelNew[i] #print(roi) matrix_datos[0, i] = katxCN[roi] matrix_datos[1, i] = bcen[roi] matrix_datos[2, i] = av_nd[roi] matrix_datos[3, i] = ctr[roi] matrix_datos[4, i] = ranPaN[roi] matrix_datos[5, i] = Gol_N[0][roi] matrix_datos[6, i] = Gol_N[1][roi] matrix_datos[7, i] = Dgc[roi] matrix_datos[8, i] = cl_ce[roi] matrix_datos[9, i] = cluster_Sq[roi] matrix_datos[10, i] = centr[roi] matrix_datos[11, i] = cami[roi] matrix_datos[12, i] = camiN[roi] matrix_datos[13, i] = trian[roi] matrix_datos[14, i] = colorG[roi] if BoolCenV: matrix_datos[15, i] = cenVNum[roi] tam = tam + 1 if BoolLoad: matrix_datos[16, i] = carga_cen[roi] tam = tam + 1 #matrix_datos[0,i]=katxC[roi] #matrix_datos[2,i]=cenV[roi] #matrix_datos[7,i]=Golp[0][roi] #matrix_datos[9,i]=Gol_si[0][roi] #matrix_datos[10,i]=Golp[1][roi] #matrix_datos[12,i]=Gol_si[1][roi] #matrix_datos[22,i]=ranPa[roi] #matrix_datos[24,i]=ranPaS[roi] FuncName = [ 'degree_pearson_correlation_coefficient', 'average_clustering', 'estrada_index', 'transitivity', 'average_node_connectivity', 'degree_assortativity_coefficient', 'katz_centrality_numpy', 'betweenness_centrality', 'average_neighbor_degree', 'clustering', 'pagerank_numpy', 'hits_numpy0', 'hits_numpy1', 'degree_centrality', 'closeness_centrality', 'square_clustering', 'core_number', 'node_clique_number', 'number_of_cliques', 'triangles', 'greedy_color', 'eigenvector_centrality_numpy', 'load_centrality' ] frame = pd.DataFrame(matrix_datos) frame.columns = labelNew frame.index = FuncName[6:tam] Resul = os.getcwd() out_data = Resul + '/graph_metrics.csv' out_mat = Resul + '/graph_metrics_global.mat' frame.to_csv(out_data) sio.savemat( out_mat, { FuncName[0]: Dpc, FuncName[1]: cluster, FuncName[2]: estra, FuncName[3]: tnsity, FuncName[4]: conNo, FuncName[5]: ac }) return out_data, out_mat
cont=0 lista_tiempos=[] lista_tiempos_completos={} tiempo_de_paro=0 tiempo_inicial=0 tiempo_final =0 tiempo_ejecucion=0 for r in range(30): lista_tiempos_completos[r+1]=[] tiempo_de_paro=0 while tiempo_de_paro<1: tiempo_inicial = time() Dic=nx.greedy_color(Graf, strategy='largest_first', interchange=False) tiempo_final = time() tiempo_ejecucion = tiempo_final - tiempo_inicial if tiempo_ejecucion>0.0: lista_tiempos_completos[r+1].append((tiempo_ejecucion*10000)) tiempo_de_paro+=tiempo_ejecucion #diccionario_inst[rog]=[] diccionario_inst_greedy_color[rog]=[] for i in lista_tiempos_completos.keys(): #desviacion=statistics.stdev(lista_tiempos_completos[i])
import networkx as nx import matplotlib.pyplot as plt G = nx.complete_graph(3) G.add_nodes_from(range(3, 7)) G.add_edges_from([(2, 3), (2, 4), (2, 6), (0, 3), (0, 6), (1, 6), (1, 5), (2, 5), (4, 5)]) fig, ax = plt.subplots() nx.draw_circular(G, ax=ax, with_labels=True) ax.set_title("Scheduling network") plt.show() coloring = nx.greedy_color(G) print("Coloring", coloring) # Coloring {2: 0, 0: 1, 1: 2, 5: 1, 6: 3, 3: 2, 4: 2} different_colors = set(coloring.values()) print("Different colors", different_colors) # Different colors {0, 1, 2, 3}
def calculate(graph): return len(set(nx.greedy_color(graph).values()))
def view_edges( aligner, viewer=None, tiles=None, vmin=None, vmax=None, gamma=1 / 2.2, ): """View EdgeAligner results in a Napari viewer using a checkerboard style. This "checkerboard" visualization colors tiles in pure red, green, and blue and applies additive blending to make good or bad alignment easy to spot at a per-pixel level. Pure yellow, cyan, and magenta objects indicate good alignment, whereas red, green, and blue fringes indicate misalignment. All tiles' contrast limits and gamma are linked so you can adjust those settings for all tiles by adjusting any one. Parameters ---------- aligner: EdgeAligner The EdgeAligner to visualize. viewer: optional napari.Viewer If present, add layers to this viewer instead of creating a new one. tiles: optional List[int] If present, visualize only the given tiles instead of every one. vmin, vmax: optional numeric Initial contrast limits. Detected from data if not provided. gamma: optional numeric Initial gamma correction. Default is appropriate for linear data. Returns ------- napari.viewer.Viewer """ if tiles is None: tiles = range(aligner.metadata.num_images) else: if not set(tiles) <= set(range(aligner.metadata.num_images)): raise ValueError("tiles contains invalid tile index values") node_colors = nx.greedy_color(aligner.neighbors_graph) num_colors = max(node_colors.values()) + 1 if num_colors > 3: raise ValueError(f"neighbors_graph requires more than 3 colors") dtype = aligner.metadata.pixel_dtype if np.issubdtype(dtype, np.integer): info = np.iinfo(dtype) elif np.issubdtype(dtype, np.floating): info = np.iinfo(dtype) else: raise ValueError(f"Can't display {dtype} image data") compute_vmin = vmin is None compute_vmax = vmax is None if compute_vmin: dmin = info.min vmin = np.inf else: dmin = vmin if compute_vmax: dmax = info.max vmax = -np.inf else: dmax = vmax # We wait until now, after we've passed all the argument validations, to # create the viewer window. It seems like bad form to throw up an empty # window only to then error out due to a bad arg value. if viewer is None: viewer = napari.Viewer() images = [] # Link contrast sliders for all tiles. def contrast_limits_callback(event): source_image = event.source new_clims = source_image.contrast_limits for image in images: # this is critical to avoid a RecursionError if image._contrast_limits != new_clims: image.contrast_limits = new_clims # Link gamma sliders for all tiles. def gamma_callback(event): source_image = event.source new_gamma = source_image.gamma for image in images: # this is critical to avoid a RecursionError if image._gamma != new_gamma: image.gamma = new_gamma for i in tiles: data = aligner.reader.read(i, aligner.channel) image = viewer.add_image( data, name=str(i), translate=aligner.positions[i], colormap=_colormaps[node_colors[i]], contrast_limits=(dmin, dmax), gamma=gamma, blending='additive', interpolation='bilinear', ) image.events.contrast_limits.connect(contrast_limits_callback) image.events.gamma.connect(gamma_callback) images.append(image) if compute_vmin: vmin = min(vmin, np.min(data)) if compute_vmax: vmax = max(vmax, np.max(data)) if compute_vmin or compute_vmax: for image in images: image.contrast_limits = (vmin, vmax) bounds_min = aligner.positions[tiles].min(axis=0) bounds_max = aligner.positions[tiles].max(axis=0) + aligner.metadata.size rect = tuple(bounds_min[::-1]) + tuple(bounds_max[::-1]) viewer.events.reset_view(rect=rect) return viewer
def print(graph, precision): return Utils.print_dict(dict(sorted(nx.greedy_color(graph).items())), precision)