AlexandreDecan / portion

portion, a Python library providing data structure and operations for intervals.
GNU Lesser General Public License v3.0
476 stars 34 forks source link

Add the total duration of the interval. #61

Closed xingminw closed 3 years ago

xingminw commented 3 years ago

I am wondering if it will be better if the total duration of the interval could be added.

For example, a interval with [1, 3] + [5, 6] have a total duration of 2 + 1 = 3

My only concern is I am not sure how to distinguish the closed interval from the open interval when calculating the total duration. They could be the same though.

AlexandreDecan commented 3 years ago

Hello,

Thanks for your question. It seems that this issue is related to #60. The question is: what would be the "duration" for an open (or open-closed, closed-open) interval such as (1, 3)? If the answer is "2", then I don't think you should wonder about the fact that an interval is closed or open. If the answer is "1", then it means you're considering that intervals are discrete (and not continuous). In that case, I would refer to #24 to see how to deal with discrete intervals.

According to #60, it seems that the answer should be 2, though ;-)

xingminw commented 3 years ago

Hi, Thanks for your reply.

Totally agree. I guess my question is, Have you considered adding an additional attribute to the Interval to keep track of the total duration of the Interval? I write my simple function as:

def size_of_interval(interval):
    if interval.empty:
        return 0

    total_duration = 0
    for sub_interval in interval._intervals:
        total_duration += sub_interval.upper - sub_interval.lower
    return total_duration

I am not sure whether this type of function is already included.

AlexandreDecan commented 3 years ago

No, such a function is not included in portion. In some other, related issues, I said I've no plan to add it in the current major branch (i.e., before 3.0.0) since it requires bounds to support subtraction... but given many people asked for it, I could change my mind ;-)

AlexandreDecan commented 3 years ago

I'm definitely going to delay this for the next major release (if any), because there are a few cases that cannot be properly solved currently. The most annoying one is what to do with empty intervals? For example, one might expect P.empty().size() to be 0 if intervals are used to encode numerical values, while one might expect it to be timedelta(0) if intervals are used for, e.g., dates. I don't want to ask users to specify the "nul value" each time, and I don't want to decide on an "appropriate default" (e.g. 0) since it's opinionated.

This is likely to be solved if, as I hope to do for 3.0.0, portion can be "parametrized" to create intervals for specific domains.