Boxes and the static index
The closed box type every index stores, and the static R-tree: bulk-loaded once by Sort-Tile-Recursive packing, then queried by window, by early-exit query and by join.
Boxes
Every entry and every query window is a Rect, imported as situs::Rect, with its
error type situs::RectError. Every test on a box is a handful of exact comparisons of stored
values, with no arithmetic.
Rect
pub struct Rect
An axis-aligned box with closed intervals on both axes. It holds two invariants: all four bounds are
finite, and min_x <= max_x and min_y <= max_y. A box of zero width,
zero height, or both (a segment, or a point) is valid, both as an entry and as a query. Only non-finite
and inverted bounds are refused, by Rect::new, so a
Rect that exists satisfies the invariants.
The rule is four finite bounds, not inverted, and nothing more. A crate whose own box type has the
same validity rules converts to and from Rect without a failure path, because each side
accepts every value the other can hold. Rect is Copy, and its
== compares the bounds numerically, so -0.0 equals 0.0.
The four bounds are read with accessors:
| Method | Returns |
|---|---|
min_x(&self) -> f64 |
The lower x bound. |
min_y(&self) -> f64 |
The lower y bound. |
max_x(&self) -> f64 |
The upper x bound. |
max_y(&self) -> f64 |
The upper y bound. |
use situs::Rect;
let point = Rect::new(2.0, 3.0, 2.0, 3.0).unwrap(); // zero width and height
assert_eq!((point.min_x(), point.max_y()), (2.0, 3.0));
let segment = Rect::new(0.0, 1.0, 4.0, 1.0).unwrap(); // zero height
assert!(segment.intersects(&Rect::new(1.0, 0.0, 1.0, 2.0).unwrap()));
Rect::new
pub fn new(min_x: f64, min_y: f64, max_x: f64, max_y: f64) -> Result<Rect,
RectError>
Builds a box from its bounds. Non-finiteness is checked before inversion, because a NaN makes the inversion comparison false and would otherwise be reported as a valid box.
Errors: RectError::NonFinite if any bound is NaN or infinite;
RectError::Inverted if min_x > max_x or min_y > max_y.
use situs::{Rect, RectError};
assert!(Rect::new(0.0, 0.0, 1.0, 1.0).is_ok());
assert_eq!(Rect::new(1.0, 0.0, 0.0, 1.0), Err(RectError::Inverted));
assert_eq!(Rect::new(0.0, 0.0, f64::INFINITY, 1.0), Err(RectError::NonFinite));
// Inverted on x and NaN on y: the NaN is reported, since it is checked first.
assert_eq!(Rect::new(1.0, f64::NAN, 0.0, 1.0), Err(RectError::NonFinite));
RectError
pub enum RectError
Why Rect::new refused its bounds. It has two variants:
NonFinite: a bound is NaN or infinite. Such a box has no extent to test, and a NaN bound would make every comparison false, so it is refused rather than stored.Inverted:min > maxon some axis. A zero-extent box (min == max) is valid; an inverted one would meet nothing and be silently useless.
The enum is non-exhaustive, so a match on it needs a wildcard arm, and a later variant is not a
breaking change. It implements Display and Error.
use situs::{Rect, RectError};
let reason = match Rect::new(0.0, 5.0, 1.0, 4.0) {
Ok(_) => "valid",
Err(RectError::NonFinite) => "non-finite",
Err(RectError::Inverted) => "inverted",
Err(_) => "other", // required: the enum is non-exhaustive
};
assert_eq!(reason, "inverted");
Rect::intersects
pub fn intersects(&self, other: &Rect) -> bool
Whether the two boxes share at least one point. The intervals are closed, so boxes that touch along an edge or at a corner intersect. The test is four exact comparisons of stored values and involves no arithmetic. It is the overlap test of the correctness argument (condition 3).
use situs::Rect;
let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let unit = r(0.0, 0.0, 1.0, 1.0);
assert!(unit.intersects(&r(1.0, 0.0, 2.0, 1.0))); // shared edge
assert!(unit.intersects(&r(1.0, 1.0, 2.0, 2.0))); // shared corner
assert!(!unit.intersects(&r(1.5, 0.0, 2.0, 1.0))); // a gap of 0.5
Rect::contains_point
pub fn contains_point(&self, x: f64, y: f64) -> bool
Whether the point is inside the box or on its boundary. The box is closed, as in
intersects. A NaN coordinate gives false, because every comparison with NaN
is false, and an infinite coordinate lies outside every finite box.
use situs::Rect;
let unit = Rect::new(0.0, 0.0, 1.0, 1.0).unwrap();
assert!(unit.contains_point(0.5, 0.5));
assert!(unit.contains_point(1.0, 0.0)); // a corner is on the boundary
assert!(!unit.contains_point(f64::NAN, 0.5));
assert!(!unit.contains_point(f64::INFINITY, 0.5));
Rect::contains_rect
pub fn contains_rect(&self, other: &Rect) -> bool
Whether other lies entirely inside this box, boundary included. The test is
closed, so a box that shares an edge with this one is contained, and it is exact. It
is the test behind the static index’s containment shortcut.
use situs::Rect;
let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let outer = r(0.0, 0.0, 4.0, 4.0);
assert!(outer.contains_rect(&r(1.0, 1.0, 2.0, 2.0)));
assert!(outer.contains_rect(&r(0.0, 0.0, 4.0, 1.0))); // shares three edges
assert!(outer.contains_rect(&outer)); // every box contains itself
assert!(!outer.contains_rect(&r(3.0, 3.0, 5.0, 4.0))); // crosses the right edge
Rect::union
pub fn union(&self, other: &Rect) -> Rect
The smallest box containing both. Each bound is one of the two inputs’ bounds, chosen by exact comparison, so the result is exact and contains both operands. That property establishes condition 2 of the correctness argument for node boxes.
On a tie (-0.0 against 0.0, which compare equal) self’s
bound is kept, so the operand order determines the result’s bit patterns.
use situs::Rect;
let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let u = r(0.0, 0.0, 1.0, 1.0).union(&r(3.0, -2.0, 4.0, 0.5));
assert_eq!(u, r(0.0, -2.0, 4.0, 1.0)); // every bound is an input bound
// On the tie between -0.0 and 0.0, self's bound is kept.
let (neg, pos) = (r(-0.0, 0.0, 1.0, 1.0), r(0.0, 0.0, 1.0, 1.0));
assert!(neg.union(&pos).min_x().is_sign_negative());
assert!(pos.union(&neg).min_x().is_sign_positive());
The static index
situs::Index is a read-only R-tree over (Rect, u32) entries. It is compact and
the fastest of the two index types to query, suited to a set that is built once and queried many times.
For a set that changes, see the dynamic index.
Index
pub struct Index
A static R-tree over (Rect, u32) entries, bulk-loaded by STR packing. It is built once by
Index::bulk_load and then queried, and it cannot be changed afterward.
The u32 is the caller’s identifier for the entry, returned by every query. It
need not be unique, and an entry stored twice is two entries. An id is a key rather than a payload, so
the index remains independent of what it indexes, and the caller maps each id back to its own
data.
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), 7), (r(5.0, 5.0, 6.0, 6.0), 9)]);
let mut hits = Vec::new();
index.query(&r(1.0, 1.0, 2.0, 2.0), |id| hits.push(id));
assert_eq!(hits, [7]); // touching at a corner counts
Index::bulk_load
pub fn bulk_load(mut entries: Vec<(Rect, u32)>) -> Index
Builds the index over entries by Sort-Tile-Recursive (STR) packing. With
n entries and node capacity M, the method has four stages:
- let P = ⌈n / M⌉ be the number of leaves and S = ⌈√P⌉;
- sort the entries by the
xof their box centers and cut them into S vertical slices of S·M consecutive entries, the last slice shorter; - sort each slice by the
yof the centers and pack consecutive runs of M into leaves; - treat the leaf boxes as entries and repeat, level by level, until one node remains.
The build costs O(n log n), from the sorts. The entry vector is reordered into
leaf order and kept rather than copied. The build never panics, because every Rect is
finite, so every sort key is finite and total_cmp orders all of them. The layout is a
deterministic function of the input sequence, and the sort keys determine only the shape of the tree
(see Where arithmetic enters).
use situs::{Index, Rect};
let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
// A 10 by 10 grid of unit cells, ids 0 to 99.
let cells: Vec<(Rect, u32)> = (0..100u32)
.map(|i| {
let (x, y) = (f64::from(i % 10), f64::from(i / 10));
(r(x, y, x + 1.0, y + 1.0), i)
})
.collect();
let index = Index::bulk_load(cells);
assert_eq!(index.len(), 100);
assert_eq!(index.bounds(), Some(r(0.0, 0.0, 10.0, 10.0)));
Index::NODE_CAPACITY and Index::memory_size_for
pub const NODE_CAPACITY: usize = 16;
pub fn memory_size_for(n: usize) -> usize
NODE_CAPACITY is the number of entries per leaf and children per node, the M of
STR packing. A capacity of 16 keeps a node’s boxes within a few cache lines and the tree shallow,
so a million entries make five levels.
memory_size_for returns the heap bytes a built index of n entries holds, so
that a caller can size an index before building it. It is exactly n · size_of::<(Rect,
u32)>() + nodes(n) · size_of::<Node>(), where nodes(n) is the node
count STR packing produces (⌈n / M⌉ leaves, then ⌈· /
M⌉ nodes per level above until one node remains, and none for n = 0) and
Node is the index’s private node record. The count is a function of n
alone, because every level is the level below cut into chunks of M.
The figure omits spare capacity in the entry vector passed to bulk_load (which the index
keeps), the transient allocations made while building (one vector per level, freed before
bulk_load returns, totaling at most the node count again), and the inline size of the
Index value itself. The node vector has no spare capacity. The result saturates: for an
n so large that the size overflows usize, it is usize::MAX, and
no such index can be built.
use situs::{Index, Rect};
let entry = core::mem::size_of::<(Rect, u32)>();
let node = Index::memory_size_for(1) - entry; // one entry, one leaf
assert_eq!(Index::memory_size_for(0), 0);
assert_eq!(Index::memory_size_for(16), 16 * entry + node); // one full leaf
assert_eq!(Index::memory_size_for(17), 17 * entry + 3 * node); // two leaves and a root
assert_eq!(Index::memory_size_for(usize::MAX), usize::MAX); // saturates
len, is_empty and bounds
pub fn len(&self) -> usize
pub fn is_empty(&self) -> bool
pub fn bounds(&self) -> Option<Rect>
len is the number of entries and is_empty is true if the index
holds none. bounds is the box containing every entry, or None for an empty
index. It is the root’s box, an exact union of every entry’s box.
use situs::{Index, Rect};
let empty = Index::bulk_load(Vec::new());
assert!(empty.is_empty());
assert_eq!(empty.bounds(), None);
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), (r(-3.0, 2.0, -2.0, 5.0), 2)]);
assert_eq!(index.len(), 2);
assert_eq!(index.bounds(), Some(r(-3.0, 0.0, 1.0, 5.0)));
Box queries
A box query reports the id of every entry whose box meets a window. Both forms report exactly those entries, run iteratively on a fixed stack, and never allocate.
Index::query
pub fn query(&self, window: &Rect, mut visit: impl FnMut(u32))
Calls visit with the id of every entry whose box meets window, and reports
exactly those entries. A node is descended only if its box meets the window, which
loses nothing because every node’s box contains its children’s, and a leaf entry is
reported only if its own box meets the window. An entry stored twice is reported twice. The order of
visits is a deterministic function of the index layout rather than a meaningful one.
The containment shortcut reports a whole subtree once the window contains its box. Every entry’s box is contained in its leaf’s box, and every node’s box in its parent’s. Containment is transitive, and a box contained in the window meets it because the test is closed, so every entry below is a hit and is reported untested. The containment test is four exact comparisons of stored values, so the shortcut adds no arithmetic and can neither add an entry nor lose one. It walks the subtree in the order the plain search would visit it, so the visit order is the same with or without it.
Panics: Never. The search stack’s capacity is a proven bound on its height, and were that bound ever broken, the query would panic rather than silently drop part of the tree.
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),
(r(0.0, 0.0, 1.0, 1.0), 1), // stored twice: two entries
(r(3.0, 3.0, 4.0, 4.0), 2),
]);
let mut hits = Vec::new();
index.query(&r(0.5, 0.5, 0.5, 0.5), |id| hits.push(id)); // a point window
assert_eq!(hits, [1, 1]);
// A window containing every box reports every entry.
let mut all = Vec::new();
index.query(&r(-10.0, -10.0, 10.0, 10.0), |id| all.push(id));
all.sort_unstable();
assert_eq!(all, [1, 1, 2]);
Index::try_query
pub fn try_query<B>(&self, window: &Rect, mut visit: impl FnMut(u32)
-> ControlFlow<B>) -> ControlFlow<B>
Calls visit with the id of each entry whose box meets window, in the same
order as query, until visit returns ControlFlow::Break. Returns
that Break, or Continue(()) if every such entry was visited.
The entries visited before a break are exactly a prefix of query’s
sequence. Like query, it never allocates.
Panics: Never, as for query.
use core::ops::ControlFlow;
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), 7), (r(5.0, 5.0, 6.0, 6.0), 9)]);
// Does any entry meet this box? Stop at the first one.
assert!(index.try_query(&r(0.5, 0.5, 2.0, 2.0), |_| ControlFlow::Break(())).is_break());
assert!(index.try_query(&r(2.0, 2.0, 3.0, 3.0), |_| ControlFlow::Break(())).is_continue());
// The first entry meeting a box, if any.
assert_eq!(index.try_query(&r(4.0, 4.0, 9.0, 9.0), ControlFlow::Break), ControlFlow::Break(9));
Joins
A join reports every pair of entries whose boxes meet. The traversal is the synchronized descent of Brinkhoff, Kriegel & Seeger (1993): it walks pairs of nodes, one from each tree, and descends a pair only when the two boxes meet. The correctness argument is the query’s, applied pairwise:
- No pair is lost. If entries
aandbhave boxes that meet, they share a point. Each ancestor’s box contains its descendants’ boxes, so every ancestor pair contains that point and meets, and the pair is reached. - No pair is added. At two leaves, each entry pair is tested with the closed overlap test before it is reported.
A leaf paired with an internal node is paired with each of that node’s children, which is how two trees of different heights meet. A join’s output can be quadratic in the sizes of the indexes, so it is never collected. Each pair goes to the caller’s visitor as it is found, and only the pending node pairs are stored, on a heap stack.
Index::join
pub fn join(&self, other: &Index, mut visit: impl FnMut(u32, u32))
Calls visit(a_id, b_id) once for every pair of entries a in
self and b in other whose boxes meet (closed: boxes that touch
at an edge or a corner meet). It reports exactly those pairs.
A pair is a pair of stored entries, so an entry stored twice, or two entries with the same id, give one report per stored pair. The order of the reports is a deterministic function of both layouts rather than a meaningful one.
use situs::{Index, Rect};
let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let roads = Index::bulk_load(vec![(r(0.0, 0.0, 10.0, 0.0), 1), (r(0.0, 5.0, 10.0, 5.0), 2)]);
let lots = Index::bulk_load(vec![
(r(2.0, -1.0, 3.0, 1.0), 10), // crosses road 1
(r(4.0, 1.0, 5.0, 4.0), 11), // between the roads
(r(6.0, 4.0, 7.0, 5.0), 12), // touches road 2 along its top edge
]);
let mut pairs = Vec::new();
roads.join(&lots, |road, lot| pairs.push((road, lot)));
pairs.sort_unstable();
assert_eq!(pairs, [(1, 10), (2, 12)]);
Index::self_join
pub fn self_join(&self, mut visit: impl FnMut(u32, u32))
Calls visit(x_id, y_id) once for every unordered pair of distinct stored entries of
self whose boxes meet (closed). An entry is never paired with itself; two stored entries
with equal boxes or equal ids are distinct entries and are paired.
Within a pair, x is the entry earlier in the index’s depth-first order, the order in
which a query covering every entry reports them. That order is deterministic rather than meaningful,
so a caller that needs (min, max) normalizes the pair. The traversal pairs a node with
itself, which pairs its children (ci, cj) with i ≤
j, and a leaf with itself tests its entries (ei, ej) with
i < j. Two different nodes have disjoint subtrees, so every pair is found
exactly once.
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, 2.0, 2.0), 1),
(r(2.0, 2.0, 3.0, 3.0), 2), // touches 1 at a corner
(r(9.0, 9.0, 9.0, 9.0), 3),
(r(9.0, 9.0, 9.0, 9.0), 3), // the same box and id again: a distinct entry
]);
let mut pairs = Vec::new();
index.self_join(|x, y| pairs.push((x.min(y), x.max(y))));
pairs.sort_unstable();
assert_eq!(pairs, [(1, 2), (3, 3)]);