def net_rnd(nodes, edges, is_directed=False, is_multigraph=False, rnd=None):
    if rnd is None:
        rnd = sp.TRnd()
    else:
        rnd = sp.TRnd(*rnd)
    if is_directed:
        if is_multigraph:
            return sp.GenRndGnm(sp.PNEANet, nodes, edges, is_directed, rnd)
        else:
            return sp.GenRndGnm(sp.PNGraph, nodes, edges, is_directed, rnd)
    else:
        return sp.GenRndGnm(sp.PUNGraph, nodes, edges, is_directed, rnd)
Exemplo n.º 2
0
def degree_frac(graph, budget, seed):
    """Selects each vertex fractionally proportional to its degree."""

    # Store incentive assignments in a dictionary indexed on nodes id
    incentives = dict()

    # Compute the fractional budget based on the number of edges and keep track of the amount spent
    budget_fraction = budget / graph.GetEdges()
    spent = 0

    # Set initial incentives to be proportional to the out-degree of each node
    for node in graph.Nodes():
        node_budget = math.floor(budget_fraction * node.GetOutDeg())

        incentives[node.GetId()] = node_budget
        spent += node_budget

    # Set snap random seed to be able to reproduce results
    snap.TRnd(seed)

    # Get the remainder unassigned budget and add it randomly
    remainder = budget - spent

    for i in range(0, remainder):
        incentives[graph.GetRndNId()] += 1

    return incentives
Exemplo n.º 3
0
def q2_2_util(dataset_name, outward):
    G = load_graph(dataset_name)
    Rnd = snap.TRnd(42)
    Rnd.Randomize()
    rand_ids = set()
    while(len(rand_ids)<100):
        NId = G.GetRndNId(Rnd)
        rand_ids.add(NId)
    
    cumulative_list = []
    for rand_nid in rand_ids:
        if outward:
            BfsTree = snap.GetBfsTree(G, rand_nid, True, False)
        else:
            BfsTree = snap.GetBfsTree(G, rand_nid, False, True)
        outward_set = set()
        for EI in BfsTree.Edges():
            outward_set.add(EI.GetDstNId())
        cumulative_list.append(len(outward_set))
        # print(len(cumulative_list))
    x = np.linspace(0, 1, 100)
    # print(x)
    cumulative_list.sort()
    cumulative_list = np.array(cumulative_list)
    # print(cumulative_list)
    plt.plot(x, cumulative_list, lw=2)
    plt.legend()
    plt.xlabel('Frac of rand ids')
    plt.ylabel('%s Reached notes (%s)' % (dataset_name, 'outward' if outward else 'inward'))
    plt.yscale('log')
    plt.show()
Exemplo n.º 4
0
def main():
    if len(sys.argv) != 2:
        print('File name must be provided')
        sys.exit(-1)

    filename = sys.argv[1]
    filenameWOExt = filename.split('.')[0].split('/')[-1]
    graph = snap.LoadEdgeList(snap.PNEANet, filename, 0, 1, '\t')
    snap.PrintInfo(graph, "New York", filenameWOExt + '_info.txt', False)

    Rnd = snap.TRnd(123124)
    erdosRenyi = snap.GenRndGnm(snap.PNEANet, graph.GetNodes(),
                                graph.GetEdges(), True, Rnd)
    snap.PrintInfo(erdosRenyi, "Erdos-Renyi", 'erdos_renyi_info.txt', False)

    grid = snap.GenGrid(snap.PNEANet, 220, 250, False)
    snap.PrintInfo(grid, "Grid", 'grid_info.txt', False)

    printGenericInformation(graph, 'New York street network')
    printGenericInformation(erdosRenyi, 'Erdos-Renyi random graph')
    printGenericInformation(grid, 'Grid random graph')

    # Plot everything in the plots directory
    os.chdir(os.path.join(os.path.abspath(sys.path[0]), 'plots'))
    saveDegreeDistribution(graph, 'deg_dist_ny.tab')
    saveDegreeDistribution(erdosRenyi, 'deg_dist_er.tab')
    saveDegreeDistribution(grid, 'deg_dist_gr.tab')

    testRobustnessAll([graph, erdosRenyi, grid])

    call(['gnuplot', 'deg_dist.plt'])
    call(['gnuplot', 'robustness_rand.plt'])
    call(['gnuplot', 'robustness_max.plt'])
