Skip to main content

scirs2_spatial/
lib.rs

1#![allow(unreachable_code)]
2#![allow(unused_mut)]
3#![allow(missing_docs)]
4#![allow(for_loops_over_fallibles)]
5#![allow(unreachable_patterns)]
6#![allow(unused_assignments)]
7#![allow(unused_variables)]
8#![allow(private_interfaces)]
9#![allow(clippy::must_use_unit)]
10#![allow(clippy::len_without_is_empty)]
11#![allow(clippy::missing_safety_doc)]
12#![allow(clippy::needless_range_loop)]
13#![allow(clippy::doc_lazy_continuation)]
14#![allow(clippy::borrowed_box)]
15#![allow(clippy::unused_must_use)]
16#![allow(clippy::should_implement_trait)]
17#![allow(clippy::doc_list_overindent)]
18#![allow(clippy::doc_overindented_list_items)]
19#![allow(unused_must_use)]
20//! # SciRS2 Spatial - Spatial Algorithms and Data Structures
21//!
22//! **scirs2-spatial** provides comprehensive spatial algorithms modeled after SciPy's `spatial` module,
23//! offering distance metrics, KD-trees, ball trees, Delaunay triangulation, convex hulls, Voronoi diagrams,
24//! and path planning with SIMD acceleration and parallel processing.
25//!
26//! ## 🎯 Key Features
27//!
28//! - **SciPy Compatibility**: Drop-in replacement for `scipy.spatial` functions
29//! - **Distance Metrics**: 20+ metrics (Euclidean, Manhattan, Minkowski, cosine, etc.)
30//! - **Spatial Trees**: KD-tree and ball tree for efficient nearest neighbor queries
31//! - **Computational Geometry**: Delaunay triangulation, Voronoi diagrams, convex hulls
32//! - **Set Distances**: Hausdorff, Wasserstein (Earth Mover's Distance)
33//! - **Path Planning**: A*, RRT, visibility graphs for robotics/navigation
34//! - **Performance**: SIMD-accelerated distance computations, parallel queries
35//!
36//! ## 📦 Module Overview
37//!
38//! | SciRS2 Module | SciPy Equivalent | Description |
39//! |---------------|------------------|-------------|
40//! | `distance` | `scipy.spatial.distance` | Distance metrics and matrices |
41//! | `KDTree` | `scipy.spatial.KDTree` | K-dimensional tree for nearest neighbors |
42//! | `cKDTree` | `scipy.spatial.cKDTree` | Optimized KD-tree (C-accelerated) |
43//! | `ConvexHull` | `scipy.spatial.ConvexHull` | Convex hull computation |
44//! | `Delaunay` | `scipy.spatial.Delaunay` | Delaunay triangulation |
45//! | `Voronoi` | `scipy.spatial.Voronoi` | Voronoi diagram |
46//! | `transform` | `scipy.spatial.transform` | Rotation and transformation utilities |
47//!
48//! ## 🚀 Quick Start
49//!
50//! ```toml
51//! [dependencies]
52//! scirs2-spatial = "0.4.4"
53//! ```
54//!
55//! ```rust
56//! use scirs2_spatial::{KDTree, distance};
57//! use scirs2_core::ndarray::array;
58//!
59//! // KD-Tree for nearest neighbor search
60//! let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
61//! let tree = KDTree::new(&points).unwrap();
62//! let (indices, dists) = tree.query(&[0.5, 0.5], 2).unwrap();
63//!
64//! // Distance computation
65//! let d = distance::euclidean(&[1.0, 2.0], &[4.0, 6.0]);
66//! ```
67//!
68//! ## 🔒 Version: 0.4.4 (March 27, 2026)
69//
70// ## Features
71//
72// * Efficient nearest-neighbor queries with KD-Tree and Ball Tree data structures
73// * Comprehensive set of distance metrics (Euclidean, Manhattan, Minkowski, etc.)
74// * Distance matrix computations (similar to SciPy's cdist and pdist)
75// * Convex hull computation using the Qhull library
76// * Delaunay triangulation for 2D and higher dimensions
77// * Customizable distance metrics for spatial data structures
78// * Advanced query capabilities (k-nearest neighbors, radius search)
79// * Set-based distances (Hausdorff, Wasserstein)
80// * Polygon operations (point-in-polygon, area, centroid)
81// * Path planning algorithms (A*, RRT, visibility graphs)
82// * **Advanced MODE: Revolutionary Computing Paradigms** - Quantum-neuromorphic fusion, next-gen GPU architectures, AI-driven optimization, extreme performance beyond current limits
83//
84// ## Examples
85//
86// ### Distance Metrics
87//
88// ```
89// use scirs2_spatial::distance::euclidean;
90//
91// let point1 = &[1.0, 2.0, 3.0];
92// let point2 = &[4.0, 5.0, 6.0];
93//
94// let dist = euclidean(point1, point2);
95// println!("Euclidean distance: {}", dist);
96// ```
97//
98// ### KD-Tree for Nearest Neighbor Searches
99//
100// ```
101// use scirs2_spatial::KDTree;
102// use scirs2_core::ndarray::array;
103//
104// // Create points
105// let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
106//
107// // Build KD-Tree
108// let kdtree = KDTree::new(&points).unwrap();
109//
110// // Find 2 nearest neighbors to [0.5, 0.5]
111// let (indices, distances) = kdtree.query(&[0.5, 0.5], 2).unwrap();
112// println!("Indices of 2 nearest points: {:?}", indices);
113// println!("Distances to 2 nearest points: {:?}", distances);
114//
115// // Find all points within radius 0.7
116// let (idx_radius, dist_radius) = kdtree.query_radius(&[0.5, 0.5], 0.7).unwrap();
117// println!("Found {} points within radius 0.7", idx_radius.len());
118// ```
119//
120// ### Distance Matrices
121//
122// ```
123// use scirs2_spatial::distance::{pdist, euclidean};
124// use scirs2_core::ndarray::array;
125//
126// // Create points
127// let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
128//
129// // Calculate pairwise distance matrix
130// let dist_matrix = pdist(&points, euclidean);
131// println!("Distance matrix shape: {:?}", dist_matrix.shape());
132// ```
133//
134// ### Convex Hull
135//
136// ```
137// use scirs2_spatial::convex_hull::ConvexHull;
138// use scirs2_core::ndarray::array;
139//
140// // Create points
141// let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [0.5, 0.5]];
142//
143// // Compute convex hull
144// let hull = ConvexHull::new(&points.view()).unwrap();
145//
146// // Get the hull vertices
147// let vertices = hull.vertices();
148// println!("Hull vertices: {:?}", vertices);
149//
150// // Check if a point is inside the hull
151// let is_inside = hull.contains(&[0.25, 0.25]).unwrap();
152// println!("Is point [0.25, 0.25] inside? {}", is_inside);
153// ```
154//
155// ### Delaunay Triangulation
156//
157// ```
158// use scirs2_spatial::delaunay::Delaunay;
159// use scirs2_core::ndarray::array;
160//
161// // Create points
162// let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
163//
164// // Compute Delaunay triangulation
165// let tri = Delaunay::new(&points).unwrap();
166//
167// // Get the simplices (triangles in 2D)
168// let simplices = tri.simplices();
169// println!("Triangles: {:?}", simplices);
170//
171// // Find which triangle contains a point
172// if let Some(idx) = tri.find_simplex(&[0.25, 0.25]) {
173//     println!("Point [0.25, 0.25] is in triangle {}", idx);
174// }
175// ```
176//
177// ### Alpha Shapes
178//
179// ```
180// use scirs2_spatial::AlphaShape;
181// use scirs2_core::ndarray::array;
182//
183// // Create a point set with some outliers
184// let points = array![
185//     [0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0],  // Square corners
186//     [0.5, 0.5],                                        // Interior point
187//     [2.0, 0.5], [3.0, 0.5]                            // Outliers
188// ];
189//
190// // Compute alpha shape with different alpha values
191// let alpha_small = AlphaShape::new(&points, 0.3).unwrap();
192// let alpha_large = AlphaShape::new(&points, 1.5).unwrap();
193//
194// // Get boundary (edges in 2D)
195// let boundary_small = alpha_small.boundary();
196// let boundary_large = alpha_large.boundary();
197//
198// println!("Small alpha boundary edges: {}", boundary_small.len());
199// println!("Large alpha boundary edges: {}", boundary_large.len());
200//
201// // Find optimal alpha automatically
202// let (optimal_alpha, optimalshape) = AlphaShape::find_optimal_alpha(&points, "area").unwrap();
203// println!("Optimal alpha: {:.3}", optimal_alpha);
204// println!("Shape area: {:.3}", optimalshape.measure().unwrap());
205// ```
206//
207// ### Halfspace Intersection
208//
209// ```
210// use scirs2_spatial::halfspace::{HalfspaceIntersection, Halfspace};
211// use scirs2_core::ndarray::array;
212//
213// // Define halfspaces for a unit square: x ≥ 0, y ≥ 0, x ≤ 1, y ≤ 1
214// let halfspaces = vec![
215//     Halfspace::new(array![-1.0, 0.0], 0.0),   // -x ≤ 0  =>  x ≥ 0
216//     Halfspace::new(array![0.0, -1.0], 0.0),   // -y ≤ 0  =>  y ≥ 0
217//     Halfspace::new(array![1.0, 0.0], 1.0),    //  x ≤ 1
218//     Halfspace::new(array![0.0, 1.0], 1.0),    //  y ≤ 1
219// ];
220//
221// let intersection = HalfspaceIntersection::new(&halfspaces, None).unwrap();
222//
223// // Get the vertices of the resulting polytope
224// let vertices = intersection.vertices();
225// println!("Polytope has {} vertices", vertices.nrows());
226//
227// // Check properties
228// println!("Is bounded: {}", intersection.is_bounded());
229// println!("Volume/Area: {:.3}", intersection.volume().unwrap());
230// ```
231//
232// ### Boolean Operations on Polygons
233//
234// ```
235// use scirs2_spatial::boolean_ops::{polygon_union, polygon_intersection, polygon_difference};
236// use scirs2_core::ndarray::array;
237//
238// // Define two overlapping squares
239// let poly1 = array![
240//     [0.0, 0.0],
241//     [2.0, 0.0],
242//     [2.0, 2.0],
243//     [0.0, 2.0]
244// ];
245//
246// let poly2 = array![
247//     [1.0, 1.0],
248//     [3.0, 1.0],
249//     [3.0, 3.0],
250//     [1.0, 3.0]
251// ];
252//
253// // Compute union
254// let union_result = polygon_union(&poly1.view(), &poly2.view()).unwrap();
255// println!("Union has {} vertices", union_result.nrows());
256//
257// // Compute intersection
258// let intersection_result = polygon_intersection(&poly1.view(), &poly2.view()).unwrap();
259// println!("Intersection has {} vertices", intersection_result.nrows());
260//
261// // Compute difference (poly1 - poly2)
262// let difference_result = polygon_difference(&poly1.view(), &poly2.view()).unwrap();
263// println!("Difference has {} vertices", difference_result.nrows());
264// ```
265//
266// ### Set-Based Distances
267//
268// ```
269// use scirs2_spatial::set_distance::hausdorff_distance;
270// use scirs2_core::ndarray::array;
271//
272// // Create two point sets
273// let set1 = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
274// let set2 = array![[0.0, 0.5], [1.0, 0.5], [0.5, 1.0]];
275//
276// // Compute the Hausdorff distance
277// let dist = hausdorff_distance(&set1.view(), &set2.view(), None);
278// println!("Hausdorff distance: {}", dist);
279// ```
280//
281// ### Polygon Operations
282//
283// ```
284// use scirs2_spatial::polygon::{point_in_polygon, polygon_area, polygon_centroid};
285// use scirs2_core::ndarray::array;
286//
287// // Create a polygon (square)
288// let polygon = array![[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
289//
290// // Check if a point is inside
291// let inside = point_in_polygon(&[0.5, 0.5], &polygon.view());
292// println!("Is point [0.5, 0.5] inside? {}", inside);
293//
294// // Calculate polygon area
295// let area = polygon_area(&polygon.view());
296// println!("Polygon area: {}", area);
297//
298// // Calculate centroid
299// let centroid = polygon_centroid(&polygon.view());
300// println!("Polygon centroid: ({}, {})", centroid[0], centroid[1]);
301// ```
302//
303// ### Ball Tree for Nearest Neighbor Searches
304//
305// ```
306// use scirs2_spatial::BallTree;
307// use scirs2_core::ndarray::array;
308//
309// // Create points
310// let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
311//
312// // Build Ball Tree
313// let ball_tree = BallTree::with_euclidean_distance(&points.view(), 2).unwrap();
314//
315// // Find 2 nearest neighbors to [0.5, 0.5]
316// let (indices, distances) = ball_tree.query(&[0.5, 0.5], 2, true).unwrap();
317// println!("Indices of 2 nearest points: {:?}", indices);
318// println!("Distances to 2 nearest points: {:?}", distances.unwrap());
319//
320// // Find all points within radius 0.7
321// let (idx_radius, dist_radius) = ball_tree.query_radius(&[0.5, 0.5], 0.7, true).unwrap();
322// println!("Found {} points within radius 0.7", idx_radius.len());
323// ```
324//
325// ### A* Pathfinding
326//
327// ```
328// use scirs2_spatial::pathplanning::GridAStarPlanner;
329//
330// // Create a grid with some obstacles (true = obstacle, false = free space)
331// let grid = vec![
332//     vec![false, false, false, false, false],
333//     vec![false, false, false, false, false],
334//     vec![false, true, true, true, false],  // A wall of obstacles
335//     vec![false, false, false, false, false],
336//     vec![false, false, false, false, false],
337// ];
338//
339// // Create an A* planner with the grid
340// let planner = GridAStarPlanner::new(grid, false);
341//
342// // Find a path from top-left to bottom-right
343// let start = [0, 0];
344// let goal = [4, 4];
345//
346// let path = planner.find_path(start, goal).unwrap().unwrap();
347//
348// println!("Found a path with {} steps:", path.len() - 1);
349// for (i, pos) in path.nodes.iter().enumerate() {
350//     println!("  Step {}: {:?}", i, pos);
351// }
352// ```
353//
354// ### SIMD-Accelerated Distance Calculations
355//
356// ```
357// use scirs2_spatial::simd_distance::{simd_euclidean_distance_batch, parallel_pdist};
358// use scirs2_core::ndarray::array;
359//
360// // SIMD batch distance calculation between corresponding points
361// let points1 = array![[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]];
362// let points2 = array![[1.0, 0.0], [2.0, 1.0], [3.0, 2.0]];
363//
364// let distances = simd_euclidean_distance_batch(&points1.view(), &points2.view()).unwrap();
365// println!("Batch distances: {:?}", distances);
366//
367// // Parallel pairwise distance matrix computation
368// let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
369// let dist_matrix = parallel_pdist(&points.view(), "euclidean").unwrap();
370// println!("Distance matrix shape: {:?}", dist_matrix.shape());
371//
372// // High-performance k-nearest neighbors search
373// use scirs2_spatial::simd_distance::simd_knn_search;
374// let (indices, distances) = simd_knn_search(&points1.view(), &points.view(), 2, "euclidean").unwrap();
375// println!("Nearest neighbor indices: {:?}", indices);
376// ```
377//
378// ### Advanced-Optimized SIMD Clustering
379//
380// ```
381// use scirs2_spatial::{AdvancedSimdKMeans, AdvancedSimdNearestNeighbors};
382// use scirs2_core::ndarray::array;
383//
384// // Optimized SIMD K-means clustering
385// let points = array![
386//     [0.0, 0.0], [0.1, 0.1], [0.0, 0.1],  // Cluster 1
387//     [5.0, 5.0], [5.1, 5.1], [5.0, 5.1],  // Cluster 2
388// ];
389//
390// let advanced_kmeans = AdvancedSimdKMeans::new(2)
391//     .with_mixed_precision(true)
392//     .with_block_size(256);
393//
394// let (centroids, assignments) = advanced_kmeans.fit(&points.view()).unwrap();
395// println!("Centroids: {:?}", centroids);
396// println!("Assignments: {:?}", assignments);
397//
398// // Optimized SIMD nearest neighbors
399// let nn_searcher = AdvancedSimdNearestNeighbors::new();
400// let query_points = array![[0.05, 0.05], [5.05, 5.05]];
401// let (indices, distances) = nn_searcher.simd_knn_advanced_fast(
402//     &query_points.view(), &points.view(), 2
403// ).unwrap();
404// println!("NN indices: {:?}", indices);
405// ```
406//
407// ### Memory Pool Optimization
408//
409// ```
410// use scirs2_spatial::{DistancePool, ClusteringArena, global_distance_pool};
411//
412// // Use global memory pool for frequent allocations
413// let pool = global_distance_pool();
414//
415// // Get a reusable distance buffer
416// let mut buffer = pool.get_distance_buffer(1000);
417//
418// // Use buffer for computations...
419// let data = buffer.as_mut_slice();
420// data[0] = 42.0;
421//
422// // Buffer automatically returns to pool on drop
423// drop(buffer);
424//
425// // Check pool performance
426// let stats = pool.statistics();
427// println!("Pool hit rate: {:.1}%", stats.hit_rate());
428//
429// // Use arena for temporary objects
430// use scirs2_spatial::ClusteringArena;
431// let arena = ClusteringArena::new();
432// let temp_vec = arena.alloc_temp_vec::<f64>(500);
433// // Temporary objects are freed when arena is reset
434// arena.reset();
435// ```
436//
437// ### GPU-Accelerated Massive-Scale Computing
438//
439// ```
440// use scirs2_spatial::{GpuDistanceMatrix, GpuKMeans, report_gpu_status};
441// use scirs2_core::ndarray::array;
442//
443// // Check GPU acceleration availability
444// report_gpu_status();
445//
446// // GPU-accelerated distance matrix for massive datasets
447// let points = array![
448//     [0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0],
449//     [2.0, 2.0], [3.0, 3.0], [4.0, 4.0], [5.0, 5.0],
450// ];
451//
452// let gpu_matrix = GpuDistanceMatrix::new()?;
453// let distances = gpu_matrix.compute_parallel(&points.view()).await?;
454// println!("GPU distance matrix computed: {:?}", distances.shape());
455//
456// // GPU-accelerated K-means for massive clusters
457// let gpu_kmeans = GpuKMeans::new(3)?
458//     .with_batch_size(1024)
459//     .with_tolerance(1e-6);
460//
461// let (centroids, assignments) = gpu_kmeans.fit(&points.view()).await?;
462// println!("GPU K-means completed: {} centroids", centroids.nrows());
463//
464// // Hybrid CPU-GPU processing
465// use scirs2_spatial::HybridProcessor;
466// let processor = HybridProcessor::new()?;
467// let strategy = processor.choose_strategy(points.nrows());
468// println!("Optimal strategy: {:?}", strategy);
469// ```
470//
471// ### Advanced-Optimized KD-Tree for Maximum Performance
472//
473// ```
474// use scirs2_spatial::{AdvancedKDTree, KDTreeConfig};
475// use scirs2_core::ndarray::array;
476//
477// // Create points dataset
478// let points = array![
479//     [0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0],
480//     [2.0, 2.0], [3.0, 3.0], [4.0, 4.0], [5.0, 5.0],
481// ];
482//
483// // Configure advanced-optimized KD-Tree
484// let config = KDTreeConfig::new()
485//     .with_cache_aware_layout(true)    // Optimize for CPU cache
486//     .with_vectorized_search(true)     // Use SIMD acceleration
487//     .with_numa_aware(true)            // NUMA-aware construction
488//     .with_parallel_construction(true, 1000);  // Parallel for large datasets
489//
490// // Build advanced-optimized tree
491// let advanced_kdtree = AdvancedKDTree::new(&points.view(), config)?;
492//
493// // Optimized k-nearest neighbors
494// let query = array![2.1, 2.1];
495// let (indices, distances) = advanced_kdtree.knn_search_advanced(&query.view(), 3)?;
496// println!("Optimized k-NN: indices={:?}, distances={:?}", indices, distances);
497//
498// // Batch processing for multiple queries
499// let queries = array![[0.5, 0.5], [2.5, 2.5], [4.5, 4.5]];
500// let (batch_indices, batch_distances) = advanced_kdtree.batch_knn_search(&queries.view(), 2)?;
501// println!("Batch k-NN shape: {:?}", batch_indices.shape());
502//
503// // Range search with radius
504// let range_results = advanced_kdtree.range_search(&query.view(), 1.0)?;
505// println!("Points within radius 1.0: {} found", range_results.len());
506//
507// // Performance statistics
508// let stats = advanced_kdtree.statistics();
509// println!("Tree depth: {}, Construction time: {:.2}ms",
510//          stats.depth, stats.construction_time_ms);
511// println!("Memory usage: {:.1} KB", stats.memory_usage_bytes as f64 / 1024.0);
512// ```
513//
514// ### RRT Pathfinding
515//
516// ```
517// use scirs2_spatial::pathplanning::{RRTConfig, RRT2DPlanner};
518//
519// // Create a configuration for RRT
520// let config = RRTConfig {
521//     max_iterations: 1000,
522//     step_size: 0.3,
523//     goal_bias: 0.1,
524//     seed: Some(42),
525//     use_rrt_star: false,
526//     neighborhood_radius: None,
527//     bidirectional: false,
528// };
529//
530// // Define obstacles as polygons
531// let obstacles = vec![
532//     // Rectangle obstacle
533//     vec![[3.0, 2.0], [3.0, 4.0], [4.0, 4.0], [4.0, 2.0]],
534// ];
535//
536// // Create RRT planner
537// let mut planner = RRT2DPlanner::new(
538//     config,
539//     obstacles,
540//     [0.0, 0.0],   // Min bounds
541//     [10.0, 10.0], // Max bounds
542//     0.1,          // Collision checking step size
543// ).unwrap();
544//
545// // Find a path from start to goal
546// let start = [1.0, 3.0];
547// let goal = [8.0, 3.0];
548// let goal_threshold = 0.5;
549//
550// let path = planner.find_path(start, goal, goal_threshold).unwrap().unwrap();
551//
552// println!("Found a path with {} segments:", path.len() - 1);
553// for (i, pos) in path.nodes.iter().enumerate() {
554//     println!("  Point {}: [{:.2}, {:.2}]", i, pos[0], pos[1]);
555// }
556// ```
557//
558// ## Advanced MODE: Revolutionary Computing Paradigms
559//
560// These cutting-edge implementations push spatial computing beyond current limitations,
561// achieving unprecedented performance through quantum computing, neuromorphic processing,
562// next-generation GPU architectures, AI-driven optimization, and extreme performance
563// optimizations that can deliver 10-100x speedups over conventional approaches.
564//
565// Note: Advanced modules are currently being optimized and may be temporarily disabled
566// during development phases.
567//
568// ### Quantum-Classical Hybrid Algorithms (Development Mode)
569//
570// ```text
571// // Temporarily disabled for optimization
572// // use scirs2_spatial::quantum_classical_hybrid::{HybridSpatialOptimizer, HybridClusterer};
573// // use scirs2_core::ndarray::array;
574// //
575// // // Quantum-classical hybrid spatial optimization
576// // let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
577// // let mut hybrid_optimizer = HybridSpatialOptimizer::new()
578// //     .with_quantum_depth(5)
579// //     .with_classical_refinement(true)
580// //     .with_adaptive_switching(0.7);
581// //
582// // let result = hybrid_optimizer.optimize_spatial_problem(&points.view()).await?;
583// // println!("Quantum-classical optimization: {} iterations", result.iterations);
584// ```
585//
586// ### Neuromorphic-Quantum Fusion Computing (Development Mode)
587//
588// ```text
589// // Temporarily disabled for optimization
590// // use scirs2_spatial::neuromorphic_quantum_fusion::{QuantumSpikingClusterer, NeuralQuantumOptimizer};
591// // use scirs2_core::ndarray::array;
592// //
593// // // Quantum-enhanced spiking neural clustering
594// // let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
595// // let mut quantum_snn = QuantumSpikingClusterer::new(2)
596// //     .with_quantum_superposition(true)
597// //     .with_spike_timing_plasticity(true)
598// //     .with_quantum_entanglement(0.7)
599// //     .with_bio_inspired_adaptation(true);
600// //
601// // let (clusters, quantum_spikes, fusion_metrics) = quantum_snn.cluster(&points.view()).await?;
602// // println!("Quantum-neural speedup: {:.2}x", fusion_metrics.quantum_neural_speedup);
603// ```
604//
605// ### Next-Generation GPU Architectures (Development Mode)
606//
607// ```text
608// // Temporarily disabled for optimization
609// // use scirs2_spatial::next_gen_gpu_architecture::{QuantumGpuProcessor, PhotonicAccelerator};
610// // use scirs2_core::ndarray::array;
611// //
612// // // Quantum-GPU hybrid processing with tensor core enhancement
613// // let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
614// // let mut quantum_gpu = QuantumGpuProcessor::new()
615// //     .with_quantum_coherence_preservation(true)
616// //     .with_tensor_core_quantum_enhancement(true)
617// //     .with_holographic_memory(true);
618// //
619// // let quantum_distances = quantum_gpu.compute_quantum_distance_matrix(&points.view()).await?;
620// // println!("Quantum-GPU: Unprecedented computing performance achieved");
621// ```
622//
623// ### AI-Driven Algorithm Selection and Optimization (Development Mode)
624//
625// ```text
626// // Temporarily disabled for optimization
627// // use scirs2_spatial::ai_driven_optimization::{AIAlgorithmSelector, MetaLearningOptimizer};
628// // use scirs2_core::ndarray::array;
629// //
630// // // AI automatically selects optimal algorithms and parameters
631// // let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
632// // let mut ai_selector = AIAlgorithmSelector::new()
633// //     .with_meta_learning(true)
634// //     .with_neural_architecture_search(true)
635// //     .with_real_time_adaptation(true)
636// //     .with_multi_objective_optimization(true);
637// //
638// // let (optimal_algorithm, parameters, performance_prediction) =
639// //     ai_selector.select_optimal_algorithm(&points.view(), "clustering").await?;
640// //
641// // println!("AI selected: {} with predicted accuracy: {:.3}",
642// //          optimal_algorithm, performance_prediction.expected_accuracy);
643// ```
644//
645// ### Extreme Performance Optimization (Development Mode)
646//
647// ```text
648// // Temporarily disabled for optimization
649// // use scirs2_spatial::extreme_performance_optimization::{
650// //     ExtremeOptimizer, AdvancedfastDistanceMatrix, SelfOptimizingAlgorithm, create_ultimate_optimizer
651// // };
652// // use scirs2_core::ndarray::array;
653// //
654// // // Achieve 50-100x performance improvements with all optimizations
655// // let points = array![[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]];
656// // let optimizer = create_ultimate_optimizer(); // All optimizations enabled
657// //
658// // let advancedfast_matrix = AdvancedfastDistanceMatrix::new(optimizer);
659// // let distances = advancedfast_matrix.compute_extreme_performance(&points.view()).await?;
660// //
661// // // Self-optimizing algorithms that improve during execution
662// // let mut self_optimizer = SelfOptimizingAlgorithm::new("clustering")
663// //     .with_hardware_counter_feedback(true)  // Real-time performance monitoring
664// //     .with_runtime_code_generation(true)    // Dynamic optimization
665// //     .with_adaptive_memory_patterns(true);  // Intelligent prefetching
666// //
667// // let optimized_result = self_optimizer.auto_optimize_and_execute(&points.view()).await?;
668// // println!("Self-optimized performance: 10-50x speedup achieved automatically");
669// //
670// // // Benchmark all extreme optimizations
671// // let extreme_metrics = benchmark_extreme_optimizations(&points.view()).await?;
672// // println!("Extreme speedup: {:.1}x faster than conventional algorithms",
673// //          extreme_metrics.extreme_speedup);
674// ```
675
676// Export error types
677pub mod error;
678pub use error::{SpatialError, SpatialResult};
679
680// Hilbert curve spatial sorting for cache-efficient access
681pub mod hilbert;
682pub use hilbert::{
683    hilbert_d2, hilbert_d2_f64, hilbert_d2_inverse, hilbert_d3, hilbert_d3_f64, hilbert_d3_inverse,
684    hilbert_sort_2d, hilbert_sort_3d,
685};
686
687// Safe conversion utilities
688pub(crate) mod safe_conversions;
689
690// Distance metrics
691pub mod distance;
692pub use distance::{
693    // Basic distance functions
694    braycurtis,
695    canberra,
696    cdist,
697    chebyshev,
698    correlation,
699    cosine,
700    dice,
701    // Convenience functions
702    euclidean,
703    is_valid_condensed_distance_matrix,
704    jaccard,
705    kulsinski,
706    mahalanobis,
707    manhattan,
708    minkowski,
709    // Distance matrix computation
710    pdist,
711    rogerstanimoto,
712    russellrao,
713    seuclidean,
714    sokalmichener,
715    sokalsneath,
716    sqeuclidean,
717    squareform,
718    squareform_to_condensed,
719    yule,
720    ChebyshevDistance,
721    // Core distance traits and structs
722    Distance,
723    EuclideanDistance,
724    ManhattanDistance,
725    MinkowskiDistance,
726};
727
728// KD-Tree for efficient nearest neighbor searches
729pub mod kdtree;
730pub use kdtree::{KDTree, Rectangle};
731
732// KD-Tree optimizations for spatial operations
733pub mod kdtree_optimized;
734pub use kdtree_optimized::KDTreeOptimized;
735
736// Advanced-optimized KD-Tree with advanced performance features
737pub mod kdtree_advanced;
738pub use kdtree_advanced::{
739    AdvancedKDTree, BoundingBox as KDTreeBoundingBox, KDTreeConfig, TreeStatistics,
740};
741
742// Ball-Tree for efficient nearest neighbor searches in high dimensions
743pub mod balltree;
744pub use balltree::BallTree;
745
746// Delaunay triangulation
747pub mod delaunay;
748pub use delaunay::Delaunay;
749
750// Voronoi diagrams
751pub mod voronoi;
752pub use voronoi::{voronoi, Voronoi};
753
754// Spherical Voronoi diagrams
755pub mod spherical_voronoi;
756pub use spherical_voronoi::SphericalVoronoi;
757
758// Procrustes analysis
759pub mod procrustes;
760pub use procrustes::{procrustes, procrustes_extended, ProcrustesParams};
761
762// Convex hull computation
763pub mod convex_hull;
764pub use convex_hull::{convex_hull, ConvexHull};
765
766// Alpha shapes
767pub mod alphashapes;
768pub use alphashapes::AlphaShape;
769
770// Halfspace intersection
771pub mod halfspace;
772pub use halfspace::{Halfspace, HalfspaceIntersection};
773
774// Boolean operations
775pub mod boolean_ops;
776pub use boolean_ops::{
777    compute_polygon_area, is_convex_polygon, is_self_intersecting, polygon_difference,
778    polygon_intersection, polygon_symmetric_difference, polygon_union,
779};
780
781// Kriging interpolation
782pub mod kriging;
783pub use kriging::{KrigingPrediction, OrdinaryKriging, SimpleKriging, VariogramModel};
784
785// Enhanced geospatial analysis components (geo module)
786pub mod geo;
787pub use geo::{
788    bearing,
789    destination_point as geo_destination_point,
790    geohash_decode,
791    geohash_encode,
792    geohash_neighbors,
793    // Distance calculations
794    haversine_distance as geo_haversine_distance,
795    lat_lon_to_utm,
796    // Coordinate transformations
797    lat_lon_to_xyz,
798    point_in_polygon as geo_point_in_polygon,
799    polygon_area as geo_polygon_area,
800    utm_to_lat_lon,
801    vincenty_distance as geo_vincenty_distance,
802    xyz_to_lat_lon,
803    // Bounding box and polygon
804    BoundingBox as GeoBoundingBox,
805    // GeoHash
806    GeoHash,
807    GeoHashCenter,
808};
809
810// Geospatial functionality (legacy module)
811pub mod geospatial;
812pub use geospatial::{
813    cross_track_distance, destination_point, final_bearing, geographic_to_utm,
814    geographic_to_web_mercator, haversine_distance, initial_bearing, midpoint, normalize_bearing,
815    point_in_spherical_polygon, spherical_polygon_area, vincenty_distance,
816    web_mercator_to_geographic, EARTH_RADIUS_KM, EARTH_RADIUS_M,
817};
818
819// Set-based distance metrics
820pub mod set_distance;
821pub use set_distance::{
822    directed_hausdorff, gromov_hausdorff_distance, hausdorff_distance, wasserstein_distance,
823};
824
825// Polygon operations
826pub mod polygon;
827pub use polygon::{
828    convex_hull_graham, douglas_peucker_simplify, is_simple_polygon, point_in_polygon,
829    point_on_boundary, polygon_area, polygon_centroid, polygon_contains_polygon,
830    visvalingam_whyatt_simplify,
831};
832
833// Computational geometry algorithms (sweep line, bounding, Fortune's Voronoi, incremental 3D hull)
834pub mod computational_geometry;
835
836// R-tree for efficient spatial indexing
837pub mod rtree;
838pub use rtree::{RTree, Rectangle as RTreeRectangle};
839
840// Octree for 3D spatial searches
841pub mod octree;
842pub use octree::{BoundingBox as OctreeBoundingBox, Octree};
843
844// Quadtree for 2D spatial searches
845pub mod quadtree;
846pub use quadtree::{BoundingBox2D, Quadtree};
847
848// Spatial interpolation methods
849pub mod interpolate;
850pub use interpolate::{IDWInterpolator, NaturalNeighborInterpolator, RBFInterpolator, RBFKernel};
851
852// Path planning algorithms
853pub mod pathplanning;
854pub use pathplanning::astar::{AStarPlanner, ContinuousAStarPlanner, GridAStarPlanner, Node, Path};
855pub use pathplanning::rrt::{RRT2DPlanner, RRTConfig, RRTPlanner};
856
857// Spatial transformations
858pub mod transform;
859
860// Collision detection
861pub mod collision;
862// Re-export shapes for convenience
863pub use collision::shapes::{
864    Box2D, Box3D, Circle, LineSegment2D, LineSegment3D, Sphere, Triangle2D, Triangle3D,
865};
866// Re-export narrowphase collision functions
867pub use collision::narrowphase::{
868    box2d_box2d_collision,
869    box3d_box3d_collision,
870    circle_box2d_collision,
871    circle_circle_collision,
872    // GJK collision detection functions
873    gjk_box_box_collision,
874    gjk_collision_detection,
875    gjk_sphere_box_collision,
876    gjk_sphere_sphere_collision,
877    point_box2d_collision,
878    point_box3d_collision,
879    point_circle_collision,
880    point_sphere_collision,
881    point_triangle2d_collision,
882    ray_box3d_collision,
883    ray_sphere_collision,
884    ray_triangle3d_collision,
885    sphere_box3d_collision,
886    sphere_sphere_collision,
887    // GJK trait for advanced users
888    GJKShape,
889};
890// Re-export continuous collision functions
891pub use collision::continuous::continuous_sphere_sphere_collision;
892
893// Spatial statistics and pattern analysis
894pub mod spatial_stats;
895pub use spatial_stats::{
896    average_nearest_neighbor,
897    clark_evans_index,
898    contiguity_weights_matrix,
899    // Enhanced global autocorrelation with significance testing
900    distance_band_weights,
901    distance_weights_matrix,
902    geary_test,
903    gearys_c,
904    getis_ord_gi,
905    // LISA with permutation tests and cluster maps
906    getis_ord_gi_star,
907    inverse_distance_weights,
908    // Spatial KDE
909    kde_at_point,
910    kde_on_grid,
911    knn_weights_matrix,
912    // Scan statistic
913    kulldorff_scan,
914    lisa_cluster_map,
915    local_moran_permutation_test,
916    local_morans_i,
917    moran_test,
918    morans_i,
919    ripleys_k,
920    ripleys_l,
921    row_standardize_weights,
922    select_bandwidth,
923    AnnResult,
924    BandwidthMethod,
925    GetisOrdResult,
926    GlobalAutocorrelationResult,
927    KdeGrid,
928    KernelType,
929    LisaCluster,
930    LisaClusterMap,
931    LisaResult,
932    ScanCluster,
933    ScanModel,
934    ScanResult,
935    ScanStatisticConfig,
936    SpatialKdeConfig,
937    SpatialWeights,
938};
939
940// Triangle mesh operations (simplification, smoothing, normals, quality, I/O)
941pub mod mesh;
942pub use mesh::{
943    face_aspect_ratio, face_min_angle, laplacian_smooth, mesh_quality_stats, simplify_mesh,
944    taubin_smooth, Edge as MeshEdge, Face, QualityStats, TriangleMesh, Vertex,
945};
946
947// Proximity queries (Hausdorff, Frechet, MST, Gabriel, RNG, alpha shapes)
948pub mod proximity;
949pub use proximity::{
950    alpha_shape_edges, discrete_frechet_distance, euclidean_mst, gabriel_graph,
951    hausdorff_distance_detailed, relative_neighborhood_graph, HausdorffResult, MstEdge,
952};
953
954// Variogram analysis for geostatistics and spatial interpolation
955pub mod variogram;
956pub use variogram::{
957    directional_variogram, experimental_variogram, fit_variogram, FittedVariogram,
958};
959
960// Distance transforms for image processing and spatial analysis
961pub mod distance_transform;
962pub use distance_transform::{
963    euclidean_distance_transform, euclidean_distance_transform_3d, feature_transform,
964    DistanceMetric as DistanceTransformMetric,
965};
966
967// Map projections and coordinate system transformations
968pub mod projections;
969pub use projections::{
970    albers_equal_area, lambert_conformal_conic, utm_to_geographic, Ellipsoid, ProjectionType,
971    UTMZone,
972};
973
974// SIMD operations (low-level, used by benchmarks)
975pub mod simd_ops;
976
977// SIMD-accelerated distance calculations
978pub mod simd_distance;
979pub use simd_distance::{
980    parallel_cdist, parallel_pdist, simd_euclidean_distance, simd_euclidean_distance_batch,
981    simd_knn_search, simd_manhattan_distance, SimdMetric,
982};
983
984// Advanced-optimized SIMD clustering and distance operations
985pub use simd_distance::advanced_simd_clustering::{
986    AdvancedSimdKMeans, AdvancedSimdNearestNeighbors,
987};
988pub use simd_distance::bench::{
989    benchmark_distance_computation, report_simd_features, BenchmarkResults,
990};
991pub use simd_distance::mixed_precision_simd::{
992    simd_euclidean_distance_batch_f32, simd_euclidean_distance_f32,
993};
994
995// Advanced-optimized memory pool system for spatial algorithms
996pub mod memory_pool;
997pub use memory_pool::{
998    global_clustering_arena, global_distance_pool, ArenaStatistics, ClusteringArena,
999    DistanceBuffer, DistancePool, IndexBuffer, MatrixBuffer, MemoryPoolConfig, PoolStatistics,
1000};
1001
1002// GPU acceleration for massive-scale spatial computations
1003pub mod gpu_accel;
1004pub use gpu_accel::{
1005    get_gpu_capabilities, global_gpu_device, is_gpu_acceleration_available, report_gpu_status,
1006    GpuCapabilities, GpuDevice, GpuDistanceMatrix, GpuKMeans, GpuNearestNeighbors, HybridProcessor,
1007    ProcessingStrategy,
1008};
1009
1010// Advanced-parallel algorithms with work-stealing and NUMA-aware optimizations
1011pub mod advanced_parallel;
1012pub use advanced_parallel::{
1013    get_numa_topology, initialize_global_pool, report_advanced_parallel_capabilities,
1014    AdvancedParallelDistanceMatrix, AdvancedParallelKMeans, MemoryStrategy, NumaTopology,
1015    PoolStatistics as AdvancedPoolStatistics, ThreadAffinityStrategy, WorkStealingConfig,
1016    WorkStealingPool,
1017};
1018
1019// Utility functions
1020mod utils;
1021
1022// Quantum-inspired spatial algorithms for cutting-edge optimization
1023pub mod quantum_inspired;
1024pub use quantum_inspired::{
1025    // Re-export from algorithms submodule
1026    algorithms::QuantumSpatialOptimizer,
1027    ErrorCorrectionConfig,
1028    ErrorCorrectionType,
1029    OptimizationConfig,
1030    OptimizerType,
1031    PerformanceMetrics,
1032    QuantumAmplitude,
1033    QuantumClusterer,
1034    // Configuration types
1035    QuantumConfig,
1036    QuantumNearestNeighbor,
1037    QuantumSpatialFramework,
1038    QuantumState,
1039};
1040
1041// Neuromorphic computing acceleration for brain-inspired spatial processing
1042pub mod neuromorphic;
1043pub use neuromorphic::{
1044    // Core neuromorphic components
1045    AdaptiveSpikingNeuron,
1046    // Clustering algorithms
1047    CompetitiveNeuralClusterer,
1048    HomeostaticNeuralClusterer,
1049    HomeostaticSynapse,
1050    MetaplasticSynapse,
1051    NetworkStats,
1052    NeuromorphicCapability,
1053    // Configuration
1054    NeuromorphicConfig,
1055    NeuromorphicFactory,
1056    // Processing
1057    NeuromorphicProcessor,
1058    SpikeEvent,
1059    SpikeSequence,
1060    SpikingNeuralClusterer,
1061    SpikingNeuron,
1062    Synapse,
1063};
1064
1065// Advanced GPU tensor core utilization for maximum performance
1066pub mod tensor_cores;
1067pub use tensor_cores::{
1068    detect_tensor_core_capabilities, GpuArchitecture, PrecisionMode, TensorCoreCapabilities,
1069    TensorCoreClustering, TensorCoreDistanceMatrix, TensorCoreType, TensorLayout,
1070};
1071
1072// Machine learning-based spatial optimization and adaptive algorithms
1073pub mod ml_optimization;
1074pub use ml_optimization::{
1075    ActivationFunction, ClusteringParameters, ClusteringResult, DataState, DistanceMetric,
1076    Experience, NeuralSpatialOptimizer, ReinforcementLearningSelector, SpatialAlgorithm,
1077};
1078
1079// Distributed spatial computing framework for massive scale processing
1080#[cfg(feature = "async")]
1081pub mod distributed;
1082#[cfg(feature = "async")]
1083pub use distributed::{
1084    ClusterStatistics, DataPartition, DistributedMessage, DistributedSpatialCluster, LoadBalancer,
1085    LoadMetrics, NodeConfig, NodeStatus, QueryResults, QueryType, SpatialBounds,
1086};
1087
1088// Real-time adaptive algorithm selection and optimization
1089#[cfg(feature = "async")]
1090pub mod adaptive_selection;
1091#[cfg(feature = "async")]
1092pub use adaptive_selection::{
1093    ActualPerformance, AdaptiveAlgorithmSelector, AlgorithmParameters, AlgorithmSelection,
1094    DataCharacteristics, ExecutionResult, PerformancePrediction, SelectedAlgorithm,
1095    SelectionContext,
1096};
1097
1098// Quantum-classical hybrid algorithms for unprecedented performance breakthroughs
1099pub mod quantum_classical_hybrid;
1100pub use quantum_classical_hybrid::{
1101    HybridClusterer, HybridClusteringMetrics, HybridOptimizationResult, HybridPerformanceMetrics,
1102    HybridSpatialOptimizer, OptimizationStepResult,
1103};
1104
1105// Neuromorphic-quantum fusion algorithms for revolutionary bio-quantum computing
1106pub mod neuromorphic_quantum_fusion;
1107pub use neuromorphic_quantum_fusion::{
1108    FusionMetrics, NeuralQuantumOptimizationResult, NeuralQuantumOptimizer, QuantumSpikeEvent,
1109    QuantumSpikePattern, QuantumSpikingClusterer, QuantumSpikingNeuron,
1110};
1111
1112// Next-generation GPU architecture support for future computing paradigms
1113pub mod next_gen_gpu_architecture;
1114pub use next_gen_gpu_architecture::{
1115    NextGenGpuArchitecture, NextGenPerformanceMetrics, PhotonicAccelerator, PhotonicProcessingUnit,
1116    QuantumGpuProcessor, QuantumProcessingUnit,
1117};
1118
1119// Generic traits and algorithms for flexible spatial computing
1120pub mod generic_traits;
1121pub use generic_traits::{
1122    ChebyshevMetric, EuclideanMetric, ManhattanMetric, Point, SpatialArray, SpatialPoint,
1123    SpatialScalar,
1124};
1125
1126pub mod generic_algorithms;
1127pub use generic_algorithms::{
1128    DBSCANResult, GMMResult, GenericConvexHull, GenericDBSCAN, GenericDistanceMatrix, GenericGMM,
1129    GenericKDTree, GenericKMeans, KMeansResult,
1130};
1131
1132// AI-driven algorithm selection and optimization for intelligent spatial computing
1133pub mod ai_driven_optimization;
1134pub use ai_driven_optimization::{
1135    AIAlgorithmSelector, AdaptationRecord, AlgorithmCandidate, AlgorithmKnowledgeBase,
1136    AlgorithmMetadata, ComplexityModel, MetaLearningModel, MetaLearningOptimizer,
1137    MetaOptimizationResult, PerformanceModel, PerformanceRecord, PredictionNetworks,
1138    ReinforcementLearningAgent, TaskMetadata,
1139};
1140
1141// Extreme performance optimization pushing spatial computing beyond current limits
1142pub mod extreme_performance_optimization;
1143pub use extreme_performance_optimization::{
1144    benchmark_extreme_optimizations, create_ultimate_optimizer, AdvancedfastDistanceMatrix,
1145    CacheHierarchyInfo, CacheObliviousSpatialAlgorithms, ExtremeMemoryAllocator, ExtremeOptimizer,
1146    ExtremePerformanceMetrics, HardwarePerformanceCounters, JitCompiler, LockFreeSpatialStructures,
1147    NumaTopologyInfo, OptimizationRecord, SelfOptimizingAlgorithm,
1148};
1149
1150#[cfg(test)]
1151mod tests {
1152    #[test]
1153    fn it_works() {
1154        assert_eq!(2 + 2, 4);
1155    }
1156}