예제 #1
0
    def test_subgraph_centrality_big_graph(self):
        g199 = nx.complete_graph(199)
        g200 = nx.complete_graph(200)

        comm199 = nx.subgraph_centrality(g199)
        comm199_exp = nx.subgraph_centrality_exp(g199)

        comm200 = nx.subgraph_centrality(g200)
        comm200_exp = nx.subgraph_centrality_exp(g200)
예제 #2
0
    def test_subgraph_centrality_big_graph(self):
        g199 = nx.complete_graph(199)
        g200 = nx.complete_graph(200)

        comm199 = nx.subgraph_centrality(g199)
        comm199_exp = nx.subgraph_centrality_exp(g199)

        comm200 = nx.subgraph_centrality(g200)
        comm200_exp = nx.subgraph_centrality_exp(g200)
예제 #3
0
def subgraph_centraility(G, num_rounds, num_seeds):
    centrality = nx.subgraph_centrality(G)
    top_nodes = sorted(centrality.items(),
                       key=operator.itemgetter(1),
                       reverse=True)[:num_seeds]
    highest_nodes = [i[0] for i in top_nodes]
    return (highest_nodes * num_rounds)
def agregar_centralidad(G, criterio='degree', max_iter=100, tol=1e-3):
    if criterio == 'degree':
        nodes = list(G.nodes())
        degree = list(dict(nx.degree(G)).values())
        return nodes, degree
    if criterio == 'eigen':
        nodes = list(G.nodes())
        eigen = list(
            dict(nx.eigenvector_centrality(G, max_iter=max_iter,
                                           tol=tol)).values())
        return nodes, eigen
    if criterio == 'sub':
        nodes = list(G.nodes())
        sub = list(dict(nx.subgraph_centrality(G)).values())
        return nodes, sub
    if criterio == 'bet':
        nodes = list(G.nodes())
        bet = list(dict(nx.betweenness_centrality(G)).values())
        return nodes, bet
    if criterio == 'flow':
        nodes = list(G.nodes())
        flow = list(dict(nx.current_flow_betweenness_centrality(G)).values())
        return nodes, flow
    if criterio == 'random':
        nodes = list(G.nodes())
        value = random.choice(nodes)
        return value, nodes
예제 #5
0
def rank_centrality(top_k_words, top_k, word_in_file):
    for i, cluster in enumerate(top_k):
        cluster = np.array(cluster)

        subgraph = calc_coo_matrix(top_k_words[i], word_in_file)
        G = nx.from_numpy_matrix(subgraph)
        sc = nx.subgraph_centrality(G)

        ind = np.argsort([sc[node]
                          for node in sorted(sc)])[-10:][::-1].astype(int)

        top_k_words[i] = np.array(top_k_words[i])[ind]
    return top_k_words
예제 #6
0
파일: TC2.py 프로젝트: helimaga/Redes2018
def RemoveNodes(RED, method):
    # Función que remueve los nodos.
    red = RED.copy()

    print('\n', method)
    x = []
    y = []
    N0 = red.number_of_nodes()
    print('Cantidad inicial de nodos de la red %s:\t%d' % (s, N0))
    giant = max(nx.connected_component_subgraphs(red), key=len)
    largest_component = giant.number_of_nodes()

    # Se remueven los nodos según el método:
    while largest_component > 1:
        if method == 'Random':
            Node = np.random.choice(list(red.nodes))
        elif method == 'Degree':
            D = dict(nx.degree_centrality(red))
            Node = max(D, key=D.get)
        elif method == 'Eigenvector':
            D = dict(nx.eigenvector_centrality(red, tol=1e-03))
            Node = max(D, key=D.get)
        elif method == 'Subgraph':
            D = dict(nx.subgraph_centrality(red))
            Node = max(D, key=D.get)
        elif method == 'Shortest path':
            D = dict(nx.betweenness_centrality(red))
            Node = max(D, key=D.get)
        elif method == 'Current flow':
            D = dict(nx.current_flow_betweenness_centrality(red))
            Node = max(D, key=D.get)

        red.remove_node(Node)
        giant = max(nx.connected_component_subgraphs(red), key=len)
        largest_component = giant.number_of_nodes()
        N = red.number_of_nodes()
        print('\rNodos restantes:\t%4d' % (N), end='')
        x.append(1 - N / N0)
        y.append(largest_component / N)

    np.save(path + '%s-x_%s' % (s, method), x)
    np.save(path + '%s-y_%s' % (s, method), y)

    plt.plot(x, y, label=method)
    return
