Class Documentation

class rtree.index.Index(*args, **kwargs)

An R-Tree, MVR-Tree, or TPR-Tree indexing object

__init__(*args, **kwargs)

Creates a new index

Parameters:
  • filename – The first argument in the constructor is assumed to be a filename determining that a file-based storage for the index should be used. If the first argument is not of type basestring, it is then assumed to be an instance of ICustomStorage or derived class. If the first argument is neither of type basestring nor an instance of ICustomStorage, it is then assumed to be an input index item stream.

  • stream

    If the first argument in the constructor is not of type basestring, it is assumed to be an iterable stream of data that will raise a StopIteration. It must be in the form defined by the interleaved attribute of the index. The following example would assume interleaved is False:

    (id,
     (minx, maxx, miny, maxy, minz, maxz, ..., ..., mink, maxk),
     object)
    

    The object can be None, but you must put a place holder of None there.

    For a TPR-Tree, this would be in the form:

    (id,
     ((minx, maxx, miny, maxy, ..., ..., mink, maxk),
      (minvx, maxvx, minvy, maxvy, ..., ..., minvk, maxvk),
      time),
     object)
    

  • storage – If the first argument in the constructor is an instance of ICustomStorage then the given custom storage is used.

  • interleaved – True or False, defaults to True. This parameter determines the coordinate order for all methods that take in coordinates.

  • properties – An index.Property object. This object sets both the creation and instantiation properties for the object and they are passed down into libspatialindex. A few properties are curried from instantiation parameters for you like pagesize and overwrite to ensure compatibility with previous versions of the library. All other properties must be set on the object.

Warning

The coordinate ordering for all functions are sensitive the index’s interleaved data member. If interleaved is False, the coordinates must be in the form [xmin, xmax, ymin, ymax, …, …, kmin, kmax]. If interleaved is True, the coordinates must be in the form [xmin, ymin, …, kmin, xmax, ymax, …, kmax]. This also applies to velocities when using a TPR-Tree.

A basic example

>>> from rtree import index
>>> p = index.Property()

>>> idx = index.Index(properties=p)
>>> idx  
rtree.index.Index(bounds=[1.7976931348623157e+308,
                        1.7976931348623157e+308,
                        -1.7976931348623157e+308,
                        -1.7976931348623157e+308],
                        size=0)

Insert an item into the index:

>>> idx.insert(4321,
...            (34.3776829412, 26.7375853734, 49.3776829412,
...             41.7375853734),
...            obj=42)

Query:

>>> hits = idx.intersection((0, 0, 60, 60), objects=True)
>>> for i in hits:
...     if i.id == 4321:
...         i.object
...         i.bbox
... 
42
[34.37768294..., 26.73758537..., 49.37768294..., 41.73758537...]

Using custom serializers:

>>> class JSONIndex(index.Index):
...     def dumps(self, obj):
...         # This import is nested so that the doctest doesn't
...         # require simplejson.
...         import simplejson
...         return simplejson.dumps(obj).encode('ascii')
...
...     def loads(self, string):
...         import simplejson
...         return simplejson.loads(string.decode('ascii'))

>>> stored_obj = {"nums": [23, 45], "letters": "abcd"}
>>> json_idx = JSONIndex()
>>> try:
...     json_idx.insert(1, (0, 1, 0, 1), stored_obj)
...     list(json_idx.nearest((0, 0), 1,
...                           objects="raw")) == [stored_obj]
... except ImportError:
...     True
True
property bounds

Returns the bounds of the index

Parameters:

coordinate_interleaved – If True, the coordinates are turned in the form [xmin, ymin, …, kmin, xmax, ymax, …, kmax], otherwise they are returned as [xmin, xmax, ymin, ymax, …, …, kmin, kmax]. If not specified, the interleaved member of the index is used, which defaults to True.

close()

Force a flush of the index to storage. Renders index inaccessible.

count(coordinates)

Return number of objects that intersect the given coordinates.

Parameters:

coordinates (Any) – This may be an object that satisfies the numpy array protocol, providing the index’s dimension * 2 coordinate pairs representing the mink and maxk coordinates in each dimension defining the bounds of the query window. For a TPR-Tree, this must be a 3-element sequence including not only the positional coordinate pairs but also the velocity pairs minvk and maxvk and a time pair for the time range as a float.

The following example queries the index for any objects any objects that were stored in the index intersect the bounds given in the coordinates:

>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321,
...            (34.3776829412, 26.7375853734, 49.3776829412,
...             41.7375853734),
...            obj=42)

>>> print(idx.count((0, 0, 60, 60)))
1

