Portion Library for Python Intervals

2.6.1 · active · verified Fri Apr 10

The portion library (current version 2.6.1) provides a robust data structure and operations for intervals in Python. It supports various types of intervals (closed, open, finite, semi-infinite) with any comparable objects, including interval sets (disjunctions of atomic intervals). The library offers automatic simplification, comparison, transformation, intersection, union, complement, difference, containment, and discrete iteration, along with a dict-like structure (`IntervalDict`) to map intervals to data. It is actively maintained with regular releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create various types of intervals, perform common set operations (union, intersection, difference, complement), check interval properties (containment, overlap, emptiness), and utilize the `IntervalDict` for mapping data to intervals.

import portion as P

# Create intervals
i1 = P.closed(1, 5) # [1,5]
i2 = P.open(3, 7)   # (3,7)
i3 = P.singleton(10) # [10,10]
i_inf = P.openclosed(-P.inf, 0) # (-inf,0]

print(f"Interval 1: {i1}")
print(f"Interval 2: {i2}")

# Perform operations
union = i1 | i2       # Union
intersection = i1 & i2  # Intersection
difference = i1 - i2  # Difference
complement = ~i1      # Complement (relative to the full domain)

print(f"Union: {union}")
print(f"Intersection: {intersection}")
print(f"Difference: {difference}")
print(f"Complement of [1,5]: {complement}")

# Check properties
print(f"Is i1 in i2? {i2.contains(i1)}") # False
print(f"Does i1 overlap i2? {i1.overlaps(i2)}") # True
print(f"Is empty interval empty? {P.empty().empty}") # True

# Using IntervalDict
id = P.IntervalDict()
id[P.closed(0, 10)] = 'Phase 1'
id[P.open(10, 20)] = 'Phase 2'
id[P.singleton(25)] = 'Event'

print(f"\nIntervalDict: {id}")
print(f"Value at 5: {id[5]}") # 'Phase 1'
print(f"Value at 15: {id[15]}") # 'Phase 2'
print(f"Value at 25: {id[25]}") # 'Event'

# Get items as (interval, value) pairs
print(f"Items: {list(id.items())}")

view raw JSON →