예제 #7
0
파일: capacities.py 프로젝트: fnss/fnss
def set_capacities_communicability_gravity(topology, capacities,
                                           capacity_unit='Mbps'):
    """
    Set link capacities proportionally to the product of the communicability
    centralities of the two end-points of the link

    Parameters
    ----------
    topology : Topology
        The topology to which link capacities will be set
    capacities : list
        A list of all possible capacity values
    capacity_unit : str, optional
        The unit in which capacity value is expressed (e.g. Mbps, Gbps etc..)
    """
    if LooseVersion(nx.__version__) < LooseVersion("2.0"):
        centrality = nx.communicability_centrality(topology)
    else:
        centrality = nx.subgraph_centrality(topology)
    _set_capacities_gravity(topology, capacities, centrality, capacity_unit)
예제 #8
0
def set_capacities_communicability_gravity(topology,
                                           capacities,
                                           capacity_unit='Mbps'):
    """
    Set link capacities proportionally to the product of the communicability
    centralities of the two end-points of the link

    Parameters
    ----------
    topology : Topology
        The topology to which link capacities will be set
    capacities : list
        A list of all possible capacity values
    capacity_unit : str, optional
        The unit in which capacity value is expressed (e.g. Mbps, Gbps etc..)
    """
    if LooseVersion(nx.__version__) < LooseVersion("2.0"):
        centrality = nx.communicability_centrality(topology)
    else:
        centrality = nx.subgraph_centrality(topology)
    _set_capacities_gravity(topology, capacities, centrality, capacity_unit)
예제 #9
0
def test_subgraph_centrality():
    ''' Check subgraph centrality with networkx implementation '''
    num_nodes = 5
    edge_list = [(0, 1), (0, 2), (0, 3), (1, 3), (2, 3), (2, 4), (3, 4)]

    # this test requires networkx as backend
    nngt.use_backend("networkx")

    g = nngt.Graph(num_nodes, directed=False)
    g.new_edges(edge_list)

    # test full centralities
    import networkx as nx

    sc_nx = nx.subgraph_centrality(g.graph)
    sc_nx = np.array([sc_nx[i] for i in range(num_nodes)])

    sc_nngt = nngt.analysis.subgraph_centrality(g,
                                                weights=False,
                                                normalize=False)

    assert np.all(np.isclose(sc_nx, sc_nngt))

    # test max_centrality
    sc_nngt = nngt.analysis.subgraph_centrality(g,
                                                weights=False,
                                                normalize="max_centrality")

    assert np.all(np.isclose(sc_nx / sc_nx.max(), sc_nngt))

    # test subpart
    sc_nngt = nngt.analysis.subgraph_centrality(g,
                                                weights=False,
                                                normalize=False,
                                                nodes=[0, 1])

    assert np.all(np.isclose(sc_nx[:2], sc_nngt))
예제 #10
0
def subg(g):
    g = g.to_undirected()
    return nx.subgraph_centrality(g)
예제 #11
0
qposts.loc[:, 'firsttag'] = qposts['TagList'].apply(lambda x: x[0])
# topics are the tags most frequently occurring as first tag
firstagdf = qposts['firsttag'].value_counts()

### using graphs
datag = data.copy()
datag.loc[:, 'forgraph'] = datag.apply(lambda x: (x['index'], x['columns'], {
    'weight': x['freq']
}),
                                       axis=1)

G = nx.Graph()
G.add_edges_from(datag['forgraph'].tolist())

