plot_antigraph.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. """
  2. =========
  3. Antigraph
  4. =========
  5. Complement graph class for small footprint when working on dense graphs.
  6. This class allows you to add the edges that *do not exist* in the dense
  7. graph. However, when applying algorithms to this complement graph data
  8. structure, it behaves as if it were the dense version. So it can be used
  9. directly in several NetworkX algorithms.
  10. This subclass has only been tested for k-core, connected_components,
  11. and biconnected_components algorithms but might also work for other
  12. algorithms.
  13. """
  14. import matplotlib.pyplot as plt
  15. import networkx as nx
  16. from networkx import Graph
  17. class AntiGraph(Graph):
  18. """
  19. Class for complement graphs.
  20. The main goal is to be able to work with big and dense graphs with
  21. a low memory footprint.
  22. In this class you add the edges that *do not exist* in the dense graph,
  23. the report methods of the class return the neighbors, the edges and
  24. the degree as if it was the dense graph. Thus it's possible to use
  25. an instance of this class with some of NetworkX functions.
  26. """
  27. all_edge_dict = {"weight": 1}
  28. def single_edge_dict(self):
  29. return self.all_edge_dict
  30. edge_attr_dict_factory = single_edge_dict
  31. def __getitem__(self, n):
  32. """Return a dict of neighbors of node n in the dense graph.
  33. Parameters
  34. ----------
  35. n : node
  36. A node in the graph.
  37. Returns
  38. -------
  39. adj_dict : dictionary
  40. The adjacency dictionary for nodes connected to n.
  41. """
  42. return {
  43. node: self.all_edge_dict for node in set(self.adj) - set(self.adj[n]) - {n}
  44. }
  45. def neighbors(self, n):
  46. """Return an iterator over all neighbors of node n in the
  47. dense graph.
  48. """
  49. try:
  50. return iter(set(self.adj) - set(self.adj[n]) - {n})
  51. except KeyError as err:
  52. raise nx.NetworkXError(f"The node {n} is not in the graph.") from err
  53. def degree(self, nbunch=None, weight=None):
  54. """Return an iterator for (node, degree) in the dense graph.
  55. The node degree is the number of edges adjacent to the node.
  56. Parameters
  57. ----------
  58. nbunch : iterable container, optional (default=all nodes)
  59. A container of nodes. The container will be iterated
  60. through once.
  61. weight : string or None, optional (default=None)
  62. The edge attribute that holds the numerical value used
  63. as a weight. If None, then each edge has weight 1.
  64. The degree is the sum of the edge weights adjacent to the node.
  65. Returns
  66. -------
  67. nd_iter : iterator
  68. The iterator returns two-tuples of (node, degree).
  69. See Also
  70. --------
  71. degree
  72. Examples
  73. --------
  74. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  75. >>> G.degree(0) # node 0 with degree 1
  76. 1
  77. >>> list(G.degree([0, 1]))
  78. [(0, 1), (1, 2)]
  79. """
  80. if nbunch is None:
  81. nodes_nbrs = (
  82. (
  83. n,
  84. {
  85. v: self.all_edge_dict
  86. for v in set(self.adj) - set(self.adj[n]) - {n}
  87. },
  88. )
  89. for n in self.nodes()
  90. )
  91. elif nbunch in self:
  92. nbrs = set(self.nodes()) - set(self.adj[nbunch]) - {nbunch}
  93. return len(nbrs)
  94. else:
  95. nodes_nbrs = (
  96. (
  97. n,
  98. {
  99. v: self.all_edge_dict
  100. for v in set(self.nodes()) - set(self.adj[n]) - {n}
  101. },
  102. )
  103. for n in self.nbunch_iter(nbunch)
  104. )
  105. if weight is None:
  106. return ((n, len(nbrs)) for n, nbrs in nodes_nbrs)
  107. else:
  108. # AntiGraph is a ThinGraph so all edges have weight 1
  109. return (
  110. (n, sum((nbrs[nbr].get(weight, 1)) for nbr in nbrs))
  111. for n, nbrs in nodes_nbrs
  112. )
  113. def adjacency(self):
  114. """Return an iterator of (node, adjacency set) tuples for all nodes
  115. in the dense graph.
  116. This is the fastest way to look at every edge.
  117. For directed graphs, only outgoing adjacencies are included.
  118. Returns
  119. -------
  120. adj_iter : iterator
  121. An iterator of (node, adjacency set) for all nodes in
  122. the graph.
  123. """
  124. nodes = set(self.adj)
  125. for n, nbrs in self.adj.items():
  126. yield (n, nodes - set(nbrs) - {n})
  127. # Build several pairs of graphs, a regular graph
  128. # and the AntiGraph of it's complement, which behaves
  129. # as if it were the original graph.
  130. Gnp = nx.gnp_random_graph(20, 0.8, seed=42)
  131. Anp = AntiGraph(nx.complement(Gnp))
  132. Gd = nx.davis_southern_women_graph()
  133. Ad = AntiGraph(nx.complement(Gd))
  134. Gk = nx.karate_club_graph()
  135. Ak = AntiGraph(nx.complement(Gk))
  136. pairs = [(Gnp, Anp), (Gd, Ad), (Gk, Ak)]
  137. # test connected components
  138. for G, A in pairs:
  139. gc = [set(c) for c in nx.connected_components(G)]
  140. ac = [set(c) for c in nx.connected_components(A)]
  141. for comp in ac:
  142. assert comp in gc
  143. # test biconnected components
  144. for G, A in pairs:
  145. gc = [set(c) for c in nx.biconnected_components(G)]
  146. ac = [set(c) for c in nx.biconnected_components(A)]
  147. for comp in ac:
  148. assert comp in gc
  149. # test degree
  150. for G, A in pairs:
  151. node = list(G.nodes())[0]
  152. nodes = list(G.nodes())[1:4]
  153. assert G.degree(node) == A.degree(node)
  154. assert sum(d for n, d in G.degree()) == sum(d for n, d in A.degree())
  155. # AntiGraph is a ThinGraph, so all the weights are 1
  156. assert sum(d for n, d in A.degree()) == sum(d for n, d in A.degree(weight="weight"))
  157. assert sum(d for n, d in G.degree(nodes)) == sum(d for n, d in A.degree(nodes))
  158. pos = nx.spring_layout(G, seed=268) # Seed for reproducible layout
  159. nx.draw(Gnp, pos=pos)
  160. plt.show()