kcomponents.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. """ Fast approximation for k-component structure
  2. """
  3. import itertools
  4. from collections import defaultdict
  5. from collections.abc import Mapping
  6. from functools import cached_property
  7. import networkx as nx
  8. from networkx.algorithms.approximation import local_node_connectivity
  9. from networkx.exception import NetworkXError
  10. from networkx.utils import not_implemented_for
  11. __all__ = ["k_components"]
  12. @not_implemented_for("directed")
  13. def k_components(G, min_density=0.95):
  14. r"""Returns the approximate k-component structure of a graph G.
  15. A `k`-component is a maximal subgraph of a graph G that has, at least,
  16. node connectivity `k`: we need to remove at least `k` nodes to break it
  17. into more components. `k`-components have an inherent hierarchical
  18. structure because they are nested in terms of connectivity: a connected
  19. graph can contain several 2-components, each of which can contain
  20. one or more 3-components, and so forth.
  21. This implementation is based on the fast heuristics to approximate
  22. the `k`-component structure of a graph [1]_. Which, in turn, it is based on
  23. a fast approximation algorithm for finding good lower bounds of the number
  24. of node independent paths between two nodes [2]_.
  25. Parameters
  26. ----------
  27. G : NetworkX graph
  28. Undirected graph
  29. min_density : Float
  30. Density relaxation threshold. Default value 0.95
  31. Returns
  32. -------
  33. k_components : dict
  34. Dictionary with connectivity level `k` as key and a list of
  35. sets of nodes that form a k-component of level `k` as values.
  36. Raises
  37. ------
  38. NetworkXNotImplemented
  39. If G is directed.
  40. Examples
  41. --------
  42. >>> # Petersen graph has 10 nodes and it is triconnected, thus all
  43. >>> # nodes are in a single component on all three connectivity levels
  44. >>> from networkx.algorithms import approximation as apxa
  45. >>> G = nx.petersen_graph()
  46. >>> k_components = apxa.k_components(G)
  47. Notes
  48. -----
  49. The logic of the approximation algorithm for computing the `k`-component
  50. structure [1]_ is based on repeatedly applying simple and fast algorithms
  51. for `k`-cores and biconnected components in order to narrow down the
  52. number of pairs of nodes over which we have to compute White and Newman's
  53. approximation algorithm for finding node independent paths [2]_. More
  54. formally, this algorithm is based on Whitney's theorem, which states
  55. an inclusion relation among node connectivity, edge connectivity, and
  56. minimum degree for any graph G. This theorem implies that every
  57. `k`-component is nested inside a `k`-edge-component, which in turn,
  58. is contained in a `k`-core. Thus, this algorithm computes node independent
  59. paths among pairs of nodes in each biconnected part of each `k`-core,
  60. and repeats this procedure for each `k` from 3 to the maximal core number
  61. of a node in the input graph.
  62. Because, in practice, many nodes of the core of level `k` inside a
  63. bicomponent actually are part of a component of level k, the auxiliary
  64. graph needed for the algorithm is likely to be very dense. Thus, we use
  65. a complement graph data structure (see `AntiGraph`) to save memory.
  66. AntiGraph only stores information of the edges that are *not* present
  67. in the actual auxiliary graph. When applying algorithms to this
  68. complement graph data structure, it behaves as if it were the dense
  69. version.
  70. See also
  71. --------
  72. k_components
  73. References
  74. ----------
  75. .. [1] Torrents, J. and F. Ferraro (2015) Structural Cohesion:
  76. Visualization and Heuristics for Fast Computation.
  77. https://arxiv.org/pdf/1503.04476v1
  78. .. [2] White, Douglas R., and Mark Newman (2001) A Fast Algorithm for
  79. Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
  80. https://www.santafe.edu/research/results/working-papers/fast-approximation-algorithms-for-finding-node-ind
  81. .. [3] Moody, J. and D. White (2003). Social cohesion and embeddedness:
  82. A hierarchical conception of social groups.
  83. American Sociological Review 68(1), 103--28.
  84. https://doi.org/10.2307/3088904
  85. """
  86. # Dictionary with connectivity level (k) as keys and a list of
  87. # sets of nodes that form a k-component as values
  88. k_components = defaultdict(list)
  89. # make a few functions local for speed
  90. node_connectivity = local_node_connectivity
  91. k_core = nx.k_core
  92. core_number = nx.core_number
  93. biconnected_components = nx.biconnected_components
  94. combinations = itertools.combinations
  95. # Exact solution for k = {1,2}
  96. # There is a linear time algorithm for triconnectivity, if we had an
  97. # implementation available we could start from k = 4.
  98. for component in nx.connected_components(G):
  99. # isolated nodes have connectivity 0
  100. comp = set(component)
  101. if len(comp) > 1:
  102. k_components[1].append(comp)
  103. for bicomponent in nx.biconnected_components(G):
  104. # avoid considering dyads as bicomponents
  105. bicomp = set(bicomponent)
  106. if len(bicomp) > 2:
  107. k_components[2].append(bicomp)
  108. # There is no k-component of k > maximum core number
  109. # \kappa(G) <= \lambda(G) <= \delta(G)
  110. g_cnumber = core_number(G)
  111. max_core = max(g_cnumber.values())
  112. for k in range(3, max_core + 1):
  113. C = k_core(G, k, core_number=g_cnumber)
  114. for nodes in biconnected_components(C):
  115. # Build a subgraph SG induced by the nodes that are part of
  116. # each biconnected component of the k-core subgraph C.
  117. if len(nodes) < k:
  118. continue
  119. SG = G.subgraph(nodes)
  120. # Build auxiliary graph
  121. H = _AntiGraph()
  122. H.add_nodes_from(SG.nodes())
  123. for u, v in combinations(SG, 2):
  124. K = node_connectivity(SG, u, v, cutoff=k)
  125. if k > K:
  126. H.add_edge(u, v)
  127. for h_nodes in biconnected_components(H):
  128. if len(h_nodes) <= k:
  129. continue
  130. SH = H.subgraph(h_nodes)
  131. for Gc in _cliques_heuristic(SG, SH, k, min_density):
  132. for k_nodes in biconnected_components(Gc):
  133. Gk = nx.k_core(SG.subgraph(k_nodes), k)
  134. if len(Gk) <= k:
  135. continue
  136. k_components[k].append(set(Gk))
  137. return k_components
  138. def _cliques_heuristic(G, H, k, min_density):
  139. h_cnumber = nx.core_number(H)
  140. for i, c_value in enumerate(sorted(set(h_cnumber.values()), reverse=True)):
  141. cands = {n for n, c in h_cnumber.items() if c == c_value}
  142. # Skip checking for overlap for the highest core value
  143. if i == 0:
  144. overlap = False
  145. else:
  146. overlap = set.intersection(
  147. *[{x for x in H[n] if x not in cands} for n in cands]
  148. )
  149. if overlap and len(overlap) < k:
  150. SH = H.subgraph(cands | overlap)
  151. else:
  152. SH = H.subgraph(cands)
  153. sh_cnumber = nx.core_number(SH)
  154. SG = nx.k_core(G.subgraph(SH), k)
  155. while not (_same(sh_cnumber) and nx.density(SH) >= min_density):
  156. # This subgraph must be writable => .copy()
  157. SH = H.subgraph(SG).copy()
  158. if len(SH) <= k:
  159. break
  160. sh_cnumber = nx.core_number(SH)
  161. sh_deg = dict(SH.degree())
  162. min_deg = min(sh_deg.values())
  163. SH.remove_nodes_from(n for n, d in sh_deg.items() if d == min_deg)
  164. SG = nx.k_core(G.subgraph(SH), k)
  165. else:
  166. yield SG
  167. def _same(measure, tol=0):
  168. vals = set(measure.values())
  169. if (max(vals) - min(vals)) <= tol:
  170. return True
  171. return False
  172. class _AntiGraph(nx.Graph):
  173. """
  174. Class for complement graphs.
  175. The main goal is to be able to work with big and dense graphs with
  176. a low memory footprint.
  177. In this class you add the edges that *do not exist* in the dense graph,
  178. the report methods of the class return the neighbors, the edges and
  179. the degree as if it was the dense graph. Thus it's possible to use
  180. an instance of this class with some of NetworkX functions. In this
  181. case we only use k-core, connected_components, and biconnected_components.
  182. """
  183. all_edge_dict = {"weight": 1}
  184. def single_edge_dict(self):
  185. return self.all_edge_dict
  186. edge_attr_dict_factory = single_edge_dict # type: ignore[assignment]
  187. def __getitem__(self, n):
  188. """Returns a dict of neighbors of node n in the dense graph.
  189. Parameters
  190. ----------
  191. n : node
  192. A node in the graph.
  193. Returns
  194. -------
  195. adj_dict : dictionary
  196. The adjacency dictionary for nodes connected to n.
  197. """
  198. all_edge_dict = self.all_edge_dict
  199. return {
  200. node: all_edge_dict for node in set(self._adj) - set(self._adj[n]) - {n}
  201. }
  202. def neighbors(self, n):
  203. """Returns an iterator over all neighbors of node n in the
  204. dense graph.
  205. """
  206. try:
  207. return iter(set(self._adj) - set(self._adj[n]) - {n})
  208. except KeyError as err:
  209. raise NetworkXError(f"The node {n} is not in the graph.") from err
  210. class AntiAtlasView(Mapping):
  211. """An adjacency inner dict for AntiGraph"""
  212. def __init__(self, graph, node):
  213. self._graph = graph
  214. self._atlas = graph._adj[node]
  215. self._node = node
  216. def __len__(self):
  217. return len(self._graph) - len(self._atlas) - 1
  218. def __iter__(self):
  219. return (n for n in self._graph if n not in self._atlas and n != self._node)
  220. def __getitem__(self, nbr):
  221. nbrs = set(self._graph._adj) - set(self._atlas) - {self._node}
  222. if nbr in nbrs:
  223. return self._graph.all_edge_dict
  224. raise KeyError(nbr)
  225. class AntiAdjacencyView(AntiAtlasView):
  226. """An adjacency outer dict for AntiGraph"""
  227. def __init__(self, graph):
  228. self._graph = graph
  229. self._atlas = graph._adj
  230. def __len__(self):
  231. return len(self._atlas)
  232. def __iter__(self):
  233. return iter(self._graph)
  234. def __getitem__(self, node):
  235. if node not in self._graph:
  236. raise KeyError(node)
  237. return self._graph.AntiAtlasView(self._graph, node)
  238. @cached_property
  239. def adj(self):
  240. return self.AntiAdjacencyView(self)
  241. def subgraph(self, nodes):
  242. """This subgraph method returns a full AntiGraph. Not a View"""
  243. nodes = set(nodes)
  244. G = _AntiGraph()
  245. G.add_nodes_from(nodes)
  246. for n in G:
  247. Gnbrs = G.adjlist_inner_dict_factory()
  248. G._adj[n] = Gnbrs
  249. for nbr, d in self._adj[n].items():
  250. if nbr in G._adj:
  251. Gnbrs[nbr] = d
  252. G._adj[nbr][n] = d
  253. G.graph = self.graph
  254. return G
  255. class AntiDegreeView(nx.reportviews.DegreeView):
  256. def __iter__(self):
  257. all_nodes = set(self._succ)
  258. for n in self._nodes:
  259. nbrs = all_nodes - set(self._succ[n]) - {n}
  260. yield (n, len(nbrs))
  261. def __getitem__(self, n):
  262. nbrs = set(self._succ) - set(self._succ[n]) - {n}
  263. # AntiGraph is a ThinGraph so all edges have weight 1
  264. return len(nbrs) + (n in nbrs)
  265. @cached_property
  266. def degree(self):
  267. """Returns an iterator for (node, degree) and degree for single node.
  268. The node degree is the number of edges adjacent to the node.
  269. Parameters
  270. ----------
  271. nbunch : iterable container, optional (default=all nodes)
  272. A container of nodes. The container will be iterated
  273. through once.
  274. weight : string or None, optional (default=None)
  275. The edge attribute that holds the numerical value used
  276. as a weight. If None, then each edge has weight 1.
  277. The degree is the sum of the edge weights adjacent to the node.
  278. Returns
  279. -------
  280. deg:
  281. Degree of the node, if a single node is passed as argument.
  282. nd_iter : an iterator
  283. The iterator returns two-tuples of (node, degree).
  284. See Also
  285. --------
  286. degree
  287. Examples
  288. --------
  289. >>> G = nx.path_graph(4)
  290. >>> G.degree(0) # node 0 with degree 1
  291. 1
  292. >>> list(G.degree([0, 1]))
  293. [(0, 1), (1, 2)]
  294. """
  295. return self.AntiDegreeView(self)
  296. def adjacency(self):
  297. """Returns an iterator of (node, adjacency set) tuples for all nodes
  298. in the dense graph.
  299. This is the fastest way to look at every edge.
  300. For directed graphs, only outgoing adjacencies are included.
  301. Returns
  302. -------
  303. adj_iter : iterator
  304. An iterator of (node, adjacency set) for all nodes in
  305. the graph.
  306. """
  307. for n in self._adj:
  308. yield (n, set(self._adj) - set(self._adj[n]) - {n})