Exemple #1
0
def gen_data():
    graph = snap.GenRndGnm(snap.PNGraph, 300, 2400, True)
    snap.SaveEdgeList(graph, "../data/Erdos-Renyi.txt")
    graph = snap.GenPrefAttach(300, 8)
    snap.SaveEdgeList(graph, "../data/PrefAttach.txt")
    graph = snap.GenRndPowerLaw(300, 1.2)
    snap.SaveEdgeList(graph, "../data/power-law.txt")
Exemple #2
0
def generate_graph(NNodes, NEdges, Model, Rnd):
  
  Graph = None
  if Model == 'rand_ungraph':
    # GnRndGnm returns error, so manually generate
    Graph = snap.GenRndGnm_PUNGraph(NNodes, NEdges, 0)

  elif Model == 'rand_ngraph':
    Graph = snap.GenRndGnm_PNGraph(NNodes, NEdges, 1)
      
  elif Model == 'rand_neagraph':
    Graph = snap.GenRndGnm_PNEANet(NNodes, NEdges, 1)

  elif Model == 'syn_neagraph':
    Graph = snap.GenSyntheticGraph_PNEANet(NNodes, NEdges/NNodes,
                                             SYNTHETIC_DELTA)

  elif Model == 'syn_ngraph':
    Graph = snap.GenSyntheticGraph_PNGraph(NNodes, NEdges/NNodes,
                                             SYNTHETIC_DELTA)

  elif Model == 'rmat':
    Graph = snap.GenRMat(NNodes, NEdges, 0.40, 0.25, 0.2, Rnd)

  elif Model == 'sw':
    Graph = snap.GenSmallWorld(NNodes, NNodes/NEdges, 0.1)
  
  elif Model == 'pref':
    Graph = snap.GenPrefAttach(NNodes, NNodes/NEdges)

  else:
    print "Unknown model: %s" % Model
    sys.exit(1)

  return Graph
Exemple #3
0
def main():
    RANDOM_SEED = 23

    SYNTHETIC_NW_NODES = 4846609        # How many nodes in the fake networks.
    SYNTHETIC_NW_EDGES = 42851237       # How many nodes in the fake networks.
    SYNTHETIC_NW_AVG_DEGREE = int(SYNTHETIC_NW_EDGES / SYNTHETIC_NW_NODES)

    random.seed(RANDOM_SEED)

    print "Generating preferential attachment graph..."
    tRnd = snap.TRnd()
    tRnd.PutSeed(RANDOM_SEED) # Re-seed every time.
    PAGraph = snap.GenPrefAttach(SYNTHETIC_NW_NODES, SYNTHETIC_NW_AVG_DEGREE, tRnd)
    filename = 'PrefAttachSynthetic-4.8M.txt'
    print "Saving edge list to file: %s" % filename
    snap.SaveEdgeList(PAGraph, filename, 'Synthetic preferential attachment graph')

    print "Generating random graph..."
    tRnd.PutSeed(RANDOM_SEED) # Re-seed every time.
    RndGraph = snap.GenRndGnm(snap.PUNGraph, SYNTHETIC_NW_NODES, SYNTHETIC_NW_EDGES, False, tRnd)
    filename = 'GnmRandomGraph-4.8M.txt'
    print "Saving edge list to file: %s" % filename
    snap.SaveEdgeList(RndGraph, filename, 'Random Gnm graph')

    print "Generating small world graph..."
    tRnd.PutSeed(RANDOM_SEED) # Re-seed every time.
    SWGraph = snap.GenSmallWorld(SYNTHETIC_NW_NODES, SYNTHETIC_NW_AVG_DEGREE, 0.1, tRnd)
    filename = 'SmallWorldGraph-4.8M.txt'
    print "Saving edge list to file: %s" % filename
    snap.SaveEdgeList(RndGraph, filename, 'Small world graph with rewire prob=0.1')

    print "Done"

    sys.exit(0)
def generate_graph(NNodes, NEdges, Model, Type, Rnd):

    if Model == 'rand_ungraph':
        # GnRndGnm returns error, so manually generate
        Graph = snap.GenRndGnm_PUNGraph(NNodes, NEdges, 0)

    elif Model == 'rand_ngraph':
        Graph = snap.GenRndGnm_PNGraph(NNodes, NEdges, 1)

    elif Model == 'rand_neanet':
        Graph = snap.GenRndGnm(NNodes, NEdges, 1)

    elif Model == 'syn_neanet':
        Graph = snap.GenSyntheticGraph(NNodes, NEdges / NNodes,
                                       SYNTHETIC_DELTA)

    elif Model == 'syn_ngraph':
        Graph = snap.GenSyntheticGraph_PNGraph(NNodes, NEdges / NNodes,
                                               SYNTHETIC_DELTA)

    elif Model == 'rmat':
        Graph = snap.GenRMat(NNodes, NEdges, 0.40, 0.25, 0.2, Rnd)

    elif Model == 'sw':
        Graph = snap.GenSmallWorld(NNodes, NNodes / NEdges, 0.1)

    elif Model == 'pref':
        Graph = snap.GenPrefAttach(NNodes, NNodes / NEdges)

    return Graph