### MEASURE OF CENTER IN SUBGRAPHS - topics are the most central
centr_subgraph = nx.subgraph_centrality(G)
centr_subgraphdf = pd.DataFrame({
    'tag':
    list(centr_subgraph.keys()),
    'subgraphcentrality':
    list(centr_subgraph.values())
})
centr_subgraphdf = centr_subgraphdf.sort_values(by='subgraphcentrality',
                                                ascending=False)

### MEASURE OF CENTER IN GRAPH - topics are the most central
centrality = nx.degree_centrality(G)
centrdf = pd.DataFrame({
    'tag': list(centrality.keys()),
    'centrality': list(centrality.values())
})
예제 #12
0
def drawGraph(G, pos, a, labels):

    print(globalLabSize, "glob")
    #Changing G for threshold here

    #Check filter metric
    if (globalOptionsMet4 == "Default"):
        G = G

    if (globalOptionsMet4 == "Degree"):
        displayedNodes = []
        nx.set_node_attributes(G,
                               values=nx.degree_centrality(G),
                               name='degree')
        for node, data in G.nodes(data=True):
            if (data['degree'] > threshold):
                displayedNodes.append(node)
        G = G.subgraph(displayedNodes)

    if (globalOptionsMet4 == "Between Centrality"):
        displayedNodes = []
        # Metrics computing
        betweenCentralities = nx.betweenness_centrality(G)
        # Add metrics as params of the nodes
        nx.set_node_attributes(G,
                               values=betweenCentralities,
                               name='betweenCentrality')

        # iterate trough nodes
        for node, data in G.nodes(data=True):
            if (data['betweenCentrality'] > threshold):
                displayedNodes.append(node)

        G = G.subgraph(displayedNodes)

    if (globalOptionsMet4 == "Load Centrality"):
        displayedNodes = []
        # Metrics computing
        loadCentralities = nx.load_centrality(G)
        # Add metrics as params of the nodes
        nx.set_node_attributes(G,
                               values=loadCentralities,
                               name='loadCentrality')

        # iterate trough nodes
        for node, data in G.nodes(data=True):
            if (data['loadCentrality'] > threshold):
                displayedNodes.append(node)

        G = G.subgraph(displayedNodes)

    if (globalOptionsMet4 == "Subgraph Centrality"):
        displayedNodes = []
        # Metrics computing
        subgraphCentralities = nx.subgraph_centrality(G)
        # Add metrics as params of the nodes
        nx.set_node_attributes(G,
                               values=subgraphCentralities,
                               name='subgraphCentrality')

        # iterate trough nodes
        for node, data in G.nodes(data=True):
            if (data['subgraphCentrality'] > threshold):
                displayedNodes.append(node)

        G = G.subgraph(displayedNodes)

    #Choosing size,  the size list will be defined here for the rest of the function
    sizeM = maxSize
    sizes = []
    if (globalOptionsMet3 == "Default"):
        for node, data in G.nodes(data=True):
            sizes.append(sizeM)
    if (globalOptionsMet3 == "Degree"):
        degrees = nx.degree_centrality(G)
        # Add metrics as params of the nodes
        nx.set_node_attributes(G, values=degrees, name='degree')
        # minmax
        minDeg = min(degrees.values())
        maxDeg = max(degrees.values())
        #loop trough nodes
        for node, data in G.nodes(data=True):
            sizes.append(
                (normalizeSize(data['degree'], maxDeg, minDeg, sizeM) + 5))

    if (globalOptionsMet3 == "Between Centrality"):
        # Metrics computing
        betweenCentralities = nx.betweenness_centrality(G)
        # Add metrics as params of the nodes
        nx.set_node_attributes(G,
                               values=betweenCentralities,
                               name='betweenCentrality')
        # minmax
        minBetween = min(betweenCentralities.values())
        maxBetween = max(betweenCentralities.values())
        #loop trough nodes
        for node, data in G.nodes(data=True):
            sizes.append((normalizeSize(data['betweenCentrality'], maxBetween,
                                        minBetween, sizeM) + 5))

    if (globalOptionsMet3 == "Load Centrality"):
        # Metrics computing
        loadCentralities = nx.load_centrality(G)
        # Add metrics as params of the nodes
        nx.set_node_attributes(G,
                               values=loadCentralities,
                               name='loadCentrality')
        # minmax
        minLoad = min(loadCentralities.values())
        maxLoad = max(loadCentralities.values())
        #loop trough nodes
        for node, data in G.nodes(data=True):
            sizes.append((normalizeSize(data['loadCentrality'], maxLoad,
                                        minLoad, sizeM) + 5))

    if (globalOptionsMet3 == "Subgraph Centrality"):
        # Metrics computing
        subgraphCentralities = nx.subgraph_centrality(G)
        # Add metrics as params of the nodes
        nx.set_node_attributes(G,
                               values=subgraphCentralities,
                               name='subgraphCentrality')
        # minmax
        minSub = min(subgraphCentralities.values())
        maxSub = max(subgraphCentralities.values())
        #loop trough nodes
        for node, data in G.nodes(data=True):
            sizes.append((normalizeSize(data['subgraphCentrality'], maxSub,
                                        minSub, sizeM) + 5))

    #Choosing cmap for colors
    cmapChosen = plt.cm.viridis
    if (cmap1 == "Viridis"):
        cmapChosen = plt.cm.viridis
    if (cmap1 == "Magma"):
        cmapChosen = plt.cm.magma
    if (cmap1 == "Plasma"):
        cmapChosen = plt.cm.plasma
    if (cmap1 == "Blues"):
        cmapChosen = plt.cm.Blues
    if (cmap1 == "Purples"):
        cmapChosen = plt.cm.Purples
    if (cmap1 == "Reds"):
        cmapChosen = plt.cm.Reds
    if (cmap1 == "Greens"):
        cmapChosen = plt.cm.Greens
    if (cmap1 == "YlOrRd"):
        cmapChosen = plt.cm.YlOrRd

    #drawing
    if (globalOptionsMet2 == "Default"):
        labelDic = nx.get_node_attributes(G, 'label')
        nx.draw_networkx_nodes(G,
                               pos=pos,
                               ax=a,
                               node_color=range(len(G)),
                               cmap=cmapChosen,
                               node_size=sizes)
        nx.draw_networkx_edges(G,
                               pos,
                               edge_color=globalEdgeCol,
                               style=globalEdgeType,
                               alpha=globalEdgeOpacity,
                               ax=a)
        if (labels):
            nx.draw_networkx_labels(G,
                                    pos,
                                    font_size=globalLabSize,
                                    ax=a,
                                    font_color=globalLabelCol)
    if (globalOptionsMet2 == "Communities"):
        cmapUsed = ""
        if (cmap1 == "Pale"):
            cmapUsed = ListedColormap(
                palettable.colorbrewer.qualitative.Set3_12.mpl_colors,
                N=len(G))
        if (cmap1 == "Bright"):
            cmapUsed = ListedColormap(
                palettable.colorbrewer.qualitative.Set1_9.mpl_colors, N=len(G))

        partition = community.best_partition(G)
        labelSet = nx.get_node_attributes(G, 'label')
        size = float(len(set(partition.values())))
        count = 0.
        for com in set(partition.values()):
            count = count + 1.
            list_nodes = [
                nodes for nodes in partition.keys() if partition[nodes] == com
            ]
            nx.draw_networkx_nodes(G,
                                   pos,
                                   list_nodes,
                                   label=labelSet,
                                   node_color=cmapUsed(com),
                                   ax=a,
                                   node_size=sizes)
        nx.draw_networkx_edges(G,
                               pos,
                               ax=a,
                               edge_color=globalEdgeCol,
                               style=globalEdgeType,
                               alpha=globalEdgeOpacity)
        if (labels):
            nx.draw_networkx_labels(G,
                                    pos,
                                    ax=a,
                                    font_size=globalLabSize,
                                    font_color=globalLabelCol)
    if (globalOptionsMet2 == "Degree"):
        # Metrics computing
        degrees = nx.degree_centrality(G)
        # Add metrics as params of the nodes
        nx.set_node_attributes(G, values=degrees, name='degree')

        # minmax
        minDeg = min(degrees.values())
        maxDeg = max(degrees.values())

        colDeg = []

        # Set the colors that could be used next
        for node, data in G.nodes(data=True):
            colDeg.append(normalize(data['degree'], maxDeg, minDeg))

        nx.draw_networkx_nodes(G,
                               pos=pos,
                               vmax=1,
                               vmin=0,
                               cmap=cmapChosen,
                               with_labels=labels,
                               node_size=sizes,
                               node_color=colDeg,
                               ax=a)
        nx.draw_networkx_edges(G,
                               pos,
                               edge_color=globalEdgeCol,
                               style=globalEdgeType,
                               alpha=globalEdgeOpacity,
                               ax=a)
        if (labels):
            nx.draw_networkx_labels(G,
                                    pos,
                                    font_size=globalLabSize,
                                    ax=a,
                                    font_color=globalLabelCol)

    if (globalOptionsMet2 == "Between Centrality"):
        # Metrics computing
        betweenCentralities = nx.betweenness_centrality(G)

        # Add metrics as params of the nodes
        nx.set_node_attributes(G,
                               values=betweenCentralities,
                               name='betweenCentrality')

        # minmax
        minBetween = min(betweenCentralities.values())
        maxBetween = max(betweenCentralities.values())

        colBetween = []

        # Set the colors that could be used next
        for node, data in G.nodes(data=True):
            colBetween.append(
                normalize(data['betweenCentrality'], maxBetween, minBetween))

        nx.draw_networkx_nodes(G,
                               pos=pos,
                               vmax=1,
                               vmin=0,
                               cmap=cmapChosen,
                               with_labels=labels,
                               node_size=sizes,
                               node_color=colBetween,
                               ax=a)
        nx.draw_networkx_edges(G,
                               pos,
                               edge_color=globalEdgeCol,
                               style=globalEdgeType,
                               alpha=globalEdgeOpacity,
                               ax=a)
        if (labels):
            nx.draw_networkx_labels(G,
                                    pos,
                                    font_size=globalLabSize,
                                    ax=a,
                                    font_color=globalLabelCol)

    if (globalOptionsMet2 == "Subgraph Centrality"):
        # Metrics computing
        subgraphCentralities = nx.subgraph_centrality(G)

        # Add metrics as params of the nodes
        nx.set_node_attributes(G,
                               values=subgraphCentralities,
                               name='subgraphCentrality')

        # minmax
        minSub = min(subgraphCentralities.values())
        maxSub = max(subgraphCentralities.values())

        colSub = []

        # Set the colors that could be used next
        for node, data in G.nodes(data=True):
            colSub.append(normalize(data['subgraphCentrality'], maxSub,
                                    minSub))

        nx.draw_networkx_nodes(G,
                               pos=pos,
                               vmax=1,
                               vmin=0,
                               cmap=cmapChosen,
                               with_labels=labels,
                               node_size=sizes,
                               node_color=colSub,
                               ax=a)
        nx.draw_networkx_edges(G,
                               pos,
                               edge_color=globalEdgeCol,
                               style=globalEdgeType,
                               alpha=globalEdgeOpacity,
                               ax=a)
        if (labels):
            nx.draw_networkx_labels(G,
                                    pos,
                                    font_size=globalLabSize,
                                    ax=a,
                                    font_color=globalLabelCol)

    if (globalOptionsMet2 == "Load Centrality"):
        # Metrics computing
        loadCentralities = nx.load_centrality(G)

        # Add metrics as params of the nodes
        nx.set_node_attributes(G,
                               values=loadCentralities,
                               name='loadCentrality')

        # minmax
        minLoad = min(loadCentralities.values())
        maxLoad = max(loadCentralities.values())

        colLoad = []

        # Set the colors that could be used next
        for node, data in G.nodes(data=True):
            colLoad.append(normalize(data['loadCentrality'], maxLoad, minLoad))

        nx.draw_networkx_nodes(G,
                               pos=pos,
                               vmax=1,
                               vmin=0,
                               cmap=cmapChosen,
                               with_labels=labels,
                               node_size=sizes,
                               node_color=colLoad,
                               ax=a)
        nx.draw_networkx_edges(G,
                               pos,
                               edge_color=globalEdgeCol,
                               style=globalEdgeType,
                               alpha=globalEdgeOpacity,
                               ax=a)
        if (labels):
            nx.draw_networkx_labels(G,
                                    pos,
                                    font_size=globalLabSize,
                                    ax=a,
                                    font_color=globalLabelCol)
