pyinterval icon indicating copy to clipboard operation
pyinterval copied to clipboard

Complement of interval?

Open kenahoo opened this issue 8 years ago • 5 comments
trafficstars

Is there a way to take the complement of an interval object?

Strictly speaking I think it's not possible since you define all your intervals to be unions of closed simple intervals, so the complements would be unions of open simple intervals, which are not representable in your scheme.

But if you define complement(x) to be the smallest object representable in your scheme whose union with x produces the entire extended real line; or equivalently, the union of the classical complement of x with x.extrema(), then it's in your scheme and it would work for me.

kenahoo avatar Mar 02 '17 18:03 kenahoo

You are perfectly right.

I should be able to add a x.closed_complement() method returning the closure of the complement of x, which, as you said, it would be equal to the union of the set-theoretic complement of x and x.extrema.

taschini avatar Mar 05 '17 17:03 taschini

Alternatively, since the set-theoretic complement of an instance of the Interval class is not representable with an instance of the Interval class, I could define a method that simply returns a list of pairs. The reason this might be preferrable is illustrated by:

>>> x = interval([1, 2], [3])
>>> x.closed_complement()
interval([-inf, 1.0], [2.0, inf])

>>> x.complement()
[(-inf, 1.0), (2.0, 3.0), (3.0, inf)]

taschini avatar Mar 05 '17 22:03 taschini

Landed here looking for exactly this functionality. Any suggestions on how to implement it?

dangom avatar May 23 '17 09:05 dangom

Here's how I'm doing it, in a new subclass of interval:

class MyInterval(interval):
    def complement(self) -> 'MyInterval':
        chain = itertools.chain(self, [[inf, None]])

        out = []
        prev = [None, neg_inf]
        for this in chain:
            if prev[1] != this[0]:
                out.append([prev[1], this[0]])
            prev = this

        return self.__class__(*out)

kenahoo avatar May 23 '17 14:05 kenahoo

Thanks @kenahoo this was exactly what I needed.

langelgjm avatar Nov 09 '18 19:11 langelgjm