chaimleib / intervaltree

A mutable, self-balancing interval tree. Queries may be by point, by range overlap, or by range containment.
Apache License 2.0
636 stars 108 forks source link

Update interval data? #116

Closed ccneko closed 2 years ago

ccneko commented 2 years ago

May I ask if there is a way io update interval data?

For example, if I want to add 1 to a numeric data of an Interval in an IntervalTree

test_tree = IntervalTree()
test_tree.addi(1, 2, 0)
print(list(test_tree)[0])
test_tree[list(test_tree)[0].begin: list(test_tree)[0].end] = list(test_tree)[0].data + 1
print(test_tree)
print(test_tree[1])
print(test_tree[list(test_tree)[0].begin: list(test_tree)[0].end])

The result is creating a new Interval object at the same location, instead of updating the existing one:

Interval(1, 2, 0)
IntervalTree([Interval(1, 2, 0), Interval(1, 2, 1)])
{Interval(1, 2, 0), Interval(1, 2, 1)}
{Interval(1, 2, 0), Interval(1, 2, 1)}

Thankyou so much for your help in advance

ccneko commented 2 years ago

I'm using the tree.merge_overlaps() function at the end for now. Is it a preferrable way?

chaimleib commented 2 years ago

Modifying the data field is disallowed by default so that users don't get tripped up when they sort Intervals and the (default) sorting order changes.

If you still want to modify the data field, you can set it to a single-element list, so [0] instead of 0, and then you can change the list member freely:

t = IntervalTree()
t.addi(1, 2, [0])
print(t)
# IntervalTree([Interval(1, 2, [0])])
data = list(t)[0].data
data[0] = data[0] + 1
print(t)
# IntervalTree([Interval(1, 2, [1])])
ccneko commented 2 years ago

Thank you so much for your helpful prompt reply! This is a good idea.