mapped_queue.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. """Priority queue class with updatable priorities."""
  2. import heapq
  3. __all__ = ["MappedQueue"]
  4. class _HeapElement:
  5. """This proxy class separates the heap element from its priority.
  6. The idea is that using a 2-tuple (priority, element) works
  7. for sorting, but not for dict lookup because priorities are
  8. often floating point values so round-off can mess up equality.
  9. So, we need inequalities to look at the priority (for sorting)
  10. and equality (and hash) to look at the element to enable
  11. updates to the priority.
  12. Unfortunately, this class can be tricky to work with if you forget that
  13. `__lt__` compares the priority while `__eq__` compares the element.
  14. In `greedy_modularity_communities()` the following code is
  15. used to check that two _HeapElements differ in either element or priority:
  16. if d_oldmax != row_max or d_oldmax.priority != row_max.priority:
  17. If the priorities are the same, this implementation uses the element
  18. as a tiebreaker. This provides compatibility with older systems that
  19. use tuples to combine priority and elements.
  20. """
  21. __slots__ = ["priority", "element", "_hash"]
  22. def __init__(self, priority, element):
  23. self.priority = priority
  24. self.element = element
  25. self._hash = hash(element)
  26. def __lt__(self, other):
  27. try:
  28. other_priority = other.priority
  29. except AttributeError:
  30. return self.priority < other
  31. # assume comparing to another _HeapElement
  32. if self.priority == other_priority:
  33. try:
  34. return self.element < other.element
  35. except TypeError as err:
  36. raise TypeError(
  37. "Consider using a tuple, with a priority value that can be compared."
  38. )
  39. return self.priority < other_priority
  40. def __gt__(self, other):
  41. try:
  42. other_priority = other.priority
  43. except AttributeError:
  44. return self.priority > other
  45. # assume comparing to another _HeapElement
  46. if self.priority == other_priority:
  47. try:
  48. return self.element > other.element
  49. except TypeError as err:
  50. raise TypeError(
  51. "Consider using a tuple, with a priority value that can be compared."
  52. )
  53. return self.priority > other_priority
  54. def __eq__(self, other):
  55. try:
  56. return self.element == other.element
  57. except AttributeError:
  58. return self.element == other
  59. def __hash__(self):
  60. return self._hash
  61. def __getitem__(self, indx):
  62. return self.priority if indx == 0 else self.element[indx - 1]
  63. def __iter__(self):
  64. yield self.priority
  65. try:
  66. yield from self.element
  67. except TypeError:
  68. yield self.element
  69. def __repr__(self):
  70. return f"_HeapElement({self.priority}, {self.element})"
  71. class MappedQueue:
  72. """The MappedQueue class implements a min-heap with removal and update-priority.
  73. The min heap uses heapq as well as custom written _siftup and _siftdown
  74. methods to allow the heap positions to be tracked by an additional dict
  75. keyed by element to position. The smallest element can be popped in O(1) time,
  76. new elements can be pushed in O(log n) time, and any element can be removed
  77. or updated in O(log n) time. The queue cannot contain duplicate elements
  78. and an attempt to push an element already in the queue will have no effect.
  79. MappedQueue complements the heapq package from the python standard
  80. library. While MappedQueue is designed for maximum compatibility with
  81. heapq, it adds element removal, lookup, and priority update.
  82. Parameters
  83. ----------
  84. data : dict or iterable
  85. Examples
  86. --------
  87. A `MappedQueue` can be created empty, or optionally, given a dictionary
  88. of initial elements and priorities. The methods `push`, `pop`,
  89. `remove`, and `update` operate on the queue.
  90. >>> colors_nm = {"red": 665, "blue": 470, "green": 550}
  91. >>> q = MappedQueue(colors_nm)
  92. >>> q.remove("red")
  93. >>> q.update("green", "violet", 400)
  94. >>> q.push("indigo", 425)
  95. True
  96. >>> [q.pop().element for i in range(len(q.heap))]
  97. ['violet', 'indigo', 'blue']
  98. A `MappedQueue` can also be initialized with a list or other iterable. The priority is assumed
  99. to be the sort order of the items in the list.
  100. >>> q = MappedQueue([916, 50, 4609, 493, 237])
  101. >>> q.remove(493)
  102. >>> q.update(237, 1117)
  103. >>> [q.pop() for i in range(len(q.heap))]
  104. [50, 916, 1117, 4609]
  105. An exception is raised if the elements are not comparable.
  106. >>> q = MappedQueue([100, "a"])
  107. Traceback (most recent call last):
  108. ...
  109. TypeError: '<' not supported between instances of 'int' and 'str'
  110. To avoid the exception, use a dictionary to assign priorities to the elements.
  111. >>> q = MappedQueue({100: 0, "a": 1})
  112. References
  113. ----------
  114. .. [1] Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2001).
  115. Introduction to algorithms second edition.
  116. .. [2] Knuth, D. E. (1997). The art of computer programming (Vol. 3).
  117. Pearson Education.
  118. """
  119. def __init__(self, data=None):
  120. """Priority queue class with updatable priorities."""
  121. if data is None:
  122. self.heap = []
  123. elif isinstance(data, dict):
  124. self.heap = [_HeapElement(v, k) for k, v in data.items()]
  125. else:
  126. self.heap = list(data)
  127. self.position = {}
  128. self._heapify()
  129. def _heapify(self):
  130. """Restore heap invariant and recalculate map."""
  131. heapq.heapify(self.heap)
  132. self.position = {elt: pos for pos, elt in enumerate(self.heap)}
  133. if len(self.heap) != len(self.position):
  134. raise AssertionError("Heap contains duplicate elements")
  135. def __len__(self):
  136. return len(self.heap)
  137. def push(self, elt, priority=None):
  138. """Add an element to the queue."""
  139. if priority is not None:
  140. elt = _HeapElement(priority, elt)
  141. # If element is already in queue, do nothing
  142. if elt in self.position:
  143. return False
  144. # Add element to heap and dict
  145. pos = len(self.heap)
  146. self.heap.append(elt)
  147. self.position[elt] = pos
  148. # Restore invariant by sifting down
  149. self._siftdown(0, pos)
  150. return True
  151. def pop(self):
  152. """Remove and return the smallest element in the queue."""
  153. # Remove smallest element
  154. elt = self.heap[0]
  155. del self.position[elt]
  156. # If elt is last item, remove and return
  157. if len(self.heap) == 1:
  158. self.heap.pop()
  159. return elt
  160. # Replace root with last element
  161. last = self.heap.pop()
  162. self.heap[0] = last
  163. self.position[last] = 0
  164. # Restore invariant by sifting up
  165. self._siftup(0)
  166. # Return smallest element
  167. return elt
  168. def update(self, elt, new, priority=None):
  169. """Replace an element in the queue with a new one."""
  170. if priority is not None:
  171. new = _HeapElement(priority, new)
  172. # Replace
  173. pos = self.position[elt]
  174. self.heap[pos] = new
  175. del self.position[elt]
  176. self.position[new] = pos
  177. # Restore invariant by sifting up
  178. self._siftup(pos)
  179. def remove(self, elt):
  180. """Remove an element from the queue."""
  181. # Find and remove element
  182. try:
  183. pos = self.position[elt]
  184. del self.position[elt]
  185. except KeyError:
  186. # Not in queue
  187. raise
  188. # If elt is last item, remove and return
  189. if pos == len(self.heap) - 1:
  190. self.heap.pop()
  191. return
  192. # Replace elt with last element
  193. last = self.heap.pop()
  194. self.heap[pos] = last
  195. self.position[last] = pos
  196. # Restore invariant by sifting up
  197. self._siftup(pos)
  198. def _siftup(self, pos):
  199. """Move smaller child up until hitting a leaf.
  200. Built to mimic code for heapq._siftup
  201. only updating position dict too.
  202. """
  203. heap, position = self.heap, self.position
  204. end_pos = len(heap)
  205. startpos = pos
  206. newitem = heap[pos]
  207. # Shift up the smaller child until hitting a leaf
  208. child_pos = (pos << 1) + 1 # start with leftmost child position
  209. while child_pos < end_pos:
  210. # Set child_pos to index of smaller child.
  211. child = heap[child_pos]
  212. right_pos = child_pos + 1
  213. if right_pos < end_pos:
  214. right = heap[right_pos]
  215. if not child < right:
  216. child = right
  217. child_pos = right_pos
  218. # Move the smaller child up.
  219. heap[pos] = child
  220. position[child] = pos
  221. pos = child_pos
  222. child_pos = (pos << 1) + 1
  223. # pos is a leaf position. Put newitem there, and bubble it up
  224. # to its final resting place (by sifting its parents down).
  225. while pos > 0:
  226. parent_pos = (pos - 1) >> 1
  227. parent = heap[parent_pos]
  228. if not newitem < parent:
  229. break
  230. heap[pos] = parent
  231. position[parent] = pos
  232. pos = parent_pos
  233. heap[pos] = newitem
  234. position[newitem] = pos
  235. def _siftdown(self, start_pos, pos):
  236. """Restore invariant. keep swapping with parent until smaller.
  237. Built to mimic code for heapq._siftdown
  238. only updating position dict too.
  239. """
  240. heap, position = self.heap, self.position
  241. newitem = heap[pos]
  242. # Follow the path to the root, moving parents down until finding a place
  243. # newitem fits.
  244. while pos > start_pos:
  245. parent_pos = (pos - 1) >> 1
  246. parent = heap[parent_pos]
  247. if not newitem < parent:
  248. break
  249. heap[pos] = parent
  250. position[parent] = pos
  251. pos = parent_pos
  252. heap[pos] = newitem
  253. position[newitem] = pos