def loadGraphPrintStats(inputFile, graphType): outGraph = snap.LoadEdgeList(snap.PUNGraph, inputFile, 0, 1) nodeCount = snap.CntNonZNodes(outGraph) edgeCount = snap.CntUniqUndirEdges(outGraph) avgDeg = float(edgeCount) / nodeCount print "Average Degree for %s graph is %f" % (graphType, avgDeg) return outGraph
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 genCircle(N=5242): """ :param - N: number of nodes return type: snap.PUNGraph return: Circle graph with N nodes and N edges. Imagine the nodes form a circle and each node is connected to its two direct neighbors. """ ############################################################################ # TODO: Your code here! Graph = snap.TUNGraph.New() for i in range(0, N): Graph.AddNode(i) print Graph.GetNodes() for i in range(0, N): #print i%N, (i+1)%N, (i+2)%N Graph.AddEdge(i % N, (i + 1) % N) Count = snap.CntUniqUndirEdges(Graph) print Count ############################################################################ return Graph
def connectRandomNodes(Graph, M=4000): """ :param - Graph: snap.PUNGraph object representing an undirected graph :param - M: number of edges to be added return type: snap.PUNGraph return: Graph object with additional M edges added by connecting M randomly selected pairs of nodes not already connected. """ ############################################################################ count = 0 N = Graph.GetNodes() adj = np.zeros((N, N)) for i in range(0, N): for j in range(0, N): if (Graph.IsEdge(i, j)): adj[i][j] = 1 while (1): src = random.randint(0, N) dest = random.randint(0, N) if (src % N != dest % N): if (adj[src % N][dest % N] == 0): adj[src % N][dest % N] = 1 Graph.AddEdge(src % N, dest % N) count = count + 1 if (count == M): break Count = snap.CntUniqUndirEdges(Graph) print Count ############################################################################ return Graph
def genErdosRenyi(N=5242, E=14484): """ :param - N: number of nodes :param - E: number of edges return type: snap.PUNGraph return: Erdos-Renyi graph with N nodes and E edges """ ############################################################################ # TODO: Your code here! Graph = snap.TUNGraph.New() for i in range(0, N): Graph.AddNode(i) adj = np.zeros((N, N)) count = 0 while (count <= E + 1): src = random.randint(0, N - 1) dest = random.randint(0, N - 1) if (src != dest): if (adj[src][dest] == 0): adj[src][dest] = 1 count = count + 1 Graph.AddEdge(src, dest) Count = snap.CntUniqUndirEdges(Graph) print Count ############################################################################ return Graph
def partOneAndTwo(WikiG): # WikiG.Dump() print('1. Number of nodes: '+str(WikiG.GetNodes())) selfloop_cnt = 0 for node in WikiG.Nodes(): # print(node.GetId()) if WikiG.IsEdge(node.GetId(), node.GetId()): selfloop_cnt += 1 print('2. Self loop Node: {}'.format(selfloop_cnt)) cnt_dir = snap.CntUniqDirEdges(WikiG) print('3. The number of directed edges: {}'.format(cnt_dir)) cnt_undir = snap.CntUniqUndirEdges(WikiG) print("4. The number of unique undirected edges is %d" % cnt_undir) print("5. The number of reciprocated edges is %d" % (cnt_dir - cnt_undir)) cnt_in = snap.CntInDegNodes(WikiG, 0) print("6. The number of nodes of zero out-degree is %d" % cnt_in) cnt_out = snap.CntOutDegNodes(WikiG, 0) print("7. The number of nodes of zero in-degree is %d" % cnt_out) cnt_deg_above_10 = 0 cnt_deg_less_10 = 0 for node in WikiG.Nodes(): if node.GetOutDeg() > 10: cnt_deg_above_10 += 1 if node.GetInDeg() < 10: cnt_deg_less_10 += 1 print("8. The number of nodes with more than 10 outgoing edges is %d" % cnt_deg_above_10) print("9. The number of nodes with fewer than 10 incoming edges is %d" % cnt_deg_less_10) # Part 2 out_file_name = 'wiki' snap.PlotInDegDistr(WikiG, out_file_name, "Directed graph - in-degree Distribution") snap.PlotOutDegDistr(WikiG, out_file_name, "Directed graph - out-degree Distribution") InDegDistr = np.loadtxt("inDeg."+out_file_name+".tab") InDegDistr = InDegDistr[InDegDistr[:, 0] > 0] OutDegDistr = np.loadtxt("OutDeg."+out_file_name+".tab") # print(OutDegDistr.shape) OutDegDistr = OutDegDistr[OutDegDistr[:, 0] > 0] # print(OutDegDistr.shape) coff = np.polyfit(np.log10(OutDegDistr)[:, 0], np.log10(OutDegDistr)[:, 1], 1) print(coff) plt.figure() plt.subplot(211) plt.loglog(InDegDistr[:, 0], InDegDistr[:, 1]) plt.title('In deg Distr') plt.subplot(212) plt.loglog(OutDegDistr[:, 0], OutDegDistr[:, 1]) plt.loglog(OutDegDistr[:, 0], np.power(10, coff[1])*np.power(OutDegDistr[:, 0], coff[0])) plt.title('Out deg Distr & Last-Square Reg Line in log-log plot') plt.show()
def wikiVotingNetwork(): Component = snap.TIntPrV() #Loding the graph Wiki = snap.LoadEdgeList(snap.PNGraph, "Wiki-Vote.txt", 0, 1) #Printing Number of Nodes in the Graph print "Number of Nodes: ", Wiki.GetNodes() #Printing Number of Edges in the Graph print "Number of Edges: ", Wiki.GetEdges() #Printing Number of Directed Edges in the Graph print "Number of Directed Edges: ", snap.CntUniqDirEdges(Wiki) #Printing Number of Un-Directed Edges in the Graph print "Number of Undirected Edges: ", snap.CntUniqUndirEdges(Wiki) #Printing Number of Directed Edges in the Graph print "Number of Self-Edges: ", snap.CntSelfEdges(Wiki) #Printing Number of Zero InDeg Nodes in the Graph print "Number of Zero InDeg Nodes: ", snap.CntInDegNodes(Wiki, 0) #Printing Number of Zero OutDeg Nodes in the Graph print "Number of Zero OutDeg Nodes: ", snap.CntOutDegNodes(Wiki, 0) #Printing Node ID with maximum degree in the Graph print "Node ID with maximum degree: ", snap.GetMxDegNId(Wiki) snap.GetSccSzCnt(Wiki, Component) for comp in Component: #printing number of strongly connected components with size print "Size: %d - Number of Strongly Connected Components: %d" % ( comp.GetVal1(), comp.GetVal2()) #printing size of largest connected components print "Size of largest connected component: ", snap.GetMxSccSz(Wiki) snap.GetWccSzCnt(Wiki, Component) for comp in Component: #printing number of weekly connected components with size print "Size: %d - Number of Weekly Connected Component Wikipedia: %d" % ( comp.GetVal1(), comp.GetVal2()) #printing size of weekly connected components print "Size of Weakly connected component: ", snap.GetMxWccSz(Wiki) #plotting out-degree distribution snap.PlotOutDegDistr(Wiki, "wiki-analysis", "Directed graph - Out-Degree Distribution")
def connectNbrOfNbr(Graph, N=5242): """ :param - Graph: snap.PUNGraph object representing a circle graph on N nodes :param - N: number of nodes return type: snap.PUNGraph return: Graph object with additional N edges added by connecting each node to the neighbors of its neighbors """ ############################################################################ print Graph.GetNodes() for i in range(0, N): #print i%N, (i+1)%N, (i+2)%N Graph.AddEdge(i % N, (i + 2) % N) Count = snap.CntUniqUndirEdges(Graph) print Count ############################################################################ return Graph
def quick_properties(graph, name, dic_path): """Get quick properties of the graph "name". dic_path is the path of the dict {players: id} """ results = {} n_edges = graph.GetEdges() n_nodes = graph.GetNodes() n_self_edges = snap.CntSelfEdges(graph) n_directed_edges, n_undirected_edges = snap.CntUniqDirEdges( graph), snap.CntUniqUndirEdges(graph) n_reciprocated_edges = snap.CntUniqBiDirEdges(graph) n_zero_out_nodes, n_zero_in_nodes = snap.CntOutDegNodes( graph, 0), snap.CntInDegNodes(graph, 0) max_node_in = graph.GetNI(snap.GetMxInDegNId(graph)).GetDeg() max_node_out = graph.GetNI(snap.GetMxOutDegNId(graph)).GetDeg() components = snap.TCnComV() snap.GetWccs(graph, components) max_wcc = snap.GetMxWcc(graph) results["a. Nodes"] = n_nodes results["b. Edges"] = n_edges results["c. Self-edges"] = n_self_edges results["d. Directed edges"] = n_directed_edges results["e. Undirected edges"] = n_undirected_edges results["f. Reciprocated edges"] = n_reciprocated_edges results["g. 0 out-degree nodes"] = n_zero_out_nodes results["h. 0 in-degree nodes"] = n_zero_in_nodes results["i. Maximum node out-degree"] = max_node_out results["j. Maximum node in-degree"] = max_node_in results["k. Weakly connected components"] = components.Len() results["l. Nodes, edges of largest WCC"] = (max_wcc.GetNodes(), max_wcc.GetEdges()) print("##########") print("Quick overview of {} Network".format(name)) print("##########") print("{} Nodes, {} Edges".format(n_nodes, n_edges)) print("{} Self-edges ".format(n_self_edges)) print("{} Directed edges, {} Undirected edges".format( n_directed_edges, n_undirected_edges)) print("{} Reciprocated edges".format(n_reciprocated_edges)) print("{} 0-out-degree nodes, {} 0-in-degree nodes".format( n_zero_out_nodes, n_zero_in_nodes)) print("Maximum node in-degree: {}, maximum node out-degree: {}".format( max_node_in, max_node_out)) print("###") print "{} Weakly connected components".format(components.Len()) print "Largest Wcc: {} Nodes, {} Edges".format(max_wcc.GetNodes(), max_wcc.GetEdges()) prankH = snap.TIntFltH() snap.GetPageRank(graph, prankH) sorted_prankH = sorted(prankH, key=lambda key: prankH[key], reverse=True) NIdHubH = snap.TIntFltH() NIdAuthH = snap.TIntFltH() snap.GetHits(graph, NIdHubH, NIdAuthH) sorted_NIdHubH = sorted(NIdHubH, key=lambda key: NIdHubH[key], reverse=True) sorted_NIdAuthH = sorted(NIdAuthH, key=lambda key: NIdAuthH[key], reverse=True) with open(dic_path, 'rb') as dic_id: mydict = pickle.load(dic_id) print("3 most central players by PageRank scores: {}, {}, {}".format( name_from_index(sorted_prankH, 0, mydict), name_from_index(sorted_prankH, 1, mydict), name_from_index(sorted_prankH, 2, mydict))) print("Top 3 hubs: {}, {}, {}".format( name_from_index(sorted_NIdHubH, 0, mydict), name_from_index(sorted_NIdHubH, 1, mydict), name_from_index(sorted_NIdHubH, 2, mydict))) print("Top 3 authorities: {}, {}, {}".format( name_from_index(sorted_NIdAuthH, 0, mydict), name_from_index(sorted_NIdAuthH, 1, mydict), name_from_index(sorted_NIdAuthH, 2, mydict))) results["m. Three top PageRank"] = (name_from_index( sorted_prankH, 0, mydict), name_from_index( sorted_prankH, 1, mydict), name_from_index(sorted_prankH, 2, mydict)) results["n. Three top hubs"] = (name_from_index( sorted_NIdHubH, 0, mydict), name_from_index(sorted_NIdHubH, 1, mydict), name_from_index( sorted_NIdHubH, 2, mydict)) results["o. Three top authorities"] = (name_from_index( sorted_NIdAuthH, 0, mydict), name_from_index(sorted_NIdAuthH, 1, mydict), name_from_index( sorted_NIdAuthH, 2, mydict)) return results
# Section 1 # # Load data from file, then construct a directed graph wiki_g = snap.LoadEdgeListStr(snap.PNGraph, "Wiki-Vote.txt", 0, 1) # solution to hw print('*' * 10 + ' Section I ' + '*' * 10) print("The wiki-vote graph has " + str(wiki_g.GetNodes()) + " nodes.") # self_loop_nodes = 0 # for edge in wiki_g.Edges(): # if edge.GetSrcNId() == edge.GetDstNId(): # self_loop_nodes = self_loop_nodes + 1 # Better use built-in functions to count the self-edges... print("The wiki-vote graph has " + str(snap.CntSelfEdges(wiki_g)) + " self-looped nodes.") print("The wiki-vote graph has " + str(snap.CntUniqDirEdges(wiki_g)) + " unique directed edges.") print("The wiki-vote graph has " + str(snap.CntUniqUndirEdges(wiki_g)) + " unique undirected edges.") print("The wiki-vote graph has " + str(int(snap.CntUniqUndirEdges(wiki_g) / 2)) + " reciprocated edges.") nodes_zero_out_degree = 0 nodes_zero_in_degree = 0 nodes_more_than_10_outgoing_edges = 0 nodes_fewer_than_10_incoming_edges = 0 min_out_degree = 1 max_out_degree = 1 for node in wiki_g.Nodes(): if node.GetOutDeg() == 0: nodes_zero_out_degree = nodes_zero_out_degree + 1
d[Community].append(NI) NodeIdList.Add(NI) SubGraph = snap.GetSubGraph(G1, NodeIdList) diam = snap.GetBfsFullDiam(SubGraph, 100, False) print "The diametre is %d" % diam DegToCCfV = snap.TFltPrV() DegList = list() result = snap.GetClustCfAll(SubGraph, DegToCCfV) for item in DegToCCfV: DegList.append(item.GetVal1()) #print "degree: %d, clustering coefficient: %f" % (item.GetVal1(), item.GetVal2()) print "average clustering coefficient", result[0] print "closed triads", result[1] print "open triads", result[2] NumTriadEdges = snap.GetTriadEdges(SubGraph) print "The number of TriadEdges is %d" % NumTriadEdges CountEdges = snap.CntUniqUndirEdges(SubGraph) print "Directed Graph: Count of undirected edges is %d" % CountEdges CountNodes = SubGraph.GetNodes() InternalDensity = CountEdges / (CountNodes * (CountNodes - 1) * 0.5) print "The Internal Density is %f" % InternalDensity AvgDeg = 2 * CountEdges / CountNodes print "The Average Degree is %f" % AvgDeg MedianDegree = np.median(DegList) print "The Median Degree is %d" % MedianDegree TPR = NumTriadEdges / CountEdges print "The Triangle Participation Rate is %d" % TPR NodeIdList.Clr() print "The modularity of the network is %f" % modularity
import sys import snap # FIn = snap.TFIn(sys.argv[1]) #!/usr/bin/env python # 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=",")
# 1.1 print("The number of nodes in the network is %s." % ( wikiGraph.GetNodes())) # 1.2 print("The number of nodes with a self-edge is %s." % ( snap.CntSelfEdges(wikiGraph))) # 1.3 print("The number of directed edges %s." % ( snap.CntUniqDirEdges(wikiGraph))) # 1.4 print("The number of undirected edges is %s." % ( snap.CntUniqUndirEdges(wikiGraph))) # 1.5 print("The number of reciprocated edges is %s." % ( snap.CntUniqDirEdges(wikiGraph) - snap.CntUniqUndirEdges(wikiGraph))) # 1.6 print("The number of nodes of zero out-degree is %s." % ( snap.CntOutDegNodes(wikiGraph, 0))) # 1.7 print("The number of nodes of zero in-degree is %s." % ( snap.CntInDegNodes(wikiGraph, 0))) # 1.8 outDegreeToCount = snap.TIntPrV()
# for edge in G1.Edges(): # src, dst = edge.GetSrcNId(), edge.GetDstNId() # # print(src, dst) # if src == dst: # self_loop_v_cnt += 1 # else: # direct_edge_cnt += 1 # Answer 2: print('There are {} self-loop nodes'.format(snap.CntSelfEdges(G1))) # Answer 3: print('Thre are {} directed edges'.format(snap.CntUniqDirEdges(G1))) # Answer 4: print('There are {} undirect edges'.format(snap.CntUniqUndirEdges(G1))) # Answer 5: print('There are {} reciprocated edges'.format(snap.CntUniqBiDirEdges(G1))) # Answer 6: print('There are {} nodes having 0 out-degree'.format( snap.CntOutDegNodes(G1, 0))) # Answer 7: print('There are {} nodes having 0 in-degree'.format( snap.CntInDegNodes(G1, 0))) # Answer 8: DegToCntV = snap.TIntPrV() snap.GetOutDegCnt(G1, DegToCntV)
import snap wiki = snap.LoadEdgeList(snap.PNGraph, "wiki-Vote.txt", 0, 1, '\t') # number of nodes print("Node number:", wiki.GetNodes()) # number of self-edge print("Self Edges:", snap.CntSelfEdges(wiki)) # number of directed edges print("Directed Edges:", wiki.GetEdges() - snap.CntSelfEdges(wiki)) # number of undirected edges (A->B and B->A counts a single undirected edge) print("Undirected Edges:", snap.CntUniqUndirEdges(wiki)) # number of reciprocated edges print("Reciprocated Edges:", snap.CntUniqBiDirEdges(wiki)) # nubmber of nodes of zero out-degree print("# of zero out-degree:", snap.CntOutDegNodes(wiki, 0)) # number of nodes of zero in-degree print("# of zero in-degree:", snap.CntInDegNodes(wiki, 0)) # number of nodes with out-degree > 10 count = 0 for i in range(11): count += snap.CntOutDegNodes(wiki, i) temp = wiki.GetNodes() - count print("Nodes with out-degree > 10:", temp)
##################################################################### ###EX4 import snap import matplotlib.pyplot as plt gh = snap.LoadEdgeList(snap.PUNGraph, "facebook/0.edges", 0, 1) DegToCntV1 = snap.TIntPrV() snap.GetDegCnt(gh, DegToCntV1) print("Number of nodes::" + str(snap.CntNonZNodes(gh))) print("Number of edges::" + str(snap.CntUniqUndirEdges(gh))) facebook_hist={} for item in DegToCntV1: facebook_hist[item.GetVal2()] = item.GetVal1() plt.bar(facebook_hist.keys(), facebook_hist.values(), color='g') fig_size = [14, 7] plt.rcParams["figure.figsize"] = fig_size plt.show() gh2 = snap.LoadEdgeList(snap.PUNGraph, "facebook/348.edges", 0, 1) DegToCntV2 = snap.TIntPrV() snap.GetDegCnt(gh2, DegToCntV2) print("Number of nodes::" + str(snap.CntNonZNodes(gh2))) print("Number of edges::" + str(snap.CntUniqUndirEdges(gh2))) f2_hist={} for item in DegToCntV2: f2_hist[item.GetVal2()] = item.GetVal1() plt.bar(map(str, f2_hist.keys()), f2_hist.values(), color='y') plt.xticks(rotation=90) plt.show()
# for e in g.Edges(): # if(e.GetSrcNId()!=e.GetDstNId()): # c=c+1; # print c; # print "\n" print snap.CntUniqDirEdges(g) print '\n' # cc=0; # ug=snap.ConvertGraph(snap.PUNGraph,g); # for e in ug.Edges(): # if(e.GetSrcNId()!=e.GetDstNId()): # cc=cc+1; # print cc; # print "\n"; print snap.CntUniqUndirEdges(g) print '\n' # print c-cc; # print "\n"; print snap.CntUniqBiDirEdges(g) print '\n' c = 0 for n in g.Nodes(): if (n.GetOutDeg() == 0): c = c + 1 print c print "\n" c = 0
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 + ": ", for i in range(maxdegreencount): NodeId = snap.GetMxDegNId(Graph)
import snap import matplotlib.pyplot as plt import numpy as np from pathlib import Path import sys gfile = sys.argv[1] print('Printing summary stats for file at:', gfile) if gfile.endswith('.graph'): FIn = snap.TFIn(gfile) Network = snap.TUNGraph.Load(FIn) else: Network = snap.LoadEdgeList(snap.PUNGraph, gfile, 0, 1) snap.PrintInfo(Network) print('Edges:', snap.CntUniqUndirEdges(Network)) # for directed graphs, should be same for undir DegToCntV = snap.TIntPrV() snap.GetInDegCnt(Network, DegToCntV) print('Nodes with deg > 10', sum([item.GetVal2() for item in DegToCntV if item.GetVal1() > 10])) ClustCoeff = snap.GetClustCf(Network, 10000) print('Clustering coeff', ClustCoeff)
def numUniqueUndirectedEdges(self): return snap.CntUniqUndirEdges(self.rawGraph)