def preferential_attachment():
    GUn = transform_directed_to_undirected()
    AverageDegree = average_degree()
    Rnd = snap.TRnd()
    GPA = snap.GenPrefAttach(GUn.GetNodes(), int(AverageDegree), Rnd)
    snap.PrintInfo(GPA, "Tweets PA Stats", "Tweets_PA-info.txt", False)
    f = open('Tweets_PA-info.txt', 'r')
    file_contents = f.read()
    print(file_contents)
    f.close()
Exemple #6
0
def gen_ba(args):
    """Generate a BA Graph"""

    for i in range(args.num_graphs):

        out_deg = int(np.random.uniform(2, 6))
        Rnd = snap.TRnd()
        Graph = snap.GenPrefAttach(args.num_vertices, out_deg, Rnd)
        snap.SaveEdgeList(Graph, f'{args.data_loc}/BA/BA_{i}.edges')

        print(f"BA Graph {i} Generated and Saved")
Exemple #7
0
def testExactEdgeCentrality():
  testG = snap.GenPrefAttach(NUM_NODES, OUT_DEGREE, Rnd)
  centrality = ExactEdgeCentrality(testG)
  unusedNodes = snap.TIntFltH()
  expectedCentrality = snap.TIntPrFltH()
  snap.GetBetweennessCentr(testG, unusedNodes, expectedCentrality, 1.0)

  for key in expectedCentrality:
    (v, w) = key.GetVal1(), key.GetVal2()
    expected = expectedCentrality[key]
    if abs(centrality[(v, w)] - expected) >= 1e-8:
      print centrality[(v, w)], expected
    assert abs(centrality[(v, w)] - expected) < 1e-8
Exemple #8
0
def generate_graphs():
    for path in GRAPHS:
        name = path.split('/')[-1].split('.')[0]

        metrics = Metrics(path, True).calculate_basic()

        print metrics

        # Generate Erdos-Renyi (Random) Graph
        # args: type, num_nodes, num_edges
        er = snap.GenRndGnm(snap.PNGraph, metrics.num_nodes, metrics.num_edges)
        snap.SaveEdgeList(er, "{}_er.elist".format(name))

        # Generate Watts-Strogatz (Small World) Graph
        # args: num_nodes, node_out_degree (average out degree will be twice this value, rewire_prob)
        ws = snap.GenSmallWorld(metrics.num_nodes,
                                int(metrics.avg_degree) / 2, 0.2)
        snap.SaveEdgeList(ws, "{}_ws.elist".format(name))

        # Generate Barabasi-Albert model (scale-free with preferential attachment) Graph
        # args: (num_nodes, degree of each node desired)
        ba = snap.GenPrefAttach(metrics.num_nodes, int(metrics.avg_degree) / 2)
        snap.SaveEdgeList(ba, "{}_ba.elist".format(name))

        # Generate Forest Fire model Graph
        # args: (num_nodes, forward_prob, backward_prob)
        if name == "USairport_2010":
            ff = snap.GenForestFire(
                metrics.num_nodes, 0.3599,
                0.3599)  # Selected value for US Airports data-set
            snap.SaveEdgeList(ff, "{}_ff.elist".format(name))

            ff = snap.GenForestFire(int(metrics.num_nodes / 10), 0.3599,
                                    0.3599)
            snap.SaveEdgeList(ff, "{}_ffdiv10.elist".format(name))

            ff = snap.GenForestFire(metrics.num_nodes * 10, 0.3599, 0.3599)
            snap.SaveEdgeList(ff, "{}_ffx10.elist".format(name))
        else:
            ff = snap.GenForestFire(metrics.num_nodes, 0.3467,
                                    0.3467)  # selected
            snap.SaveEdgeList(ff, "{}_ff.elist".format(name))

            ff = snap.GenForestFire(int(metrics.num_nodes / 10), 0.3467,
                                    0.3467)
            snap.SaveEdgeList(ff, "{}_ffdiv10.elist".format(name))

            ff = snap.GenForestFire(metrics.num_nodes * 10, 0.3467, 0.3467)
            snap.SaveEdgeList(ff, "{}_ffx10.elist".format(name))