Exemplo n.º 5
0
def generate_friends_network(user_count=10,
                             friends_count=get_friends_count(),
                             prob=get_prob(),
                             network_type='random',
                             conf_model=False):
    # User list, probability p and network_type is given, construct a graph
    res = "empty"

    # generate specific graphs
    if network_type.lower().find("small") >= 0:
        # This is a small world network
        print "Creating a small world network with " + str(
            user_count) + " users"
        rnd = snap.TRnd(1, 0)
        new_graph = snap.GenSmallWorld(user_count, friends_count, prob, rnd)
    elif network_type.lower().find("ring") >= 0:
        # A ring graph
        print "Creating a ring with " + str(user_count) + " users"
        new_graph = snap.GenCircle(snap.PUNGraph, user_count, friends_count)
    elif network_type.lower().find("power") >= 0:
        # Power Law network
        print "Creating a powerlaw network with " + str(user_count) + " users"
        new_graph = snap.GenRndPowerLaw(user_count, friends_count, conf_model)
    else:
        # A random graph
        print "Creating a random network with " + str(user_count) + " users"
        edge_count = user_count * friends_count
        new_graph = snap.GenRndGnm(snap.PUNGraph, user_count, edge_count)
    save_graph_in_db(new_graph)
Exemplo n.º 6
0
def main():
	if len(sys.argv) < 3:
		print("enter n and nnz as arguments")
		return

	n = int(sys.argv[1])
	e = int(sys.argv[2])

	now = time.time()
	Rnd = snap.TRnd()
	Rnd.PutSeed(int(now))

	for i in range(5):
		Graph = snap.GenRMat(n, e, .25, .25, .25, Rnd) 

		filestr = str(n) + "_" + str(e) + "_" + str(i)

		f = open(filestr, "w+")

		for EI in Graph.Edges():
			src = '{:10}'.format("%d" % (EI.GetSrcNId()))
			dst = '{:10}'.format("%d" % (EI.GetDstNId()))
			f.write(src + " " + dst + "\n")

		f.flush()
Exemplo n.º 7
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)
Exemplo n.º 8
0
def main():
    if len(sys.argv) < 4:
        print("enter a b c as arguments")
        return

    n = 32768
    e = 262144

    a = float(sys.argv[1])
    b = float(sys.argv[2])
    c = float(sys.argv[3])

    now = time.time()
    Rnd = snap.TRnd()
    Rnd.PutSeed(int(now))

    for i in range(5):
        Graph = snap.GenRMat(n, e, a / 100, b / 100, c / 100, Rnd)

        filestr = str(int(a)) + "_" + str(int(b)) + "_" + str(
            int(c)) + "_" + str(i)

        f = open(filestr, "w+")

        for EI in Graph.Edges():
            src = '{:10}'.format("%d" % (EI.GetSrcNId()))
            dst = '{:10}'.format("%d" % (EI.GetDstNId()))
            f.write(src + " " + dst + "\n")

        f.flush()
Exemplo n.º 9
0
def analysis_wwr():

    try:
        import snap
    except ModuleNotFoundError:
        pass

    stanford_data = load_stanford_dataset()
    node_set, node_id_to_idx, idx_to_node_id = _get_mapping(stanford_data)
    to_followings, to_followers = _get_followings_and_followers(
        stanford_data, node_id_to_idx, len(node_set))

    num_nodes = len(node_set)
    num_edges = 0
    for u, vs in stanford_data.items():
        num_edges += len(vs)

    degree_skew_list, wwr_list = [], []
    a, b = 0.6, 0.1
    c_list = [0.05, 0.1, 0.15, 0.2, 0.25]
    for c in tqdm_s(c_list):

        g = snap.GenRMat(num_nodes, num_edges, a, b, c, snap.TRnd())

        g_adjdict = {ni.GetId(): [] for ni in g.Nodes()}
        for ei in g.Edges():
            g_adjdict[ei.GetSrcNId()].append(ei.GetDstNId())

        g_degree = np.asarray(
            [ni.GetOutDeg() + ni.GetInDeg() for ni in g.Nodes()])
        degree_skew = skew(g_degree)
        degree_skew_list.append(degree_skew)

        orderings, wwr = slashburn(g_adjdict, k=1000)
        wwr_list.append(wwr)

        print("\nc: {}, ds: {}, wwr: {}".format(c, degree_skew, wwr))

    idx_to_degree = _get_idx_to_degree(to_followings, to_followers, num_nodes)
    stanford_degree_skew = skew(np.asarray([d
                                            for d in idx_to_degree.values()]))
    stanford_orderings, standford_wwr = slashburn(deepcopy(stanford_data),
                                                  k=1000)

    print("\n\n--- Result ---")
    print("\t".join(
        ["Graph (c or name)", "degree skewness", "Wing width ratio"]))
    for c, degree_skew, wwr in zip(c_list, degree_skew_list, wwr_list):
        print("\t".join(
            ["c-{}".format(c),
             str(round(degree_skew, 5)),
             str(round(wwr, 5))]))
    print("\t".join([
        "web-Stanford",
        str(round(stanford_degree_skew, 5)),
        str(round(standford_wwr, 5))
    ]))
