Ejemplo n.º 1
0
def calcClusteringCoefficientSingleNode(Node, Graph):
    """
    :param - Node: node from snap.PUNGraph object. Graph.Nodes() will give an
                   iterable of nodes in a graph
    :param - Graph: snap.PUNGraph object representing an undirected graph

    return type: float
    returns: local clustering coeffient of Node
    """
    ############################################################################
    # TODO: Your code here!
    # C = 0.0
    ki = Node.GetDeg()
    if ki < 2:
        return 0
    else:
        Nbrs = snap.TIntV()
        common_neighbours = 0
        for Id in Node.GetOutEdges():
            common_neighbour = snap.GetCmnNbrs(Graph, Node.GetId(), Id, Nbrs)
            common_neighbours += common_neighbour
        # ei is number of edges between neighbours,
        # divide by 2, because each pair of connected neighbours are counted twice
        ei = common_neighbours / 2
        # c = 2ei/ki(ki-1)
        C = 2 * ei / (ki * (ki - 1))
    ############################################################################
    return C
Ejemplo n.º 2
0
def getCampaign_folded(G, legislator_node):
    '''
    For a campaign network and node id for legislators, return an one-mode projection of campaign graphs
    '''
    G_Campaign_folded = snap.TUNGraph.New()

    for i in range(len(legislator_node)):
        for j in range(i + 1, len(legislator_node)):
            Nbrs = snap.TIntV()
            if snap.GetCmnNbrs(G, legislator_node[i], legislator_node[j]) != 0:
                if G_Campaign_folded.IsNode(legislator_node[i]) == False:
                    G_Campaign_folded.AddNode(legislator_node[i])
                if G_Campaign_folded.IsNode(legislator_node[j]) == False:
                    G_Campaign_folded.AddNode(legislator_node[j])
                if G_Campaign_folded.IsEdge(legislator_node[i],
                                            legislator_node[j]) == False:
                    G_Campaign_folded.AddEdge(legislator_node[i],
                                              legislator_node[j])
            else:
                if G_Campaign_folded.IsNode(legislator_node[i]) == False:
                    G_Campaign_folded.AddNode(legislator_node[i])
                if G_Campaign_folded.IsNode(legislator_node[j]) == False:
                    G_Campaign_folded.AddNode(legislator_node[j])

    return G_Campaign_folded
def get_common_neighbors(G, n1, n2):
    deleted = False
    if G.IsEdge(n1, n2):
        G.DelEdge(n1, n2)
        deleted = True
    result = snap.GetCmnNbrs(G, n1, n2)
    if deleted: G.AddEdge(n1, n2)
    return result
Ejemplo n.º 4
0
def gen_G_subgraph(component, D, Pi_minus, Pi_exo, V_exo, theta2):
    """ 
    Returns a pairwise-stable network for nodes in component, via myopic best-
    response dynamics. This subnetwork is pairwise-stable taking as given the
    links in the rest of the network. Initial network for best-response dynamics
    is the opportunity graph. 

    NB: This function is specific to the joint surplus used in our simulations.
    
    component = component of D for which we want a pairwise-stable subnetwork.
    D, Pi_minus, Pi_exo = outputs of gen_D().
    V_exo = 'exogenous' part of joint surplus (output of gen_V_exo).
    theta2 = transitivity parameter (theta[2]).
    """
    stable = False
    meetings_without_deviations = 0

    D_subgraph = snap.GetSubGraph(D, component)

    # Start initial network on Pi, without robustly absent potential links.
    G = snap.GetSubGraph(Pi_minus, component)

    # For each node pair (i,j) linked in Pi_exo (i.e. their links are robust),
    # with either i or j in component, add their link to G.  Result is the
    # subgraph of Pi_minus on an augmented component of D.
    for i in component:
        for j in Pi_exo.GetNI(i).GetOutEdges():
            if not G.IsNode(j): G.AddNode(j)
            G.AddEdge(i, j)

    while not stable:
        # Need only iterate through links of D, since all other links are
        # robust.
        for edge in D_subgraph.Edges():
            # Iterate deterministically through default edge order order. Add or
            # remove link in G according to myopic best-respnose dynamics. If we
            # cycle back to any edge with no changes to the network, conclude
            # it's pairwise stable.
            i = min(edge.GetSrcNId(), edge.GetDstNId())
            j = max(edge.GetSrcNId(), edge.GetDstNId())
            cfriend = snap.GetCmnNbrs(G, i, j) > 0
            if V_exo[i, j] + theta2 * cfriend > 0:  # specific to model of V
                if G.IsEdge(i, j):
                    meetings_without_deviations += 1
                else:
                    G.AddEdge(i, j)
                    meetings_without_deviations = 0
            else:
                if G.IsEdge(i, j):
                    G.DelEdge(i, j)
                    meetings_without_deviations = 0
                else:
                    meetings_without_deviations += 1

        if meetings_without_deviations > D_subgraph.GetEdges():
            stable = True

    return snap.GetSubGraph(G, component)