예제 #13
0
def get_subgraph(graph, run):
    if run:
        centrality = nx.subgraph_centrality(graph)
        df = pd.DataFrame(centrality, index=['Subgraph Centrality'])
        return df
    def compute_subgraph_center(self, subgraph):

        if self.method == 'betweenness_centrality':
            d = nx.betweenness_centrality(subgraph, weight='weight')
            center = max(d, key=d.get)

        elif self.method == 'betweenness_centrality_subset':
            d = nx.betweenness_centrality_subset(subgraph, weight='weight')
            center = max(d, key=d.get)

        elif self.method == 'information_centrality':
            d = nx.information_centrality(subgraph, weight='weight')
            center = max(d, key=d.get)

        elif self.method == 'local_reaching_centrality':

            d = {}
            for n in self.G.nodes():
                d[n] = nx.local_reaching_centrality(self.G, n, weight='weight')

            center = max(d, key=d.get)

        elif self.method == 'voterank':
            d = nx.voterank(subgraph)
            center = max(d, key=d.get)

        elif self.method == 'percolation_centrality':
            d = nx.percolation_centrality(subgraph, weight='weight')
            center = max(d, key=d.get)

        elif self.method == 'subgraph_centrality':
            d = nx.subgraph_centrality(subgraph)
            center = max(d, key=d.get)

        elif self.method == 'subgraph_centrality_exp':
            d = nx.subgraph_centrality_exp(subgraph)
            center = max(d, key=d.get)

        elif self.method == 'estrada_index':
            d = nx.estrada_index(subgraph)
            center = max(d, key=d.get)

        elif self.method == 'second_order_centrality':
            d = nx.second_order_centrality(subgraph)
            center = max(d, key=d.get)

        elif self.method == 'eigenvector_centrality':

            d = nx.eigenvector_centrality(subgraph, weight='weight')
            center = max(d, key=d.get)
        elif self.method == 'load_centrality':

            d = nx.load_centrality(subgraph, weight='weight')
            center = max(d, key=d.get)

        elif self.method == 'closeness_centrality':
            d = nx.closeness_centrality(subgraph)
            center = max(d, key=d.get)

        elif self.method == 'current_flow_closeness_centrality':
            d = nx.current_flow_closeness_centrality(subgraph, weight='weight')
            center = max(d, key=d.get)

        elif self.method == 'current_flow_betweenness_centrality':
            d = nx.current_flow_betweenness_centrality(subgraph,
                                                       weight='weight')
            center = max(d, key=d.get)

        elif self.method == 'current_flow_betweenness_centrality_subset':
            d = nx.current_flow_betweenness_centrality_subset(subgraph,
                                                              weight='weight')
            center = max(d, key=d.get)

        elif self.method == 'approximate_current_flow_betweenness_centrality':
            d = nx.approximate_current_flow_betweenness_centrality(
                subgraph, weight='weight')
            center = max(d, key=d.get)

        elif self.method == 'harmonic_centrality':
            d = nx.harmonic_centrality(subgraph)
            center = max(d, key=d.get)

        elif self.method == 'page_rank':

            d = nx.pagerank(subgraph, weight='weight')
            center = max(d, key=d.get)

        elif self.method == 'hits':

            d = nx.hits(subgraph)
            center = max(d, key=d.get)

        elif self.method == 'katz_centrality':
            d = nx.katz_centrality(subgraph, weight='weight')
            center = max(d, key=d.get)

        else:
            new_centers = nx.center(subgraph)

            # new_centers gives a list of centers and here we just pick one randomly --not good for stability
            # to do : find a better way to choose the center--make it stable

            index = random.randint(0, len(new_centers) - 1)

            center = new_centers[index]
        return center