Exemplo n.º 10
0
def random_node_id(Graph):
    """return a randome node ID of graph
    Args:
        Graph: 

    Return: 
    """
    Rnd = snap.TRnd(42)
    Rnd.Randomize()
    return Graph.GetRndNId(Rnd)
Exemplo n.º 11
0
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()
Exemplo n.º 12
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")
Exemplo n.º 13
0
def node_rewiring():
    GUn = transform_directed_to_undirected()
    # Node Rewiring
    Rnd = snap.TRnd()
    GRW = snap.GenRewire(GUn, 1000, Rnd)
    snap.PrintInfo(GRW, "Tweets Rewire Stats", "Tweets_Rewire-info.txt", False)

    f = open('Tweets_Rewire-info.txt', 'r')
    file_contents = f.read()
    print(file_contents)
    f.close()
Exemplo n.º 14
0
def gen_sw(args):
    """Generate a SW Graph"""

    for i in range(args.num_graphs):

        fp = np.random.uniform(0, 0.5)
        Rnd = snap.TRnd()
        Graph = snap.GenSmallWorld(args.num_vertices, 3, fp, Rnd)
        snap.SaveEdgeList(Graph, f'{args.data_loc}/SW/SW_{i}.edges')

        print(f"SW Graph {i} Generated and Saved")
Exemplo n.º 15
0
    def generate_watts_strogatz_model(self,
                                      num_nodes: int = 10,
                                      out_degree: int = None,
                                      rewire_prob: float = 0.5):
        if out_degree is None:
            # Generate a random out degree in [5, 20].
            out_degree = random.randint(5, 20)

        rnd = snap.TRnd(1, 0)
        graph = snap.GenSmallWorld(num_nodes, out_degree, rewire_prob, rnd)

        return graph
Exemplo n.º 16
0
def configuration_model():
    GUn = transform_directed_to_undirected()
    GUnDegSeqV = snap.TIntV()
    snap.GetDegSeqV(GUn, GUnDegSeqV)

    Rnd = snap.TRnd()
    GConfModel = snap.GenConfModel(GUnDegSeqV, Rnd)
    snap.PrintInfo(GConfModel, "Tweets ConfModel Stats",
                   "Tweets_ConfModel-info.txt", False)
    f = open('Tweets_ConfModel-info.txt', 'r')
    file_contents = f.read()
    print(file_contents)
    f.close()
Exemplo n.º 17
0
def runRobustnessTestRandomly(graph, rounds=30):
    graph = cloneGraph(graph)
    result = []
    rnd = snap.TRnd()
    rnd.Randomize()
    originalEdgesCnt = graph.GetEdges()
    for i in range(rounds):
        fractionRemoved = 1.0 - float(
            graph.GetEdges()) / float(originalEdgesCnt)
        result.append((fractionRemoved, snap.GetMxSccSz(graph)))
        for n in range(originalEdgesCnt / rounds):
            graph.DelEdge(graph.GetRndEId(rnd))
    return result
