1use spatialrust_core::{HasPositions3, PointCloud, SpatialError, SpatialResult};
8
9use crate::kdtree::KdTree;
10use crate::{NearestNeighborIndex, RadiusSearchIndex};
11
12#[derive(Clone, Debug, PartialEq, Eq)]
14pub struct NeighborGraph {
15 pub num_nodes: usize,
17 pub edges: Vec<[u32; 2]>,
19}
20
21impl NeighborGraph {
22 #[must_use]
24 pub fn num_edges(&self) -> usize {
25 self.edges.len()
26 }
27
28 #[must_use]
30 pub fn is_empty(&self) -> bool {
31 self.edges.is_empty()
32 }
33}
34
35pub 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
63pub 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#[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#[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 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 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 assert_eq!(graph.num_edges(), 10 * 2);
213 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 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 let graph = radius_graph(&cloud, 1.5).unwrap();
232 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;