Exemple #9
0
def testApproxEdgeCentrality():
  testG = snap.GenPrefAttach(NUM_NODES, OUT_DEGREE, Rnd)
  centrality = ApproxEdgeCentrality(
      testG, testG.GetNodes() / 10, 5 * testG.GetNodes())
  unusedNodes = snap.TIntFltH()
  expectedCentrality = snap.TIntPrFltH()
  snap.GetBetweennessCentr(testG, unusedNodes, expectedCentrality, 1.0)

  errorSum = 0.0
  for key in expectedCentrality:
    (v, w) = key.GetVal1(), key.GetVal2()
    expected = expectedCentrality[key]
    errorSum += (centrality[(v, w)] - expected)**2

  print errorSum
  print np.sqrt(errorSum / len(expectedCentrality))
Exemple #10
0
    def base_graph(self):
        G = None
        if self.graph_type == 'star':
            G = snap.GenStar(snap.PUNGraph, self.nnodes, False)
        elif self.graph_type == 'full':
            G = snap.GenFull(snap.PUNGraph, self.nnodes)
        elif self.graph_type == 'circle':
            G = snap.GenCircle(snap.PUNGraph, self.nnodes, False)
        elif self.graph_type == 'tree':
            G = snap.GenTree(snap.PUNGraph, Fanout=2, Levels=10, IsDir=False)
        elif self.graph_type == 'erdos-renyi' or self.graph_type == 'er':
            G = snap.GenRndGnm(snap.PUNGraph, self.nnodes, self.nnodes * 5,
                               False)
        elif self.graph_type == 'barabasi-albert' or self.graph_type == 'ba':
            G = snap.GenPrefAttach(self.nnodes, 10)
        else:
            print "> Defaulting to full mode"
            G = snap.GenFull(snap.PUNGraph, self.nnodes)

        return G
Exemple #11
0
def getGraph(p,d):
    # construct a graph from scale free distribution
    # paper: The joint graphical lasso for inverse covarianceestimation across multiple classes
    # reference: https://rss.onlinelibrary.wiley.com/doi/epdf/10.1111/rssb.12033
    # p: number of nodes
    # d: out degree of each node
    Rnd = snap.TRnd(10)
    UGraph = snap.GenPrefAttach(p, d, Rnd)
    S = np.zeros((p,p))
    for EI in UGraph.Edges():
    # generate a random number in (-0.4, -0.1)U(0.1,0.4)
    # method: https://stats.stackexchange.com/questions/270856/how-to-randomly-generate-random-numbers-in-one-of-two-intervals
        r = np.random.uniform(0, 0.6)
        S[EI.GetSrcNId(), EI.GetDstNId()] = r-0.4 if r < 0.3 else r-0.2 # assign values to edges
    
    S0 = S.copy() 
    # orginal half graph without standardizing it into a PD matrix
    S =  S + S.T 
    S = S/(1.5*np.sum(np.absolute(S), axis = 1)[:,None])
    A = (S + S.T)/2 + np.matrix(np.eye(p))
    # check if A is PD
    print(np.all(alg.eigvals(A) > 0))
    return S0, A
    def __init__(self, beta, delta, graphType, rewireProbInput, numNodes,
                 scalingFactor):
        self.graphType = graphType
        self.numNodes = numNodes

        # initialize snap.py graph: self.G

        # for degree, use reproductive number 1.5 = degree * beta: on avg, ebola patient should infect 1.5 other people
        # nodeDeg = math.ceil((1.5 / beta) / scalingFactor)

        nodeDeg = math.ceil(
            10.0 /
            scalingFactor)  # most real world graphs have node degree 2~15

        if graphType == 'small world':
            rewireProb = rewireProbInput  # probability that an edge will be rewired in Watts-Strogatz model
            self.G = snap.GenSmallWorld(
                numNodes, int(nodeDeg / 2),
                rewireProb)  # for snap function, must divide degree by 2
        elif graphType == 'random':
            numEdges = numNodes * nodeDeg / 2
            self.G = snap.GenRndGnm(snap.PUNGraph, numNodes, numEdges)
        elif graphType == 'complete':
            self.G = snap.GenFull(snap.PUNGraph, numNodes)
        elif graphType == 'scale free':
            self.G = snap.GenPrefAttach(numNodes, nodeDeg)
        else:
            raise NotImplementedError(
                "graphType argument must be in {'random', 'small world', 'complete', 'scale free}"
            )

        # initialize variables for SIR model
        self.beta, self.delta = beta, delta
        self.state = dict.fromkeys(
            xrange(numNodes), SUSCEPTIBLE
        )  # dict: int nodeID => string SUSCEPTIBLE or INFECTED or RECOVERED
        self.countyHasBeenInfected = False
