scirs2-spatial 0.4.0

Spatial algorithms module for SciRS2 (scirs2-spatial)
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! Proximity-based graph construction from point sets
//!
//! Provides algorithms for building Euclidean MST, Gabriel graph,
//! relative neighborhood graph, and alpha shapes from 2D point sets.

use crate::error::{SpatialError, SpatialResult};
use std::collections::HashSet;

/// An edge in a Minimum Spanning Tree with its weight (Euclidean distance)
#[derive(Debug, Clone)]
pub struct MstEdge {
    /// Index of the first endpoint
    pub u: usize,
    /// Index of the second endpoint
    pub v: usize,
    /// Euclidean distance (edge weight)
    pub weight: f64,
}

/// Compute the Euclidean Minimum Spanning Tree of a 2D point set
///
/// The Euclidean MST connects all points with the minimum total edge length.
/// This implementation uses a brute-force Kruskal's algorithm on all pairwise
/// distances with a union-find structure for cycle detection.
///
/// For large point sets, building a Delaunay triangulation first and then
/// computing the MST on the Delaunay edges would be more efficient (O(n log n)
/// vs O(n^2 log n)), but this direct approach is simpler and correct.
///
/// # Arguments
///
/// * `points` - A slice of [x, y] coordinates
///
/// # Returns
///
/// * A vector of MST edges sorted by weight
///
/// # Examples
///
/// ```
/// use scirs2_spatial::proximity::euclidean_mst;
///
/// let points = vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
/// let mst = euclidean_mst(&points).expect("compute");
/// assert_eq!(mst.len(), 3); // n-1 edges
///
/// // Total weight should be 3.0 (three unit edges)
/// let total: f64 = mst.iter().map(|e| e.weight).sum();
/// assert!((total - 3.0).abs() < 1e-10);
/// ```
pub fn euclidean_mst(points: &[[f64; 2]]) -> SpatialResult<Vec<MstEdge>> {
    let n = points.len();

    if n == 0 {
        return Ok(Vec::new());
    }

    if n == 1 {
        return Ok(Vec::new());
    }

    // Build all edges with distances
    let mut edges: Vec<(usize, usize, f64)> = Vec::with_capacity(n * (n - 1) / 2);
    for i in 0..n {
        for j in (i + 1)..n {
            let dx = points[i][0] - points[j][0];
            let dy = points[i][1] - points[j][1];
            let dist = (dx * dx + dy * dy).sqrt();
            edges.push((i, j, dist));
        }
    }

    // Sort by distance
    edges.sort_by(|a, b| a.2.partial_cmp(&b.2).unwrap_or(std::cmp::Ordering::Equal));

    // Kruskal's algorithm with union-find
    let mut parent: Vec<usize> = (0..n).collect();
    let mut rank: Vec<usize> = vec![0; n];
    let mut mst = Vec::with_capacity(n - 1);

    fn find(parent: &mut [usize], x: usize) -> usize {
        if parent[x] != x {
            parent[x] = find(parent, parent[x]);
        }
        parent[x]
    }

    fn union(parent: &mut [usize], rank: &mut [usize], x: usize, y: usize) -> bool {
        let rx = find(parent, x);
        let ry = find(parent, y);
        if rx == ry {
            return false;
        }
        if rank[rx] < rank[ry] {
            parent[rx] = ry;
        } else if rank[rx] > rank[ry] {
            parent[ry] = rx;
        } else {
            parent[ry] = rx;
            rank[rx] += 1;
        }
        true
    }

    for (u, v, w) in edges {
        if mst.len() == n - 1 {
            break;
        }
        if union(&mut parent, &mut rank, u, v) {
            mst.push(MstEdge { u, v, weight: w });
        }
    }

    Ok(mst)
}