Exemplo n.º 18
0
def run(nodes_exp, edges_exp, InputModel, OutputType):
  
  '''
  Perform tests with specified exponent range
  '''

  if opt_verbose:
    print "Running results from %e to %e" % (min_nodes_exponent,
                                           max_nodes_exponent)

  Rnd = snap.TRnd()

  # Random number of nodes of degree i
  NNodes = 10**nodes_exp
  NEdges = 10**edges_exp
  
  if opt_deterministic:
    if opt_verbose:
      print "Deterministic mode, putting seed"
  else:
    if opt_verbose:
      print "Non-deterministic mode"
    Rnd.PutSeed(0)

  if opt_verbose: print "Using average degree of 10^%d" % avg_deg
    
  StartTime = clock()
    
  # User wants to re-generate graph, or no graph data available.
  if opt_verbose:
    print "Generating '%s %s' graph with %e nodes, %e edges..." % \
            (Type, g, NNodes, NEdges),
    sys.stdout.flush()
  Graph = generate_graph(NNodes, NEdges, InputModel, Rnd)
  if opt_verbose: print "done"

  if InputModel in ['rmat', 'rand_ngraph', 'syn_ngraph','syn_negraph']:
    TypeSrc = "ngraph"
  
  elif InputModel in ['sw', 'pref', 'rand_ungraph']:
    TypeSrc = "ungraph"
  
  elif InputModel in ['rand_neagraph', 'syn_neagraph']:
    TypeSrc = "neagraph"
  
  else:
    print "Unknown graph type: %s" % g
    sys.exit(1)

  convert_graph(Graph, TypeSrc, OutputType)
  print "-"*75
Exemplo n.º 19
0
def PlotRandomBFS(Graph, num_test=100):
    Rnd = snap.TRnd(42)
    Rnd.Randomize()
    num_out = []
    num_in = []
    for i in range(0, num_test):
        NodeId = Graph.GetRndNId(Rnd)
        BfsTreeOut = snap.GetBfsTree(Graph, NodeId, True, False)
        BfsTreeIn = snap.GetBfsTree(Graph, NodeId, False, True)
        num_out.append(np.log(BfsTreeOut.GetNodes()))
        num_in.append(np.log(BfsTreeIn.GetNodes()))
    num_out.sort()
    num_in.sort()
    return num_out, num_in
Exemplo n.º 20
0
def TestFracPath(Graph, num_test=1000):
    Rnd = snap.TRnd(42)
    Rnd.Randomize()
    count = 0
    i = 0
    while i < num_test:
        NodeId1 = Graph.GetRndNId(Rnd)
        NodeId2 = Graph.GetRndNId(Rnd)
        if (NodeId1 != NodeId2):
            Length = snap.GetShortPath(Graph, NodeId1, NodeId2, True)
            if (Length > 0):
                count += 1
            i += 1
    print(" fraction of reachable pairs", count / num_test)
Exemplo n.º 21
0
def ex5(graph):
    Rnd = snap.TRnd(42)
    Rnd.Randomize()
    start = graph.GetRndNId(Rnd)
    deptharray = []
    starttime = time.time()

    for i in range(0, 1000):
        Rnd.Randomize()
        start = graph.GetRndNId(Rnd)
        ID, depth = bfs(graph, start)
        deptharray.append(depth)
    timing = time.time() - starttime
    diameter = sum(deptharray) / len(deptharray)
    return timing, diameter
Exemplo n.º 22
0
def cascade(G,threshold,num_init_adopters,random_seed):
    q = Queue(maxsize = 0) 
    init_adopters = []
    count_nodes = 0
    for i in G.Nodes():
        count_nodes+=1
    node_is_B = [False] * count_nodes
    #get random nodes
    Rnd = snap.TRnd(random_seed)
    #we want to use same set of init adopters, we dont need  Rnd.Randomize()
    for i in range(0,num_init_adopters):
        nodeId = G.GetRndNId(Rnd)
        init_adopters.append(nodeId)
        node_is_B[nodeId] = True
    for NId in init_adopters:
        node = G.GetNI(NId)
        for node_fd_Id in node.GetOutEdges():
            if not node_is_B[node_fd_Id]:
                q.put((node_fd_Id,1))
    process_num=0
    while q.empty() is False:
        NId, num_ita = q.get()
        if node_is_B[NId]:
            continue
        node = G.GetNI(NId)
        neigh_total=0
        neigh_B=0
        for node_fd_Id in node.GetOutEdges():
            if node_fd_Id == NId:
                continue
            neigh_total+=1
            if node_is_B[node_fd_Id]:
                neigh_B+=1
        if neigh_B/neigh_total >= threshold:
            node_is_B[NId] = True
            for node_fd_Id in node.GetOutEdges():
                if not node_is_B[node_fd_Id]:
                    q.put((node_fd_Id,num_ita+1))
        #process_num+=1
        #if process_num%5000 ==0:
            #print("process "+str(process_num))
    count_B = 0
    for is_B in node_is_B:
        if is_B:
            count_B+=1
    #if (count_B-num_init_adopters) != 0 :
        #print((threshold,count_B,num_init_adopters))
    return (count_B-num_init_adopters)*100/(count_nodes-num_init_adopters)