예제 #15
0
def calc_centralities(G,org_name,string_version):
    print("Calculating centralities")
    centrality_measures = {}
    string_location=f.string_version_data(string_version)[0]
    print(string_location)
    # if 1==0:
    if os.path.isfile('centrality_data/%s/%s.cent'%(string_location,org_name)):
        print("Using cached centrality data")
        file=open('centrality_data/%s/%s.cent'%(string_location,org_name))
        lines=file.readlines()
        centrality_list=lines.pop(0).strip().split(' ')
        centrality_list.pop(0)
        
        for i,centrality in enumerate(centrality_list):
            centrality_measures[centrality]={}

        for line in lines:
            value_list=line.split(' ')
            for i,centrality in enumerate(centrality_list):
                # print("%d. %s" % (i+1,centrality))
                centrality_measures[centrality][value_list[0]]=float(value_list[i+1])
    else:
        
        print("1. Degree centrality")
        centrality_measures['Degree_Centrality']=nx.degree_centrality(G)
        
        print("2. Closeness centrality")
        centrality_measures['Closeness_Centrality']=Counter(nx.algorithms.centrality.closeness_centrality(G))
        
        print("3. Betweenness centrality")
        centrality_measures['Betweenness_Centrality']=Counter(nx.algorithms.centrality.betweenness_centrality(G))
        
        print("4. Clustering coefficient")
        centrality_measures['Clustering_Co-efficient']=Counter(nx.clustering(G))
        
        print("5. Eigenvector centrality")
        centrality_measures['Eigenvector_Centrality']= nx.eigenvector_centrality(G)
        
        print("6. Subgraph centrality")
        centrality_measures["Subgraph_Centrality"]=nx.subgraph_centrality(G)
        
        print("7. Information centrality")
        centrality_measures["Information_Centrality"]=nx.current_flow_closeness_centrality(f.trim_graph(G))
        
        print("8. Clique Number")
        cliq={}
        for i in G.nodes():
           cliq[i]=nx.node_clique_number(G,i)
        centrality_measures["Clique_Number"]=cliq
        
        print("9. Edge clustering coefficient")
        edge_clus_coeff={}
        for n in G.nodes:
            edge_clus_coeff[n]=0
            for e in G.edges(n):
                num=len(list(nx.common_neighbors(G,e[0],e[1])))
                den=(min(G.degree(e[0]),G.degree(e[1]))-1)
                if den==0:
                    den=1
                edge_clus_coeff[n]+=num/den
    
        centrality_measures['Edge_Clustering_Coefficient']=edge_clus_coeff
        
        print("10. Page Rank")
        centrality_measures['Page_Rank']=nx.pagerank(G)
        
        print("11. Random Walk Betweenness Centrality")
        centrality_measures["Random_Walk_Betweenness_Centrality"]=nx.current_flow_betweenness_centrality(f.trim_graph(G))
        
        print("12. Load Centrality")
        centrality_measures["Load_Centrality"]=nx.load_centrality(G)
        
        print("13. Communicability Betweenness")
        centrality_measures["Communicability_Betweenness"]=nx.communicability_betweenness_centrality(f.trim_graph(G))
        
        print("14. Harmonic Centrality")
        centrality_measures["Harmonic_Centrality"]=nx.harmonic_centrality(G)
            
        print("15. Reaching Centrality")
        reach_cent={}
        for node in G.nodes:
            reach_cent[node] = nx.local_reaching_centrality(G,node)
        centrality_measures["Reaching_Centrality"]=reach_cent
        
        print("16. Katz Centrality(not calculated)")
    #   centrality_measures["Katz_Centrality"]=nx.katz_centrality(G)
    
        datafile=open("refex_props/%s.refex" % (org_name))
        sample_line=datafile.readline()
        s= sample_line.strip().split(' ')
        for x in range(1,len(s)):
            centrality_measures["refex#%d" % (x)]={}                
        for line in datafile:
            props=line.strip().split(" ")
            props=[i.strip('\t') for i in props]
            for x in range(1,len(s)):
                centrality_measures["refex#%d" % (x)][props[0]]=float(props[x])

        datafile=open("refex_rider_props/%s.riderproperties" % (org_name))
        sample_line=datafile.readline()
        s= sample_line.strip().split(' ')
        s.pop(1)
        print(len(s))
        for x in range(1,len(s)):
            centrality_measures["refex_rider#%d" % (x)]={}                
        
        for line in datafile:
            props=line.strip().split(" ")
            props.pop(1)
            for x in range(1,len(props)):

                centrality_measures["refex_rider#%d" % (x)][props[0]]=float(props[x])
    
     
        with open('centrality_data/%s/%s.cent'%(string_location,org_name),'w') as file:
            file.write(str(org_name)+' ')
            centrality_list=list(centrality_measures)
            for x in centrality_list:
                file.write(str(x)+' ')

            for node in G.nodes:
                file.write('\n'+node+' ')
                for x in centrality_list:
                    if node not in centrality_measures[x]:
                        file.write('-1 ')
                    else:
                        file.write(str(centrality_measures[x][node])+' ')
    return centrality_measures
