Nearest neighbors
Finding the entries nearest to a query point on either index: candidate sets and distance
browsing by certified bounds, and exact ranking under the exact-nearest feature.
Neighbors and errors
Every nearest-neighbor operation returns situs::Neighbor values and refuses a non-finite
query point with situs::QueryError. Distances are Euclidean, from the query point to the
nearest point of each entry’s box, so a point inside or on a box is at distance zero from it.
Neighbor
pub struct Neighbor
Certified bounds on the squared Euclidean distance from the query point to one entry’s box:
lower_sq ≤ d² ≤ upper_sq, with d² the exact value. A neighbor
carries bounds rather than a distance, so two entries’ true distances are
ordered only where their intervals do not overlap. A caller that must rank exactly decides with its own
arithmetic among the candidates returned, or uses nearest_exact.
How the bounds are certified is set out in
Certified distance bounds.
| Field | Meaning |
|---|---|
id: u32 |
The entry’s id, as stored; not necessarily unique. |
lower_sq: f64 |
A certified lower bound on the exact squared distance. Finite and non-negative. |
upper_sq: f64 |
A certified upper bound on the exact squared distance. It is positive, never below
2−1019 even at distance zero, because it bounds the distance rather than equals
it, and it is +∞ where the squared distance can overflow
f64.
|
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, 3.0, 4.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 is inside entry 2: d² = 0, and upper_sq is still positive.
assert_eq!(near[0].id, 2);
assert_eq!(near[0].lower_sq, 0.0);
assert!(near[0].upper_sq >= 2f64.powi(-1019));
// Entry 1 is the point (3, 4): d² = 25, bracketed by the bounds.
assert_eq!(near[1].id, 1);
assert!(near[1].lower_sq <= 25.0 && 25.0 <= near[1].upper_sq);
// Far out, the squared distance overflows f64, and the upper bound is +∞.
let far = index.nearest_candidates(f64::MAX, f64::MAX, 1).unwrap();
assert_eq!(far[0].upper_sq, f64::INFINITY);
assert!(far[0].lower_sq.is_finite());
QueryError
pub enum QueryError
Why a nearest-neighbor query was refused. Its one variant, NonFinite, means the query
point was NaN or infinite. Every comparison with NaN is false, so such a point would silently match
nothing, a false negative, and it is refused instead. The check is made before
anything else.
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::{Index, QueryError, Rect};
let index = Index::bulk_load(vec![(Rect::new(0.0, 0.0, 1.0, 1.0).unwrap(), 1)]);
assert_eq!(index.nearest_candidates(f64::NAN, 0.0, 1), Err(QueryError::NonFinite));
assert!(matches!(index.browse(0.0, f64::INFINITY), Err(QueryError::NonFinite)));
// An empty index is not an error: it has no neighbors.
let empty = Index::bulk_load(Vec::new());
assert_eq!(empty.nearest_candidates(0.0, 0.0, 3), Ok(Vec::new()));
Candidates
A candidate query returns every entry whose bounds could place it among the k nearest. It runs a
best-first search over the lower bounds (Hjaltason & Samet, 1999), holding nodes and entries in one
min-heap keyed by lower_sq, with ties broken by a fixed rule so that the pop order is
deterministic. The search is complete because the lower bound is monotone in the box and a node’s
box contains every descendant’s box: a node’s key is at most every descendant
entry’s lower_sq.
Index::nearest_candidates
pub fn nearest_candidates(&self, x: f64, y: f64, k: usize) ->
Result<Vec<Neighbor>, QueryError>
The candidates for the k entries nearest to (x, y): exactly the entries
e with lower_sq(e) ≤ τ, where τ is the k-th smallest
upper_sq over all entries (+∞ when k >= len).
The result always contains the k entries truly nearest to the point, and every
entry tied with the k-th. Let d²k be the k-th
smallest exact squared distance. The k entries with the smallest upper_sq each
have d² ≤ upper_sq ≤ τ, so at least k entries have
d² ≤ τ, which means d²k ≤ τ. Any entry among
the true k nearest, or tied with the k-th, has lower_sq ≤
d² ≤ d²k ≤ τ, so it is in the result.
The result has exactly k entries unless distances near the k-th lie within a few
ulps of each other, in which case it holds the extras rather than guessing among them. It depends only
on the entries and the point rather than on the tree’s shape. An entry stored twice is a
candidate twice, and k = 0 gives an empty result. The result is ordered by
(lower_sq, id), then by internal position; the order is deterministic but carries no
meaning.
Errors: QueryError::NonFinite if x or y is NaN
or infinite, checked before anything else. An empty index gives Ok of an empty
vector.
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, 3.0, 4.0), 5), // d² = 25 from the origin
(r(4.0, 3.0, 4.0, 3.0), 2), // d² = 25: tied with entry 5
(r(6.0, 8.0, 6.0, 8.0), 9), // d² = 100
]);
// k = 1, but the tie at the first place keeps both tied entries.
let near: Vec<u32> = index.nearest_candidates(0.0, 0.0, 1).unwrap().iter().map(|n| n.id).collect();
assert_eq!(near, [2, 5]); // equal bounds, so ordered by id
assert_eq!(index.nearest_candidates(0.0, 0.0, 2).unwrap().len(), 2);
assert_eq!(index.nearest_candidates(0.0, 0.0, 10).unwrap().len(), 3); // k >= len: every entry
assert!(index.nearest_candidates(0.0, 0.0, 0).unwrap().is_empty());
DynamicIndex::nearest_candidates
pub fn nearest_candidates(&self, x: f64, y: f64, k: usize) ->
Result<Vec<Neighbor>, QueryError>
The same search on the dynamic tree, run by the same code, with the same guarantee and argument: the
entries e with lower_sq(e) ≤ τ, where τ is the k-th smallest
upper_sq over all stored entries. The argument needs only that every node’s box
contains its descendants’ boxes, and this tree keeps every node box as the exact union of its
children’s.
The set depends only on the stored entries and the point, so it equals the static
index’s set for the same entries. The order of entries with equal
(lower_sq, id) follows the internal position, which differs between the two trees.
Errors: QueryError::NonFinite if x or y is NaN
or infinite. An empty tree gives Ok of an empty vector.
use situs::{DynamicIndex, Rect};
let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let mut index = DynamicIndex::new();
index.insert(r(0.0, 0.0, 1.0, 1.0), 7);
index.insert(r(5.0, 5.0, 6.0, 6.0), 9);
let near = index.nearest_candidates(2.0, 2.0, 1).unwrap();
assert_eq!(near[0].id, 7); // d² = 2 to the corner (1, 1)
assert!(index.remove(&r(0.0, 0.0, 1.0, 1.0), 7));
let near = index.nearest_candidates(2.0, 2.0, 1).unwrap();
assert_eq!(near.len(), 1);
assert_eq!(near[0].id, 9); // the removed entry is gone
Distance browsing
Browsing runs the same heap as the candidate search without the cutoff, and yields each entry as it is
popped, in nondecreasing lower_sq. It serves a caller that refines entries with its own
exact distance and stops once no later entry can do better. This is distance browsing in the sense of
Hjaltason & Samet.
Index::browse
pub fn browse(&self, x: f64, y: f64) -> Result<Browse<'_>,
QueryError>
The entries in nondecreasing lower_sq (ties by id, then internal position), each exactly
once per stored entry.
The iterator holds one contract: once a Neighbor with lower_sq =
ℓ has been yielded, every entry not yet yielded has true d² ≥ ℓ. A
caller refining candidates by its own exact distance stops once its best answer is at or below the next
lower_sq.
Errors: QueryError::NonFinite if x or y is NaN
or infinite. An empty index gives an iterator that yields nothing.
use situs::{Index, Rect};
// Points stored as zero-extent boxes. Their integer coordinates make
// this caller's own squared distance exact in f64.
let pts = [(3.0, 4.0), (6.0, 8.0), (30.0, 40.0)];
let r = |x, y| Rect::new(x, y, x, y).unwrap();
let index = Index::bulk_load(pts.iter().zip(0u32..).map(|(&(x, y), id)| (r(x, y), id)).collect());
let (mut best, mut best_id, mut examined) = (f64::INFINITY, None, 0);
for n in index.browse(0.0, 0.0).unwrap() {
if best <= n.lower_sq {
break; // no entry still to come can be nearer
}
examined += 1;
let (x, y) = pts[n.id as usize];
let d2 = x * x + y * y;
if d2 < best {
(best, best_id) = (d2, Some(n.id));
}
}
assert_eq!((best, best_id), (25.0, Some(0)));
assert_eq!(examined, 1); // the second entry's lower bound already exceeds 25
Browse and DynamicIndex::browse
pub struct Browse<'a>
pub fn browse(&self, x: f64, y: f64) -> Result<Browse<'_>, QueryError>
Browse is the iterator of Index::browse and DynamicIndex::browse,
which yields entries by nondecreasing lower_sq. It implements Iterator with
Item = Neighbor.
DynamicIndex::browse is the same iterator on the dynamic tree, and it holds the same
contract. The iterator borrows the tree, so the tree cannot change while it runs.
Errors: QueryError::NonFinite if x or y is NaN
or infinite. An empty tree gives an iterator that yields nothing.
use situs::{DynamicIndex, Neighbor, Rect};
let r = |a, b, c, d| Rect::new(a, b, c, d).unwrap();
let mut index = DynamicIndex::new();
index.insert(r(5.0, 5.0, 6.0, 6.0), 9);
index.insert(r(0.0, 0.0, 1.0, 1.0), 7);
index.insert(r(0.0, 0.0, 1.0, 1.0), 7); // stored twice: yielded twice
let all: Vec<Neighbor> = index.browse(2.0, 2.0).unwrap().collect();
let ids: Vec<u32> = all.iter().map(|n| n.id).collect();
assert_eq!(ids, [7, 7, 9]);
assert!(all.windows(2).all(|w| w[0].lower_sq <= w[1].lower_sq));
assert_eq!(DynamicIndex::new().browse(0.0, 0.0).unwrap().count(), 0);
Exact ranking
The certified bounds return a candidate set that holds the true k nearest, but they cannot always
establish which of two candidates is nearer: two entries whose bound intervals overlap are both returned,
unranked. Under the opt-in exact-nearest feature, nearest_exact ranks them
exactly. The feature adds arithmetica, which is also no_std, as
the one dependency; the default build has none.
[dependencies]
situs = { version = "0.1", features = ["exact-nearest"] }
The bounds and the search remain in situs, and the one exact operation, comparing the distances from the
query point to two points, is arithmetica’s compare_distance. The method has four
steps:
- Candidates: the candidate set of
nearest_candidates, unchanged. - Clamp: for each candidate, the query point clamped to its box. Each coordinate is the query’s own when it lies inside the box’s interval on that axis, and otherwise the interval’s nearer end, chosen by exact comparisons. The clamped point is a selection of input values rather than a computed one, so its distance from the query is exactly the distance to the box.
- Sort: by
compare_distancefrom the query to the clamped points, then by id, then by internal position.compare_distanceis exact for every finite input. - Cut: the first
kare kept, then every following candidate whose distance equals the k-th’s exactly.
The result is the exact answer over all entries. The candidate set contains every entry
with d² ≤ d²k. An entry outside it has
lower_sq > τ ≥ d²k, so it is strictly farther than
the k-th and can be neither among the k nearest nor tied with the k-th. Sorting the
set exactly therefore orders every entry that can appear in the answer, and the cut recovers the exact
answer.
Index::nearest_exact
pub fn nearest_exact(&self, x: f64, y: f64, k: usize) ->
Result<Vec<Neighbor>, QueryError>
The k entries nearest to (x, y) by exact Euclidean distance to their boxes,
plus every entry exactly as near as the k-th. The result is ordered by exact distance, and
entries at exactly equal distance by id, then by internal position. Each Neighbor still
carries its certified bounds, while the order and the cut are exact.
The result has exactly k entries unless the k-th is exactly tied, and it never
guesses between candidates the bounds alone could not order. k = 0 gives an empty result,
and k >= len gives every entry, exactly ordered.
Errors: QueryError::NonFinite if x or y is NaN
or infinite, checked before anything else.
use situs::{Index, Rect};
let r = |x, y| Rect::new(x, y, x, y).unwrap();
// Squared distances from the origin are 2^54 + 1 and 2^54. They round
// to the same f64, so the bounds cannot order them, and the exact
// ranking can.
let p27 = 134_217_728.0; // 2^27
let index = Index::bulk_load(vec![(r(p27, 1.0), 1), (r(p27, 0.0), 2)]);
let candidates = index.nearest_candidates(0.0, 0.0, 1).unwrap();
assert_eq!(candidates.len(), 2); // the intervals overlap: both are kept
let exact = index.nearest_exact(0.0, 0.0, 1).unwrap();
assert_eq!(exact.len(), 1);
assert_eq!(exact[0].id, 2); // 2^54 < 2^54 + 1, decided exactly
use situs::{Index, Rect};
let r = |x, y| Rect::new(x, y, x, y).unwrap();
let index = Index::bulk_load(vec![(r(3.0, 4.0), 5), (r(4.0, 3.0), 2), (r(6.0, 8.0), 9)]);
// An exact tie at the k-th place keeps every tied entry, ordered by id.
let ids: Vec<u32> = index.nearest_exact(0.0, 0.0, 1).unwrap().iter().map(|n| n.id).collect();
assert_eq!(ids, [2, 5]);
// k >= len gives every entry, exactly ordered.
let ids: Vec<u32> = index.nearest_exact(0.0, 0.0, 9).unwrap().iter().map(|n| n.id).collect();
assert_eq!(ids, [2, 5, 9]);
DynamicIndex::nearest_exact
pub fn nearest_exact(&self, x: f64, y: f64, k: usize) ->
Result<Vec<Neighbor>, QueryError>
The ranking of Index::nearest_exact on the dynamic tree, run by the same code, with the
same guarantee and argument. For the same stored entries the two trees return the same entries
in the same order, except that entries at exactly equal distance with equal ids follow each
tree’s internal position.
Errors: QueryError::NonFinite if x or y is NaN
or infinite.
use situs::{DynamicIndex, Index, Rect};
let r = |x, y| Rect::new(x, y, x, y).unwrap();
let p27 = 134_217_728.0; // 2^27
let entries = vec![(r(p27, 1.0), 1), (r(p27, 0.0), 2), (r(0.0, p27), 3)];
let mut dynamic = DynamicIndex::new();
for &(rect, id) in &entries {
dynamic.insert(rect, id);
}
let fixed = Index::bulk_load(entries);
// Entries 2 and 3 are both exactly 2^27 from the origin; entry 1 is farther.
let ids = |v: Vec<situs::Neighbor>| v.iter().map(|n| n.id).collect::<Vec<u32>>();
assert_eq!(ids(dynamic.nearest_exact(0.0, 0.0, 1).unwrap()), [2, 3]);
assert_eq!(ids(dynamic.nearest_exact(0.0, 0.0, 3).unwrap()), ids(fixed.nearest_exact(0.0, 0.0, 3).unwrap()));