Debian Codegraph @

collections_extended/range_map.py

raw
1 """RangeMap class definition."""
2 from abc import ABCMeta, abstractmethod
3 from bisect import bisect_left, bisect_right
4 from collections.abc import Collection, Mapping, Set
5
6 from .sentinel import NOT_SET
7
8
9 class MappedRange:
10 """Represents a subrange of a RangeMap.
11
12 This is a glorified namedtuple.
13 """
14
15 __slots__ = ('start', 'stop', 'value')
16
17 def __init__(self, start, stop, value):
18 """Create a mapped range.
19
20 Args:
21 start: The start of the range, inclusive.
22 stop: The end of the range, exclusive.
23 value: The mapped value.
24 """
25 self.start = start
26 self.stop = stop
27 self.value = value
28
29 # Implement __iter__ so we can unpack this
30 def __iter__(self):
31 yield self.start
32 yield self.stop
33 yield self.value
34
35 def __str__(self):
36 return '[{start!r}, {stop!r}) -> {value!r}'.format(
37 start=self.start,
38 stop=self.stop,
39 value=self.value,
40 )
41
42 def __repr__(self):
43 return '{class_name}({start!r}, {stop!r}, {value!r})'.format(
44 class_name=self.__class__.__name__,
45 start=self.start,
46 stop=self.stop,
47 value=self.value,
48 )
49
50 def __eq__(self, other):
51 if isinstance(other, MappedRange):
52 return (self.start, self.stop, self.value) ==\
53 (other.start, other.stop, other.value)
54 return False
55
56
57 class RangeMapView(Collection):
58 """Base class for views of RangeMaps."""
59
60 __metaclass__ = ABCMeta
61
62 def __init__(self, mapping):
63 """Create a RangeMapView from a RangeMap."""
64 self._mapping = mapping
65
66 def __len__(self):
67 return len(self._mapping)
68
69 @abstractmethod
70 def __iter__(self):
71 raise NotImplementedError
72
73 @abstractmethod
74 def __contains__(self, item):
75 raise NotImplementedError
76
77 def __repr__(self):
78 return '{0.__class__.__name__}({0._mapping!r})'.format(self)
79
80 @property
81 def mapping(self):
82 """Return the underlying RangeMap."""
83 return self._mapping
84
85
86 class RangeMapKeysView(RangeMapView, Set):
87 """A view of the keys that mark the starts of subranges of a RangeMap.
88
89 Since iterating over all the keys is impossible, the view only
90 iterates over the keys that start each subrange.
91 """
92
93 def __contains__(self, key):
94 return key in self.mapping
95
96 def __iter__(self):
97 for mapped_range in self.mapping.ranges():
98 yield mapped_range.start
99
100
101 class RangeMapItemsView(RangeMapView, Set):
102 """A view of the items that mark the starts of subranges of a RangeMap.
103
104 Since iterating over all the items is impossible, the view only
105 iterates over the items that start each subrange.
106 """
107
108 def __contains__(self, item):
109 # TODO should item be a MappedRange instead of a 2-tuple
110 key, value = item
111 try:
112 mapped_value = self.mapping[key]
113 except KeyError:
114 return False
115 else:
116 return mapped_value == value
117
118 def __iter__(self):
119 for mapped_range in self.mapping.ranges():
120 yield (mapped_range.start, mapped_range.value)
121
122
123 class RangeMapValuesView(RangeMapView):
124 """A view on the values that mark the start of subranges of a RangeMap.
125
126 Since iterating over all the values is impossible, the view only
127 iterates over the values that start each subrange.
128 """
129
130 def __contains__(self, value):
131 for mapped_range in self.mapping.ranges():
132 if mapped_range.value == value:
133 return True
134 return False
135
136 def __iter__(self):
137 for mapped_range in self.mapping.ranges():
138 yield mapped_range.value
139
140
141 def _check_start_stop(start, stop):
142 """Check that start and stop are valid - orderable and in the right order.
143
144 Raises:
145 ValueError: if stop <= start
146 TypeError: if unorderable
147 """
148 if start is not None and stop is not None and stop <= start:
149 raise ValueError('stop must be > start')
150
151
152 def _check_key_slice(key):
153 if not isinstance(key, slice):
154 raise TypeError('Can only set and delete slices')
155 if key.step is not None:
156 raise ValueError('Cannot set or delete slices with steps')
157
158
159 class RangeMap(Mapping):
160 """Map ranges of orderable elements to values."""
161
162 def __init__(self, iterable=None, default_value=NOT_SET):
163 """Create a RangeMap.
164
165 A mapping or other iterable can be passed to initialize the RangeMap.
166 If mapping is passed, it is interpreted as a mapping from range start
167 indices to values.
168 If an iterable is passed, each element will define a range in the
169 RangeMap and should be formatted (start, stop, value).
170
171 default_value is a an optional keyword argument that will initialize the
172 entire RangeMap to that value. Any missing ranges will be mapped to that
173 value. However, if ranges are subsequently deleted they will be removed
174 and *not* mapped to the default_value.
175
176 Args:
177 iterable: A Mapping or an Iterable to initialize from.
178 default_value: If passed, the return value for all keys less than the
179 least key in mapping or missing ranges in iterable. If no mapping
180 or iterable, the return value for all keys.
181 """
182 self._keys = [None]
183 self._values = [default_value]
184 if iterable:
185 if isinstance(iterable, Mapping):
186 self._init_from_mapping(iterable)
187 else:
188 self._init_from_iterable(iterable)
189
190 @classmethod
191 def from_mapping(cls, mapping):
192 """Create a RangeMap from a mapping of interval starts to values."""
193 obj = cls()
194 obj._init_from_mapping(mapping)
195 return obj
196
197 def _init_from_mapping(self, mapping):
198 for key, value in sorted(mapping.items()):
199 self.set(value, key)
200
201 @classmethod
202 def from_iterable(cls, iterable):
203 """Create a RangeMap from an iterable of tuples defining each range.
204
205 Each element of the iterable is a tuple (start, stop, value).
206 """
207 obj = cls()
208 obj._init_from_iterable(iterable)
209 return obj
210
211 def _init_from_iterable(self, iterable):
212 for start, stop, value in iterable:
213 self.set(value, start=start, stop=stop)
214
215 def __str__(self):
216 range_format = '({range.start}, {range.stop}): {range.value}'
217 values = ', '.join([range_format.format(range=r) for r in self.ranges()])
218 return 'RangeMap(%s)' % values
219
220 def __repr__(self):
221 range_format = '({range.start!r}, {range.stop!r}, {range.value!r})'
222 values = ', '.join([range_format.format(range=r) for r in self.ranges()])
223 return 'RangeMap([%s])' % values
224
225 def ranges(self, start=None, stop=None):
226 """Generate MappedRanges for all mapped ranges.
227
228 Yields:
229 MappedRange
230 """
231 _check_start_stop(start, stop)
232 if start is None:
233 start_loc = 1
234 else:
235 start_loc = bisect_right(self._keys, start, lo=1)
236 if stop is None:
237 stop_loc = len(self._keys)
238 else:
239 stop_loc = bisect_left(self._keys, stop, lo=1)
240 start_val = self._values[start_loc - 1]
241 candidate_keys = [start] + self._keys[start_loc:stop_loc] + [stop]
242 candidate_values = [start_val] + self._values[start_loc:stop_loc]
243 for i, value in enumerate(candidate_values):
244 if value is not NOT_SET:
245 start_key = candidate_keys[i]
246 stop_key = candidate_keys[i + 1]
247 yield MappedRange(start_key, stop_key, value)
248
249 def __contains__(self, key):
250 try:
251 self._getitem(key)
252 except KeyError:
253 return False
254 else:
255 return True
256
257 def __iter__(self):
258 for key, value in zip(self._keys, self._values):
259 if value is not NOT_SET:
260 yield key
261
262 def __bool__(self):
263 # any(val is not NOT_SET for val in self._values)
264 if len(self._keys) > 1:
265 return True
266 else:
267 return self._values[0] != NOT_SET
268
269 __nonzero__ = __bool__
270
271 def _getitem(self, key):
272 """Get the value for a key (not a slice)."""
273 if key is None:
274 loc = 0
275 else:
276 loc = bisect_right(self._keys, key, lo=1) - 1
277 value = self._values[loc]
278 if value is NOT_SET:
279 raise KeyError(key)
280 else:
281 return value
282
283 def get(self, key, restval=None):
284 """Get the value of the range containing key, otherwise return restval."""
285 try:
286 return self._getitem(key)
287 except KeyError:
288 return restval
289
290 def get_range(self, start=None, stop=None):
291 """Return a RangeMap for the range start to stop.
292
293 Returns:
294 A RangeMap
295 """
296 return self.from_iterable(self.ranges(start, stop))
297
298 def set(self, value, start=None, stop=None):
299 """Set the range from start to stop to value."""
300 _check_start_stop(start, stop)
301 # start_index, stop_index will denote the section we are replacing
302 if start is None:
303 start_index = 0
304 else:
305 start_index = bisect_left(self._keys, start, lo=1)
306 if self._values[start_index - 1] == value:
307 # We're setting a range where the left range has the same
308 # value, so create one big range
309 start_index -= 1
310 start = self._keys[start_index]
311 new_keys = [start]
312 new_values = [value]
313 if stop is None:
314 stop_index = len(self._keys)
315 else:
316 stop_index = bisect_right(self._keys, stop, lo=1)
317 stop_value = self._values[stop_index - 1]
318 if value != stop_value:
319 new_keys.append(stop)
320 new_values.append(stop_value)
321 self._keys[start_index:stop_index] = new_keys
322 self._values[start_index:stop_index] = new_values
323
324 def delete(self, start=None, stop=None):
325 """Delete the range from start to stop from self.
326
327 Raises:
328 KeyError: If part of the passed range isn't mapped.
329 """
330 _check_start_stop(start, stop)
331 if start is None:
332 start_loc = 0
333 else:
334 start_loc = bisect_right(self._keys, start, lo=1) - 1
335 if stop is None:
336 stop_loc = len(self._keys)
337 else:
338 stop_loc = bisect_left(self._keys, stop, lo=1)
339 for value in self._values[start_loc:stop_loc]:
340 if value is NOT_SET:
341 raise KeyError((start, stop))
342 # this is inefficient, we've already found the sub ranges
343 self.set(NOT_SET, start=start, stop=stop)
344
345 def empty(self, start=None, stop=None):
346 """Empty the range from start to stop.
347
348 Like delete, but no Error is raised if the entire range isn't mapped.
349 """
350 self.set(NOT_SET, start=start, stop=stop)
351
352 def clear(self):
353 """Remove all elements."""
354 self._keys = [None]
355 self._values = [NOT_SET]
356
357 @property
358 def start(self):
359 """Get the start key of the first range.
360
361 None if RangeMap is empty or unbounded to the left.
362 """
363 if self._values[0] is NOT_SET:
364 try:
365 return self._keys[1]
366 except IndexError:
367 # This is empty or everything is mapped to a single value
368 return None
369 else:
370 # This is unbounded to the left
371 return self._keys[0]
372
373 @property
374 def end(self):
375 """Get the stop key of the last range.
376
377 None if RangeMap is empty or unbounded to the right.
378 """
379 if self._values[-1] is NOT_SET:
380 return self._keys[-1]
381 else:
382 # This is unbounded to the right
383 return None
384
385 def __eq__(self, other):
386 if isinstance(other, RangeMap):
387 return (
388 self._keys == other._keys
389 and self._values == other._values
390 )
391 else:
392 return False
393
394 def __getitem__(self, key):
395 try:
396 _check_key_slice(key)
397 except TypeError:
398 return self._getitem(key)
399 else:
400 return self.get_range(key.start, key.stop)
401
402 def __setitem__(self, key, value):
403 _check_key_slice(key)
404 self.set(value, key.start, key.stop)
405
406 def __delitem__(self, key):
407 _check_key_slice(key)
408 self.delete(key.start, key.stop)
409
410 def __len__(self):
411 count = 0
412 for v in self._values:
413 if v is not NOT_SET:
414 count += 1
415 return count
416
417 def keys(self):
418 """Return a view of the keys."""
419 return RangeMapKeysView(self)
420
421 def values(self):
422 """Return a view of the values."""
423 return RangeMapValuesView(self)
424
425 def items(self):
426 """Return a view of the item pairs."""
427 return RangeMapItemsView(self)