3 """This is an augmented interval tree for storing ranges and identifying overlaps as
4 described by: https://en.wikipedia.org/wiki/Interval_tree.
7 from __future__ import annotations
9 from functools import total_ordering
10 from typing import Any, Generator, Optional, Union
12 from overrides import overrides
14 from pyutils.collectionz import bst
16 Numeric = Union[int, float]
20 class NumericRange(object):
21 """Essentially a tuple of numbers denoting a range with some added
22 helper methods on it."""
24 def __init__(self, low: Numeric, high: Numeric):
29 self.low: Numeric = low
30 self.high: Numeric = high
31 self.highest_in_subtree: Numeric = high
33 def __lt__(self, other: NumericRange) -> bool:
34 return self.low < other.low
37 def __eq__(self, other: object) -> bool:
38 if not isinstance(other, NumericRange):
40 return self.low == other.low and self.high == other.high
42 def overlaps_with(self, other: NumericRange) -> bool:
43 return self.low <= other.high and self.high >= other.low
45 def __repr__(self) -> str:
46 return f"{self.low}..{self.high}"
49 class AugmentedIntervalTree(bst.BinarySearchTree):
51 def _assert_value_must_be_range(value: Any) -> None:
52 if not isinstance(value, NumericRange):
54 "AugmentedIntervalTree expects to use NumericRanges, see bst for a "
55 + "general purpose tree usable for other types."
59 def _on_insert(self, parent: Optional[bst.Node], new: bst.Node) -> None:
60 AugmentedIntervalTree._assert_value_must_be_range(new.value)
61 for ancestor in self.parent_path(new):
63 if new.value.high > ancestor.value.highest_in_subtree:
64 ancestor.value.highest_in_subtree = new.value.high
67 def _on_delete(self, parent: Optional[bst.Node], deleted: bst.Node) -> None:
69 new_highest_candidates = [parent.value.high]
71 new_highest_candidates.append(parent.left.value.highest_in_subtree)
73 new_highest_candidates.append(parent.right.value.highest_in_subtree)
74 parent.value.highest_in_subtree = max(new_highest_candidates)
76 def find_one_overlap(self, x: NumericRange):
77 """Identify and return one overlapping node from the tree.
79 >>> tree = AugmentedIntervalTree()
80 >>> tree.insert(NumericRange(20, 24))
81 >>> tree.insert(NumericRange(18, 22))
82 >>> tree.insert(NumericRange(14, 16))
83 >>> tree.insert(NumericRange(1, 30))
84 >>> tree.insert(NumericRange(25, 30))
85 >>> tree.insert(NumericRange(29, 33))
86 >>> tree.insert(NumericRange(5, 12))
87 >>> tree.insert(NumericRange(1, 6))
88 >>> tree.insert(NumericRange(13, 18))
89 >>> tree.insert(NumericRange(16, 28))
90 >>> tree.insert(NumericRange(21, 27))
91 >>> tree.find_one_overlap(NumericRange(6, 7))
94 return self._find_one_overlap(self.root, x)
96 def _find_one_overlap(
97 self, root: bst.Node, x: NumericRange
98 ) -> Optional[NumericRange]:
102 if root.value.overlaps_with(x):
106 if root.left.value.highest_in_subtree >= x.low:
107 return self._find_one_overlap(root.left, x)
110 return self._find_one_overlap(root.right, x)
113 def find_all_overlaps(self, x: NumericRange):
114 """Yields ranges previously added to the tree that x overlaps with.
116 >>> tree = AugmentedIntervalTree()
117 >>> tree.insert(NumericRange(20, 24))
118 >>> tree.insert(NumericRange(18, 22))
119 >>> tree.insert(NumericRange(14, 16))
120 >>> tree.insert(NumericRange(1, 30))
121 >>> tree.insert(NumericRange(25, 30))
122 >>> tree.insert(NumericRange(29, 33))
123 >>> tree.insert(NumericRange(5, 12))
124 >>> tree.insert(NumericRange(1, 6))
125 >>> tree.insert(NumericRange(13, 18))
126 >>> tree.insert(NumericRange(16, 28))
127 >>> tree.insert(NumericRange(21, 27))
128 >>> for x in tree.find_all_overlaps(NumericRange(19, 21)):
136 >>> del tree[NumericRange(1, 30)]
137 >>> for x in tree.find_all_overlaps(NumericRange(19, 21)):
144 if self.root is None:
146 yield from self._find_all_overlaps(self.root, x)
148 def _find_all_overlaps(
149 self, root: bst.Node, x: NumericRange
150 ) -> Generator[NumericRange, None, None]:
154 if root.value.overlaps_with(x):
158 if root.left.value.highest_in_subtree >= x.low:
159 yield from self._find_all_overlaps(root.left, x)
162 if root.right.value.highest_in_subtree >= x.low:
163 yield from self._find_all_overlaps(root.right, x)
166 if __name__ == "__main__":