예제 #16
0
#Get edge list from the file
edgelist = [(row['protein1'], row['protein2']) for index, row in file.iterrows()]

# Create graph for the virus-human PPI network
G = nx.Graph()
G.add_edges_from(edgelist)
    
# Print the virus-human PPI network info    
print(nx.info(G))

deg_centrality = nx.degree_centrality(G)   
eig_vec_centrality = nx.eigenvector_centrality(G)
close_centrality = nx.closeness_centrality(G)
#egde_betw_centrality = nx.edge_betweenness_centrality(G)   
harm_centrality = nx.harmonic_centrality(G)
ld_centrality = nx.load_centrality(G)
subg_centrality = nx.subgraph_centrality(G)

centrality_df = pd.DataFrame({'prot_id': list(deg_centrality.keys()) ,                   #add nodes
                                  'degree_centrality': list(deg_centrality.values()) ,         #add degree centrality
                                  'eigen_vector_centrality': list(eig_vec_centrality.values()),   #add eigen vector centrality 
                                  'close_centrality': list(close_centrality.values()),      #add closeness centrality
                                  #'edge_betweenness': ,          #add edge betweenness
                                  'harmonic_centrality': list(harm_centrality.values()),       #add harmonic centrality
                                  'load_centrality': list(ld_centrality.values()),      #add load centrality
                                  'subgraph_centrality': list(subg_centrality.values()) #add subg centrality 
                                  })
    
    
