Package: intervaltree
intervaltreeA mutable, self-balancing interval tree for Python 2 and 3. Queries may be by point, by range overlap, or by range envelopment.This library was designed to allow tagging text and time intervals, where the intervals include the lower bound but not the upper bound.Version 3 changes!Thesearch(begin, end, strict)method no longer exists. Instead, use one of these:at(point)overlap(begin, end)envelop(begin, end)Theextend(items)method no longer exists. Instead, useupdate(items).Methods likemerge_overlaps()which took astrictargument consistently default tostrict=True. Before, some methods defaulted toTrueand others toFalse.InstallingpipinstallintervaltreeFeaturesSupports Python 2.7 and Python 3.5+ (Tested under 2.7, and 3.5 thru 3.8)Initializingblanktree = IntervalTree()from an iterable ofIntervalobjects (tree = IntervalTree(intervals))from an iterable of tuples (tree = IntervalTree.from_tuples(interval_tuples))Insertionstree[begin:end] = datatree.add(interval)tree.addi(begin, end, data)Deletionstree.remove(interval)(raisesValueErrorif not present)tree.discard(interval)(quiet if not present)tree.removei(begin, end, data)(short fortree.remove(Interval(begin, end, data)))tree.discardi(begin, end, data)(short fortree.discard(Interval(begin, end, data)))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)Point queriestree[point]tree.at(point)(same as previous)Overlap queriestree[begin:end]tree.overlap(begin, end)(same as previous)Envelop queriestree.envelop(begin, end)Membership queriesinterval_obj in tree(this is fastest, O(1))tree.containsi(begin, end, data)tree.overlaps(point)tree.overlaps(begin, end)Iterablefor interval_obj in tree:tree.items()Sizinglen(tree)tree.is_empty()not treetree.begin()(thebegincoordinate of the leftmost interval)tree.end()(theendcoordinate of the rightmost interval)Set-like operationsunionresult_tree = tree.union(iterable)result_tree = tree1 | tree2tree.update(iterable)tree |= other_treedifferenceresult_tree = tree.difference(iterable)result_tree = tree1 - tree2tree.difference_update(iterable)tree -= other_treeintersectionresult_tree = tree.intersection(iterable)result_tree = tree1 & tree2tree.intersection_update(iterable)tree &= other_treesymmetric differenceresult_tree = tree.symmetric_difference(iterable)result_tree = tree1 ^ tree2tree.symmetric_difference_update(iterable)tree ^= other_treecomparisontree1.issubset(tree2)ortree1 <= tree2tree1 <= tree2tree1.issuperset(tree2)ortree1 > tree2tree1 >= tree2tree1 == tree2Restructuringchop(begin, end)(slice intervals and remove everything betweenbeginandend, optionally modifying the data fields of the chopped-up intervals)slice(point)(slice intervals atpoint)split_overlaps()(slice at all interval boundaries, optionally modifying the data field)merge_overlaps()(joins overlapping intervals into a single interval, optionally merging the data fields)merge_equals()(joins intervals with matching ranges into a single interval, optionally merging the data fields)Copying and typecastingIntervalTree(tree)(Intervalobjects are same as those in tree)tree.copy()(Intervalobjects are shallow copies of those in tree)set(tree)(can later be fed intoIntervalTree())list(tree)(ditto)Pickle-friendlyAutomatic AVL balancingExamplesGetting started>>>fromintervaltreeimportInterval,IntervalTree>>>t=IntervalTree()>>>tIntervalTree()Adding intervals - any object works!>>>t[1:2]="1-2">>>t[4:7]=(4,7)>>>t[5:9]={5:9}Query by pointThe result of a query is asetobject, so if ordering is important,
you must sort it first.>>>sorted(t[6])[Interval(4,7,(4,7)),Interval(5,9,{5:9})]>>>sorted(t[6])[0]Interval(4,7,(4,7))Query by rangeNote that ranges are inclusive of the lower limit, but non-inclusive of the upper limit. So:>>>sorted(t[2:4])[]Since our search was over2 ≤ x < 4, neitherInterval(1, 2)norInterval(4, 7)was included. The first interval,1 ≤ x < 2does not includex = 2. The second
interval,4 ≤ x < 7, does includex = 4, but our search interval excludes it. So,
there were no overlapping intervals. However:>>>sorted(t[1:5])[Interval(1,2,'1-2'),Interval(4,7,(4,7))]To only return intervals that are completely enveloped by the search range:>>>sorted(t.envelop(1,5))[Interval(1,2,'1-2')]Accessing anIntervalobject>>>iv=Interval(4,7,(4,7))>>>iv.begin4>>>iv.end7>>>iv.data(4,7)>>>begin,end,data=iv>>>begin4>>>end7>>>data(4,7)Constructing from lists of intervalsWe could have made a similar tree this way:>>>ivs=[(1,2),(4,7),(5,9)]>>>t=IntervalTree(...Interval(begin,end,"%d-%d"%(begin,end))forbegin,endinivs...)Or, if we don't need the data fields:>>>t2=IntervalTree(Interval(*iv)forivinivs)Or even:>>>t2=IntervalTree.from_tuples(ivs)Removing intervals>>>t.remove(Interval(1,2,"1-2"))>>>sorted(t)[Interval(4,7,'4-7'),Interval(5,9,'5-9')]>>>t.remove(Interval(500,1000,"Doesn't exist"))# raises ValueErrorTraceback(mostrecentcalllast):ValueError>>>t.discard(Interval(500,1000,"Doesn't exist"))# quietly does nothing>>>delt[5]# same as t.remove_overlap(5)>>>tIntervalTree()We could also empty a tree entirely:>>>t2.clear()>>>t2IntervalTree()Or remove intervals that overlap a range:>>>t=IntervalTree([...Interval(0,10),...Interval(10,20),...Interval(20,30),...Interval(30,40)])>>>t.remove_overlap(25,35)>>>sorted(t)[Interval(0,10),Interval(10,20)]We can also remove only those intervals completely enveloped in a range:>>>t.remove_envelop(5,20)>>>sorted(t)[Interval(0,10)]ChoppingWe could also chop out parts of the tree:>>>t=IntervalTree([Interval(0,10)])>>>t.chop(3,7)>>>sorted(t)[Interval(0,3),Interval(7,10)]To modify the new intervals' data fields based on which side of the interval is being chopped:>>>defdatafunc(iv,islower):...oldlimit=iv[islower]...return"oldlimit:{0}, islower:{1}".format(oldlimit,islower)>>>t=IntervalTree([Interval(0,10)])>>>t.chop(3,7,datafunc)>>>sorted(t)[0]Interval(0,3,'oldlimit: 10, islower: True')>>>sorted(t)[1]Interval(7,10,'oldlimit: 0, islower: False')SlicingYou can also slice intervals in the tree without removing them:>>>t=IntervalTree([Interval(0,10),Interval(5,15)])>>>t.slice(3)>>>sorted(t)[Interval(0,3),Interval(3,10),Interval(5,15)]You can also set the data fields, for example, re-usingdatafunc()from above:>>>t=IntervalTree([Interval(5,15)])>>>t.slice(10,datafunc)>>>sorted(t)[0]Interval(5,10,'oldlimit: 15, islower: True')>>>sorted(t)[1]Interval(10,15,'oldlimit: 5, islower: False')Future improvementsSee theissue trackeron GitHub.Based onEternally Confuzzled'sAVL treeWikipedia'sInterval TreeHeavily modified from Tyler Kahn'sInterval Tree implementation in Python(GitHub project)Incorporates contributions from:konstantint/Konstantin Tretyakovof the University of Tartu (Estonia)siniG/Avi Gabaylmcarril/Luis M. Carrilof the Karlsruhe Institute for Technology (Germany)depristo/MarkDePristoCopyrightChaim Leib Halbert, 2013-2020Modifications,Konstantin Tretyakov, 2014Licensed under theApache License, version 2.0.The source code for this project is athttps://github.com/chaimleib/intervaltree