oxigeo-algorithms 0.2.2

High-performance SIMD-optimized raster and vector algorithms for OxiGeo - Pure Rust geospatial processing
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
//! Spatial join operations with spatial indexing
//!
//! Efficient spatial joins using R-tree and other spatial indices.

use crate::error::{AlgorithmError, Result};
use oxigeo_core::vector::Point;
use rstar::{AABB, PointDistance, RTree, RTreeObject};

/// Spatial join predicate
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpatialJoinPredicate {
    /// Features intersect
    Intersects,
    /// First feature contains second
    Contains,
    /// First feature is within second
    Within,
    /// Features touch (share boundary)
    Touches,
    /// Features are within distance
    WithinDistance,
}

/// Options for spatial join
#[derive(Debug, Clone)]
pub struct SpatialJoinOptions {
    /// Spatial predicate
    pub predicate: SpatialJoinPredicate,
    /// Distance threshold (for WithinDistance predicate)
    pub distance: f64,
    /// Whether to build spatial index
    pub use_index: bool,
}

impl Default for SpatialJoinOptions {
    fn default() -> Self {
        Self {
            predicate: SpatialJoinPredicate::Intersects,
            distance: 0.0,
            use_index: true,
        }
    }
}

/// Result of spatial join
#[derive(Debug, Clone)]
pub struct SpatialJoinResult {
    /// Pairs of matching indices (left_idx, right_idx)
    pub matches: Vec<(usize, usize)>,
    /// Number of matches
    pub num_matches: usize,
}

/// Indexed point for R-tree
#[derive(Debug, Clone)]
struct IndexedPoint {
    point: Point,
    index: usize,
}

impl RTreeObject for IndexedPoint {
    type Envelope = AABB<[f64; 2]>;

    fn envelope(&self) -> Self::Envelope {
        AABB::from_point([self.point.coord.x, self.point.coord.y])
    }
}

impl PointDistance for IndexedPoint {
    fn distance_2(&self, point: &[f64; 2]) -> f64 {
        let dx = self.point.coord.x - point[0];
        let dy = self.point.coord.y - point[1];
        dx * dx + dy * dy
    }
}

