def alternative_clust(graph): """Computes the clustering coefficient by taking into account the fraction of inactive nodes""" N = graph.GetNodes() n0 = snap.CntDegNodes(graph, 0) n1 = snap.CntDegNodes(graph, 1) f = 1 / (1 - (n0 + n1) / N) return f * clustering_WS(graph)
def getBasicInfo(strPath, net): G = snap.LoadEdgeList(snap.PUNGraph,strPath,0,1) GraphInfo = {} GraphInfo['nodes'] = G.GetNodes() GraphInfo['edges'] = G.GetEdges() GraphInfo['zeroDegNodes'] = snap.CntDegNodes(G, 0) GraphInfo['zeroInDegNodes'] = snap.CntInDegNodes(G, 0) GraphInfo['zeroOutDegNodes'] = snap.CntOutDegNodes(G, 0) GraphInfo['nonZeroIn-OutDegNodes'] = snap.CntNonZNodes(G) GraphInfo['uniqueDirectedEdges'] = snap.CntUniqDirEdges(G) GraphInfo['uniqueUndirectedEdges'] = snap.CntUniqUndirEdges(G) GraphInfo['selfEdges'] = snap.CntSelfEdges(G) GraphInfo['biDirEdges'] = snap.CntUniqBiDirEdges(G) NTestNodes = 10 IsDir = False GraphInfo['approxFullDiameter'] = snap.GetBfsEffDiam(G, NTestNodes, IsDir) GraphInfo['90effectiveDiameter'] = snap.GetAnfEffDiam(G) DegToCntV = snap.TIntPrV() snap.GetDegCnt(G, DegToCntV) sumofNode = G.GetNodes() L = [item.GetVal1()*item.GetVal2() for item in DegToCntV] GraphInfo['averageDegree'] = float(sum(L))/(sumofNode) (DegreeCountMax ,Degree, DegreeCount, CluDegree, Clu) = getGraphInfo(G) # creatNet(G,net) return GraphInfo,DegreeCountMax , Degree, DegreeCount, CluDegree, Clu
def temporal_alt_clust_coef(graphs, nodeID, directed=True): """Return the temporal alternative clustering coefficient of node nodeID during graphs It takes sparseness of graphs into account""" t_neighbors = temporal_neighbors(graphs, nodeID, False) subgraphs = temporal_subgraphs(graphs, t_neighbors) d = len(subgraphs) t_degree = t_neighbors.Len() c = 0 if t_degree == 0: return c elif t_degree == 1: return c else: for s, g in zip(subgraphs, graphs): N = g.GetNodes() n0 = snap.CntDegNodes(g, 0) n1 = snap.CntDegNodes(g, 1) f = 1 / (1 - (n0 + n1) / N) c += s.GetEdges()*f if directed: return c/(d*t_degree*(t_degree-1)) else: return 2*c/(d*t_degree*(t_degree-1))
def active_nodes_evolution(graphs, name, time_units, verbose=False, duration=None): """Plot the time evolution of the number of nodes with degree of at least one of snap graph in graphs""" Y = [] for g in graphs: Y.append(g.GetNodes() - snap.CntDegNodes(g, 0)) X = range(len(Y)) if duration is not None: X = range(duration[0], duration[1] + 1) plt.plot(X, Y) plt.xlabel("Time in {}".format(time_units)) plt.ylabel("Number of active nodes") plt.title("Active nodes evolution of {} graphs".format(name)) plt.savefig("nodes_time_{}".format(name)) if verbose: plt.show()
def getDataPointsToPlot(Graph): """ :param - Graph: snap.PUNGraph object representing an undirected graph return values: X: list of degrees Y: list of frequencies: Y[i] = fraction of nodes with degree X[i] """ ############################################################################ #find out the max out degree l1 = [] for NI in Graph.Nodes(): l1.append(NI.GetOutDeg()) maxOutDegree = max(l1) # populate list l2 with the count of nodes with out degree as index ( for eg., l2[outdegree] = count) l2 = [] #allocate the memory first for x in range(0, maxOutDegree + 1): l2.append(snap.CntDegNodes(Graph, x)) #for NI in Graph.Nodes() : # l2[NI.GetOutDeg()] = l2[NI.GetOutDeg()] + 1 # populate x and y as np array Y = np.array(l2) X = np.array(list(range(0, maxOutDegree + 1))) ############################################################################ #NId1 = snap.GetMxDegNId(Graph) #NI = Graph.GetNI(NId1) #maxDeg = NI.GetDeg() #for x in range(0, maxDeg + 1): # l2.append(snap.CntDegNodes(Graph, x)) #Y = np.array(l2) #X = np.array(list(range(0,maxDeg+1))) return X, Y
def getDataPointsToPlot(Graph): #find out the max out degree l1 = [] for NI in Graph.Nodes(): l1.append(NI.GetOutDeg()) maxOutDegree = max(l1) # populate list l2 with the count of nodes with out degree as index ( for eg., l2[outdegree] = count) l2 = [] #allocate the memory first for x in range(0, maxOutDegree+1): l2.append(snap.CntDegNodes(Graph, x)) Y = np.array(l2) X = np.array(list(range(0,maxOutDegree+1))) return X, Y
def print_degrees(G): """ Prints the number of nodes having degree=7 in the graph Also prints the nodes with the highest degree in the graph """ print('Number of nodes with degree=7:', snap.CntDegNodes(G, 7)) highest_deg = 0 highest_deg_list = [] for node in G.Nodes(): degree = node.GetDeg() if degree > highest_deg: highest_deg = degree highest_deg_list = [] highest_deg_list.append(node.GetId()) elif degree == highest_deg: highest_deg_list.append(node.GetId()) print('Node id(s) with highest degree:', end=' ') for node in highest_deg_list[: -1]: print(node, end=',') print(highest_deg_list[-1])
sys.exit() if input_file == "random5000by6.txt": #create random graph Graph = snap.GenRndGnm(snap.PUNGraph, 5000, 5000 * (5000 - 1) / 2) V = snap.TIntV() for i in range(5000): if (i % 6 != 0): V.Add(i) snap.DelNodes(Graph, V) snap.SaveEdgeList(Graph, 'random5000by6.txt') else: Graph = snap.LoadEdgeList(snap.PUNGraph, input_file, 0, 1) nodes = snap.CntNonZNodes(Graph) nodes0 = snap.CntDegNodes(Graph, 0) final_nodes = nodes + nodes0 edges = snap.CntUniqUndirEdges(Graph) nodes7 = snap.CntDegNodes(Graph, 7) DegToCntV = snap.TIntPrV() snap.GetDegCnt(Graph, DegToCntV) vector_length = len(DegToCntV) maxdegreencount = DegToCntV[vector_length - 1].GetVal2() #for item in DegToCntV: # print "%d nodes with degree %d" % (item.GetVal2(), item.GetVal1()) print "" print "Number of nodes in " + input_file + ": ", final_nodes print "Number of edges in " + input_file + ": ", edges print "Number of nodes with degree=7 in " + input_file + ": ", nodes7 print "Node id(s) with highest degree in " + input_file + ": ",
snap.SaveEdgeList(azsg, 'amazon.elist') subgraph_name = sys.argv[1] fbsgel = snap.LoadEdgeList(snap.PUNGraph, subgraph_name, 0, 1) MaxDegVfb = [] #Q1 #a fbnn = fbsgel.GetNodes() print("Number of nodes:", fbnn) #b fben = fbsgel.GetEdges() print("Number of edges:", fben) #Q2 #a print("Number of nodes with degree=7:", snap.CntDegNodes(fbsgel, 7)) #b max_deg_fb_id = snap.GetMxDegNId(fbsgel) NI = fbsgel.GetNI(max_deg_fb_id) max_deg_fb = NI.GetDeg() for NI in fbsgel.Nodes(): if (NI.GetDeg() == max_deg_fb): MaxDegVfb.append(NI.GetId()) MaxDegNodeString = ','.join(map(str, MaxDegVfb)) print("Node id(s) with highest degree:", MaxDegNodeString) #c snap.PlotOutDegDistr(fbsgel, "deg_dist_" + str(subgraph_name), "deg_dist_" + str(subgraph_name)) #Q3 #a i = 10
exit(1) graph.AddEdge2(u, v) # Question 1 ## Nodes print("Number of nodes: {}".format(graph.GetNodes())) ## Edges print("Number of edges: {}".format(graph.GetEdges())) # Question 2 ## Degree 7 print("Number of nodes with degree={}: {}".format(7, sn.CntDegNodes(graph, 7))) ## The Maximum Degree MxDeg = graph.GetNI(sn.GetMxDegNId(graph)).GetDeg() print("Node id(s) with highest degree: ", end="") flag = True for node in graph.Nodes(): if node.GetDeg() == MxDeg: if flag: print(node.GetId(), end="") flag = False else: print(", {}".format(node.GetId), end="") print() ## Plot of degrees
mean = (v1 + v2 + v3) / 3 mean2 = (v1 * v1 + v2 * v2 + v3 * v3) / 3 variance = (mean2 - mean * mean) return [mean, variance] Rnd = snap.TRnd(42) Rnd.Randomize() dirname = os.path.dirname(os.path.realpath(__file__)) if not os.path.exists('plots'): os.makedirs('plots') G = snap.LoadEdgeList(snap.PUNGraph, os.path.join(dirname, "subgraphs", sys.argv[1]), 0, 1) print("Number of nodes:", G.GetNodes()) print("Number of edges:", G.GetEdges()) print("Number of nodes which have degree=7:", snap.CntDegNodes(G, 7)) print("Node id(s) with highest degree: ", end="") InDegV = snap.TIntPrV() snap.GetNodeInDegV(G, InDegV) nodes = [] max_d = 0 for item in InDegV: max_d = max(max_d, item.GetVal2()) for item in InDegV: if (item.GetVal2() == max_d): nodes.append(item.GetVal1()) print(", ".join(list(map(str, sorted(nodes))))) dFull_10 = snap.GetBfsFullDiam(G, 10, False) dFull_100 = snap.GetBfsFullDiam(G, 100, False) dFull_1000 = snap.GetBfsFullDiam(G, 1000, False)
V2.Add(node.GetId()) snap.DelNodes(G2, V2) snap.SaveEdgeList(G2, "amazon.elist") file_name = sys.argv[1] Graph1 = snap.LoadEdgeList(snap.PUNGraph, file_name, 0, 1) #1.Size of the network node_count = Graph1.GetNodes() print("Number of nodes: ", node_count) edge_count = Graph1.GetEdges() print("Number of edges: ", edge_count) #2.Degree of nodes in the network node_deg7 = snap.CntDegNodes(Graph1, 7) print("Number of nodes with degree=7: ", node_deg7) max_deg = 0 #to store the highest degree of the graph nodes_max = [] #list to store node IDs of nodes with highest degree for node in Graph1.Nodes(): if node.GetDeg() > max_deg: max_deg = node.GetDeg() #print("Max degree:",max_deg) for node in Graph1.Nodes(): if node.GetDeg() == max_deg: nodes_max.append(node.GetId()) nodesmaxstring = ','.join(map( str, nodes_max)) #converting list to comma separated string print("Node id(s) with highest degree: %s" % nodesmaxstring)
plt.ylabel(y_label) plt.title(name) plt.savefig("plots/" + name + ".png") plt.close() if __name__ == "__main__": file_name = sys.argv[1] subgraph_name = file_name.split('.')[0] graph = make_snap_graph(list_of_edge_from_file(file_name)) print("Number of nodes:", graph.GetNodes()) print("Number of edges:", graph.GetEdges()) print("Number of nodes with degree=7:", snap.CntDegNodes(graph, 7)) print("Node id(s) with highest degree:", end=" ") print(*nodes_with_highest_degree(graph), sep=",") snap.PlotInDegDistr(graph, "temp", "Undirected graph - in-degree Distribution") os.system("mv inDeg.temp.png plots/deg_dist_" + subgraph_name + ".png") os.system("rm inDeg.*") full_diameter = [] full_diameter.append(snap.GetBfsFullDiam(graph, 10)) print("Approximate full diameter by sampling 10 nodes:", full_diameter[-1]) full_diameter.append(snap.GetBfsFullDiam(graph, 100)) print("Approximate full diameter by sampling 100 nodes:", full_diameter[-1]) full_diameter.append(snap.GetBfsFullDiam(graph, 1000))
#! /usr/bin/python import snap import matplotlib.pyplot as plt G1 = snap.LoadEdgeList(snap.PUNGraph, "edges-100k.txt", 0, 1) print("G1: Nodes %d, Edges %d" % (G1.GetNodes(), G1.GetEdges())) print("Number of Nodes: %d" % G1.GetNodes()) # 1.6 number of nodes of zero degree print("Number of nodes of zero degree: %d" % snap.CntDegNodes(G1, 0)) # Get in degree distribution DegToCntV = snap.TIntPrV() snap.GetDegCnt(G1, DegToCntV) degree = [] numNodes = [] sumDegrees = 0 for item in DegToCntV: degree.append(item.GetVal1()) numNodes.append(item.GetVal2()) sumDegrees += item.GetVal1() * item.GetVal2() #print("%d nodes with in-degree %d" % (item.GetVal2(), item.GetVal1())) plt.plot(degree, numNodes) plt.yscale('log') plt.xscale('log') plt.ylabel('frequency') plt.xlabel('degree') plt.title('Degree distribution')
def main(): parentDir = os.getcwd() os.chdir(parentDir + "/subgraphs") sub_graph = snap.LoadEdgeList(snap.PUNGraph, sys.argv[1], 0, 1) subGraphName = sys.argv[1].split(".")[0] os.chdir(parentDir) #### 1 ######## node_count = 0 for node in sub_graph.Nodes(): node_count = node_count + 1 printWithOutNewLine("Number of nodes:", node_count) printWithOutNewLine("Number of edges:", snap.CntUniqBiDirEdges(sub_graph)) #### 2 ######## printWithOutNewLine("Number of nodes with degree=7:", snap.CntDegNodes(sub_graph, 7)) rndMaxDegNId = snap.GetMxDegNId(sub_graph) nodeDegPairs = snap.TIntPrV() snap.GetNodeInDegV(sub_graph, nodeDegPairs) maxDegVal = 0 for pair in nodeDegPairs: if (pair.GetVal1() == rndMaxDegNId): maxDegVal = pair.GetVal2() break maxDegNodes = [] for pair in nodeDegPairs: if (pair.GetVal2() == maxDegVal): maxDegNodes.append(pair.GetVal1()) print("Node id(s) with highest degree:", end=" ") print(*maxDegNodes, sep=',') #### 3 ######## sampledFullDiam = [] sampledFullDiam.append(snap.GetBfsFullDiam(sub_graph, 10, False)) sampledFullDiam.append(snap.GetBfsFullDiam(sub_graph, 100, False)) sampledFullDiam.append(snap.GetBfsFullDiam(sub_graph, 1000, False)) sampledFullDiamStats = [] sampledFullDiamStats.append(round(statistics.mean(sampledFullDiam), 4)) sampledFullDiamStats.append(round(statistics.variance(sampledFullDiam), 4)) printWithOutNewLine("Approximate full diameter by sampling 10 nodes:", sampledFullDiam[0]) printWithOutNewLine("Approximate full diameter by sampling 100 nodes:", sampledFullDiam[1]) printWithOutNewLine("Approximate full diameter by sampling 1000 nodes:", sampledFullDiam[2]) print("Approximate full diameter (mean and variance):", end=" ") print(*sampledFullDiamStats, sep=',') sampledEffDiam = [] sampledEffDiam.append(round(snap.GetBfsEffDiam(sub_graph, 10, False), 4)) sampledEffDiam.append(round(snap.GetBfsEffDiam(sub_graph, 100, False), 4)) sampledEffDiam.append(round(snap.GetBfsEffDiam(sub_graph, 1000, False), 4)) sampledEffDiamStats = [] sampledEffDiamStats.append(round(statistics.mean(sampledEffDiam), 4)) sampledEffDiamStats.append(round(statistics.variance(sampledEffDiam), 4)) printWithOutNewLine("Approximate effective diameter by sampling 10 nodes:", sampledEffDiam[0]) printWithOutNewLine( "Approximate effective diameter by sampling 100 nodes:", sampledEffDiam[1]) printWithOutNewLine( "Approximate effective diameter by sampling 1000 nodes:", sampledEffDiam[2]) print("Approximate effective diameter (mean and variance):", end=" ") print(*sampledEffDiamStats, sep=',') #### 4 ######## printWithOutNewLine("Fraction of nodes in largest connected component:", round(snap.GetMxSccSz(sub_graph), 4)) bridgeEdges = snap.TIntPrV() snap.GetEdgeBridges(sub_graph, bridgeEdges) printWithOutNewLine("Number of edge bridges:", len(bridgeEdges)) articulationPoints = snap.TIntV() snap.GetArtPoints(sub_graph, articulationPoints) printWithOutNewLine("Number of articulation points:", len(articulationPoints)) #### 5 ######## printWithOutNewLine("Average clustering coefficient:", round(snap.GetClustCf(sub_graph, -1), 4)) printWithOutNewLine("Number of triads:", snap.GetTriads(sub_graph, -1)) randomNodeId = sub_graph.GetRndNId() nodeIdCcfMap = snap.TIntFltH() snap.GetNodeClustCf(sub_graph, nodeIdCcfMap) print("Clustering coefficient of random node", end=" ") print(randomNodeId, end=": ") print(round(nodeIdCcfMap[randomNodeId], 4)) print("Number of triads random node", end=" ") print(randomNodeId, end=" participates: ") print(snap.GetNodeTriads(sub_graph, randomNodeId)) printWithOutNewLine( "Number of edges that participate in at least one triad:", snap.GetTriadEdges(sub_graph, -1)) #### plots ######## if not os.path.isdir('plots'): os.makedirs('plots') os.chdir(parentDir + "/plots") plotsDir = os.getcwd() snap.PlotOutDegDistr(sub_graph, subGraphName, subGraphName + " Subgraph Degree Distribution") snap.PlotShortPathDistr( sub_graph, subGraphName, subGraphName + " Subgraph Shortest Path Lengths Distribution") snap.PlotSccDistr( sub_graph, subGraphName, subGraphName + " Subgraph Connected Components Size Distribution") snap.PlotClustCf( sub_graph, subGraphName, subGraphName + " Subgraph Clustering Coefficient Distribution") files = os.listdir(plotsDir) for file in files: if not file.endswith(".png"): os.remove(os.path.join(plotsDir, file)) plots = os.listdir(plotsDir) filePrefix = "filename" for file in plots: nameSplit = file.split(".") if (len(nameSplit) == 2): continue if (nameSplit[0] == "ccf"): filePrefix = "clustering_coeff_" elif (nameSplit[0] == "outDeg"): filePrefix = "deg_dist_" elif (nameSplit[0] == "diam"): filePrefix = "shortest_path_" elif (nameSplit[0] == "scc"): filePrefix = "connected_comp_" os.rename(file, filePrefix + nameSplit[1] + "." + nameSplit[2]) os.chdir(parentDir)
#UGraph.Dump() # analyzing network print "\n\t Analyzing Network\n\n" # 1) Size of network: print "Size of the network:\n" # a) prints the number of nodes in a graph print "Number of nodes in %s: %d" % (file, UGraph.GetNodes()) # b) print number of edges: print "Number of edges in %s: %d\n" % (file, UGraph.GetEdges()) # 2) degree of nodes in the network print "Degree of nodes in the network:\n" # a) print number of nodes which have degree = 7 Count = snap.CntDegNodes(UGraph, 7) print "Number of nodes with degree = 7 in %s: %d" % (file, Count) # b) prints node id(s) for the nodes with the highest degree maxNodes = [] maxDegree = 0 for node in UGraph.Nodes(): if (node.GetOutDeg()) > maxDegree: maxDegree = (node.GetOutDeg()) for node in UGraph.Nodes(): if (node.GetOutDeg()) == maxDegree: maxNodes.append(node.GetId()) print "Node id(s) with the highest degree in %s: %s\n" % (file, maxNodes)
# coding: utf-8 FIn = snap.TFIn("facebook.elist") Fb_graph = snap.TNGraph.Load(FIn) # # 1 and 2 c(partial) no_of_nodes = snap.CntNonZNodes(Fb_graph) print("Number of Nodes: " + str(no_of_nodes)) no_of_edges = snap.CntUniqUndirEdges(Fb_graph) print("Number of Edges: " + str(no_of_edges)) max_degree = -1 degdis_y = [] degdis_x = [] for i in range(1, no_of_nodes - 1): degree = snap.CntDegNodes(Fb_graph, i) max_degree = max(degree, max_degree) degdis_x.append(i) degdis_y.append(degree) # # 2 b print("Max degree:" + str(max_degree)) print("Node id(s) with highest degree:", end=" ") for NI in Fb_graph.Nodes(): if (NI.GetInDeg() == max_degree): print(NI.GetId(), end=",") # # 2 c plotting from matplotlib import pyplot as plt