{ } JustinGeoSci

The guarantee

Why situs never omits an answer: the one obligation it carries, the three conditions that establish it, the certified bounds behind nearest-neighbor search, and the places where floating-point arithmetic enters without touching the answer.

No false negatives

situs operates as a candidate filter rather than a decision procedure. It answers two questions of a set of stored boxes: which of them might meet a query box, and which might lie nearest to a query point. The caller then decides exactly among the candidates, and situs decides nothing geometric itself.

The index carries one obligation, no false negatives: every entry whose box meets the query box is returned. An extra entry would cost time rather than correctness, since the caller decides exactly afterward. A missing entry is the one failure a later exact test cannot repair, because the caller never sees it.

A box query in fact returns exactly the entries whose boxes meet the window, no more and no fewer, because every leaf entry’s own box is tested before it is reported. The looser obligation matters for nearest-neighbor search, where the result can hold extra candidates whose distances the bounds cannot separate (see Certified distance bounds).

use situs::{Index, Rect};

let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let index = Index::bulk_load(vec![
    (r(0.0, 0.0, 1.0, 1.0), 1), // meets the window at a corner
    (r(2.0, 0.0, 3.0, 1.0), 2), // meets it along an edge
    (r(2.5, 2.5, 3.0, 3.0), 3), // inside it
    (r(5.0, 5.0, 6.0, 6.0), 4), // apart from it
]);

let mut hits = Vec::new();
index.query(&r(1.0, 1.0, 4.0, 4.0), |id| hits.push(id));
hits.sort_unstable(); // the visit order carries no meaning
assert_eq!(hits, [1, 2, 3]); // exactly the entries that meet the window

The crate is no_std (with alloc), has no dependencies by default, uses no unsafe code, and does not panic on any input it accepts.

The three conditions

No false negatives holds if and only if three conditions hold:

  1. Every entry’s box contains its geometry. This condition is the caller’s obligation. It is met by taking the box as the minimum and maximum of the stored coordinates, which is exact and requires no arithmetic.
  2. Every node’s box contains all of its children’s boxes. A node’s box is the Rect::union of its children’s boxes, a minimum and maximum of stored values and therefore exact.
  3. The overlap test is the exact closed-interval test on stored values, a.min_x <= b.max_x && b.min_x <= a.max_x and the same on y (Rect::intersects).

Together they suffice by induction. If a query box meets an entry, it meets that entry’s box (condition 1), and by condition 2 it meets every ancestor’s box, so the search never prunes an ancestor of a match. Condition 3 makes every one of those tests exact, so none of them can fail on a box the window truly meets.

The intervals are closed, so boxes that touch along an edge or at a corner meet. That is what a caller deciding exactly afterward requires: a contact is an intersection, and a filter that dropped touching boxes would lose every answer that rests on a shared boundary point.

The same argument governs every search in the crate. The containment shortcut on the static index reports a whole subtree once the window contains its box, which follows from condition 2 and the closed test. A join applies the argument pairwise: two entries whose boxes meet share a point, so every pair of their ancestors meets and is descended (see Joins).

Certified distance bounds

Nearest-neighbor search ranks entries by distance, which cannot be computed exactly in f64. situs holds no exact distance arithmetic, so for a query point and each box it computes two f64 values, L and U, that bracket the exact squared Euclidean distance d² from the point to the box, taken as a real number. The bounds are certified: L ≤ d² ≤ U holds for every finite query point and every valid Rect.

The point of a box nearest to the query point is the query clamped to the box, a selection among input values decided by exact comparisons. Per axis the exact distance dx is x0 − x left of the box, x − x1 right of it, and 0 otherwise, and dy likewise. The computation takes a = fl(dx) and b = fl(dy), one rounded subtraction each (or exactly 0), with fl the IEEE 754 round-to-nearest of each operation, and then

Computed sum\hat s = \operatorname{fl}\big(\operatorname{fl}(a \cdot a) + \operatorname{fl}(b \cdot b)\big)