/// Perform spatial join between two point sets
///
/// # Arguments
///
/// * `left_points` - First set of points
/// * `right_points` - Second set of points
/// * `options` - Spatial join options
///
/// # Returns
///
/// Join result with matching pairs
///
/// # Errors
///
/// Returns [`AlgorithmError::UnsupportedOperation`] if `options.predicate` is
/// `Contains`, `Within`, or `Touches` — only `Intersects` and `WithinDistance`
/// are meaningful for point-only joins.
///
/// # Examples
///
/// ```
/// use oxigeo_algorithms::vector::spatial_join::{spatial_join_points, SpatialJoinOptions, SpatialJoinPredicate};
/// use oxigeo_algorithms::Point;
/// # use oxigeo_algorithms::error::Result;
///
/// # fn main() -> Result<()> {
/// let left = vec![
///     Point::new(0.0, 0.0),
///     Point::new(1.0, 1.0),
/// ];
///
/// let right = vec![
///     Point::new(0.1, 0.1),
///     Point::new(10.0, 10.0),
/// ];
///
/// let options = SpatialJoinOptions {
///     predicate: SpatialJoinPredicate::WithinDistance,
///     distance: 0.5,
///     use_index: true,
/// };
///
/// let result = spatial_join_points(&left, &right, &options)?;
/// assert!(result.num_matches >= 1);
/// # Ok(())
/// # }
/// ```
pub fn spatial_join_points(
    left_points: &[Point],
    right_points: &[Point],
    options: &SpatialJoinOptions,
) -> Result<SpatialJoinResult> {
    // Only `Intersects` and `WithinDistance` are meaningful for point-only
    // joins. Previously the other predicates silently produced zero matches
    // (indistinguishable from a legitimate "no matches" result), masking
    // predicate misconfiguration. Reject them explicitly instead.
    match options.predicate {
        SpatialJoinPredicate::Intersects | SpatialJoinPredicate::WithinDistance => {}
        SpatialJoinPredicate::Contains
        | SpatialJoinPredicate::Within
        | SpatialJoinPredicate::Touches => {
            return Err(AlgorithmError::UnsupportedOperation {
                operation: format!(
                    "{:?} predicate on point geometries (only Intersects and WithinDistance are supported)",
                    options.predicate
                ),
            });
        }
    }

    if left_points.is_empty() || right_points.is_empty() {
        return Ok(SpatialJoinResult {
            matches: Vec::new(),
            num_matches: 0,
        });
    }

    let matches = if options.use_index {
        // Build R-tree for right points
        let indexed_points: Vec<IndexedPoint> = right_points
            .iter()
            .enumerate()
            .map(|(idx, point)| IndexedPoint {
                point: point.clone(),
                index: idx,
            })
            .collect();

        let rtree = RTree::bulk_load(indexed_points);

        // Query R-tree for each left point
        let mut all_matches = Vec::new();

        for (left_idx, left_point) in left_points.iter().enumerate() {
            let nearby = match options.predicate {
                SpatialJoinPredicate::WithinDistance => {
                    // Query points within distance
                    let envelope = AABB::from_corners(
                        [
                            left_point.coord.x - options.distance,
                            left_point.coord.y - options.distance,
                        ],
                        [
                            left_point.coord.x + options.distance,
                            left_point.coord.y + options.distance,
                        ],
                    );

                    rtree
                        .locate_in_envelope(envelope)
                        .filter(|indexed| {
                            point_distance(left_point, &indexed.point) <= options.distance
                        })
                        .map(|indexed| indexed.index)
                        .collect::<Vec<_>>()
                }
                SpatialJoinPredicate::Intersects => {
                    // For points, intersects means exactly coincident
                    let mut matches = Vec::new();
                    for indexed in rtree.locate_at_point([left_point.coord.x, left_point.coord.y]) {
                        matches.push(indexed.index);
                    }
                    matches
                }
                _ => {
                    // Other predicates not applicable to points
                    Vec::new()
                }
            };

            for right_idx in nearby {
                all_matches.push((left_idx, right_idx));
            }
        }

        all_matches
    } else {
        // Brute force comparison
        let mut all_matches = Vec::new();

        for (left_idx, left_point) in left_points.iter().enumerate() {
            for (right_idx, right_point) in right_points.iter().enumerate() {
                if matches_predicate(left_point, right_point, options) {
                    all_matches.push((left_idx, right_idx));
                }
            }
        }

        all_matches
    };

    Ok(SpatialJoinResult {
        num_matches: matches.len(),
        matches,
    })
}

/// Check if two points match the join predicate
fn matches_predicate(left: &Point, right: &Point, options: &SpatialJoinOptions) -> bool {
    match options.predicate {
        SpatialJoinPredicate::Intersects => {
            (left.coord.x - right.coord.x).abs() < 1e-10
                && (left.coord.y - right.coord.y).abs() < 1e-10
        }
        SpatialJoinPredicate::WithinDistance => point_distance(left, right) <= options.distance,
        _ => false,
    }
}

/// Calculate Euclidean distance between points
fn point_distance(p1: &Point, p2: &Point) -> f64 {
    let dx = p1.coord.x - p2.coord.x;
    let dy = p1.coord.y - p2.coord.y;
    (dx * dx + dy * dy).sqrt()
}

/// Nearest neighbor search
pub fn nearest_neighbor(query: &Point, points: &[Point]) -> Option<(usize, f64)> {
    let indexed_points: Vec<IndexedPoint> = points
        .iter()
        .enumerate()
        .map(|(idx, point)| IndexedPoint {
            point: point.clone(),
            index: idx,
        })
        .collect();

    if indexed_points.is_empty() {
        return None;
    }

    let rtree = RTree::bulk_load(indexed_points);
    let nearest = rtree.nearest_neighbor([query.coord.x, query.coord.y])?;

    let distance = point_distance(query, &nearest.point);

    Some((nearest.index, distance))
}

/// K-nearest neighbors search
pub fn k_nearest_neighbors(query: &Point, points: &[Point], k: usize) -> Vec<(usize, f64)> {
    let indexed_points: Vec<IndexedPoint> = points
        .iter()
        .enumerate()
        .map(|(idx, point)| IndexedPoint {
            point: point.clone(),
            index: idx,
        })
        .collect();

    if indexed_points.is_empty() {
        return Vec::new();
    }

    let rtree = RTree::bulk_load(indexed_points);

    rtree
        .nearest_neighbor_iter([query.coord.x, query.coord.y])
        .take(k)
        .map(|indexed| {
            let dist = point_distance(query, &indexed.point);
            (indexed.index, dist)
        })
        .collect()
}