Exemplo n.º 23
0
def q2_3_util(dataset_name):
        # G = load_graph("email")
    G = load_graph(dataset_name)
    MxWcc = snap.GetMxWcc(G)
    total_size = G.GetNodes()
    wcc_size = MxWcc.GetNodes()
    disconnected_size = total_size - wcc_size
    print 'Total size: ', total_size
    print 'WCC size: ', wcc_size
    print 'DISCONNECTED: ', disconnected_size
    Rnd = snap.TRnd(42)
    Rnd.Randomize()
    MxScc = snap.GetMxScc(G)
    scc_size = MxScc.GetNodes()
    number_of_trials = 1
    scc_plus_out = 0
    scc_plus_in = 0
    out_size = 0
    in_size = 0
    tendrils_plus_tubes = 0
    for i in xrange(number_of_trials):
        NId = MxScc.GetRndNId(Rnd)
        # print 'Random node id', NId
        outward_set = set()
        BfsTree = snap.GetBfsTree(G, NId, True, False)
        for EI in BfsTree.Edges():
            outward_set.add(EI.GetDstNId())
        scc_plus_out = max(scc_plus_out, len(outward_set))
        out_size = max( out_size, scc_plus_out - scc_size)
        #
        inward_set = set()
        BfsTree = snap.GetBfsTree(G, NId, False, True)
        for EI in BfsTree.Edges():
            inward_set.add(EI.GetDstNId())
        scc_plus_in = max(scc_plus_in, len(inward_set))
        in_size = max(in_size, scc_plus_in - scc_size)
        tendrils_plus_tubes = max(tendrils_plus_tubes, wcc_size - in_size - out_size)

    print 'IN: ', in_size
    print 'scc_size', scc_size
    print 'scc + out: ', scc_plus_out
    print 'OUT: ', out_size
    print 'scc + in: ', scc_plus_in
    print 'TENDRILS + TUBES', tendrils_plus_tubes
    print '------------------'
Exemplo n.º 24
0
def q2_4_utils(dataset_name):
    G = load_graph(dataset_name)
    Rnd = snap.TRnd(42)
    Rnd.Randomize()
    count = 0
    positive_count = 0
    negative_count = 0
    while count < 1000:
        NId_src = G.GetRndNId(Rnd)
        NId_dst = G.GetRndNId(Rnd)
        if NId_src != NId_dst:
            if snap.GetShortPath(G, NId_src, NId_dst, True) > 0:
                positive_count = positive_count + 1
            else:
                negative_count = negative_count + 1
        count = count + 1
            # print (snap.GetShortPath(G, NId_src, NId_dst))
    print 'positive_count', positive_count
    print 'negative_count', negative_count
Exemplo n.º 25
0
def analyze(graph):

    n = graph.GetNodes()
    m = graph.GetEdges()

    maxSCCsize = snap.GetMxSccSz(graph)
    maxWCCsize = snap.GetMxWccSz(graph)
    avgDegree = (m * float(2)) / n

    # estimate power law exponent
    degs = []
    degCounts = []
    DegToCntV = snap.TIntPrV()
    snap.GetDegCnt(graph, DegToCntV)
    for item in DegToCntV:
        degs.append(item.GetVal1())
        degCounts.append(item.GetVal2())
    xMin = min(degs) - 0.5
    m = graph.GetNodes()
    alphaMLLE = 1 + (m / (sum([np.log(i / xMin) * degCounts[degs.index(i)] for i in degs])))

    # erdos-renyi clustering coefficient
    graphER = snap.GenRndGnm(snap.PUNGraph, n, m)
    avgClustCoeffER = snap.GetClustCf(graphER, -1)

    # average shortest path
    graphWCC = snap.GetMxWcc(graph)
    avgClustCoeff = snap.GetClustCf(graphWCC, -1)
    numSamples = min(graphWCC.GetNodes(), 617) # all nodes or sample size
    Rnd = snap.TRnd(42)
    Rnd.Randomize()
    shortPathList = []
    for i in xrange(numSamples):
        s = graphWCC.GetRndNId(Rnd)
        NIdToDistH = snap.TIntH()
        snap.GetShortPath(graphWCC, s, NIdToDistH)
        for item in NIdToDistH:
            shortPathList.append(NIdToDistH[item])
    avgShortPath = np.mean(shortPathList)

    return avgClustCoeff, maxSCCsize, maxWCCsize, avgDegree, alphaMLLE, avgClustCoeffER, avgShortPath
