Python networkx.closeness_centrality() Examples

The following are 21 code examples of networkx.closeness_centrality(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: analyse_meg_epilepsy_clips.py    From mmvt with GNU General Public License v3.0 8 votes vote down vote up
def _calc_graph_func(p):
    con, times_chunk, graph_func = p
    vals = []
    now = time.time()
    for run, t in enumerate(times_chunk):
        utils.time_to_go(now, run, len(times_chunk), 10)
        con_t = con[:, :, t]
        g = nx.from_numpy_matrix(con_t)
        if graph_func == 'closeness_centrality':
            x = nx.closeness_centrality(g)
        elif graph_func == 'degree_centrality':
            x = nx.degree_centrality(g)
        elif graph_func == 'eigenvector_centrality':
            x = nx.eigenvector_centrality(g, max_iter=10000)
        elif graph_func == 'katz_centrality':
            x = nx.katz_centrality(g, max_iter=100000)
        else:
            raise Exception('Wrong graph func!')
        vals.append([x[k] for k in range(len(x))])
    vals = np.array(vals)
    return vals, times_chunk 
Example #2
Source File: test_closeness_centrality.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_florentine_families_closeness(self):
        c=nx.closeness_centrality(self.F)
        d={'Acciaiuoli':    0.368,
           'Albizzi':       0.483,
           'Barbadori':     0.4375,
           'Bischeri':      0.400,
           'Castellani':    0.389,
           'Ginori':        0.333,
           'Guadagni':      0.467,
           'Lamberteschi':  0.326,
           'Medici':        0.560,
           'Pazzi':         0.286,
           'Peruzzi':       0.368,
           'Ridolfi':       0.500,
           'Salviati':      0.389,
           'Strozzi':       0.4375,
           'Tornabuoni':    0.483}
        for n in sorted(self.F):
            assert_almost_equal(c[n],d[n],places=3) 
Example #3
Source File: test_closeness_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_digraph(self):
        G = nx.path_graph(3, create_using=nx.DiGraph())
        c = nx.closeness_centrality(G)
        cr = nx.closeness_centrality(G.reverse())
        d = {0: 0.0, 1: 0.500, 2: 0.667}
        dr = {0: 0.667, 1: 0.500, 2: 0.0}
        for n in sorted(self.P3):
            assert_almost_equal(c[n], d[n], places=3)
            assert_almost_equal(cr[n], dr[n], places=3) 
Example #4
Source File: test_closeness_centrality.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_weighted_closeness(self):
        edges = ([('s', 'u', 10), ('s', 'x', 5), ('u', 'v', 1),
                  ('u', 'x', 2), ('v', 'y', 1), ('x', 'u', 3),
                  ('x', 'v', 5), ('x', 'y', 2), ('y', 's', 7), ('y', 'v', 6)])
        XG = nx.Graph()
        XG.add_weighted_edges_from(edges)
        c = nx.closeness_centrality(XG, distance='weight')
        d = {'y': 0.200,
             'x': 0.286,
             's': 0.138,
             'u': 0.235,
             'v': 0.200}
        for n in sorted(XG):
            assert_almost_equal(c[n], d[n], places=3) 
Example #5
Source File: test_closeness_centrality.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_krackhardt_closeness(self):
        c = nx.closeness_centrality(self.K)
        d = {0: 0.529,
             1: 0.529,
             2: 0.500,
             3: 0.600,
             4: 0.500,
             5: 0.643,
             6: 0.643,
             7: 0.600,
             8: 0.429,
             9: 0.310}
        for n in sorted(self.K):
            assert_almost_equal(c[n], d[n], places=3) 
Example #6
Source File: test_closeness_centrality.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_p3_closeness(self):
        c = nx.closeness_centrality(self.P3)
        d = {0: 0.667,
             1: 1.000,
             2: 0.667}
        for n in sorted(self.P3):
            assert_almost_equal(c[n], d[n], places=3) 
Example #7
Source File: test_closeness_centrality.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_k5_closeness(self):
        c = nx.closeness_centrality(self.K5)
        d = {0: 1.000,
             1: 1.000,
             2: 1.000,
             3: 1.000,
             4: 1.000}
        for n in sorted(self.K5):
            assert_almost_equal(c[n], d[n], places=3) 
Example #8
Source File: test_closeness_centrality.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_digraph(self):
        G = nx.path_graph(3, create_using=nx.DiGraph())
        c = nx.closeness_centrality(G)
        cr = nx.closeness_centrality(G, reverse=True)
        d = {0: 0.0, 1: 0.500, 2: 0.667}
        dr = {0: 0.667, 1: 0.500, 2: 0.0}
        for n in sorted(self.P3):
            assert_almost_equal(c[n], d[n], places=3)
            assert_almost_equal(cr[n], dr[n], places=3) 
Example #9
Source File: test_closeness_centrality.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_wf_improved(self):
        G = nx.union(self.P4, nx.path_graph([4, 5, 6]))
        c = nx.closeness_centrality(G)
        cwf = nx.closeness_centrality(G, wf_improved=False)
        res = {0: 0.25, 1: 0.375, 2: 0.375, 3: 0.25,
               4: 0.222, 5: 0.333, 6: 0.222}
        wf_res = {0: 0.5, 1: 0.75, 2: 0.75, 3: 0.5,
                  4: 0.667, 5: 1.0, 6: 0.667}
        for n in G:
            assert_almost_equal(c[n], res[n], places=3)
            assert_almost_equal(cwf[n], wf_res[n], places=3) 
Example #10
Source File: test_closeness_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_weighted_closeness(self):
        edges = ([('s', 'u', 10), ('s', 'x', 5), ('u', 'v', 1),
                  ('u', 'x', 2), ('v', 'y', 1), ('x', 'u', 3),
                  ('x', 'v', 5), ('x', 'y', 2), ('y', 's', 7), ('y', 'v', 6)])
        XG = nx.Graph()
        XG.add_weighted_edges_from(edges)
        c = nx.closeness_centrality(XG, distance='weight')
        d = {'y': 0.200,
             'x': 0.286,
             's': 0.138,
             'u': 0.235,
             'v': 0.200}
        for n in sorted(XG):
            assert_almost_equal(c[n], d[n], places=3) 
Example #11
Source File: test_closeness_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_krackhardt_closeness(self):
        c = nx.closeness_centrality(self.K)
        d = {0: 0.529,
             1: 0.529,
             2: 0.500,
             3: 0.600,
             4: 0.500,
             5: 0.643,
             6: 0.643,
             7: 0.600,
             8: 0.429,
             9: 0.310}
        for n in sorted(self.K):
            assert_almost_equal(c[n], d[n], places=3) 
Example #12
Source File: test_closeness_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_p3_closeness(self):
        c = nx.closeness_centrality(self.P3)
        d = {0: 0.667,
             1: 1.000,
             2: 0.667}
        for n in sorted(self.P3):
            assert_almost_equal(c[n], d[n], places=3) 
Example #13
Source File: test_closeness_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_k5_closeness(self):
        c = nx.closeness_centrality(self.K5)
        d = {0: 1.000,
             1: 1.000,
             2: 1.000,
             3: 1.000,
             4: 1.000}
        for n in sorted(self.K5):
            assert_almost_equal(c[n], d[n], places=3) 
Example #14
Source File: test_closeness_centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_wf_improved(self):
        G = nx.union(self.P4, nx.path_graph([4, 5, 6]))
        c = nx.closeness_centrality(G)
        cwf = nx.closeness_centrality(G, wf_improved=False)
        res = {0: 0.25, 1: 0.375, 2: 0.375, 3: 0.25,
               4: 0.222, 5: 0.333, 6: 0.222}
        wf_res = {0: 0.5, 1: 0.75, 2: 0.75, 3: 0.5,
                  4: 0.667, 5: 1.0, 6: 0.667}
        for n in G:
            assert_almost_equal(c[n], res[n], places=3)
            assert_almost_equal(cwf[n], wf_res[n], places=3) 
Example #15
Source File: graph_test.py    From mmvt with GNU General Public License v3.0 5 votes vote down vote up
def calc_closeness_centrality(p):
    con, times_chunk = p
    vals = []
    now = time.time()
    for run, t in enumerate(times_chunk):
        utils.time_to_go(now, run, len(times_chunk), 10)
        con_t = con[:, :, t]
        g = nx.from_numpy_matrix(con_t)
        # x = nx.closeness_centrality(g)
        x = nx.degree_centrality(g)
        vals.append([x[k] for k in range(len(x))])
    vals = np.array(vals)
    return vals, times_chunk 
Example #16
Source File: test_closeness_centrality.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_weighted_closeness(self):
        XG=nx.Graph()
        XG.add_weighted_edges_from([('s','u',10), ('s','x',5), ('u','v',1),
                                    ('u','x',2), ('v','y',1), ('x','u',3),
                                    ('x','v',5), ('x','y',2), ('y','s',7),
                                    ('y','v',6)])
        c=nx.closeness_centrality(XG,distance='weight')
        d={'y': 0.200,
           'x': 0.286,
           's': 0.138,
           'u': 0.235,
           'v': 0.200}
        for n in sorted(XG):
            assert_almost_equal(c[n],d[n],places=3) 
Example #17
Source File: test_closeness_centrality.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_krackhardt_closeness(self):
        c=nx.closeness_centrality(self.K)
        d={0: 0.529,
           1: 0.529,
           2: 0.500,
           3: 0.600,
           4: 0.500,
           5: 0.643,
           6: 0.643,
           7: 0.600,
           8: 0.429,
           9: 0.310}
        for n in sorted(self.K):
            assert_almost_equal(c[n],d[n],places=3) 
Example #18
Source File: test_closeness_centrality.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_p3_closeness(self):
        c=nx.closeness_centrality(self.P3)
        d={0: 0.667,
           1: 1.000,
           2: 0.667}
        for n in sorted(self.P3):
            assert_almost_equal(c[n],d[n],places=3) 
Example #19
Source File: test_closeness_centrality.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_k5_closeness(self):
        c=nx.closeness_centrality(self.K5)
        d={0: 1.000,
           1: 1.000,
           2: 1.000,
           3: 1.000,
           4: 1.000}
        for n in sorted(self.K5):
            assert_almost_equal(c[n],d[n],places=3) 
Example #20
Source File: graph_score_vectorizer.py    From Quadflor with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, method='degree', analyzer=NltkNormalizer().split_and_normalize):
        self.analyze = analyzer
        self.method = method
        self.methods_on_digraph = {'hits', 'pagerank', 'katz'}
        self._get_scores = {'degree': nx.degree, 'betweenness': nx.betweenness_centrality,
                            'pagerank': nx.pagerank_scipy, 'hits': self._hits, 'closeness': nx.closeness_centrality,
                            'katz': nx.katz_centrality}[method]
        # Add a new value when a new vocabulary item is seen
        self.vocabulary = defaultdict()
        self.vocabulary.default_factory = self.vocabulary.__len__ 
