def diameter(self ): try: return diameter( self._network ) except: components = connected_component_subgraphs( self._network) biggest_c = None for c in components: if biggest_c == None: biggest_c = c continue if( len( biggest_c) < len( c ) ) : biggest_c = c continue return diameter( biggest_c )
def calculate_gamma(g_matrix, graph): def k_neighbors(graph, node, k): def aux(node_list): res = set() for n in node_list: for i in graph.neighbors(n): res.add(i) return list(res) seen = [node] result = aux(seen) for _ in range(0, k - 1): not_seen = [elm for elm in result if elm not in seen] result += [elm for elm in aux(not_seen) if elm not in seen] seen += not_seen return list(set(result)) def gamma(g_matrix, graph, l): _sum = 0 number_of_nodes = len(graph.degree) for j in range(0, number_of_nodes): for i in k_neighbors(graph, j, l): _sum += g_matrix[i][j] return _sum / number_of_nodes return [gamma(g_matrix, graph, l) for l in range(1, diameter(graph) + 1)]
def get_topological_features(G, nodes=None): N_ = len(G.nodes) if nodes is None: nodes = G.nodes # Degree centrality d_c = get_features(degree_centrality(G).values()) print 'a' # Betweeness centrality b_c = get_features(betweenness_centrality(G).values()) print 'b' # Close ness centrality c_c = get_features(closeness_centrality(G).values()) print 'c' # Clustering c = get_features(clustering(G).values()) print 'd' d = diameter(G) r = radius(G) s_p_average = [] for s in shortest_path_length(G): dic = s[1] lengths = dic.values() s_p_average += [sum(lengths) / float(N_)] s_p_average = get_features(s_p_average) features = np.concatenate((d_c, b_c, c_c, c, s_p_average, [d], [r]), axis=0) return features
def diameter(graph: nx.Graph): """ Diameter or max. eccentricity of a graph Returns float or inf """ try: # graph must be connected and undirected return distance_measures.diameter(graph) except NetworkXError: return np.inf
def find_pairs(G): d = diameter(G) pairs = [] num_nodes = nx.number_of_nodes(G) for i in range(num_nodes): for j in range(i + 1, num_nodes): if nx.algorithms.shortest_path_length(G, source=i, target=j) == d: pairs.append((i, j)) return pairs
def get_diameter(graph): networkx_graph = to_networkx(graph).to_undirected() sub_graph_list = [ networkx_graph.subgraph(c) for c in connected_components(networkx_graph) ] sub_graph_diam = [] for sub_g in sub_graph_list: sub_graph_diam.append(diameter(sub_g)) return max(sub_graph_diam)
def _process(self, graph: dgl.DGLGraph) -> int: # type: ignore[override] """Compute the graph diameter Args: graph (dgl.DGLGraph): Input graph Returns: int: Diameter of graph """ networkx_graph = graph.to_networkx() return diameter(networkx_graph)
def get_diameter(): l = list() result = shanghai_graph_by_date() for k in result.keys(): g = result[k] d = diameter(g) l.append({'date': k.strftime("%Y-%m-%d"), 'diameter': d}) with open(os.path.join(base_dir, '上海分阶段数据/网络直径.csv'), 'a') as f: w = csv.DictWriter(f, ['date', 'diameter']) w.writeheader() w.writerows(l)
def compute_metrics(graph): G = json_graph.node_link_graph(graph, multigraph=False) degree_centrality = centrality.degree_centrality(G) closeness_centrality = centrality.closeness_centrality(G) betweenness_centrality = centrality.betweenness_centrality(G) page_rank = link_analysis.pagerank_alg.pagerank(G) max_clique = approximation.clique.max_clique(G) diameters = [distance_measures.diameter(g) for g in connected_component_subgraphs(G)] copy = dict() copy['id'] = graph['id'] copy['name'] = graph['name'] copy['graph'] = dict() copy['graph']['nodes'] = graph['nodes'] copy['graph']['links'] = graph['links'] copy['metrics'] = dict() # diameters copy['metrics']['diameter'] = dict() copy['metrics']['diameter']['all'] = diameters copy['metrics']['diameter']['max'] = max(diameters) copy['metrics']['diameter']['average'] = float(sum(diameters)) / float(len(diameters)) # clique size copy['metrics']['maxClique'] = len(list(max_clique)) # degree centrality copy['metrics']['degreeCentrality'] = dict() copy['metrics']['degreeCentrality']['byId'] = degree_centrality copy['metrics']['degreeCentrality']['max'] = sum(degree_centrality.values()) copy['metrics']['degreeCentrality']['average'] = float(sum(degree_centrality.values())) / float(len(degree_centrality.values())) # closeness centrality copy['metrics']['closenessCentrality'] = dict() copy['metrics']['closenessCentrality']['byId'] = closeness_centrality copy['metrics']['closenessCentrality']['max'] = sum(closeness_centrality.values()) copy['metrics']['closenessCentrality']['average'] = float(sum(closeness_centrality.values())) / float(len(closeness_centrality.values())) # degree centrality copy['metrics']['betweennessCentrality'] = dict() copy['metrics']['betweennessCentrality']['byId'] = betweenness_centrality copy['metrics']['betweennessCentrality']['max'] = sum(betweenness_centrality.values()) copy['metrics']['betweennessCentrality']['average'] = float(sum(betweenness_centrality.values())) / float(len(betweenness_centrality.values())) # degree centrality copy['metrics']['pageRank'] = dict() copy['metrics']['pageRank']['byId'] = page_rank copy['metrics']['pageRank']['max'] = sum(page_rank.values()) copy['metrics']['pageRank']['average'] = float(sum(page_rank.values())) / float(len(page_rank.values())) return copy
def is_strongly_regular(G): """Returns True if and only if the given graph is strongly regular. An undirected graph is *strongly regular* if * it is regular, * each pair of adjacent vertices has the same number of neighbors in common, * each pair of nonadjacent vertices has the same number of neighbors in common. Each strongly regular graph is a distance-regular graph. Conversely, if a distance-regular graph has diameter two, then it is a strongly regular graph. For more information on distance-regular graphs, see :func:`is_distance_regular`. Parameters ---------- G : NetworkX graph An undirected graph. Returns ------- bool Whether `G` is strongly regular. Examples -------- The cycle graph on five vertices is strongly regular. It is two-regular, each pair of adjacent vertices has no shared neighbors, and each pair of nonadjacent vertices has one shared neighbor:: >>> import networkx as nx >>> G = nx.cycle_graph(5) >>> nx.is_strongly_regular(G) True """ # Here is an alternate implementation based directly on the # definition of strongly regular graphs: # # return (all_equal(G.degree().values()) # and all_equal(len(common_neighbors(G, u, v)) # for u, v in G.edges()) # and all_equal(len(common_neighbors(G, u, v)) # for u, v in non_edges(G))) # # We instead use the fact that a distance-regular graph of diameter # two is strongly regular. return is_distance_regular(G) and diameter(G) == 2
def generate_graph(self, g: nx.Graph): for uid in g: v = Node(uid) self.nodes[uid] = v self.sharp_nodes = len(self.nodes) for uid in g: node = self.nodes[uid] for eid in g.neighbors(uid): neighbor = self.nodes[eid] node.adj.add(neighbor) node.adjlist.append(neighbor) if self.diameter == -1: self.diameter = diameter(g)
def get_graph_diameter(data): networkx_graph = to_networkx(data).to_undirected() sub_graph_list = [ networkx_graph.subgraph(c) for c in connected_components(networkx_graph) ] sub_graph_diam = [] for sub_g in sub_graph_list: sub_graph_diam.append(diameter(sub_g)) data.diameter = max(sub_graph_diam) if data.x is None: data.x = torch.ones(data.num_nodes, 1) return data
def runWith(fname) : print(fname) gm=dr.GraphMaker() gm.load(fname) # dpr=gm.pagerank() dg=gm.graph() #for x in dg: print('VERT::', x) print('nodes:', dg.number_of_nodes()) print('edges:', dg.number_of_edges()) comps=nx.strongly_connected_components(dg) print('strongly connected components:',len(list(comps))) c = max(nx.strongly_connected_components(dg), key=len) mg=dg.subgraph(c) print('attracting components:', co.number_attracting_components(dg)) print('number_weakly_connected_components:',co.number_weakly_connected_components(dg)) print('Transitivity:',cl.transitivity(dg)) return e=dm.eccentricity(mg) dprint('ecc:', e) cent=dm.center(mg,e=e) print('CENTER',cent) p=dm.periphery(mg,e=e) print('perif:', len(list(e))) #dprint('perif:', e) print('diameter:', dm.diameter(nx.Graph(mg))) print('radius:', dm.radius(nx.Graph(mg))) g = nx.Graph(dg) print('omega:', omega(g)) print('sigma:', sigma(g))
def check95(): with open("result_short.txt") as f: content = f.read().splitlines() counts = 0 print(len(content)) print("Starting to compute for n=9, r=5 using circuits!") for items in content: f = chirotope(9, 4, items) vertices = circuits(9, 4, f) G = make_graph(9, 5, vertices) d = diameter(G) if d != 6: print("Something wrong with line " + str(counts)) print(items) print(d) break counts += 1 if counts % 100 == 0: print("Now processing line " + str(counts))
def get_graph_diameter(data): ''' compute the graph diameter and add the attribute to data object :param data: the graph :return: the graph representation augmented with diameter attribute ''' networkx_graph = to_networkx(data).to_undirected() sub_graph_list = [ networkx_graph.subgraph(c) for c in connected_components(networkx_graph) ] sub_graph_diam = [] for sub_g in sub_graph_list: sub_graph_diam.append(diameter(sub_g)) data.diameter = max(sub_graph_diam) if data.x is None: data.x = torch.ones(data.num_nodes, 1) return data
def check_tope(string, n, r): f = chirotope(n, r, string) vertices = cocircuits(n, r, f) G = make_graph(n, r, vertices) for vector in gen_bin_comb(n): multiplier = np.array(vector) non_negatives = [] counting = np.ones(n) for i in range(len(vertices)): v = vertices[i] if (v * multiplier >= 0).all(): non_negatives.append(i) counting = counting * (v * multiplier) if len(non_negatives) > 0: H = G.subgraph(non_negatives) diam = diameter(H) new_n = sum(counting == 0) if diam > new_n - r + 1: print(string) print(multiplier) print(non_negatives) print(new_n) print(diam)
def getDiameter( self ) -> Union[int, list[Unknown], dict[Unknown, Any], float, Any, None]: """ """ return diameter(self.graph)
def __init__(self, g: nx.Graph, info: str, l2: float, d: int = None): self.g = g self.info = info self.l2 = l2 self.dia = d if d is not None else diameter(self.g)
def print_Measures(self, G, blnCalculateDimater=False, blnCalculateRadius=False, blnCalculateExtremaBounding=False, blnCalculateCenterNodes=False, fileName_to_print=None): #verify if graph is connected or not try: blnGraphConnected = is_connected(G) except: blnGraphConnected = False no_nodes = str(len(G.nodes())) no_edges = str(len(G.edges())) print("# Nodes: " + no_nodes) print("# Edges: " + no_edges) #Calculate and print Diameter if blnCalculateDimater == True: if blnGraphConnected == True: diameter_value = str(distance_measures.diameter(G)) print("Diameter: " + diameter_value) else: diameter_value = "Not possible to calculate diameter. Graph must be connected" print(diameter_value) #Calculate and print Radius if blnCalculateRadius == True: if blnGraphConnected == True: radius_value = str(distance_measures.radius(G)) print("Radius: " + radius_value) else: radius_value = "Not possible to calculate radius. Graph must be connected" print(radius_value) #Calculate and print Extrema bounding if blnCalculateExtremaBounding == True: if blnGraphConnected == True: extrema_bounding_value = str( distance_measures.extrema_bounding(G)) print("Extrema bounding: " + extrema_bounding_value) else: extrema_bounding_value = "Not possible to calculate Extrema bounding. Graph must be connected" print(extrema_bounding_value) #Calculate and print Centers if blnCalculateCenterNodes == True: str_centers_nodes = "" if blnGraphConnected == True: centers_nodes = distance_measures.center(G) str_centers_nodes = str( sorted(G.degree(centers_nodes), key=lambda x: x[1], reverse=True)) print("Centers with their degree: " + str_centers_nodes) else: centers_nodes = "Not possible to calculate Centers. Graph must be connected" print(centers_nodes) # if file name is passed in the parameters, we save the measures into a file if fileName_to_print != None: #creates path if does not exists if not os.path.exists(os.path.dirname(fileName_to_print)): os.makedirs(os.path.dirname(fileName_to_print)) f = open(fileName_to_print, "w") f.write("# Nodes: " + no_nodes + "\n") f.write("# Edges: " + no_edges + "\n") if blnCalculateDimater == True: f.write("Diameter: " + diameter_value + "\n") if blnCalculateRadius == True: f.write("Radius: " + radius_value + "\n") #if blnCalculateBaryCenter == True: # f.write("Bary Center: " + barycenter_node + "\n") if blnCalculateExtremaBounding == True: f.write("Extrema bounding: " + extrema_bounding_value + "\n") if blnCalculateCenterNodes == True: f.write("Centers with their degree: " + str_centers_nodes + "\n") f.close()
def get_diameter(graph): ''' Calculates the diameter (maximum eccentricity) of nodes of a given graph. @return number representing diameter of graph ''' return nx_dist.diameter(graph)
def run_GT_calcs(G, just_data, Do_kdist, Do_dia, Do_BCdist, Do_CCdist, Do_ECdist, Do_GD, Do_Eff, \ Do_clust, Do_ANC, Do_Ast, Do_WI, multigraph): # getting nodes and edges and defining variables for later use klist = [0] Tlist = [0] BCdist = [0] CCdist = [0] ECdist = [0] if multigraph: Do_BCdist = 0 Do_ECdist = 0 Do_clust = 0 data_dict = {"x": [], "y": []} nnum = int(nx.number_of_nodes(G)) enum = int(nx.number_of_edges(G)) if Do_ANC | Do_dia: connected_graph = nx.is_connected(G) # making a dictionary for the parameters and results just_data.append(nnum) data_dict["x"].append("Number of nodes") data_dict["y"].append(nnum) just_data.append(enum) data_dict["x"].append("Number of edges") data_dict["y"].append(enum) multi_image_settings.progress(35) # calculating parameters as requested # creating degree histogram if (Do_kdist == 1): klist1 = nx.degree(G) ksum = 0 klist = np.zeros(len(klist1)) for j in range(len(klist1)): ksum = ksum + klist1[j] klist[j] = klist1[j] k = ksum / len(klist1) k = round(k, 5) just_data.append(k) data_dict["x"].append("Average degree") data_dict["y"].append(k) multi_image_settings.progress(40) # calculating network diameter if (Do_dia == 1): if connected_graph: dia = int(diameter(G)) else: dia = 'NaN' just_data.append(dia) data_dict["x"].append("Network Diameter") data_dict["y"].append(dia) multi_image_settings.progress(45) # calculating graph density if (Do_GD == 1): GD = nx.density(G) GD = round(GD, 5) just_data.append(GD) data_dict["x"].append("Graph density") data_dict["y"].append(GD) multi_image_settings.progress(50) # calculating global efficiency if (Do_Eff == 1): Eff = global_efficiency(G) Eff = round(Eff, 5) just_data.append(Eff) data_dict["x"].append("Global Efficiency") data_dict["y"].append(Eff) multi_image_settings.progress(55) if (Do_WI == 1): WI = wiener_index(G) WI = round(WI, 1) just_data.append(WI) data_dict["x"].append("Wiener Index") data_dict["y"].append(WI) multi_image_settings.progress(60) # calculating clustering coefficients if (Do_clust == 1): Tlist1 = clustering(G) Tlist = np.zeros(len(Tlist1)) for j in range(len(Tlist1)): Tlist[j] = Tlist1[j] clust = average_clustering(G) clust = round(clust, 5) just_data.append(clust) data_dict["x"].append("Average clustering coefficient") data_dict["y"].append(clust) # calculating average nodal connectivity if (Do_ANC == 1): if connected_graph: ANC = average_node_connectivity(G) ANC = round(ANC, 5) else: ANC = 'NaN' just_data.append(ANC) data_dict["x"].append("Average nodal connectivity") data_dict["y"].append(ANC) multi_image_settings.progress(65) # calculating assortativity coefficient if (Do_Ast == 1): Ast = degree_assortativity_coefficient(G) Ast = round(Ast, 5) just_data.append(Ast) data_dict["x"].append("Assortativity Coefficient") data_dict["y"].append(Ast) multi_image_settings.progress(70) # calculating betweenness centrality histogram if (Do_BCdist == 1): BCdist1 = betweenness_centrality(G) Bsum = 0 BCdist = np.zeros(len(BCdist1)) for j in range(len(BCdist1)): Bsum += BCdist1[j] BCdist[j] = BCdist1[j] Bcent = Bsum / len(BCdist1) Bcent = round(Bcent, 5) just_data.append(Bcent) data_dict["x"].append("Average betweenness centrality") data_dict["y"].append(Bcent) multi_image_settings.progress(75) # calculating closeness centrality if (Do_CCdist == 1): CCdist1 = closeness_centrality(G) Csum = 0 CCdist = np.zeros(len(CCdist1)) for j in range(len(CCdist1)): Csum += CCdist1[j] CCdist[j] = CCdist1[j] Ccent = Csum / len(CCdist1) Ccent = round(Ccent, 5) just_data.append(Ccent) data_dict["x"].append("Average closeness centrality") data_dict["y"].append(Ccent) multi_image_settings.progress(80) # calculating eigenvector centrality if (Do_ECdist == 1): try: ECdist1 = eigenvector_centrality(G, max_iter=100) except: ECdist1 = eigenvector_centrality(G, max_iter=10000) Esum = 0 ECdist = np.zeros(len(ECdist1)) for j in range(len(ECdist1)): Esum += ECdist1[j] ECdist[j] = ECdist1[j] Ecent = Esum / len(ECdist1) Ecent = round(Ccent, 5) just_data.append(Ecent) data_dict["x"].append("Average eigenvector centrality") data_dict["y"].append(Ecent) data = pd.DataFrame(data_dict) return data, just_data, klist, Tlist, BCdist, CCdist, ECdist
def _get_diameter(G): return diameter(G)
data = [] data.append(fname) data.append(G.number_of_nodes()) data.append(G.number_of_edges()) data.append(density(G)) deg_centrality = degree_centrality(G) data.extend(properties_of_array(deg_centrality)) cln_centrality = closeness_centrality(G) data.extend(properties_of_array(cln_centrality)) btn_centrality = betweenness_centrality(G) data.extend(properties_of_array(btn_centrality)) st_path = shortest_path(G) deg = [len(val) for key, val in st_path.items()] d = np.array(deg) data.extend( [np.min(d), np.max(d), np.median(d), np.mean(d), np.std(d)]) try: data.append(diameter(G.to_undirected())) except: data.append(0) try: data.append(radius(G.to_undirected())) except: data.append(0) csvwriter.writerow(data) csvfile.close()
def find_diameter(string, n, r): G = construct_graph(string, n, r) return diameter(G)
ii_two_core_test = ii_two_core_test(C, ii_key) #print(ii_two_core_test) # [9] Transitivity # Def : the proportion of all triads that exhibit closure in the network # Outputs a float representing 3 (triangles / triads). transitivity = transitivity.transitivity(C) # [10] Diameter # Def : The diameter is the maximum eccentricity. # The eccentricity of a node v is the maximum distance from v to all other nodes in G. diameter = diameter.diameter(C) # ______________________________________________________________________________ # How to display the network. pylab.show() is necessary if not in the interactive # mode. Enter into interactive mode by typing ipython -pylab in the cmd. options = { 'node_color': 'grey', 'node_size': 1000, 'width': 3, } #nx.draw_shell(C, with_labels=True, **options) #pylab.show() # ______________________________________________________________________________
def ver_medidas(G): print(function.info(G)) """ Numero minimo de nodos que deben ser removidos para desconectar G """ print("Numero minimo de nodos que deben ser removidos para desconectar G :"+str(approximation.node_connectivity(G))) """ average clustering coefficient of G. """ print("average clustering coefficient of G: "+str(approximation.average_clustering(G))) """ Densidad de un Grafo """ print("Densidad de G: "+str(function.density(G))) """ Assortativity measures the similarity of connections in the graph with respect to the node degree. Valores positivos de r indican que existe una correlacion entre nodos con grado similar, mientras que un valor negativo indica correlaciones entre nodos de diferente grado """ print("degree assortativity:"+str(assortativity.degree_assortativity_coefficient(G))) """ Assortativity measures the similarity of connections in the graph with respect to the given attribute. """ print("assortativity for node attributes: "+str(assortativity.attribute_assortativity_coefficient(G,"crime"))) """ Grado promedio vecindad """ plt.plot(assortativity.average_neighbor_degree(G).values()) plt.title("Grado promedio vecindad") plt.xlabel("Nodo") plt.ylabel("Grado") plt.show(); """ Grado de Centralidad de cada nodo """ plt.plot(centrality.degree_centrality(G).values()) plt.title("Grado de centralidad") plt.xlabel("Nodo") plt.ylabel("Centralidad") plt.show(); """ Calcular el coeficiente de agrupamiento para nodos """ plt.plot(cluster.clustering(G).values()) plt.title("coeficiente de agrupamiento") plt.xlabel("Nodo") plt.show(); """ Media coeficiente de Agrupamiento """ print("Coeficiente de agrupamiento de G:"+str(cluster.average_clustering(G))) """ Centro del grafo El centro de un grafo G es el subgrafo inducido por el conjunto de vertices de excentricidad minima. La excentricidad de v in V se define como la distancia maxima desde v a cualquier otro vertice del grafo G siguiendo caminos de longitud minima. """ print("Centro de G:"+ str(distance_measures.center(G))) """ Diametro de un grafo The diameter is the maximum eccentricity. """ print("Diametro de G:"+str(distance_measures.diameter(G))) """ Excentricidad de cada Nodo The eccentricity of a node v is the maximum distance from v to all other nodes in G. """ plt.plot(distance_measures.eccentricity(G).values()) plt.title("Excentricidad de cada Nodo") plt.xlabel("Nodo") plt.show(); """ Periferia The periphery is the set of nodes with eccentricity equal to the diameter. """ print("Periferia de G:") print(distance_measures.periphery(G)) """ Radio The radius is the minimum eccentricity. """ print("Radio de G:"+str(distance_measures.radius(G))) """ PageRank calcula una clasificacion de los nodos en el grafico G en funcion de la estructura de los enlaces entrantes. Originalmente fue disenado como un algoritmo para clasificar paginas web. """ plt.plot(link_analysis.pagerank_alg.pagerank(G).values()) plt.title("Puntaje de cada Nodo") plt.xlabel("Nodo") plt.show(); """ Coeficiente de Small World. A graph is commonly classified as small-world if sigma>1. """ print("Coeficiente de Small World: " + str(smallworld.sigma(G))) """ The small-world coefficient (omega) ranges between -1 and 1. Values close to 0 means the G features small-world characteristics. Values close to -1 means G has a lattice shape whereas values close to 1 means G is a random graph. """ print("Omega coeficiente: "+str(smallworld.omega(G)))