The bounds follow from ŝ in three cases:

Case Lower bound L Upper bound U
ŝ < T 0 U_SMALL
ŝ infinite fl(MAX · K_LO) +∞
otherwise fl(ŝ · K_LO) fl(ŝ · K_HI)

Here T = 2−1020, U_SMALL = 2−1019, K_LO = 1 − 2−50 and K_HI = 1 + 2−50 (both factors exactly representable), and MAX is the largest finite f64.

Why L ≤ d² ≤ U. With unit roundoff u = 2−53, the subtraction, the squaring and the addition each contribute a relative error of at most u, and a square that lands among the subnormals contributes an absolute error of at most 2−1075 instead. Together they place ŝ within a factor of (1 ± u)4 of d², plus an absolute term of at most 2−1073. The proof then turns on the constants:

  • The threshold T makes the absolute term negligible. At or above 2−1020 it is at most u·ŝ, so the whole error is relative, at most about 5u in each direction.
  • The factors K_LO and K_HI move ŝ by 2−50 = 8u, which covers that error with margin even after the multiplication itself rounds: fl(ŝ · K_LO) < d² and fl(ŝ · K_HI) > d². The margin is wide enough that no final directed-rounding step is needed.
  • Below T, L = 0 is always valid, and the exact value is below 2T, so the constant U_SMALL = 2T bounds it from above. The constant is required rather than a convenience: ŝ can be 0 while d² > 0 (a square that underflows), and fl(ŝ · K_HI) would then be 0.
  • On overflow, ŝ = +∞ only if d² is at least about 21024, above fl(MAX · K_LO), and U = +∞ bounds anything. Every operand is non-negative, so no subtraction of infinities can produce a NaN.

The lower bound is also monotone in the box: if one box contains another, its L is no larger, because every step of the computation is monotone non-decreasing. The search rests on this property. A node’s box contains every descendant’s box, so a best-first search over L can stop without descending further; a non-monotone step would break that stopping rule and produce a false negative. The full proof, item by item, is in src/nearest/bounds.rs.

use situs::{Index, Rect};

let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let index = Index::bulk_load(vec![(r(3.0, 4.0, 5.0, 6.0), 1), (r(-1.0, -1.0, 1.0, 1.0), 2)]);
let near = index.nearest_candidates(0.0, 0.0, 2).unwrap();

// The origin lies inside entry 2: d² = 0, and the upper bound is
// still positive, because it bounds the distance rather than equals it.
assert_eq!(near[0].id, 2);
assert_eq!(near[0].lower_sq, 0.0);
assert!(near[0].upper_sq > 0.0);

// The nearest point of entry 1 is (3, 4): d² = 25, bracketed strictly.
assert_eq!(near[1].id, 1);
assert!(near[1].lower_sq < 25.0 && 25.0 < near[1].upper_sq);

No distance is presented as exact. Nearest-neighbor results carry their bounds rather than a distance, and the candidate sets are stated in terms of the bounds, so the error of a bound can only add a candidate and never remove one. Two entries whose intervals overlap are both returned, unranked. Under the opt-in exact-nearest feature, nearest_exact ranks those candidates exactly with arithmetica’s compare_distance, applied to the nearest point of each box, and returns the exact k nearest plus every entry exactly tied with the k-th.

Where arithmetic enters

Apart from the certified bounds, floating-point arithmetic enters in two places, and both determine the shape of the tree rather than its contents. A poor value produces a slower tree with the same answers.

  • The bulk loader’s sort keys. STR packing sorts entries by the centers of their boxes, computed as min · 0.5 + max · 0.5. That sum cannot overflow for finite bounds, since each product is at most half its bound. Its rounding, and the loss of precision when the bounds are subnormal, affect only the order of the entries.
  • The R* heuristics. The dynamic tree chooses where to insert and how to split by area, margin, overlap and center distance, all computed in f64. Every heuristic comparison runs through one total order that places NaN past every number, so a degenerate value, such as an area that overflows to infinity, can only select a worse shape.

