use alloc::collections::BinaryHeap;
use alloc::vec::Vec;
use core::cmp::{Ordering, Reverse};
use crate::Rect;
use crate::dynamic::node::Child;
use crate::dynamic::{DynamicIndex, SLOTS};
use crate::static_index::Index;
pub(crate) mod bounds;
pub(crate) use bounds::bounds_sq;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Neighbor {
pub id: u32,
pub lower_sq: f64,
pub upper_sq: f64,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QueryError {
NonFinite,
}
impl core::fmt::Display for QueryError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::NonFinite => f.write_str("query point is NaN or infinite"),
}
}
}
impl core::error::Error for QueryError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum ItemKind {
Node,
Entry,
}
#[derive(Clone, Copy, Debug)]
struct Item {
lower: f64,
upper: f64,
kind: ItemKind,
id: u32,
pos: usize,
}
impl Item {
fn neighbor(&self) -> Neighbor {
Neighbor {
id: self.id,
lower_sq: self.lower,
upper_sq: self.upper,
}
}
}
impl Ord for Item {
fn cmp(&self, other: &Self) -> Ordering {
self.lower
.total_cmp(&other.lower)
.then_with(|| self.kind.cmp(&other.kind))
.then_with(|| self.id.cmp(&other.id))
.then_with(|| self.pos.cmp(&other.pos))
}
}
impl PartialOrd for Item {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Item {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Item {}
#[derive(Clone, Copy, Debug)]
struct TotalF64(f64);
impl Ord for TotalF64 {
fn cmp(&self, other: &Self) -> Ordering {
self.0.total_cmp(&other.0)
}
}
impl PartialOrd for TotalF64 {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for TotalF64 {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for TotalF64 {}
struct Cutoff {
k: usize,
worst: BinaryHeap<TotalF64>,
}
impl Cutoff {
fn new(k: usize) -> Cutoff {
Cutoff {
k,
worst: BinaryHeap::with_capacity(k.min(1024) + 1),
}
}
fn offer(&mut self, upper: f64) {
self.worst.push(TotalF64(upper));
if self.worst.len() > self.k {
self.worst.pop();
}
}
fn value(&self) -> f64 {
if self.worst.len() == self.k {
self.worst.peek().map_or(f64::INFINITY, |t| t.0)
} else {
f64::INFINITY
}
}
}
#[derive(Clone, Copy)]
enum Tree<'a> {
Static(&'a Index),
Dynamic(&'a DynamicIndex),
}
impl Tree<'_> {
fn root(self) -> Option<(Rect, usize)> {
match self {
Tree::Static(index) => index.nodes.first().map(|root| (root.rect, 0)),
Tree::Dynamic(index) => index.root.map(|slot| (index.arena[slot].rect, slot)),
}
}
fn push_children(self, i: usize, x: f64, y: f64, heap: &mut BinaryHeap<Reverse<Item>>) {
match self {
Tree::Static(index) => {
let node = &index.nodes[i];
if node.leaf {
for (pos, (rect, id)) in index.entries[node.first..node.end].iter().enumerate()
{
push_entry(heap, x, y, rect, *id, node.first + pos);
}
} else {
for child in node.first..node.end {
push_node(heap, x, y, &index.nodes[child].rect, child);
}
}
}
Tree::Dynamic(index) => {
for (at, child) in index.arena[i].children().enumerate() {
match *child {
Child::Entry(rect, id) => push_entry(heap, x, y, &rect, id, i * SLOTS + at),
Child::Node(slot) => push_node(heap, x, y, &index.arena[slot].rect, slot),
}
}
}
}
}
#[cfg(feature = "exact-nearest")]
fn entry_rect(self, pos: usize) -> Rect {
match self {
Tree::Static(index) => index.entries[pos].0,
Tree::Dynamic(index) => match index.arena[pos / SLOTS].child(pos % SLOTS) {
Child::Entry(rect, _) => rect,
Child::Node(_) => unreachable!("an entry position names an entry"),
},
}
}
fn frontier(self, x: f64, y: f64) -> Result<BinaryHeap<Reverse<Item>>, QueryError> {
if !x.is_finite() || !y.is_finite() {
return Err(QueryError::NonFinite);
}
let mut heap = BinaryHeap::new();
if let Some((rect, pos)) = self.root() {
push_node(&mut heap, x, y, &rect, pos);
}
Ok(heap)
}
}
fn push_entry(
heap: &mut BinaryHeap<Reverse<Item>>,
x: f64,
y: f64,
rect: &Rect,
id: u32,
pos: usize,
) {
let (lower, upper) = bounds_sq(x, y, rect);
heap.push(Reverse(Item {
lower,
upper,
kind: ItemKind::Entry,
id,
pos,
}));
}
fn push_node(heap: &mut BinaryHeap<Reverse<Item>>, x: f64, y: f64, rect: &Rect, pos: usize) {
let (lower, _) = bounds_sq(x, y, rect);
heap.push(Reverse(Item {
lower,
upper: f64::INFINITY,
kind: ItemKind::Node,
id: 0,
pos,
}));
}
impl Index {
pub fn nearest_candidates(
&self,
x: f64,
y: f64,
k: usize,
) -> Result<Vec<Neighbor>, QueryError> {
candidates(Tree::Static(self), x, y, k)
}
pub fn browse(&self, x: f64, y: f64) -> Result<Browse<'_>, QueryError> {
browse(Tree::Static(self), x, y)
}
}
impl DynamicIndex {
pub fn nearest_candidates(
&self,
x: f64,
y: f64,
k: usize,
) -> Result<Vec<Neighbor>, QueryError> {
candidates(Tree::Dynamic(self), x, y, k)
}
pub fn browse(&self, x: f64, y: f64) -> Result<Browse<'_>, QueryError> {
browse(Tree::Dynamic(self), x, y)
}
}
pub struct Browse<'a> {
tree: Tree<'a>,
x: f64,
y: f64,
heap: BinaryHeap<Reverse<Item>>,
}
impl Iterator for Browse<'_> {
type Item = Neighbor;
fn next(&mut self) -> Option<Neighbor> {
while let Some(Reverse(top)) = self.heap.pop() {
match top.kind {
ItemKind::Entry => {
return Some(Neighbor {
id: top.id,
lower_sq: top.lower,
upper_sq: top.upper,
});
}
ItemKind::Node => self
.tree
.push_children(top.pos, self.x, self.y, &mut self.heap),
}
}
None
}
}
fn candidates(tree: Tree<'_>, x: f64, y: f64, k: usize) -> Result<Vec<Neighbor>, QueryError> {
Ok(candidate_items(tree, x, y, k)?
.into_iter()
.map(|e| e.neighbor())
.collect())
}
fn candidate_items(tree: Tree<'_>, x: f64, y: f64, k: usize) -> Result<Vec<Item>, QueryError> {
let mut heap = tree.frontier(x, y)?;
if k == 0 {
return Ok(Vec::new());
}
let mut cutoff = Cutoff::new(k);
let mut popped: Vec<Item> = Vec::new();
while let Some(Reverse(top)) = heap.peek().copied() {
if top.lower > cutoff.value() {
break;
}
heap.pop();
match top.kind {
ItemKind::Entry => {
cutoff.offer(top.upper);
popped.push(top);
}
ItemKind::Node => tree.push_children(top.pos, x, y, &mut heap),
}
}
let tau = cutoff.value();
popped.retain(|e| e.lower <= tau);
popped.sort_by(|a, b| {
a.lower
.total_cmp(&b.lower)
.then_with(|| a.id.cmp(&b.id))
.then_with(|| a.pos.cmp(&b.pos))
});
Ok(popped)
}
fn browse(tree: Tree<'_>, x: f64, y: f64) -> Result<Browse<'_>, QueryError> {
Ok(Browse {
tree,
x,
y,
heap: tree.frontier(x, y)?,
})
}
#[cfg(feature = "exact-nearest")]
mod exact;
#[cfg(test)]
mod tests;