Skip to main content

spatialrust_search/
graph.rs

1//! Neighborhood graph construction (k-NN and radius graphs).
2//!
3//! Turns a point cloud into the edge list that graph neural networks consume
4//! (PyG-style `edge_index`): each point becomes a node, with a directed edge to
5//! every neighbor. Built on the KD-tree, so it scales to large clouds.
6
7use spatialrust_core::{HasPositions3, PointCloud, SpatialError, SpatialResult};
8
9use crate::kdtree::KdTree;
10use crate::{NearestNeighborIndex, RadiusSearchIndex};
11
12/// A directed neighborhood graph over a point cloud.
13#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct NeighborGraph {
15    /// Number of nodes (input points).
16    pub num_nodes: usize,
17    /// Directed edges as `[source, target]` index pairs (no self-loops).
18    pub edges: Vec<[u32; 2]>,
19}
20
21impl NeighborGraph {
22    /// Number of directed edges.
23    #[must_use]
24    pub fn num_edges(&self) -> usize {
25        self.edges.len()
26    }
27
28    /// Whether the graph has no edges.
29    #[must_use]
30    pub fn is_empty(&self) -> bool {
31        self.edges.is_empty()
32    }
33}
34
35/// Builds a directed k-nearest-neighbor graph: an edge from every point to each
36/// of its `k` nearest neighbors (excluding itself).
37///
38/// Requests exceeding the cloud size search all points. Equal-distance neighbor
39/// selection and order follow the KD-tree, including duplicate coordinates.
40pub fn knn_graph(cloud: &PointCloud, k: usize) -> SpatialResult<NeighborGraph> {
41    if k == 0 {
42        return Err(SpatialError::InvalidArgument("k must be greater than zero".to_owned()));
43    }
44    let (x, y, z) = cloud.positions3()?;
45    let len = cloud.len();
46    validate_node_count(len)?;
47    if len == 0 {
48        return Ok(NeighborGraph { num_nodes: 0, edges: Vec::new() });
49    }
50    let tree = KdTree::from_slices(x, y, z);
51    let count = k.saturating_add(1).min(len);
52    let mut edges = Vec::with_capacity(len.checked_mul(k.min(len)).unwrap_or(0));
53    for i in 0..len {
54        for neighbor in tree.nearest_k(x[i], y[i], z[i], count) {
55            if neighbor.index != i {
56                edges.push([i as u32, neighbor.index as u32]);
57            }
58        }
59    }
60    Ok(NeighborGraph { num_nodes: len, edges })
61}
62
63/// Builds a directed radius graph: an edge from every point to each other point
64/// within `radius`.
65pub fn radius_graph(cloud: &PointCloud, radius: f32) -> SpatialResult<NeighborGraph> {
66    if radius <= 0.0 || radius.is_nan() {
67        return Err(SpatialError::InvalidArgument("radius must be positive".to_owned()));
68    }
69    let (x, y, z) = cloud.positions3()?;
70    let len = cloud.len();
71    validate_node_count(len)?;
72    if len == 0 {
73        return Ok(NeighborGraph { num_nodes: 0, edges: Vec::new() });
74    }
75    let tree = KdTree::from_slices(x, y, z);
76    let mut edges = Vec::new();
77    for i in 0..len {
78        for neighbor in tree.radius_search(x[i], y[i], z[i], radius) {
79            if neighbor.index != i {
80                edges.push([i as u32, neighbor.index as u32]);
81            }
82        }
83    }
84    Ok(NeighborGraph { num_nodes: len, edges })
85}
86
87/// Builds a k-NN graph using bounded scoped CPU workers (`parallel` feature).
88///
89/// Returns exactly the same edge sequence as [`knn_graph`], including KD-tree
90/// tie selection. One shared tree is built on the caller; contiguous 256-point
91/// query chunks use at most the available CPU parallelism. Fewer than 4,096
92/// points or one available worker run on the caller. Worker-local edge storage
93/// and the final graph scale with edge count; dispatch metadata scales with
94/// workers. Concurrent calls have independent worker budgets.
95#[cfg(feature = "parallel")]
96pub fn knn_graph_parallel(cloud: &PointCloud, k: usize) -> SpatialResult<NeighborGraph> {
97    build_graph(cloud, GraphQuery::Knn(k), crate::parallel_chunked::available_workers())
98}
99
100/// Builds a radius graph using bounded scoped CPU workers (`parallel` feature).
101///
102/// Returns exactly the same edge sequence as [`radius_graph`]. Uses the same
103/// worker, small-input and storage policy as [`knn_graph_parallel`]. Radius
104/// graphs can contain quadratically many edges; parallel execution does not
105/// bound the result size.
106#[cfg(feature = "parallel")]
107pub fn radius_graph_parallel(cloud: &PointCloud, radius: f32) -> SpatialResult<NeighborGraph> {
108    build_graph(cloud, GraphQuery::Radius(radius), crate::parallel_chunked::available_workers())
109}
110
111#[cfg(any(feature = "parallel", test))]
112#[derive(Clone, Copy)]
113enum GraphQuery {
114    Knn(usize),
115    Radius(f32),
116}
117
118fn validate_node_count(len: usize) -> SpatialResult<()> {
119    // The KD-tree's end offsets and graph indices are u32.
120    if u32::try_from(len).is_err() {
121        return Err(SpatialError::InvalidArgument("graph point count exceeds u32::MAX".to_owned()));
122    }
123    Ok(())
124}
125
126#[cfg(any(feature = "parallel", test))]
127fn build_graph(
128    cloud: &PointCloud,
129    query: GraphQuery,
130    _available: usize,
131) -> SpatialResult<NeighborGraph> {
132    match query {
133        GraphQuery::Knn(0) => {
134            return Err(SpatialError::InvalidArgument("k must be greater than zero".to_owned()));
135        }
136        GraphQuery::Radius(radius) if radius <= 0.0 || radius.is_nan() => {
137            return Err(SpatialError::InvalidArgument("radius must be positive".to_owned()));
138        }
139        _ => {}
140    }
141    let (x, y, z) = cloud.positions3()?;
142    let len = cloud.len();
143    validate_node_count(len)?;
144    if len == 0 {
145        return Ok(NeighborGraph { num_nodes: 0, edges: Vec::new() });
146    }
147    let tree = KdTree::from_slices(x, y, z);
148    // Select the query kind outside the per-point loop. A one-worker
149    // parallel call also uses a specialized traversal and one caller range.
150    let edges = match query {
151        GraphQuery::Knn(k) => {
152            let count = k.saturating_add(1).min(len);
153            let capacity = len.checked_mul(k.min(len)).unwrap_or(0);
154            collect_edges(cloud, _available, capacity, |i| tree.nearest_k(x[i], y[i], z[i], count))?
155        }
156        GraphQuery::Radius(radius) => {
157            collect_edges(cloud, _available, 0, |i| tree.radius_search(x[i], y[i], z[i], radius))?
158        }
159    };
160    Ok(NeighborGraph { num_nodes: len, edges })
161}
162
163#[cfg(any(feature = "parallel", test))]
164fn collect_edges<Q>(
165    cloud: &PointCloud,
166    _available: usize,
167    capacity: usize,
168    query: Q,
169) -> SpatialResult<Vec<[u32; 2]>>
170where
171    Q: Fn(usize) -> Vec<crate::Neighbor> + Sync,
172{
173    let query_band = |range: std::ops::Range<usize>, edges: &mut Vec<[u32; 2]>| {
174        for i in range {
175            for neighbor in query(i) {
176                if neighbor.index != i {
177                    edges.push([i as u32, neighbor.index as u32]);
178                }
179            }
180        }
181    };
182    let mut edges = Vec::with_capacity(capacity);
183    #[cfg(feature = "parallel")]
184    if cloud.len() >= crate::PARALLEL_CHUNK_QUERY_MIN_POINTS && _available > 1 {
185        let tensor = cloud.spatial_tensor_chunks(256)?;
186        crate::parallel_chunked::dispatch_chunks(&tensor, _available, &mut edges, query_band);
187        return Ok(edges);
188    }
189    query_band(0..cloud.len(), &mut edges);
190    Ok(edges)
191}
192
193#[cfg(test)]
194mod tests {
195    use super::{knn_graph, radius_graph};
196    use spatialrust_core::{PointCloudBuilder, StandardSchemas};
197
198    fn line(n: usize) -> spatialrust_core::PointCloud {
199        let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
200        for i in 0..n {
201            builder.push_point([i as f32, 0.0, 0.0]).unwrap();
202        }
203        builder.build().unwrap()
204    }
205
206    #[test]
207    fn knn_graph_has_k_edges_per_node() {
208        let cloud = line(10);
209        let graph = knn_graph(&cloud, 2).unwrap();
210        assert_eq!(graph.num_nodes, 10);
211        // Every node has exactly k outgoing edges.
212        assert_eq!(graph.num_edges(), 10 * 2);
213        // No self-loops.
214        assert!(graph.edges.iter().all(|[s, t]| s != t));
215    }
216
217    #[test]
218    fn knn_nearest_neighbor_is_adjacent_on_a_line() {
219        let cloud = line(5);
220        let graph = knn_graph(&cloud, 1).unwrap();
221        // Point 0's single nearest neighbor is point 1.
222        let from_0: Vec<u32> =
223            graph.edges.iter().filter(|[s, _]| *s == 0).map(|[_, t]| *t).collect();
224        assert_eq!(from_0, vec![1]);
225    }
226
227    #[test]
228    fn radius_graph_links_points_within_radius() {
229        let cloud = line(5);
230        // Radius 1.5 reaches the immediate neighbors on each side (spacing 1.0).
231        let graph = radius_graph(&cloud, 1.5).unwrap();
232        // Interior nodes have 2 neighbors, the two ends have 1 each: 3*2 + 2*1 = 8.
233        assert_eq!(graph.num_edges(), 8);
234    }
235
236    #[test]
237    fn rejects_bad_params() {
238        let cloud = line(3);
239        assert!(knn_graph(&cloud, 0).is_err());
240        assert!(radius_graph(&cloud, 0.0).is_err());
241    }
242}
243
244#[cfg(test)]
245#[path = "graph_tests.rs"]
246mod graph_tests;