def generate_possibilities(k): graphs = [] nodes = [i for i in range(k)] possible_edges = [] for i in range(len(nodes)): for j in range(len(nodes)): if i != j: possible_edges.append((i, j)) possible_graphs = [] # get all possible graphs for i in range(len(possible_edges)): combos = combinations(possible_edges, i) for combo in combos: possible_graphs.append(combo) print('Checking...' + str(len(possible_graphs)) + ' graphs') i = 0 # check that they are connected and not already in our list for possible_graph in possible_graphs: G = construct_graph(possible_graph, k) if snap.IsConnected(G): if is_new_graph(graphs, G, k): graphs.append(G) i += 1 if i % 500 == 0: print('Processed...' + str(i) + ' graphs') print('number of found graphs', len(graphs)) return graphs
def get_properties_with_sanppy(extension, input_folder): id_map = {} next_id = 0 graph = snap.PNGraph.New() files_read = 0 for file in os.listdir(input_folder): if not extension or file.endswith(extension): files_read += 1 with open(os.path.join(input_folder, file)) as file: for line in file.readlines(): edge = line.rstrip().split() n1 = id_map.get(edge[0], next_id) if n1 == next_id: id_map[edge[0]] = n1 next_id += 1 n2 = id_map.get(edge[1], next_id) if n2 == next_id: id_map[edge[1]] = n2 next_id += 1 if not graph.IsNode(n1): graph.AddNode(n1) if not graph.IsNode(n2): graph.AddNode(n2) graph.AddEdge(n1, n2) ef_diam_l, ef_diam_h, diam, sp = snap.GetBfsEffDiamAll(graph, 10, True) properties = [ snap.CntNonZNodes(graph), snap.CntUniqDirEdges(graph), snap.IsConnected(graph), snap.CntNonZNodes(graph) / snap.CntUniqDirEdges(graph), snap.GetClustCf(graph), sp, diam, snap.CntUniqDirEdges(graph) / (snap.CntNonZNodes(graph) * snap.CntNonZNodes(graph)) ] return dict(zip(get_property_names(), properties))
def has_euler_circuit(graph): # If graph is not connected then it has no Euler circuit if not snap.IsConnected(graph): return False for node in graph.Nodes(): if node.GetDeg() % 2 == 1: return False return True
def get_metrics(out_dir): print "Loading edges..." G = snap.LoadEdgeList(snap.PNGraph, out_dir + 'metricscompletegraph.txt', 0, 1, ' ') get_nodes(G) get_edges(G) print "Graph is connected? %s" % snap.IsConnected(G) get_degree_distribution(G) get_diameter(G) get_alpha(G) get_average_degree(G) get_connected_info(G)
def graphInfo(net): print '|V| = {}'.format(net.GetNodes()) print '|E| = {}'.format(net.GetEdges()) DegToCntV = snap.TIntPrV() snap.GetDegCnt(net, DegToCntV) overallDeg = 0 for item in DegToCntV: overallDeg = overallDeg + item.GetVal2()*item.GetVal1() print 'Average degree: {:.1f}'.format(float(overallDeg)/net.GetNodes()) print 'Graph connected: {}'.format(snap.IsConnected(net))
def has_euler_path(self, graph): vertices = set() odd_degree_count = 0 ### # Condition: verify that the graph is connected. # # If not, the graph cannot have an Euler path. ## if snap.IsConnected(graph) == False: # print("has_euler_path()::disconnected graph") return False, vertices # Type snap.PUNGraph is of an undirected graph. if type(graph) is snap.PUNGraph: nodes_degrees = self.util.get_in_out_degree_table(graph) # Iterate table of node degrees. for i in range(nodes_degrees.shape[0]): # If node has odd degree. if nodes_degrees[i, 1] % 2 != 0: # Add the vertex with odd degree to the vertices set. vertices.add(nodes_degrees[i, 0]) # Increase the odd degree counter by 1. odd_degree_count += 1 # Loop exit condition, if odd degree count surpasses 2. if odd_degree_count > 2: # print("has_euler_path()::graph has odd degree > 2") return False, set() if odd_degree_count != 2: # print("has_euler_path()::graph has odd degree != 2 ({})".format(odd_degree_count)) return False, set() else: # print("has_euler_path()::found Euler path") return True, vertices # Type snap.PNGraph is of a directed graph. if type(graph) is snap.PNGraph: pass return False, set()
def has_euler_path(graph): vertices = set() # If graph is not connected then it has no Euler path if not snap.IsConnected(graph): return False, vertices for node in graph.Nodes(): if node.GetDeg() % 2 == 1: vertices.add(node.GetId()) if len(vertices) == 2: return True, vertices else: return False, set()
def has_euler_circuit(graph): """ This method checks whether an undirected SNAP graph has an euler circuit. :param graph: SNAP object. A precomputed undirected Graph. :return: Boolean. """ # An undirected Eulerian circuit has no vertices of odd degrees for NI in graph.Nodes(): if NI.GetDeg() % 2 != 0: return False # Must be connected if not snap.IsConnected(graph): return False return True
def analyze_with_sanppy(extension, input_path): id_map = {} next_id = 0 graph = snap.PNGraph.New() files_read = 0 if os.path.isdir(input_path): for file in os.listdir(input_path): if not extension or file.endswith(extension): files_read += 1 next_id = load_graph_from_file(os.path.join(input_path, file), graph, id_map, next_id) else: load_graph_from_file(input_path, graph, id_map, next_id) print("Nodes: {}".format(snap.CntNonZNodes(graph))) print("Edges: {}".format(snap.CntUniqDirEdges(graph))) print("Connected: {}".format(snap.IsConnected(graph))) print("Average degree: {}".format(snap.CntNonZNodes(graph) / snap.CntUniqDirEdges(graph))) print("Average clustering coefficient: {}".format(snap.GetClustCf(graph))) ef_diam_l, ef_diam_h, diam, sp = snap.GetBfsEffDiamAll(graph, 10, True) print("Average shortest-path: {}".format(sp)) print("Diameter: {}".format(diam)) print("Density: {}".format(snap.CntUniqDirEdges(graph)/(snap.CntNonZNodes(graph)*snap.CntNonZNodes(graph))))
def has_euler_circuit(self, graph): ### # Condition: verify that the graph is connected. ## if snap.IsConnected(graph) == False: return False # Type snap.PUNGraph is of an undirected graph. if type(graph) is snap.PUNGraph: nodes_degrees = self.util.get_in_out_degree_table(graph) # Iterate table of node degrees. for i in range(nodes_degrees.shape[0]): # If a node with odd degree is found, return False. if nodes_degrees[i, 1] % 2 != 0: return False return True # Type snap.PNGraph is of a directed graph. if type(graph) is snap.PNGraph: pass
def create_connected_graph(self, graph, node_a=None, node_b=None, connected_nodes=None): # Initialize the connected nodes array. if connected_nodes is None: connected_nodes = [] # Initial conditions. # Pick a couple of random nodes to connect, initially. if node_a is None and node_b is None: node_a = random.randrange(graph.GetNodes()) node_b = None # Loop while node_b is not the same as node_a. while node_b is None or node_a == node_b: node_b = random.randrange(graph.GetNodes()) # Add edge (node_a, node_b). graph.AddEdge(node_a, node_b) # Add nodes to list of connected nodes. connected_nodes.append(node_a) connected_nodes.append(node_b) # Nodes have been connected from previous iteration. else: # Pick a random node from the set of {node_a, node_b} as the initial node for the next edge. # If false, set node_a as node_b. if not bool(random.getrandbits(1)): node_a = node_b node_b = None while node_b is None or node_b in connected_nodes: node_b = random.randrange(graph.GetNodes()) # Add edge (node_a, node_b). graph.AddEdge(node_a, node_b) # Add node to list of connected nodes. connected_nodes.append(node_b) # Otherwise select node_a and pick another candidate node for connection. else: node_b = None while node_b is None or node_b in connected_nodes: node_b = random.randrange(graph.GetNodes()) # Add edge (node_a, node_b). graph.AddEdge(node_a, node_b) # Add node to list of connected nodes. connected_nodes.append(node_b) # Recursion exit condition. # If graph is connected, return the graph. if snap.IsConnected(graph): return graph # If not, continue until a connected graph is created. else: return self.create_connected_graph(graph, node_a, node_b, connected_nodes)
file_2.write("Total number of different components = %d\n" % len(Components)) file_2.write("\n") i = 1 for idx, component in enumerate(Components): file_2.write("Size of component #%d : %d\n" % (idx, len(component))) file_2.close() # Output the average of the shortest paths, adding more edges to the graph if it's not connected average_shortest_paths = [] v_in_short_paths_len = [] vertices = u_rndm_graph.Nodes() len_vertices = sum(1 for _ in vertices) edge_list = list((item.GetSrcNId(), item.GetDstNId()) for item in u_rndm_graph.Edges()) # is the graph connected? print snap.IsConnected(u_rndm_graph) while not snap.IsConnected(u_rndm_graph): #in_vertex, out_vertex = rand.sample([(v_i, v_o) # for v_i in set(range(len_vertices)) # for v_o in set(range(len_vertices)) # if v_i not in [cc for cc in Components] dans lequel est v_o, m) u_rndm_graph.AddEdge(in_vertex, out_vertex) print "Now graph is fully connected" for v_in in vertices: id_v_in = v_in.GetId() set_v_out = filter(lambda x: x != id_v_in, vertices) for v_out in set_v_out: v_in_short_paths_len.append(snap.GetShortPath(u_rndm_graph, id_v_in, v_out.GetId())) #les reduce dessous c'est juste un tricks pour faire des sommes de toute la liste (; v_in_average__short_paths_len = reduce(lambda x, y: x+y, v_in_short_paths_len) / float(len(v_in_short_paths_len))
def is_connected(graph): # Just use the snap library to do that as the exercise points out. return snap.IsConnected(graph)
def calc_metric(net, i, ego, G): IsDir = True n_nodes = G.GetNodes() n_edges = G.GetEdges() ################################################################################## RANDOM GRAPH print( str(net) + " " + str(i) + " - Gerando grafo aleatório com " + str(n_nodes) + " vertices e " + str(n_edges) + " arestas...") connected = False Rnd = snap.TRnd() while not connected: print( str(net) + " " + str(i) + " - Testando se grafo aleatório é conectado...") Gnm = snap.GenRndGnm( snap.PNGraph, n_nodes, n_edges, IsDir, Rnd ) # Cria um grafo aleatório com as mesmas dimensões do original (nodes,edges) connected = snap.IsConnected(Gnm) print(str(net) + " " + str(i) + " - Grafo conectado... OK") ################################################################################### Coef Clust print( str(net) + " " + str(i) + " - Calculando o coeficiente de clustering do grafo...") coef_clust_G = snap.GetClustCf(G, -1) # Calcula o coeficiente de clustering print( str(net) + " " + str(i) + " - Calculando a coeficiente de clustering do grafo aleatório...") coef_clust_Gnm = snap.GetClustCf( Gnm, -1) # Calcula o coeficiente de clustering do grafo aleatório ################################################################################## AVERAGE SHORTEST PATH LENGHT print( str(net) + " " + str(i) + " - Calculando média dos menores caminhos mínimos do grafo...") t_spl_G = 0.0 # Somatório dos caminhos mínimos = total do somatório dos caminhos mínimos de cada vértice n_paths_G = 0 # Contador para quantidade de caminhos mínimos for node in G.Nodes(): NIdToDistH = snap.TIntH() node_spl = snap.GetShortPath(G, node.GetId(), NIdToDistH, IsDir) path = 0 for item in NIdToDistH: # print node.GetId(),item,NIdToDistH[item] path += 1 t_spl_G += NIdToDistH[item] n_paths_G += path - 1 # print # print ego,node.GetId(),t_spl_G,n_paths_G,path # print avg_spl_G = t_spl_G / float( n_paths_G ) # Calcula a média dos caminhos mínimos para todo o grafo considerando apenas caminhos existentes. avg_spl_G_all = t_spl_G / float( n_nodes * (n_nodes - 1)) # Calcula a média dos caminhos mínimos para todo o grafo. # labels = snap.TIntStrH() # for NI in G.Nodes(): # labels[NI.GetId()] = str(NI.GetId()) # snap.DrawGViz(G, snap.gvlDot, "/home/amaury/"+str(ego)+"_G.png", " ", labels) ################################################################################## AVERAGE SHORTEST PATH LENGHT RANDOM GRAPH print( str(net) + " " + str(i) + " - Calculando média dos menores caminhos mínimos do grafo aletório..." ) t_spl_Gnm = 0.0 # Somatório dos caminhos mínimos = total do somatório dos caminhos mínimos de cada vértice n_paths_Gnm = 0 # Contador para quantidade de caminhos mínimos for node in Gnm.Nodes(): NIdToDistH = snap.TIntH() node_spl = snap.GetShortPath(Gnm, node.GetId(), NIdToDistH, IsDir) path = 0 for item in NIdToDistH: # print node.GetId(),item,NIdToDistH[item] path += 1 t_spl_Gnm += NIdToDistH[item] n_paths_Gnm += path - 1 # print # print ego, node.GetId(),t_spl_Gnm,n_paths_Gnm,path # print avg_spl_Gnm = t_spl_Gnm / float( n_paths_Gnm ) # Calcula a média dos caminhos mínimos para todo o grafo considerando apenas caminhos existentes. avg_spl_Gnm_all = t_spl_Gnm / float( n_nodes * (n_nodes - 1) ) # Calcula a média dos caminhos mínimos para todo o grafo = (N*(N-1)) nodes. # labels = snap.TIntStrH() # for NI in Gnm.Nodes(): # labels[NI.GetId()] = str(NI.GetId()) # snap.DrawGViz(Gnm, snap.gvlDot, "/home/amaury/"+str(ego)+"_Gnm.png", " ", labels) # print ("Ego / Coef Clust: Graph / Random Graph") # print ego,coef_clust_G,coef_clust_Gnm # print ("ASPL Exists Path: Graph / Random Graph") # print ego,avg_spl_G, avg_spl_Gnm # print ("EGO / ASPL Total Paths: Graph / Random Graph") # print avg_spl_G_all, avg_spl_Gnm_all # print "##############################################" # print ################################################################################### S METRIC # if coef_clust_Gnm == 0: GAMMA = 0 else: GAMMA = float(coef_clust_G) / float( coef_clust_Gnm) # Numerador da métrica S LAMBDA_paths_exists = float(avg_spl_G) / float( avg_spl_Gnm ) # Denominador da métrica S com todos os caminhos existentes (só considera caminhos que existem) LAMBDA_all_paths = float(avg_spl_G_all) / float( avg_spl_Gnm_all ) # Denominador da métrica S com todos os caminhos possiveis (N*(N-1)) nodes # S1 = float(GAMMA) / float( LAMBDA_paths_exists ) # Métrica S de acordo com o artigo que o Prof. Thierson enviou S2 = float(GAMMA) / float( LAMBDA_all_paths ) # Métrica S de acordo com o artigo que o Prof. Thierson enviou return coef_clust_G, coef_clust_Gnm, avg_spl_G, avg_spl_Gnm, avg_spl_G_all, avg_spl_Gnm_all, S1, S2
def isConnected(self): return snap.IsConnected(self.rawGraph)
def is_graph_connected(G): return snap.IsConnected(G)
import snap # create a random directed graph G = snap.GenRndGnm(snap.PNGraph, 10000, 5000) # test if the graph is connected or weakly connected print("IsConnected(G) =", snap.IsConnected(G)) print("IsWeaklyConnected(G) =", snap.IsWeaklyConn(G)) # get the weakly connected component counts WccSzCnt = snap.TIntPr64V() snap.GetWccSzCnt(G, WccSzCnt) #print (WccSzCnt[0],WccSzCnt[0].Val1,WccSzCnt[0].Val2) for i in range(0, WccSzCnt.Len()): print("WccSzCnt[%d] = (%d, %d)" % (i, WccSzCnt[i].Val1.Val, WccSzCnt[i].Val2.Val)) # return nodes in the same weakly connected component as node 1 CnCom = snap.TInt64V() snap.GetNodeWcc(G, 1, CnCom) print("CnCom.Len() = %d" % (CnCom.Len())) # get nodes in weakly connected components WCnComV = snap.TCnComV() snap.GetWccs(G, WCnComV) for i in range(0, WCnComV.Len()): print("WCnComV[%d].Len() = %d" % (i, WCnComV[i].Len())) for j in range(0, WCnComV[i].Len()): print("WCnComV[%d][%d] = %d" % (i, j, WCnComV[i][j])) # get the size of the maximum weakly connected component
print("Source Node: ", mapping.GetKeyId(srcNode), "is", srcNode) for dstNode in range(1, G0.GetMxNId()): if G0.IsEdge(mapping.GetKeyId(srcNode), dstNode): NIdV.Add(dstNode) pass SubGraph = snap.GetSubGraph(G0, NIdV) for outDeg in range(00, 10): for inDeg in range(00, 10): snap.DelDegKNodes(SubGraph, outDeg, inDeg) for dstNode in range(1, SubGraph.GetMxNId()): if SubGraph.IsEdge(mapping.GetKeyId(srcNode), dstNode): print(dstNode, mapping.GetKey(dstNode)) Nodes = snap.TIntFltH() Edges = snap.TIntPrFltH() snap.GetBetweennessCentr(SubGraph, Nodes, Edges, 1.0) for node in Nodes: print "node: %d centrality: %f" % (node, Nodes[node]) print snap.IsConnected(SubGraph) snap.SaveEdgeList( SubGraph, "RelGraph.txt", "Save as tab-separated list of edges with no Zero InDeg Nodes") print("Number of edges is %d" % (snap.CntUniqDirEdges(SubGraph))) snap.PrintInfo(SubGraph)