#centrality_df.to_csv("centrality_measures_hhv1.csv",index=False)
예제 #17
0
plt.show()

nx.draw(g1, with_labels=1)
plt.title("Example visualization of Maslov-Snepen graph")
plt.show()

list_of_weighted_cms_lists = []
list_of_unweighted_cms_lists = []

# Centrality measurements for weighted graphs
for i in listOfWeightedGraphs:
    centrality_measurements = []
    centrality_measurements.append(list(nx.degree_centrality(i).values()))
    centrality_measurements.append(list(nx.eigenvector_centrality(i).values()))
    centrality_measurements.append(list(nx.betweenness_centrality(i).values()))
    centrality_measurements.append(list(nx.subgraph_centrality(i).values()))
    centrality_measurements.append(list(nx.katz_centrality_numpy(i).values()))
    centrality_measurements.append(list(nx.pagerank(i).values()))
    centrality_measurements.append(list(nx.closeness_centrality(i).values()))
    #centrality_measurements.append(list(nx.current_flow_betweenness_centrality(i).values()))
    #centrality_measurements.append(list(nx.communicability_betweenness_centrality(i).values()))
    #centrality_measurements.append(list(nx.average_neighbor_degree(i).values()))
    list_of_weighted_cms_lists.append(centrality_measurements)

# Centrality measurements for unweighted graphs
for i in listOfUnweightedGraphs:
    centrality_measurements = []
    centrality_measurements.append(list(nx.degree_centrality(i).values()))
    centrality_measurements.append(list(nx.eigenvector_centrality(i).values()))
    centrality_measurements.append(list(nx.betweenness_centrality(i).values()))
    centrality_measurements.append(list(nx.subgraph_centrality(i).values()))