diff --git a/CHANGELOG.md b/CHANGELOG.md index 6811d46..32034f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/Cargo.lock b/Cargo.lock index a1e7e55..8320df5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -231,13 +231,12 @@ checksum = "5912b862fa5ffb462607bfd1e35036c458c537921f508c8235a83d5f3987edfe" dependencies = [ "heapless", "num-traits", - "serde", "smallvec", ] [[package]] name = "rstar-python" -version = "0.1.0" +version = "0.2.0" dependencies = [ "numpy", "pyo3", @@ -250,36 +249,6 @@ version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" -[[package]] -name = "serde" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "smallvec" version = "1.15.1" diff --git a/Cargo.toml b/Cargo.toml index c46fe00..5918e0b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" @@ -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"] } \ No newline at end of file +rstar = "0.13" diff --git a/README.md b/README.md index 3ea5053..257b04a 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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) @@ -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) @@ -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 @@ -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 diff --git a/pyproject.toml b/pyproject.toml index 5af478b..fa35cec 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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"} diff --git a/python/benchmarks/benchmark_bbox_rtree.py b/python/benchmarks/benchmark_bbox_rtree.py new file mode 100644 index 0000000..72690ae --- /dev/null +++ b/python/benchmarks/benchmark_bbox_rtree.py @@ -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() diff --git a/python/rstar_python/__init__.py b/python/rstar_python/__init__.py index 6d30a52..9982d92 100644 --- a/python/rstar_python/__init__.py +++ b/python/rstar_python/__init__.py @@ -1,3 +1,3 @@ -from .rstar_python import PyRTree, __version__ +from .rstar_python import PyBBoxRTree, PyRTree, __version__ -__all__ = ["PyRTree", "__version__"] +__all__ = ["PyBBoxRTree", "PyRTree", "__version__"] diff --git a/python/rstar_python/rstar_python.pyi b/python/rstar_python/rstar_python.pyi index 6df411f..14c2fc2 100644 --- a/python/rstar_python/rstar_python.pyi +++ b/python/rstar_python/rstar_python.pyi @@ -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]]: @@ -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: ... diff --git a/python/tests/test_bbox_rtree.py b/python/tests/test_bbox_rtree.py new file mode 100644 index 0000000..45627ff --- /dev/null +++ b/python/tests/test_bbox_rtree.py @@ -0,0 +1,162 @@ +import numpy as np +import pytest + +import rstar_python +from rstar_python import PyBBoxRTree + + +def test_public_export_and_protocols(): + assert rstar_python.PyBBoxRTree is PyBBoxRTree + assert "PyBBoxRTree" in rstar_python.__all__ + + tree = PyBBoxRTree(dims=2) + assert tree.dims == 2 + assert tree.size() == len(tree) == 0 + assert repr(tree) == "PyBBoxRTree(dims=2, size=0)" + + +def test_insert_ids_and_intersection_semantics(): + tree = PyBBoxRTree(dims=2) + assert tree.insert([0.0, 0.0], [4.0, 4.0]) == 0 + assert tree.insert([3.0, 3.0], [6.0, 6.0], data=10) == 10 + assert tree.insert([8.0, 8.0], [9.0, 9.0]) == 11 + + # A query contained by the first box still intersects it; the second only touches. + assert sorted(tree.intersection([1.0, 1.0], [3.0, 3.0])) == [0, 10] + assert sorted(tree.intersection([6.0, 6.0], [8.0, 8.0])) == [10, 11] + assert tree.intersection([6.1, 6.1], [7.9, 7.9]) == [] + + +def test_bulk_load_without_data_assigns_ids_and_advances_counter(): + tree = PyBBoxRTree(dims=2) + mins = np.array([[0.0, 0.0], [5.0, 5.0]], dtype=np.float64) + maxs = mins + 1.0 + tree.bulk_load(mins, maxs) + + assert tree.intersection([0.5, 0.5], [0.5, 0.5]) == [0] + assert tree.intersection([5.5, 5.5], [5.5, 5.5]) == [1] + assert tree.insert([10.0, 10.0], [11.0, 11.0]) == 2 + + +def test_ids_saturate_instead_of_wrapping(): + max_id = 2**63 - 1 + + inserted = PyBBoxRTree(dims=2) + assert inserted.insert([0.0, 0.0], [1.0, 1.0], data=max_id) == max_id + assert inserted.insert([2.0, 2.0], [3.0, 3.0]) == max_id + + bulk_loaded = PyBBoxRTree(dims=2) + bulk_loaded.bulk_load( + np.array([[0.0, 0.0]], dtype=np.float64), + np.array([[1.0, 1.0]], dtype=np.float64), + data=np.array([max_id], dtype=np.int64), + ) + assert bulk_loaded.insert([2.0, 2.0], [3.0, 3.0]) == max_id + + +def test_bulk_load_numpy_4d_replaces_contents(): + tree = PyBBoxRTree(dims=4) + tree.insert([0.0] * 4, [1.0] * 4, data=99) + # Fortran order exercises the strided ndarray fast path. + mins = np.asfortranarray([[0.0] * 4, [5.0] * 4], dtype=np.float64) + maxs = np.asfortranarray([[2.0] * 4, [6.0] * 4], dtype=np.float64) + tree.bulk_load(mins, maxs, data=[20, 30]) + + assert len(tree) == 2 + assert tree.intersection([1.0] * 4, [1.0] * 4) == [20] + assert tree.intersection([5.5] * 4, [5.5] * 4) == [30] + assert tree.insert([10.0] * 4, [11.0] * 4) == 100 + + +def test_numpy_and_batched_intersection_results(): + tree = PyBBoxRTree(dims=2) + mins = np.array([[0.0, 0.0], [2.0, 2.0], [8.0, 8.0]], dtype=np.float64) + maxs = np.array([[4.0, 4.0], [6.0, 6.0], [9.0, 9.0]], dtype=np.float64) + strided_ids = np.array([10, -1, 20, -1, 30], dtype=np.int64)[::2] + tree.bulk_load(mins, maxs, data=strided_ids) + + query_mins = np.asfortranarray([[3.0, 3.0], [6.1, 6.1]], dtype=np.float64) + query_maxs = np.asfortranarray([[8.0, 8.0], [7.9, 7.9]], dtype=np.float64) + ids, offsets = tree.intersection_batch(query_mins, query_maxs) + assert ids.dtype == offsets.dtype == np.int64 + assert offsets.tolist() == [0, 3, 3] + assert sorted(ids[offsets[0] : offsets[1]].tolist()) == [10, 20, 30] + + empty_ids, empty_offsets = tree.intersection_batch( + np.empty((0, 2), dtype=np.float64), + np.empty((0, 2), dtype=np.float64), + ) + assert empty_ids.tolist() == [] + assert empty_offsets.tolist() == [0] + + +def test_numpy_inputs_reject_wrong_dtypes(): + tree = PyBBoxRTree(dims=2) + float32_corners = np.zeros((2, 2), dtype=np.float32) + float64_corners = np.zeros((2, 2), dtype=np.float64) + + with pytest.raises( + ValueError, + match=r"min_corners is a numpy array of dtype float32; expected float64", + ): + tree.bulk_load(float32_corners, float64_corners) + with pytest.raises( + ValueError, + match=r"data is a numpy array of dtype int32; expected int64", + ): + tree.bulk_load( + float64_corners, + float64_corners, + data=np.arange(2, dtype=np.int32), + ) + with pytest.raises( + ValueError, + match=r"min_corners is a numpy array of dtype float32; expected float64", + ): + tree.intersection_batch(float32_corners, float64_corners) + + +def test_remove_item_distinguishes_coincident_boxes(): + tree = PyBBoxRTree(dims=2) + tree.insert([0.0, 0.0], [1.0, 1.0], data=10) + tree.insert([0.0, 0.0], [1.0, 1.0], data=20) + + assert tree.remove_item([0.0, 0.0], [1.0, 1.0], 10) is True + assert tree.intersection([0.5, 0.5], [0.5, 0.5]) == [20] + assert tree.remove_item([0.0, 0.0], [1.0, 1.0], 10) is False + + +def test_empty_bulk_load_resets_contents(): + tree = PyBBoxRTree(dims=2) + tree.insert([0.0, 0.0], [1.0, 1.0]) + tree.bulk_load([], []) + assert len(tree) == 0 + assert tree.intersection([0.0, 0.0], [1.0, 1.0]) == [] + + +@pytest.mark.parametrize("dims", [1, 9]) +def test_invalid_tree_dimensions(dims): + with pytest.raises(ValueError, match="Dimensions must be between 2 and 8"): + PyBBoxRTree(dims=dims) + + +def test_dimension_row_and_id_mismatch_errors(): + tree = PyBBoxRTree(dims=2) + with pytest.raises(ValueError, match="Expected 2 dimensions, got 3"): + tree.insert([0.0, 0.0, 0.0], [1.0, 1.0]) + with pytest.raises(ValueError, match="same number of rows"): + tree.bulk_load([[0.0, 0.0]], []) + with pytest.raises(ValueError, match="Expected 1 ids.*got 2"): + tree.bulk_load([[0.0, 0.0]], [[1.0, 1.0]], data=[1, 2]) + with pytest.raises(ValueError, match="max_corners row 0 must have 2 dimensions"): + tree.bulk_load([[0.0, 0.0]], [[1.0, 1.0, 1.0]]) + with pytest.raises(ValueError, match="min_corners must have 2 columns, got 4"): + tree.bulk_load( + np.empty((0, 4), dtype=np.float64), + np.empty((0, 2), dtype=np.float64), + ) + with pytest.raises(ValueError, match="same number of rows"): + tree.intersection_batch( + np.empty((1, 2), dtype=np.float64), + np.empty((2, 2), dtype=np.float64), + ) diff --git a/python/tests/test_rtree.py b/python/tests/test_rtree.py index c370260..24d1258 100644 --- a/python/tests/test_rtree.py +++ b/python/tests/test_rtree.py @@ -46,6 +46,18 @@ def test_insert_returns_id(): assert tree.insert([3.0, 3.0]) == 101 +def test_ids_saturate_instead_of_wrapping(): + max_id = 2**63 - 1 + + inserted = PyRTree(dims=2) + assert inserted.insert([0.0, 0.0], data=max_id) == max_id + assert inserted.insert([1.0, 1.0]) == max_id + + bulk_loaded = PyRTree(dims=2) + bulk_loaded.bulk_load([[0.0, 0.0]], data=[max_id]) + assert bulk_loaded.insert([1.0, 1.0]) == max_id + + def test_repr_and_contains(): tree = PyRTree(dims=2) tree.insert([1.0, 2.0]) @@ -107,6 +119,15 @@ def test_bulk_load_numpy(): assert np.allclose(tree.nearest_neighbor([0.1, 0.1]), [0.0, 0.0]) +def test_bulk_load_numpy_rejects_wrong_dtype(): + tree = PyRTree(dims=2) + with pytest.raises( + ValueError, + match=r"points is a numpy array of dtype float32; expected float64", + ): + tree.bulk_load(np.zeros((2, 2), dtype=np.float32)) + + def test_bulk_load_with_ids(): tree = PyRTree(dims=2) tree.bulk_load([[0.0, 0.0], [5.0, 5.0]], data=[10, 20]) @@ -134,6 +155,21 @@ def test_locate_in_envelope(): assert len(found) == 2 +def test_locate_in_envelope_ids_includes_boundaries(): + tree = PyRTree(dims=2) + tree.bulk_load([[0.0, 0.0], [1.0, 1.0], [1.1, 0.5]], data=[10, 20, 30]) + assert sorted(tree.locate_in_envelope_ids([0.0, 0.0], [1.0, 1.0])) == [10, 20] + + +def test_remove_item_distinguishes_coincident_points(): + tree = PyRTree(dims=2) + tree.insert([1.0, 2.0], data=10) + tree.insert([1.0, 2.0], data=20) + assert tree.remove_item([1.0, 2.0], 10) is True + assert tree.locate_in_envelope_ids([1.0, 2.0], [1.0, 2.0]) == [20] + assert tree.remove_item([1.0, 2.0], 10) is False + + def test_remove(): tree = PyRTree(dims=2) tree.insert([1.0, 2.0]) diff --git a/src/lib.rs b/src/lib.rs index a845e21..f9adba5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,9 +1,14 @@ +use std::ops::ControlFlow; + use numpy::ndarray::{Array2, ArrayView2}; -use numpy::{IntoPyArray, PyArray2, PyReadonlyArray2}; +use numpy::{ + IntoPyArray, PyArray1, PyArray2, PyReadonlyArray1, PyReadonlyArray2, PyUntypedArray, + PyUntypedArrayMethods, +}; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::types::PyAny; -use rstar::primitives::GeomWithData; +use rstar::primitives::{GeomWithData, Rectangle}; use rstar::{RTree, AABB}; /// Minimum and maximum number of dimensions supported. rstar requires at @@ -14,9 +19,15 @@ const MAX_DIMS: usize = 8; /// A point with an associated integer id, as stored in the tree. type Item = GeomWithData<[f64; N], i64>; +/// An axis-aligned bounding box with an associated integer id. +type BBoxItem = GeomWithData, i64>; + /// Return type of [`PyRTree::query`]: `(distances, ids)` numpy arrays. type QueryResult<'py> = (Bound<'py, PyArray2>, Bound<'py, PyArray2>); +/// Compressed sparse row result of a batched bounding-box intersection. +type BBoxBatchResult<'py> = (Bound<'py, PyArray1>, Bound<'py, PyArray1>); + /// Convert a slice into a fixed-size point, validating its length. fn to_point(v: &[f64]) -> PyResult<[f64; N]> { <[f64; N]>::try_from(v) @@ -71,11 +82,25 @@ fn g_envelope( .collect()) } +fn g_envelope_ids( + t: &RTree>, + min: &[f64], + max: &[f64], +) -> PyResult> { + let envelope = AABB::from_corners(to_point::(min)?, to_point::(max)?); + Ok(t.locate_in_envelope(envelope).map(|g| g.data).collect()) +} + fn g_remove(t: &mut RTree>, p: &[f64]) -> PyResult { let q = to_point::(p)?; Ok(t.remove_at_point(q).is_some()) } +fn g_remove_item(t: &mut RTree>, p: &[f64], id: i64) -> PyResult { + let item = GeomWithData::new(to_point::(p)?, id); + Ok(t.remove(&item).is_some()) +} + fn g_contains(t: &RTree>, p: &[f64]) -> PyResult { let q = to_point::(p)?; Ok(t.locate_at_point(q).is_some()) @@ -142,6 +167,128 @@ fn g_query_radius( Ok(out) } +fn g_bbox_insert( + t: &mut RTree>, + min: &[f64], + max: &[f64], + id: i64, +) -> PyResult<()> { + let rectangle = Rectangle::from_corners(to_point::(min)?, to_point::(max)?); + t.insert(GeomWithData::new(rectangle, id)); + Ok(()) +} + +fn bbox_id(ids: Option<&[i64]>, index: usize) -> i64 { + ids.map_or(index as i64, |ids| ids[index]) +} + +fn g_bbox_bulk( + py: Python<'_>, + min_corners: &[Vec], + max_corners: &[Vec], + ids: Option<&[i64]>, +) -> PyResult>> { + let items = min_corners + .iter() + .zip(max_corners) + .enumerate() + .map(|(index, (min, max))| { + let rectangle = Rectangle::from_corners(to_point::(min)?, to_point::(max)?); + Ok(GeomWithData::new(rectangle, bbox_id(ids, index))) + }) + .collect::>>()?; + Ok(py.detach(move || RTree::bulk_load(items))) +} + +/// Fast NumPy bulk-load path. Rows are copied directly into fixed-size points, +/// avoiding the two heap allocations per box incurred by `Vec>`. +fn g_bbox_bulk_array( + py: Python<'_>, + min_corners: ArrayView2<'_, f64>, + max_corners: ArrayView2<'_, f64>, + ids: Option<&[i64]>, +) -> RTree> { + let items = if let (Some(mins), Some(maxs)) = (min_corners.as_slice(), max_corners.as_slice()) { + (0..min_corners.nrows()) + .map(|index| { + let row_start = index * N; + let min = &mins[row_start..row_start + N]; + let max = &maxs[row_start..row_start + N]; + GeomWithData::new( + Rectangle::from_corners( + std::array::from_fn(|axis| min[axis]), + std::array::from_fn(|axis| max[axis]), + ), + bbox_id(ids, index), + ) + }) + .collect() + } else { + (0..min_corners.nrows()) + .map(|index| { + let min = std::array::from_fn(|axis| min_corners[[index, axis]]); + let max = std::array::from_fn(|axis| max_corners[[index, axis]]); + GeomWithData::new(Rectangle::from_corners(min, max), bbox_id(ids, index)) + }) + .collect() + }; + py.detach(move || RTree::bulk_load(items)) +} + +fn g_bbox_intersection( + t: &RTree>, + min: &[f64], + max: &[f64], +) -> PyResult> { + let envelope = AABB::from_corners(to_point::(min)?, to_point::(max)?); + let mut ids = Vec::new(); + let _: ControlFlow<()> = t.locate_in_envelope_intersecting_int(envelope, |item| { + ids.push(item.data); + ControlFlow::Continue(()) + }); + Ok(ids) +} + +fn g_bbox_intersection_batch( + py: Python<'_>, + t: &RTree>, + min_corners: ArrayView2<'_, f64>, + max_corners: ArrayView2<'_, f64>, +) -> (Vec, Vec) { + let envelopes: Vec<_> = (0..min_corners.nrows()) + .map(|index| { + AABB::from_corners( + std::array::from_fn(|axis| min_corners[[index, axis]]), + std::array::from_fn(|axis| max_corners[[index, axis]]), + ) + }) + .collect(); + + py.detach(|| { + let mut ids = Vec::new(); + let mut offsets = Vec::with_capacity(envelopes.len() + 1); + offsets.push(0); + for envelope in envelopes { + let _: ControlFlow<()> = t.locate_in_envelope_intersecting_int(envelope, |item| { + ids.push(item.data); + ControlFlow::Continue(()) + }); + offsets.push(ids.len() as i64); + } + (ids, offsets) + }) +} + +fn g_bbox_remove_item( + t: &mut RTree>, + min: &[f64], + max: &[f64], + id: i64, +) -> PyResult { + let rectangle = Rectangle::from_corners(to_point::(min)?, to_point::(max)?); + Ok(t.remove(&GeomWithData::new(rectangle, id)).is_some()) +} + // --- The dimension-tagged tree storage ---------------------------------------- macro_rules! define_tree { @@ -199,6 +346,81 @@ macro_rules! dispatch { }; } +macro_rules! define_bbox_tree { + ($(($variant:ident, $n:literal)),+ $(,)?) => { + enum BBoxTree { $($variant(RTree>)),+ } + + impl BBoxTree { + fn empty(dims: usize) -> PyResult { + match dims { + $($n => Ok(BBoxTree::$variant(RTree::new())),)+ + _ => Err(PyValueError::new_err(format!( + "Dimensions must be between {} and {}, got {}", MIN_DIMS, MAX_DIMS, dims + ))), + } + } + + fn bulk( + py: Python<'_>, + dims: usize, + min_corners: &[Vec], + max_corners: &[Vec], + ids: Option<&[i64]>, + ) -> PyResult { + match dims { + $($n => Ok(BBoxTree::$variant(g_bbox_bulk::<$n>(py, min_corners, max_corners, ids)?)),)+ + _ => Err(PyValueError::new_err(format!( + "Dimensions must be between {} and {}, got {}", MIN_DIMS, MAX_DIMS, dims + ))), + } + } + + fn bulk_array( + py: Python<'_>, + dims: usize, + min_corners: ArrayView2<'_, f64>, + max_corners: ArrayView2<'_, f64>, + ids: Option<&[i64]>, + ) -> PyResult { + match dims { + $($n => Ok(BBoxTree::$variant(g_bbox_bulk_array::<$n>(py, min_corners, max_corners, ids))),)+ + _ => Err(PyValueError::new_err(format!( + "Dimensions must be between {} and {}, got {}", MIN_DIMS, MAX_DIMS, dims + ))), + } + } + + fn dims(&self) -> usize { + match self { $(BBoxTree::$variant(_) => $n),+ } + } + } + }; +} + +define_bbox_tree!( + (D2, 2), + (D3, 3), + (D4, 4), + (D5, 5), + (D6, 6), + (D7, 7), + (D8, 8), +); + +macro_rules! dispatch_bbox { + ($e:expr, $t:ident => $body:expr) => { + match $e { + BBoxTree::D2($t) => $body, + BBoxTree::D3($t) => $body, + BBoxTree::D4($t) => $body, + BBoxTree::D5($t) => $body, + BBoxTree::D6($t) => $body, + BBoxTree::D7($t) => $body, + BBoxTree::D8($t) => $body, + } + }; +} + /// An R*-tree spatial index over points of 2 to 8 dimensions. /// /// Each point carries an integer id (auto-assigned or supplied via ``data``). @@ -226,7 +448,7 @@ impl PyRTree { fn insert(&mut self, point: Vec, data: Option) -> PyResult { let id = data.unwrap_or(self.next_id); dispatch!(&mut self.tree, t => g_insert(t, &point, id)?); - self.next_id = self.next_id.max(id + 1); + self.next_id = self.next_id.max(id.saturating_add(1)); Ok(id) } @@ -256,7 +478,7 @@ impl PyRTree { }; let max_id = ids.iter().copied().max().unwrap_or(-1); self.tree = Tree::bulk(self.tree.dims(), &pts, &ids)?; - self.next_id = self.next_id.max(max_id + 1); + self.next_id = self.next_id.max(max_id.saturating_add(1)); Ok(()) } @@ -287,6 +509,15 @@ impl PyRTree { dispatch!(&self.tree, t => g_envelope(t, &min_corner, &max_corner)) } + /// Return the ids of all points inside the closed axis-aligned box. + fn locate_in_envelope_ids( + &self, + min_corner: Vec, + max_corner: Vec, + ) -> PyResult> { + dispatch!(&self.tree, t => g_envelope_ids(t, &min_corner, &max_corner)) + } + /// Vectorised k-NN query (scipy/sklearn style). /// /// ``points`` is an ``(M, dims)`` numpy ``float64`` array. Returns a tuple @@ -326,6 +557,11 @@ impl PyRTree { dispatch!(&mut self.tree, t => g_remove(t, &point)) } + /// Remove the point with exactly matching coordinates and id. + fn remove_item(&mut self, point: Vec, data: i64) -> PyResult { + dispatch!(&mut self.tree, t => g_remove_item(t, &point, data)) + } + /// Number of dimensions this tree indexes. #[getter] fn dims(&self) -> usize { @@ -350,6 +586,166 @@ impl PyRTree { } } +/// An R*-tree spatial index over axis-aligned bounding boxes in 2 to 8 dimensions. +/// +/// Each box carries an integer id (auto-assigned or supplied via ``data``). +/// Intersection queries return ids for every box whose closed bounds overlap or +/// touch the query bounds. 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. Callers must synchronize mutation of the same instance while a +/// batch is in flight; otherwise PyO3 may raise ``RuntimeError: Already borrowed``. +#[pyclass] +struct PyBBoxRTree { + tree: BBoxTree, + next_id: i64, +} + +#[pymethods] +impl PyBBoxRTree { + #[new] + fn new(dims: usize) -> PyResult { + Ok(PyBBoxRTree { + tree: BBoxTree::empty(dims)?, + next_id: 0, + }) + } + + /// Insert a bounding box, returning its id. + /// If ``data`` is omitted, an incrementing id is assigned automatically. + #[pyo3(signature = (min_corner, max_corner, data = None))] + fn insert( + &mut self, + min_corner: Vec, + max_corner: Vec, + data: Option, + ) -> PyResult { + let id = data.unwrap_or(self.next_id); + dispatch_bbox!(&mut self.tree, t => { + g_bbox_insert(t, &min_corner, &max_corner, id)? + }); + self.next_id = self.next_id.max(id.saturating_add(1)); + Ok(id) + } + + /// Build the tree from bounding boxes at once (replaces existing contents). + /// Corner batches may be lists of lists or 2-D numpy ``float64`` arrays. + #[pyo3(signature = (min_corners, max_corners, data = None))] + fn bulk_load( + &mut self, + py: Python<'_>, + min_corners: &Bound<'_, PyAny>, + max_corners: &Bound<'_, PyAny>, + data: Option<&Bound<'_, PyAny>>, + ) -> PyResult<()> { + let dims = self.tree.dims(); + + // Keep NumPy batches in ndarray views instead of allocating one Vec + // per row. Nested Python sequences retain the compatibility path. + if let (Ok(min_array), Ok(max_array)) = ( + min_corners.extract::>(), + max_corners.extract::>(), + ) { + let mins = min_array.as_array(); + let maxs = max_array.as_array(); + let num_boxes = validate_bbox_array_shapes(&mins, &maxs, dims)?; + let ids = extract_bbox_ids(data, num_boxes)?; + if num_boxes == 0 { + self.tree = BBoxTree::empty(dims)?; + return Ok(()); + } + + let max_id = max_bbox_id(ids.as_deref(), num_boxes); + self.tree = BBoxTree::bulk_array(py, dims, mins, maxs, ids.as_deref())?; + self.next_id = self.next_id.max(max_id.saturating_add(1)); + return Ok(()); + } + + let mins = extract_bbox_corners(min_corners, dims, "min_corners")?; + let maxs = extract_bbox_corners(max_corners, dims, "max_corners")?; + if mins.len() != maxs.len() { + return Err(PyValueError::new_err(format!( + "min_corners and max_corners must have the same number of rows, got {} and {}", + mins.len(), + maxs.len() + ))); + } + let ids = extract_bbox_ids(data, mins.len())?; + if mins.is_empty() { + self.tree = BBoxTree::empty(dims)?; + return Ok(()); + } + + let max_id = max_bbox_id(ids.as_deref(), mins.len()); + self.tree = BBoxTree::bulk(py, dims, &mins, &maxs, ids.as_deref())?; + self.next_id = self.next_id.max(max_id.saturating_add(1)); + Ok(()) + } + + /// Return ids for boxes whose closed bounds overlap or touch the query. + fn intersection(&self, min_corner: Vec, max_corner: Vec) -> PyResult> { + dispatch_bbox!(&self.tree, t => { + g_bbox_intersection(t, &min_corner, &max_corner) + }) + } + + /// Query many boxes at once, returning ids and CSR row offsets. + /// + /// Results for query row ``i`` are ``ids[offsets[i]:offsets[i + 1]]``. + fn intersection_batch<'py>( + &self, + py: Python<'py>, + min_corners: &Bound<'py, PyAny>, + max_corners: &Bound<'py, PyAny>, + ) -> PyResult> { + let min_array = extract_float_array2(min_corners, "min_corners")?; + let max_array = extract_float_array2(max_corners, "max_corners")?; + let mins = min_array.as_array(); + let maxs = max_array.as_array(); + validate_bbox_array_shapes(&mins, &maxs, self.tree.dims())?; + let (ids, offsets) = dispatch_bbox!(&self.tree, t => { + g_bbox_intersection_batch(py, t, mins, maxs) + }); + Ok((ids.into_pyarray(py), offsets.into_pyarray(py))) + } + + /// Remove the box with exactly matching normalized geometry and id. + fn remove_item( + &mut self, + min_corner: Vec, + max_corner: Vec, + data: i64, + ) -> PyResult { + dispatch_bbox!(&mut self.tree, t => { + g_bbox_remove_item(t, &min_corner, &max_corner, data) + }) + } + + /// Number of dimensions this tree indexes. + #[getter] + fn dims(&self) -> usize { + self.tree.dims() + } + + /// Number of bounding boxes in the tree. + fn size(&self) -> usize { + dispatch_bbox!(&self.tree, t => t.size()) + } + + fn __len__(&self) -> usize { + self.size() + } + + fn __repr__(&self) -> String { + format!( + "PyBBoxRTree(dims={}, size={})", + self.tree.dims(), + self.size() + ) + } +} + /// Accept either a list-of-lists or a 2-D numpy ``float64`` array. fn extract_points(obj: &Bound<'_, PyAny>) -> PyResult>> { if let Ok(arr) = obj.extract::>() { @@ -359,15 +755,144 @@ fn extract_points(obj: &Bound<'_, PyAny>) -> PyResult>> { .map(|row| row.to_vec()) .collect()) } else { + reject_wrong_dtype(obj, "points", "float64")?; obj.extract::>>().map_err(|_| { PyValueError::new_err("points must be a list of lists or a 2-D float64 numpy array") }) } } +/// NumPy arrays that fail a typed extraction would otherwise fall through to +/// the generic sequence path, silently making large inputs much slower. +fn reject_wrong_dtype(obj: &Bound<'_, PyAny>, name: &str, want: &str) -> PyResult<()> { + if let Ok(array) = obj.cast::() { + return Err(PyValueError::new_err(format!( + "{} is a numpy array of dtype {}; expected {}. Use .astype(np.{})", + name, + array.dtype(), + want, + want + ))); + } + Ok(()) +} + +fn extract_float_array2<'py>( + obj: &Bound<'py, PyAny>, + name: &str, +) -> PyResult> { + if let Ok(array) = obj.extract::>() { + Ok(array) + } else { + reject_wrong_dtype(obj, name, "float64")?; + Err(PyValueError::new_err(format!( + "{} must be a 2-D float64 numpy array", + name + ))) + } +} + +fn validate_bbox_array_shapes( + min_corners: &ArrayView2<'_, f64>, + max_corners: &ArrayView2<'_, f64>, + dims: usize, +) -> PyResult { + if min_corners.ncols() != dims { + return Err(PyValueError::new_err(format!( + "min_corners must have {} columns, got {}", + dims, + min_corners.ncols() + ))); + } + if max_corners.ncols() != dims { + return Err(PyValueError::new_err(format!( + "max_corners must have {} columns, got {}", + dims, + max_corners.ncols() + ))); + } + if min_corners.nrows() != max_corners.nrows() { + return Err(PyValueError::new_err(format!( + "min_corners and max_corners must have the same number of rows, got {} and {}", + min_corners.nrows(), + max_corners.nrows() + ))); + } + Ok(min_corners.nrows()) +} + +fn extract_bbox_ids( + data: Option<&Bound<'_, PyAny>>, + num_boxes: usize, +) -> PyResult>> { + let Some(data) = data else { + return Ok(None); + }; + let ids = if let Ok(array) = data.extract::>() { + array.as_array().iter().copied().collect() + } else { + reject_wrong_dtype(data, "data", "int64")?; + data.extract::>().map_err(|_| { + PyValueError::new_err("data must be an integer sequence or a 1-D int64 numpy array") + })? + }; + if ids.len() != num_boxes { + return Err(PyValueError::new_err(format!( + "Expected {} ids to match {} boxes, got {}", + num_boxes, + num_boxes, + ids.len() + ))); + } + Ok(Some(ids)) +} + +fn max_bbox_id(ids: Option<&[i64]>, num_boxes: usize) -> i64 { + ids.and_then(|ids| ids.iter().copied().max()) + .unwrap_or(num_boxes as i64 - 1) +} + +fn extract_bbox_corners( + obj: &Bound<'_, PyAny>, + dims: usize, + name: &str, +) -> PyResult>> { + if let Ok(arr) = obj.extract::>() { + let view = arr.as_array(); + if view.ncols() != dims { + return Err(PyValueError::new_err(format!( + "{} must have {} columns, got {}", + name, + dims, + view.ncols() + ))); + } + Ok(view.outer_iter().map(|row| row.to_vec()).collect()) + } else { + reject_wrong_dtype(obj, name, "float64")?; + let rows = obj.extract::>>().map_err(|_| { + PyValueError::new_err(format!( + "{} must be a list of lists or a 2-D float64 numpy array", + name + )) + })?; + if let Some((index, row)) = rows.iter().enumerate().find(|(_, row)| row.len() != dims) { + return Err(PyValueError::new_err(format!( + "{} row {} must have {} dimensions, got {}", + name, + index, + dims, + row.len() + ))); + } + Ok(rows) + } +} + #[pymodule] fn rstar_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; + m.add_class::()?; m.add("__version__", env!("CARGO_PKG_VERSION"))?; Ok(()) }