def generate_graph(NNodes, NEdges, Model, Type, Rnd):

    if Model == 'rand_ungraph':
        # GnRndGnm returns error, so manually generate
        #Graph = snap.GenRndGnm_PUNGraph(NNodes, NEdges, 0)
        Graph = snap.GenRndGnm(snap.PUNGraph, NNodes, NEdges, 0)

    elif Model == 'rand_ngraph':
        #Graph = snap.GenRndGnm_PNGraph(NNodes, NEdges, 1)
        Graph = snap.GenRndGnm(snap.PNGraph, NNodes, NEdges, 1)

    elif Model == 'rand_neanet':
        print "1", NNodes, NEdges
        #Graph = snap.GenRndGnm_PNEANet(NNodes, NEdges, 1)
        Graph = snap.GenRndGnm(snap.PNEANet, NNodes, NEdges, 1)
        print "2"
        print "3", Graph.GetNodes(), Graph.GetEdges()

    elif Model == 'syn_neanet':
        Graph = snap.GenSyntheticGraph(NNodes, NEdges / NNodes,
                                       SYNTHETIC_DELTA)

    elif Model == 'syn_ngraph':
        Graph = snap.GenSyntheticGraph_PNGraph(NNodes, NEdges / NNodes,
                                               SYNTHETIC_DELTA)

    elif Model == 'rmat':
        Graph = snap.GenRMat(NNodes, NEdges, 0.40, 0.25, 0.2, Rnd)

    elif Model == 'sw':
        Graph = snap.GenSmallWorld(NNodes, NNodes / NEdges, 0.1)

    elif Model == 'pref':
        Graph = snap.GenPrefAttach(NNodes, NNodes / NEdges)

    return Graph
 def SimpleNetworkGenerator(self, params):
     #print params
     Rnd = snap.TRnd(1, 0)
     G = None
     try:
         if params[0] == GlobalParameters.NetworkType[0]:
             G = snap.GenSmallWorld(int(params[1]), int(params[2]),
                                    float(params[3]), Rnd)
         if params[0] == GlobalParameters.NetworkType[1]:
             G = snap.GenPrefAttach(int(params[1]), int(params[2]), Rnd)
         if params[0] == GlobalParameters.NetworkType[2]:
             G = snap.GenForestFire(int(params[1]), float(params[2]),
                                    float(params[3]))
         if params[0] == GlobalParameters.NetworkType[3]:
             G = snap.GenRndGnm(snap.PUNGraph, int(params[1]),
                                int(params[2]), False, Rnd)
         if params[0] == GlobalParameters.NetworkType[4]:
             G = snap.GenCircle(snap.PUNGraph, int(params[1]),
                                int(params[2]), False)
         if params[0] == GlobalParameters.NetworkType[5]:
             G = snap.GenFull(snap.PUNGraph, int(params[1]))
         return G
     except:
         return None
Exemple #15
0
def Q2():
  prefAttachmentGraph = snap.GenPrefAttach(NUM_NODES, OUT_DEGREE, Rnd)
  N = prefAttachmentGraph.GetNodes()
  global exactEdgeCentrality, approxEdgeCentrality
  exactEdgeCentrality = ExactEdgeCentrality(prefAttachmentGraph)
  approxEdgeCentrality = ApproxEdgeCentrality(
      prefAttachmentGraph, N / 10, 5 * N)
  assert len(exactEdgeCentrality) == len(approxEdgeCentrality)

  Y1 = sorted(exactEdgeCentrality.values(), reverse=True)
  Y2 = sorted(approxEdgeCentrality.values(), reverse=True)
  X = range(len(Y1))

  plt.close()
  plt.title("Exact and Approximate Betweeness Centrality Ordering")
  plt.xlabel("x-th largest edge")
  plt.ylabel("Calculated betweeness centrality")
  plt.semilogy(X, Y1)
  plt.semilogy(X, Y2)
  plt.legend(["Exact Algorithm", "Approximate Algorithm"])
  if not os.path.exists("output"):
    os.mkdir("output")
  plt.savefig("output/2", dpi=500)
  plt.show()
Exemple #16
0
                delta[vw] = sigma[v] * 1.0 / sigma[w] * delta[vw]

            if type == 1:
                B[vw] = B[vw] + delta[vw]
            else:
                if B[vw] <= c * G.GetNodes():
                    B[vw] = B[vw] + delta[vw]
                    k[vw] = k[vw] + 1


# Simulation
n = 1000
c = 5

Rnd = snap.TRnd()
G = snap.GenPrefAttach(n, 4, Rnd)
B1 = {}  # Betweenness Centrality for algorithm 1
B2 = {}  # Betweenness Centrality for algorithm 2
k = {}  # Number of samples for each edge
edges = []
for edge in G.Edges():
    edges.append((edge.GetSrcNId(), edge.GetDstNId()))
for i in xrange(len(edges)):
    B1[edges[i]] = 0
    B2[edges[i]] = 0
    k[edges[i]] = 0

