scirs2_spatial/
lib.rs

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