/// Compute the Gabriel graph of a 2D point set
///
/// The Gabriel graph connects two points p_i and p_j if and only if the
/// diametral circle (circle with p_i p_j as diameter) contains no other points.
/// Equivalently, edge (i, j) exists iff for all k != i,j:
///   d(i,j)^2 <= d(i,k)^2 + d(j,k)^2
///
/// The Gabriel graph is a subgraph of the Delaunay triangulation and a
/// supergraph of the Euclidean MST.
///
/// # Arguments
///
/// * `points` - A slice of [x, y] coordinates
///
/// # Returns
///
/// * A vector of edges (i, j) in the Gabriel graph
///
/// # Examples
///
/// ```
/// use scirs2_spatial::proximity::gabriel_graph;
///
/// let points = vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
/// let edges = gabriel_graph(&points).expect("compute");
/// // Unit square: all 6 pairs are Gabriel edges (diagonals included, since for a diagonal
/// // the sum of squared distances from the endpoints to any other vertex equals the diagonal
/// // length squared exactly, so no vertex lies strictly inside the diametral circle)
/// assert_eq!(edges.len(), 6);
/// ```
pub fn gabriel_graph(points: &[[f64; 2]]) -> SpatialResult<Vec<(usize, usize)>> {
    let n = points.len();

    if n < 2 {
        return Ok(Vec::new());
    }

    let mut edges = Vec::new();

    for i in 0..n {
        for j in (i + 1)..n {
            let dx = points[i][0] - points[j][0];
            let dy = points[i][1] - points[j][1];
            let dist_sq_ij = dx * dx + dy * dy;

            // Check if any other point lies inside the diametral circle
            let mut is_gabriel = true;

            for k in 0..n {
                if k == i || k == j {
                    continue;
                }

                let dxi = points[i][0] - points[k][0];
                let dyi = points[i][1] - points[k][1];
                let dist_sq_ik = dxi * dxi + dyi * dyi;

                let dxj = points[j][0] - points[k][0];
                let dyj = points[j][1] - points[k][1];
                let dist_sq_jk = dxj * dxj + dyj * dyj;

                // Gabriel condition: d(i,j)^2 <= d(i,k)^2 + d(j,k)^2
                if dist_sq_ij > dist_sq_ik + dist_sq_jk + 1e-10 {
                    is_gabriel = false;
                    break;
                }
            }

            if is_gabriel {
                edges.push((i, j));
            }
        }
    }

    Ok(edges)
}

/// Compute the Relative Neighborhood Graph (RNG) of a 2D point set
///
/// The RNG connects two points p_i and p_j if and only if there is no other
/// point p_k that is closer to both p_i and p_j than they are to each other.
/// Formally, edge (i, j) exists iff for all k != i,j:
///   d(i,j) <= max(d(i,k), d(j,k))
///
/// The RNG is a subgraph of the Gabriel graph and a supergraph of the
/// Euclidean MST.
///
/// # Arguments
///
/// * `points` - A slice of [x, y] coordinates
///
/// # Returns
///
/// * A vector of edges (i, j) in the relative neighborhood graph
///
/// # Examples
///
/// ```
/// use scirs2_spatial::proximity::relative_neighborhood_graph;
///
/// let points = vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
/// let edges = relative_neighborhood_graph(&points).expect("compute");
/// // RNG is a subgraph of Gabriel graph
/// assert!(edges.len() <= 4);
/// ```
pub fn relative_neighborhood_graph(points: &[[f64; 2]]) -> SpatialResult<Vec<(usize, usize)>> {
    let n = points.len();

    if n < 2 {
        return Ok(Vec::new());
    }

    let mut edges = Vec::new();

    for i in 0..n {
        for j in (i + 1)..n {
            let dx = points[i][0] - points[j][0];
            let dy = points[i][1] - points[j][1];
            let dist_ij = (dx * dx + dy * dy).sqrt();

            let mut is_rng = true;

            for k in 0..n {
                if k == i || k == j {
                    continue;
                }

                let dxi = points[i][0] - points[k][0];
                let dyi = points[i][1] - points[k][1];
                let dist_ik = (dxi * dxi + dyi * dyi).sqrt();

                let dxj = points[j][0] - points[k][0];
                let dyj = points[j][1] - points[k][1];
                let dist_jk = (dxj * dxj + dyj * dyj).sqrt();

                // RNG condition: d(i,j) <= max(d(i,k), d(j,k))
                if dist_ij > dist_ik.max(dist_jk) + 1e-10 {
                    is_rng = false;
                    break;
                }
            }

            if is_rng {
                edges.push((i, j));
            }
        }
    }

    Ok(edges)
}