def make_examples_simple(data_dir, author_ids, affiliation_ids, n_authors, negative_samples):
    graph = snap.LoadEdgeList(snap.PUNGraph, data_dir + 'graph.txt', 0, 1)
    new_edges = defaultdict(dict)
    with open(data_dir + 'new_edges.txt', 'r') as f:
        line = f.readline()
        while line:
            u, b = map(int, line.split())
            new_edges[u][b] = 1
            line = f.readline()
    
    # Just use all authors in new_edges
    examples = defaultdict(dict)
    Rnd = snap.TRnd(42)
    Rnd.Randomize()
    authors = []
    #for i in range(n_authors):
    #    authors.append(graph.GetRndNId(Rnd))
    # If just add in nodes from new_edges, there is KeyError
    for u in new_edges.keys():
        authors.append(u)
    
    print(len(authors))
    for u in authors:
        examples[u] = new_edges[u]
        for i in range(negative_samples):
            b = random.choice(affiliation_ids)
            examples[u][b] = 0

    p, n = 0, 0
    for u in examples:
        for b in examples[u]:
            p += examples[u][b]
            n += 1 - examples[u][b]

    print("Positive: ", p)
    print("Negative: ", n)
    print("Data skew: ", p / (p + n) )
    print("Sampling rate: ", negative_samples / len(affiliation_ids))
    print("writing examples...")
    util.write_json(examples, data_dir + 'oag_examples_simple.json')
Exemplo n.º 27
0
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.
    """
    ############################################################################
    # TODO: Your code here!
    Rnd = snap.TRnd(42)
    Rnd.Randomize()
    counter = 0
    while counter <= M:
        Nid = Graph.GetRndNId(Rnd)
        Mid = Graph.GetRndNId(Rnd)
        if not Graph.IsEdge(Nid, Mid):
            Graph.AddEdge(Nid, Mid)
            counter += 1
    ############################################################################
    return Graph
Exemplo n.º 28
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 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
Exemplo n.º 30
0
def make_subgraphs(num_subgraphs, radii, in_dir, out_dir):
    graphs = {}
    for r in radii.keys():
        graph_dir = os.path.join(in_dir, f"adj_r_{r}")
        in_data = load_graph(graph_dir)
        graphs[r] = in_data
        # cells_ref = in_data["cells"]

    rnd = snap.TRnd(42)
    rnd.Randomize()
    graph_ref = graphs[min(radii.keys())]

    for i in range(num_subgraphs):
        # ref = random.choice(cells_ref)
        while True:
            try:
                ref = graph_ref["cells"][graph_ref["graph"].GetRndNId(rnd)]
                for r, graph_data in graphs.items():
                    hop = radii[r]
                    graph = graph_data["graph"]
                    cell_map = graph_data["cell_map"]
                    cells = graph_data["cells"]
                    cell_pos = graph_data["cell_pos"]

                    node = cell_map[ref]
                    subgraph = get_egonet(graph, node, hop)
                    nodelist, pos, z = get_annotations(subgraph, cells,
                                                       cell_pos)

                    os.makedirs(out_dir, exist_ok=True)
                    out_path = os.path.join(out_dir, f"sub_{i}_r_{r}.svg")
                    title = f"{r} μm Radius, {hop}-Hop\nCell {ref}"
                    plot_egonet(subgraph, nodelist, pos, z, title, out_path)
                break
            except ValueError:
                continue