plot_antigraph.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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. # Author: Jordi Torrents <jtorrents@milnou.net>
  15. # Copyright (C) 2015-2019 by
  16. # Jordi Torrents <jtorrents@milnou.net>
  17. # All rights reserved.
  18. # BSD license.
  19. import networkx as nx
  20. from networkx.exception import NetworkXError
  21. import matplotlib.pyplot as plt
  22. __all__ = ['AntiGraph']
  23. class AntiGraph(nx.Graph):
  24. """
  25. Class for complement graphs.
  26. The main goal is to be able to work with big and dense graphs with
  27. a low memory footprint.
  28. In this class you add the edges that *do not exist* in the dense graph,
  29. the report methods of the class return the neighbors, the edges and
  30. the degree as if it was the dense graph. Thus it's possible to use
  31. an instance of this class with some of NetworkX functions.
  32. """
  33. all_edge_dict = {'weight': 1}
  34. def single_edge_dict(self):
  35. return self.all_edge_dict
  36. edge_attr_dict_factory = single_edge_dict
  37. def __getitem__(self, n):
  38. """Return a dict of neighbors of node n in the dense graph.
  39. Parameters
  40. ----------
  41. n : node
  42. A node in the graph.
  43. Returns
  44. -------
  45. adj_dict : dictionary
  46. The adjacency dictionary for nodes connected to n.
  47. """
  48. return dict((node, self.all_edge_dict) for node in
  49. set(self.adj) - set(self.adj[n]) - set([n]))
  50. def neighbors(self, n):
  51. """Return an iterator over all neighbors of node n in the
  52. dense graph.
  53. """
  54. try:
  55. return iter(set(self.adj) - set(self.adj[n]) - set([n]))
  56. except KeyError:
  57. raise NetworkXError("The node %s is not in the graph." % (n,))
  58. def degree(self, nbunch=None, weight=None):
  59. """Return an iterator for (node, degree) in the dense graph.
  60. The node degree is the number of edges adjacent to the node.
  61. Parameters
  62. ----------
  63. nbunch : iterable container, optional (default=all nodes)
  64. A container of nodes. The container will be iterated
  65. through once.
  66. weight : string or None, optional (default=None)
  67. The edge attribute that holds the numerical value used
  68. as a weight. If None, then each edge has weight 1.
  69. The degree is the sum of the edge weights adjacent to the node.
  70. Returns
  71. -------
  72. nd_iter : iterator
  73. The iterator returns two-tuples of (node, degree).
  74. See Also
  75. --------
  76. degree
  77. Examples
  78. --------
  79. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  80. >>> list(G.degree(0)) # node 0 with degree 1
  81. [(0, 1)]
  82. >>> list(G.degree([0, 1]))
  83. [(0, 1), (1, 2)]
  84. """
  85. if nbunch is None:
  86. nodes_nbrs = ((n, {v: self.all_edge_dict for v in
  87. set(self.adj) - set(self.adj[n]) - set([n])})
  88. for n in self.nodes())
  89. elif nbunch in self:
  90. nbrs = set(self.nodes()) - set(self.adj[nbunch]) - {nbunch}
  91. return len(nbrs)
  92. else:
  93. nodes_nbrs = ((n, {v: self.all_edge_dict for v in
  94. set(self.nodes()) - set(self.adj[n]) - set([n])})
  95. for n in self.nbunch_iter(nbunch))
  96. if weight is None:
  97. return ((n, len(nbrs)) for n, nbrs in nodes_nbrs)
  98. else:
  99. # AntiGraph is a ThinGraph so all edges have weight 1
  100. return ((n, sum((nbrs[nbr].get(weight, 1)) for nbr in nbrs))
  101. for n, nbrs in nodes_nbrs)
  102. def adjacency_iter(self):
  103. """Return an iterator of (node, adjacency set) tuples for all nodes
  104. in the dense graph.
  105. This is the fastest way to look at every edge.
  106. For directed graphs, only outgoing adjacencies are included.
  107. Returns
  108. -------
  109. adj_iter : iterator
  110. An iterator of (node, adjacency set) for all nodes in
  111. the graph.
  112. """
  113. for n in self.adj:
  114. yield (n, set(self.adj) - set(self.adj[n]) - set([n]))
  115. if __name__ == '__main__':
  116. # Build several pairs of graphs, a regular graph
  117. # and the AntiGraph of it's complement, which behaves
  118. # as if it were the original graph.
  119. Gnp = nx.gnp_random_graph(20, 0.8, seed=42)
  120. Anp = AntiGraph(nx.complement(Gnp))
  121. Gd = nx.davis_southern_women_graph()
  122. Ad = AntiGraph(nx.complement(Gd))
  123. Gk = nx.karate_club_graph()
  124. Ak = AntiGraph(nx.complement(Gk))
  125. pairs = [(Gnp, Anp), (Gd, Ad), (Gk, Ak)]
  126. # test connected components
  127. for G, A in pairs:
  128. gc = [set(c) for c in nx.connected_components(G)]
  129. ac = [set(c) for c in nx.connected_components(A)]
  130. for comp in ac:
  131. assert comp in gc
  132. # test biconnected components
  133. for G, A in pairs:
  134. gc = [set(c) for c in nx.biconnected_components(G)]
  135. ac = [set(c) for c in nx.biconnected_components(A)]
  136. for comp in ac:
  137. assert comp in gc
  138. # test degree
  139. for G, A in pairs:
  140. node = list(G.nodes())[0]
  141. nodes = list(G.nodes())[1:4]
  142. assert G.degree(node) == A.degree(node)
  143. assert sum(pen_weight for n, pen_weight in G.degree()) == sum(pen_weight for n, pen_weight in A.degree())
  144. # AntiGraph is a ThinGraph, so all the weights are 1
  145. assert sum(pen_weight for n, pen_weight in A.degree()) == sum(pen_weight for n, pen_weight in A.degree(weight='weight'))
  146. assert sum(pen_weight for n, pen_weight in G.degree(nodes)) == sum(pen_weight for n, pen_weight in A.degree(nodes))
  147. nx.draw(Gnp)
  148. plt.show()