CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-rtree

R-Tree spatial index for Python GIS

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

utilities.mddocs/

Utilities and Support

Utility functions for library management, exception handling, coordinate format conversion, and supporting classes that enhance the Rtree functionality.

Capabilities

Library Management

Functions for loading and managing the underlying libspatialindex library.

def load() -> ctypes.CDLL:
    """
    Load the libspatialindex shared library.
    
    Searches for the library in several locations:
    - SPATIALINDEX_C_LIBRARY environment variable
    - Package installation directory
    - System library paths
    - Conda environment paths (if applicable)
    
    Returns:
    ctypes.CDLL: Loaded shared library object
    
    Raises:
    OSError: If library cannot be found or loaded
    """

def get_include() -> str:
    """
    Return the directory containing spatialindex header files.
    
    Useful for building extensions or custom storage implementations.
    Searches in:
    - Package installation directory  
    - System include paths
    - Conda environment paths
    
    Returns:
    str: Path to include directory or empty string if not found
    """

Usage example:

from rtree import finder

# Load the library explicitly (usually done automatically)
try:
    lib = finder.load()
    print(f"Loaded library: {lib}")
except OSError as e:
    print(f"Failed to load library: {e}")

# Get include directory for development
include_dir = finder.get_include()
if include_dir:
    print(f"Headers available at: {include_dir}")
else:
    print("Headers not found")

Exception Handling

Exception classes for error handling in spatial indexing operations.

class RTreeError(Exception):
    """
    Main exception class for RTree-related errors.
    
    Raised for various error conditions including:
    - Invalid coordinate specifications
    - Library initialization failures
    - Storage or I/O errors
    - Invalid property values
    - Memory allocation errors
    """
    pass

class InvalidHandleException(Exception):
    """
    Exception raised when attempting to use a destroyed handle.
    
    Handles become invalid after the associated index or property
    object has been destroyed or closed.
    """
    pass

Usage example:

from rtree import index
from rtree.exceptions import RTreeError

try:
    idx = index.Index()
    # Invalid coordinates (min > max)
    idx.insert(0, (1.0, 1.0, 0.0, 0.0))
except RTreeError as e:
    print(f"Spatial index error: {e}")

try:
    # Invalid property value
    p = index.Property()
    p.pagesize = -1000
except RTreeError as e:
    print(f"Property error: {e}")

Coordinate Format Conversion

Utility methods for converting between coordinate formats.

@classmethod
def interleave(cls, deinterleaved: Sequence[float]) -> list[float]:
    """
    Convert non-interleaved coordinates to interleaved format.
    
    Parameters:
    - deinterleaved (sequence): Coordinates in [minx, maxx, miny, maxy, ...] format
    
    Returns:
    list: Coordinates in [minx, miny, maxx, maxy, ...] format
    
    Example:
    [0, 2, 1, 3] -> [0, 1, 2, 3]  # 2D case
    """

@classmethod  
def deinterleave(cls, interleaved: Sequence[object]) -> list[object]:
    """
    Convert interleaved coordinates to non-interleaved format.
    
    Parameters:
    - interleaved (sequence): Coordinates in [minx, miny, maxx, maxy, ...] format
    
    Returns:
    list: Coordinates in [minx, maxx, miny, maxy, ...] format
    
    Example:
    [0, 1, 2, 3] -> [0, 2, 1, 3]  # 2D case
    """

Usage example:

from rtree import index

# Convert coordinate formats
interleaved_coords = [0, 1, 2, 3]  # minx, miny, maxx, maxy
non_interleaved = index.Index.deinterleave(interleaved_coords)
print(non_interleaved)  # [0, 2, 1, 3] - minx, maxx, miny, maxy

# Convert back
back_to_interleaved = index.Index.interleave(non_interleaved)
print(back_to_interleaved)  # [0, 1, 2, 3]

Query Result Container

Container class for query results that provides access to item details.