# compute betweenness centrality for algorithm 1 - exact betweenness centrality
for sNode in G.Nodes():
    ComputeBetweennessCentrality(G, sNode, B1, 1, k)
Exemple #17
0
    ### LOAD GRAPH ###
    graph = snap.LoadEdgeList(snap.PUNGraph,
                              target_graph + "/" + target_graph + ".txt", 0, 1,
                              ' ')
    nodes = graph.GetNodes()
    edges = graph.GetEdges()
    InDegV = snap.TIntPrV()
    snap.GetNodeInDegV(graph, InDegV)
    sum_deg = 0
    for item in InDegV:
        sum_deg += item.GetVal2()
    avg_deg = sum_deg / nodes

    ### BASIC CHECKS OF GRAPHS ###
    print("Nodes: ", graph.GetNodes())
    print("Edges: ", graph.GetEdges())

    ###  Draw graph temporarily ###
    # snap.DrawGViz(graph, snap.gvlNeato, target_graph + ".png", target_graph, False)

    ### Structural Properties of Graph ###
    SCC = snap.GetMxScc(graph)
    print("SCC Nodes: ", SCC.GetNodes())
    print("SCC Edges: ", SCC.GetEdges())

    ### PREFERENTIAL ATTACHMENT ###
    Rnd = snap.TRnd()
    UGraph = snap.GenPrefAttach(nodes, int(avg_deg), Rnd)
    snap.DrawGViz(UGraph, snap.gvlDot, "pref.png", "Pref Graph", False)
def fitPA():
    for gname in GraphNames:
        G = snap.LoadEdgeList(snap.PUNGraph, 'data/rep/' + gname + '.txt')
        G1 = snap.GenPrefAttach(
            G.GetNodes(), int(math.ceil(1.0 * G.GetEdges() / G.GetNodes())))
        snap.SaveEdgeList(G1, '/Users/qv/cs224w/fit/' + gname + '-PA' + '.txt')
Exemple #19
0
print "G9: Nodes %d, Edges %d" % (G9.GetNodes(), G9.GetEdges())

# define a vector of pairs of integers (size, count) and
# get a distribution of connected components (component size, count)
CntV = snap.TIntPrV()
snap.GetWccSzCnt(G9, CntV)
for p in CntV:
    print "size %d: count %d" % (p.GetVal1(), p.GetVal2())

# get degree distribution pairs (out-degree, count):
snap.GetOutDegCnt(G9, CntV)
for p in CntV:
    print "degree %d: count %d" % (p.GetVal1(), p.GetVal2())

# generate a Preferential Attachment graph on 100 nodes and out-degree of 3
G10 = snap.GenPrefAttach(100, 3)
print "G10: Nodes %d, Edges %d" % (G10.GetNodes(), G10.GetEdges())

# define a vector of floats and get first eigenvector of graph adjacency matrix
EigV = snap.TFltV()
snap.GetEigVec(G10, EigV)
nr = 0
for f in EigV:
    nr += 1
    print "%d: %.6f" % (nr, f)

# get an approximation of graph diameter
diam = snap.GetBfsFullDiam(G10, 10)
print "diam", diam

