cluster.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. """Functions for computing clustering of pairs
  2. """
  3. import itertools
  4. import networkx as nx
  5. __all__ = [
  6. "clustering",
  7. "average_clustering",
  8. "latapy_clustering",
  9. "robins_alexander_clustering",
  10. ]
  11. def cc_dot(nu, nv):
  12. return len(nu & nv) / len(nu | nv)
  13. def cc_max(nu, nv):
  14. return len(nu & nv) / max(len(nu), len(nv))
  15. def cc_min(nu, nv):
  16. return len(nu & nv) / min(len(nu), len(nv))
  17. modes = {"dot": cc_dot, "min": cc_min, "max": cc_max}
  18. def latapy_clustering(G, nodes=None, mode="dot"):
  19. r"""Compute a bipartite clustering coefficient for nodes.
  20. The bipartie 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 pariwise 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. def average_clustering(G, nodes=None, mode="dot"):
  94. r"""Compute the average bipartite clustering coefficient.
  95. A clustering coefficient for the whole graph is the average,
  96. .. math::
  97. C = \frac{1}{n}\sum_{v \in G} c_v,
  98. where `n` is the number of nodes in `G`.
  99. Similar measures for the two bipartite sets can be defined [1]_
  100. .. math::
  101. C_X = \frac{1}{|X|}\sum_{v \in X} c_v,
  102. where `X` is a bipartite set of `G`.
  103. Parameters
  104. ----------
  105. G : graph
  106. a bipartite graph
  107. nodes : list or iterable, optional
  108. A container of nodes to use in computing the average.
  109. The nodes should be either the entire graph (the default) or one of the
  110. bipartite sets.
  111. mode : string
  112. The pariwise bipartite clustering method.
  113. It must be "dot", "max", or "min"
  114. Returns
  115. -------
  116. clustering : float
  117. The average bipartite clustering for the given set of nodes or the
  118. entire graph if no nodes are specified.
  119. Examples
  120. --------
  121. >>> from networkx.algorithms import bipartite
  122. >>> G = nx.star_graph(3) # star graphs are bipartite
  123. >>> bipartite.average_clustering(G)
  124. 0.75
  125. >>> X, Y = bipartite.sets(G)
  126. >>> bipartite.average_clustering(G, X)
  127. 0.0
  128. >>> bipartite.average_clustering(G, Y)
  129. 1.0
  130. See Also
  131. --------
  132. clustering
  133. Notes
  134. -----
  135. The container of nodes passed to this function must contain all of the nodes
  136. in one of the bipartite sets ("top" or "bottom") in order to compute
  137. the correct average bipartite clustering coefficients.
  138. See :mod:`bipartite documentation <networkx.algorithms.bipartite>`
  139. for further details on how bipartite graphs are handled in NetworkX.
  140. References
  141. ----------
  142. .. [1] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008).
  143. Basic notions for the analysis of large two-mode networks.
  144. Social Networks 30(1), 31--48.
  145. """
  146. if nodes is None:
  147. nodes = G
  148. ccs = latapy_clustering(G, nodes=nodes, mode=mode)
  149. return sum(ccs[v] for v in nodes) / len(nodes)
  150. def robins_alexander_clustering(G):
  151. r"""Compute the bipartite clustering of G.
  152. Robins and Alexander [1]_ defined bipartite clustering coefficient as
  153. four times the number of four cycles `C_4` divided by the number of
  154. three paths `L_3` in a bipartite graph:
  155. .. math::
  156. CC_4 = \frac{4 * C_4}{L_3}
  157. Parameters
  158. ----------
  159. G : graph
  160. a bipartite graph
  161. Returns
  162. -------
  163. clustering : float
  164. The Robins and Alexander bipartite clustering for the input graph.
  165. Examples
  166. --------
  167. >>> from networkx.algorithms import bipartite
  168. >>> G = nx.davis_southern_women_graph()
  169. >>> print(round(bipartite.robins_alexander_clustering(G), 3))
  170. 0.468
  171. See Also
  172. --------
  173. latapy_clustering
  174. networkx.algorithms.cluster.square_clustering
  175. References
  176. ----------
  177. .. [1] Robins, G. and M. Alexander (2004). Small worlds among interlocking
  178. directors: Network structure and distance in bipartite graphs.
  179. Computational & Mathematical Organization Theory 10(1), 69–94.
  180. """
  181. if G.order() < 4 or G.size() < 3:
  182. return 0
  183. L_3 = _threepaths(G)
  184. if L_3 == 0:
  185. return 0
  186. C_4 = _four_cycles(G)
  187. return (4.0 * C_4) / L_3
  188. def _four_cycles(G):
  189. cycles = 0
  190. for v in G:
  191. for u, w in itertools.combinations(G[v], 2):
  192. cycles += len((set(G[u]) & set(G[w])) - {v})
  193. return cycles / 4
  194. def _threepaths(G):
  195. paths = 0
  196. for v in G:
  197. for u in G[v]:
  198. for w in set(G[u]) - {v}:
  199. paths += len(set(G[w]) - {v, u})
  200. # Divide by two because we count each three path twice
  201. # one for each possible starting point
  202. return paths / 2