class Item:
    """
    Container for index entries returned by query operations.
    
    Automatically created when using objects=True in query methods.
    Should not be instantiated directly.
    """
    
    id: int
    """
    Unique identifier of the index entry.
    """
    
    object: object
    """
    Python object stored with the entry (may be None).
    """
    
    bounds: list[float]
    """
    Bounding box coordinates in non-interleaved format.
    Format: [minx, maxx, miny, maxy, minz, maxz, ...]
    """
    
    @property
    def bbox(self) -> list[float]:
        """
        Bounding box coordinates in interleaved format.
        
        Returns:
        list: Coordinates in [minx, miny, maxx, maxy, ...] format
        """
    
    def __lt__(self, other: Item) -> bool:
        """
        Less than comparison based on item ID.
        
        Parameters:
        - other (Item): Another Item object
        
        Returns:
        bool: True if this item's ID is less than other's ID
        """
    
    def __gt__(self, other: Item) -> bool:
        """
        Greater than comparison based on item ID.
        
        Parameters:
        - other (Item): Another Item object
        
        Returns:
        bool: True if this item's ID is greater than other's ID
        """

Usage example:

from rtree import index

idx = index.Index()
idx.insert(0, (0, 0, 1, 1), obj="Rectangle A")
idx.insert(1, (0.5, 0.5, 1.5, 1.5), obj="Rectangle B")

# Query returns Item objects
for item in idx.intersection((0, 0, 2, 2), objects=True):
    print(f"ID: {item.id}")
    print(f"Object: {item.object}")
    print(f"Bounds (non-interleaved): {item.bounds}")
    print(f"BBox (interleaved): {item.bbox}")
    print("---")

# Items can be sorted by ID
items = list(idx.intersection((0, 0, 2, 2), objects=True))
items.sort()  # Sorts by ID using __lt__
print([item.id for item in items])  # [0, 1]

Internal Handle Classes

Low-level handle classes for advanced usage and custom storage implementations.

class Handle:
    """
    Base handle class for internal resource management.
    
    Handles the lifecycle of underlying C library objects.
    """
    
    def __init__(self, *args: Any, **kwargs: Any) -> None:
        """Initialize handle with C library resources."""
    
    def destroy(self) -> None:
        """Destroy handle and free associated resources."""
    
    @property
    def _as_parameter_(self) -> ctypes.c_void_p:
        """Return handle as ctypes parameter for C library calls."""

class IndexHandle(Handle):
    """
    Handle for spatial index objects.
    
    Manages the connection to libspatialindex index instances.
    """
    
    def flush(self) -> None:
        """Flush pending operations to storage."""

class IndexStreamHandle(IndexHandle):
    """
    Handle for stream-based index operations.
    
    Used during bulk loading from data streams.
    """

class IndexArrayHandle(IndexHandle):
    """
    Handle for array-based bulk operations (optional).
    
    Available when libspatialindex supports array operations.
    """

class PropertyHandle(Handle):
    """
    Handle for property objects.
    
    Manages property configuration in the C library.
    """

Note: Handle classes are primarily for internal use and custom storage implementations. Most users should not need to interact with them directly.

Version Information

Access version information for the library and its components.

__version__: str
"""Rtree Python package version string."""

__c_api_version__: bytes  
"""libspatialindex C library version (as bytes)."""

major_version: int
"""Major version of libspatialindex C library."""

minor_version: int  
"""Minor version of libspatialindex C library."""

patch_version: int
"""Patch version of libspatialindex C library."""

Usage example:

from rtree import __version__
from rtree.index import __c_api_version__, major_version, minor_version, patch_version

print(f"Rtree Python version: {__version__}")  # "1.4.1"
print(f"libspatialindex version: {__c_api_version__.decode('utf-8')}")  # C library version
print(f"C library version components: {major_version}.{minor_version}.{patch_version}")

Constants and Enumerations