def get_2_hops(G, n1, n2, directed=False):
    deleted = False
    if G.IsEdge(n1, n2):
        G.DelEdge(n1, n2)
        deleted = True
    result = 0
    if (n1 >= 18630353 and n1 < 31097109) and (n2 < 18630353
                                               or n2 >= 31097109):
        b_neighbors = snap.TIntV()
        snap.GetNodesAtHop(G, n1, 1, b_neighbors, directed)
        for n in b_neighbors:
            result += snap.GetCmnNbrs(G, n, n2)
    elif (n2 >= 18630353 and n2 < 31097109) and (n1 < 18630353
                                                 or n1 >= 31097109):
        b_neighbors = snap.TIntV()
        snap.GetNodesAtHop(G, n2, 1, b_neighbors, directed)
        for n in b_neighbors:
            result += snap.GetCmnNbrs(G, n, n1)
    if deleted: G.AddEdge(n1, n2)
    return result
def jaccard_coefficient(G, n1, n2):
    deleted = False
    if G.IsEdge(n1, n2):
        G.DelEdge(n1, n2)
        deleted = True
    common_neighbors = snap.GetCmnNbrs(G, n1, n2)
    total_neighbors = G.GetNI(n1).GetDeg() + G.GetNI(n2).GetDeg()
    result = 0.0 if total_neighbors == 0 else float(
        common_neighbors) / total_neighbors
    if deleted: G.AddEdge(n1, n2)
    return result
Ejemplo n.º 7
0
def getCoSponsor(G, bill_node,legislator_node):
    '''
    returns the one mode projection graph of co-sponsorship

    '''
    CoSponsor = snap.TUNGraph.New()

    print len(legislator_node)
    for i in range(len(legislator_node)):
        for j in range(i+1,len(legislator_node)):
            Nbrs = snap.TIntV()
            if snap.GetCmnNbrs(G,legislator_node['NId'][i],legislator_node['NId'][j]) != 0:
                if CoSponsor.IsNode(legislator_node['NId'][i]) == False:
                    CoSponsor.AddNode(legislator_node['NId'][i])
                if CoSponsor.IsNode(legislator_node['NId'][j]) == False:
                    CoSponsor.AddNode(legislator_node['NId'][j])
                if CoSponsor.IsEdge(legislator_node['NId'][i],legislator_node['NId'][j]) == False:
                    CoSponsor.AddEdge(legislator_node['NId'][i],legislator_node['NId'][j]) 

    return CoSponsor
def get_number_of_shared_neighbors(G, n1, n2):
    return snap.GetCmnNbrs(G, n1, n2)
Ejemplo n.º 9
0
    print "Bill network max node degree is %d for legislators, out of %d pool" % (
        max(cand), len(cand))
    print "Bill network max node degree is %d for bills, out of %d pool" % (
        max(com), len(com))

    ## Fold G_cand to create a one-node projection onto candidate nodes

    H_bill = snap.TUNGraph.New()

    for i in G_bill.Nodes():
        for j in G_bill.Nodes():
            if (i.GetId() < j.GetId() and j.GetId() <
                    10000):  #10000 is the upper limit for candidate nodes
                NbrV = snap.TIntV()
                Num = snap.GetCmnNbrs(G_bill, i.GetId(), j.GetId())
