R-Tree spatial index for Python GIS
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
High-level container for storing Python objects with spatial coordinates, providing a more Pythonic interface for spatial data management without explicit ID management. The RtreeContainer class automatically handles ID assignment and provides object-centric operations.
Create spatial containers for storing Python objects with automatic ID management.
class RtreeContainer:
def __init__(self, *args, **kwargs):
"""
Create a spatial container for Python objects.
Parameters:
- *args, **kwargs: Same parameters as Index constructor
The container automatically manages object IDs and provides
object-centric spatial operations.
"""Insert Python objects with associated spatial coordinates into the container.
def insert(self, obj, coordinates):
"""
Insert a Python object with spatial coordinates.
Parameters:
- obj (object): Python object to store
- coordinates (sequence): Bounding box as (minx, miny, maxx, maxy)
The container automatically assigns an internal ID to the object.
"""
def add(self, obj, coordinates):
"""Alias for insert method."""Remove Python objects from the container by object reference and coordinates.
def delete(self, obj, coordinates):
"""
Delete a Python object from the container.
Parameters:
- obj (object): Object to remove (must be the same object reference)
- coordinates (sequence): Bounding box used during insertion
Uses object identity to locate and remove the object.
"""Perform spatial queries that return actual Python objects instead of IDs.
def intersection(self, coordinates, bbox=False):
"""
Find objects that intersect with given coordinates.
Parameters:
- coordinates (sequence): Query bounding box
- bbox (bool): If True, return (object, bbox) tuples
Returns:
Generator yielding stored objects or (object, bbox) tuples
"""
def nearest(self, coordinates, num_results=1, bbox=False):
"""
Find nearest objects to given coordinates.
Parameters:
- coordinates (sequence): Query point or bounding box
- num_results (int): Number of results to return
- bbox (bool): If True, return (object, bbox) tuples
Returns:
Generator yielding stored objects or (object, bbox) tuples
"""Standard Python container operations for object management and introspection.
def __contains__(self, obj):
"""
Check if object is stored in container.
Parameters:
- obj (object): Object to check
Returns:
bool: True if object is in container
"""
def __len__(self):
"""
Get number of unique objects in container.
Returns:
int: Count of stored objects
"""
def __iter__(self):
"""
Iterate over all stored objects.
Returns:
Iterator yielding stored objects
"""Access leaf node information with actual stored objects instead of IDs.
def leaves(self):
"""
Get leaf node information with actual objects.
Returns:
Generator yielding (node_id, bbox, objects) tuples where
objects is a list of actual stored Python objects
"""from rtree.index import RtreeContainer
# Create container
container = RtreeContainer()
# Insert objects with coordinates
buildings = [
{"name": "City Hall", "type": "government"},
{"name": "Library", "type": "public"},
{"name": "Mall", "type": "commercial"}
]
container.insert(buildings[0], (10, 10, 20, 20))
container.insert(buildings[1], (15, 15, 25, 25))
container.insert(buildings[2], (30, 30, 40, 40))
# Query operations return actual objects
nearby = list(container.intersection((12, 12, 18, 18)))
# [{"name": "City Hall", "type": "government"}, {"name": "Library", "type": "public"}]
closest = list(container.nearest((5, 5, 5, 5), 1))
# [{"name": "City Hall", "type": "government"}]from rtree.index import RtreeContainer
container = RtreeContainer()
# Insert objects
container.insert({"id": 1, "name": "Park"}, (0, 0, 100, 100))
container.insert({"id": 2, "name": "School"}, (50, 50, 150, 150))
# Get objects with their bounding boxes
results = list(container.intersection((25, 25, 75, 75), bbox=True))
# [({"id": 1, "name": "Park"}, (0, 0, 100, 100)),
# ({"id": 2, "name": "School"}, (50, 50, 150, 150))]
nearest_with_bbox = list(container.nearest((0, 0, 0, 0), 1, bbox=True))
# [({"id": 1, "name": "Park"}, (0, 0, 100, 100))]from rtree.index import RtreeContainer
container = RtreeContainer()
# Store various object types
objects = [
{"type": "point", "coords": [10, 20]},
{"type": "line", "length": 50},
[1, 2, 3, 4] # Even lists can be stored
]
for i, obj in enumerate(objects):
container.insert(obj, (i*10, i*10, (i+1)*10, (i+1)*10))
# Check membership
print(objects[0] in container) # True
print({"type": "point", "coords": [10, 20]} in container) # False (different object)
# Container size
print(len(container)) # 3
# Iterate over all objects
for obj in container:
print(obj)from rtree.index import RtreeContainer
container = RtreeContainer()
# Insert objects (keep references)
obj1 = {"name": "Building A"}
obj2 = {"name": "Building B"}
container.insert(obj1, (0, 0, 10, 10))
container.insert(obj2, (5, 5, 15, 15))
print(len(container)) # 2
# Delete by object reference
container.delete(obj1, (0, 0, 10, 10))
print(len(container)) # 1
# Remaining object
remaining = list(container)
print(remaining) # [{"name": "Building B"}]from rtree.index import RtreeContainer
class SpatialObject:
def __init__(self, name, geometry):
self.name = name
self.geometry = geometry
def __repr__(self):
return f"SpatialObject('{self.name}')"
container = RtreeContainer()
# Store custom objects
objects = [
SpatialObject("River", "LINESTRING(0 0, 100 100)"),
SpatialObject("Lake", "POLYGON((10 10, 20 10, 20 20, 10 20, 10 10))"),
SpatialObject("Mountain", "POINT(50 75)")
]
container.insert(objects[0], (0, 0, 100, 100))
container.insert(objects[1], (10, 10, 20, 20))
container.insert(objects[2], (50, 75, 50, 75))
# Query returns actual custom objects
features = list(container.intersection((15, 15, 60, 60)))
for feature in features:
print(f"{feature.name}: {feature.geometry}")from rtree.index import RtreeContainer
container = RtreeContainer()
# Add several objects
for i in range(10):
obj = {"id": i, "value": f"object_{i}"}
container.insert(obj, (i, i, i+5, i+5))
# Inspect leaf nodes with actual objects
for node_id, bbox, objects in container.leaves():
print(f"Node {node_id} (bbox: {bbox}) contains {len(objects)} objects:")
for obj in objects:
print(f" {obj}")Install with Tessl CLI
npx tessl i tessl/pypi-rtree