Skip to main content

situs/
lib.rs

1// src/lib.rs
2
3//! Spatial indexes over `f64` boxes, with no false negatives.
4//!
5//! `situs` answers two questions of a set of stored boxes: **which of them
6//! might meet a query box**, and **which might lie nearest to a query point**. It
7//! holds `(`[`Rect`]`, u32)` entries in an R-tree, either the static,
8//! bulk-loaded [`Index`], built once and queried many times, or the
9//! [`DynamicIndex`], which accepts insertions and removals as the set
10//! changes. A box query returns every entry whose box meets the window, and
11//! a nearest-neighbor query returns candidates ordered by certified bounds.
12//! The index operates as a **candidate filter** rather than a decision
13//! procedure. The caller decides exactly among the candidates, and `situs`
14//! decides nothing geometric itself.
15//!
16//! The crate is `no_std` (with `alloc`), has no dependencies by default,
17//! uses no `unsafe` code, and does not panic on any input it accepts.
18//!
19//! # The correctness argument
20//!
21//! The index carries one obligation, **no false negatives**: every entry whose
22//! box meets the query box is returned. An extra entry would cost time
23//! rather than correctness, since the caller decides exactly afterward. A
24//! query in fact returns *exactly* the entries whose boxes meet the window
25//! (see [`Index::query`]), because every leaf entry's own box is tested
26//! before it is reported.
27//!
28//! No false negatives holds if and only if three conditions hold:
29//!
30//! 1. **Every entry's box contains its geometry.** This condition is the
31//!    caller's obligation, met by taking the box as the minimum and maximum
32//!    of stored coordinates, which is exact and requires no arithmetic.
33//! 2. **Every node's box contains all of its children's boxes.** A node's box is
34//!    the [`Rect::union`] of its children's boxes, a minimum and maximum of
35//!    stored values and therefore exact. By induction, a box that meets an
36//!    entry meets every ancestor of that entry, so the search never prunes
37//!    an ancestor of a match.
38//! 3. **The overlap test is the exact closed-interval test on stored values**,
39//!    `a.min_x <= b.max_x && b.min_x <= a.max_x` and the same on `y`
40//!    ([`Rect::intersects`]). The intervals are closed, so boxes that touch
41//!    along an edge or at a corner meet, which is what a caller deciding
42//!    exactly afterward requires. A contact *is* an intersection.
43//!
44//! **Every comparison in the crate is made on stored `f64` values, on
45//! certified bounds whose error can only add candidates, or, under the
46//! `exact-nearest` feature, on exact predicates from `arithmetica`. No
47//! distance is returned as though it were exact.** The bounds, the searches
48//! and the join remain in `situs`, and the one exact operation the feature
49//! requires, comparing the distances from a query point to two stored
50//! points, belongs to `arithmetica`.
51//!
52//! **The bulk loader is the one place where arithmetic enters.** It sorts
53//! entries by the centers of their boxes, computed in floating point, and
54//! those keys determine the *shape* of the tree rather than its *contents*. A
55//! poor key produces a slower tree with the same answers. The tests attack
56//! each of the three conditions separately, and a mutation test breaks each
57//! condition in turn and fails a named test.
58//!
59//! # Bulk loading
60//!
61//! [`Index::bulk_load`] packs the entries by **Sort-Tile-Recursive** (STR)
62//! packing (Leutenegger, Lopez & Edgington, "STR: A Simple and Efficient
63//! Algorithm for R-Tree Packing", ICDE 1997). With `n` entries and node
64//! capacity `M` ([`Index::NODE_CAPACITY`]), the method has four stages:
65//!
66//! - let `P = ⌈n / M⌉` be the number of leaves and `S = ⌈√P⌉`;
67//! - sort the entries by the `x` of their box centers and cut them into `S`
68//!   vertical slices of `S·M` consecutive entries, the last slice shorter;
69//! - sort each slice by the `y` of the centers and pack consecutive runs of
70//!   `M` into leaves;
71//! - treat the leaf boxes as entries and repeat, level by level, until one
72//!   node remains.
73//!
74//! A slice holds a multiple of `M` entries, so the runs of `M` over the
75//! reordered array coincide with the per-slice runs, and a level is simply
76//! the array cut into chunks of `M`, the last chunk possibly shorter.
77//!
78//! Hilbert-curve packing (Kamel & Faloutsos, "On Packing R-trees", CIKM
79//! 1993) orders entries along a space-filling curve instead and gives
80//! somewhat better query performance on some distributions. It remains the
81//! documented alternative rather than a built one. STR is simpler to state
82//! and to verify, its layout is a plain function of two sorts, and no
83//! measured workload has required more.
84//!
85//! **The layout is a deterministic function of the input sequence.** Each sort
86//! orders entries by their centers in `f64::total_cmp` order, then by entry
87//! id, then by their position before the sort, which is the order a stable
88//! sort by center and id would produce. A center is `min · 0.5 + max ·
89//! 0.5`, which cannot overflow for finite bounds, since each product is at
90//! most half its bound and their sum at most the larger bound in magnitude.
91//! The rounding in that sum, and the loss of precision when the bounds are
92//! subnormal, affect only the order.
93//!
94//! # Storage and search
95//!
96//! The nodes live in one `Vec` in level order, root first, and the entries
97//! live in another, reordered into leaf order. Each node holds its box and
98//! the index range of its children, nodes for an internal node and entries
99//! for a leaf.
100//!
101//! **The containment shortcut** reports a whole subtree once the query window
102//! *contains* its box. Every entry's box is contained in its leaf's box, and
103//! every node's box in its parent's (condition 2). Containment is
104//! transitive, and a box contained in the window meets it because the test
105//! is closed. The search therefore reports that subtree without testing
106//! anything below it. The containment test ([`Rect::contains_rect`]) is four
107//! exact comparisons of stored values, so the shortcut adds no arithmetic
108//! and can neither add an entry nor lose one.
109//!
110//! The shortcut **walks** the subtree rather than taking it as one range of the
111//! entry array. STR reorders each level after its nodes are cut, so the
112//! nodes of a level are not in child-range order, and a subtree's entries
113//! are in general not contiguous. The range from its first leaf's first
114//! entry to its last leaf's end can hold entries of other subtrees and miss
115//! some of its own.
116//!
117//! **The search is iterative and runs on a fixed stack.** It pops a node, and
118//! if the node is internal it pushes all of its children, in reverse, so
119//! that they are visited in index order. At any moment the stack holds the
120//! siblings not yet visited of each node on the current root-to-node path,
121//! at most `M − 1` per level, plus the children just pushed. With `depth`
122//! node levels the stack holds at most `(M − 1) · (depth − 1) + 1` indices,
123//! below `(M − 1) · depth + 1`. The shortcut's subtree walk pushes onto the
124//! same stack with the same discipline, starting from the node just popped,
125//! so it is one more descent of the same kind and the bound holds through
126//! it.
127//!
128//! The depth is bounded as well. STR packing makes `⌈n / M⌉` leaves, and
129//! each level above divides the count by `M = 16 = 2⁴`, rounding up, so with
130//! `n ≤ usize::MAX` there are at most `⌈usize::BITS / 4⌉ + 1` levels (17 on
131//! a 64-bit target). The stack is therefore a fixed array of
132//! `(M − 1) · 17 + 1 = 256` indices on a 64-bit target (2 KiB), held on the
133//! call stack. No query allocates, and the search does not recurse. Were the
134//! bound ever exceeded, the search would panic rather than drop a node,
135//! since a dropped node would remove its whole subtree from the answer.
136//!
137//! **The visit order is the order of this depth-first walk.** The shortcut emits
138//! a subtree in the order the plain search would visit it, because every
139//! node and entry below a contained node meets the window and the walk is
140//! the same walk. [`Index::try_query`], which can stop early, therefore
141//! visits a prefix of [`Index::query`]'s sequence.
142//!
143//! # Joins
144//!
145//! [`Index::join`] reports every pair of entries, one from each of two
146//! indexes, whose boxes meet, and [`Index::self_join`] reports every pair of
147//! distinct entries of one index whose boxes meet, once each. The traversal
148//! is the synchronized descent of Brinkhoff, Kriegel & Seeger ("Efficient
149//! Processing of Spatial Joins Using R-trees", SIGMOD 1993). It walks pairs
150//! of nodes, one from each tree, and descends a pair only when the two
151//! boxes meet. The correctness argument is the query's, applied pairwise:
152//!
153//! - **No pair is lost:** If entry `a` (below node `N`) and entry `b` (below
154//!   node `P`) have boxes that meet, they share a point. `N`'s box contains
155//!   `a`'s and `P`'s contains `b`'s (condition 2), so both node boxes
156//!   contain that point and meet. By induction every ancestor pair of
157//!   `(a, b)` is descended, and the pair is reached.
158//! - **No pair is added:** At two leaves, each entry pair is tested with the
159//!   closed overlap test (condition 3) before it is reported.
160//!
161//! A leaf paired with an internal node is paired with each of that node's
162//! children, which is how two trees of different heights meet. A join's
163//! output can be quadratic in the sizes of the indexes, so it is never
164//! collected. Each pair goes to the caller's visitor as it is found, and
165//! only the pending node pairs are stored.
166//!
167//! # Nearest neighbors
168//!
169//! [`Index::nearest_candidates`] and [`Index::browse`] find the entries
170//! nearest to a query point without computing any exact distance. For each
171//! box the crate computes two `f64` values that bracket the exact squared
172//! distance, `lower_sq ≤ d² ≤ upper_sq`, certified by a rounding-error
173//! argument (see the `nearest` module documentation). A best-first search
174//! over the lower bounds (Hjaltason & Samet, "Distance Browsing in Spatial
175//! Databases", ACM TODS 24(2), 1999) then returns every entry whose interval
176//! could place it among the k nearest. The result always includes the true
177//! k nearest and every tie, and it never chooses between candidates whose
178//! intervals overlap. The bounds reach the caller as bounds, and no computed
179//! distance is presented as the exact one.
180//!
181//! Under the opt-in `exact-nearest` feature, `Index::nearest_exact` and
182//! `DynamicIndex::nearest_exact` rank those candidates exactly, with
183//! `arithmetica::compare_distance` on the nearest point of each box, and
184//! return the exact k nearest plus every entry exactly tied with the k-th.
185//! The default build has no dependencies, and the feature adds
186//! `arithmetica`, which is also `no_std`.
187//!
188//! # The dynamic tree
189//!
190//! [`DynamicIndex`] is an R\*-tree (Beckmann, Kriegel, Schneider & Seeger,
191//! SIGMOD 1990) that accepts insertions and exact removals, alongside the
192//! read-only [`Index`]. The R\* heuristics are computed in `f64` and
193//! determine only the tree's shape. Every node box is maintained as the
194//! exact union of its children's boxes, so the argument above applies
195//! unchanged, and [`DynamicIndex::bounds`] is always exact and tight. The
196//! two types remain separate because their contracts differ. The static
197//! index is compact and the fastest to query, and the dynamic tree can
198//! change. Removal matches a box and an id exactly and recomputes every box
199//! on its path, so the bounds shrink as entries leave.
200//! [`DynamicIndex::bulk_load`] builds an initial tree by the static index's
201//! packing, and nearest-neighbor candidates and browsing run on the dynamic
202//! tree by the same search and the same argument as on the static index.
203//!
204//! # Not built
205//!
206//! - [`Index::join`], [`Index::self_join`], the early-exit
207//!   [`Index::try_query`] and the containment shortcut have no dynamic
208//!   counterparts. [`DynamicIndex::query`] tests every entry it reaches.
209//! - Any distance presented as exact. Nearest-neighbor results carry
210//!   certified bounds rather than a distance.
211//! - An encoding of an index. An index is rebuilt from its entries, which
212//!   the caller already holds.
213
214#![no_std]
215#![cfg_attr(docsrs, feature(doc_cfg))]
216#![forbid(unsafe_code)]
217#![deny(clippy::unwrap_used)]
218#![warn(missing_docs)]
219
220extern crate alloc;
221
222#[cfg(test)]
223extern crate std;
224
225mod dynamic;
226mod nearest;
227mod static_index;
228
229pub use dynamic::DynamicIndex;
230pub use nearest::{Browse, Neighbor, QueryError};
231pub use static_index::Index;
232
233// The README's examples run as doctests, so the published README cannot
234// drift from the API. Compiled only by `cargo test --doc`.
235#[cfg(doctest)]
236#[doc = include_str!("../README.md")]
237struct ReadmeDoctests;
238
239// ===========================================================================
240// Rect
241// ===========================================================================
242
243/// An axis-aligned box with closed intervals on both axes.
244///
245/// # Invariants
246///
247/// - All four bounds are finite.
248/// - `min_x <= max_x` and `min_y <= max_y`.
249///
250/// A box of zero width, zero height, or both (a segment, or a point) is
251/// valid: it is a legitimate entry and a legitimate query. Only non-finite
252/// and inverted bounds are refused, by [`Rect::new`], so a `Rect` that
253/// exists satisfies the invariants.
254///
255/// The rule is four finite bounds, not inverted, and nothing more. A crate
256/// whose own box type has the same validity rules converts to and from
257/// `Rect` without a failure path, because each side accepts every value the
258/// other can hold.
259#[derive(Clone, Copy, Debug, PartialEq)]
260pub struct Rect {
261    min_x: f64,
262    min_y: f64,
263    max_x: f64,
264    max_y: f64,
265}
266
267/// Why [`Rect::new`] refused its bounds.
268///
269/// Non-exhaustive: a match on it needs a wildcard arm, so that a later
270/// variant is not a breaking change.
271#[derive(Clone, Copy, Debug, PartialEq, Eq)]
272#[non_exhaustive]
273pub enum RectError {
274    /// A bound is NaN or infinite. Such a box has no extent to test, and a
275    /// NaN bound would make every comparison false, so it is refused rather
276    /// than stored.
277    NonFinite,
278    /// `min > max` on some axis. A zero-extent box (`min == max`) is valid;
279    /// an inverted one would meet nothing and be silently useless.
280    Inverted,
281}
282
283impl core::fmt::Display for RectError {
284    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
285        match self {
286            Self::NonFinite => f.write_str("rect bound is NaN or infinite"),
287            Self::Inverted => f.write_str("rect min exceeds max on an axis"),
288        }
289    }
290}
291
292impl core::error::Error for RectError {}
293
294impl Rect {
295    /// Builds a box from its bounds.
296    ///
297    /// Non-finiteness is checked before inversion, because a NaN makes the
298    /// inversion comparison false and would otherwise be reported as a
299    /// valid box.
300    ///
301    /// # Errors
302    ///
303    /// [`RectError::NonFinite`] if any bound is NaN or infinite;
304    /// [`RectError::Inverted`] if `min_x > max_x` or `min_y > max_y`.
305    pub fn new(min_x: f64, min_y: f64, max_x: f64, max_y: f64) -> Result<Rect, RectError> {
306        if !(min_x.is_finite() && min_y.is_finite() && max_x.is_finite() && max_y.is_finite()) {
307            return Err(RectError::NonFinite);
308        }
309        if min_x > max_x || min_y > max_y {
310            return Err(RectError::Inverted);
311        }
312        Ok(Rect {
313            min_x,
314            min_y,
315            max_x,
316            max_y,
317        })
318    }
319
320    /// The lower `x` bound.
321    pub fn min_x(&self) -> f64 {
322        self.min_x
323    }
324
325    /// The lower `y` bound.
326    pub fn min_y(&self) -> f64 {
327        self.min_y
328    }
329
330    /// The upper `x` bound.
331    pub fn max_x(&self) -> f64 {
332        self.max_x
333    }
334
335    /// The upper `y` bound.
336    pub fn max_y(&self) -> f64 {
337        self.max_y
338    }
339
340    /// Do the two boxes share at least one point?
341    ///
342    /// The intervals are **closed**, so boxes that touch along an edge or at a
343    /// corner intersect. The test is four exact comparisons of stored values
344    /// and involves no arithmetic. It is condition 3 of the crate's
345    /// correctness argument.
346    pub fn intersects(&self, other: &Rect) -> bool {
347        self.min_x <= other.max_x
348            && other.min_x <= self.max_x
349            && self.min_y <= other.max_y
350            && other.min_y <= self.max_y
351    }
352
353    /// Is the point inside the box or on its boundary?
354    ///
355    /// The box is **closed**, as in [`Self::intersects`]. A NaN coordinate gives
356    /// `false`, because every comparison with NaN is false, and an infinite
357    /// coordinate lies outside every finite box.
358    pub fn contains_point(&self, x: f64, y: f64) -> bool {
359        x >= self.min_x && x <= self.max_x && y >= self.min_y && y <= self.max_y
360    }
361
362    /// The smallest box containing both.
363    ///
364    /// Each bound is one of the two inputs' bounds, chosen by exact
365    /// comparison, so the result is exact and contains both operands, the
366    /// property that establishes condition 2 of the correctness argument for
367    /// node boxes. On a tie (`-0.0` against `0.0`, which compare equal)
368    /// `self`'s bound is kept, so the operand order determines the result's
369    /// bit patterns.
370    #[must_use]
371    pub fn union(&self, other: &Rect) -> Rect {
372        Rect {
373            min_x: if other.min_x < self.min_x {
374                other.min_x
375            } else {
376                self.min_x
377            },
378            min_y: if other.min_y < self.min_y {
379                other.min_y
380            } else {
381                self.min_y
382            },
383            max_x: if other.max_x > self.max_x {
384                other.max_x
385            } else {
386                self.max_x
387            },
388            max_y: if other.max_y > self.max_y {
389                other.max_y
390            } else {
391                self.max_y
392            },
393        }
394    }
395
396    /// Is `other` entirely inside this box, boundary included?
397    ///
398    /// The test is **closed**, so a box that shares an edge with this one is
399    /// contained. It is exact.
400    pub fn contains_rect(&self, other: &Rect) -> bool {
401        other.min_x >= self.min_x
402            && other.max_x <= self.max_x
403            && other.min_y >= self.min_y
404            && other.max_y <= self.max_y
405    }
406
407    /// The center of the box, as a sort key only.
408    ///
409    /// The center is `min · 0.5 + max · 0.5`, which cannot overflow for finite
410    /// bounds. It is rounded, and it loses precision for subnormal bounds.
411    /// Neither affects an answer, because a center determines where an entry
412    /// sits in the tree rather than whether a query returns it.
413    pub(crate) fn center(&self) -> (f64, f64) {
414        (
415            self.min_x * 0.5 + self.max_x * 0.5,
416            self.min_y * 0.5 + self.max_y * 0.5,
417        )
418    }
419}
420
421#[cfg(test)]
422mod tests;