0
# Intervals
1
2
The Interval class represents a half-open interval [begin, end) with optional data. Intervals are immutable namedtuples that provide comparison, overlap detection, and utility methods for working with ranges.
3
4
## Capabilities
5
6
### Construction
7
8
Create intervals from begin/end points with optional data payload.
9
10
```python { .api }
11
class Interval:
12
def __new__(cls, begin, end, data=None):
13
"""
14
Create a new interval (namedtuple constructor).
15
16
Parameters:
17
- begin: Lower bound (inclusive) - any comparable type
18
- end: Upper bound (exclusive) - any comparable type
19
- data: Optional data payload - any type
20
21
Returns:
22
Interval object representing [begin, end)
23
"""
24
```
25
26
### Properties
27
28
Access interval boundaries and data.
29
30
```python { .api }
31
# Properties (read-only)
32
begin: Any # Lower bound (inclusive)
33
end: Any # Upper bound (exclusive)
34
data: Any # Optional data payload (None if not provided)
35
```
36
37
### Overlap Detection
38
39
Test for overlaps between intervals, ranges, or points.
40
41
```python { .api }
42
def overlaps(self, begin, end=None):
43
"""
44
Test whether interval overlaps with point, range, or another interval.
45
46
Parameters:
47
- begin: Point value, range start, or Interval object
48
- end: Range end (optional, only needed for range queries)
49
50
Returns:
51
bool: True if overlap exists, False otherwise
52
"""
53
54
def overlap_size(self, begin, end=None):
55
"""
56
Calculate the size of overlap between intervals or with a range.
57
58
Parameters:
59
- begin: Point value, range start, or Interval object
60
- end: Range end (optional, only needed for range queries)
61
62
Returns:
63
Number: Size of overlap, 0 if no overlap exists
64
"""
65
```
66
67
### Containment Testing
68
69
Test point and interval containment relationships.
70
71
```python { .api }
72
def contains_point(self, p):
73
"""
74
Test whether interval contains a point.
75
76
Parameters:
77
- p: Point to test (any comparable type)
78
79
Returns:
80
bool: True if begin <= p < end, False otherwise
81
"""
82
83
def contains_interval(self, other):
84
"""
85
Test whether this interval completely contains another interval.
86
87
Parameters:
88
- other: Interval to test for containment
89
90
Returns:
91
bool: True if other is completely contained, False otherwise
92
"""
93
```
94
95
### Comparison Operations
96
97
Standard comparison operations for sorting and ordering intervals.
98
99
```python { .api }
100
def __eq__(self, other):
101
"""
102
Test equality including data field.
103
104
Parameters:
105
- other: Interval to compare
106
107
Returns:
108
bool: True if begin, end, and data all match
109
"""
110
111
def range_matches(self, other):
112
"""
113
Test whether ranges match (ignoring data field).
114
115
Parameters:
116
- other: Interval to compare
117
118
Returns:
119
bool: True if begin and end match, ignoring data
120
"""
121
122
def __hash__(self):
123
"""
124
Hash based on begin and end only (data ignored).
125
126
Returns:
127
int: Hash value suitable for use in sets and dicts
128
"""
129
130
def __lt__(self, other):
131
"""Less than comparison for sorting."""
132
133
def __gt__(self, other):
134
"""Greater than comparison for sorting."""
135
```
136
137
### Positional Comparisons
138
139
Specialized comparison methods for interval positioning.
140
141
```python { .api }
142
def lt(self, other):
143
"""
144
Test if strictly less than (no overlap).
145
146
Parameters:
147
- other: Interval or point to compare
148
149
Returns:
150
bool: True if this interval ends before other begins
151
152
Raises:
153
ValueError: If either interval is null
154
"""
155
156
def le(self, other):
157
"""
158
Test if less than or overlapping.
159
160
Parameters:
161
- other: Interval or point to compare
162
163
Returns:
164
bool: True if this interval doesn't extend past other's end
165
166
Raises:
167
ValueError: If either interval is null
168
"""
169
170
def gt(self, other):
171
"""
172
Test if strictly greater than (no overlap).
173
174
Parameters:
175
- other: Interval or point to compare
176
177
Returns:
178
bool: True if this interval begins after other ends
179
180
Raises:
181
ValueError: If either interval is null
182
"""
183
184
def ge(self, other):
185
"""
186
Test if greater than or overlapping.
187
188
Parameters:
189
- other: Interval or point to compare
190
191
Returns:
192
bool: True if this interval doesn't start before other
193
194
Raises:
195
ValueError: If either interval is null
196
"""
197
```
198
199
### Distance and Metrics
200
201
Calculate distances and measurements between intervals.
202
203
```python { .api }
204
def distance_to(self, other):
205
"""
206
Calculate distance between intervals or to a point.
207
208
Parameters:
209
- other: Interval or point
210
211
Returns:
212
Number: Distance between intervals (0 if overlapping)
213
"""
214
215
def length(self):
216
"""
217
Calculate interval length.
218
219
Returns:
220
Number: Length of interval (end - begin), 0 for null intervals
221
"""
222
223
def is_null(self):
224
"""
225
Test if interval is null (begin >= end).
226
227
Returns:
228
bool: True if interval is null, False otherwise
229
"""
230
```
231
232
### Utility Methods
233
234
Copying and string representation methods.
235
236
```python { .api }
237
def copy(self):
238
"""
239
Create shallow copy of interval.
240
241
Returns:
242
Interval: New interval with same begin, end, and data
243
"""
244
245
def __repr__(self):
246
"""
247
String representation suitable for eval().
248
249
Returns:
250
str: Executable string representation
251
"""
252
253
def __str__(self):
254
"""Alias for __repr__()."""
255
```
256
257
## Usage Examples
258
259
### Basic Interval Operations
260
261
```python
262
from intervaltree import Interval
263
264
# Create intervals
265
i1 = Interval(0, 10, "first")
266
i2 = Interval(5, 15, "second")
267
i3 = Interval(20, 30)
268
269
# Test overlaps
270
print(i1.overlaps(i2)) # True
271
print(i1.overlaps(7)) # True (point overlap)
272
print(i1.overlaps(i3)) # False
273
274
# Calculate overlap size
275
print(i1.overlap_size(i2)) # 5 (overlaps from 5 to 10)
276
277
# Test containment
278
print(i1.contains_point(7)) # True
279
print(i1.contains_point(15)) # False
280
print(i2.contains_interval(Interval(6, 9))) # True
281
```
282
283
### Comparison and Sorting
284
285
```python
286
from intervaltree import Interval
287
288
intervals = [
289
Interval(10, 20, "third"),
290
Interval(0, 10, "first"),
291
Interval(5, 15, "second")
292
]
293
294
# Sort intervals
295
sorted_intervals = sorted(intervals)
296
# Result: [Interval(0, 10, 'first'), Interval(5, 15, 'second'), Interval(10, 20, 'third')]
297
298
# Positional comparisons
299
i1 = Interval(0, 5)
300
i2 = Interval(10, 15)
301
print(i1.lt(i2)) # True (i1 is strictly before i2)
302
print(i1.distance_to(i2)) # 5 (gap between intervals)
303
```