sphereql-index 0.1.0-alpha

Spatial indexing and queries for sphereQL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
use crate::item::{SpatialItem, SpatialQueryResult};
use sphereql_core::{Band, Cap, Contains, SphericalPoint, Wedge, angular_distance};
use std::collections::HashMap;
use std::f64::consts::{PI, TAU};

/// Angular sector index that partitions S² into a grid of theta × phi sectors.
///
/// Each sector covers a rectangular region in (theta, phi) space. Items are
/// placed in the sector containing their angular position, enabling fast
/// spatial queries by scanning only the sectors that overlap the query region.
pub struct SectorIndex<T: SpatialItem> {
    theta_divisions: usize,
    phi_divisions: usize,
    sectors: Vec<Vec<T>>,
    item_map: HashMap<T::Id, usize>,
}

impl<T: SpatialItem> SectorIndex<T> {
    pub fn new(theta_divisions: usize, phi_divisions: usize) -> Self {
        assert!(theta_divisions >= 1, "theta_divisions must be >= 1");
        assert!(phi_divisions >= 1, "phi_divisions must be >= 1");

        let total = theta_divisions * phi_divisions;
        let mut sectors = Vec::with_capacity(total);
        for _ in 0..total {
            sectors.push(Vec::new());
        }

        Self {
            theta_divisions,
            phi_divisions,
            sectors,
            item_map: HashMap::new(),
        }
    }

    pub fn insert(&mut self, item: T) {
        let pos = item.position();
        let idx = self.sector_index(pos.theta, pos.phi);
        self.item_map.insert(item.id().clone(), idx);
        self.sectors[idx].push(item);
    }

    pub fn remove(&mut self, id: &T::Id) -> Option<T> {
        let sector_idx = self.item_map.remove(id)?;
        let sector = &mut self.sectors[sector_idx];
        let pos = sector.iter().position(|item| item.id() == id)?;
        Some(sector.swap_remove(pos))
    }

    pub fn get(&self, id: &T::Id) -> Option<&T> {
        let &sector_idx = self.item_map.get(id)?;
        self.sectors[sector_idx].iter().find(|item| item.id() == id)
    }

    pub fn len(&self) -> usize {
        self.item_map.len()
    }

    pub fn is_empty(&self) -> bool {
        self.item_map.is_empty()
    }

    pub fn query_band(&self, band: &Band) -> SpatialQueryResult<T> {
        let mut items = Vec::new();
        let mut total_scanned = 0;

        for phi_idx in 0..self.phi_divisions {
            let (phi_min, phi_max) = self.phi_range(phi_idx);
            if phi_max < band.phi_min || phi_min > band.phi_max {
                continue;
            }
            for theta_idx in 0..self.theta_divisions {
                let sector_idx = theta_idx * self.phi_divisions + phi_idx;
                for item in &self.sectors[sector_idx] {
                    total_scanned += 1;
                    if band.contains(item.position()) {
                        items.push(item.clone());
                    }
                }
            }
        }

        SpatialQueryResult {
            items,
            total_scanned,
        }
    }

    pub fn query_wedge(&self, wedge: &Wedge) -> SpatialQueryResult<T> {
        let mut items = Vec::new();
        let mut total_scanned = 0;

        for theta_idx in 0..self.theta_divisions {
            let (t_min, t_max) = self.theta_range(theta_idx);
            if !self.theta_range_overlaps_wedge(t_min, t_max, wedge) {
                continue;
            }
            for phi_idx in 0..self.phi_divisions {
                let sector_idx = theta_idx * self.phi_divisions + phi_idx;
                for item in &self.sectors[sector_idx] {
                    total_scanned += 1;
                    if wedge.contains(item.position()) {
                        items.push(item.clone());
                    }
                }
            }
        }

        SpatialQueryResult {
            items,
            total_scanned,
        }
    }

    pub fn query_cone(
        &self,
        cone_center: &SphericalPoint,
        half_angle: f64,
    ) -> SpatialQueryResult<T> {
        let mut items = Vec::new();
        let mut total_scanned = 0;
        let threshold = half_angle + self.sector_diagonal();
        let center_unit = SphericalPoint::new_unchecked(1.0, cone_center.theta, cone_center.phi);

        for sector_idx in 0..self.sectors.len() {
            let center = self.sector_center(sector_idx);
            if angular_distance(&center_unit, &center) > threshold {
                continue;
            }
            for item in &self.sectors[sector_idx] {
                total_scanned += 1;
                let item_unit =
                    SphericalPoint::new_unchecked(1.0, item.position().theta, item.position().phi);
                if angular_distance(&center_unit, &item_unit) <= half_angle {
                    items.push(item.clone());
                }
            }
        }

        SpatialQueryResult {
            items,
            total_scanned,
        }
    }