# count the number of triads:
Exemple #20
0
def intro():

    # create a graph PNGraph
    G1 = snap.TNGraph.New()
    G1.AddNode(1)
    G1.AddNode(5)
    G1.AddNode(32)
    G1.AddEdge(1, 5)
    G1.AddEdge(5, 1)
    G1.AddEdge(5, 32)
    print("G1: Nodes %d, Edges %d" % (G1.GetNodes(), G1.GetEdges()))

    # create a directed random graph on 100 nodes and 1k edges
    G2 = snap.GenRndGnm(snap.PNGraph, 100, 1000)
    print("G2: Nodes %d, Edges %d" % (G2.GetNodes(), G2.GetEdges()))

    # traverse the nodes
    for NI in G2.Nodes():
        print("node id %d with out-degree %d and in-degree %d" %
              (NI.GetId(), NI.GetOutDeg(), NI.GetInDeg()))
    # traverse the edges
    for EI in G2.Edges():
        print("edge (%d, %d)" % (EI.GetSrcNId(), EI.GetDstNId()))

    # traverse the edges by nodes
    for NI in G2.Nodes():
        for Id in NI.GetOutEdges():
            print("edge (%d %d)" % (NI.GetId(), Id))

    # generate a network using Forest Fire model
    G3 = snap.GenForestFire(1000, 0.35, 0.35)
    print("G3: Nodes %d, Edges %d" % (G3.GetNodes(), G3.GetEdges()))

    # save and load binary
    FOut = snap.TFOut("test.graph")
    G3.Save(FOut)
    FOut.Flush()
    FIn = snap.TFIn("test.graph")
    G4 = snap.TNGraph.Load(FIn)
    print("G4: Nodes %d, Edges %d" % (G4.GetNodes(), G4.GetEdges()))

    # save and load from a text file
    snap.SaveEdgeList(G4, "test.txt", "Save as tab-separated list of edges")
    G5 = snap.LoadEdgeList(snap.PNGraph, "test.txt", 0, 1)
    print("G5: Nodes %d, Edges %d" % (G5.GetNodes(), G5.GetEdges()))

    # generate a network using Forest Fire model
    G6 = snap.GenForestFire(1000, 0.35, 0.35)
    print("G6: Nodes %d, Edges %d" % (G6.GetNodes(), G6.GetEdges()))
    # convert to undirected graph
    G7 = snap.ConvertGraph(snap.PUNGraph, G6)
    print("G7: Nodes %d, Edges %d" % (G7.GetNodes(), G7.GetEdges()))
    # get largest weakly connected component of G
    WccG = snap.GetMxWcc(G6)
    # get a subgraph induced on nodes {0,1,2,3,4,5}
    SubG = snap.GetSubGraph(G6, snap.TIntV.GetV(0, 1, 2, 3, 4))
    # get 3-core of G
    Core3 = snap.GetKCore(G6, 3)
    # delete nodes of out degree 10 and in degree 5
    snap.DelDegKNodes(G6, 10, 5)
    print("G6a: Nodes %d, Edges %d" % (G6.GetNodes(), G6.GetEdges()))

    # generate a Preferential Attachment graph on 1000 nodes and node out degree of 3
    G8 = snap.GenPrefAttach(1000, 3)
    print("G8: Nodes %d, Edges %d" % (G8.GetNodes(), G8.GetEdges()))
    # vector of pairs of integers (size, count)
    CntV = snap.TIntPrV()
    # get distribution of connected components (component size, count)
    snap.GetWccSzCnt(G8, CntV)
    # get degree distribution pairs (degree, count)
    snap.GetOutDegCnt(G8, CntV)
    # vector of floats
    EigV = snap.TFltV()
    # get first eigenvector of graph adjacency matrix
    snap.GetEigVec(G8, EigV)
    # get diameter of G8
    snap.GetBfsFullDiam(G8, 100)
    # count the number of triads in G8, get the clustering coefficient of G8
    snap.GetTriads(G8)
    snap.GetClustCf(G8)
Exemple #21
0
def generate_graph(n_nodes=50, out_degree=None, seed=1):
    """
    This method generates a Graph based on the Barabasi Algorithm and computes several metrics:
    1) It finds the Node with the maximum Degree.
    2) It finds the Node with the maximum PageRank Score.
    3) Calculates communities within the graph by using two different algorithms:
        a) Girvan - Newman community Detection
        b) Clauset-Newman-Moore community Detection.
        
    :param n_nodes: int. Specifies the number of nodes for the graph to be created.
    :param out_degree: int. Specifies the outer degree for each node. If None, then a random integer is generated
                            between 5 and 20.
    :param seed: Int. An integer that is used to generate the same 'random' integer for the out degree.
    :return: Boolean. Whether the execution time of the specific community detection algorithms is over 10 minutes.
    """

    if out_degree is None:
        random.seed(seed)
        out_degree = random.randint(5, 20)

    print
    print "Generating Graph with %s Nodes of Out Degree: %s " % (n_nodes,
                                                                 out_degree)

    # Generating a random graph based on the Barabasi Algorithm.
    barabasi_graph = snap.GenPrefAttach(n_nodes, out_degree)

    # Finding the node ID with the maximoun Degree.
    maximum_degree_node = snap.GetMxDegNId(barabasi_graph)

    # Iterating in the graph nodes in order to find the Maximum degree for this particular node.
    for NI in barabasi_graph.Nodes():
        if NI.GetId() == maximum_degree_node:
            print "Node: %d, Maximum Degree %d" % (NI.GetId(), NI.GetDeg())

    # Computing the PageRank score of every node in Graph

    # Setting the ID and the PageRank score to -1. (minimum of both of these is 0)
    page_rank_id, page_rank_score = -1, -1

    # Creating the iterator for the PageRank algorithm.
    PRankH = snap.TIntFltH()
    # Calculating the PageRank for every Node.
    snap.GetPageRank(barabasi_graph, PRankH)

    # By iterating on each node we find the Node with the maximum PageRank Score.
    for node in PRankH:
        if PRankH[node] > page_rank_score:
            page_rank_score = PRankH[node]
            page_rank_id = node

    print
    print "Node with the Highest PageRank value: "
    print "Node: %s, PageRank value %s " % (page_rank_id, page_rank_score)
    print

    try:
        start_Girvan_Newman = time.time(
        )  # setting the timer for the first community detection algorithm.

        # Calculating Girvan - Newman community Detection Algorithm
        CmtyV = snap.TCnComV()
        snap.CommunityGirvanNewman(barabasi_graph, CmtyV)
        print 'Girvan-Newman community Detection Algorithm: Execution Time: ', time.time(
        ) - start_Girvan_Newman

        # Calculating Girvan-Newman community Detection Algorithm
        start_Clauset_Newman_Moore = time.time(
        )  # setting the timer for the second community detection algorithm.
        CmtyV = snap.TCnComV()
        snap.CommunityCNM(barabasi_graph, CmtyV)
        print 'Clauset-Newman-Moore community Detection Algorithm: Execution Time: ', time.time(
        ) - start_Clauset_Newman_Moore

        print '-' * 100
        print '-' * 100

        if time.time(
        ) - start_Girvan_Newman > 10 * 60:  # if the total execution time for both algorithms is over 10
            # minutes then return False in order to quit the loop that this method will be used in.
            return False

        return True

    except MemoryError:  # if we get a memory error during the Community Detection algorithms we set to False in order
        # to avoid adding more Nodes when running this method in a while loop.
        return False
