rstar/
rtree.rs

1use crate::algorithm::bulk_load;
2use crate::algorithm::intersection_iterator::IntersectionIterator;
3use crate::algorithm::iterators::*;
4use crate::algorithm::nearest_neighbor;
5use crate::algorithm::nearest_neighbor::NearestNeighborDistance2Iterator;
6use crate::algorithm::nearest_neighbor::NearestNeighborIterator;
7use crate::algorithm::removal;
8use crate::algorithm::removal::DrainIterator;
9use crate::algorithm::selection_functions::*;
10use crate::envelope::Envelope;
11use crate::node::ParentNode;
12use crate::object::{PointDistance, RTreeObject};
13use crate::params::{verify_parameters, DefaultParams, InsertionStrategy, RTreeParams};
14use crate::Point;
15
16use alloc::vec::Vec;
17
18#[cfg(feature = "serde")]
19use serde::{Deserialize, Serialize};
20
21impl<T, Params> Default for RTree<T, Params>
22where
23    T: RTreeObject,
24    Params: RTreeParams,
25{
26    fn default() -> Self {
27        Self::new_with_params()
28    }
29}
30
31/// An n-dimensional r-tree data structure.
32///
33/// # R-Trees
34/// R-Trees are data structures containing multi-dimensional objects like points, rectangles
35/// or polygons. They are optimized for retrieving the nearest neighbor at any point.
36///
37/// R-trees can efficiently find answers to queries like "Find the nearest point of a polygon",
38/// "Find all police stations within a rectangle" or "Find the 10 nearest restaurants, sorted
39/// by their distances". Compared to a naive implementation for these scenarios that runs
40/// in `O(n)` for `n` inserted elements, r-trees reduce this time to `O(log(n))`.
41///
42/// However, creating an r-tree is time consuming
43/// and runs in `O(n * log(n))`. Thus, r-trees are suited best if many queries and only few
44/// insertions are made. rstar also supports [bulk loading](RTree::bulk_load),
45/// which cuts down the constant factors when creating an r-tree significantly compared to
46/// sequential insertions.
47///
48/// R-trees are also _dynamic_: points can be inserted and removed from an existing tree.
49///
50/// ## Partitioning heuristics
51/// The inserted objects are internally partitioned into several boxes which should have small
52/// overlap and volume. This is done heuristically. While the originally proposed heuristic focused
53/// on fast insertion operations, the resulting r-trees were often suboptimally structured. Another
54/// heuristic, called `R*-tree` (r-star-tree), was proposed to improve the tree structure at the cost of
55/// longer insertion operations and is currently the crate's only implemented
56/// [insertion strategy].
57///
58/// ## Further reading
59/// For more information refer to the [wikipedia article](https://en.wikipedia.org/wiki/R-tree).
60///
61/// # Usage
62/// The items inserted into an r-tree must implement the [RTreeObject]
63/// trait. To support nearest neighbor queries, implement the [PointDistance]
64/// trait. Some useful geometric primitives that implement the above traits can be found in the
65/// [crate::primitives]x module. Several primitives in the [`geo-types`](https://docs.rs/geo-types/) crate also
66/// implement these traits.
67///
68/// ## Example
69/// ```
70/// use rstar::RTree;
71///
72/// let mut tree = RTree::new();
73/// tree.insert([0.1, 0.0f32]);
74/// tree.insert([0.2, 0.1]);
75/// tree.insert([0.3, 0.0]);
76///
77/// assert_eq!(tree.nearest_neighbor(&[0.4, -0.1]), Some(&[0.3, 0.0]));
78/// tree.remove(&[0.3, 0.0]);
79/// assert_eq!(tree.nearest_neighbor(&[0.4, 0.3]), Some(&[0.2, 0.1]));
80///
81/// assert_eq!(tree.size(), 2);
82/// // &RTree implements IntoIterator!
83/// for point in &tree {
84///     println!("Tree contains a point {:?}", point);
85/// }
86/// ```
87///
88/// ## Supported point types
89/// All types implementing the [Point] trait can be used as underlying point type.
90/// By default, fixed size arrays can be used as points.
91///
92/// ## Type Parameters
93/// * `T`: The type of objects stored in the r-tree.
94/// * `Params`: Compile time parameters that change the r-tree's internal layout. Refer to the
95/// [RTreeParams] trait for more information.
96///
97/// ## Defining methods generic over r-trees
98/// If a library defines a method that should be generic over the r-tree type signature, make
99/// sure to include both type parameters like this:
100/// ```
101/// # use rstar::{RTree,RTreeObject, RTreeParams};
102/// pub fn generic_rtree_function<T, Params>(tree: &mut RTree<T, Params>)
103/// where
104///   T: RTreeObject,
105///   Params: RTreeParams
106/// {
107///   // ...
108/// }
109/// ```
110/// Otherwise, any user of `generic_rtree_function` would be forced to use
111/// a tree with default parameters.
112///
113/// # Runtime and Performance
114/// The runtime of query operations (e.g. `nearest neighbor` or `contains`) is usually
115/// `O(log(n))`, where `n` refers to the number of elements contained in the r-tree.
116/// A naive sequential algorithm would take `O(n)` time. However, r-trees incur higher
117/// build up times: inserting an element into an r-tree costs `O(log(n))` time.
118///
119/// ## Bulk loading
120/// In many scenarios, insertion is only carried out once for many points. In this case,
121/// [RTree::bulk_load] will be considerably faster. Its total run time
122/// is still `O(log(n))`.
123///
124/// ## Element distribution
125/// The tree's performance heavily relies on the spatial distribution of its elements.
126/// Best performance is achieved if:
127///  * No element is inserted more than once
128///  * The overlapping area of elements is as small as
129///    possible.
130///
131/// For the edge case that all elements are overlapping (e.g, one and the same element
132/// is contained `n` times), the performance of most operations usually degrades to `O(n)`.
133///
134/// # (De)Serialization
135/// Enable the `serde` feature for [Serde](https://crates.io/crates/serde) support.
136///
137#[derive(Clone)]
138#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
139#[cfg_attr(
140    feature = "serde",
141    serde(bound(
142        serialize = "T: Serialize, T::Envelope: Serialize",
143        deserialize = "T: Deserialize<'de>, T::Envelope: Deserialize<'de>"
144    ))
145)]
146pub struct RTree<T, Params = DefaultParams>
147where
148    Params: RTreeParams,
149    T: RTreeObject,
150{
151    root: ParentNode<T>,
152    size: usize,
153    _params: ::core::marker::PhantomData<Params>,
154}
155
156struct DebugHelper<'a, T, Params>
157where
158    T: RTreeObject + ::core::fmt::Debug + 'a,
159    Params: RTreeParams + 'a,
160{
161    rtree: &'a RTree<T, Params>,
162}
163
164impl<'a, T, Params> ::core::fmt::Debug for DebugHelper<'a, T, Params>
165where
166    T: RTreeObject + ::core::fmt::Debug,
167    Params: RTreeParams,
168{
169    fn fmt(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
170        formatter.debug_set().entries(self.rtree.iter()).finish()
171    }
172}
173
174impl<T, Params> ::core::fmt::Debug for RTree<T, Params>
175where
176    Params: RTreeParams,
177    T: RTreeObject + ::core::fmt::Debug,
178{
179    fn fmt(&self, formatter: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
180        formatter
181            .debug_struct("RTree")
182            .field("size", &self.size)
183            .field("items", &DebugHelper { rtree: self })
184            .finish()
185    }
186}
187
188impl<T> RTree<T>
189where
190    T: RTreeObject,
191{
192    /// Creates a new, empty r-tree.
193    ///
194    /// The created r-tree is configured with [default parameters](DefaultParams).
195    pub fn new() -> Self {
196        Self::new_with_params()
197    }
198
199    /// Creates a new r-tree with some elements already inserted.
200    ///
201    /// This method should be the preferred way for creating r-trees. It both
202    /// runs faster and yields an r-tree with better internal structure that
203    /// improves query performance.
204    ///
205    /// This method implements the overlap minimizing top-down bulk loading algorithm (OMT)
206    /// as described in [this paper by Lee and Lee (2003)](http://ceur-ws.org/Vol-74/files/FORUM_18.pdf).
207    ///
208    /// # Runtime
209    /// Bulk loading runs in `O(n * log(n))`, where `n` is the number of loaded
210    /// elements.
211    pub fn bulk_load(elements: Vec<T>) -> Self {
212        Self::bulk_load_with_params(elements)
213    }
214}
215
216impl<T, Params> RTree<T, Params>
217where
218    Params: RTreeParams,
219    T: RTreeObject,
220{
221    /// Creates a new, empty r-tree.
222    ///
223    /// The tree's compile time parameters must be specified. Refer to the
224    /// [RTreeParams] trait for more information and a usage example.
225    pub fn new_with_params() -> Self {
226        verify_parameters::<T, Params>();
227        RTree {
228            root: ParentNode::new_root::<Params>(),
229            size: 0,
230            _params: Default::default(),
231        }
232    }
233
234    /// Creates a new r-tree with some given elements and configurable parameters.
235    ///
236    /// For more information refer to [RTree::bulk_load]
237    /// and [RTreeParams].
238    pub fn bulk_load_with_params(elements: Vec<T>) -> Self {
239        Self::new_from_bulk_loading(elements, bulk_load::bulk_load_sequential::<_, Params>)
240    }
241
242    /// Returns the number of objects in an r-tree.
243    ///
244    /// # Example
245    /// ```
246    /// use rstar::RTree;
247    ///
248    /// let mut tree = RTree::new();
249    /// assert_eq!(tree.size(), 0);
250    /// tree.insert([0.0, 1.0, 2.0]);
251    /// assert_eq!(tree.size(), 1);
252    /// tree.remove(&[0.0, 1.0, 2.0]);
253    /// assert_eq!(tree.size(), 0);
254    /// ```
255    pub fn size(&self) -> usize {
256        self.size
257    }
258
259    pub(crate) fn size_mut(&mut self) -> &mut usize {
260        &mut self.size
261    }
262
263    /// Returns an iterator over all elements contained in the tree.
264    ///
265    /// The order in which the elements are returned is not specified.
266    ///
267    /// # Example
268    /// ```
269    /// use rstar::RTree;
270    /// let tree = RTree::bulk_load(vec![(0.0, 0.1), (0.3, 0.2), (0.4, 0.2)]);
271    /// for point in tree.iter() {
272    ///     println!("This tree contains point {:?}", point);
273    /// }
274    /// ```
275    pub fn iter(&self) -> RTreeIterator<T> {
276        RTreeIterator::new(&self.root, SelectAllFunc)
277    }
278
279    /// Returns an iterator over all mutable elements contained in the tree.
280    ///
281    /// The order in which the elements are returned is not specified.
282    ///
283    /// *Note*: It is a logic error to change an inserted item's position or dimensions. This
284    /// method is primarily meant for own implementations of [RTreeObject]
285    /// which can contain arbitrary additional data.
286    /// If the position or location of an inserted object need to change, you will need to [RTree::remove]
287    /// and reinsert it.
288    ///
289    pub fn iter_mut(&mut self) -> RTreeIteratorMut<T> {
290        RTreeIteratorMut::new(&mut self.root, SelectAllFunc)
291    }
292
293    /// Returns all elements contained in an [Envelope].
294    ///
295    /// Usually, an envelope is an [axis aligned bounding box](crate::AABB). This
296    /// method can be used to retrieve all elements that are fully contained within an envelope.
297    ///
298    /// # Example
299    /// ```
300    /// use rstar::{RTree, AABB};
301    /// let mut tree = RTree::bulk_load(vec![
302    ///   [0.0, 0.0],
303    ///   [0.0, 1.0],
304    ///   [1.0, 1.0]
305    /// ]);
306    /// let half_unit_square = AABB::from_corners([0.0, 0.0], [0.5, 1.0]);
307    /// let unit_square = AABB::from_corners([0.0, 0.0], [1.0, 1.0]);
308    /// let elements_in_half_unit_square = tree.locate_in_envelope(&half_unit_square);
309    /// let elements_in_unit_square = tree.locate_in_envelope(&unit_square);
310    /// assert_eq!(elements_in_half_unit_square.count(), 2);
311    /// assert_eq!(elements_in_unit_square.count(), 3);
312    /// ```
313    pub fn locate_in_envelope(&self, envelope: &T::Envelope) -> LocateInEnvelope<T> {
314        LocateInEnvelope::new(&self.root, SelectInEnvelopeFunction::new(envelope.clone()))
315    }
316
317    /// Mutable variant of [locate_in_envelope](#method.locate_in_envelope).
318    pub fn locate_in_envelope_mut(&mut self, envelope: &T::Envelope) -> LocateInEnvelopeMut<T> {
319        LocateInEnvelopeMut::new(
320            &mut self.root,
321            SelectInEnvelopeFunction::new(envelope.clone()),
322        )
323    }
324
325    /// Returns a draining iterator over all elements contained in the tree.
326    ///
327    /// The order in which the elements are returned is not specified.
328    ///
329    /// See
330    /// [drain_with_selection_function](#method.drain_with_selection_function)
331    /// for more information.
332    pub fn drain(&mut self) -> DrainIterator<T, SelectAllFunc, Params> {
333        self.drain_with_selection_function(SelectAllFunc)
334    }
335
336    /// Draining variant of [locate_in_envelope](#method.locate_in_envelope).
337    pub fn drain_in_envelope(
338        &mut self,
339        envelope: T::Envelope,
340    ) -> DrainIterator<T, SelectInEnvelopeFunction<T>, Params> {
341        let sel = SelectInEnvelopeFunction::new(envelope);
342        self.drain_with_selection_function(sel)
343    }
344
345    /// Returns all elements whose envelope intersects a given envelope.
346    ///
347    /// Any element fully contained within an envelope is also returned by this method. Two
348    /// envelopes that "touch" each other (e.g. by sharing only a common corner) are also
349    /// considered to intersect. Usually, an envelope is an [axis aligned bounding box](crate::AABB).
350    /// This method will return all elements whose AABB has some common area with
351    /// a given AABB.
352    ///
353    /// # Example
354    /// ```
355    /// use rstar::{RTree, AABB};
356    /// use rstar::primitives::Rectangle;
357    ///
358    /// let left_piece = AABB::from_corners([0.0, 0.0], [0.4, 1.0]);
359    /// let right_piece = AABB::from_corners([0.6, 0.0], [1.0, 1.0]);
360    /// let middle_piece = AABB::from_corners([0.25, 0.0], [0.75, 1.0]);
361    ///
362    /// let mut tree = RTree::<Rectangle<_>>::bulk_load(vec![
363    ///   left_piece.into(),
364    ///   right_piece.into(),
365    ///   middle_piece.into(),
366    /// ]);
367    ///
368    /// let elements_intersecting_left_piece = tree.locate_in_envelope_intersecting(&left_piece);
369    /// // The left piece should not intersect the right piece!
370    /// assert_eq!(elements_intersecting_left_piece.count(), 2);
371    /// let elements_intersecting_middle = tree.locate_in_envelope_intersecting(&middle_piece);
372    /// // Only the middle piece intersects all pieces within the tree
373    /// assert_eq!(elements_intersecting_middle.count(), 3);
374    ///
375    /// let large_piece = AABB::from_corners([-100., -100.], [100., 100.]);
376    /// let elements_intersecting_large_piece = tree.locate_in_envelope_intersecting(&large_piece);
377    /// // Any element that is fully contained should also be returned:
378    /// assert_eq!(elements_intersecting_large_piece.count(), 3);
379    /// ```
380    pub fn locate_in_envelope_intersecting(
381        &self,
382        envelope: &T::Envelope,
383    ) -> LocateInEnvelopeIntersecting<T> {
384        LocateInEnvelopeIntersecting::new(
385            &self.root,
386            SelectInEnvelopeFuncIntersecting::new(envelope.clone()),
387        )
388    }
389
390    /// Mutable variant of [locate_in_envelope_intersecting](#method.locate_in_envelope_intersecting)
391    pub fn locate_in_envelope_intersecting_mut(
392        &mut self,
393        envelope: &T::Envelope,
394    ) -> LocateInEnvelopeIntersectingMut<T> {
395        LocateInEnvelopeIntersectingMut::new(
396            &mut self.root,
397            SelectInEnvelopeFuncIntersecting::new(envelope.clone()),
398        )
399    }
400
401    /// Locates elements in the r-tree defined by a selection function.
402    ///
403    /// Refer to the documentation of [`SelectionFunction`] for
404    /// more information.
405    ///
406    /// Usually, other `locate` methods should cover most common use cases. This method is only required
407    /// in more specific situations.
408    pub fn locate_with_selection_function<S: SelectionFunction<T>>(
409        &self,
410        selection_function: S,
411    ) -> SelectionIterator<T, S> {
412        SelectionIterator::new(&self.root, selection_function)
413    }
414
415    /// Mutable variant of [`locate_with_selection_function`](#method.locate_with_selection_function).
416    pub fn locate_with_selection_function_mut<S: SelectionFunction<T>>(
417        &mut self,
418        selection_function: S,
419    ) -> SelectionIteratorMut<T, S> {
420        SelectionIteratorMut::new(&mut self.root, selection_function)
421    }
422
423    /// Returns all possible intersecting objects of this and another tree.
424    ///
425    /// This will return all objects whose _envelopes_ intersect. No geometric intersection
426    /// checking is performed.
427    pub fn intersection_candidates_with_other_tree<'a, U>(
428        &'a self,
429        other: &'a RTree<U>,
430    ) -> IntersectionIterator<T, U>
431    where
432        U: RTreeObject<Envelope = T::Envelope>,
433    {
434        IntersectionIterator::new(self.root(), other.root())
435    }
436
437    /// Returns the tree's root node.
438    ///
439    /// Usually, you will not need to call this method. However, for debugging purposes or for
440    /// advanced algorithms, knowledge about the tree's internal structure may be required.
441    /// For these cases, this method serves as an entry point.
442    pub fn root(&self) -> &ParentNode<T> {
443        &self.root
444    }
445
446    pub(crate) fn root_mut(&mut self) -> &mut ParentNode<T> {
447        &mut self.root
448    }
449
450    fn new_from_bulk_loading(
451        elements: Vec<T>,
452        root_loader: impl Fn(Vec<T>) -> ParentNode<T>,
453    ) -> Self {
454        verify_parameters::<T, Params>();
455        let size = elements.len();
456        let root = if size == 0 {
457            ParentNode::new_root::<Params>()
458        } else {
459            root_loader(elements)
460        };
461        RTree {
462            root,
463            size,
464            _params: Default::default(),
465        }
466    }
467
468    /// Removes and returns a single element from the tree. The element to remove is specified
469    /// by a [`SelectionFunction`].
470    ///
471    /// See also: [`RTree::remove`], [`RTree::remove_at_point`]
472    ///
473    pub fn remove_with_selection_function<F>(&mut self, function: F) -> Option<T>
474    where
475        F: SelectionFunction<T>,
476    {
477        removal::DrainIterator::new(self, function).take(1).last()
478    }
479
480    /// Drain elements selected by a [`SelectionFunction`]. Returns an
481    /// iterator that successively removes selected elements and returns
482    /// them. This is the most generic drain API, see also:
483    /// [`RTree::drain_in_envelope_intersecting`],
484    /// [`RTree::drain_within_distance`].
485    ///
486    /// # Remarks
487    ///
488    /// This API is similar to `Vec::drain_filter`, but stopping the
489    /// iteration would stop the removal. However, the returned iterator
490    /// must be properly dropped. Leaking this iterator leads to a leak
491    /// amplification, where all the elements in the tree are leaked.
492    pub fn drain_with_selection_function<F>(&mut self, function: F) -> DrainIterator<T, F, Params>
493    where
494        F: SelectionFunction<T>,
495    {
496        removal::DrainIterator::new(self, function)
497    }
498
499    /// Drains elements intersecting the `envelope`. Similar to
500    /// `locate_in_envelope_intersecting`, except the elements are removed
501    /// and returned via an iterator.
502    pub fn drain_in_envelope_intersecting(
503        &mut self,
504        envelope: T::Envelope,
505    ) -> DrainIterator<T, SelectInEnvelopeFuncIntersecting<T>, Params> {
506        let selection_function = SelectInEnvelopeFuncIntersecting::new(envelope);
507        self.drain_with_selection_function(selection_function)
508    }
509}
510
511impl<T, Params> RTree<T, Params>
512where
513    Params: RTreeParams,
514    T: PointDistance,
515{
516    /// Returns a single object that covers a given point.
517    ///
518    /// Method [contains_point](PointDistance::contains_point)
519    /// is used to determine if a tree element contains the given point.
520    ///
521    /// If multiple elements contain the given point, any of them is returned.
522    pub fn locate_at_point(&self, point: &<T::Envelope as Envelope>::Point) -> Option<&T> {
523        self.locate_all_at_point(point).next()
524    }
525
526    /// Mutable variant of [RTree::locate_at_point].
527    pub fn locate_at_point_mut(
528        &mut self,
529        point: &<T::Envelope as Envelope>::Point,
530    ) -> Option<&mut T> {
531        self.locate_all_at_point_mut(point).next()
532    }
533
534    /// Locate all elements containing a given point.
535    ///
536    /// Method [PointDistance::contains_point] is used
537    /// to determine if a tree element contains the given point.
538    /// # Example
539    /// ```
540    /// use rstar::RTree;
541    /// use rstar::primitives::Rectangle;
542    ///
543    /// let tree = RTree::bulk_load(vec![
544    ///   Rectangle::from_corners([0.0, 0.0], [2.0, 2.0]),
545    ///   Rectangle::from_corners([1.0, 1.0], [3.0, 3.0])
546    /// ]);
547    ///
548    /// assert_eq!(tree.locate_all_at_point(&[1.5, 1.5]).count(), 2);
549    /// assert_eq!(tree.locate_all_at_point(&[0.0, 0.0]).count(), 1);
550    /// assert_eq!(tree.locate_all_at_point(&[-1., 0.0]).count(), 0);
551    /// ```
552    pub fn locate_all_at_point(
553        &self,
554        point: &<T::Envelope as Envelope>::Point,
555    ) -> LocateAllAtPoint<T> {
556        LocateAllAtPoint::new(&self.root, SelectAtPointFunction::new(point.clone()))
557    }
558
559    /// Mutable variant of [locate_all_at_point](#method.locate_all_at_point).
560    pub fn locate_all_at_point_mut(
561        &mut self,
562        point: &<T::Envelope as Envelope>::Point,
563    ) -> LocateAllAtPointMut<T> {
564        LocateAllAtPointMut::new(&mut self.root, SelectAtPointFunction::new(point.clone()))
565    }
566
567    /// Removes an element containing a given point.
568    ///
569    /// The removed element, if any, is returned. If multiple elements cover the given point,
570    /// only one of them is removed and returned.
571    ///
572    /// # Example
573    /// ```
574    /// use rstar::RTree;
575    /// use rstar::primitives::Rectangle;
576    ///
577    /// let mut tree = RTree::bulk_load(vec![
578    ///   Rectangle::from_corners([0.0, 0.0], [2.0, 2.0]),
579    ///   Rectangle::from_corners([1.0, 1.0], [3.0, 3.0])
580    /// ]);
581    ///
582    /// assert!(tree.remove_at_point(&[1.5, 1.5]).is_some());
583    /// assert!(tree.remove_at_point(&[1.5, 1.5]).is_some());
584    /// assert!(tree.remove_at_point(&[1.5, 1.5]).is_none());
585    ///```
586    pub fn remove_at_point(&mut self, point: &<T::Envelope as Envelope>::Point) -> Option<T> {
587        let removal_function = SelectAtPointFunction::new(point.clone());
588        self.remove_with_selection_function(removal_function)
589    }
590}
591
592impl<T, Params> RTree<T, Params>
593where
594    Params: RTreeParams,
595    T: RTreeObject + PartialEq,
596{
597    /// Returns `true` if a given element is equal (`==`) to an element in the
598    /// r-tree.
599    ///
600    /// This method will only work correctly if two equal elements also have the
601    /// same envelope.
602    ///
603    /// # Example
604    /// ```
605    /// use rstar::RTree;
606    ///
607    /// let mut tree = RTree::new();
608    /// assert!(!tree.contains(&[0.0, 2.0]));
609    /// tree.insert([0.0, 2.0]);
610    /// assert!(tree.contains(&[0.0, 2.0]));
611    /// ```
612    pub fn contains(&self, t: &T) -> bool {
613        self.locate_in_envelope(&t.envelope()).any(|e| e == t)
614    }
615
616    /// Removes and returns an element of the r-tree equal (`==`) to a given element.
617    ///
618    /// If multiple elements equal to the given elements are contained in the tree, only
619    /// one of them is removed and returned.
620    ///
621    /// This method will only work correctly if two equal elements also have the
622    /// same envelope.
623    ///
624    /// # Example
625    /// ```
626    /// use rstar::RTree;
627    ///
628    /// let mut tree = RTree::new();
629    /// tree.insert([0.0, 2.0]);
630    /// // The element can be inserted twice just fine
631    /// tree.insert([0.0, 2.0]);
632    /// assert!(tree.remove(&[0.0, 2.0]).is_some());
633    /// assert!(tree.remove(&[0.0, 2.0]).is_some());
634    /// assert!(tree.remove(&[0.0, 2.0]).is_none());
635    /// ```
636    pub fn remove(&mut self, t: &T) -> Option<T> {
637        let removal_function = SelectEqualsFunction::new(t);
638        self.remove_with_selection_function(removal_function)
639    }
640}
641
642impl<T, Params> RTree<T, Params>
643where
644    Params: RTreeParams,
645    T: PointDistance,
646{
647    /// Returns the nearest neighbor for a given point.
648    ///
649    /// The distance is calculated by calling
650    /// [PointDistance::distance_2]
651    ///
652    /// # Example
653    /// ```
654    /// use rstar::RTree;
655    /// let tree = RTree::bulk_load(vec![
656    ///   [0.0, 0.0],
657    ///   [0.0, 1.0],
658    /// ]);
659    /// assert_eq!(tree.nearest_neighbor(&[-1., 0.0]), Some(&[0.0, 0.0]));
660    /// assert_eq!(tree.nearest_neighbor(&[0.0, 2.0]), Some(&[0.0, 1.0]));
661    /// ```
662    pub fn nearest_neighbor(&self, query_point: &<T::Envelope as Envelope>::Point) -> Option<&T> {
663        if self.size > 0 {
664            // The single-nearest-neighbor retrieval may in rare cases return None due to
665            // rounding issues. The iterator will still work, though.
666            nearest_neighbor::nearest_neighbor(&self.root, query_point.clone())
667                .or_else(|| self.nearest_neighbor_iter(query_point).next())
668        } else {
669            None
670        }
671    }
672
673    /// Returns the nearest neighbors for a given point.
674    ///
675    /// The distance is calculated by calling
676    /// [PointDistance::distance_2]
677    ///
678    /// All returned values will have the exact same distance from the given query point.
679    /// Returns an empty `Vec` if the tree is empty.
680    ///
681    /// # Example
682    /// ```
683    /// use rstar::RTree;
684    /// let tree = RTree::bulk_load(vec![
685    ///   [0.0, 0.0],
686    ///   [0.0, 1.0],
687    ///   [1.0, 0.0],
688    /// ]);
689    /// assert_eq!(tree.nearest_neighbors(&[1.0, 1.0]), &[&[0.0, 1.0], &[1.0, 0.0]]);
690    /// assert_eq!(tree.nearest_neighbors(&[0.01, 0.01]), &[&[0.0, 0.0]]);
691    /// ```
692    pub fn nearest_neighbors(&self, query_point: &<T::Envelope as Envelope>::Point) -> Vec<&T> {
693        nearest_neighbor::nearest_neighbors(&self.root, query_point.clone())
694    }
695
696    /// Returns all elements of the tree within a certain distance.
697    ///
698    /// The elements may be returned in any order. Each returned element
699    /// will have a squared distance less or equal to the given squared distance.
700    ///
701    /// This method makes use of [PointDistance::distance_2_if_less_or_equal].
702    /// If performance is critical and the distance calculation to the object is fast,
703    /// overwriting this function may be beneficial.
704    pub fn locate_within_distance(
705        &self,
706        query_point: <T::Envelope as Envelope>::Point,
707        max_squared_radius: <<T::Envelope as Envelope>::Point as Point>::Scalar,
708    ) -> LocateWithinDistanceIterator<T> {
709        let selection_function = SelectWithinDistanceFunction::new(query_point, max_squared_radius);
710        LocateWithinDistanceIterator::new(self.root(), selection_function)
711    }
712
713    /// Drain all elements of the tree within a certain distance.
714    ///
715    /// Similar to [`RTree::locate_within_distance`], but removes and
716    /// returns the elements via an iterator.
717    pub fn drain_within_distance(
718        &mut self,
719        query_point: <T::Envelope as Envelope>::Point,
720        max_squared_radius: <<T::Envelope as Envelope>::Point as Point>::Scalar,
721    ) -> DrainIterator<T, SelectWithinDistanceFunction<T>, Params> {
722        let selection_function = SelectWithinDistanceFunction::new(query_point, max_squared_radius);
723        self.drain_with_selection_function(selection_function)
724    }
725
726    /// Returns all elements of the tree sorted by their distance to a given point.
727    ///
728    /// # Runtime
729    /// Every `next()` call runs in `O(log(n))`. Creating the iterator runs in
730    /// `O(log(n))`.
731    /// The [r-tree documentation](RTree) contains more information about
732    /// r-tree performance.
733    ///
734    /// # Example
735    /// ```
736    /// use rstar::RTree;
737    /// let tree = RTree::bulk_load(vec![
738    ///   [0.0, 0.0],
739    ///   [0.0, 1.0],
740    /// ]);
741    ///
742    /// let nearest_neighbors = tree.nearest_neighbor_iter(&[0.5, 0.0]).collect::<Vec<_>>();
743    /// assert_eq!(nearest_neighbors, vec![&[0.0, 0.0], &[0.0, 1.0]]);
744    /// ```
745    pub fn nearest_neighbor_iter(
746        &self,
747        query_point: &<T::Envelope as Envelope>::Point,
748    ) -> NearestNeighborIterator<T> {
749        nearest_neighbor::NearestNeighborIterator::new(&self.root, query_point.clone())
750    }
751
752    /// Returns `(element, distance^2)` tuples of the tree sorted by their distance to a given point.
753    ///
754    /// The distance is calculated by calling
755    /// [PointDistance::distance_2].
756    #[deprecated(note = "Please use nearest_neighbor_iter_with_distance_2 instead")]
757    pub fn nearest_neighbor_iter_with_distance(
758        &self,
759        query_point: &<T::Envelope as Envelope>::Point,
760    ) -> NearestNeighborDistance2Iterator<T> {
761        nearest_neighbor::NearestNeighborDistance2Iterator::new(&self.root, query_point.clone())
762    }
763
764    /// Returns `(element, distance^2)` tuples of the tree sorted by their distance to a given point.
765    ///
766    /// The distance is calculated by calling
767    /// [PointDistance::distance_2].
768    pub fn nearest_neighbor_iter_with_distance_2(
769        &self,
770        query_point: &<T::Envelope as Envelope>::Point,
771    ) -> NearestNeighborDistance2Iterator<T> {
772        nearest_neighbor::NearestNeighborDistance2Iterator::new(&self.root, query_point.clone())
773    }
774
775    /// Removes the nearest neighbor for a given point and returns it.
776    ///
777    /// The distance is calculated by calling
778    /// [PointDistance::distance_2].
779    ///
780    /// # Example
781    /// ```
782    /// use rstar::RTree;
783    /// let mut tree = RTree::bulk_load(vec![
784    ///   [0.0, 0.0],
785    ///   [0.0, 1.0],
786    /// ]);
787    /// assert_eq!(tree.pop_nearest_neighbor(&[0.0, 0.0]), Some([0.0, 0.0]));
788    /// assert_eq!(tree.pop_nearest_neighbor(&[0.0, 0.0]), Some([0.0, 1.0]));
789    /// assert_eq!(tree.pop_nearest_neighbor(&[0.0, 0.0]), None);
790    /// ```
791    pub fn pop_nearest_neighbor(
792        &mut self,
793        query_point: &<T::Envelope as Envelope>::Point,
794    ) -> Option<T> {
795        if let Some(neighbor) = self.nearest_neighbor(query_point) {
796            let removal_function = SelectByAddressFunction::new(neighbor.envelope(), neighbor);
797            self.remove_with_selection_function(removal_function)
798        } else {
799            None
800        }
801    }
802}
803
804impl<T, Params> RTree<T, Params>
805where
806    T: RTreeObject,
807    Params: RTreeParams,
808{
809    /// Inserts a new element into the r-tree.
810    ///
811    /// If the element is already present in the tree, it will now be present twice.
812    ///
813    /// # Runtime
814    /// This method runs in `O(log(n))`.
815    /// The [r-tree documentation](RTree) contains more information about
816    /// r-tree performance.
817    pub fn insert(&mut self, t: T) {
818        Params::DefaultInsertionStrategy::insert(self, t);
819        self.size += 1;
820    }
821}
822
823impl<T, Params> RTree<T, Params>
824where
825    T: RTreeObject,
826    <T::Envelope as Envelope>::Point: Point,
827    Params: RTreeParams,
828{
829}
830
831impl<'a, T, Params> IntoIterator for &'a RTree<T, Params>
832where
833    T: RTreeObject,
834    Params: RTreeParams,
835{
836    type IntoIter = RTreeIterator<'a, T>;
837    type Item = &'a T;
838
839    fn into_iter(self) -> Self::IntoIter {
840        self.iter()
841    }
842}
843
844impl<'a, T, Params> IntoIterator for &'a mut RTree<T, Params>
845where
846    T: RTreeObject,
847    Params: RTreeParams,
848{
849    type IntoIter = RTreeIteratorMut<'a, T>;
850    type Item = &'a mut T;
851
852    fn into_iter(self) -> Self::IntoIter {
853        self.iter_mut()
854    }
855}
856
857#[cfg(test)]
858mod test {
859    use super::RTree;
860    use crate::algorithm::rstar::RStarInsertionStrategy;
861    use crate::params::RTreeParams;
862    use crate::test_utilities::{create_random_points, SEED_1};
863    use crate::DefaultParams;
864
865    struct TestParams;
866    impl RTreeParams for TestParams {
867        const MIN_SIZE: usize = 10;
868        const MAX_SIZE: usize = 20;
869        const REINSERTION_COUNT: usize = 1;
870        type DefaultInsertionStrategy = RStarInsertionStrategy;
871    }
872
873    #[test]
874    fn test_remove_capacity() {
875        pub struct WeirdParams;
876
877        impl RTreeParams for WeirdParams {
878            const MIN_SIZE: usize = 1;
879            const MAX_SIZE: usize = 10;
880            const REINSERTION_COUNT: usize = 1;
881            type DefaultInsertionStrategy = RStarInsertionStrategy;
882        }
883
884        let mut items: Vec<[f32; 2]> = Vec::new();
885        for i in 0..2 {
886            items.push([i as f32, i as f32]);
887        }
888        let mut tree: RTree<_, WeirdParams> = RTree::bulk_load_with_params(items);
889        assert_eq!(tree.remove(&[1.0, 1.0]).unwrap(), [1.0, 1.0]);
890    }
891
892    #[test]
893    fn test_create_rtree_with_parameters() {
894        let tree: RTree<[f32; 2], TestParams> = RTree::new_with_params();
895        assert_eq!(tree.size(), 0);
896    }
897
898    #[test]
899    fn test_insert_single() {
900        let mut tree: RTree<_> = RTree::new();
901        tree.insert([0.02f32, 0.4f32]);
902        assert_eq!(tree.size(), 1);
903        assert!(tree.contains(&[0.02, 0.4]));
904        assert!(!tree.contains(&[0.3, 0.2]));
905    }
906
907    #[test]
908    fn test_insert_many() {
909        const NUM_POINTS: usize = 1000;
910        let points = create_random_points(NUM_POINTS, SEED_1);
911        let mut tree = RTree::new();
912        for p in &points {
913            tree.insert(*p);
914            tree.root.sanity_check::<DefaultParams>(true);
915        }
916        assert_eq!(tree.size(), NUM_POINTS);
917        for p in &points {
918            assert!(tree.contains(p));
919        }
920    }
921
922    #[test]
923    fn test_fmt_debug() {
924        let tree = RTree::bulk_load(vec![[0, 1], [0, 1]]);
925        let debug: String = format!("{:?}", tree);
926        assert_eq!(debug, "RTree { size: 2, items: {[0, 1], [0, 1]} }");
927    }
928
929    #[test]
930    fn test_default() {
931        let tree: RTree<[f32; 2]> = Default::default();
932        assert_eq!(tree.size(), 0);
933    }
934
935    #[cfg(feature = "serde")]
936    #[test]
937    fn test_serialization() {
938        use crate::test_utilities::create_random_integers;
939
940        use serde_json;
941        const SIZE: usize = 20;
942        let points = create_random_integers::<[i32; 2]>(SIZE, SEED_1);
943        let tree = RTree::bulk_load(points.clone());
944        let json = serde_json::to_string(&tree).expect("Serializing tree failed");
945        let parsed: RTree<[i32; 2]> =
946            serde_json::from_str(&json).expect("Deserializing tree failed");
947        assert_eq!(parsed.size(), SIZE);
948        for point in &points {
949            assert!(parsed.contains(point));
950        }
951    }
952
953    #[test]
954    fn test_bulk_load_crash() {
955        let bulk_nodes = vec![
956            [570.0, 1080.0, 89.0],
957            [30.0, 1080.0, 627.0],
958            [1916.0, 1080.0, 68.0],
959            [274.0, 1080.0, 790.0],
960            [476.0, 1080.0, 895.0],
961            [1557.0, 1080.0, 250.0],
962            [1546.0, 1080.0, 883.0],
963            [1512.0, 1080.0, 610.0],
964            [1729.0, 1080.0, 358.0],
965            [1841.0, 1080.0, 434.0],
966            [1752.0, 1080.0, 696.0],
967            [1674.0, 1080.0, 705.0],
968            [136.0, 1080.0, 22.0],
969            [1593.0, 1080.0, 71.0],
970            [586.0, 1080.0, 272.0],
971            [348.0, 1080.0, 373.0],
972            [502.0, 1080.0, 2.0],
973            [1488.0, 1080.0, 1072.0],
974            [31.0, 1080.0, 526.0],
975            [1695.0, 1080.0, 559.0],
976            [1663.0, 1080.0, 298.0],
977            [316.0, 1080.0, 417.0],
978            [1348.0, 1080.0, 731.0],
979            [784.0, 1080.0, 126.0],
980            [225.0, 1080.0, 847.0],
981            [79.0, 1080.0, 819.0],
982            [320.0, 1080.0, 504.0],
983            [1714.0, 1080.0, 1026.0],
984            [264.0, 1080.0, 229.0],
985            [108.0, 1080.0, 158.0],
986            [1665.0, 1080.0, 604.0],
987            [496.0, 1080.0, 231.0],
988            [1813.0, 1080.0, 865.0],
989            [1200.0, 1080.0, 326.0],
990            [1661.0, 1080.0, 818.0],
991            [135.0, 1080.0, 229.0],
992            [424.0, 1080.0, 1016.0],
993            [1708.0, 1080.0, 791.0],
994            [1626.0, 1080.0, 682.0],
995            [442.0, 1080.0, 895.0],
996        ];
997
998        let nodes = vec![
999            [1916.0, 1060.0, 68.0],
1000            [1664.0, 1060.0, 298.0],
1001            [1594.0, 1060.0, 71.0],
1002            [225.0, 1060.0, 846.0],
1003            [1841.0, 1060.0, 434.0],
1004            [502.0, 1060.0, 2.0],
1005            [1625.5852, 1060.0122, 682.0],
1006            [1348.5273, 1060.0029, 731.08124],
1007            [316.36127, 1060.0298, 418.24515],
1008            [1729.3253, 1060.0023, 358.50134],
1009        ];
1010        let mut tree = RTree::bulk_load(bulk_nodes);
1011        for node in nodes {
1012            // Bulk loading will create nodes larger than Params::MAX_SIZE,
1013            // which is intentional and not harmful.
1014            tree.insert(node);
1015            tree.root().sanity_check::<DefaultParams>(false);
1016        }
1017    }
1018}