Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/networkx/algorithms/centrality/harmonic.py: 29%
17 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-20 07:00 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-20 07:00 +0000
1"""Functions for computing the harmonic centrality of a graph."""
2from functools import partial
4import networkx as nx
6__all__ = ["harmonic_centrality"]
9@nx._dispatch(edge_attrs="distance")
10def harmonic_centrality(G, nbunch=None, distance=None, sources=None):
11 r"""Compute harmonic centrality for nodes.
13 Harmonic centrality [1]_ of a node `u` is the sum of the reciprocal
14 of the shortest path distances from all other nodes to `u`
16 .. math::
18 C(u) = \sum_{v \neq u} \frac{1}{d(v, u)}
20 where `d(v, u)` is the shortest-path distance between `v` and `u`.
22 If `sources` is given as an argument, the returned harmonic centrality
23 values are calculated as the sum of the reciprocals of the shortest
24 path distances from the nodes specified in `sources` to `u` instead
25 of from all nodes to `u`.
27 Notice that higher values indicate higher centrality.
29 Parameters
30 ----------
31 G : graph
32 A NetworkX graph
34 nbunch : container (default: all nodes in G)
35 Container of nodes for which harmonic centrality values are calculated.
37 sources : container (default: all nodes in G)
38 Container of nodes `v` over which reciprocal distances are computed.
39 Nodes not in `G` are silently ignored.
41 distance : edge attribute key, optional (default=None)
42 Use the specified edge attribute as the edge distance in shortest
43 path calculations. If `None`, then each edge will have distance equal to 1.
45 Returns
46 -------
47 nodes : dictionary
48 Dictionary of nodes with harmonic centrality as the value.
50 See Also
51 --------
52 betweenness_centrality, load_centrality, eigenvector_centrality,
53 degree_centrality, closeness_centrality
55 Notes
56 -----
57 If the 'distance' keyword is set to an edge attribute key then the
58 shortest-path length will be computed using Dijkstra's algorithm with
59 that edge attribute as the edge weight.
61 References
62 ----------
63 .. [1] Boldi, Paolo, and Sebastiano Vigna. "Axioms for centrality."
64 Internet Mathematics 10.3-4 (2014): 222-262.
65 """
67 nbunch = set(G.nbunch_iter(nbunch)) if nbunch is not None else set(G.nodes)
68 sources = set(G.nbunch_iter(sources)) if sources is not None else G.nodes
70 spl = partial(nx.shortest_path_length, G, weight=distance)
71 centrality = {u: 0 for u in nbunch}
72 for v in sources:
73 dist = spl(v)
74 for u in nbunch.intersection(dist):
75 d = dist[u]
76 if d == 0: # handle u == v and edges with 0 weight
77 continue
78 centrality[u] += 1 / d
80 return centrality