Exemple #22
0
with open(file, "r") as f:
    for x in f:
        edges += 1
print "nodes: %d, edges: %d" % (nodes, edges)

path = os.path.join(r"p3_data", filename[3:])

print "starting BA graph at time %s\n" % time.ctime()
edgeList = []
outDegree = 0
OutDegV = snap.TIntPrV()
snap.GetNodeOutDegV(inGraph, OutDegV)
#Sums the value of all out degrees of each node
for item in OutDegV:
    outDegree += item.GetVal2()
    # print "node ID %d: out-degree %d" % (item.GetVal1(), item.GetVal2())
# averages the out degree in OutDeg Vector, and rounds it to the nearest integar
avgOutDegree = round(outDegree / nodes)
# print avgOutDegree

Rnd = snap.TRnd()
barabasiAlbertGraph = snap.GenPrefAttach(nodes, int(avgOutDegree), Rnd)

for EI in barabasiAlbertGraph.Edges():
    edgeList.append([EI.GetSrcNId(), EI.GetDstNId()])
with open(path, "w") as f:
    for x in edgeList:
        f.write('{0:4d} {1:9d}\n'.format(x[0], x[1]))

print "finished BA graph at time %s\n" % time.ctime()
def pref_attach(nodes, out_degree, rnd=None):
    if rnd is None:
        rnd = sp.TRnd()
    else:
        rnd = sp.TRnd(*rnd)
    return sp.GenPrefAttach(nodes, out_degree, rnd)
Exemple #24
0
def genScaleFreeBA(N=5000, k=2):
    return snap.GenPrefAttach(N, k)
def run_ba_simulation(num_nodes, num_edges, alpha, zeta, *args, **kwargs):
    r = snap.GenPrefAttach(num_nodes, num_edges, gen)
    return run_simulation(r, alpha, zeta, *args, **kwargs)
Exemple #26
0
    nodes = int(sys.argv[1])
    degree = int(sys.argv[2])

    name = "test-%d-%d" % (nodes, degree)
    txtname = name + ".txt"
    adjname = name + "-adj" + ".txt"
    binname = name + ".bin"

    print("nodes", nodes)
    print("degree", degree)

    t = time.time()
    t = printtime(t, "generating the graph")

    G1 = snap.GenPrefAttach(nodes, degree)
    print("G1 nodes", G1.GetNodes())
    print("G1 edges", G1.GetEdges())

    t = printtime(t, "saving the graph to edge list")
    snap.SaveEdgeList(G1, txtname, "Save as tab-separated list of edges")

    t = printtime(t, "reading the graph from edge list")
    G2 = snap.LoadEdgeList(snap.PUNGraph, txtname, 0, 1)
    print("G2 nodes", G2.GetNodes())
    print("G2 edges", G2.GetEdges())

    t = printtime(t, "saving the graph to adjacency list")
    SaveConnList(G1, adjname)

    t = printtime(t, "reading the graph from adjacency list")
with open("WSOutput.txt", 'w+') as fp:
    header = str(WS_Nodes) + ',' + str(WS_Edges) + '\n'
    fp.write(header)
    timesteps = graphWS.values_at_each
    for i in range(0, len(timesteps)):
        line = str(timesteps[i][0]) + ',' + str(timesteps[i][1]) + ',' + str(
            timesteps[i][2]) + ',' + str(timesteps[i][3]) + '\n'
        fp.write(line)
print "Finished outputting\n"