Example #21
Source File: graph.py    From momepy with MIT License 4 votes vote down vote up
def local_closeness_centrality(
    graph, radius=5, name="closeness", distance=None, weight=None
):
    """
    Calculates local closeness for each node based on the defined distance.

    Subgraph is generated around each node within set radius. If ``distance=None``,
    radius will define topological distance, otherwise it uses values in ``distance``
    attribute. Based on ``networkx.closeness_centrality``.

    Local closeness centrality of a node `u` is the reciprocal of the
    average shortest path distance to `u` over all `n-1` nodes within subgraph.

    .. math::

        C(u) = \\frac{n - 1}{\\sum_{v=1}^{n-1} d(v, u)},

    where :math:`d(v, u)` is the shortest-path distance between :math:`v` and :math:`u`,
    and :math:`n` is the number of nodes that can reach :math:`u`.

    Adapted from :cite:`porta2006`.


    Parameters
    ----------
    graph : networkx.Graph
        Graph representing street network.
        Ideally generated from GeoDataFrame using :func:`momepy.gdf_to_nx`
    radius: int
        Include all neighbors of distance <= radius from n
    name : str, optional
        calculated attribute name
    distance : str, optional
        Use specified edge data key as distance.
        For example, setting ``distance=’weight’`` will use the edge ``weight`` to
        measure the distance from the node n during ego_graph generation.
    weight : str, optional
      Use the specified edge attribute as the edge distance in shortest
      path calculations in closeness centrality algorithm

    Returns
    -------
    Graph
        networkx.Graph

    Examples
    --------
    >>> network_graph = mm.local_closeness_centrality(network_graph, radius=400, distance='edge_length')

    """
    warnings.warn(
        "local_closeness_centrality() is deprecated and will be removed in momepy 0.4.0. "
        "Use closeness_centrality() instead.",
        FutureWarning,
    )

    return closeness_centrality(
        graph=graph, radius=radius, name=name, distance=distance, weight=weight
    )