R-Tree spatial index for Python GIS
npx @tessl/cli install tessl/pypi-rtree@1.4.00
# Rtree
1
2
Rtree provides Python bindings to libspatialindex for spatial indexing operations. It enables efficient storage and querying of spatial data using R-Tree data structures, supporting advanced features like nearest neighbor search, intersection queries, bulk operations, and custom storage implementations.
3
4
## Package Information
5
6
- **Package Name**: rtree
7
- **Language**: Python
8
- **Installation**: `pip install rtree`
9
10
## Core Imports
11
12
```python
13
import rtree
14
from rtree import index
15
```
16
17
Common import patterns:
18
19
```python
20
from rtree.index import Index, Rtree, Property
21
from rtree.exceptions import RTreeError
22
```
23
24
Import constants for configuration:
25
26
```python
27
from rtree.index import RT_RTree, RT_MVRTree, RT_TPRTree
28
from rtree.index import RT_Linear, RT_Quadratic, RT_Star
29
from rtree.index import RT_Memory, RT_Disk, RT_Custom
30
```
31
32
## Basic Usage
33
34
```python
35
from rtree import index
36
37
# Create a new spatial index
38
idx = index.Index()
39
40
# Insert some spatial objects
41
idx.insert(0, (0, 0, 1, 1)) # id, (minx, miny, maxx, maxy)
42
idx.insert(1, (0.5, 0.5, 1.5, 1.5))
43
idx.insert(2, (1, 1, 2, 2))
44
45
# Query for intersections
46
hits = list(idx.intersection((0.5, 0.5, 1.5, 1.5)))
47
print(hits) # [0, 1, 2]
48
49
# Find nearest neighbors
50
nearest = list(idx.nearest((0.25, 0.25), 2))
51
print(nearest) # [0, 1]
52
53
# Store objects with spatial data
54
idx_with_objects = index.Index()
55
idx_with_objects.insert(0, (0, 0, 1, 1), obj="First polygon")
56
idx_with_objects.insert(1, (2, 2, 3, 3), obj="Second polygon")
57
58
# Query with objects
59
for hit in idx_with_objects.intersection((0, 0, 1, 1), objects=True):
60
print(f"ID: {hit.id}, Object: {hit.object}, Bounds: {hit.bounds}")
61
```
62
63
## Architecture
64
65
Rtree's architecture consists of several key components:
66
67
- **Index Class**: Main spatial index implementation supporting R-Tree, MVR-Tree, and TPR-Tree variants
68
- **Property Class**: Configuration object for index properties and performance tuning
69
- **Item Class**: Container for query results that includes ID, stored object, and bounding box
70
- **Storage Backends**: Support for memory-based, disk-based, and custom storage implementations
71
- **Query Engine**: Efficient spatial queries including intersection, containment, nearest neighbor, and counting
72
73
The library serves as a bridge between Python's ecosystem and high-performance spatial indexing operations with cross-platform compatibility.
74
75
## Capabilities
76
77
### Core Indexing Operations
78
79
Fundamental spatial indexing functionality including inserting, deleting, and querying spatial data. Supports intersection queries, containment tests, nearest neighbor search, and counting operations.
80
81
```python { .api }
82
def insert(id: int, coordinates: Any, obj: object = None) -> None: ...
83
def delete(id: int, coordinates: Any) -> None: ...
84
def intersection(coordinates: Any, objects: bool | Literal["raw"] = False) -> Iterator: ...
85
def nearest(coordinates: Any, num_results: int = 1, objects: bool | Literal["raw"] = False) -> Iterator: ...
86
def count(coordinates: Any) -> int: ...
87
```
88
89
[Core Indexing Operations](./core-indexing.md)
90
91
### Advanced Features
92
93
Advanced spatial indexing capabilities including bulk operations with NumPy integration, custom storage implementations, TPR-Tree temporal indexing, object-oriented containers, and set operations between indexes.
94
95
```python { .api }
96
def intersection_v(mins, maxs): ...
97
def nearest_v(mins, maxs, *, num_results=1, max_dists=None, strict=False, return_max_dists=False): ...
98
class ICustomStorage: ...
99
class RtreeContainer: ...
100
def __and__(other: Index) -> Index: ...
101
def __or__(other: Index) -> Index: ...
102
```
103
104
[Advanced Features](./advanced-features.md)
105
106
### Configuration and Properties
107
108
Index configuration through the Property class, which controls performance characteristics, storage options, index variants, and spatial dimensions. Many properties must be set at index creation time.
109
110
```python { .api }
111
class Property:
112
def __init__(handle=None, owned: bool = True, **kwargs: Any) -> None: ...
113
type: int # RT_RTree, RT_MVRTree, RT_TPRTree
114
variant: int # RT_Linear, RT_Quadratic, RT_Star
115
dimension: int
116
storage: int # RT_Memory, RT_Disk, RT_Custom
117
```
118
119
[Configuration and Properties](./configuration.md)
120
121
### Utilities and Support
122
123
Utility functions for library management, exception handling, coordinate format conversion, and serialization support.
124
125
```python { .api }
126
def load() -> ctypes.CDLL: ...
127
def get_include() -> str: ...
128
class RTreeError(Exception): ...
129
def interleave(deinterleaved: Sequence[float]) -> list[float]: ...
130
def deinterleave(interleaved: Sequence[object]) -> list[object]: ...
131
```
132
133
[Utilities and Support](./utilities.md)
134
135
## Types
136
137
```python { .api }
138
class Index:
139
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
140
interleaved: bool
141
properties: Property
142
bounds: list[float]
143
result_limit: int
144
result_offset: int
145
146
Rtree = Index # Alias for backward compatibility
147
148
class Item:
149
id: int
150
object: object
151
bounds: list[float]
152
bbox: list[float]
153
154
class Property:
155
type: int
156
variant: int
157
dimension: int
158
storage: int
159
pagesize: int
160
index_capacity: int
161
leaf_capacity: int
162
overwrite: bool
163
writethrough: bool
164
fill_factor: float
165
166
class RTreeError(Exception):
167
pass
168
169
class InvalidHandleException(Exception):
170
pass
171
172
class RtreeContainer:
173
def __init__(self, *args: Any, **kwargs: Any) -> None: ...
174
def insert(self, obj: object, coordinates: Any) -> None: ...
175
def delete(self, obj: object, coordinates: Any) -> None: ...
176
def intersection(self, coordinates: Any, bbox: bool = False) -> Iterator: ...
177
def nearest(self, coordinates: Any, num_results: int = 1, bbox: bool = True) -> Iterator: ...
178
179
# Constants
180
RT_RTree: int # = 0
181
RT_MVRTree: int # = 1
182
RT_TPRTree: int # = 2
183
184
RT_Linear: int # = 0
185
RT_Quadratic: int # = 1
186
RT_Star: int # = 2
187
188
RT_Memory: int # = 0
189
RT_Disk: int # = 1
190
RT_Custom: int # = 2
191
```