This example is similar for a TPR-Tree:

>>> p = index.Property(type=index.RT_TPRTree)  
>>> idx = index.Index(properties=p)  
>>> idx.insert(4321,
...            ((34.3776829412, 26.7375853734, 49.3776829412,
...             41.7375853734),
...             (0.5, 2, 1.5, 2.5),
...             3.0),
...            obj=42)  

>>> print(idx.count(((0, 0, 60, 60), (0, 0, 0, 0), (3, 5))))
... 
1
delete(id, coordinates)
Deletes an item from the index with the given 'id' and

coordinates given by the coordinates sequence. As the index can contain multiple items with the same ID and coordinates, deletion is not guaranteed to delete all items in the index with the given ID and coordinates.

Parameters:
  • id (int) – A long integer ID for the entry, which need not be unique. The index can contain multiple entries with identical IDs and coordinates. Uniqueness of items should be enforced at the application level by the user.

  • coordinates (Any) – Dimension * 2 coordinate pairs, representing the min and max coordinates in each dimension of the item to be deleted from the index. Their ordering will depend on the index’s interleaved data member. These are not the coordinates of a space containing the item, but those of the item itself. Together with the id parameter, they determine which item will be deleted. This may be an object that satisfies the numpy array protocol. For a TPR-Tree, this must be a 3-element sequence including not only the positional coordinate pairs but also the velocity pairs minvk and maxvk and a time pair for the original time the object was inserted and the current time as a float.

Example:

>>> from rtree import index
>>> idx = index.Index()
>>> idx.delete(4321,
...            (34.3776829412, 26.7375853734, 49.3776829412,
...             41.7375853734))

For the TPR-Tree:

>>> p = index.Property(type=index.RT_TPRTree)  
>>> idx = index.Index(properties=p)  
>>> idx.delete(4321,
...            ((34.3776829412, 26.7375853734, 49.3776829412,
...             41.7375853734),
...             (0.5, 2, 1.5, 2.5),
...             (3.0, 5.0)))  
insert(id, coordinates, obj=None)

Inserts an item into the index with the given coordinates.

Parameters:
  • id (int) – A long integer that is the identifier for this index entry. IDs need not be unique to be inserted into the index, and it is up to the user to ensure they are unique if this is a requirement.

  • coordinates (Any) – This may be an object that satisfies the numpy array protocol, providing the index’s dimension * 2 coordinate pairs representing the mink and maxk coordinates in each dimension defining the bounds of the query window. For a TPR-Tree, this must be a 3-element sequence including not only the positional coordinate pairs but also the velocity pairs minvk and maxvk and a time value as a float.

  • obj (object) – a pickleable object. If not None, this object will be stored in the index with the id.

The following example inserts an entry into the index with id 4321, and the object it stores with that id is the number 42. The coordinate ordering in this instance is the default (interleaved=True) ordering:

>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321,
...            (34.3776829412, 26.7375853734, 49.3776829412,
...             41.7375853734),
...            obj=42)

This example is inserting the same object for a TPR-Tree, additionally including a set of velocities at time 3:

>>> p = index.Property(type=index.RT_TPRTree)  
>>> idx = index.Index(properties=p)  
>>> idx.insert(4321,
...            ((34.3776829412, 26.7375853734, 49.3776829412,
...             41.7375853734),
...             (0.5, 2, 1.5, 2.5),
...            3.0),
...            obj=42)  
intersection(coordinates: Any, objects: Literal[True]) Iterator[Item]
intersection(coordinates: Any, objects: Literal[False] = False) Iterator[int]
intersection(coordinates: Any, objects: Literal['raw']) Iterator[object]

Return ids or objects in the index that intersect the given coordinates.

Parameters:
  • coordinates – This may be an object that satisfies the numpy array protocol, providing the index’s dimension * 2 coordinate pairs representing the mink and maxk coordinates in each dimension defining the bounds of the query window. For a TPR-Tree, this must be a 3-element sequence including not only the positional coordinate pairs but also the velocity pairs minvk and maxvk and a time pair for the time range as a float.

  • objects – If True, the intersection method will return index objects that were pickled when they were stored with each index entry, as well as the id and bounds of the index entries. If ‘raw’, the objects will be returned without the rtree.index.Item wrapper.

The following example queries the index for any objects any objects that were stored in the index intersect the bounds given in the coordinates:

>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321,
...            (34.3776829412, 26.7375853734, 49.3776829412,
...             41.7375853734),
...            obj=42)

>>> hits = list(idx.intersection((0, 0, 60, 60), objects=True))
>>> [(item.object, item.bbox) for item in hits if item.id == 4321]
... 
[(42, [34.37768294..., 26.73758537..., 49.37768294...,
       41.73758537...])]