#Num = snap.GetLen2Paths(G_bill, i.GetId(), j.GetId(), NbrV)
            if Num != 0:
                if H_bill.IsNode(i.GetId()) == False:
                    H_bill.AddNode(i.GetId())
                if H_bill.IsNode(j.GetId()) == False:
                    H_bill.AddNode(j.GetId())
                if H_bill.IsEdge(i.GetId(), j.GetId()) == False:
                    H_bill.AddEdge(i.GetId(), j.GetId())

    print "One-node Projected Graph Node count total: %d" % (H_bill.GetNodes())

    print "One-node Projected Edge count total: %d" % (H_bill.GetEdges())

    GraphClustCoeff = snap.GetClustCf(H_bill, -1)
    print "Bill Network Clustering coefficient: %f" % GraphClustCoeff
Ejemplo n.º 10
0
n = len(nodes)
n2 = n * n

denom = n * (n2 - 1)

corr_pe = 1 - (float(6 * sum_pe) / float(denom))
corr_ed = 1 - (float(6 * sum_ed) / float(denom))
corr_dp = 1 - (float(6 * sum_dp) / float(denom))

print "The relation of pAgeRank with respect to eigen vector = ", corr_pe
print "The relation of eigen vector with respect to deg centr= ", corr_ed
print "The relation of Deg Cent with respect to Page Rank is ", corr_dp

high_sim = 0
node1 = 0
node2 = 0
k = 0
for i in ugraph.Nodes():
    l = 0
    for j in ugraph.Nodes():
        if (k == l):
            continue
        com = snap.GetCmnNbrs(ugraph, nodes[k], nodes[l])
        sim = float(com) / (i.GetOutDeg() + j.GetOutDeg() - com)
        if (sim > high_sim):
            high_sim = sim
            node1 = i
            node2 = j
        l += 1
    k += 1
print "Most similar nodes are " + node1 + " and " + node2
Ejemplo n.º 11
0
    def compute_attri(x):
        NId_i = int(x['node_i'])
        NId_j = int(x['node_j'])
        if G_Campaign_folded.IsNode(NId_i) and G_Campaign_folded.IsNode(NId_j):
            node_i_contribution_sum = 0.0
            node_j_contribution_sum = 0.0
            neighbors_i = []
            neighbors_j = []

            clustering_cf_i = NIdCCfH[NId_i]

            clustering_cf_j = NIdCCfH[NId_j]

            CommNeighbors = snap.GetCmnNbrs(G_Campaign, NId_i, NId_j)
            NeighborsUnion = float(
                len(
                    list(set().union(getNeighbors(NId_i, G_Campaign),
                                     getNeighbors(NId_j, G_Campaign)))))

            FromSameCluster = 0
            if NId_i in cluster_0 and NId_j in cluster_0:
                FromSameCluster = 1
            if NId_i in cluster_1 and NId_j in cluster_1:
                FromSameCluster = 1
            '''
            Nbrs = snap.TIntV()
            snap.GetCmnNbrs(G_Campaign, NId_i,NId_j, Nbrs)
            for NId in Nbrs:
                eid_i = G_Campaign.GetEId(NId,NId_i)
                eid_j = G_Campaign.GetEId(NId,NId_j)
                neighbors_i.append(NId)
                neighbors_j.append(NId)
                node_i_contribution_sum += G_Campaign.GetIntAttrDatE(eid_i, 'TRANSACTION_AMT')              
                node_j_contribution_sum += G_Campaign.GetIntAttrDatE(eid_j, 'TRANSACTION_AMT')
            '''
            result = {
                'Degree_Diff':
                abs(in_deg[NId_i] - in_deg[NId_j]),
                'Union_of_Neighbors':
                NeighborsUnion,
                'CommNeighbors':
                CommNeighbors,
                'Clustering_Coeff_Diff':
                abs(clustering_cf_i - clustering_cf_j),
                'Clustering_Coeff_Sum':
                clustering_cf_i + clustering_cf_j,
                'Clustering_Coeff_Avg':
                clustering_cf_i + clustering_cf_j / 2.0,
                #'Contribution_Diff': abs(node_i_contribution_sum - node_j_contribution_sum),
                #'Contribution_Sum': node_i_contribution_sum + node_j_contribution_sum,
                'Jaccard':
                CommNeighbors * 1.0 / NeighborsUnion,
                'Shortest_Dist':
                snap.GetShortPath(G_Campaign, NId_i, NId_j),
                'Deg_Centrality_Diff':
                abs(node_centrality[NId_i] - node_centrality[NId_j]),
                'FromSameCluster':
                FromSameCluster
            }
        else:
            result = {}
        return pd.Series(result, name="Attri")