Easier and more self documenting patterns for loading/saving Persistent
[python_utils.git] / iter_utils.py
1 #!/usr/bin/env python3
2
3 # © Copyright 2021-2022, Scott Gasch
4
5 """A collection if :class:`Iterator` subclasses that can be composed
6 with another iterator and provide extra functionality.  e.g.
7
8     + :class:`PeekingIterator`
9     + :class:`PushbackIterator`
10     + :class:`SamplingIterator`
11
12 """
13
14 import random
15 from collections.abc import Iterator
16 from typing import Any, List, Optional
17
18
19 class PeekingIterator(Iterator):
20     """An iterator that lets you :meth:`peek` at the next item on deck.
21     Returns None when there is no next item (i.e. when
22     :meth:`__next__` will produce a StopIteration exception).
23
24     >>> p = PeekingIterator(iter(range(3)))
25     >>> p.__next__()
26     0
27     >>> p.peek()
28     1
29     >>> p.peek()
30     1
31     >>> p.__next__()
32     1
33     >>> p.__next__()
34     2
35     >>> p.peek() == None
36     True
37     >>> p.__next__()
38     Traceback (most recent call last):
39       ...
40     StopIteration
41
42     """
43
44     def __init__(self, source_iter: Iterator):
45         self.source_iter = source_iter
46         self.on_deck: List[Any] = []
47
48     def __iter__(self) -> Iterator:
49         return self
50
51     def __next__(self) -> Any:
52         if len(self.on_deck) > 0:
53             return self.on_deck.pop()
54         else:
55             item = self.source_iter.__next__()
56             return item
57
58     def peek(self) -> Optional[Any]:
59         if len(self.on_deck) > 0:
60             return self.on_deck[0]
61         try:
62             item = self.source_iter.__next__()
63             self.on_deck.append(item)
64             return self.peek()
65         except StopIteration:
66             return None
67
68
69 class PushbackIterator(Iterator):
70     """An iterator that allows you to push items back
71     onto the front of the sequence.  e.g.
72
73     >>> i = PushbackIterator(iter(range(3)))
74     >>> i.__next__()
75     0
76     >>> i.push_back(99)
77     >>> i.push_back(98)
78     >>> i.__next__()
79     98
80     >>> i.__next__()
81     99
82     >>> i.__next__()
83     1
84     >>> i.__next__()
85     2
86     >>> i.push_back(100)
87     >>> i.__next__()
88     100
89     >>> i.__next__()
90     Traceback (most recent call last):
91       ...
92     StopIteration
93     """
94
95     def __init__(self, source_iter: Iterator):
96         self.source_iter = source_iter
97         self.pushed_back: List[Any] = []
98
99     def __iter__(self) -> Iterator:
100         return self
101
102     def __next__(self) -> Any:
103         if len(self.pushed_back) > 0:
104             return self.pushed_back.pop()
105         return self.source_iter.__next__()
106
107     def push_back(self, item: Any):
108         self.pushed_back.append(item)
109
110
111 class SamplingIterator(Iterator):
112     """An iterator that simply echoes what source_iter produces but also
113     collects a random sample (of size sample_size) of the stream that can
114     be queried at any time.
115
116     .. note::
117         Until sample_size elements have been seen the sample will be
118         less than sample_size elements in length.
119
120     .. note::
121         If sample_size is > len(source_iter) then it will produce a
122         copy of source_iter.
123
124     >>> import collections
125     >>> import random
126
127     >>> random.seed(22)
128     >>> s = SamplingIterator(iter(range(100)), 10)
129     >>> s.__next__()
130     0
131
132     >>> s.__next__()
133     1
134
135     >>> s.get_sample()
136     [0, 1]
137
138     >>> collections.deque(s)
139     deque([2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])
140
141     >>> s.get_sample()
142     [78, 18, 47, 83, 93, 26, 25, 73, 94, 38]
143
144     """
145
146     def __init__(self, source_iter: Iterator, sample_size: int):
147         self.source_iter = source_iter
148         self.sample_size = sample_size
149         self.resovoir: List[Any] = []
150         self.stream_length_so_far = 0
151
152     def __iter__(self) -> Iterator:
153         return self
154
155     def __next__(self) -> Any:
156         item = self.source_iter.__next__()
157         self.stream_length_so_far += 1
158
159         # Filling the resovoir
160         pop = len(self.resovoir)
161         if pop < self.sample_size:
162             self.resovoir.append(item)
163             if self.sample_size == (pop + 1):  # just finished filling...
164                 random.shuffle(self.resovoir)
165
166         # Swap this item for one in the resovoir with probabilty
167         # sample_size / stream_length_so_far.  See:
168         #
169         # https://en.wikipedia.org/wiki/Reservoir_sampling
170         else:
171             r = random.randint(0, self.stream_length_so_far)
172             if r < self.sample_size:
173                 self.resovoir[r] = item
174         return item
175
176     def get_sample(self) -> List[Any]:
177         return self.resovoir
178
179
180 if __name__ == '__main__':
181     import doctest
182
183     doctest.testmod()