strtree.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. """STRtree spatial index for efficient spatial queries."""
  2. from collections.abc import Iterable
  3. from typing import Any
  4. import numpy as np
  5. from shapely import lib
  6. from shapely._enum import ParamEnum
  7. from shapely.decorators import UnsupportedGEOSVersionError
  8. from shapely.geometry.base import BaseGeometry
  9. from shapely.predicates import is_empty, is_missing
  10. __all__ = ["STRtree"]
  11. class BinaryPredicate(ParamEnum):
  12. """The enumeration of GEOS binary predicates types."""
  13. intersects = 1
  14. within = 2
  15. contains = 3
  16. overlaps = 4
  17. crosses = 5
  18. touches = 6
  19. covers = 7
  20. covered_by = 8
  21. contains_properly = 9
  22. class STRtree:
  23. """A query-only R-tree spatial index.
  24. It is created using the Sort-Tile-Recursive (STR) [1]_ algorithm.
  25. The tree indexes the bounding boxes of each geometry. The tree is
  26. constructed directly at initialization and nodes cannot be added or
  27. removed after it has been created.
  28. All operations return indices of the input geometries. These indices
  29. can be used to index into anything associated with the input geometries,
  30. including the input geometries themselves, or custom items stored in
  31. another object of the same length as the geometries.
  32. Bounding boxes limited to two dimensions and are axis-aligned (equivalent to
  33. the ``bounds`` property of a geometry); any Z values present in geometries
  34. are ignored for purposes of indexing within the tree.
  35. Any mixture of geometry types may be stored in the tree.
  36. Note: the tree is more efficient for querying when there are fewer
  37. geometries that have overlapping bounding boxes and where there is greater
  38. similarity between the outer boundary of a geometry and its bounding box.
  39. For example, a MultiPolygon composed of widely-spaced individual Polygons
  40. will have a large overall bounding box compared to the boundaries of its
  41. individual Polygons, and the bounding box may also potentially overlap many
  42. other geometries within the tree. This means that the resulting tree may be
  43. less efficient to query than a tree constructed from individual Polygons.
  44. Parameters
  45. ----------
  46. geoms : sequence
  47. A sequence of geometry objects.
  48. node_capacity : int, default 10
  49. The maximum number of child nodes per parent node in the tree.
  50. References
  51. ----------
  52. .. [1] Leutenegger, Scott T.; Edgington, Jeffrey M.; Lopez, Mario A.
  53. (February 1997). "STR: A Simple and Efficient Algorithm for
  54. R-Tree Packing".
  55. https://ia600900.us.archive.org/27/items/nasa_techdoc_19970016975/19970016975.pdf
  56. """
  57. def __init__(self, geoms: Iterable[BaseGeometry], node_capacity: int = 10):
  58. """Create a new STRtree spatial index."""
  59. # Keep references to geoms in a copied array so that this array is not
  60. # modified while the tree depends on it remaining the same
  61. self._geometries = np.array(geoms, dtype=np.object_, copy=True)
  62. # initialize GEOS STRtree
  63. self._tree = lib.STRtree(self.geometries, node_capacity)
  64. def __len__(self):
  65. """Return the number of geometries in the tree."""
  66. return self._tree.count
  67. def __reduce__(self):
  68. """Pickle support."""
  69. return (STRtree, (self.geometries,))
  70. @property
  71. def geometries(self):
  72. """Geometries stored in the tree in the order used to construct the tree.
  73. The order of this array corresponds to the tree indices returned by
  74. other STRtree methods.
  75. Do not attempt to modify items in the returned array.
  76. Returns
  77. -------
  78. ndarray of Geometry objects
  79. """
  80. return self._geometries
  81. def query(self, geometry, predicate=None, distance=None):
  82. """Get the index combinations of all possibly intersecting geometries.
  83. Returns the integer indices of all combinations of each input geometry
  84. and tree geometries where the bounding box of each input geometry
  85. intersects the bounding box of a tree geometry.
  86. If the input geometry is a scalar, this returns an array of shape (n, ) with
  87. the indices of the matching tree geometries. If the input geometry is an
  88. array_like, this returns an array with shape (2,n) where the subarrays
  89. correspond to the indices of the input geometries and indices of the
  90. tree geometries associated with each. To generate an array of pairs of
  91. input geometry index and tree geometry index, simply transpose the
  92. result.
  93. If a predicate is provided, the tree geometries are first queried based
  94. on the bounding box of the input geometry and then are further filtered
  95. to those that meet the predicate when comparing the input geometry to
  96. the tree geometry:
  97. predicate(geometry, tree_geometry)
  98. The 'dwithin' predicate requires GEOS >= 3.10.
  99. Bounding boxes are limited to two dimensions and are axis-aligned
  100. (equivalent to the ``bounds`` property of a geometry); any Z values
  101. present in input geometries are ignored when querying the tree.
  102. Any input geometry that is None or empty will never match geometries in
  103. the tree.
  104. Parameters
  105. ----------
  106. geometry : Geometry or array_like
  107. Input geometries to query the tree and filter results using the
  108. optional predicate.
  109. predicate : {None, 'intersects', 'within', 'contains', 'overlaps', 'crosses',\
  110. 'touches', 'covers', 'covered_by', 'contains_properly', 'dwithin'}, optional
  111. The predicate to use for testing geometries from the tree
  112. that are within the input geometry's bounding box.
  113. distance : number or array_like, optional
  114. Distances around each input geometry within which to query the tree
  115. for the 'dwithin' predicate. If array_like, shape must be
  116. broadcastable to shape of geometry. Required if predicate='dwithin'.
  117. Returns
  118. -------
  119. ndarray with shape (n,) if geometry is a scalar
  120. Contains tree geometry indices.
  121. OR
  122. ndarray with shape (2, n) if geometry is an array_like
  123. The first subarray contains input geometry indices.
  124. The second subarray contains tree geometry indices.
  125. Examples
  126. --------
  127. >>> from shapely import box, Point, STRtree
  128. >>> import numpy as np
  129. >>> points = [Point(0, 0), Point(1, 1), Point(2,2), Point(3, 3)]
  130. >>> tree = STRtree(points)
  131. Query the tree using a scalar geometry:
  132. >>> indices = tree.query(box(0, 0, 1, 1))
  133. >>> indices.tolist()
  134. [0, 1]
  135. Query using an array of geometries:
  136. >>> boxes = np.array([box(0, 0, 1, 1), box(2, 2, 3, 3)])
  137. >>> arr_indices = tree.query(boxes)
  138. >>> arr_indices.tolist()
  139. [[0, 0, 1, 1], [0, 1, 2, 3]]
  140. Or transpose to get all pairs of input and tree indices:
  141. >>> arr_indices.T.tolist()
  142. [[0, 0], [0, 1], [1, 2], [1, 3]]
  143. Retrieve the tree geometries by results of query:
  144. >>> tree.geometries.take(indices).tolist()
  145. [<POINT (0 0)>, <POINT (1 1)>]
  146. Retrieve all pairs of input and tree geometries:
  147. >>> np.array([boxes.take(arr_indices[0]),\
  148. tree.geometries.take(arr_indices[1])]).T.tolist()
  149. [[<POLYGON ((1 0, 1 1, 0 1, 0 0, 1 0))>, <POINT (0 0)>],
  150. [<POLYGON ((1 0, 1 1, 0 1, 0 0, 1 0))>, <POINT (1 1)>],
  151. [<POLYGON ((3 2, 3 3, 2 3, 2 2, 3 2))>, <POINT (2 2)>],
  152. [<POLYGON ((3 2, 3 3, 2 3, 2 2, 3 2))>, <POINT (3 3)>]]
  153. Query using a predicate:
  154. >>> tree = STRtree([box(0, 0, 0.5, 0.5), box(0.5, 0.5, 1, 1), box(1, 1, 2, 2)])
  155. >>> tree.query(box(0, 0, 1, 1), predicate="contains").tolist()
  156. [0, 1]
  157. >>> tree.query(Point(0.75, 0.75), predicate="dwithin", distance=0.5).tolist()
  158. [0, 1, 2]
  159. >>> tree.query(boxes, predicate="contains").tolist()
  160. [[0, 0], [0, 1]]
  161. >>> tree.query(boxes, predicate="dwithin", distance=0.5).tolist()
  162. [[0, 0, 0, 1], [0, 1, 2, 2]]
  163. Retrieve custom items associated with tree geometries (records can
  164. be in whatever data structure so long as geometries and custom data
  165. can be extracted into arrays of the same length and order):
  166. >>> records = [
  167. ... {"geometry": Point(0, 0), "value": "A"},
  168. ... {"geometry": Point(2, 2), "value": "B"}
  169. ... ]
  170. >>> tree = STRtree([record["geometry"] for record in records])
  171. >>> items = np.array([record["value"] for record in records])
  172. >>> items.take(tree.query(box(0, 0, 1, 1))).tolist()
  173. ['A']
  174. Notes
  175. -----
  176. In the context of a spatial join, input geometries are the "left"
  177. geometries that determine the order of the results, and tree geometries
  178. are "right" geometries that are joined against the left geometries. This
  179. effectively performs an inner join, where only those combinations of
  180. geometries that can be joined based on overlapping bounding boxes or
  181. optional predicate are returned.
  182. """
  183. geometry = np.asarray(geometry)
  184. is_scalar = False
  185. if geometry.ndim == 0:
  186. geometry = np.expand_dims(geometry, 0)
  187. is_scalar = True
  188. if predicate is None:
  189. indices = self._tree.query(geometry, 0)
  190. return indices[1] if is_scalar else indices
  191. # Requires GEOS >= 3.10
  192. elif predicate == "dwithin":
  193. if lib.geos_version < (3, 10, 0):
  194. raise UnsupportedGEOSVersionError(
  195. "dwithin predicate requires GEOS >= 3.10"
  196. )
  197. if distance is None:
  198. raise ValueError(
  199. "distance parameter must be provided for dwithin predicate"
  200. )
  201. distance = np.asarray(distance, dtype="float64")
  202. if distance.ndim > 1:
  203. raise ValueError("Distance array should be one dimensional")
  204. try:
  205. distance = np.broadcast_to(distance, geometry.shape)
  206. except ValueError:
  207. raise ValueError("Could not broadcast distance to match geometry")
  208. indices = self._tree.dwithin(geometry, distance)
  209. return indices[1] if is_scalar else indices
  210. predicate = BinaryPredicate.get_value(predicate)
  211. indices = self._tree.query(geometry, predicate)
  212. return indices[1] if is_scalar else indices
  213. def nearest(self, geometry) -> Any | None:
  214. """Return the index of the nearest geometry in the tree.
  215. This is determined for each input geometry based on distance within
  216. two-dimensional Cartesian space.
  217. This distance will be 0 when input geometries intersect tree geometries.
  218. If there are multiple equidistant or intersected geometries in the tree,
  219. only a single result is returned for each input geometry, based on the
  220. order that tree geometries are visited; this order may be
  221. nondeterministic.
  222. If any input geometry is None or empty, an error is raised. Any Z
  223. values present in input geometries are ignored when finding nearest
  224. tree geometries.
  225. Parameters
  226. ----------
  227. geometry : Geometry or array_like
  228. Input geometries to query the tree.
  229. Returns
  230. -------
  231. scalar or ndarray
  232. Indices of geometries in tree. Return value will have the same shape
  233. as the input.
  234. None is returned if this index is empty. This may change in
  235. version 2.0.
  236. See Also
  237. --------
  238. query_nearest: returns all equidistant geometries, exclusive geometries, \
  239. and optional distances
  240. Examples
  241. --------
  242. >>> from shapely import Point, STRtree
  243. >>> tree = STRtree([Point(i, i) for i in range(10)])
  244. Query the tree for nearest using a scalar geometry:
  245. >>> index = tree.nearest(Point(2.2, 2.2))
  246. >>> index
  247. 2
  248. >>> tree.geometries.take(index)
  249. <POINT (2 2)>
  250. Query the tree for nearest using an array of geometries:
  251. >>> indices = tree.nearest([Point(2.2, 2.2), Point(4.4, 4.4)])
  252. >>> indices.tolist()
  253. [2, 4]
  254. >>> tree.geometries.take(indices).tolist()
  255. [<POINT (2 2)>, <POINT (4 4)>]
  256. Nearest only return one object if there are multiple equidistant results:
  257. >>> tree = STRtree ([Point(0, 0), Point(0, 0)])
  258. >>> tree.nearest(Point(0, 0))
  259. 0
  260. """
  261. if self._tree.count == 0:
  262. return None
  263. geometry_arr = np.asarray(geometry, dtype=object)
  264. if is_missing(geometry_arr).any() or is_empty(geometry_arr).any():
  265. raise ValueError(
  266. "Cannot determine nearest geometry for empty geometry or "
  267. "missing value (None)."
  268. )
  269. # _tree.nearest returns ndarray with shape (2, 1) -> index in input
  270. # geometries and index into tree geometries
  271. indices = self._tree.nearest(np.atleast_1d(geometry_arr))[1]
  272. if geometry_arr.ndim == 0:
  273. return indices[0]
  274. else:
  275. return indices
  276. def query_nearest(
  277. self,
  278. geometry,
  279. max_distance=None,
  280. return_distance=False,
  281. exclusive=False,
  282. all_matches=True,
  283. ):
  284. """Return the index of the nearest geometries in the tree.
  285. This is determined for each input geometry based on distance within
  286. two-dimensional Cartesian space.
  287. This distance will be 0 when input geometries intersect tree geometries.
  288. If there are multiple equidistant or intersected geometries in tree and
  289. `all_matches` is True (the default), all matching tree geometries are
  290. returned; otherwise only the first matching tree geometry is returned.
  291. Tree indices are returned in the order they are visited for each input
  292. geometry and may not be in ascending index order; no meaningful order is
  293. implied.
  294. The max_distance used to search for nearest items in the tree may have a
  295. significant impact on performance by reducing the number of input
  296. geometries that are evaluated for nearest items in the tree. Only those
  297. input geometries with at least one tree geometry within +/- max_distance
  298. beyond their envelope will be evaluated. However, using a large
  299. max_distance may have a negative performance impact because many tree
  300. geometries will be queried for each input geometry.
  301. The distance, if returned, will be 0 for any intersected geometries in
  302. the tree.
  303. Any geometry that is None or empty in the input geometries is omitted
  304. from the output. Any Z values present in input geometries are ignored
  305. when finding nearest tree geometries.
  306. Parameters
  307. ----------
  308. geometry : Geometry or array_like
  309. Input geometries to query the tree.
  310. max_distance : float, optional
  311. Maximum distance within which to query for nearest items in tree.
  312. Must be greater than 0.
  313. return_distance : bool, default False
  314. If True, will return distances in addition to indices.
  315. exclusive : bool, default False
  316. If True, the nearest tree geometries that are equal to the input
  317. geometry will not be returned.
  318. all_matches : bool, default True
  319. If True, all equidistant and intersected geometries will be returned
  320. for each input geometry.
  321. If False, only the first nearest geometry will be returned.
  322. Returns
  323. -------
  324. tree indices or tuple of (tree indices, distances) if geometry is a scalar
  325. indices is an ndarray of shape (n, ) and distances (if present) an
  326. ndarray of shape (n, )
  327. OR
  328. indices or tuple of (indices, distances)
  329. indices is an ndarray of shape (2,n) and distances (if present) an
  330. ndarray of shape (n).
  331. The first subarray of indices contains input geometry indices.
  332. The second subarray of indices contains tree geometry indices.
  333. See Also
  334. --------
  335. nearest: returns singular nearest geometry for each input
  336. Examples
  337. --------
  338. >>> import numpy as np
  339. >>> from shapely import box, Point, STRtree
  340. >>> points = [Point(0, 0), Point(1, 1), Point(2,2), Point(3, 3)]
  341. >>> tree = STRtree(points)
  342. Find the nearest tree geometries to a scalar geometry:
  343. >>> indices = tree.query_nearest(Point(0.25, 0.25))
  344. >>> indices.tolist()
  345. [0]
  346. Retrieve the tree geometries by results of query:
  347. >>> tree.geometries.take(indices).tolist()
  348. [<POINT (0 0)>]
  349. Find the nearest tree geometries to an array of geometries:
  350. >>> query_points = np.array([Point(2.25, 2.25), Point(1, 1)])
  351. >>> arr_indices = tree.query_nearest(query_points)
  352. >>> arr_indices.tolist()
  353. [[0, 1], [2, 1]]
  354. Or transpose to get all pairs of input and tree indices:
  355. >>> arr_indices.T.tolist()
  356. [[0, 2], [1, 1]]
  357. Retrieve all pairs of input and tree geometries:
  358. >>> list(zip(query_points.take(arr_indices[0]), tree.geometries.take(arr_indices[1])))
  359. [(<POINT (2.25 2.25)>, <POINT (2 2)>), (<POINT (1 1)>, <POINT (1 1)>)]
  360. All intersecting geometries in the tree are returned by default:
  361. >>> tree.query_nearest(box(1,1,3,3)).tolist()
  362. [1, 2, 3]
  363. Set all_matches to False to to return a single match per input geometry:
  364. >>> tree.query_nearest(box(1,1,3,3), all_matches=False).tolist()
  365. [1]
  366. Return the distance to each nearest tree geometry:
  367. >>> index, distance = tree.query_nearest(Point(0.5, 0.5), return_distance=True)
  368. >>> index.tolist()
  369. [0, 1]
  370. >>> distance.round(4).tolist()
  371. [0.7071, 0.7071]
  372. Return the distance for each input and nearest tree geometry for an array
  373. of geometries:
  374. >>> indices, distance = tree.query_nearest([Point(0.5, 0.5), Point(1, 1)], return_distance=True)
  375. >>> indices.tolist()
  376. [[0, 0, 1], [0, 1, 1]]
  377. >>> distance.round(4).tolist()
  378. [0.7071, 0.7071, 0.0]
  379. Retrieve custom items associated with tree geometries (records can
  380. be in whatever data structure so long as geometries and custom data
  381. can be extracted into arrays of the same length and order):
  382. >>> records = [
  383. ... {"geometry": Point(0, 0), "value": "A"},
  384. ... {"geometry": Point(2, 2), "value": "B"}
  385. ... ]
  386. >>> tree = STRtree([record["geometry"] for record in records])
  387. >>> items = np.array([record["value"] for record in records])
  388. >>> items.take(tree.query_nearest(Point(0.5, 0.5))).tolist()
  389. ['A']
  390. """ # noqa: E501
  391. geometry = np.asarray(geometry, dtype=object)
  392. is_scalar = False
  393. if geometry.ndim == 0:
  394. geometry = np.expand_dims(geometry, 0)
  395. is_scalar = True
  396. if max_distance is not None:
  397. if not np.isscalar(max_distance):
  398. raise ValueError("max_distance parameter only accepts scalar values")
  399. if max_distance <= 0:
  400. raise ValueError("max_distance must be greater than 0")
  401. # a distance of 0 means no max_distance is used
  402. max_distance = max_distance or 0
  403. if not np.isscalar(exclusive):
  404. raise ValueError("exclusive parameter only accepts scalar values")
  405. if exclusive not in {True, False}:
  406. raise ValueError("exclusive parameter must be boolean")
  407. if not np.isscalar(all_matches):
  408. raise ValueError("all_matches parameter only accepts scalar values")
  409. if all_matches not in {True, False}:
  410. raise ValueError("all_matches parameter must be boolean")
  411. results = self._tree.query_nearest(
  412. geometry, max_distance, exclusive, all_matches
  413. )
  414. # output indices are shape (n, )
  415. if is_scalar:
  416. if not return_distance:
  417. return results[0][1]
  418. else:
  419. return (results[0][1], results[1])
  420. # output indices are shape (2, n)
  421. if not return_distance:
  422. return results[0]
  423. return results