Debian Codegraph @

rtree/index.py

raw symbols SCIP
1 from __future__ import annotations
2
3 import ctypes
4 import os
5 import os.path
6 import pickle
7 import pprint
8 import warnings
9 from collections.abc import Iterator, Sequence
10 from typing import Any, Literal, overload
11
12 from . import core
13 from .exceptions import RTreeError
14
15 RT_Memory = 0
16 RT_Disk = 1
17 RT_Custom = 2
18
19 RT_Linear = 0
20 RT_Quadratic = 1
21 RT_Star = 2
22
23 RT_RTree = 0
24 RT_MVRTree = 1
25 RT_TPRTree = 2
26
27 __c_api_version__ = core.rt.SIDX_Version()
28
29 major_version, minor_version, patch_version = (
30 int(t) for t in __c_api_version__.decode("utf-8").split(".")
31 )
32
33 if (major_version, minor_version, patch_version) < (1, 8, 5):
34 raise Exception("Rtree requires libspatialindex 1.8.5 or greater")
35
36 __all__ = ["Rtree", "Index", "Property"]
37
38
39 def _get_bounds(handle, bounds_fn, interleaved):
40 pp_mins = ctypes.pointer(ctypes.c_double())
41 pp_maxs = ctypes.pointer(ctypes.c_double())
42 dimension = ctypes.c_uint32(0)
43
44 bounds_fn(
45 handle, ctypes.byref(pp_mins), ctypes.byref(pp_maxs), ctypes.byref(dimension)
46 )
47 if dimension.value == 0:
48 return None
49
50 mins = ctypes.cast(pp_mins, ctypes.POINTER(ctypes.c_double * dimension.value))
51 maxs = ctypes.cast(pp_maxs, ctypes.POINTER(ctypes.c_double * dimension.value))
52
53 results = [mins.contents[i] for i in range(dimension.value)]
54 results += [maxs.contents[i] for i in range(dimension.value)]
55
56 p_mins = ctypes.cast(mins, ctypes.POINTER(ctypes.c_double))
57 p_maxs = ctypes.cast(maxs, ctypes.POINTER(ctypes.c_double))
58 core.rt.Index_Free(ctypes.cast(p_mins, ctypes.POINTER(ctypes.c_void_p)))
59 core.rt.Index_Free(ctypes.cast(p_maxs, ctypes.POINTER(ctypes.c_void_p)))
60 if interleaved: # they want bbox order.
61 return results
62 return Index.deinterleave(results)
63
64
65 def _get_data(handle):
66 length = ctypes.c_uint64(0)
67 d = ctypes.pointer(ctypes.c_uint8(0))
68 core.rt.IndexItem_GetData(handle, ctypes.byref(d), ctypes.byref(length))
69 c = ctypes.cast(d, ctypes.POINTER(ctypes.c_void_p))
70 if length.value == 0:
71 core.rt.Index_Free(c)
72 return None
73 s = ctypes.string_at(d, length.value)
74 core.rt.Index_Free(c)
75 return s
76
77
78 class Index:
79 """An R-Tree, MVR-Tree, or TPR-Tree indexing object"""
80
81 def __init__(self, *args: Any, **kwargs: Any) -> None:
82 """Creates a new index
83
84 :param filename:
85 The first argument in the constructor is assumed to be a filename
86 determining that a file-based storage for the index should be used.
87 If the first argument is not of type basestring, it is then assumed
88 to be an instance of ICustomStorage or derived class.
89 If the first argument is neither of type basestring nor an instance
90 of ICustomStorage, it is then assumed to be an input index item
91 stream.
92
93 :param stream:
94 If the first argument in the constructor is not of type basestring,
95 it is assumed to be an iterable stream of data that will raise a
96 StopIteration. It must be in the form defined by the
97 :attr:`interleaved` attribute of the index. The following example
98 would assume :attr:`interleaved` is False::
99
100 (id,
101 (minx, maxx, miny, maxy, minz, maxz, ..., ..., mink, maxk),
102 object)
103
104 The object can be None, but you must put a place holder of
105 ``None`` there.
106
107 For a TPR-Tree, this would be in the form::
108
109 (id,
110 ((minx, maxx, miny, maxy, ..., ..., mink, maxk),
111 (minvx, maxvx, minvy, maxvy, ..., ..., minvk, maxvk),
112 time),
113 object)
114
115 :param storage:
116 If the first argument in the constructor is an instance of
117 ICustomStorage then the given custom storage is used.
118
119 :param interleaved: True or False, defaults to True.
120 This parameter determines the coordinate order for all methods that
121 take in coordinates.
122
123 :param properties: An :class:`index.Property` object.
124 This object sets both the creation and instantiation properties
125 for the object and they are passed down into libspatialindex.
126 A few properties are curried from instantiation parameters
127 for you like ``pagesize`` and ``overwrite``
128 to ensure compatibility with previous versions of the library. All
129 other properties must be set on the object.
130
131 .. warning::
132 The coordinate ordering for all functions are sensitive the
133 index's :attr:`interleaved` data member. If :attr:`interleaved`
134 is False, the coordinates must be in the form
135 [xmin, xmax, ymin, ymax, ..., ..., kmin, kmax]. If
136 :attr:`interleaved` is True, the coordinates must be in the form
137 [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax]. This also applies
138 to velocities when using a TPR-Tree.
139
140 A basic example
141 ::
142
143 >>> from rtree import index
144 >>> p = index.Property()
145
146 >>> idx = index.Index(properties=p)
147 >>> idx # doctest: +NORMALIZE_WHITESPACE
148 rtree.index.Index(bounds=[1.7976931348623157e+308,
149 1.7976931348623157e+308,
150 -1.7976931348623157e+308,
151 -1.7976931348623157e+308],
152 size=0)
153
154 Insert an item into the index::
155
156 >>> idx.insert(4321,
157 ... (34.3776829412, 26.7375853734, 49.3776829412,
158 ... 41.7375853734),
159 ... obj=42)
160
161 Query::
162
163 >>> hits = idx.intersection((0, 0, 60, 60), objects=True)
164 >>> for i in hits:
165 ... if i.id == 4321:
166 ... i.object
167 ... i.bbox
168 ... # doctest: +ELLIPSIS
169 42
170 [34.37768294..., 26.73758537..., 49.37768294..., 41.73758537...]
171
172
173 Using custom serializers::
174
175 >>> class JSONIndex(index.Index):
176 ... def dumps(self, obj):
177 ... # This import is nested so that the doctest doesn't
178 ... # require simplejson.
179 ... import simplejson
180 ... return simplejson.dumps(obj).encode('ascii')
181 ...
182 ... def loads(self, string):
183 ... import simplejson
184 ... return simplejson.loads(string.decode('ascii'))
185
186 >>> stored_obj = {"nums": [23, 45], "letters": "abcd"}
187 >>> json_idx = JSONIndex()
188 >>> try:
189 ... json_idx.insert(1, (0, 1, 0, 1), stored_obj)
190 ... list(json_idx.nearest((0, 0), 1,
191 ... objects="raw")) == [stored_obj]
192 ... except ImportError:
193 ... True
194 True
195
196 """
197 self.properties = kwargs.get("properties", Property())
198
199 if self.properties.type == RT_TPRTree and not hasattr(
200 core.rt, "Index_InsertTPData"
201 ):
202 raise RuntimeError(
203 "TPR-Tree type not supported with version of libspatialindex"
204 )
205
206 # interleaved True gives 'bbox' order.
207 self.interleaved = bool(kwargs.get("interleaved", True))
208
209 stream = None
210 arrays = None
211 basename = None
212 storage = None
213 if args:
214 if isinstance(args[0], str) or isinstance(args[0], bytes):
215 # they sent in a filename
216 basename = args[0]
217 # they sent in a filename, stream or filename, buffers
218 if len(args) > 1:
219 if isinstance(args[1], tuple):
220 arrays = args[1]
221 else:
222 stream = args[1]
223 elif isinstance(args[0], ICustomStorage):
224 storage = args[0]
225 # they sent in a storage, stream
226 if len(args) > 1:
227 stream = args[1]
228 elif isinstance(args[0], tuple):
229 arrays = args[0]
230 else:
231 stream = args[0]
232
233 if basename:
234 self.properties.storage = RT_Disk
235 self.properties.filename = basename
236
237 # check we can read the file
238 f = str(basename) + "." + self.properties.idx_extension
239 p = os.path.abspath(f)
240
241 # assume if the file exists, we're not going to overwrite it
242 # unless the user explicitly set the property to do so
243 if os.path.exists(p):
244 self.properties.overwrite = bool(kwargs.get("overwrite", False))
245
246 # assume we're fetching the first index_id. If the user
247 # set it, we'll fetch that one.
248 if not self.properties.overwrite:
249 try:
250 self.properties.index_id
251 except RTreeError:
252 self.properties.index_id = 1
253
254 d = os.path.dirname(p)
255 if not os.access(d, os.W_OK):
256 message = f"Unable to open file '{f}' for index storage"
257 raise OSError(message)
258 elif storage:
259 self.properties.storage = RT_Custom
260 if storage.hasData:
261 self.properties.overwrite = bool(kwargs.get("overwrite", False))
262 if not self.properties.overwrite:
263 try:
264 self.properties.index_id
265 except RTreeError:
266 self.properties.index_id = 1
267 else:
268 storage.clear()
269 self.customstorage = storage
270 storage.registerCallbacks(self.properties)
271 else:
272 self.properties.storage = RT_Memory
273
274 ps = kwargs.get("pagesize", None)
275 if ps:
276 self.properties.pagesize = int(ps)
277
278 if stream and self.properties.type == RT_RTree:
279 self._exception = None
280 self.handle = self._create_idx_from_stream(stream)
281 if self._exception:
282 raise self._exception
283 elif arrays and self.properties.type == RT_RTree:
284 self._exception = None
285
286 try:
287 self.handle = self._create_idx_from_array(*arrays)
288 except NameError:
289 raise NotImplementedError(
290 "libspatialindex >= 2.1 needed for bulk insert"
291 )
292
293 if self._exception:
294 raise self._exception
295 else:
296 self.handle = IndexHandle(self.properties.handle)
297 if stream: # Bulk insert not supported, so add one by one
298 for item in stream:
299 self.insert(*item)
300 elif arrays:
301 raise NotImplementedError("Bulk insert only supported for RTrees")
302
303 def get_size(self) -> int:
304 warnings.warn(
305 "index.get_size() is deprecated, use len(index) instead", DeprecationWarning
306 )
307 return len(self)
308
309 def __len__(self) -> int:
310 """The number of entries in the index.
311
312 :return: number of entries
313 """
314 try:
315 return self.count(self.bounds)
316 except RTreeError:
317 return 0
318
319 def __repr__(self) -> str:
320 return f"rtree.index.Index(bounds={self.bounds}, size={len(self)})"
321
322 def __getstate__(self) -> dict[str, Any]:
323 state = self.__dict__.copy()
324 del state["handle"]
325 return state
326
327 def __setstate__(self, state: dict[str, Any]) -> None:
328 self.__dict__.update(state)
329 self.handle = IndexHandle(self.properties.handle)
330
331 def dumps(self, obj: object) -> bytes:
332 return pickle.dumps(obj)
333
334 def loads(self, string: bytes) -> object:
335 return pickle.loads(string)
336
337 def close(self) -> None:
338 """Force a flush of the index to storage. Renders index
339 inaccessible."""
340 if self.handle:
341 self.handle.destroy()
342 self.handle = None
343 else:
344 raise OSError("Unclosable index")
345
346 def flush(self) -> None:
347 """Force a flush of the index to storage."""
348 if self.handle:
349 self.handle.flush()
350
351 def get_coordinate_pointers(
352 self, coordinates: Sequence[float]
353 ) -> tuple[float, float]:
354 dimension = self.properties.dimension
355 coordinates = list(coordinates)
356
357 arr = ctypes.c_double * dimension
358 mins = arr()
359
360 # Point
361 if len(coordinates) == dimension:
362 mins[:] = coordinates
363 maxs = mins
364 # Bounding box
365 else:
366 maxs = arr()
367
368 # Interleaved box
369 if self.interleaved:
370 p = coordinates[:dimension]
371 q = coordinates[dimension:]
372 # Non-interleaved box
373 else:
374 p = coordinates[::2]
375 q = coordinates[1::2]
376
377 mins[:] = p
378 maxs[:] = q
379
380 if not p <= q:
381 raise RTreeError(
382 "Coordinates must not have minimums more than maximums"
383 )
384
385 return mins, maxs
386
387 @staticmethod
388 def _get_time_doubles(times):
389 if times[0] > times[1]:
390 raise RTreeError("Start time must be less than end time")
391 t_start = ctypes.c_double(times[0])
392 t_end = ctypes.c_double(times[1])
393 return t_start, t_end
394
395 def _serialize(self, obj):
396 serialized = self.dumps(obj)
397 size = len(serialized)
398
399 d = ctypes.create_string_buffer(serialized)
400 # d.value = serialized
401 p = ctypes.pointer(d)
402
403 # return serialized to keep it alive for the pointer.
404 return size, ctypes.cast(p, ctypes.POINTER(ctypes.c_uint8)), serialized
405
406 def set_result_limit(self, value):
407 return core.rt.Index_SetResultSetOffset(self.handle, value)
408
409 def get_result_limit(self):
410 return core.rt.Index_GetResultSetOffset(self.handle)
411
412 result_limit = property(get_result_limit, set_result_limit)
413
414 def set_result_offset(self, value):
415 return core.rt.Index_SetResultSetLimit(self.handle, value)
416
417 def get_result_offset(self):
418 return core.rt.Index_GetResultSetLimit(self.handle)
419
420 result_offset = property(get_result_offset, set_result_offset)
421
422 def insert(self, id: int, coordinates: Any, obj: object = None) -> None:
423 """Inserts an item into the index with the given coordinates.
424
425 :param id: A long integer that is the identifier for this index entry. IDs
426 need not be unique to be inserted into the index, and it is up
427 to the user to ensure they are unique if this is a requirement.
428
429 :param coordinates: This may be an object that satisfies the numpy array
430 protocol, providing the index's dimension * 2 coordinate
431 pairs representing the `mink` and `maxk` coordinates in
432 each dimension defining the bounds of the query window.
433 For a TPR-Tree, this must be a 3-element sequence including
434 not only the positional coordinate pairs but also the
435 velocity pairs `minvk` and `maxvk` and a time value as a float.
436
437 :param obj: a pickleable object. If not None, this object will be
438 stored in the index with the :attr:`id`.
439
440 The following example inserts an entry into the index with id `4321`,
441 and the object it stores with that id is the number `42`. The
442 coordinate ordering in this instance is the default (interleaved=True)
443 ordering::
444
445 >>> from rtree import index
446 >>> idx = index.Index()
447 >>> idx.insert(4321,
448 ... (34.3776829412, 26.7375853734, 49.3776829412,
449 ... 41.7375853734),
450 ... obj=42)
451
452 This example is inserting the same object for a TPR-Tree, additionally
453 including a set of velocities at time `3`::
454
455 >>> p = index.Property(type=index.RT_TPRTree) # doctest: +SKIP
456 >>> idx = index.Index(properties=p) # doctest: +SKIP
457 >>> idx.insert(4321,
458 ... ((34.3776829412, 26.7375853734, 49.3776829412,
459 ... 41.7375853734),
460 ... (0.5, 2, 1.5, 2.5),
461 ... 3.0),
462 ... obj=42) # doctest: +SKIP
463
464 """
465 if self.properties.type == RT_TPRTree:
466 # https://github.com/python/mypy/issues/6799
467 return self._insertTP(id, *coordinates, obj=obj) # type: ignore[misc]
468
469 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
470 data = ctypes.c_ubyte(0)
471 size = 0
472 pyserialized = None
473 if obj is not None:
474 size, data, pyserialized = self._serialize(obj)
475 core.rt.Index_InsertData(
476 self.handle, id, p_mins, p_maxs, self.properties.dimension, data, size
477 )
478
479 add = insert
480
481 def _insertTP(
482 self,
483 id: int,
484 coordinates: Sequence[float],
485 velocities: Sequence[float],
486 time: float,
487 obj: object = None,
488 ) -> None:
489 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
490 pv_mins, pv_maxs = self.get_coordinate_pointers(velocities)
491 # End time isn't used
492 t_start, t_end = self._get_time_doubles((time, time + 1))
493 data = ctypes.c_ubyte(0)
494 size = 0
495 if obj is not None:
496 size, data, _ = self._serialize(obj)
497 core.rt.Index_InsertTPData(
498 self.handle,
499 id,
500 p_mins,
501 p_maxs,
502 pv_mins,
503 pv_maxs,
504 t_start,
505 t_end,
506 self.properties.dimension,
507 data,
508 size,
509 )
510
511 def count(self, coordinates: Any) -> int:
512 """Return number of objects that intersect the given coordinates.
513
514 :param coordinates: This may be an object that satisfies the numpy array
515 protocol, providing the index's dimension * 2 coordinate
516 pairs representing the `mink` and `maxk` coordinates in
517 each dimension defining the bounds of the query window.
518 For a TPR-Tree, this must be a 3-element sequence including
519 not only the positional coordinate pairs but also the
520 velocity pairs `minvk` and `maxvk` and a time pair for the
521 time range as a float.
522
523 The following example queries the index for any objects any objects
524 that were stored in the index intersect the bounds given in the
525 coordinates::
526
527 >>> from rtree import index
528 >>> idx = index.Index()
529 >>> idx.insert(4321,
530 ... (34.3776829412, 26.7375853734, 49.3776829412,
531 ... 41.7375853734),
532 ... obj=42)
533
534 >>> print(idx.count((0, 0, 60, 60)))
535 1
536
537 This example is similar for a TPR-Tree::
538
539 >>> p = index.Property(type=index.RT_TPRTree) # doctest: +SKIP
540 >>> idx = index.Index(properties=p) # doctest: +SKIP
541 >>> idx.insert(4321,
542 ... ((34.3776829412, 26.7375853734, 49.3776829412,
543 ... 41.7375853734),
544 ... (0.5, 2, 1.5, 2.5),
545 ... 3.0),
546 ... obj=42) # doctest: +SKIP
547
548 >>> print(idx.count(((0, 0, 60, 60), (0, 0, 0, 0), (3, 5))))
549 ... # doctest: +SKIP
550 1
551
552 """
553 if self.properties.type == RT_TPRTree:
554 return self._countTP(*coordinates)
555 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
556
557 p_num_results = ctypes.c_uint64(0)
558
559 core.rt.Index_Intersects_count(
560 self.handle,
561 p_mins,
562 p_maxs,
563 self.properties.dimension,
564 ctypes.byref(p_num_results),
565 )
566
567 return p_num_results.value
568
569 def _countTP(
570 self, coordinates: Sequence[float], velocities: Sequence[float], times: float
571 ) -> int:
572 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
573 pv_mins, pv_maxs = self.get_coordinate_pointers(velocities)
574 t_start, t_end = self._get_time_doubles(times)
575
576 p_num_results = ctypes.c_uint64(0)
577
578 core.rt.Index_TPIntersects_count(
579 self.handle,
580 p_mins,
581 p_maxs,
582 pv_mins,
583 pv_maxs,
584 t_start,
585 t_end,
586 self.properties.dimension,
587 ctypes.byref(p_num_results),
588 )
589
590 return p_num_results.value
591
592 @overload
593 def contains(self, coordinates: Any, objects: Literal[True]) -> Iterator[Item]: ...
594
595 @overload
596 def contains(
597 self, coordinates: Any, objects: Literal[False] = False
598 ) -> Iterator[int] | None: ...
599
600 @overload
601 def contains(
602 self, coordinates: Any, objects: Literal["raw"]
603 ) -> Iterator[object]: ...
604
605 def contains(
606 self, coordinates: Any, objects: bool | Literal["raw"] = False
607 ) -> Iterator[Item | int | object] | None:
608 """Return ids or objects in the index that contains within the given
609 coordinates.
610
611 :param coordinates: This may be an object that satisfies the numpy array
612 protocol, providing the index's dimension * 2 coordinate
613 pairs representing the `mink` and `maxk` coordinates in
614 each dimension defining the bounds of the query window.
615
616 :param objects: If True, the intersection method will return index objects that
617 were pickled when they were stored with each index entry, as well
618 as the id and bounds of the index entries. If 'raw', the objects
619 will be returned without the :class:`rtree.index.Item` wrapper.
620
621 The following example queries the index for any objects any objects
622 that were stored in the index intersect the bounds given in the
623 coordinates::
624
625 >>> from rtree import index
626 >>> idx = index.Index()
627 >>> idx.insert(4321,
628 ... (34.3776829412, 26.7375853734, 49.3776829412,
629 ... 41.7375853734),
630 ... obj=42)
631
632 >>> hits = list(idx.contains((0, 0, 60, 60), objects=True))
633 ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS +SKIP
634 >>> [(item.object, item.bbox) for item in hits if item.id == 4321]
635 ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS +SKIP
636 [(42, [34.37768294..., 26.73758537..., 49.37768294...,
637 41.73758537...])]
638
639 If the :class:`rtree.index.Item` wrapper is not used, it is faster to
640 request the 'raw' objects::
641
642 >>> list(idx.contains((0, 0, 60, 60), objects="raw"))
643 ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS +SKIP
644 [42]
645
646 """
647
648 if objects:
649 return self._contains_obj(coordinates, objects)
650
651 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
652
653 p_num_results = ctypes.c_uint64(0)
654
655 it = ctypes.pointer(ctypes.c_int64())
656
657 try:
658 core.rt.Index_Contains_id
659 except AttributeError:
660 return None
661
662 core.rt.Index_Contains_id(
663 self.handle,
664 p_mins,
665 p_maxs,
666 self.properties.dimension,
667 ctypes.byref(it),
668 ctypes.byref(p_num_results),
669 )
670 return self._get_ids(it, p_num_results.value)
671
672 def __and__(self, other: Index) -> Index:
673 """Take the intersection of two Index objects.
674
675 :param other: another index
676 :return: a new index
677 :raises AssertionError: if self and other have different interleave or dimension
678 """
679 assert self.interleaved == other.interleaved
680 assert self.properties.dimension == other.properties.dimension
681
682 i = 0
683 new_idx = Index(interleaved=self.interleaved, properties=self.properties)
684
685 # For each Item in self...
686 for item1 in self.intersection(self.bounds, objects=True):
687 if self.interleaved:
688 # For each Item in other that intersects...
689 for item2 in other.intersection(item1.bbox, objects=True):
690 # Compute the intersection bounding box
691 bbox = []
692 for j in range(len(item1.bbox)):
693 if j < len(item1.bbox) // 2:
694 bbox.append(max(item1.bbox[j], item2.bbox[j]))
695 else:
696 bbox.append(min(item1.bbox[j], item2.bbox[j]))
697
698 new_idx.insert(i, bbox, (item1.object, item2.object))
699 i += 1
700
701 else:
702 # For each Item in other that intersects...
703 for item2 in other.intersection(item1.bounds, objects=True):
704 # Compute the intersection bounding box
705 bounds = []
706 for j in range(len(item1.bounds)):
707 if j % 2 == 0:
708 bounds.append(max(item1.bounds[j], item2.bounds[j]))
709 else:
710 bounds.append(min(item1.bounds[j], item2.bounds[j]))
711
712 new_idx.insert(i, bounds, (item1.object, item2.object))
713 i += 1
714
715 return new_idx
716
717 def __or__(self, other: Index) -> Index:
718 """Take the union of two Index objects.
719
720 :param other: another index
721 :return: a new index
722 :raises AssertionError: if self and other have different interleave or dimension
723 """
724 assert self.interleaved == other.interleaved
725 assert self.properties.dimension == other.properties.dimension
726
727 new_idx = Index(interleaved=self.interleaved, properties=self.properties)
728
729 # For each index...
730 for old_idx in [self, other]:
731 # For each item...
732 for item in old_idx.intersection(old_idx.bounds, objects=True):
733 if self.interleaved:
734 new_idx.insert(item.id, item.bbox, item.object)
735 else:
736 new_idx.insert(item.id, item.bounds, item.object)
737
738 return new_idx
739
740 @overload
741 def intersection(
742 self, coordinates: Any, objects: Literal[True]
743 ) -> Iterator[Item]: ...
744
745 @overload
746 def intersection(
747 self, coordinates: Any, objects: Literal[False] = False
748 ) -> Iterator[int]: ...
749
750 @overload
751 def intersection(
752 self, coordinates: Any, objects: Literal["raw"]
753 ) -> Iterator[object]: ...
754
755 def intersection(
756 self, coordinates: Any, objects: bool | Literal["raw"] = False
757 ) -> Iterator[Item | int | object]:
758 """Return ids or objects in the index that intersect the given
759 coordinates.
760
761 :param coordinates: This may be an object that satisfies the numpy array
762 protocol, providing the index's dimension * 2 coordinate
763 pairs representing the `mink` and `maxk` coordinates in
764 each dimension defining the bounds of the query window.
765 For a TPR-Tree, this must be a 3-element sequence including
766 not only the positional coordinate pairs but also the
767 velocity pairs `minvk` and `maxvk` and a time pair for the
768 time range as a float.
769
770 :param objects: If True, the intersection method will return index objects that
771 were pickled when they were stored with each index entry, as well
772 as the id and bounds of the index entries. If 'raw', the objects
773 will be returned without the :class:`rtree.index.Item` wrapper.
774
775 The following example queries the index for any objects any objects
776 that were stored in the index intersect the bounds given in the
777 coordinates::
778
779 >>> from rtree import index
780 >>> idx = index.Index()
781 >>> idx.insert(4321,
782 ... (34.3776829412, 26.7375853734, 49.3776829412,
783 ... 41.7375853734),
784 ... obj=42)
785
786 >>> hits = list(idx.intersection((0, 0, 60, 60), objects=True))
787 >>> [(item.object, item.bbox) for item in hits if item.id == 4321]
788 ... # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
789 [(42, [34.37768294..., 26.73758537..., 49.37768294...,
790 41.73758537...])]
791
792 If the :class:`rtree.index.Item` wrapper is not used, it is faster to
793 request the 'raw' objects::
794
795 >>> list(idx.intersection((0, 0, 60, 60), objects="raw"))
796 [42]
797
798 Similar for the TPR-Tree::
799
800 >>> p = index.Property(type=index.RT_TPRTree) # doctest: +SKIP
801 >>> idx = index.Index(properties=p) # doctest: +SKIP
802 >>> idx.insert(4321,
803 ... ((34.3776829412, 26.7375853734, 49.3776829412,
804 ... 41.7375853734),
805 ... (0.5, 2, 1.5, 2.5),
806 ... 3.0),
807 ... obj=42) # doctest: +SKIP
808
809 >>> hits = list(idx.intersection(
810 ... ((0, 0, 60, 60), (0, 0, 0, 0), (3, 5)), objects=True))
811 ... # doctest: +SKIP
812 >>> [(item.object, item.bbox) for item in hits if item.id == 4321]
813 ... # doctest: +SKIP
814 [(42, [34.37768294..., 26.73758537..., 49.37768294...,
815 41.73758537...])]
816
817 """
818 if self.properties.type == RT_TPRTree:
819 # https://github.com/python/mypy/issues/6799
820 return self._intersectionTP( # type: ignore[misc]
821 *coordinates, objects=objects
822 )
823 if objects:
824 return self._intersection_obj(coordinates, objects)
825
826 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
827
828 p_num_results = ctypes.c_uint64(0)
829
830 it = ctypes.pointer(ctypes.c_int64())
831
832 core.rt.Index_Intersects_id(
833 self.handle,
834 p_mins,
835 p_maxs,
836 self.properties.dimension,
837 ctypes.byref(it),
838 ctypes.byref(p_num_results),
839 )
840 return self._get_ids(it, p_num_results.value)
841
842 def _intersectionTP(self, coordinates, velocities, times, objects=False):
843 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
844 pv_mins, pv_maxs = self.get_coordinate_pointers(velocities)
845 t_start, t_end = self._get_time_doubles(times)
846
847 p_num_results = ctypes.c_uint64(0)
848
849 if objects:
850 call = core.rt.Index_TPIntersects_obj
851 it = ctypes.pointer(ctypes.c_void_p())
852 else:
853 call = core.rt.Index_TPIntersects_id
854 it = ctypes.pointer(ctypes.c_int64())
855
856 call(
857 self.handle,
858 p_mins,
859 p_maxs,
860 pv_mins,
861 pv_maxs,
862 t_start,
863 t_end,
864 self.properties.dimension,
865 ctypes.byref(it),
866 ctypes.byref(p_num_results),
867 )
868
869 if objects:
870 return self._get_objects(it, p_num_results.value, objects)
871 else:
872 return self._get_ids(it, p_num_results.value)
873
874 def _intersection_obj(self, coordinates, objects):
875 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
876
877 p_num_results = ctypes.c_uint64(0)
878
879 it = ctypes.pointer(ctypes.c_void_p())
880
881 core.rt.Index_Intersects_obj(
882 self.handle,
883 p_mins,
884 p_maxs,
885 self.properties.dimension,
886 ctypes.byref(it),
887 ctypes.byref(p_num_results),
888 )
889 return self._get_objects(it, p_num_results.value, objects)
890
891 def _contains_obj(self, coordinates: Any, objects):
892 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
893
894 p_num_results = ctypes.c_uint64(0)
895
896 it = ctypes.pointer(ctypes.c_void_p())
897
898 try:
899 core.rt.Index_Contains_obj
900 except AttributeError:
901 return None
902
903 core.rt.Index_Contains_obj(
904 self.handle,
905 p_mins,
906 p_maxs,
907 self.properties.dimension,
908 ctypes.byref(it),
909 ctypes.byref(p_num_results),
910 )
911 return self._get_objects(it, p_num_results.value, objects)
912
913 def _get_objects(self, it, num_results, objects):
914 # take the pointer, yield the result objects and free
915 items = ctypes.cast(
916 it, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p * num_results))
917 )
918 its = ctypes.cast(items, ctypes.POINTER(ctypes.POINTER(ctypes.c_void_p)))
919
920 try:
921 if objects != "raw":
922 for i in range(num_results):
923 yield Item(self.loads, items[i])
924 else:
925 for i in range(num_results):
926 data = _get_data(items[i])
927 if data is None:
928 yield data
929 else:
930 yield self.loads(data)
931
932 finally:
933 core.rt.Index_DestroyObjResults(its, num_results)
934
935 def _get_ids(self, it, num_results):
936 # take the pointer, yield the results and free
937 items = ctypes.cast(it, ctypes.POINTER(ctypes.c_int64 * num_results))
938 its = ctypes.cast(items, ctypes.POINTER(ctypes.c_void_p))
939
940 try:
941 for i in range(num_results):
942 yield items.contents[i]
943
944 finally:
945 core.rt.Index_Free(its)
946
947 def _nearest_obj(self, coordinates, num_results, objects):
948 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
949
950 p_num_results = ctypes.pointer(ctypes.c_uint64(num_results))
951
952 it = ctypes.pointer(ctypes.c_void_p())
953
954 core.rt.Index_NearestNeighbors_obj(
955 self.handle,
956 p_mins,
957 p_maxs,
958 self.properties.dimension,
959 ctypes.byref(it),
960 p_num_results,
961 )
962
963 return self._get_objects(it, p_num_results.contents.value, objects)
964
965 @overload
966 def nearest(
967 self, coordinates: Any, num_results: int, objects: Literal[True]
968 ) -> Iterator[Item]: ...
969
970 @overload
971 def nearest(
972 self, coordinates: Any, num_results: int, objects: Literal[False] = False
973 ) -> Iterator[int]: ...
974
975 @overload
976 def nearest(
977 self, coordinates: Any, num_results: int, objects: Literal["raw"]
978 ) -> Iterator[object]: ...
979
980 def nearest(
981 self,
982 coordinates: Any,
983 num_results: int = 1,
984 objects: bool | Literal["raw"] = False,
985 ) -> Iterator[Item | int | object]:
986 """Returns the ``k``-nearest objects to the given coordinates.
987
988 :param coordinates: This may be an object that satisfies the numpy array
989 protocol, providing the index's dimension * 2 coordinate
990 pairs representing the `mink` and `maxk` coordinates in
991 each dimension defining the bounds of the query window.
992 For a TPR-Tree, this must be a 3-element sequence including
993 not only the positional coordinate pairs but also the
994 velocity pairs `minvk` and `maxvk` and a time pair for the
995 time range as a float.
996
997 :param num_results: The number of results to return nearest to the given
998 coordinates. If two index entries are equidistant, *both* are returned.
999 This property means that :attr:`num_results` may return more
1000 items than specified
1001
1002 :param objects: If True, the nearest method will return index objects that
1003 were pickled when they were stored with each index entry, as
1004 well as the id and bounds of the index entries.
1005 If 'raw', it will return the object as entered into the database
1006 without the :class:`rtree.index.Item` wrapper.
1007
1008 .. warning::
1009 This is currently not implemented for the TPR-Tree.
1010
1011 Example of finding the three items nearest to this one::
1012
1013 >>> from rtree import index
1014 >>> idx = index.Index()
1015 >>> idx.insert(4321, (34.37, 26.73, 49.37, 41.73), obj=42)
1016 >>> hits = idx.nearest((0, 0, 10, 10), 3, objects=True)
1017 """
1018 if self.properties.type == RT_TPRTree:
1019 # https://github.com/python/mypy/issues/6799
1020 return self._nearestTP(*coordinates, objects=objects) # type: ignore[misc]
1021
1022 if objects:
1023 return self._nearest_obj(coordinates, num_results, objects)
1024 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
1025
1026 # p_num_results is an input and output for C++ lib
1027 # as an input it says "get n closest neighbors"
1028 # but if multiple neighbors are at the same distance, both
1029 # will be returned
1030 # so the number of returned neighbors may be > p_num_results
1031 # thus p_num_results.contents.value gets set as an output by the
1032 # C++ lib to indicate the actual number of results for
1033 # _get_ids to use
1034 p_num_results = ctypes.pointer(ctypes.c_uint64(num_results))
1035
1036 it = ctypes.pointer(ctypes.c_int64())
1037
1038 core.rt.Index_NearestNeighbors_id(
1039 self.handle,
1040 p_mins,
1041 p_maxs,
1042 self.properties.dimension,
1043 ctypes.byref(it),
1044 p_num_results,
1045 )
1046
1047 return self._get_ids(it, p_num_results.contents.value)
1048
1049 def intersection_v(self, mins, maxs):
1050 """Bulk intersection query for obtaining the ids of entries
1051 which intersect with the provided bounding boxes. The return
1052 value is a tuple consisting of two 1D NumPy arrays: one of
1053 intersecting ids and another containing the counts for each
1054 bounding box.
1055
1056 :param mins: A NumPy array of shape `(n, d)` containing the
1057 minima to query.
1058
1059 :param maxs: A NumPy array of shape `(n, d)` containing the
1060 maxima to query.
1061 """
1062 import numpy as np
1063
1064 mins, maxs = self._prepare_v_arrays(mins, maxs)
1065
1066 # Extract counts
1067 n, d = mins.shape
1068
1069 # Compute strides
1070 d_i_stri = mins.strides[0] // mins.itemsize
1071 d_j_stri = mins.strides[1] // mins.itemsize
1072
1073 ids = np.empty(2 * n, dtype=np.int64)
1074 counts = np.empty(n, dtype=np.uint64)
1075 nr = ctypes.c_int64(0)
1076 offn, offi = 0, 0
1077
1078 while True:
1079 core.rt.Index_Intersects_id_v(
1080 self.handle,
1081 n - offn,
1082 d,
1083 len(ids) - offi,
1084 d_i_stri,
1085 d_j_stri,
1086 mins[offn:].ctypes.data,
1087 maxs[offn:].ctypes.data,
1088 ids[offi:].ctypes.data,
1089 counts[offn:].ctypes.data,
1090 ctypes.byref(nr),
1091 )
1092
1093 # If we got the expected nuber of results then return
1094 if nr.value == n - offn:
1095 return ids[: counts.sum()], counts
1096 # Otherwise, if our array is too small then resize
1097 else:
1098 offi += counts[offn : offn + nr.value].sum()
1099 offn += nr.value
1100
1101 ids.resize(2 * len(ids) + counts[offn], refcheck=False)
1102
1103 def nearest_v(
1104 self,
1105 mins,
1106 maxs,
1107 *,
1108 num_results=1,
1109 max_dists=None,
1110 strict=False,
1111 return_max_dists=False,
1112 ):
1113 """Bulk ``k``-nearest query for the given bounding boxes. The
1114 return value is a tuple consisting of, by default, two 1D NumPy
1115 arrays: one of intersecting ids and another containing the
1116 counts for each bounding box.
1117
1118 :param mins: A NumPy array of shape `(n, d)` containing the
1119 minima to query.
1120
1121 :param maxs: A NumPy array of shape `(n, d)` containing the
1122 maxima to query.
1123
1124 :param num_results: The maximum number of neighbors to return
1125 for each bounding box. If there are multiple equidistant
1126 furthest neighbors then, by default, they are *all*
1127 returned. Hence, the actual number of results can be
1128 greater than requested.
1129
1130 :param max_dists: Optional; a NumPy array of shape `(n,)`
1131 containing the maximum distance to consider for each
1132 bounding box.
1133
1134 :param strict: If True then each point will never return more
1135 than `num_results` even in cases of equidistant furthest
1136 neighbors.
1137
1138 :param return_max_dists: If True, the distance of the furthest
1139 neighbor for each bounding box will also be returned.
1140 """
1141 import numpy as np
1142
1143 mins, maxs = self._prepare_v_arrays(mins, maxs)
1144
1145 # Extract counts
1146 n, d = mins.shape
1147
1148 # Compute strides
1149 d_i_stri = mins.strides[0] // mins.itemsize
1150 d_j_stri = mins.strides[1] // mins.itemsize
1151
1152 ids = np.empty(n * num_results, dtype=np.int64)
1153 counts = np.empty(n, dtype=np.uint64)
1154 nr = ctypes.c_int64(0)
1155 offn, offi = 0, 0
1156
1157 if max_dists is not None:
1158 dists = np.ascontiguousarray(np.atleast_1d(max_dists), dtype=np.float64)
1159 if dists.ndim != 1:
1160 raise ValueError("max_dists must have 1 dimension")
1161 if len(dists) != n:
1162 raise ValueError(f"max_dists must have length {n}")
1163 elif return_max_dists:
1164 dists = np.zeros(n)
1165 else:
1166 dists = None
1167
1168 while True:
1169 core.rt.Index_NearestNeighbors_id_v(
1170 self.handle,
1171 num_results if not strict else -num_results,
1172 n - offn,
1173 d,
1174 len(ids) - offi,
1175 d_i_stri,
1176 d_j_stri,
1177 mins[offn:].ctypes.data,
1178 maxs[offn:].ctypes.data,
1179 ids[offi:].ctypes.data,
1180 counts[offn:].ctypes.data,
1181 dists[offn:].ctypes.data if dists is not None else None,
1182 ctypes.byref(nr),
1183 )
1184
1185 # If we got the expected number of results then return
1186 if nr.value == n - offn:
1187 if return_max_dists:
1188 return ids[: counts.sum()], counts, dists
1189 else:
1190 return ids[: counts.sum()], counts
1191 # Otherwise, if our array is too small then resize
1192 else:
1193 offi += counts[offn : offn + nr.value].sum()
1194 offn += nr.value
1195
1196 ids.resize(2 * len(ids) + counts[offn], refcheck=False)
1197
1198 def _prepare_v_arrays(self, mins, maxs):
1199 import numpy as np
1200
1201 # Ensure inputs are 2D float64 arrays
1202 if mins is maxs:
1203 mins = maxs = np.atleast_2d(mins).astype(np.float64)
1204 else:
1205 mins = np.atleast_2d(mins).astype(np.float64)
1206 maxs = np.atleast_2d(maxs).astype(np.float64)
1207
1208 if mins.ndim != 2 or maxs.ndim != 2:
1209 raise ValueError("mins/maxs must have 2 dimensions: (n, d)")
1210 if mins.shape != maxs.shape:
1211 raise ValueError("mins and maxs shapes not equal")
1212 if mins.strides != maxs.strides:
1213 raise ValueError("mins and maxs strides not equal")
1214
1215 # Handle invalid strides
1216 if any(s % mins.itemsize for s in mins.strides):
1217 if mins is maxs:
1218 mins = maxs = mins.copy()
1219 else:
1220 mins = mins.copy()
1221 maxs = maxs.copy()
1222
1223 return mins, maxs
1224
1225 def _nearestTP(self, coordinates, velocities, times, num_results=1, objects=False):
1226 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
1227 pv_mins, pv_maxs = self.get_coordinate_pointers(velocities)
1228 t_start, t_end = self._get_time_doubles(times)
1229
1230 p_num_results = ctypes.pointer(ctypes.c_uint64(num_results))
1231
1232 if objects:
1233 it = ctypes.pointer(ctypes.c_void_p())
1234 call = core.rt.Index_TPNearestNeighbors_obj
1235 else:
1236 it = ctypes.pointer(ctypes.c_int64())
1237 call = core.rt.Index_TPNearestNeighbors_id
1238
1239 call(
1240 self.handle,
1241 p_mins,
1242 p_maxs,
1243 pv_mins,
1244 pv_maxs,
1245 t_start,
1246 t_end,
1247 self.properties.dimension,
1248 ctypes.byref(it),
1249 p_num_results,
1250 )
1251
1252 if objects:
1253 return self._get_objects(it, p_num_results.contents.value, objects)
1254 else:
1255 return self._get_ids(it, p_num_results.contents.value)
1256
1257 def get_bounds(self, coordinate_interleaved=None):
1258 """Returns the bounds of the index
1259
1260 :param coordinate_interleaved: If True, the coordinates are turned
1261 in the form [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax],
1262 otherwise they are returned as
1263 [xmin, xmax, ymin, ymax, ..., ..., kmin, kmax]. If not specified,
1264 the :attr:`interleaved` member of the index is used, which
1265 defaults to True.
1266 """
1267 if coordinate_interleaved is None:
1268 coordinate_interleaved = self.interleaved
1269 return _get_bounds(self.handle, core.rt.Index_GetBounds, coordinate_interleaved)
1270
1271 bounds = property(get_bounds)
1272
1273 def delete(self, id: int, coordinates: Any) -> None:
1274 """Deletes an item from the index with the given ``'id'`` and
1275 coordinates given by the ``coordinates`` sequence. As the index can
1276 contain multiple items with the same ID and coordinates, deletion
1277 is not guaranteed to delete all items in the index with the given ID
1278 and coordinates.
1279
1280 :param id: A long integer ID for the entry, which need not be unique. The
1281 index can contain multiple entries with identical IDs and
1282 coordinates. Uniqueness of items should be enforced at the
1283 application level by the user.
1284
1285 :param coordinates: Dimension * 2 coordinate pairs, representing the min
1286 and max coordinates in each dimension of the item to be
1287 deleted from the index. Their ordering will depend on the
1288 index's :attr:`interleaved` data member.
1289 These are not the coordinates of a space containing the
1290 item, but those of the item itself. Together with the
1291 id parameter, they determine which item will be deleted.
1292 This may be an object that satisfies the numpy array protocol.
1293 For a TPR-Tree, this must be a 3-element sequence including
1294 not only the positional coordinate pairs but also the
1295 velocity pairs `minvk` and `maxvk` and a time pair for the
1296 original time the object was inserted and the current time
1297 as a float.
1298
1299 Example::
1300
1301 >>> from rtree import index
1302 >>> idx = index.Index()
1303 >>> idx.delete(4321,
1304 ... (34.3776829412, 26.7375853734, 49.3776829412,
1305 ... 41.7375853734))
1306
1307 For the TPR-Tree::
1308
1309 >>> p = index.Property(type=index.RT_TPRTree) # doctest: +SKIP
1310 >>> idx = index.Index(properties=p) # doctest: +SKIP
1311 >>> idx.delete(4321,
1312 ... ((34.3776829412, 26.7375853734, 49.3776829412,
1313 ... 41.7375853734),
1314 ... (0.5, 2, 1.5, 2.5),
1315 ... (3.0, 5.0))) # doctest: +SKIP
1316
1317 """
1318 if self.properties.type == RT_TPRTree:
1319 return self._deleteTP(id, *coordinates)
1320 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
1321 core.rt.Index_DeleteData(
1322 self.handle, id, p_mins, p_maxs, self.properties.dimension
1323 )
1324
1325 def _deleteTP(
1326 self,
1327 id: int,
1328 coordinates: Sequence[float],
1329 velocities: Sequence[float],
1330 times: float,
1331 ) -> None:
1332 p_mins, p_maxs = self.get_coordinate_pointers(coordinates)
1333 pv_mins, pv_maxs = self.get_coordinate_pointers(velocities)
1334 t_start, t_end = self._get_time_doubles(times)
1335 core.rt.Index_DeleteTPData(
1336 self.handle,
1337 id,
1338 p_mins,
1339 p_maxs,
1340 pv_mins,
1341 pv_maxs,
1342 t_start,
1343 t_end,
1344 self.properties.dimension,
1345 )
1346
1347 def valid(self) -> bool:
1348 return bool(core.rt.Index_IsValid(self.handle))
1349
1350 def clearBuffer(self):
1351 return core.rt.Index_ClearBuffer(self.handle)
1352
1353 @classmethod
1354 def deinterleave(self, interleaved: Sequence[object]) -> list[object]:
1355 """
1356 [xmin, ymin, xmax, ymax] => [xmin, xmax, ymin, ymax]
1357
1358 >>> Index.deinterleave([0, 10, 1, 11])
1359 [0, 1, 10, 11]
1360
1361 >>> Index.deinterleave([0, 1, 2, 10, 11, 12])
1362 [0, 10, 1, 11, 2, 12]
1363
1364 """
1365 assert len(interleaved) % 2 == 0, "must be a pairwise list"
1366 dimension = len(interleaved) // 2
1367 di = []
1368 for i in range(dimension):
1369 di.extend([interleaved[i], interleaved[i + dimension]])
1370 return di
1371
1372 @classmethod
1373 def interleave(self, deinterleaved: Sequence[float]) -> list[float]:
1374 """
1375 [xmin, xmax, ymin, ymax, zmin, zmax]
1376 => [xmin, ymin, zmin, xmax, ymax, zmax]
1377
1378 >>> Index.interleave([0, 1, 10, 11])
1379 [0, 10, 1, 11]
1380
1381 >>> Index.interleave([0, 10, 1, 11, 2, 12])
1382 [0, 1, 2, 10, 11, 12]
1383
1384 >>> Index.interleave((-1, 1, 58, 62, 22, 24))
1385 [-1, 58, 22, 1, 62, 24]
1386
1387 """
1388 assert len(deinterleaved) % 2 == 0, "must be a pairwise list"
1389 # dimension = len(deinterleaved) / 2
1390 interleaved = []
1391 for i in range(2):
1392 interleaved.extend(
1393 [deinterleaved[i + j] for j in range(0, len(deinterleaved), 2)]
1394 )
1395 return interleaved
1396
1397 def _create_idx_from_stream(self, stream):
1398 """This function is used to instantiate the index given an
1399 iterable stream of data."""
1400
1401 stream_iter = iter(stream)
1402 dimension = self.properties.dimension
1403 darray = ctypes.c_double * dimension
1404 mins = darray()
1405 maxs = darray()
1406 no_data = ctypes.cast(
1407 ctypes.pointer(ctypes.c_ubyte(0)), ctypes.POINTER(ctypes.c_ubyte)
1408 )
1409
1410 def py_next_item(p_id, p_mins, p_maxs, p_dimension, p_data, p_length):
1411 """This function must fill pointers to individual entries that will
1412 be added to the index. The C API will actually call this function
1413 to fill out the pointers. If this function returns anything other
1414 than 0, it is assumed that the stream of data is done."""
1415
1416 try:
1417 p_id[0], coordinates, obj = next(stream_iter)
1418 except StopIteration:
1419 # we're done
1420 return -1
1421 except Exception as exc:
1422 self._exception = exc
1423 return -1
1424
1425 if self.interleaved:
1426 mins[:] = coordinates[:dimension]
1427 maxs[:] = coordinates[dimension:]
1428 else:
1429 mins[:] = coordinates[::2]
1430 maxs[:] = coordinates[1::2]
1431
1432 p_mins[0] = mins
1433 p_maxs[0] = maxs
1434
1435 # set the dimension
1436 p_dimension[0] = dimension
1437 if obj is None:
1438 p_data[0] = no_data
1439 p_length[0] = 0
1440 else:
1441 p_length[0], data, _ = self._serialize(obj)
1442 p_data[0] = ctypes.cast(data, ctypes.POINTER(ctypes.c_ubyte))
1443
1444 return 0
1445
1446 stream = core.NEXTFUNC(py_next_item)
1447 return IndexStreamHandle(self.properties.handle, stream)
1448
1449 def _create_idx_from_array(self, ibuf, minbuf, maxbuf):
1450 import numpy as np
1451
1452 # Prepare the arrays
1453 ibuf = ibuf.astype(np.int64)
1454 minbuf, maxbuf = self._prepare_v_arrays(minbuf, maxbuf)
1455
1456 if len(ibuf) != len(minbuf):
1457 raise ValueError("index and point counts different")
1458
1459 # Handle misaligned data
1460 if ibuf.strides[0] % ibuf.itemsize:
1461 ibuf = ibuf.copy()
1462
1463 # Extract counts
1464 n, d = minbuf.shape
1465
1466 # Compute strides
1467 i_stri = ibuf.strides[0] // ibuf.itemsize
1468 d_i_stri = minbuf.strides[0] // minbuf.itemsize
1469 d_j_stri = minbuf.strides[1] // minbuf.itemsize
1470
1471 return IndexArrayHandle(
1472 self.properties.handle,
1473 n,
1474 d,
1475 i_stri,
1476 d_i_stri,
1477 d_j_stri,
1478 ibuf.ctypes.data,
1479 minbuf.ctypes.data,
1480 maxbuf.ctypes.data,
1481 )
1482
1483 def leaves(self):
1484 leaf_node_count = ctypes.c_uint32()
1485 p_leafsizes = ctypes.pointer(ctypes.c_uint32())
1486 p_leafids = ctypes.pointer(ctypes.c_int64())
1487 pp_childids = ctypes.pointer(ctypes.pointer(ctypes.c_int64()))
1488
1489 pp_mins = ctypes.pointer(ctypes.pointer(ctypes.c_double()))
1490 pp_maxs = ctypes.pointer(ctypes.pointer(ctypes.c_double()))
1491 dimension = ctypes.c_uint32(0)
1492
1493 core.rt.Index_GetLeaves(
1494 self.handle,
1495 ctypes.byref(leaf_node_count),
1496 ctypes.byref(p_leafsizes),
1497 ctypes.byref(p_leafids),
1498 ctypes.byref(pp_childids),
1499 ctypes.byref(pp_mins),
1500 ctypes.byref(pp_maxs),
1501 ctypes.byref(dimension),
1502 )
1503
1504 output = []
1505
1506 count = leaf_node_count.value
1507 sizes = ctypes.cast(p_leafsizes, ctypes.POINTER(ctypes.c_uint32 * count))
1508 ids = ctypes.cast(p_leafids, ctypes.POINTER(ctypes.c_int64 * count))
1509 child = ctypes.cast(
1510 pp_childids, ctypes.POINTER(ctypes.POINTER(ctypes.c_int64) * count)
1511 )
1512 mins = ctypes.cast(
1513 pp_mins, ctypes.POINTER(ctypes.POINTER(ctypes.c_double) * count)
1514 )
1515 maxs = ctypes.cast(
1516 pp_maxs, ctypes.POINTER(ctypes.POINTER(ctypes.c_double) * count)
1517 )
1518 for i in range(count):
1519 p_child_ids = child.contents[i]
1520
1521 id = ids.contents[i]
1522 size = sizes.contents[i]
1523 child_ids_array = ctypes.cast(
1524 p_child_ids, ctypes.POINTER(ctypes.c_int64 * size)
1525 )
1526
1527 child_ids = []
1528 for j in range(size):
1529 child_ids.append(child_ids_array.contents[j])
1530
1531 # free the child ids list
1532 core.rt.Index_Free(
1533 ctypes.cast(p_child_ids, ctypes.POINTER(ctypes.c_void_p))
1534 )
1535
1536 p_mins = mins.contents[i]
1537 p_maxs = maxs.contents[i]
1538
1539 p_mins = ctypes.cast(
1540 p_mins, ctypes.POINTER(ctypes.c_double * dimension.value)
1541 )
1542 p_maxs = ctypes.cast(
1543 p_maxs, ctypes.POINTER(ctypes.c_double * dimension.value)
1544 )
1545
1546 bounds = []
1547 bounds = [p_mins.contents[i] for i in range(dimension.value)]
1548 bounds += [p_maxs.contents[i] for i in range(dimension.value)]
1549
1550 # free the bounds
1551 p_mins = ctypes.cast(p_mins, ctypes.POINTER(ctypes.c_double))
1552 p_maxs = ctypes.cast(p_maxs, ctypes.POINTER(ctypes.c_double))
1553 core.rt.Index_Free(ctypes.cast(p_mins, ctypes.POINTER(ctypes.c_void_p)))
1554 core.rt.Index_Free(ctypes.cast(p_maxs, ctypes.POINTER(ctypes.c_void_p)))
1555
1556 output.append((id, child_ids, bounds))
1557
1558 return output
1559
1560
1561 # An alias to preserve backward compatibility
1562 Rtree = Index
1563
1564
1565 class Item:
1566 """A container for index entries"""
1567
1568 __slots__ = ("handle", "owned", "id", "object", "bounds")
1569
1570 def __init__(self, loads, handle, owned=False) -> None:
1571 """There should be no reason to instantiate these yourself. Items are
1572 created automatically when you call
1573 :meth:`rtree.index.Index.intersection` (or other index querying
1574 methods) with objects=True given the parameters of the function."""
1575
1576 if handle:
1577 self.handle = handle
1578
1579 self.owned = owned
1580
1581 self.id = core.rt.IndexItem_GetID(self.handle)
1582
1583 self.object = None
1584 self.object = self.get_object(loads)
1585 self.bounds = _get_bounds(self.handle, core.rt.IndexItem_GetBounds, False)
1586
1587 def __lt__(self, other: Item) -> bool:
1588 return self.id < other.id
1589
1590 def __gt__(self, other: Item) -> bool:
1591 return self.id > other.id
1592
1593 @property
1594 def bbox(self) -> list[float]:
1595 """Returns the bounding box of the index entry"""
1596 return Index.interleave(self.bounds)
1597
1598 def get_object(self, loads):
1599 # short circuit this so we only do it at construction time
1600 if self.object is not None:
1601 return self.object
1602 data = _get_data(self.handle)
1603 if data is None:
1604 return None
1605 return loads(data)
1606
1607
1608 class InvalidHandleException(Exception):
1609 """Handle has been destroyed and can no longer be used"""
1610
1611
1612 class Handle:
1613 def __init__(self, *args: Any, **kwargs: Any) -> None:
1614 self._ptr = self._create(*args, **kwargs)
1615
1616 def _create(self, *args: Any, **kwargs: Any):
1617 raise NotImplementedError
1618
1619 def _destroy(self, ptr):
1620 raise NotImplementedError
1621
1622 def destroy(self) -> None:
1623 try:
1624 if self._ptr is not None:
1625 self._destroy(self._ptr)
1626 self._ptr = None
1627 except AttributeError:
1628 pass
1629
1630 @property
1631 def _as_parameter_(self):
1632 if self._ptr is None:
1633 raise InvalidHandleException
1634 return self._ptr
1635
1636 def __del__(self) -> None:
1637 try:
1638 self.destroy()
1639 except NameError:
1640 # The core.py model doesn't have
1641 # core.rt available anymore and it was tore
1642 # down. We don't want to try to do anything
1643 # in that instance
1644 return
1645
1646
1647 class IndexHandle(Handle):
1648 _create = core.rt.Index_Create
1649 _destroy = core.rt.Index_Destroy
1650
1651 def flush(self) -> None:
1652 try:
1653 core.rt.Index_Flush
1654 if self._ptr is not None:
1655 core.rt.Index_Flush(self._ptr)
1656 except AttributeError:
1657 pass
1658
1659
1660 class IndexStreamHandle(IndexHandle):
1661 _create = core.rt.Index_CreateWithStream
1662
1663
1664 try:
1665
1666 class IndexArrayHandle(IndexHandle):
1667 _create = core.rt.Index_CreateWithArray
1668 except AttributeError:
1669 pass
1670
1671
1672 class PropertyHandle(Handle):
1673 _create = core.rt.IndexProperty_Create
1674 _destroy = core.rt.IndexProperty_Destroy
1675
1676
1677 class Property:
1678 """An index property object is a container that contains a number of
1679 settable index properties. Many of these properties must be set at
1680 index creation times, while others can be used to adjust performance
1681 or behavior."""
1682
1683 pkeys = (
1684 "buffering_capacity",
1685 "custom_storage_callbacks",
1686 "custom_storage_callbacks_size",
1687 "dat_extension",
1688 "dimension",
1689 "filename",
1690 "fill_factor",
1691 "idx_extension",
1692 "index_capacity",
1693 "index_id",
1694 "leaf_capacity",
1695 "near_minimum_overlap_factor",
1696 "overwrite",
1697 "pagesize",
1698 "point_pool_capacity",
1699 "region_pool_capacity",
1700 "reinsert_factor",
1701 "split_distribution_factor",
1702 "storage",
1703 "tight_mbr",
1704 "tpr_horizon",
1705 "type",
1706 "variant",
1707 "writethrough",
1708 )
1709
1710 def __init__(self, handle=None, owned: bool = True, **kwargs: Any) -> None:
1711 if handle is None:
1712 handle = PropertyHandle()
1713 self.handle = handle
1714 self.initialize_from_dict(kwargs)
1715
1716 def initialize_from_dict(self, state: dict[str, Any]) -> None:
1717 for k, v in state.items():
1718 if v is not None:
1719 setattr(self, k, v)
1720
1721 # Consistency checks
1722 if "near_minimum_overlap_factor" not in state:
1723 nmof = self.near_minimum_overlap_factor
1724 ilc = min(self.index_capacity, self.leaf_capacity)
1725 if nmof >= ilc:
1726 self.near_minimum_overlap_factor = ilc // 3 + 1
1727
1728 def __getstate__(self) -> dict[Any, Any]:
1729 return self.as_dict()
1730
1731 def __setstate__(self, state):
1732 self.handle = PropertyHandle()
1733 self.initialize_from_dict(state)
1734
1735 def as_dict(self) -> dict[str, Any]:
1736 d = {}
1737 for k in self.pkeys:
1738 try:
1739 v = getattr(self, k)
1740 except RTreeError:
1741 v = None
1742 d[k] = v
1743 return d
1744
1745 def __repr__(self) -> str:
1746 return repr(self.as_dict())
1747
1748 def __str__(self) -> str:
1749 return pprint.pformat(self.as_dict())
1750
1751 def get_index_type(self) -> int:
1752 try:
1753 return self._type
1754 except AttributeError:
1755 type = core.rt.IndexProperty_GetIndexType(self.handle)
1756 self._type: int = type
1757 return type
1758
1759 def set_index_type(self, value: int) -> None:
1760 self._type = value
1761 return core.rt.IndexProperty_SetIndexType(self.handle, value)
1762
1763 type = property(get_index_type, set_index_type)
1764 """Index type. Valid index type values are
1765 :data:`RT_RTree`, :data:`RT_MVTree`, or :data:`RT_TPRTree`. Only
1766 RT_RTree (the default) is practically supported at this time."""
1767
1768 def get_variant(self) -> int:
1769 return core.rt.IndexProperty_GetIndexVariant(self.handle)
1770
1771 def set_variant(self, value: int) -> None:
1772 return core.rt.IndexProperty_SetIndexVariant(self.handle, value)
1773
1774 variant = property(get_variant, set_variant)
1775 """Index variant. Valid index variant values are
1776 :data:`RT_Linear`, :data:`RT_Quadratic`, and :data:`RT_Star`"""
1777
1778 def get_dimension(self) -> int:
1779 try:
1780 return self._dimension
1781 except AttributeError:
1782 dim = core.rt.IndexProperty_GetDimension(self.handle)
1783 self._dimension: int = dim
1784 return dim
1785
1786 def set_dimension(self, value: int) -> None:
1787 if value <= 0:
1788 raise RTreeError("Negative or 0 dimensional indexes are not allowed")
1789 self._dimension = value
1790 return core.rt.IndexProperty_SetDimension(self.handle, value)
1791
1792 dimension = property(get_dimension, set_dimension)
1793 """Index dimension. Must be greater than 0, though a dimension of 1 might
1794 have undefined behavior."""
1795
1796 def get_storage(self) -> int:
1797 return core.rt.IndexProperty_GetIndexStorage(self.handle)
1798
1799 def set_storage(self, value: int) -> None:
1800 return core.rt.IndexProperty_SetIndexStorage(self.handle, value)
1801
1802 storage = property(get_storage, set_storage)
1803 """Index storage.
1804
1805 One of :data:`RT_Disk`, :data:`RT_Memory` or :data:`RT_Custom`.
1806
1807 If a filename is passed as the first parameter to :class:index.Index,
1808 :data:`RT_Disk` is assumed. If a CustomStorage instance is passed,
1809 :data:`RT_Custom` is assumed. Otherwise, :data:`RT_Memory` is the default.
1810 """
1811
1812 def get_pagesize(self) -> int:
1813 return core.rt.IndexProperty_GetPagesize(self.handle)
1814
1815 def set_pagesize(self, value: int) -> None:
1816 if value <= 0:
1817 raise RTreeError("Pagesize must be > 0")
1818 return core.rt.IndexProperty_SetPagesize(self.handle, value)
1819
1820 pagesize = property(get_pagesize, set_pagesize)
1821 """The pagesize when disk storage is used. It is ideal to ensure that your
1822 index entries fit within a single page for best performance."""
1823
1824 def get_index_capacity(self) -> int:
1825 return core.rt.IndexProperty_GetIndexCapacity(self.handle)
1826
1827 def set_index_capacity(self, value: int) -> None:
1828 if value <= 0:
1829 raise RTreeError("index_capacity must be > 0")
1830 return core.rt.IndexProperty_SetIndexCapacity(self.handle, value)
1831
1832 index_capacity = property(get_index_capacity, set_index_capacity)
1833 """Index capacity"""
1834
1835 def get_leaf_capacity(self) -> int:
1836 return core.rt.IndexProperty_GetLeafCapacity(self.handle)
1837
1838 def set_leaf_capacity(self, value: int) -> None:
1839 if value <= 0:
1840 raise RTreeError("leaf_capacity must be > 0")
1841 return core.rt.IndexProperty_SetLeafCapacity(self.handle, value)
1842
1843 leaf_capacity = property(get_leaf_capacity, set_leaf_capacity)
1844 """Leaf capacity"""
1845
1846 def get_index_pool_capacity(self) -> int:
1847 return core.rt.IndexProperty_GetIndexPoolCapacity(self.handle)
1848
1849 def set_index_pool_capacity(self, value: int) -> None:
1850 if value <= 0:
1851 raise RTreeError("index_pool_capacity must be > 0")
1852 return core.rt.IndexProperty_SetIndexPoolCapacity(self.handle, value)
1853
1854 index_pool_capacity = property(get_index_pool_capacity, set_index_pool_capacity)
1855 """Index pool capacity"""
1856
1857 def get_point_pool_capacity(self) -> int:
1858 return core.rt.IndexProperty_GetPointPoolCapacity(self.handle)
1859
1860 def set_point_pool_capacity(self, value: int) -> None:
1861 if value <= 0:
1862 raise RTreeError("point_pool_capacity must be > 0")
1863 return core.rt.IndexProperty_SetPointPoolCapacity(self.handle, value)
1864
1865 point_pool_capacity = property(get_point_pool_capacity, set_point_pool_capacity)
1866 """Point pool capacity"""
1867
1868 def get_region_pool_capacity(self) -> int:
1869 return core.rt.IndexProperty_GetRegionPoolCapacity(self.handle)
1870
1871 def set_region_pool_capacity(self, value: int) -> None:
1872 if value <= 0:
1873 raise RTreeError("region_pool_capacity must be > 0")
1874 return core.rt.IndexProperty_SetRegionPoolCapacity(self.handle, value)
1875
1876 region_pool_capacity = property(get_region_pool_capacity, set_region_pool_capacity)
1877 """Region pool capacity"""
1878
1879 def get_buffering_capacity(self) -> int:
1880 return core.rt.IndexProperty_GetBufferingCapacity(self.handle)
1881
1882 def set_buffering_capacity(self, value: int) -> None:
1883 if value <= 0:
1884 raise RTreeError("buffering_capacity must be > 0")
1885 return core.rt.IndexProperty_SetBufferingCapacity(self.handle, value)
1886
1887 buffering_capacity = property(get_buffering_capacity, set_buffering_capacity)
1888 """Buffering capacity"""
1889
1890 def get_tight_mbr(self):
1891 return bool(core.rt.IndexProperty_GetEnsureTightMBRs(self.handle))
1892
1893 def set_tight_mbr(self, value):
1894 value = bool(value)
1895 return bool(core.rt.IndexProperty_SetEnsureTightMBRs(self.handle, value))
1896
1897 tight_mbr = property(get_tight_mbr, set_tight_mbr)
1898 """Uses tight bounding rectangles"""
1899
1900 def get_overwrite(self):
1901 return bool(core.rt.IndexProperty_GetOverwrite(self.handle))
1902
1903 def set_overwrite(self, value):
1904 value = bool(value)
1905 return bool(core.rt.IndexProperty_SetOverwrite(self.handle, value))
1906
1907 overwrite = property(get_overwrite, set_overwrite)
1908 """Overwrite existing index files"""
1909
1910 def get_near_minimum_overlap_factor(self) -> int:
1911 return core.rt.IndexProperty_GetNearMinimumOverlapFactor(self.handle)
1912
1913 def set_near_minimum_overlap_factor(self, value: int) -> None:
1914 if value <= 0:
1915 raise RTreeError("near_minimum_overlap_factor must be > 0")
1916 return core.rt.IndexProperty_SetNearMinimumOverlapFactor(self.handle, value)
1917
1918 near_minimum_overlap_factor = property(
1919 get_near_minimum_overlap_factor, set_near_minimum_overlap_factor
1920 )
1921 """Overlap factor for MVRTrees"""
1922
1923 def get_writethrough(self):
1924 return bool(core.rt.IndexProperty_GetWriteThrough(self.handle))
1925
1926 def set_writethrough(self, value):
1927 value = bool(value)
1928 return bool(core.rt.IndexProperty_SetWriteThrough(self.handle, value))
1929
1930 writethrough = property(get_writethrough, set_writethrough)
1931 """Write through caching"""
1932
1933 def get_fill_factor(self) -> int:
1934 return core.rt.IndexProperty_GetFillFactor(self.handle)
1935
1936 def set_fill_factor(self, value: int) -> None:
1937 return core.rt.IndexProperty_SetFillFactor(self.handle, value)
1938
1939 fill_factor = property(get_fill_factor, set_fill_factor)
1940 """Index node fill factor before branching"""
1941
1942 def get_split_distribution_factor(self) -> int:
1943 return core.rt.IndexProperty_GetSplitDistributionFactor(self.handle)
1944
1945 def set_split_distribution_factor(self, value: int) -> None:
1946 return core.rt.IndexProperty_SetSplitDistributionFactor(self.handle, value)
1947
1948 split_distribution_factor = property(
1949 get_split_distribution_factor, set_split_distribution_factor
1950 )
1951 """Split distribution factor"""
1952
1953 def get_tpr_horizon(self):
1954 return core.rt.IndexProperty_GetTPRHorizon(self.handle)
1955
1956 def set_tpr_horizon(self, value):
1957 return core.rt.IndexProperty_SetTPRHorizon(self.handle, value)
1958
1959 tpr_horizon = property(get_tpr_horizon, set_tpr_horizon)
1960 """TPR horizon"""
1961
1962 def get_reinsert_factor(self):
1963 return core.rt.IndexProperty_GetReinsertFactor(self.handle)
1964
1965 def set_reinsert_factor(self, value):
1966 return core.rt.IndexProperty_SetReinsertFactor(self.handle, value)
1967
1968 reinsert_factor = property(get_reinsert_factor, set_reinsert_factor)
1969 """Reinsert factor"""
1970
1971 def get_filename(self):
1972 return core.rt.IndexProperty_GetFileName(self.handle).decode()
1973
1974 def set_filename(self, value):
1975 if isinstance(value, str):
1976 value = value.encode("utf-8")
1977 return core.rt.IndexProperty_SetFileName(self.handle, value)
1978
1979 filename = property(get_filename, set_filename)
1980 """Index filename for disk storage"""
1981
1982 def get_dat_extension(self):
1983 ext = core.rt.IndexProperty_GetFileNameExtensionDat(self.handle)
1984 return ext.decode()
1985
1986 def set_dat_extension(self, value):
1987 if isinstance(value, str):
1988 value = value.encode("utf-8")
1989 return core.rt.IndexProperty_SetFileNameExtensionDat(self.handle, value)
1990
1991 dat_extension = property(get_dat_extension, set_dat_extension)
1992 """Extension for .dat file"""
1993
1994 def get_idx_extension(self):
1995 ext = core.rt.IndexProperty_GetFileNameExtensionIdx(self.handle)
1996 return ext.decode()
1997
1998 def set_idx_extension(self, value):
1999 if isinstance(value, str):
2000 value = value.encode("utf-8")
2001 return core.rt.IndexProperty_SetFileNameExtensionIdx(self.handle, value)
2002
2003 idx_extension = property(get_idx_extension, set_idx_extension)
2004 """Extension for .idx file"""
2005
2006 def get_custom_storage_callbacks_size(self) -> int:
2007 return core.rt.IndexProperty_GetCustomStorageCallbacksSize(self.handle)
2008
2009 def set_custom_storage_callbacks_size(self, value: int) -> None:
2010 return core.rt.IndexProperty_SetCustomStorageCallbacksSize(self.handle, value)
2011
2012 custom_storage_callbacks_size = property(
2013 get_custom_storage_callbacks_size, set_custom_storage_callbacks_size
2014 )
2015 """Size of callbacks for custom storage"""
2016
2017 def get_custom_storage_callbacks(self):
2018 return core.rt.IndexProperty_GetCustomStorageCallbacks(self.handle)
2019
2020 def set_custom_storage_callbacks(self, value):
2021 return core.rt.IndexProperty_SetCustomStorageCallbacks(self.handle, value)
2022
2023 custom_storage_callbacks = property(
2024 get_custom_storage_callbacks, set_custom_storage_callbacks
2025 )
2026 """Callbacks for custom storage"""
2027
2028 def get_index_id(self):
2029 return core.rt.IndexProperty_GetIndexID(self.handle)
2030
2031 def set_index_id(self, value):
2032 return core.rt.IndexProperty_SetIndexID(self.handle, value)
2033
2034 index_id = property(get_index_id, set_index_id)
2035 """First node index id"""
2036
2037
2038 # custom storage implementation
2039
2040 id_type = ctypes.c_int64
2041
2042
2043 class CustomStorageCallbacks(ctypes.Structure):
2044 # callback types
2045 createCallbackType = ctypes.CFUNCTYPE(
2046 None, ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)
2047 )
2048 destroyCallbackType = ctypes.CFUNCTYPE(
2049 None, ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)
2050 )
2051 flushCallbackType = ctypes.CFUNCTYPE(
2052 None, ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)
2053 )
2054
2055 loadCallbackType = ctypes.CFUNCTYPE(
2056 None,
2057 ctypes.c_void_p,
2058 id_type,
2059 ctypes.POINTER(ctypes.c_uint32),
2060 ctypes.POINTER(ctypes.POINTER(ctypes.c_uint8)),
2061 ctypes.POINTER(ctypes.c_int),
2062 )
2063 storeCallbackType = ctypes.CFUNCTYPE(
2064 None,
2065 ctypes.c_void_p,
2066 ctypes.POINTER(id_type),
2067 ctypes.c_uint32,
2068 ctypes.POINTER(ctypes.c_uint8),
2069 ctypes.POINTER(ctypes.c_int),
2070 )
2071 deleteCallbackType = ctypes.CFUNCTYPE(
2072 None, ctypes.c_void_p, id_type, ctypes.POINTER(ctypes.c_int)
2073 )
2074
2075 _fields_ = [
2076 ("context", ctypes.c_void_p),
2077 ("createCallback", createCallbackType),
2078 ("destroyCallback", destroyCallbackType),
2079 ("flushCallback", flushCallbackType),
2080 ("loadCallback", loadCallbackType),
2081 ("storeCallback", storeCallbackType),
2082 ("deleteCallback", deleteCallbackType),
2083 ]
2084
2085 def __init__(
2086 self,
2087 context,
2088 createCallback,
2089 destroyCallback,
2090 flushCallback,
2091 loadCallback,
2092 storeCallback,
2093 deleteCallback,
2094 ) -> None:
2095 ctypes.Structure.__init__(
2096 self,
2097 ctypes.c_void_p(context),
2098 self.createCallbackType(createCallback),
2099 self.destroyCallbackType(destroyCallback),
2100 self.flushCallbackType(flushCallback),
2101 self.loadCallbackType(loadCallback),
2102 self.storeCallbackType(storeCallback),
2103 self.deleteCallbackType(deleteCallback),
2104 )
2105
2106
2107 class ICustomStorage:
2108 # error codes
2109 NoError = 0
2110 InvalidPageError = 1
2111 IllegalStateError = 2
2112
2113 # special pages
2114 EmptyPage = -0x1
2115 NewPage = -0x1
2116
2117 def allocateBuffer(self, length):
2118 return core.rt.SIDX_NewBuffer(length)
2119
2120 def registerCallbacks(self, properties):
2121 raise NotImplementedError()
2122
2123 def clear(self):
2124 raise NotImplementedError()
2125
2126 hasData = property(lambda self: False)
2127 """Override this property to allow for reloadable storages"""
2128
2129
2130 class CustomStorageBase(ICustomStorage):
2131 """Derive from this class to create your own storage manager with access
2132 to the raw C buffers."""
2133
2134 def registerCallbacks(self, properties):
2135 callbacks = CustomStorageCallbacks(
2136 ctypes.c_void_p(),
2137 self.create,
2138 self.destroy,
2139 self.flush,
2140 self.loadByteArray,
2141 self.storeByteArray,
2142 self.deleteByteArray,
2143 )
2144 properties.custom_storage_callbacks_size = ctypes.sizeof(callbacks)
2145 self.callbacks = callbacks
2146 properties.custom_storage_callbacks = ctypes.cast(
2147 ctypes.pointer(callbacks), ctypes.c_void_p
2148 )
2149
2150 # the user must override these callback functions
2151 def create(self, context, returnError):
2152 returnError.contents.value = self.IllegalStateError
2153 raise NotImplementedError("You must override this method.")
2154
2155 def destroy(self, context, returnError):
2156 """please override"""
2157 returnError.contents.value = self.IllegalStateError
2158 raise NotImplementedError("You must override this method.")
2159
2160 def loadByteArray(self, context, page, resultLen, resultData, returnError):
2161 """please override"""
2162 returnError.contents.value = self.IllegalStateError
2163 raise NotImplementedError("You must override this method.")
2164
2165 def storeByteArray(self, context, page, len, data, returnError):
2166 """please override"""
2167 returnError.contents.value = self.IllegalStateError
2168 raise NotImplementedError("You must override this method.")
2169
2170 def deleteByteArray(self, context, page, returnError):
2171 """please override"""
2172 returnError.contents.value = self.IllegalStateError
2173 raise NotImplementedError("You must override this method.")
2174
2175 def flush(self, context, returnError):
2176 """please override"""
2177 returnError.contents.value = self.IllegalStateError
2178 raise NotImplementedError("You must override this method.")
2179
2180
2181 class CustomStorage(ICustomStorage):
2182 """Provides a useful default custom storage implementation which marshals
2183 the buffers on the C side from/to python strings.
2184 Derive from this class and override the necessary methods to provide
2185 your own custom storage manager."""
2186
2187 def registerCallbacks(self, properties):
2188 callbacks = CustomStorageCallbacks(
2189 0,
2190 self._create,
2191 self._destroy,
2192 self._flush,
2193 self._loadByteArray,
2194 self._storeByteArray,
2195 self._deleteByteArray,
2196 )
2197 properties.custom_storage_callbacks_size = ctypes.sizeof(callbacks)
2198 self.callbacks = callbacks
2199 properties.custom_storage_callbacks = ctypes.cast(
2200 ctypes.pointer(callbacks), ctypes.c_void_p
2201 )
2202
2203 # these functions handle the C callbacks and massage the data, then
2204 # delegate to the function without underscore below
2205 def _create(self, context, returnError):
2206 self.create(returnError)
2207
2208 def _destroy(self, context, returnError):
2209 self.destroy(returnError)
2210
2211 def _flush(self, context, returnError):
2212 self.flush(returnError)
2213
2214 def _loadByteArray(self, context, page, resultLen, resultData, returnError):
2215 resultString = self.loadByteArray(page, returnError)
2216 if returnError.contents.value != self.NoError:
2217 return
2218 # Copy python string over into a buffer allocated on the C side.
2219 # The buffer will later be freed by the C side. This prevents
2220 # possible heap corruption issues as buffers allocated by ctypes
2221 # and the c library might be allocated on different heaps.
2222 # Freeing a buffer allocated on another heap might make the application
2223 # crash.
2224 count = len(resultString)
2225 resultLen.contents.value = count
2226 buffer = self.allocateBuffer(count)
2227 ctypes.memmove(buffer, ctypes.c_char_p(resultString), count)
2228 resultData[0] = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_uint8))
2229
2230 def _storeByteArray(self, context, page, len, data, returnError):
2231 str = ctypes.string_at(data, len)
2232 newPageId = self.storeByteArray(page.contents.value, str, returnError)
2233 page.contents.value = newPageId
2234
2235 def _deleteByteArray(self, context, page, returnError):
2236 self.deleteByteArray(page, returnError)
2237
2238 # the user must override these callback functions
2239 def create(self, returnError):
2240 """Must be overridden. No return value."""
2241 returnError.contents.value = self.IllegalStateError
2242 raise NotImplementedError("You must override this method.")
2243
2244 def destroy(self, returnError):
2245 """Must be overridden. No return value."""
2246 returnError.contents.value = self.IllegalStateError
2247 raise NotImplementedError("You must override this method.")
2248
2249 def flush(self, returnError):
2250 """Must be overridden. No return value."""
2251 returnError.contents.value = self.IllegalStateError
2252 raise NotImplementedError("You must override this method.")
2253
2254 def loadByteArray(self, page, returnError):
2255 """Must be overridden. Must return a string with the loaded data."""
2256 returnError.contents.value = self.IllegalStateError
2257 raise NotImplementedError("You must override this method.")
2258 return ""
2259
2260 def storeByteArray(self, page, data, returnError):
2261 """Must be overridden. Must return the new 64-bit page ID of the stored
2262 data if a new page had to be created (i.e. page is not NewPage)."""
2263 returnError.contents.value = self.IllegalStateError
2264 raise NotImplementedError("You must override this method.")
2265 return 0
2266
2267 def deleteByteArray(self, page, returnError):
2268 """please override"""
2269 returnError.contents.value = self.IllegalStateError
2270 raise NotImplementedError("You must override this method.")
2271
2272
2273 class RtreeContainer(Rtree):
2274 """An R-Tree, MVR-Tree, or TPR-Tree indexed container for python objects"""
2275
2276 def __init__(self, *args: Any, **kwargs: Any) -> None:
2277 """Creates a new index
2278
2279 :param stream:
2280 If the first argument in the constructor is not of type basestring,
2281 it is assumed to be an iterable stream of data that will raise a
2282 StopIteration. It must be in the form defined by the
2283 :attr:`interleaved` attribute of the index. The following example
2284 would assume :attr:`interleaved` is False::
2285
2286 (obj,
2287 (minx, maxx, miny, maxy, minz, maxz, ..., ..., mink, maxk))
2288
2289 For a TPR-Tree, this would be in the form::
2290
2291 (id,
2292 ((minx, maxx, miny, maxy, ..., ..., mink, maxk),
2293 (minvx, maxvx, minvy, maxvy, ..., ..., minvk, maxvk),
2294 time),
2295 object)
2296
2297 :param interleaved: True or False, defaults to True.
2298 This parameter determines the coordinate order for all methods that
2299 take in coordinates.
2300
2301 :param properties: This object sets both the creation and instantiation
2302 properties for the object and they are passed down into libspatialindex.
2303 A few properties are curried from instantiation parameters
2304 for you like ``pagesize`` to ensure compatibility with previous
2305 versions of the library. All other properties must be set on the
2306 object.
2307
2308 .. warning::
2309 The coordinate ordering for all functions are sensitive the
2310 index's :attr:`interleaved` data member. If :attr:`interleaved`
2311 is False, the coordinates must be in the form
2312 [xmin, xmax, ymin, ymax, ..., ..., kmin, kmax]. If
2313 :attr:`interleaved` is True, the coordinates must be in the form
2314 [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax]. This also applies
2315 to velocities when using a TPR-Tree.
2316
2317 A basic example
2318 ::
2319
2320 >>> from rtree import index
2321 >>> p = index.Property()
2322
2323 >>> idx = index.RtreeContainer(properties=p)
2324 >>> idx # doctest: +NORMALIZE_WHITESPACE
2325 rtree.index.RtreeContainer(bounds=[1.7976931348623157e+308,
2326 1.7976931348623157e+308,
2327 -1.7976931348623157e+308,
2328 -1.7976931348623157e+308],
2329 size=0)
2330
2331 Insert an item into the index::
2332
2333 >>> idx.insert(object(),
2334 ... (34.3776829412, 26.7375853734, 49.3776829412,
2335 ... 41.7375853734))
2336
2337 Query::
2338
2339 >>> hits = idx.intersection((0, 0, 60, 60), bbox=True)
2340 >>> for obj in hits:
2341 ... obj.object
2342 ... obj.bbox # doctest: +ELLIPSIS
2343 <object object at 0x...>
2344 [34.37768294..., 26.73758537..., 49.37768294..., 41.73758537...]
2345 """
2346 if args:
2347 if (
2348 isinstance(args[0], str)
2349 or isinstance(args[0], bytes)
2350 or isinstance(args[0], ICustomStorage)
2351 ):
2352 raise ValueError(f"{self.__class__} supports only in-memory indexes")
2353 self._objects: dict[int, tuple[int, object]] = {}
2354 return super().__init__(*args, **kwargs)
2355
2356 def get_size(self) -> int:
2357 try:
2358 return self.count(self.bounds)
2359 except RTreeError:
2360 return 0
2361
2362 def __repr__(self) -> str:
2363 m = "rtree.index.RtreeContainer(bounds={}, size={})"
2364 return m.format(self.bounds, self.get_size())
2365
2366 def __contains__(self, obj: object) -> bool:
2367 return id(obj) in self._objects
2368
2369 def __len__(self) -> int:
2370 return sum(count for count, obj in self._objects.values())
2371
2372 def __iter__(self) -> Iterator[object]:
2373 return iter(obj for count, obj in self._objects.values())
2374
2375 def insert(self, obj: object, coordinates: Any) -> None: # type: ignore[override]
2376 """Inserts an item into the index with the given coordinates.
2377
2378 :param obj: Any object.
2379
2380 :param coordinates: This may be an object that satisfies the numpy array
2381 protocol, providing the index's dimension * 2 coordinate
2382 pairs representing the `mink` and `maxk` coordinates in
2383 each dimension defining the bounds of the query window.
2384 For a TPR-Tree, this must be a 3-element sequence including
2385 not only the positional coordinate pairs but also the
2386 velocity pairs `minvk` and `maxvk` and a time value as a float.
2387
2388 The following example inserts a simple object into the container.
2389 The coordinate ordering in this instance is the default
2390 (interleaved=True) ordering::
2391
2392 >>> from rtree import index
2393 >>> idx = index.RtreeContainer()
2394 >>> idx.insert(object(),
2395 ... (34.3776829412, 26.7375853734, 49.3776829412,
2396 ... 41.7375853734))
2397
2398 Similar for TPR-Tree::
2399
2400 >>> p = index.Property(type=index.RT_TPRTree) # doctest: +SKIP
2401 >>> idx = index.RtreeContainer(properties=p) # doctest: +SKIP
2402 >>> idx.insert(object(),
2403 ... ((34.3776829412, 26.7375853734, 49.3776829412,
2404 ... 41.7375853734),
2405 ... (0.5, 2, 1.5, 2.5),
2406 ... 3.0)) # doctest: +SKIP
2407
2408 """
2409 try:
2410 count = self._objects[id(obj)][0] + 1
2411 except KeyError:
2412 count = 1
2413 self._objects[id(obj)] = (count, obj)
2414 return super().insert(id(obj), coordinates, None)
2415
2416 add = insert # type: ignore[assignment]
2417
2418 @overload # type: ignore[override]
2419 def intersection(self, coordinates: Any, bbox: Literal[True]) -> Iterator[Item]: ...
2420
2421 @overload
2422 def intersection(
2423 self, coordinates: Any, bbox: Literal[False] = False
2424 ) -> Iterator[object]: ...
2425
2426 def intersection(
2427 self, coordinates: Any, bbox: bool = False
2428 ) -> Iterator[Item | object]:
2429 """Return ids or objects in the index that intersect the given
2430 coordinates.
2431
2432 :param coordinates: This may be an object that satisfies the numpy array
2433 protocol, providing the index's dimension * 2 coordinate
2434 pairs representing the `mink` and `maxk` coordinates in
2435 each dimension defining the bounds of the query window.
2436 For a TPR-Tree, this must be a 3-element sequence including
2437 not only the positional coordinate pairs but also the
2438 velocity pairs `minvk` and `maxvk` and a time pair for the
2439 time range as a float.
2440
2441 :param bbox: If True, the intersection method will return the stored objects,
2442 as well as the bounds of the entry.
2443
2444 The following example queries the container for any stored objects that
2445 intersect the bounds given in the coordinates::
2446
2447 >>> from rtree import index
2448 >>> idx = index.RtreeContainer()
2449 >>> idx.insert(object(),
2450 ... (34.3776829412, 26.7375853734, 49.3776829412,
2451 ... 41.7375853734))
2452
2453 >>> hits = list(idx.intersection((0, 0, 60, 60), bbox=True))
2454 >>> [(item.object, item.bbox) for item in hits]
2455 ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
2456 [(<object object at 0x...>, [34.3776829412, 26.7375853734,
2457 49.3776829412, 41.7375853734])]
2458
2459 If the :class:`rtree.index.Item` wrapper is not used, it is faster to
2460 request only the stored objects::
2461
2462 >>> list(idx.intersection((0, 0, 60, 60))) # doctest: +ELLIPSIS
2463 [<object object at 0x...>]
2464
2465 Similar for the TPR-Tree::
2466
2467 >>> p = index.Property(type=index.RT_TPRTree) # doctest: +SKIP
2468 >>> idx = index.RtreeContainer(properties=p) # doctest: +SKIP
2469 >>> idx.insert(object(),
2470 ... ((34.3776829412, 26.7375853734, 49.3776829412,
2471 ... 41.7375853734),
2472 ... (0.5, 2, 1.5, 2.5),
2473 ... 3.0)) # doctest: +SKIP
2474
2475 >>> hits = list(idx.intersection(
2476 ... ((0, 0, 60, 60), (0, 0, 0, 0), (3, 5)), bbox=True))
2477 ... # doctest: +SKIP
2478 >>> [(item.object, item.bbox) for item in hits]
2479 ... # doctest: +SKIP
2480 [(<object object at 0x...>, [34.3776829412, 26.7375853734,
2481 49.3776829412, 41.7375853734])]
2482
2483 """
2484 if bbox is False:
2485 for id in super().intersection(coordinates, bbox):
2486 yield self._objects[id][1]
2487 elif bbox is True:
2488 for value in super().intersection(coordinates, bbox):
2489 value.object = self._objects[value.id][1]
2490 value.id = None
2491 yield value
2492 else:
2493 raise ValueError("valid values for the bbox argument are True and False")
2494
2495 @overload # type: ignore[override]
2496 def nearest(
2497 self, coordinates: Any, num_results: int = 1, bbox: Literal[True] = True
2498 ) -> Iterator[Item]: ...
2499
2500 @overload
2501 def nearest(
2502 self, coordinates: Any, num_results: int = 1, bbox: Literal[False] = False
2503 ) -> Iterator[object]: ...
2504
2505 def nearest(
2506 self, coordinates: Any, num_results: int = 1, bbox: bool = False
2507 ) -> Iterator[Item | object]:
2508 """Returns the ``k``-nearest objects to the given coordinates
2509 in increasing distance order.
2510
2511 :param coordinates: This may be an object that satisfies the numpy array
2512 protocol, providing the index's dimension * 2 coordinate
2513 pairs representing the `mink` and `maxk` coordinates in
2514 each dimension defining the bounds of the query window.
2515 For a TPR-Tree, this must be a 3-element sequence including
2516 not only the positional coordinate pairs but also the
2517 velocity pairs `minvk` and `maxvk` and a time pair for the
2518 time range as a float.
2519
2520 :param num_results: The number of results to return nearest to the given
2521 coordinates. If two entries are equidistant, *both* are returned.
2522 This property means that :attr:`num_results` may return more
2523 items than specified.
2524
2525 :param bbox: If True, the nearest method will return the stored objects, as
2526 well as the bounds of the entry.
2527
2528 .. warning::
2529 This is currently not implemented for the TPR-Tree.
2530
2531 Example of finding the three items nearest to this one::
2532
2533 >>> from rtree import index
2534 >>> idx = index.RtreeContainer()
2535 >>> idx.insert(object(), (34.37, 26.73, 49.37, 41.73))
2536 >>> hits = idx.nearest((0, 0, 10, 10), 3, bbox=True)
2537 """
2538 if bbox is False:
2539 for id in super().nearest(coordinates, num_results, bbox):
2540 yield self._objects[id][1]
2541 elif bbox is True:
2542 for value in super().nearest(coordinates, num_results, bbox):
2543 value.object = self._objects[value.id][1]
2544 value.id = None
2545 yield value
2546 else:
2547 raise ValueError("valid values for the bbox argument are True and False")
2548
2549 def delete(self, obj: object, coordinates: Any) -> None:
2550 """Deletes the item from the container within the specified
2551 coordinates.
2552
2553 :param obj: Any object.
2554
2555 :param coordinates: Dimension * 2 coordinate pairs, representing the min
2556 and max coordinates in each dimension of the item to be
2557 deleted from the index. Their ordering will depend on the
2558 index's :attr:`interleaved` data member.
2559 These are not the coordinates of a space containing the
2560 item, but those of the item itself. Together with the
2561 id parameter, they determine which item will be deleted.
2562 This may be an object that satisfies the numpy array protocol.
2563 For a TPR-Tree, this must be a 3-element sequence including
2564 not only the positional coordinate pairs but also the
2565 velocity pairs `minvk` and `maxvk` and a time pair for the
2566 original time the object was inserted and the current time
2567 as a float.
2568
2569 Example::
2570
2571 >>> from rtree import index
2572 >>> idx = index.RtreeContainer()
2573 >>> idx.delete(object(),
2574 ... (34.3776829412, 26.7375853734, 49.3776829412,
2575 ... 41.7375853734))
2576 Traceback (most recent call last):
2577 ...
2578 IndexError: object is not in the index
2579
2580 For the TPR-Tree::
2581
2582 >>> p = index.Property(type=index.RT_TPRTree) # doctest: +SKIP
2583 >>> idx = index.RtreeContainer(properties=p) # doctest: +SKIP
2584 >>> idx.delete(object(),
2585 ... ((34.3776829412, 26.7375853734, 49.3776829412,
2586 ... 41.7375853734),
2587 ... (0.5, 2, 1.5, 2.5),
2588 ... (3.0, 5.0))) # doctest: +SKIP
2589 Traceback (most recent call last):
2590 ...
2591 IndexError: object is not in the index
2592
2593 """
2594 try:
2595 count = self._objects[id(obj)][0] - 1
2596 except KeyError:
2597 raise IndexError("object is not in the index")
2598 if count == 0:
2599 del self._objects[id(obj)]
2600 else:
2601 self._objects[id(obj)] = (count, obj)
2602 return super().delete(id(obj), coordinates)
2603
2604 def leaves(self):
2605 return [
2606 (
2607 self._objects[id][1],
2608 [self._objects[child_id][1] for child_id in child_ids],
2609 bounds,
2610 )
2611 for id, child_ids, bounds in super().leaves()
2612 ]