BA_Nodes = 100000
BA_Edge = 10
#Single instance for WS graph.
gen.PutSeed(current_seed)
graphBA = Graph(alpha, zeta)
BA = snap.GenPrefAttach(BA_Nodes, BA_Edge, gen)
for it in BA.Edges():
    graphBA.AddEdge(it.GetSrcNId(), it.GetDstNId())
#Choose random infected.
infected = random.randint(0, len(graphBA.verts))
graphBA.states[infected] = (0, 1, 0, 0)
print "BA graph:"
start = time.time()
graphBA.do_simulation(10000)
end = time.time()
print "Simulation took", (end - start)

print "Writing to output:"
with open("BAOutput.txt", 'w+') as fp:
    header = str(BA_Nodes) + ',' + str(BA_Edge) + '\n'
    fp.write(header)
Exemple #28
0
for line in iter(fin):
    ugraph.AddNode(int(line))
    numnod += 1
    node_list.append(int(line))
fin.close()

fin = open("An_Edges.txt", "rb")

for line in iter(fin):
    ugraph.AddEdge(int(line.split(",", 1)[0]), int(line.split(",", 1)[1]))
    numedg += 1
fin.close()

rand_grph = snap.GenRndGnm(snap.PUNGraph, numnod, numedg, False)
snap.PlotInDegDistr(rand_grph, "degDistRand", "degDistRand")
#rand_grph.GetBfsEffDiam(ugraph,1,False,)
clust = snap.GetClustCf(rand_grph)
print "C Coeff Rand" + str(clust)

pref_grph = snap.GenPrefAttach(numnod, 4)
snap.PlotInDegDistr(pref_grph, "degDistPref", "degDistPref")
clust = snap.GetClustCf(pref_grph)
print "C Coeff Pref" + str(clust)

prob = (float(numnod) / (numedg * (numedg - 1))) * 2
print prob
smal_grph = snap.GenSmallWorld(numnod, 4, prob)
snap.PlotInDegDistr(smal_grph, "degDistSmal", "degDistSmal")
clust = snap.GetClustCf(smal_grph)
print "C Coeff Small" + str(clust)
Exemple #29
0
filenames = ["0301/{}.txt".format(i) for i in range(0, 4)]
data = Data(filenames)
graph = make_graph(data)
Graph = snap.ConvertGraph(snap.PUNGraph, graph)
save_graph_data(data, graph, "try")
data, graph = load_graph_data("try")
Graph = snap.ConvertGraph(snap.PUNGraph, graph)

GraphClustCoeff = snap.GetClustCf(Graph, -1)

print "Average clustering coefficient of the graph is ", GraphClustCoeff

for category in data.categories:
    graph1 = make_graph(data, [category])
    save_graph_data(data, graph1, "temp")
    data, graph1 = load_graph_data("temp")
    Graph1 = snap.ConvertGraph(snap.PUNGraph, graph1)
    print category, Graph1.GetNodes(), Graph1.GetEdges()
    GraphClustCoeff1 = snap.GetClustCf(Graph1, -1)
    print "Average clustering coefficient of the " + category + " graph is ", GraphClustCoeff1

V = Graph.GetNodes()
E = Graph.GetEdges()
print V, E
Erdos = snap.GenRndGnm(snap.PNGraph, V, E)
print "Erdos CC", snap.GetClustCf(Erdos, -1)

Rnd = snap.TRnd()
UGraph = snap.GenPrefAttach(V, 20, Rnd)
print "Pref Attachment CC", snap.GetClustCf(UGraph, -1)
Exemple #30
0

def Q2():
  prefAttachmentGraph = snap.GenPrefAttach(NUM_NODES, OUT_DEGREE, Rnd)
  N = prefAttachmentGraph.GetNodes()
  global exactEdgeCentrality, approxEdgeCentrality
  exactEdgeCentrality = ExactEdgeCentrality(prefAttachmentGraph)
  approxEdgeCentrality = ApproxEdgeCentrality(
      prefAttachmentGraph, N / 10, 5 * N)
  assert len(exactEdgeCentrality) == len(approxEdgeCentrality)

  Y1 = sorted(exactEdgeCentrality.values(), reverse=True)
  Y2 = sorted(approxEdgeCentrality.values(), reverse=True)
  X = range(len(Y1))

  plt.close()
  plt.title("Exact and Approximate Betweeness Centrality Ordering")
  plt.xlabel("x-th largest edge")
  plt.ylabel("Calculated betweeness centrality")
  plt.semilogy(X, Y1)
  plt.semilogy(X, Y2)
  plt.legend(["Exact Algorithm", "Approximate Algorithm"])
  if not os.path.exists("output"):
    os.mkdir("output")
  plt.savefig("output/2", dpi=500)
  plt.show()

Q2()

testG = snap.GenPrefAttach(NUM_NODES, OUT_DEGREE, Rnd)