graphlib.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. __all__ = ["TopologicalSorter", "CycleError"]
  2. _NODE_OUT = -1
  3. _NODE_DONE = -2
  4. class _NodeInfo:
  5. __slots__ = "node", "npredecessors", "successors"
  6. def __init__(self, node):
  7. # The node this class is augmenting.
  8. self.node = node
  9. # Number of predecessors, generally >= 0. When this value falls to 0,
  10. # and is returned by get_ready(), this is set to _NODE_OUT and when the
  11. # node is marked done by a call to done(), set to _NODE_DONE.
  12. self.npredecessors = 0
  13. # List of successor nodes. The list can contain duplicated elements as
  14. # long as they're all reflected in the successor's npredecessors attribute.
  15. self.successors = []
  16. class CycleError(ValueError):
  17. """Subclass of ValueError raised by TopologicalSorter.prepare if cycles
  18. exist in the working graph.
  19. If multiple cycles exist, only one undefined choice among them will be reported
  20. and included in the exception. The detected cycle can be accessed via the second
  21. element in the *args* attribute of the exception instance and consists in a list
  22. of nodes, such that each node is, in the graph, an immediate predecessor of the
  23. next node in the list. In the reported list, the first and the last node will be
  24. the same, to make it clear that it is cyclic.
  25. """
  26. pass
  27. class TopologicalSorter:
  28. """Provides functionality to topologically sort a graph of hashable nodes"""
  29. def __init__(self, graph=None):
  30. self._node2info = {}
  31. self._ready_nodes = None
  32. self._npassedout = 0
  33. self._nfinished = 0
  34. if graph is not None:
  35. for node, predecessors in graph.items():
  36. self.add(node, *predecessors)
  37. def _get_nodeinfo(self, node):
  38. if (result := self._node2info.get(node)) is None:
  39. self._node2info[node] = result = _NodeInfo(node)
  40. return result
  41. def add(self, node, *predecessors):
  42. """Add a new node and its predecessors to the graph.
  43. Both the *node* and all elements in *predecessors* must be hashable.
  44. If called multiple times with the same node argument, the set of dependencies
  45. will be the union of all dependencies passed in.
  46. It is possible to add a node with no dependencies (*predecessors* is not provided)
  47. as well as provide a dependency twice. If a node that has not been provided before
  48. is included among *predecessors* it will be automatically added to the graph with
  49. no predecessors of its own.
  50. Raises ValueError if called after "prepare".
  51. """
  52. if self._ready_nodes is not None:
  53. raise ValueError("Nodes cannot be added after a call to prepare()")
  54. # Create the node -> predecessor edges
  55. nodeinfo = self._get_nodeinfo(node)
  56. nodeinfo.npredecessors += len(predecessors)
  57. # Create the predecessor -> node edges
  58. for pred in predecessors:
  59. pred_info = self._get_nodeinfo(pred)
  60. pred_info.successors.append(node)
  61. def prepare(self):
  62. """Mark the graph as finished and check for cycles in the graph.
  63. If any cycle is detected, "CycleError" will be raised, but "get_ready" can
  64. still be used to obtain as many nodes as possible until cycles block more
  65. progress. After a call to this function, the graph cannot be modified and
  66. therefore no more nodes can be added using "add".
  67. """
  68. if self._ready_nodes is not None:
  69. raise ValueError("cannot prepare() more than once")
  70. self._ready_nodes = [
  71. i.node for i in self._node2info.values() if i.npredecessors == 0
  72. ]
  73. # ready_nodes is set before we look for cycles on purpose:
  74. # if the user wants to catch the CycleError, that's fine,
  75. # they can continue using the instance to grab as many
  76. # nodes as possible before cycles block more progress
  77. cycle = self._find_cycle()
  78. if cycle:
  79. raise CycleError(f"nodes are in a cycle", cycle)
  80. def get_ready(self):
  81. """Return a tuple of all the nodes that are ready.
  82. Initially it returns all nodes with no predecessors; once those are marked
  83. as processed by calling "done", further calls will return all new nodes that
  84. have all their predecessors already processed. Once no more progress can be made,
  85. empty tuples are returned.
  86. Raises ValueError if called without calling "prepare" previously.
  87. """
  88. if self._ready_nodes is None:
  89. raise ValueError("prepare() must be called first")
  90. # Get the nodes that are ready and mark them
  91. result = tuple(self._ready_nodes)
  92. n2i = self._node2info
  93. for node in result:
  94. n2i[node].npredecessors = _NODE_OUT
  95. # Clean the list of nodes that are ready and update
  96. # the counter of nodes that we have returned.
  97. self._ready_nodes.clear()
  98. self._npassedout += len(result)
  99. return result
  100. def is_active(self):
  101. """Return ``True`` if more progress can be made and ``False`` otherwise.
  102. Progress can be made if cycles do not block the resolution and either there
  103. are still nodes ready that haven't yet been returned by "get_ready" or the
  104. number of nodes marked "done" is less than the number that have been returned
  105. by "get_ready".
  106. Raises ValueError if called without calling "prepare" previously.
  107. """
  108. if self._ready_nodes is None:
  109. raise ValueError("prepare() must be called first")
  110. return self._nfinished < self._npassedout or bool(self._ready_nodes)
  111. def __bool__(self):
  112. return self.is_active()
  113. def done(self, *nodes):
  114. """Marks a set of nodes returned by "get_ready" as processed.
  115. This method unblocks any successor of each node in *nodes* for being returned
  116. in the future by a call to "get_ready".
  117. Raises :exec:`ValueError` if any node in *nodes* has already been marked as
  118. processed by a previous call to this method, if a node was not added to the
  119. graph by using "add" or if called without calling "prepare" previously or if
  120. node has not yet been returned by "get_ready".
  121. """
  122. if self._ready_nodes is None:
  123. raise ValueError("prepare() must be called first")
  124. n2i = self._node2info
  125. for node in nodes:
  126. # Check if we know about this node (it was added previously using add()
  127. if (nodeinfo := n2i.get(node)) is None:
  128. raise ValueError(f"node {node!r} was not added using add()")
  129. # If the node has not being returned (marked as ready) previously, inform the user.
  130. stat = nodeinfo.npredecessors
  131. if stat != _NODE_OUT:
  132. if stat >= 0:
  133. raise ValueError(
  134. f"node {node!r} was not passed out (still not ready)"
  135. )
  136. elif stat == _NODE_DONE:
  137. raise ValueError(f"node {node!r} was already marked done")
  138. else:
  139. assert False, f"node {node!r}: unknown status {stat}"
  140. # Mark the node as processed
  141. nodeinfo.npredecessors = _NODE_DONE
  142. # Go to all the successors and reduce the number of predecessors, collecting all the ones
  143. # that are ready to be returned in the next get_ready() call.
  144. for successor in nodeinfo.successors:
  145. successor_info = n2i[successor]
  146. successor_info.npredecessors -= 1
  147. if successor_info.npredecessors == 0:
  148. self._ready_nodes.append(successor)
  149. self._nfinished += 1
  150. def _find_cycle(self):
  151. n2i = self._node2info
  152. stack = []
  153. itstack = []
  154. seen = set()
  155. node2stacki = {}
  156. for node in n2i:
  157. if node in seen:
  158. continue
  159. while True:
  160. if node in seen:
  161. # If we have seen already the node and is in the
  162. # current stack we have found a cycle.
  163. if node in node2stacki:
  164. return stack[node2stacki[node] :] + [node]
  165. # else go on to get next successor
  166. else:
  167. seen.add(node)
  168. itstack.append(iter(n2i[node].successors).__next__)
  169. node2stacki[node] = len(stack)
  170. stack.append(node)
  171. # Backtrack to the topmost stack entry with
  172. # at least another successor.
  173. while stack:
  174. try:
  175. node = itstack[-1]()
  176. break
  177. except StopIteration:
  178. del node2stacki[stack.pop()]
  179. itstack.pop()
  180. else:
  181. break
  182. return None
  183. def static_order(self):
  184. """Returns an iterable of nodes in a topological order.
  185. The particular order that is returned may depend on the specific
  186. order in which the items were inserted in the graph.
  187. Using this method does not require to call "prepare" or "done". If any
  188. cycle is detected, :exc:`CycleError` will be raised.
  189. """
  190. self.prepare()
  191. while self.is_active():
  192. node_group = self.get_ready()
  193. yield from node_group
  194. self.done(*node_group)