use std::collections::{HashMap, HashSet};
use relate_core::{NodeId, Value};
use relate_model::point::{
is_geographic, wrap_longitude, LATITUDE_MAX as LAT_MAX, LATITUDE_MIN as LAT_MIN,
LONGITUDE_MAX as LON_MAX, LONGITUDE_MIN as LON_MIN, LONGITUDE_TURN as LON_TURN,
};
use rstar::{RTree, RTreeObject, AABB};
use super::order::SpatialSeek;
use super::DrainState;
use crate::spatial::{bbox_longitude_wraps, EARTH_RADIUS_METERS};
#[derive(Debug)]
pub(crate) struct PointIndex {
pts: HashMap<NodeId, (i32, f64, f64)>,
tree: RTree<PointLeaf>,
dirty: HashSet<NodeId>,
bulk: bool,
has_negative_height: bool,
has_out_of_domain_latitude: bool,
}
impl Default for PointIndex {
fn default() -> Self {
Self {
pts: HashMap::new(),
tree: RTree::new(),
dirty: HashSet::new(),
bulk: true,
has_negative_height: false,
has_out_of_domain_latitude: false,
}
}
}
impl PointIndex {
#[cfg(feature = "research")]
pub(crate) fn pt_count(&self) -> usize {
self.pts.len()
}
}
#[derive(Clone, Debug, PartialEq)]
struct PointLeaf {
pos: [f64; 2],
id: NodeId,
}
impl RTreeObject for PointLeaf {
type Envelope = AABB<[f64; 2]>;
fn envelope(&self) -> Self::Envelope {
AABB::from_point(self.pos)
}
}
fn leaf_of(id: NodeId, x: f64, y: f64) -> Option<PointLeaf> {
(x.is_finite() && y.is_finite()).then_some(PointLeaf { pos: [x, y], id })
}
impl DrainState for PointIndex {
fn dirty_mut(&mut self) -> &mut HashSet<NodeId> {
&mut self.dirty
}
fn seal(&mut self) {
let leaves: Vec<PointLeaf> = self
.pts
.iter()
.filter_map(|(id, (_, x, y))| leaf_of(*id, *x, *y))
.collect();
self.tree = RTree::bulk_load(leaves);
self.bulk = false;
}
fn insert(&mut self, id: NodeId, value: &Value) {
if let Value::Point(p) = value {
point_insert(self, id, p.srid, p.x, p.y, p.z);
}
}
fn remove_node(&mut self, id: NodeId) {
point_remove_node(self, id);
}
}
fn point_remove_node(st: &mut PointIndex, id: NodeId) {
if let Some((_, x, y)) = st.pts.remove(&id) {
if !st.bulk {
if let Some(leaf) = leaf_of(id, x, y) {
st.tree.remove(&leaf);
}
}
}
}
pub(crate) fn point_insert(
st: &mut PointIndex,
id: NodeId,
srid: i32,
x: f64,
y: f64,
z: Option<f64>,
) {
point_remove_node(st, id);
st.pts.insert(id, (srid, x, y));
if z.is_some_and(|z| z < 0.0) {
st.has_negative_height = true;
}
if is_geographic(srid) && !latitude_in_domain(y) {
st.has_out_of_domain_latitude = true;
}
if !st.bulk {
if let Some(leaf) = leaf_of(id, x, y) {
st.tree.insert(leaf);
}
}
}
pub(crate) fn spatial_ids(st: &PointIndex, seek: &SpatialSeek) -> HashSet<NodeId> {
let envelopes = seek_envelopes(st, seek);
if envelopes.is_empty() {
return st.pts.keys().copied().collect();
}
let mut out = HashSet::new();
for envelope in envelopes {
out.extend(
st.tree
.locate_in_envelope_intersecting(envelope)
.map(|leaf| leaf.id),
);
}
out
}
pub(crate) fn spatial_holds(v: &Value, seek: &SpatialSeek) -> bool {
match seek {
SpatialSeek::BBox { lo, hi } => {
match crate::spatial::point_within_bbox(&[v.clone(), lo.clone(), hi.clone()]) {
Ok(Value::Bool(b)) => b,
Ok(_) => false,
Err(_) => true,
}
}
SpatialSeek::Distance {
origin,
max,
inclusive,
} => match crate::spatial::point_distance(&[v.clone(), origin.clone()]) {
Ok(Value::Float(d)) => {
if *inclusive {
d <= *max
} else {
d < *max
}
}
Ok(_) => false,
Err(_) => true,
},
}
}
fn lon_envelopes(lo: f64, hi: f64, miny: f64, maxy: f64) -> Vec<AABB<[f64; 2]>> {
if hi - lo >= LON_TURN {
return vec![AABB::from_corners([LON_MIN, miny], [LON_MAX, maxy])];
}
let mut out = Vec::new();
for shift in [-LON_TURN, 0.0, LON_TURN] {
let (lo, hi) = ((lo + shift).max(LON_MIN), (hi + shift).min(LON_MAX));
if lo <= hi {
out.push(AABB::from_corners([lo, miny], [hi, maxy]));
}
}
out
}
fn longitude_in_domain(x: f64) -> bool {
x.is_finite() && (LON_MIN..=LON_MAX).contains(&x)
}
fn latitude_in_domain(y: f64) -> bool {
y.is_finite() && (LAT_MIN..=LAT_MAX).contains(&y)
}
fn seek_envelopes(st: &PointIndex, seek: &SpatialSeek) -> Vec<AABB<[f64; 2]>> {
match seek {
SpatialSeek::BBox { lo, hi } => bbox_envelopes(lo, hi),
SpatialSeek::Distance {
origin,
max,
inclusive: _,
} => distance_envelopes(
origin,
*max,
st.has_negative_height,
st.has_out_of_domain_latitude,
),
}
}
fn bbox_envelopes(lo: &Value, hi: &Value) -> Vec<AABB<[f64; 2]>> {
let (Value::Point(lo), Value::Point(hi)) = (lo, hi) else {
return Vec::new();
};
if !is_geographic(lo.srid) {
return vec![AABB::from_corners([lo.x, lo.y], [hi.x, hi.y])];
}
if !longitude_in_domain(lo.x) || !longitude_in_domain(hi.x) {
return Vec::new();
}
if bbox_longitude_wraps(lo.srid, lo.x, hi.x) {
return vec![
AABB::from_corners([lo.x, lo.y], [LON_MAX, hi.y]),
AABB::from_corners([LON_MIN, lo.y], [hi.x, hi.y]),
];
}
lon_envelopes(lo.x, hi.x, lo.y, hi.y)
}
fn distance_envelopes(
origin: &Value,
max: f64,
negative_height: bool,
out_of_domain_latitude: bool,
) -> Vec<AABB<[f64; 2]>> {
const EPS: f64 = 1.01;
let Value::Point(origin) = origin else {
return Vec::new();
};
if !is_geographic(origin.srid) {
let (dx, dy) = (max.abs() * EPS, max.abs() * EPS);
return vec![AABB::from_corners(
[origin.x - dx, origin.y - dy],
[origin.x + dx, origin.y + dy],
)];
}
if !origin.x.is_finite() || !latitude_in_domain(origin.y) {
return Vec::new();
}
if negative_height || origin.z.is_some_and(|z| z < 0.0) || out_of_domain_latitude {
return Vec::new();
}
let delta = max.abs() / EARTH_RADIUS_METERS * EPS;
if !delta.is_finite() || delta >= std::f64::consts::FRAC_PI_2 {
return Vec::new();
}
let origin_x = wrap_longitude(origin.x);
let lat = origin.y.to_radians();
let miny = (lat - delta).to_degrees();
let maxy = (lat + delta).to_degrees();
let lon_delta = if delta.sin() >= lat.cos().abs() {
LON_MAX
} else {
(delta.sin() / lat.cos().abs()).asin().to_degrees()
};
lon_envelopes(origin_x - lon_delta, origin_x + lon_delta, miny, maxy)
}
#[cfg(test)]
mod tests {
use super::*;
use relate_test_support::values::point;
fn seek_bbox(srid: i32, minx: f64, miny: f64, maxx: f64, maxy: f64) -> SpatialSeek {
SpatialSeek::BBox {
lo: point(srid, minx, miny),
hi: point(srid, maxx, maxy),
}
}
fn seek_distance(srid: i32, x: f64, y: f64, max: f64) -> SpatialSeek {
SpatialSeek::Distance {
origin: point(srid, x, y),
max,
inclusive: true,
}
}
fn assert_superset(st: &PointIndex, seek: &SpatialSeek) {
let candidates = spatial_ids(st, seek);
for id in &candidates {
assert!(st.pts.contains_key(id), "ghost candidate {id}");
}
for (id, (srid, x, y)) in &st.pts {
if spatial_holds(&point(*srid, *x, *y), seek) {
assert!(candidates.contains(id), "missed posted match {id}");
}
}
}
#[test]
fn bulk_mode_appends_then_the_seal_bulk_loads() {
let mut st = PointIndex::default();
for i in 0..2_000 {
point_insert(
&mut st,
i,
4326,
(i % 50) as f64 * 0.01,
(i / 50) as f64 * 0.01,
None,
);
}
assert_eq!(st.tree.size(), 0);
st.seal();
assert_eq!(st.tree.size(), 2_000);
assert_superset(&st, &seek_bbox(7203, 0.05, 0.05, 0.25, 0.25));
point_insert(&mut st, 9_999, 4326, 0.10, 0.10, None);
assert!(spatial_ids(&st, &seek_bbox(7203, 0.05, 0.05, 0.25, 0.25)).contains(&9_999));
point_remove_node(&mut st, 9_999);
assert!(!spatial_ids(&st, &seek_bbox(7203, 0.05, 0.05, 0.25, 0.25)).contains(&9_999));
st.seal();
assert_superset(&st, &seek_bbox(7203, 0.05, 0.05, 0.25, 0.25));
}
#[test]
fn splits_and_underflow_keep_the_superset() {
let mut st = PointIndex::default();
for i in 0..10_000 {
let (x, y) = ((i % 100) as f64 / 10_000.0, (i / 100) as f64 / 10_000.0);
point_insert(&mut st, i, 7203, x, y, None);
}
st.seal();
let seek = seek_bbox(7203, 0.002, 0.002, 0.004, 0.004);
assert_superset(&st, &seek);
assert_superset(&st, &seek_distance(7203, 0.003, 0.003, 150.0));
for i in (0..10_000).filter(|i| i % 10 != 0) {
point_remove_node(&mut st, i);
}
assert_superset(&st, &seek);
assert_superset(&st, &seek_distance(7203, 0.003, 0.003, 150.0));
assert_eq!(st.pts.len(), 1_000);
assert_eq!(st.tree.size(), 1_000);
}
#[test]
fn non_finite_coordinates_stay_removable_but_never_seekable() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 7203, f64::NAN, 1.0, None);
point_insert(&mut st, 2, 7203, f64::INFINITY, 2.0, None);
point_insert(&mut st, 3, 7203, 1.0, 1.0, None);
assert_eq!(st.pts.len(), 3);
st.seal();
assert_eq!(st.tree.size(), 1);
assert_eq!(
spatial_ids(&st, &seek_bbox(7203, -10.0, -10.0, 10.0, 10.0)),
HashSet::from([3])
);
point_remove_node(&mut st, 1);
point_remove_node(&mut st, 2);
assert_eq!(st.pts.len(), 1);
assert_eq!(st.tree.size(), 1);
}
#[test]
fn bbox_wrap_answers_across_the_antimeridian() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 4326, 179.5, 10.0, None);
point_insert(&mut st, 2, 4326, -179.5, 10.0, None);
point_insert(&mut st, 3, 4326, 0.0, 10.0, None);
st.seal();
let seek = seek_bbox(4326, 179.0, -10.0, -179.0, 10.0);
assert_superset(&st, &seek);
assert_eq!(
spatial_ids(&st, &seek),
HashSet::from([1, 2]),
"the wrap band is answered, not its complement"
);
}
#[test]
fn bbox_wrap_keeps_a_point_stored_exactly_at_the_corner_longitude() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 4326, 0.7, 10.0, None);
point_insert(&mut st, 2, 4326, 179.5, 10.0, None);
point_insert(&mut st, 3, 4326, -179.5, 10.0, None);
st.seal();
let seek = seek_bbox(4326, 170.0, -10.0, 0.7, 10.0);
assert_superset(&st, &seek);
assert_eq!(spatial_ids(&st, &seek), HashSet::from([1, 2, 3]));
}
#[test]
fn a_posted_latitude_outside_the_domain_takes_the_decline() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 4326, 0.0, 95.0, None);
point_insert(&mut st, 2, 4326, 0.0, 10.0, None);
st.seal();
assert!(st.has_out_of_domain_latitude);
let seek = seek_distance(4326, 0.0, 10.0, 9_600_000.0);
assert_superset(&st, &seek);
assert_eq!(
spatial_ids(&st, &seek),
HashSet::from([1, 2]),
"the seek declines: every posting answers"
);
assert!(spatial_holds(
&point(4326, 80.0, 95.0),
&seek_distance(4326, 0.0, 10.0, 9_020_000.0)
));
}
#[test]
fn a_non_finite_origin_takes_the_decline_not_a_full_range_band() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 4326, 10.0, 10.0, None);
point_insert(&mut st, 2, 4326, 20.0, 20.0, None);
st.seal();
let seek = seek_distance(4326, f64::NAN, 10.0, 100_000.0);
assert_eq!(
spatial_ids(&st, &seek),
HashSet::from([1, 2]),
"the seek declines: every posting answers, the residual rejects"
);
}
#[test]
fn geographic_distance_envelope_bounds_the_great_circle() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 4326, 60.0, 60.0, None);
point_insert(&mut st, 2, 4326, -0.5, 60.5, None);
point_insert(&mut st, 3, 4326, 0.5, 60.5, None);
point_insert(&mut st, 4, 4326, 100.0, 60.0, None);
st.seal();
let seek = SpatialSeek::Distance {
origin: point(4326, 0.0, 60.0),
max: 3_000_000.0,
inclusive: true,
};
assert_superset(&st, &seek);
let matches = spatial_ids(&st, &seek);
assert!(matches.contains(&1), "the 60°-out point is a match");
assert!(matches.contains(&2) && matches.contains(&3));
assert!(
!matches.contains(&4),
"100° out in longitude at 60° is ~5000 km, past the bound"
);
}
#[test]
fn distance_past_a_quarter_circumference_keeps_the_far_hemisphere() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 4326, 0.0, 89.0, None);
point_insert(&mut st, 2, 4326, 0.0, 70.0, None);
point_insert(&mut st, 3, 4326, 0.0, 0.0, None);
st.seal();
assert_superset(&st, &seek_distance(4326, 0.0, -10.0, 12_000_000.0));
assert_superset(&st, &seek_distance(4326, 0.0, -60.0, 19_000_000.0));
assert_eq!(
spatial_ids(&st, &seek_distance(4326, 0.0, -10.0, 9_000_000.0)),
HashSet::from([2, 3])
);
}
#[test]
fn bbox_wrap_ending_at_the_antimeridian_keeps_the_180_meridian() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 4326, -180.0, 10.0, None);
point_insert(&mut st, 2, 4326, 180.0, 10.0, None);
point_insert(&mut st, 3, 4326, 0.0, 10.0, None);
st.seal();
let seek = seek_bbox(4326, 179.0, -10.0, -180.0, 10.0);
assert_superset(&st, &seek);
assert_eq!(spatial_ids(&st, &seek), HashSet::from([1, 2]));
}
#[test]
fn bbox_wrap_with_corners_outside_the_domain_keeps_the_residual_matches() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 4326, -170.0, 10.0, None);
point_insert(&mut st, 2, 4326, 140.0, 10.0, None);
point_insert(&mut st, 3, 4326, 0.0, 10.0, None);
st.seal();
let seek = seek_bbox(4326, -200.0, -10.0, -250.0, 10.0);
assert_superset(&st, &seek);
assert_eq!(spatial_ids(&st, &seek), HashSet::from([1, 2, 3]));
}
#[test]
fn distance_with_an_origin_outside_the_domain_answers_at_its_stored_spelling() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 4326, -179.5, 10.0, None);
point_insert(&mut st, 2, 4326, 0.0, 10.0, None);
st.seal();
let seek = seek_distance(4326, 540.5, 10.0, 100_000.0);
assert_superset(&st, &seek);
assert_eq!(
spatial_ids(&st, &seek),
HashSet::from([1]),
"the origin's stored spelling is answered, the far point is not"
);
assert!(spatial_holds(&point(4326, -179.5, 10.0), &seek));
assert!(!spatial_holds(&point(4326, 0.0, 10.0), &seek));
}
#[test]
fn distance_with_a_latitude_outside_the_domain_takes_the_decline() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 4326, -179.5, 10.0, None);
point_insert(&mut st, 2, 4326, 0.0, 10.0, None);
st.seal();
assert_eq!(
spatial_ids(&st, &seek_distance(4326, 0.0, 95.0, 100_000.0)),
HashSet::from([1, 2])
);
}
#[test]
fn distance_wrap_answers_across_the_antimeridian() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 4326, 179.9, 10.0, None);
point_insert(&mut st, 2, 4326, -179.9, 10.0, None);
st.seal();
let seek = SpatialSeek::Distance {
origin: point(4326, -179.9, 10.0),
max: 30_000.0,
inclusive: true,
};
assert_superset(&st, &seek);
assert_eq!(spatial_ids(&st, &seek), HashSet::from([1, 2]));
}
#[test]
fn negative_heights_fall_back_to_the_full_posting_set() {
let mut st = PointIndex::default();
point_insert(&mut st, 1, 4979, 10.0, 10.0, None);
point_insert(&mut st, 2, 4979, 10.5, 10.5, None);
st.seal();
let seek = SpatialSeek::Distance {
origin: point(4979, 10.0, 10.0),
max: 100_000.0,
inclusive: true,
};
assert!(!st.has_negative_height);
assert_eq!(spatial_ids(&st, &seek), HashSet::from([1, 2]));
point_insert(&mut st, 3, 4979, 20.0, 20.0, Some(-1.0));
assert!(st.has_negative_height);
let far = SpatialSeek::Distance {
origin: point(4979, 10.0, 10.0),
max: 1.0,
inclusive: true,
};
assert_superset(&st, &far);
assert_eq!(spatial_ids(&st, &far).len(), 3, "full posting fallback");
}
proptest::proptest! {
#[test]
fn spatial_ids_superset_under_churn(
ops in proptest::collection::vec(
(
0..64i64,
proptest::prop_oneof![
// Clustered: half the inserts land in a tight box.
(0.0f64..1.0, 0.0f64..1.0),
(-5.0f64..5.0, -5.0f64..5.0),
],
proptest::prop_oneof![
proptest::prelude::Just(7203i32),
proptest::prelude::Just(4326)
],
proptest::prelude::any::<bool>(),
),
0..200,
),
) {
let mut st = PointIndex::default();
for (id, (x, y), srid, remove) in ops {
if remove {
point_remove_node(&mut st, id);
} else {
point_insert(&mut st, id, srid, x, y, None);
}
}
st.seal();
assert_eq!(st.tree.size(), st.pts.len());
for seek in [
seek_bbox(7203, -2.0, -2.0, 2.0, 2.0),
seek_bbox(7203, 0.0, 0.0, 0.5, 0.5),
seek_distance(7203, 0.0, 0.0, 500.0),
seek_distance(7203, 0.5, 0.5, 50.0),
] {
assert_superset(&st, &seek);
}
}
#[test]
fn geographic_distance_seek_superset_up_to_half_a_circumference(
pts in proptest::collection::vec((-180.0f64..180.0, -90.0f64..90.0), 1..64),
ox in -180.0f64..180.0,
oy in -90.0f64..90.0,
frac in 0.0f64..1.0,
) {
let mut st = PointIndex::default();
point_insert(&mut st, 0, 4326, 0.0, 90.0, None);
point_insert(&mut st, 1, 4326, 0.0, -90.0, None);
for (i, (x, y)) in pts.iter().enumerate() {
point_insert(&mut st, i as i64 + 2, 4326, *x, *y, None);
}
st.seal();
let max = frac * std::f64::consts::PI * EARTH_RADIUS_METERS;
assert_superset(&st, &seek_distance(4326, ox, oy, max));
}
}
}