/// Range query (all points within distance)
pub fn range_query(query: &Point, points: &[Point], distance: f64) -> Vec<usize> {
    let options = SpatialJoinOptions {
        predicate: SpatialJoinPredicate::WithinDistance,
        distance,
        use_index: true,
    };

    let result = spatial_join_points(std::slice::from_ref(query), points, &options);

    result
        .map(|r| {
            r.matches
                .into_iter()
                .map(|(_, right_idx)| right_idx)
                .collect()
        })
        .unwrap_or_else(|_| Vec::new())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_spatial_join_within_distance() {
        let left = vec![Point::new(0.0, 0.0), Point::new(10.0, 10.0)];

        let right = vec![Point::new(0.1, 0.1), Point::new(5.0, 5.0)];

        let options = SpatialJoinOptions {
            predicate: SpatialJoinPredicate::WithinDistance,
            distance: 0.5,
            use_index: true,
        };

        let result = spatial_join_points(&left, &right, &options);
        assert!(result.is_ok());

        let join_result = result.expect("Join failed");
        assert!(join_result.num_matches >= 1);
    }

    #[test]
    fn test_nearest_neighbor() {
        let points = vec![
            Point::new(0.0, 0.0),
            Point::new(5.0, 5.0),
            Point::new(10.0, 10.0),
        ];

        let query = Point::new(0.1, 0.1);
        let result = nearest_neighbor(&query, &points);

        assert!(result.is_some());

        let (idx, dist) = result.expect("Nearest neighbor failed");
        assert_eq!(idx, 0);
        assert!(dist < 0.2);
    }

    #[test]
    fn test_k_nearest_neighbors() {
        let points = vec![
            Point::new(0.0, 0.0),
            Point::new(1.0, 1.0),
            Point::new(2.0, 2.0),
            Point::new(10.0, 10.0),
        ];

        let query = Point::new(0.0, 0.0);
        let result = k_nearest_neighbors(&query, &points, 2);

        assert_eq!(result.len(), 2);
        assert_eq!(result[0].0, 0); // First is the query point itself
    }

    #[test]
    fn test_range_query() {
        let points = vec![
            Point::new(0.0, 0.0),
            Point::new(0.5, 0.5),
            Point::new(10.0, 10.0),
        ];

        let query = Point::new(0.0, 0.0);
        let result = range_query(&query, &points, 1.0);

        assert!(result.len() >= 2); // Should find points at 0.0 and 0.5
    }

    #[test]
    fn test_point_distance() {
        let p1 = Point::new(0.0, 0.0);
        let p2 = Point::new(3.0, 4.0);

        let dist = point_distance(&p1, &p2);
        assert!((dist - 5.0).abs() < 1e-6);
    }

    #[test]
    fn test_unsupported_predicates_error_not_silent_empty() {
        let left = vec![Point::new(0.0, 0.0), Point::new(1.0, 1.0)];
        let right = vec![Point::new(0.0, 0.0), Point::new(2.0, 2.0)];

        for predicate in [
            SpatialJoinPredicate::Contains,
            SpatialJoinPredicate::Within,
            SpatialJoinPredicate::Touches,
        ] {
            for use_index in [true, false] {
                let options = SpatialJoinOptions {
                    predicate,
                    distance: 0.0,
                    use_index,
                };
                let result = spatial_join_points(&left, &right, &options);
                assert!(
                    matches!(result, Err(AlgorithmError::UnsupportedOperation { .. })),
                    "predicate {predicate:?} (use_index={use_index}) must return \
                     UnsupportedOperation, got {result:?}"
                );
            }
        }
    }

    #[test]
    fn test_supported_predicates_still_ok() {
        let left = vec![Point::new(0.0, 0.0)];
        let right = vec![Point::new(0.0, 0.0)];

        for predicate in [
            SpatialJoinPredicate::Intersects,
            SpatialJoinPredicate::WithinDistance,
        ] {
            for use_index in [true, false] {
                let options = SpatialJoinOptions {
                    predicate,
                    distance: 1.0,
                    use_index,
                };
                let result = spatial_join_points(&left, &right, &options);
                assert!(
                    result.is_ok(),
                    "predicate {predicate:?} (use_index={use_index}) must succeed"
                );
            }
        }
    }
}