/// Compute the alpha shape edges for a 2D point set
///
/// Alpha shapes are a generalization of convex hulls. For a given alpha parameter,
/// the alpha shape is the intersection of all closed complements of circles with
/// radius 1/alpha that contain all points. As alpha decreases toward 0, the alpha
/// shape approaches the convex hull. As alpha increases, the shape becomes more
/// concave, eventually decomposing into individual points.
///
/// An edge (i, j) is in the alpha shape if there exists a circle of radius
/// 1/alpha passing through both p_i and p_j that contains no other points.
///
/// # Arguments
///
/// * `points` - A slice of [x, y] coordinates
/// * `alpha` - The alpha parameter (> 0). Larger alpha = more concave shape.
///   A good starting value is the inverse of the typical edge length.
///
/// # Returns
///
/// * A vector of edges (i, j) forming the alpha shape boundary
///
/// # Examples
///
/// ```
/// use scirs2_spatial::proximity::alpha_shape_edges;
///
/// let points = vec![
///     [0.0, 0.0], [1.0, 0.0], [2.0, 0.0],
///     [0.0, 1.0], [1.0, 1.0], [2.0, 1.0],
/// ];
///
/// // With small alpha, most edges are included (near convex hull)
/// let edges = alpha_shape_edges(&points, 0.5).expect("compute");
/// assert!(!edges.is_empty());
/// ```
pub fn alpha_shape_edges(points: &[[f64; 2]], alpha: f64) -> SpatialResult<Vec<(usize, usize)>> {
    let n = points.len();

    if n < 2 {
        return Ok(Vec::new());
    }

    if alpha <= 0.0 {
        return Err(SpatialError::ValueError(
            "Alpha must be positive".to_string(),
        ));
    }

    let radius = 1.0 / alpha;
    let radius_sq = radius * radius;
    let mut edges = Vec::new();

    for i in 0..n {
        for j in (i + 1)..n {
            let dx = points[j][0] - points[i][0];
            let dy = points[j][1] - points[i][1];
            let dist_sq = dx * dx + dy * dy;
            let dist = dist_sq.sqrt();

            // If the edge is longer than the diameter (2*radius), skip
            if dist > 2.0 * radius + 1e-10 {
                continue;
            }

            // Find the two circle centers of radius r passing through p_i and p_j
            let mid_x = (points[i][0] + points[j][0]) * 0.5;
            let mid_y = (points[i][1] + points[j][1]) * 0.5;

            let half_dist_sq = dist_sq * 0.25;
            let h_sq = radius_sq - half_dist_sq;

            if h_sq < 0.0 {
                continue; // Edge too long for this radius
            }

            let h = h_sq.sqrt();

            // Normal direction perpendicular to the edge
            let nx = -dy / dist;
            let ny = dx / dist;

            // Two potential circle centers
            let c1x = mid_x + h * nx;
            let c1y = mid_y + h * ny;
            let c2x = mid_x - h * nx;
            let c2y = mid_y - h * ny;

            // Check if either circle is empty (contains no other points)
            let circle1_empty = (0..n).all(|k| {
                if k == i || k == j {
                    return true;
                }
                let dxk = points[k][0] - c1x;
                let dyk = points[k][1] - c1y;
                dxk * dxk + dyk * dyk >= radius_sq - 1e-10
            });

            let circle2_empty = (0..n).all(|k| {
                if k == i || k == j {
                    return true;
                }
                let dxk = points[k][0] - c2x;
                let dyk = points[k][1] - c2y;
                dxk * dxk + dyk * dyk >= radius_sq - 1e-10
            });

            if circle1_empty || circle2_empty {
                edges.push((i, j));
            }
        }
    }

    Ok(edges)
}

