Repository navigation
Add stored bounding-box R-tree support - #4
Conversation
Introduce PyBBoxRTree for indexing axis-aligned bounding boxes with inclusive intersection queries, bulk loading, and exact geometry-plus-ID removal. Extend PyRTree with ID-returning envelope queries and exact point removal so consumers can distinguish coincident objects.
kephale
left a comment
There was a problem hiding this comment.
Thanks for this — nice work. I checked it out and built it locally, and the core of it is exactly the shape I want: PyRTree's hot paths are untouched, so this is genuinely additive.
What I verified (release build, this branch vs. main):
-
cargo clippy --all-targets -- -D warningsclean,cargo fmt --checkclean, 37 tests pass. -
No point-tree regression. 200k×3D points, median of 7, two runs each:
bulk_load query(k=4) query_radius nearest_neighbor ×2000 locate_in_envelope main 0.049–0.050 0.044–0.045 0.015–0.016 0.0053 0.0002 this PR 0.050–0.052 0.046 0.016 0.0053–0.0054 0.0002 All within noise. Import time unchanged (~0.16 ms), and the wheel contents are clean —
python/benchmarks/correctly does not leak in. -
The batch claim holds: 200k boxes / 20k queries,
intersection_batchis 2.7× faster than the scalar loop. That earns its place.
Before merge I'd like a small set of changes. I prototyped all of them locally to confirm they compile and pass (+57 −46, and the API gets smaller), so none of this should require restructuring.
1. Drop intersection_numpy
This is the main one. I benchmarked it across result sizes (500k boxes, 3D):
few hits hits= 4 list= 0.001ms numpy= 0.001ms batch(1row)= 0.002ms
many hits hits= 1775 list= 0.024ms numpy= 0.013ms batch(1row)= 0.014ms
all hits hits= 500000 list= 22.082ms numpy= 10.951ms batch(1row)= 10.151ms
It is 2× faster than intersection on large results — but intersection_batch with a single row matches or beats it at every size. So it's fully dominated: intersection for the scalar case, intersection_batch for the dense case, and the middle method buys nothing. Cutting it removes a public method, a stub, a README block, a CHANGELOG line, and a benchmark variant, at zero perf cost. Given three public spellings of "find overlapping boxes" is a lot of surface for one concept, I'd rather ship two.
2. Version/CHANGELOG mismatch will produce empty release notes
Cargo.toml/pyproject.toml move to 0.2.0, but the entries stay under ## [Unreleased]. release.yml:213 awk-extracts the ## [0.2.0] section, finds nothing, and falls back to "See CHANGELOG.md for details." Just rename the section to ## [0.2.0] - <date> and leave an empty [Unreleased] above it.
While there: the two ### Changed bullets describe optimizations to code introduced in this same PR, so there's no user-visible change — fold them into ### Added.
3. Wrong dtype should raise, not silently take the slow path
bulk_load with a float32 array falls through the typed extraction into the Vec<Vec<f64>> sequence path. It's correct, but silently skips the fast path this PR exists to add — on exactly the large arrays it targets. And intersection_batch with float32 gives an unhelpful TypeError: argument 'min_corners': 'ndarray' object is not an instance of 'ndarray'.
One small helper called from the three fallback sites covers it:
/// Numpy arrays that fail a typed extraction would otherwise fall through to the
/// generic sequence path: correct, but silently ~an order of magnitude slower.
/// Reject them with an actionable message instead.
fn reject_wrong_dtype(obj: &Bound<'_, PyAny>, name: &str, want: &str) -> PyResult<()> {
if let Ok(array) = obj.cast::<PyUntypedArray>() {
return Err(PyValueError::new_err(format!(
"{} is a numpy array of dtype {}; expected {}. Use .astype(np.{})",
name, array.dtype(), want, want
)));
}
Ok(())
}(Note obj.cast, not downcast — the latter is deprecated in pyo3 0.28 and trips -D warnings.) Wire it into extract_points, extract_bbox_corners, and extract_bbox_ids just before each sequence fallback, and you get:
min_corners is a numpy array of dtype float32; expected float64. Use .astype(np.float64)
data is a numpy array of dtype int32; expected int64. Use .astype(np.int64)
Lists keep working unchanged. PyRTree.bulk_load's data stays unguarded since it's a plain Option<Vec<i64>> in the signature — not worth changing here.
4. next_id overflow wraps silently
insert(data=2**63-1) followed by insert() returns 0. Pre-existing in PyRTree, but now duplicated in PyBBoxRTree, so worth fixing in both: self.next_id.max(id.saturating_add(1)), four sites.
5. Two doc notes (no code)
Both of these are new behavior that a caller can't guess:
- Corners are silently normalized —
insert([5,5],[0,0])becomes a valid box, on both insert and query. - This is the first place the library drops the GIL. That's a real win for concurrent readers, but I confirmed that mutating from another thread during an in-flight
intersection_batchraisesRuntimeError: Already borrowed. It's safe (pyo3's borrow flag, not UB), just opaque — worth a sentence on the class docstring.
6. Small test gaps
bulk_load without data (auto-id assignment and the resulting next_id), and the new dtype rejection. Two short tests.
Not blocking, just noting
- The
.sogrows 1.64 MB → 2.46 MB (+50%) from seven more monomorphizations. Compile-time and disk only, no runtime effect — I'm fine paying it, but it's the real cost of the dimension-generic approach, and it'll roughly double again for a third geometry type. PyBBoxRTreeis write-mostly: no geometry read-back, noremovewithout an id, no__contains__, no nearest-neighbour. So callers must keep their own box store to callremove_item. Fine to defer, but it's an asymmetry withPyRTreeworth a follow-up issue.- Naming across the two classes is drifting — points use
locate_in_envelope/locate_in_envelope_ids/query/query_radius, boxes useintersection/intersection_batch. I don't want to churn published names, and "intersection" vs. "containment" is a genuine semantic difference, so I'm happy to leave it. Butquery_radiusstill returnslist[list[int]]— the exact Python-boxing cost the CSR output was added to avoid. Giving it the same CSR form later would be a nice follow-up. - Dropping rstar's
serdefeature is unrelated to the feature, but a good build-time win (kills theserde_deriveproc-macro). Only keep it if pickling is on the roadmap. - Could you paste the benchmark numbers into the PR body? The benchmark isn't run in CI, so the description is the only record.
|
Addressed the review in small commits:
I also updated the PR body with benchmark results. Validation: 42 Python tests, release clippy with warnings denied, fmt check, and |
rstar-python currently indexes only points, so consumers cannot query objects by overlapping spatial extents.
Adds
PyBBoxRTreewith optimized NumPy bulk loading, inclusive scalar intersections, CSR-style batched intersections, exact geometry-plus-ID removal, documentation, and type stubs. Also adds ID-returning point envelope queries and exact point removal, and bumps the package to 0.2.0.Release benchmark on 200k 3D boxes and 20k queries:
intersection_batchis about 2.7× faster than the scalar loop. In paired before/after wheels, the NumPy bulk-load path was about 41% faster and scalar intersections were 14–27% faster.Tests: 42 Python tests pass;
cargo fmt --check, clippy with warnings denied, andcargo test --all-featurespass.