Named constants for configuring index behavior.

# Index Types
RT_RTree = 0      # Standard R-Tree
RT_MVRTree = 1    # Multi-Version R-Tree  
RT_TPRTree = 2    # Time-Parameterized R-Tree

# Index Variants  
RT_Linear = 0     # Linear splitting algorithm
RT_Quadratic = 1  # Quadratic splitting algorithm
RT_Star = 2       # R*-Tree splitting algorithm

# Storage Types
RT_Memory = 0     # Memory-based storage
RT_Disk = 1       # File-based storage
RT_Custom = 2     # Custom storage implementation

Usage example:

from rtree import index

# Use constants for clarity
p = index.Property()
p.type = index.RT_RTree
p.variant = index.RT_Star
p.storage = index.RT_Memory

idx = index.Index(properties=p)

Debug and Inspection Utilities

Tools for inspecting index state and debugging spatial operations.

def get_coordinate_pointers(self, coordinates: Sequence[float]) -> tuple[float, float]:
    """
    Convert coordinates to internal pointer format.
    
    Parameters:
    - coordinates (sequence): Spatial coordinates
    
    Returns:
    tuple: Internal coordinate representation
    
    Note: Primarily for debugging and advanced use cases.
    """

Serialization Support

Built-in serialization methods for index persistence.

def dumps(self, obj: object) -> bytes:
    """
    Serialize an object for storage (default: pickle).
    
    Parameters:
    - obj (object): Object to serialize
    
    Returns:
    bytes: Serialized object data
    
    Note: Override this method to implement custom serialization.
    """

def loads(self, string: bytes) -> object:
    """
    Deserialize an object from storage (default: pickle).
    
    Parameters:
    - string (bytes): Serialized object data
    
    Returns:
    object: Deserialized object
    
    Note: Override this method to implement custom deserialization.
    """

Error Checking Functions

Internal error checking utilities (primarily for development).

# Internal error checking functions
def check_return(result, func, cargs): ...
def check_void(result, func, cargs): ...
def check_value(result, func, cargs): ...

Note: These are internal functions used by the library for C API error checking. They are not part of the public API but may be visible in advanced usage scenarios.

Common Usage Patterns

Robust Error Handling

from rtree import index
from rtree.exceptions import RTreeError

def safe_spatial_operation():
    try:
        idx = index.Index()
        idx.insert(0, (0, 0, 1, 1))
        return list(idx.intersection((0, 0, 1, 1)))
    except RTreeError as e:
        print(f"Spatial index error: {e}")
        return []        
    except Exception as e:
        print(f"Unexpected error: {e}")
        return []

Library Validation

from rtree import finder

def check_library_availability():
    try:
        lib = finder.load()
        include_dir = finder.get_include()
        
        print(f"✓ Library loaded successfully")
        if include_dir:
            print(f"✓ Headers available at: {include_dir}")
        else:
            print("⚠ Headers not found (development features limited)")
            
        return True
    except OSError as e:
        print(f"✗ Library not available: {e}")
        return False

Coordinate Format Management

from rtree import index

def normalize_coordinates(coords, target_format="interleaved"):
    """Convert coordinates to specified format."""
    if target_format == "interleaved":
        # Assume input is non-interleaved, convert to interleaved
        return index.Index.interleave(coords)
    else:
        # Assume input is interleaved, convert to non-interleaved  
        return index.Index.deinterleave(coords)

# Usage
non_interleaved = [0, 2, 1, 3]  # minx, maxx, miny, maxy
interleaved = normalize_coordinates(non_interleaved, "interleaved")
print(interleaved)  # [0, 1, 2, 3] - minx, miny, maxx, maxy

Install with Tessl CLI

npx tessl i tessl/pypi-rtree@1.4.1

docs

advanced-features.md

configuration.md

container.md

core-indexing.md

custom-storage.md

index.md

utilities.md

tile.json