intervaltree icon indicating copy to clipboard operation
intervaltree copied to clipboard

add method to find complement

Open quantumdot opened this issue 8 years ago • 4 comments

It would be great to have a method to find the complement of the intervals in the tree, with the option of specifying the true bounds of the universe the tree lives within.

Example (= is interval; . is gap): ....===..==.....=====...===..... <<<Interval tree .......==..=====.....===........ <<<Complement ====...==..=====.....===...===== <<<Complement w/ bounds

quantumdot avatar Sep 05 '16 22:09 quantumdot

Here's a basic algorithm, which you can test and modify. I'm having some issues with the automated tests in Travis, so I can't easily add this method at the moment, but I hope this will get you unstuck.

def complement(tree):
    result = IntervalTree()
    result.addi(tree.begin(), tree.end())  # using input tree bounds
    for iv in tree:
        result.chop(iv)
    return result

chaimleib avatar Sep 06 '16 00:09 chaimleib

@chaimleib thanks for the sample code, it does not seem to work anymore. Here is an updated version, if someone needs bounds then you have to set start and end.

def complement(tree, start=None, end=None):
    result = IntervalTree()
    if start is None:
        start = tree.begin()
    if end is None:
        end = tree.end()

    result.addi(start, end)  # using input tree bounds
    for iv in tree:
        result.chop(iv[0], iv[1])
    return result

reinoldus avatar May 08 '19 05:05 reinoldus

Thanks @reinoldus

OhadRubin avatar Sep 04 '20 05:09 OhadRubin

Thanks @chaimleib and @reinoldus! Super helpful!

mayankbpatel avatar Sep 28 '22 18:09 mayankbpatel