cluster.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. """Functions for computing clustering of pairs"""
  2. import itertools
  3. import networkx as nx
  4. __all__ = [
  5. "clustering",
  6. "average_clustering",
  7. "latapy_clustering",
  8. "robins_alexander_clustering",
  9. ]
  10. def cc_dot(nu, nv):
  11. return len(nu & nv) / len(nu | nv)
  12. def cc_max(nu, nv):
  13. return len(nu & nv) / max(len(nu), len(nv))
  14. def cc_min(nu, nv):
  15. return len(nu & nv) / min(len(nu), len(nv))
  16. modes = {"dot": cc_dot, "min": cc_min, "max": cc_max}
  17. @nx._dispatchable
  18. def latapy_clustering(G, nodes=None, mode="dot"):
  19. r"""Compute a bipartite clustering coefficient for nodes.
  20. The bipartite clustering coefficient is a measure of local density
  21. of connections defined as [1]_:
  22. .. math::
  23. c_u = \frac{\sum_{v \in N(N(u))} c_{uv} }{|N(N(u))|}
  24. where `N(N(u))` are the second order neighbors of `u` in `G` excluding `u`,
  25. and `c_{uv}` is the pairwise clustering coefficient between nodes
  26. `u` and `v`.
  27. The mode selects the function for `c_{uv}` which can be:
  28. `dot`:
  29. .. math::
  30. c_{uv}=\frac{|N(u)\cap N(v)|}{|N(u) \cup N(v)|}
  31. `min`:
  32. .. math::
  33. c_{uv}=\frac{|N(u)\cap N(v)|}{min(|N(u)|,|N(v)|)}
  34. `max`:
  35. .. math::
  36. c_{uv}=\frac{|N(u)\cap N(v)|}{max(|N(u)|,|N(v)|)}
  37. Parameters
  38. ----------
  39. G : graph
  40. A bipartite graph
  41. nodes : list or iterable (optional)
  42. Compute bipartite clustering for these nodes. The default
  43. is all nodes in G.
  44. mode : string
  45. The pairwise bipartite clustering method to be used in the computation.
  46. It must be "dot", "max", or "min".
  47. Returns
  48. -------
  49. clustering : dictionary
  50. A dictionary keyed by node with the clustering coefficient value.
  51. Examples
  52. --------
  53. >>> from networkx.algorithms import bipartite
  54. >>> G = nx.path_graph(4) # path graphs are bipartite
  55. >>> c = bipartite.clustering(G)
  56. >>> c[0]
  57. 0.5
  58. >>> c = bipartite.clustering(G, mode="min")
  59. >>> c[0]
  60. 1.0
  61. See Also
  62. --------
  63. robins_alexander_clustering
  64. average_clustering
  65. networkx.algorithms.cluster.square_clustering
  66. References
  67. ----------
  68. .. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008).
  69. Basic notions for the analysis of large two-mode networks.
  70. Social Networks 30(1), 31--48.
  71. """
  72. if not nx.algorithms.bipartite.is_bipartite(G):
  73. raise nx.NetworkXError("Graph is not bipartite")
  74. try:
  75. cc_func = modes[mode]
  76. except KeyError as err:
  77. raise nx.NetworkXError(
  78. "Mode for bipartite clustering must be: dot, min or max"
  79. ) from err
  80. if nodes is None:
  81. nodes = G
  82. ccs = {}
  83. for v in nodes:
  84. cc = 0.0
  85. nbrs2 = {u for nbr in G[v] for u in G[nbr]} - {v}
  86. for u in nbrs2:
  87. cc += cc_func(set(G[u]), set(G[v]))
  88. if cc > 0.0: # len(nbrs2)>0
  89. cc /= len(nbrs2)
  90. ccs[v] = cc
  91. return ccs
  92. clustering = latapy_clustering
  93. @nx._dispatchable(name="bipartite_average_clustering")
  94. def average_clustering(G, nodes=None, mode="dot"):
  95. r"""Compute the average bipartite clustering coefficient.
  96. A clustering coefficient for the whole graph is the average,
  97. .. math::
  98. C = \frac{1}{n}\sum_{v \in G} c_v,
  99. where `n` is the number of nodes in `G`.
  100. Similar measures for the two bipartite sets can be defined [1]_
  101. .. math::
  102. C_X = \frac{1}{|X|}\sum_{v \in X} c_v,
  103. where `X` is a bipartite set of `G`.
  104. Parameters
  105. ----------
  106. G : graph
  107. a bipartite graph
  108. nodes : list or iterable, optional
  109. A container of nodes to use in computing the average.
  110. The nodes should be either the entire graph (the default) or one of the
  111. bipartite sets.
  112. mode : string
  113. The pairwise bipartite clustering method.
  114. It must be "dot", "max", or "min"
  115. Returns
  116. -------
  117. clustering : float
  118. The average bipartite clustering for the given set of nodes or the
  119. entire graph if no nodes are specified.
  120. Examples
  121. --------
  122. >>> from networkx.algorithms import bipartite
  123. >>> G = nx.star_graph(3) # star graphs are bipartite
  124. >>> bipartite.average_clustering(G)
  125. 0.75
  126. >>> X, Y = bipartite.sets(G)
  127. >>> bipartite.average_clustering(G, X)
  128. 0.0
  129. >>> bipartite.average_clustering(G, Y)
  130. 1.0
  131. See Also
  132. --------
  133. clustering
  134. Notes
  135. -----
  136. The container of nodes passed to this function must contain all of the nodes
  137. in one of the bipartite sets ("top" or "bottom") in order to compute
  138. the correct average bipartite clustering coefficients.
  139. See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
  140. for further details on how bipartite graphs are handled in NetworkX.
  141. References
  142. ----------
  143. .. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008).
  144. Basic notions for the analysis of large two-mode networks.
  145. Social Networks 30(1), 31--48.
  146. """
  147. if nodes is None:
  148. nodes = G
  149. ccs = latapy_clustering(G, nodes=nodes, mode=mode)
  150. return sum(ccs[v] for v in nodes) / len(nodes)
  151. @nx._dispatchable
  152. def robins_alexander_clustering(G):
  153. r"""Compute the bipartite clustering of G.
  154. Robins and Alexander [1]_ defined bipartite clustering coefficient as
  155. four times the number of four cycles `C_4` divided by the number of
  156. three paths `L_3` in a bipartite graph:
  157. .. math::
  158. CC_4 = \frac{4 * C_4}{L_3}
  159. Parameters
  160. ----------
  161. G : graph
  162. a bipartite graph
  163. Returns
  164. -------
  165. clustering : float
  166. The Robins and Alexander bipartite clustering for the input graph.
  167. Examples
  168. --------
  169. >>> from networkx.algorithms import bipartite
  170. >>> G = nx.davis_southern_women_graph()
  171. >>> print(round(bipartite.robins_alexander_clustering(G), 3))
  172. 0.468
  173. See Also
  174. --------
  175. latapy_clustering
  176. networkx.algorithms.cluster.square_clustering
  177. References
  178. ----------
  179. .. [1] Robins, G. and M. Alexander (2004). Small worlds among interlocking
  180. directors: Network structure and distance in bipartite graphs.
  181. Computational & Mathematical Organization Theory 10(1), 69–94.
  182. """
  183. if G.order() < 4 or G.size() < 3:
  184. return 0
  185. L_3 = _threepaths(G)
  186. if L_3 == 0:
  187. return 0
  188. C_4 = _four_cycles(G)
  189. return (4.0 * C_4) / L_3
  190. def _four_cycles(G):
  191. # Also see `square_clustering` which counts squares in a similar way
  192. cycles = 0
  193. seen = set()
  194. G_adj = G._adj
  195. for v in G:
  196. seen.add(v)
  197. v_neighbors = set(G_adj[v])
  198. if len(v_neighbors) < 2:
  199. # Can't form a square without at least two neighbors
  200. continue
  201. two_hop_neighbors = set().union(*(G_adj[u] for u in v_neighbors))
  202. two_hop_neighbors -= seen
  203. for x in two_hop_neighbors:
  204. p2 = len(v_neighbors.intersection(G_adj[x]))
  205. cycles += p2 * (p2 - 1)
  206. return cycles / 4
  207. def _threepaths(G):
  208. paths = 0
  209. for v in G:
  210. for u in G[v]:
  211. for w in set(G[u]) - {v}:
  212. paths += len(set(G[w]) - {v, u})
  213. # Divide by two because we count each three path twice
  214. # one for each possible starting point
  215. return paths / 2