Neither can change what a query returns, because no computed value is ever stored as a box. Every node box, in both trees, is the exact union of its children’s boxes, recomputed by exact min and max at every structural change, so the three conditions hold whatever shape the arithmetic selects.

Both trees are deterministic. The static layout is a deterministic function of the input sequence: each sort orders entries by center in f64::total_cmp order, then by id, then by position before the sort. For the dynamic tree, the same operations on the same starting tree produce the same internal state, bit for bit, because node slots are reused in last-in, first-out order and every heuristic tie breaks by a fixed rule. Visit orders are deterministic as a result, though they carry no meaning.

use situs::{Index, Rect};

let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let entries: Vec<(Rect, u32)> = (0..100u32)
    .map(|i| {
        let (x, y) = (f64::from(i % 10), f64::from(i / 10));
        (r(x, y, x + 1.5, y + 1.5), i)
    })
    .collect();

// The same entries in the same order give the same tree, and so the
// same visit order.
let (a, b) = (Index::bulk_load(entries.clone()), Index::bulk_load(entries));
let (mut ha, mut hb) = (Vec::new(), Vec::new());
a.query(&r(2.0, 2.0, 6.0, 6.0), |id| ha.push(id));
b.query(&r(2.0, 2.0, 6.0, 6.0), |id| hb.push(id));
assert_eq!(ha, hb);

The static index searches on a fixed stack. Its box query is iterative: it pops a node and pushes its children, so the stack holds at most the unvisited siblings on the current path, M − 1 per level, plus the children most recently pushed. With node capacity M = 16, each level divides the node count by 16, so a 64-bit target has at most 17 levels, and the stack is a fixed array of (M − 1) · 17 + 1 = 256 indices (2 KiB) on the call stack. No query allocates and the search does not recurse. Were the bound ever exceeded, the search would panic rather than drop a node, since a dropped node would remove its whole subtree from the answer; the bound is proven, so it never does.

References

  • Leutenegger, S. T., Lopez, M. A., & Edgington, J. (1997). STR: A simple and efficient algorithm for R-tree packing. In Proceedings of the 13th International Conference on Data Engineering (ICDE), 497–506. https://doi.org/10.1109/ICDE.1997.582015. Sort-Tile-Recursive packing, the bulk loader of both index types.
  • Beckmann, N., Kriegel, H.-P., Schneider, R., & Seeger, B. (1990). The R*-tree: An efficient and robust access method for points and rectangles. In Proceedings of the 1990 ACM SIGMOD International Conference on Management of Data, 322–331. The insertion heuristics, forced reinsertion and split of the dynamic tree.
  • Guttman, A. (1984). R-trees: A dynamic index structure for spatial searching. In Proceedings of the 1984 ACM SIGMOD International Conference on Management of Data, 47–57. https://doi.org/10.1145/602259.602266. CondenseTree, the basis of removal from the dynamic tree.
  • Brinkhoff, T., Kriegel, H.-P., & Seeger, B. (1993). Efficient processing of spatial joins using R-trees. In Proceedings of the 1993 ACM SIGMOD International Conference on Management of Data, 237–246. https://doi.org/10.1145/170035.170075. The synchronized descent of join and self_join.
  • Hjaltason, G. R., & Samet, H. (1999). Distance browsing in spatial databases. ACM Transactions on Database Systems, 24(2), 265–318. https://doi.org/10.1145/320248.320255. The best-first search behind nearest_candidates and browse.
  • Kamel, I., & Faloutsos, C. (1993). On packing R-trees. In Proceedings of the Second International Conference on Information and Knowledge Management (CIKM), 490–499. https://doi.org/10.1145/170088.170403. Hilbert-curve packing, the documented alternative to STR. It gives somewhat better query performance on some distributions; STR is simpler to state and to verify, and no measured workload has required more.