Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add remove_data method #119

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ Features
* `tree.remove_overlap(point)`
* `tree.remove_overlap(begin, end)` (removes all overlapping the range)
* `tree.remove_envelop(begin, end)` (removes all enveloped in the range)
* `tree.remove_data(data)` (removes all intervals containing this data)
* `tree.remove_data(data, point)` (removes all intervals containing this data and overlapping the point)

* Point queries
* `tree[point]`
Expand Down
31 changes: 31 additions & 0 deletions intervaltree/intervaltree.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,15 @@ class IntervalTree(MutableSet):
>>> tree
IntervalTree()

Delete intervals, containing certain data:
>>> tree = IntervalTree([Interval(-10, 0, "x"), Interval(0, 10, "y"), Interval(-10, 0, "y")])
>>> tree
IntervalTree([Interval(-10, 0, "x"), Interval(0, 10, "y"), Interval(-10, 0, "y")])
>>> tree.remove_data("y", set(1))
IntervalTree([Interval(-10, 0, "x"), Interval(-10, 0, "y")])
>>> tree.remove_data("y")
IntervalTree([Interval(-10, 0, "x")])

Point queries::

>>> tree = IntervalTree([Interval(-1.1, 1.1), Interval(-0.5, 1.5), Interval(0.5, 1.7)])
Expand Down Expand Up @@ -467,6 +476,28 @@ def symmetric_difference_update(self, other):
other.remove(iv)
self.update(other)

def remove_data(self, data, points=None):
"""
Removes all intervals containing the given data. If a set of points is provided,
only intervals containing the points AND containing the given data will be removed.
Providing a set of points speeds up the operation considerably.
"""
if data is None:
raise ValueError("IntervalTree: No data submitted.")

if points is not None:
root = self.top_node
ivs = set()
for point in points:
ivs |= root.search_point(point, set())
ivs_with_data = [iv for iv in ivs if iv.data == data]
for iv in ivs_with_data:
self.discard(iv)
else:
ivs_without_data = [iv for iv in self.items() if iv.data != data]
self.clear()
self.__init__(ivs_without_data)

def remove_overlap(self, begin, end=None):
"""
Removes all intervals overlapping the given point or range.
Expand Down