Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.2.0] - 2026-08-21

### Added
- `PyRTree.locate_in_envelope_ids()` for stored ids within a closed bounding box.
- `PyRTree.remove_item()` for exact point-and-id removal when points coincide.
- `PyBBoxRTree`, a 2–8 dimensional index for stored axis-aligned bounding boxes,
with insertion, optimized NumPy bulk loading, closed-boundary intersection,
and exact removal.
- `PyBBoxRTree.intersection_batch()` for vectorised queries with CSR-style output.
- Bounding-box bulk loading and batched intersections release the GIL while
running native tree operations.

## [0.1.0] - 2026-06-07

### Added
Expand Down
33 changes: 1 addition & 32 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rstar-python"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
license = "MIT"
description = "Python bindings for the rstar R*-tree spatial index"
Expand All @@ -14,4 +14,4 @@ crate-type = ["cdylib"]
[dependencies]
pyo3 = { version = "0.28", features = ["extension-module", "abi3-py310"] }
numpy = "0.28"
rstar = { version = "0.13", features = ["serde"] }
rstar = "0.13"
52 changes: 41 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

Python bindings for the [rstar](https://github.com/georust/rstar) R*-tree spatial index library.

A fast, **dynamic** spatial index for points in 2–8 dimensions: insert and remove
points after construction, run nearest-neighbour and radius searches, and query
axis-aligned bounding boxes. Each point can carry an integer id so queries can
return references to *your* data, not just coordinates.
A fast, **dynamic** spatial index for points and stored axis-aligned bounding
boxes in 2–8 dimensions. Insert and remove items after construction, run
nearest-neighbour and radius searches, and query spatial regions. Each item can
carry an integer id so queries can return references to *your* data.

## Installation

Expand Down Expand Up @@ -35,7 +35,7 @@ easy prebuilt wheels and no C/C++ system dependency.

```python
import numpy as np
from rstar_python import PyRTree
from rstar_python import PyBBoxRTree, PyRTree

# Create a 3D R-tree
tree = PyRTree(dims=3)
Expand All @@ -56,6 +56,10 @@ tree.nearest_neighbor([1.1, 2.1, 3.1]) # -> [1.0, 2.0, 3.0]
tree.k_nearest_neighbors([1.1, 2.1, 3.1], k=2) # -> [[...], [...]]
tree.neighbors_within_radius([1.0, 2.0, 3.0], radius=1.0)
tree.locate_in_envelope(min_corner=[0, 0, 0], max_corner=[2, 2, 2])
tree.locate_in_envelope_ids([0, 0, 0], [2, 2, 2]) # stored ids, closed AABB

# Remove an exact point+id when coordinates are shared by multiple items.
tree.remove_item([1.0, 2.0, 3.0], data=10)

# --- Vectorised, id-returning queries (scipy/sklearn style) ---
query_pts = np.array([[1.1, 2.1, 3.1], [7.0, 8.0, 9.0]], dtype=np.float64)
Expand All @@ -70,18 +74,41 @@ len(tree) # number of points
tree.dims # 3
[1.0, 2.0, 3.0] in tree # membership test
tree.remove([1.0, 2.0, 3.0])

# --- Stored bounding boxes ---
boxes = PyBBoxRTree(dims=2)
boxes.insert([0.0, 0.0], [2.0, 2.0], data=100)
boxes.insert([2.0, 1.0], [3.0, 3.0])
# Returns both ids: intersection uses closed bounds, so touching counts.
boxes.intersection([1.0, 1.0], [2.0, 2.0])

# Query many boxes in one native call. Results use CSR-style row offsets:
# the matches for row i are ids[offsets[i]:offsets[i + 1]].
query_mins = np.array([[0.0, 0.0], [5.0, 5.0]], dtype=np.float64)
query_maxs = np.array([[2.0, 2.0], [6.0, 6.0]], dtype=np.float64)
ids, offsets = boxes.intersection_batch(query_mins, query_maxs)

boxes.remove_item([0.0, 0.0], [2.0, 2.0], data=100)

# Bulk loading replaces the stored boxes.
boxes.bulk_load(
min_corners=[[0.0, 0.0], [5.0, 5.0]],
max_corners=[[1.0, 1.0], [6.0, 6.0]],
data=[10, 20],
)
```

## Features

- Points in 2–8 dimensions
- Dynamic `insert` / `remove`
- Per-point integer ids (auto-assigned or supplied)
- Points and stored axis-aligned bounding boxes in 2–8 dimensions
- Dynamic insertion and exact item removal
- Per-item integer ids (auto-assigned or supplied)
- Nearest-neighbour and k-nearest-neighbour queries
- Radius search and axis-aligned bounding-box (envelope) queries
- Vectorised `query` / `query_radius` over a numpy array of points, returning
distances and ids
- Bulk loading (lists or numpy arrays) for fast construction
- Vectorised point `query` / `query_radius` and bounding-box
`intersection_batch` queries over NumPy arrays
- NumPy-native batched intersection results without Python integer boxing
- Bulk loading (lists or NumPy arrays) for fast construction
- Type stubs (`py.typed`) for IDE and `mypy` support
- Built on the fast Rust [rstar](https://github.com/georust/rstar) library

Expand All @@ -106,6 +133,9 @@ maturin develop --release

# Run tests
pytest python/tests -v

# Run the bounding-box performance benchmark
python python/benchmarks/benchmark_bbox_rtree.py
```

## License
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "maturin"

[project]
name = "rstar-python"
version = "0.1.0"
version = "0.2.0"
description = "Python bindings for the rstar R*-tree spatial index"
readme = "README.md"
license = {text = "MIT"}
Expand Down
102 changes: 102 additions & 0 deletions python/benchmarks/benchmark_bbox_rtree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""Reproducible microbenchmark for bounding-box bulk loads and intersections."""

from __future__ import annotations

import argparse
import gc
import json
import statistics
import time
from collections.abc import Callable
from typing import Any

import numpy as np
import numpy.typing as npt

from rstar_python import PyBBoxRTree

FloatArray = npt.NDArray[np.float64]


def make_boxes(
rng: np.random.Generator, rows: int, dims: int, size: float
) -> tuple[FloatArray, FloatArray]:
mins = rng.random((rows, dims), dtype=np.float64)
maxs = mins + rng.random((rows, dims), dtype=np.float64) * size
return mins, maxs


def median_seconds(function: Callable[[], Any], repeats: int) -> float:
function() # Warm native code and allocations before measuring.
samples: list[float] = []
for _ in range(repeats):
gc.disable()
start = time.perf_counter()
result = function()
samples.append(time.perf_counter() - start)
gc.enable()
del result
return statistics.median(samples)


def run_benchmark(
num_boxes: int, num_queries: int, dims: int, repeats: int
) -> dict[str, float | int]:
rng = np.random.default_rng(42)
mins, maxs = make_boxes(rng, num_boxes, dims, 0.005)
query_mins, query_maxs = make_boxes(rng, num_queries, dims, 0.05)
ids = np.arange(num_boxes, dtype=np.int64)

def build() -> PyBBoxRTree:
tree = PyBBoxRTree(dims)
tree.bulk_load(mins, maxs, ids)
return tree

bulk_seconds = median_seconds(build, repeats)
tree = build()

def scalar_list() -> int:
return sum(
len(tree.intersection(lower, upper))
for lower, upper in zip(query_mins, query_maxs, strict=True)
)

def batch() -> int:
result_ids, offsets = tree.intersection_batch(query_mins, query_maxs)
assert offsets[-1] == len(result_ids)
return len(result_ids)

hits = scalar_list()
assert batch() == hits
scalar_list_seconds = median_seconds(scalar_list, repeats)
batch_seconds = median_seconds(batch, repeats)

return {
"boxes": num_boxes,
"queries": num_queries,
"dims": dims,
"hits": hits,
"bulk_seconds": bulk_seconds,
"scalar_list_seconds": scalar_list_seconds,
"batch_seconds": batch_seconds,
"batch_speedup_over_list": scalar_list_seconds / batch_seconds,
}


def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--boxes", type=int, default=200_000)
parser.add_argument("--queries", type=int, default=20_000)
parser.add_argument("--dims", type=int, default=3)
parser.add_argument("--repeats", type=int, default=7)
args = parser.parse_args()
print(
json.dumps(
run_benchmark(args.boxes, args.queries, args.dims, args.repeats),
indent=2,
)
)


if __name__ == "__main__":
main()
4 changes: 2 additions & 2 deletions python/rstar_python/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from .rstar_python import PyRTree, __version__
from .rstar_python import PyBBoxRTree, PyRTree, __version__

__all__ = ["PyRTree", "__version__"]
__all__ = ["PyBBoxRTree", "PyRTree", "__version__"]
68 changes: 68 additions & 0 deletions python/rstar_python/rstar_python.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ class PyRTree:
) -> list[list[float]]:
"""Coordinates of all points inside the axis-aligned box."""

def locate_in_envelope_ids(
self, min_corner: Sequence[float], max_corner: Sequence[float]
) -> list[int]:
"""Ids of all points inside the closed axis-aligned box."""

def query(
self, points: npt.NDArray[np.float64], k: int = ...
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.int64]]:
Expand All @@ -69,9 +74,72 @@ class PyRTree:
def remove(self, point: Sequence[float]) -> bool:
"""Remove a point by coordinates. Returns ``True`` if one was removed."""

def remove_item(self, point: Sequence[float], data: int) -> bool:
"""Remove the point with exactly matching coordinates and id."""

def size(self) -> int:
"""Number of points in the tree."""

def __len__(self) -> int: ...
def __contains__(self, point: Sequence[float]) -> bool: ...
def __repr__(self) -> str: ...

class PyBBoxRTree:
"""An R*-tree spatial index over axis-aligned bounding boxes.

Corner arguments are normalized per axis, so either corner order is
accepted for inserts and queries. Bulk loading and batched intersections
release the GIL during native tree operations. Synchronize mutation of the
same instance while a batch is in flight to avoid an ``Already borrowed``
runtime error.
"""

def __init__(self, dims: int) -> None: ...
@property
def dims(self) -> int:
"""Number of dimensions this tree indexes."""

def insert(
self,
min_corner: Sequence[float],
max_corner: Sequence[float],
data: int | None = ...,
) -> int:
"""Insert a bounding box, returning its id."""

def bulk_load(
self,
min_corners: Sequence[Sequence[float]] | npt.NDArray[np.float64],
max_corners: Sequence[Sequence[float]] | npt.NDArray[np.float64],
data: Sequence[int] | npt.NDArray[np.int64] | None = ...,
) -> None:
"""Build from bounding boxes at once, replacing existing contents."""

def intersection(
self, min_corner: Sequence[float], max_corner: Sequence[float]
) -> list[int]:
"""Ids of boxes whose closed bounds overlap or touch the query."""

def intersection_batch(
self,
min_corners: npt.NDArray[np.float64],
max_corners: npt.NDArray[np.float64],
) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]:
"""Query many boxes, returning ids and CSR row offsets.

Results for row ``i`` are ``ids[offsets[i]:offsets[i + 1]]``.
"""

def remove_item(
self,
min_corner: Sequence[float],
max_corner: Sequence[float],
data: int,
) -> bool:
"""Remove the box with exactly matching normalized geometry and id."""

def size(self) -> int:
"""Number of bounding boxes in the tree."""

def __len__(self) -> int: ...
def __repr__(self) -> str: ...
Loading
Loading