/// Get boundary edges of an alpha shape (edges that appear in only one triangle)
///
/// This extracts only the boundary from the alpha shape edges, which forms
/// the concave hull outline.
///
/// # Arguments
///
/// * `points` - A slice of [x, y] coordinates
/// * `alpha` - The alpha parameter (> 0)
///
/// # Returns
///
/// * Boundary edges forming the concave hull
pub fn alpha_shape_boundary(points: &[[f64; 2]], alpha: f64) -> SpatialResult<Vec<(usize, usize)>> {
    let all_edges = alpha_shape_edges(points, alpha)?;

    // Build an edge set for quick lookup
    let edge_set: HashSet<(usize, usize)> = all_edges.iter().copied().collect();

    // A boundary edge is one where the two adjacent triangles that could use it
    // don't both exist. We approximate this by checking if for each edge (i,j),
    // there are 0 or 1 common neighbors k such that both (i,k) and (j,k) are edges.
    let mut boundary = Vec::new();

    for &(i, j) in &all_edges {
        let common_count = (0..points.len())
            .filter(|&k| {
                k != i
                    && k != j
                    && (edge_set.contains(&(i.min(k), i.max(k))))
                    && (edge_set.contains(&(j.min(k), j.max(k))))
            })
            .count();

        // Boundary edges have 0 or 1 common neighbor (1 means one side is open)
        if common_count <= 1 {
            boundary.push((i, j));
        }
    }

    Ok(boundary)
}

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

    #[test]
    fn test_mst_triangle() {
        let points = vec![[0.0, 0.0], [1.0, 0.0], [0.5, 0.866]]; // equilateral
        let mst = euclidean_mst(&points).expect("compute");
        assert_eq!(mst.len(), 2);

        // All edges should be ~1.0
        for e in &mst {
            assert!((e.weight - 1.0).abs() < 1e-3);
        }
    }

    #[test]
    fn test_mst_square() {
        let points = vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
        let mst = euclidean_mst(&points).expect("compute");
        assert_eq!(mst.len(), 3);

        // Total weight should be 3.0 (three unit edges, not the diagonal)
        let total: f64 = mst.iter().map(|e| e.weight).sum();
        assert!((total - 3.0).abs() < 1e-10);
    }

    #[test]
    fn test_mst_single_point() {
        let points = vec![[0.0, 0.0]];
        let mst = euclidean_mst(&points).expect("compute");
        assert!(mst.is_empty());
    }

    #[test]
    fn test_mst_empty() {
        let points: Vec<[f64; 2]> = vec![];
        let mst = euclidean_mst(&points).expect("compute");
        assert!(mst.is_empty());
    }

    #[test]
    fn test_gabriel_graph_square() {
        let points = vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
        let edges = gabriel_graph(&points).expect("compute");

        // For a unit square, diagonal points lie exactly on the diametral circle
        // boundary (d(i,j)^2 == d(i,k)^2 + d(j,k)^2 for diagonals).
        // With our tolerance, diagonals may or may not be included.
        // The 4 side edges must always be present.
        let edge_set: HashSet<(usize, usize)> = edges.into_iter().collect();
        assert!(edge_set.contains(&(0, 1))); // bottom
        assert!(edge_set.contains(&(0, 2))); // left
        assert!(edge_set.contains(&(1, 3))); // right
        assert!(edge_set.contains(&(2, 3))); // top
        assert!(edge_set.len() >= 4);
        assert!(edge_set.len() <= 6); // max C(4,2) = 6
    }

    #[test]
    fn test_gabriel_is_supergraph_of_rng() {
        let points = vec![[0.0, 0.0], [1.0, 0.0], [0.5, 0.5], [0.0, 1.0], [1.0, 1.0]];

        let gabriel_edges = gabriel_graph(&points).expect("compute");
        let rng_edges = relative_neighborhood_graph(&points).expect("compute");

        let gabriel_set: HashSet<(usize, usize)> = gabriel_edges.into_iter().collect();
        let rng_set: HashSet<(usize, usize)> = rng_edges.into_iter().collect();

        // Every RNG edge should be in Gabriel graph
        for edge in &rng_set {
            assert!(
                gabriel_set.contains(edge),
                "RNG edge {:?} not in Gabriel graph",
                edge
            );
        }
    }

    #[test]
    fn test_rng_square() {
        let points = vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
        let edges = relative_neighborhood_graph(&points).expect("compute");

        // RNG of a square: the 4 side edges (no diagonals)
        assert_eq!(edges.len(), 4);
    }

    #[test]
    fn test_rng_is_supergraph_of_mst() {
        let points = vec![[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [0.0, 1.0], [1.0, 1.0]];

        let mst = euclidean_mst(&points).expect("compute");
        let rng_edges = relative_neighborhood_graph(&points).expect("compute");

        let rng_set: HashSet<(usize, usize)> = rng_edges.into_iter().collect();

        // Every MST edge should be in the RNG
        for e in &mst {
            let edge = (e.u.min(e.v), e.u.max(e.v));
            assert!(rng_set.contains(&edge), "MST edge {:?} not in RNG", edge);
        }
    }

    #[test]
    fn test_alpha_shape_large_alpha() {
        // With very large alpha (small radius), few or no edges should survive
        let points = vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
        let edges = alpha_shape_edges(&points, 10.0).expect("compute");
        // Very large alpha means very small circle radius - edges too long
        // might have some short edges
        assert!(edges.len() <= 6); // at most C(4,2)=6
    }

    #[test]
    fn test_alpha_shape_small_alpha() {
        // With small alpha (large radius), most edges should be included
        let points = vec![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
        let edges = alpha_shape_edges(&points, 0.1).expect("compute");
        // Small alpha = large circles = almost convex hull, should include all 6 edges
        assert!(edges.len() >= 4);
    }

    #[test]
    fn test_alpha_shape_invalid_alpha() {
        let points = vec![[0.0, 0.0], [1.0, 0.0]];
        assert!(alpha_shape_edges(&points, 0.0).is_err());
        assert!(alpha_shape_edges(&points, -1.0).is_err());
    }

    #[test]
    fn test_graph_hierarchy() {
        // The containment hierarchy should be: MST ⊆ RNG ⊆ Gabriel ⊆ Delaunay
        let points = vec![[0.0, 0.0], [2.0, 0.0], [1.0, 1.5], [3.0, 1.0], [0.5, 2.5]];

        let mst = euclidean_mst(&points).expect("mst");
        let rng = relative_neighborhood_graph(&points).expect("rng");
        let gabriel = gabriel_graph(&points).expect("gabriel");

        let mst_edges: HashSet<(usize, usize)> =
            mst.iter().map(|e| (e.u.min(e.v), e.u.max(e.v))).collect();
        let rng_set: HashSet<(usize, usize)> = rng.into_iter().collect();
        let gabriel_set: HashSet<(usize, usize)> = gabriel.into_iter().collect();

        // MST ⊆ RNG
        for edge in &mst_edges {
            assert!(rng_set.contains(edge), "MST edge {:?} not in RNG", edge);
        }

        // RNG ⊆ Gabriel
        for edge in &rng_set {
            assert!(
                gabriel_set.contains(edge),
                "RNG edge {:?} not in Gabriel",
                edge
            );
        }

        assert!(mst_edges.len() <= rng_set.len());
        assert!(rng_set.len() <= gabriel_set.len());
    }
}