iterutils.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import heapq
  16. from itertools import islice
  17. from typing import (
  18. Collection,
  19. Dict,
  20. Generator,
  21. Iterable,
  22. Iterator,
  23. Mapping,
  24. Set,
  25. Sized,
  26. Tuple,
  27. TypeVar,
  28. )
  29. from typing_extensions import Protocol
  30. T = TypeVar("T")
  31. S = TypeVar("S", bound="_SelfSlice")
  32. class _SelfSlice(Sized, Protocol):
  33. """A helper protocol that matches types where taking a slice results in the
  34. same type being returned.
  35. This is more specific than `Sequence`, which allows another `Sequence` to be
  36. returned.
  37. """
  38. def __getitem__(self: S, i: slice) -> S:
  39. ...
  40. def batch_iter(iterable: Iterable[T], size: int) -> Iterator[Tuple[T, ...]]:
  41. """batch an iterable up into tuples with a maximum size
  42. Args:
  43. iterable: the iterable to slice
  44. size: the maximum batch size
  45. Returns:
  46. an iterator over the chunks
  47. """
  48. # make sure we can deal with iterables like lists too
  49. sourceiter = iter(iterable)
  50. # call islice until it returns an empty tuple
  51. return iter(lambda: tuple(islice(sourceiter, size)), ())
  52. def chunk_seq(iseq: S, maxlen: int) -> Iterator[S]:
  53. """Split the given sequence into chunks of the given size
  54. The last chunk may be shorter than the given size.
  55. If the input is empty, no chunks are returned.
  56. """
  57. return (iseq[i : i + maxlen] for i in range(0, len(iseq), maxlen))
  58. def sorted_topologically(
  59. nodes: Iterable[T],
  60. graph: Mapping[T, Collection[T]],
  61. ) -> Generator[T, None, None]:
  62. """Given a set of nodes and a graph, yield the nodes in toplogical order.
  63. For example `sorted_topologically([1, 2], {1: [2]})` will yield `2, 1`.
  64. """
  65. # This is implemented by Kahn's algorithm.
  66. degree_map = {node: 0 for node in nodes}
  67. reverse_graph: Dict[T, Set[T]] = {}
  68. for node, edges in graph.items():
  69. if node not in degree_map:
  70. continue
  71. for edge in set(edges):
  72. if edge in degree_map:
  73. degree_map[node] += 1
  74. reverse_graph.setdefault(edge, set()).add(node)
  75. reverse_graph.setdefault(node, set())
  76. zero_degree = [node for node, degree in degree_map.items() if degree == 0]
  77. heapq.heapify(zero_degree)
  78. while zero_degree:
  79. node = heapq.heappop(zero_degree)
  80. yield node
  81. for edge in reverse_graph.get(node, []):
  82. if edge in degree_map:
  83. degree_map[edge] -= 1
  84. if degree_map[edge] == 0:
  85. heapq.heappush(zero_degree, edge)