If the rtree.index.Item wrapper is not used, it is faster to request the ‘raw’ objects:

>>> list(idx.intersection((0, 0, 60, 60), objects="raw"))
[42]

Similar for the TPR-Tree:

>>> p = index.Property(type=index.RT_TPRTree)  
>>> idx = index.Index(properties=p)  
>>> idx.insert(4321,
...            ((34.3776829412, 26.7375853734, 49.3776829412,
...             41.7375853734),
...             (0.5, 2, 1.5, 2.5),
...             3.0),
...            obj=42)  

>>> hits = list(idx.intersection(
...     ((0, 0, 60, 60), (0, 0, 0, 0), (3, 5)), objects=True))
...  
>>> [(item.object, item.bbox) for item in hits if item.id == 4321]
... 
[(42, [34.37768294..., 26.73758537..., 49.37768294...,
       41.73758537...])]
nearest(coordinates: Any, num_results: int, objects: Literal[True]) Iterator[Item]
nearest(coordinates: Any, num_results: int, objects: Literal[False] = False) Iterator[int]
nearest(coordinates: Any, num_results: int, objects: Literal['raw']) Iterator[object]

Returns the k-nearest objects to the given coordinates.

Parameters:
  • coordinates – This may be an object that satisfies the numpy array protocol, providing the index’s dimension * 2 coordinate pairs representing the mink and maxk coordinates in each dimension defining the bounds of the query window. For a TPR-Tree, this must be a 3-element sequence including not only the positional coordinate pairs but also the velocity pairs minvk and maxvk and a time pair for the time range as a float.

  • num_results – The number of results to return nearest to the given coordinates. If two index entries are equidistant, both are returned. This property means that num_results may return more items than specified

  • objects – If True, the nearest method will return index objects that were pickled when they were stored with each index entry, as well as the id and bounds of the index entries. If ‘raw’, it will return the object as entered into the database without the rtree.index.Item wrapper.

Warning

This is currently not implemented for the TPR-Tree.

Example of finding the three items nearest to this one:

>>> from rtree import index
>>> idx = index.Index()
>>> idx.insert(4321, (34.37, 26.73, 49.37, 41.73), obj=42)
>>> hits = idx.nearest((0, 0, 10, 10), 3, objects=True)
class rtree.index.Property(handle=None, owned=True, **kwargs)

An index property object is a container that contains a number of settable index properties. Many of these properties must be set at index creation times, while others can be used to adjust performance or behavior.

property buffering_capacity: int

Buffering capacity

property custom_storage_callbacks

Callbacks for custom storage

property custom_storage_callbacks_size: int

Size of callbacks for custom storage

property dat_extension

Extension for .dat file

property dimension: int

Index dimension. Must be greater than 0, though a dimension of 1 might have undefined behavior.

property filename

Index filename for disk storage

property fill_factor: int

Index node fill factor before branching

property idx_extension

Extension for .idx file

property index_capacity: int

Index capacity

property index_id

First node index id

property index_pool_capacity: int

Index pool capacity

property leaf_capacity: int

Leaf capacity

property near_minimum_overlap_factor: int

Overlap factor for MVRTrees

property overwrite

Overwrite existing index files

property pagesize: int

The pagesize when disk storage is used. It is ideal to ensure that your index entries fit within a single page for best performance.

property point_pool_capacity: int

Point pool capacity

property region_pool_capacity: int

Region pool capacity

property reinsert_factor

Reinsert factor

property split_distribution_factor: int

Split distribution factor

property storage: int

Index storage.

One of RT_Disk, RT_Memory or RT_Custom.

If a filename is passed as the first parameter to :class:index.Index, RT_Disk is assumed. If a CustomStorage instance is passed, RT_Custom is assumed. Otherwise, RT_Memory is the default.

property tight_mbr

Uses tight bounding rectangles

property tpr_horizon

TPR horizon

property type: int

Index type. Valid index type values are RT_RTree, RT_MVTree, or RT_TPRTree. Only RT_RTree (the default) is practically supported at this time.

property variant: int

Index variant. Valid index variant values are RT_Linear, RT_Quadratic, and RT_Star

property writethrough

Write through caching

class rtree.index.Item(loads, handle, owned=False)

A container for index entries

__init__(loads, handle, owned=False)

There should be no reason to instantiate these yourself. Items are created automatically when you call rtree.index.Index.intersection() (or other index querying methods) with objects=True given the parameters of the function.

property bbox: list[float]

Returns the bounding box of the index entry