    pub fn query_cap(&self, cap: &Cap) -> SpatialQueryResult<T> {
        let mut items = Vec::new();
        let mut total_scanned = 0;
        let threshold = cap.half_angle + self.sector_diagonal();
        let center_unit = SphericalPoint::new_unchecked(1.0, cap.center.theta, cap.center.phi);

        for sector_idx in 0..self.sectors.len() {
            let center = self.sector_center(sector_idx);
            if angular_distance(&center_unit, &center) > threshold {
                continue;
            }
            for item in &self.sectors[sector_idx] {
                total_scanned += 1;
                if cap.contains(item.position()) {
                    items.push(item.clone());
                }
            }
        }

        SpatialQueryResult {
            items,
            total_scanned,
        }
    }

    /// Returns all items from sectors whose angular center is within
    /// `proxy_threshold` cosine proxy distance of the query direction.
    ///
    /// Cosine proxy = `1 - dot(a, b)` for unit vectors, monotone with
    /// angular distance. The sector's angular diagonal is added as margin
    /// to ensure no edge items are missed.
    ///
    /// This is the fast path for sector-accelerated k-NN: it does only
    /// 3 muls + 2 adds per sector center (no trig), and returns references
    /// without cloning items.
    pub fn items_in_nearby_sectors<'a>(
        &'a self,
        query_cart: &[f64; 3],
        proxy_threshold: f64,
    ) -> Vec<&'a T> {
        let sector_margin = 1.0 - self.sector_diagonal().cos();
        let adjusted = proxy_threshold + sector_margin;
        let mut items = Vec::new();

        for sector_idx in 0..self.sectors.len() {
            let center = self.sector_center(sector_idx);
            let center_cart = center.unit_cartesian();
            let dot = query_cart[0] * center_cart[0]
                + query_cart[1] * center_cart[1]
                + query_cart[2] * center_cart[2];
            let proxy = 1.0 - dot.clamp(-1.0, 1.0);

            if proxy <= adjusted {
                items.extend(self.sectors[sector_idx].iter());
            }
        }

        items
    }

    pub fn all_items(&self) -> Vec<&T> {
        self.sectors.iter().flat_map(|s| s.iter()).collect()
    }

    fn sector_index(&self, theta: f64, phi: f64) -> usize {
        let theta_idx = ((theta / TAU) * self.theta_divisions as f64).floor() as usize;
        let phi_idx = ((phi / PI) * self.phi_divisions as f64).floor() as usize;

        let theta_idx = theta_idx.min(self.theta_divisions - 1);
        let phi_idx = phi_idx.min(self.phi_divisions - 1);

        theta_idx * self.phi_divisions + phi_idx
    }

    fn theta_range(&self, theta_idx: usize) -> (f64, f64) {
        let step = TAU / self.theta_divisions as f64;
        (theta_idx as f64 * step, (theta_idx + 1) as f64 * step)
    }

    fn phi_range(&self, phi_idx: usize) -> (f64, f64) {
        let step = PI / self.phi_divisions as f64;
        (phi_idx as f64 * step, (phi_idx + 1) as f64 * step)
    }

    pub(crate) fn sector_center(&self, sector_idx: usize) -> SphericalPoint {
        let theta_idx = sector_idx / self.phi_divisions;
        let phi_idx = sector_idx % self.phi_divisions;

        let (t_min, t_max) = self.theta_range(theta_idx);
        let (p_min, p_max) = self.phi_range(phi_idx);

        SphericalPoint::new_unchecked(1.0, (t_min + t_max) / 2.0, (p_min + p_max) / 2.0)
    }

    /// Conservative upper bound on the angular diagonal of a single sector.
    ///
    /// Treats the theta and phi angular extents as legs of a right triangle
    /// on the sphere. Overestimates for large sectors, which is the safe
    /// direction for candidate pruning.
    /// Conservative upper bound on the angular diagonal of a single sector,
    /// accounting for the latitude-dependent shrinkage of theta arcs.
    ///
    /// Uses the equatorial sin(phi)=1 as worst case, since this is a global
    /// bound. Near-pole sectors have smaller effective diagonals, so this
    /// overestimates for them — safe for candidate pruning.
    pub(crate) fn sector_diagonal(&self) -> f64 {
        let d_theta = TAU / self.theta_divisions as f64;
        let d_phi = PI / self.phi_divisions as f64;
        (d_theta * d_theta + d_phi * d_phi).sqrt()
    }

    fn theta_range_overlaps_wedge(&self, t_min: f64, t_max: f64, wedge: &Wedge) -> bool {
        if wedge.theta_min <= wedge.theta_max {
            t_max >= wedge.theta_min && t_min <= wedge.theta_max
        } else {
            // Wrapping wedge: overlaps if sector is in the high range OR the low range
            t_max >= wedge.theta_min || t_min <= wedge.theta_max
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::f64::consts::{FRAC_PI_2, FRAC_PI_4};
    #[derive(Debug, Clone)]
    struct TestItem {
        id: u32,
        pos: SphericalPoint,
    }

    impl SpatialItem for TestItem {
        type Id = u32;
        fn id(&self) -> &u32 {
            &self.id
        }
        fn position(&self) -> &SphericalPoint {
            &self.pos
        }
    }

    fn item(id: u32, theta: f64, phi: f64) -> TestItem {
        TestItem {
            id,
            pos: SphericalPoint::new_unchecked(1.0, theta, phi),
        }
    }

    #[test]
    fn insert_and_get() {
        let mut index = SectorIndex::new(4, 4);
        index.insert(item(1, 0.5, 0.5));
        index.insert(item(2, 3.0, 1.5));

        assert_eq!(index.len(), 2);
        assert!(!index.is_empty());
        assert!(index.get(&1).is_some());
        assert!(index.get(&2).is_some());
        assert!(index.get(&99).is_none());
    }

    #[test]
    fn correct_sector_placement() {
        let mut index = SectorIndex::new(4, 2);
        let a = item(1, 0.1, 0.1);
        let b = item(2, FRAC_PI_2 + 0.1, FRAC_PI_2 + 0.1);

        index.insert(a);
        index.insert(b);

        assert_eq!(index.sectors[0].len(), 1);
        assert_eq!(index.sectors[0][0].id, 1);
        assert_eq!(index.sectors[3].len(), 1);
        assert_eq!(index.sectors[3][0].id, 2);
    }

    #[test]
    fn remove_item() {
        let mut index = SectorIndex::new(4, 4);
        index.insert(item(1, 0.5, 0.5));
        index.insert(item(2, 0.5, 0.5));

        let removed = index.remove(&1);
        assert!(removed.is_some());
        assert_eq!(removed.unwrap().id, 1);
        assert_eq!(index.len(), 1);
        assert!(index.get(&1).is_none());
        assert!(index.get(&2).is_some());
    }

    #[test]
    fn remove_nonexistent() {
        let mut index: SectorIndex<TestItem> = SectorIndex::new(4, 4);
        assert!(index.remove(&99).is_none());
    }

    #[test]
    fn query_band_filters_by_phi() {
        let mut index = SectorIndex::new(4, 8);
        index.insert(item(1, 1.0, 0.3));
        index.insert(item(2, 2.0, FRAC_PI_2));
        index.insert(item(3, 3.0, PI - 0.1));

        let band = Band::new(FRAC_PI_4, 3.0 * FRAC_PI_4).unwrap();
        let result = index.query_band(&band);

        let ids: Vec<u32> = result.items.iter().map(|i| i.id).collect();
        assert!(ids.contains(&2));
        assert!(!ids.contains(&1));
        assert!(!ids.contains(&3));
    }

    #[test]
    fn query_band_skips_sectors() {
        let mut index = SectorIndex::new(4, 8);
        for i in 0..100 {
            index.insert(item(i, (i as f64 * 0.06) % TAU, 0.05));
        }
        index.insert(item(999, 1.0, FRAC_PI_2));

        let band = Band::new(FRAC_PI_4, 3.0 * FRAC_PI_4).unwrap();
        let result = index.query_band(&band);

        assert_eq!(result.items.len(), 1);
        assert!(result.total_scanned < index.len());
    }

    #[test]
    fn query_wedge_filters_by_theta() {
        let mut index = SectorIndex::new(8, 4);
        index.insert(item(1, 0.5, FRAC_PI_2));
        index.insert(item(2, 3.0, FRAC_PI_2));
        index.insert(item(3, 5.5, FRAC_PI_2));

        let wedge = Wedge::new(0.2, 1.0).unwrap();
        let result = index.query_wedge(&wedge);

        let ids: Vec<u32> = result.items.iter().map(|i| i.id).collect();
        assert!(ids.contains(&1));
        assert!(!ids.contains(&2));
        assert!(!ids.contains(&3));
    }

    #[test]
    fn query_wedge_wraparound() {
        let mut index = SectorIndex::new(8, 4);
        index.insert(item(1, 6.0, FRAC_PI_2));
        index.insert(item(2, 0.1, FRAC_PI_2));
        index.insert(item(3, 3.0, FRAC_PI_2));

        let wedge = Wedge::new(5.5, 0.3).unwrap();
        let result = index.query_wedge(&wedge);

        let ids: Vec<u32> = result.items.iter().map(|i| i.id).collect();
        assert!(ids.contains(&1));
        assert!(ids.contains(&2));
        assert!(!ids.contains(&3));
    }

    #[test]
    fn query_cone_returns_nearby_items() {
        let mut index = SectorIndex::new(8, 8);
        let center = SphericalPoint::new_unchecked(1.0, 1.0, FRAC_PI_2);

        index.insert(item(1, 1.0, FRAC_PI_2));
        index.insert(item(2, 1.05, FRAC_PI_2));
        index.insert(item(3, 4.0, FRAC_PI_2));

        let result = index.query_cone(&center, 0.2);

        let ids: Vec<u32> = result.items.iter().map(|i| i.id).collect();
        assert!(ids.contains(&1));
        assert!(ids.contains(&2));
        assert!(!ids.contains(&3));
    }

    #[test]
    fn query_cone_skips_distant_sectors() {
        let mut index = SectorIndex::new(16, 16);
        for i in 0..50 {
            let theta = PI + (i as f64 * 0.02);
            index.insert(item(i, theta, FRAC_PI_2));
        }
        index.insert(item(999, 0.1, FRAC_PI_4));

        let center = SphericalPoint::new_unchecked(1.0, 0.1, FRAC_PI_4);
        let result = index.query_cone(&center, 0.3);

        assert_eq!(result.items.len(), 1);
        assert!(result.total_scanned < index.len());
    }

    #[test]
    fn query_cap() {
        let mut index = SectorIndex::new(8, 8);
        index.insert(item(1, 0.5, 0.5));
        index.insert(item(2, 0.6, 0.5));
        index.insert(item(3, 3.5, 2.5));

        let cap = Cap::new(SphericalPoint::new_unchecked(1.0, 0.5, 0.5), 0.3).unwrap();
        let result = index.query_cap(&cap);

        let ids: Vec<u32> = result.items.iter().map(|i| i.id).collect();
        assert!(ids.contains(&1));
        assert!(ids.contains(&2));
        assert!(!ids.contains(&3));
    }

    #[test]
    fn all_items_returns_everything() {
        let mut index = SectorIndex::new(4, 4);
        index.insert(item(1, 0.5, 0.5));
        index.insert(item(2, 3.0, 1.5));
        index.insert(item(3, 5.0, 2.5));

        let all = index.all_items();
        assert_eq!(all.len(), 3);
    }

    #[test]
    fn single_sector_index() {
        let mut index = SectorIndex::new(1, 1);
        index.insert(item(1, 0.0, 0.0));
        index.insert(item(2, 3.0, FRAC_PI_2));
        index.insert(item(3, 5.0, PI));

        assert_eq!(index.len(), 3);
        assert_eq!(index.sectors.len(), 1);
        assert_eq!(index.sectors[0].len(), 3);

        let band = Band::new(FRAC_PI_4, 3.0 * FRAC_PI_4).unwrap();
        let result = index.query_band(&band);
        assert_eq!(result.items.len(), 1);
        assert_eq!(result.items[0].id, 2);
    }

    #[test]
    fn items_at_sector_boundaries() {
        let mut index = SectorIndex::new(4, 4);
        index.insert(item(1, 0.0, PI));
        index.insert(item(2, TAU - 0.001, FRAC_PI_2));

        assert_eq!(index.len(), 2);
        assert!(index.get(&1).is_some());
        assert!(index.get(&2).is_some());
    }

    #[test]
    fn empty_index() {
        let index: SectorIndex<TestItem> = SectorIndex::new(4, 4);
        assert!(index.is_empty());
        assert_eq!(index.len(), 0);
        assert!(index.all_items().is_empty());
    }

    #[test]
    #[should_panic(expected = "theta_divisions must be >= 1")]
    fn zero_theta_divisions_panics() {
        SectorIndex::<TestItem>::new(0, 4);
    }

    #[test]
    #[should_panic(expected = "phi_divisions must be >= 1")]
    fn zero_phi_divisions_panics() {
        SectorIndex::<TestItem>::new(4, 0);
    }

    #[test]
    fn items_in_nearby_sectors_returns_local_items() {
        let mut index = SectorIndex::new(8, 8);
        index.insert(item(1, 0.5, FRAC_PI_2));
        index.insert(item(2, PI + 0.5, FRAC_PI_2));

        let query_point = SphericalPoint::new_unchecked(1.0, 0.5, FRAC_PI_2);
        let query_cart = query_point.unit_cartesian();

        let results = index.items_in_nearby_sectors(&query_cart, 0.5);
        let ids: Vec<u32> = results.iter().map(|i| i.id).collect();
        assert!(ids.contains(&1));
        assert!(!ids.contains(&2));
    }
}