Skip to main content

scirs2_graph/
lib.rs

1#![allow(clippy::field_reassign_with_default)]
2#![allow(clippy::needless_range_loop)]
3//! # SciRS2 Graph - Graph Algorithms and Network Analysis
4//!
5//! **scirs2-graph** provides comprehensive graph algorithms and data structures for network analysis,
6//! offering shortest paths, centrality measures, community detection, spectral methods, and graph
7//! embeddings with parallel processing and memory-efficient implementations.
8//!
9//! ## 🎯 Key Features
10//!
11//! - **Graph Representations**: Directed, undirected, weighted, multi-graphs
12//! - **Classic Algorithms**: BFS, DFS, Dijkstra, A*, Bellman-Ford, Floyd-Warshall
13//! - **Centrality Measures**: Betweenness, closeness, eigenvector, PageRank
14//! - **Community Detection**: Louvain, label propagation, spectral clustering
15//! - **Spectral Methods**: Graph Laplacian, spectral clustering, graph embeddings
16//! - **Network Metrics**: Clustering coefficient, diameter, average path length
17//! - **Performance**: Parallel algorithms, memory profiling
18//!
19//! ## 📦 Module Overview
20//!
21//! | SciRS2 Module | NetworkX/igraph Equivalent | Description |
22//! |---------------|----------------------------|-------------|
23//! | `algorithms` | `networkx.algorithms` | Core graph algorithms (BFS, DFS, shortest paths) |
24//! | `measures` | `networkx.centrality` | Centrality and network metrics |
25//! | `spectral` | `scipy.sparse.linalg` | Spectral graph theory and embeddings |
26//! | `generators` | `networkx.generators` | Graph generation (random, regular, etc.) |
27//! | `io` | `networkx.readwrite` | Graph I/O (GML, GraphML, edge lists) |
28//!
29//! ## 🚀 Quick Start
30//!
31//! ```toml
32//! [dependencies]
33//! scirs2-graph = "0.6.0"
34//! ```
35//!
36//! ```rust,no_run
37//! use scirs2_graph::{Graph, breadth_first_search, betweenness_centrality};
38//!
39//! // Create graph and run BFS
40//! let mut g: Graph<i32, f64> = Graph::new();
41//! let n0 = g.add_node(0);
42//! let n1 = g.add_node(1);
43//! g.add_edge(0, 1, 1.0);
44//! ```
45//!
46//! ## 🔒 Version: 0.6.0
47//!
48//! ## API Stability and Versioning
49//!
50//! scirs2-graph follows strict semantic versioning with clear stability guarantees:
51//!
52//! ### Stability Classifications
53//! - ✅ **Stable**: Core APIs guaranteed until next major version (2.0.0)
54//! - ⚠️ **Experimental**: May change in minor versions, marked with `#[cfg(feature = "experimental")]`
55//! - 📋 **Deprecated**: Will be removed in next major version, use alternatives
56//!
57//! ### Version Guarantees
58//! - **MAJOR** (1.x.x → 2.x.x): Breaking changes to stable APIs allowed
59//! - **MINOR** (1.0.x → 1.1.x): New features, deprecations only (no breaks to stable APIs)
60//! - **PATCH** (1.0.0 → 1.0.1): Bug fixes only, no API changes
61//!
62//! ### Stable Core APIs (v0.4.0+)
63//! - Graph data structures (`Graph`, `DiGraph`, `MultiGraph`)
64//! - Basic algorithms (traversal, shortest paths, connectivity)
65//! - Graph generators and I/O operations
66//! - Community detection with `_result` suffix functions
67//! - Error handling and core types
68
69#![warn(missing_docs)]
70
71pub mod advanced;
72pub mod algorithms;
73pub mod attributes;
74pub mod base;
75pub mod compressed;
76pub mod embeddings;
77pub mod error;
78pub mod generators;
79pub mod graph_memory_profiler;
80pub mod io;
81pub mod layout;
82pub mod link_prediction;
83pub mod measures;
84pub mod memory;
85pub mod numerical_accuracy_validation;
86pub mod parallel_algorithms;
87pub mod performance;
88pub mod spectral;
89pub mod spectral_graph;
90pub mod streaming;
91pub mod temporal;
92pub mod temporal_graph;
93pub mod temporal_interval;
94pub mod weighted;
95
96// Graph alignment (IsoRank)
97pub mod alignment;
98// Graph condensation (coreset, distillation, evaluation)
99pub mod condensation;
100// Distributed graph algorithms
101pub mod distributed;
102// GPU-accelerated graph operations
103pub mod gpu;
104
105/// CUDA-accelerated sparse graph linear algebra (optional, off-by-default,
106/// NVIDIA-only). Compiles to nothing unless the `cuda` feature is enabled.
107#[cfg(feature = "cuda")]
108pub mod gpu_cuda;
109// Graph transformers (GraphGPS, Graphormer)
110pub mod graph_transformer;
111// Graph partitioning (METIS, FENNEL)
112pub mod partitioning;
113// Signed and directed graph embeddings
114pub mod signed_directed;
115// Self-supervised learning on graphs
116pub mod ssl;
117
118// Graph Neural Network layers and transformers
119pub mod gnn;
120
121// SIMD-accelerated graph operations
122#[cfg(feature = "simd")]
123pub mod simd_ops;
124
125// Re-export stable APIs for 1.0
126pub use algorithms::{
127    articulation_points,
128    astar_search,
129    astar_search_digraph,
130    // Centrality measures - stable for 1.0
131    betweenness_centrality,
132    bidirectional_search,
133    bidirectional_search_digraph,
134
135    // Core traversal algorithms - stable for 1.0
136    breadth_first_search,
137    breadth_first_search_digraph,
138    bridges,
139    // Flow algorithms - stable for 1.0
140    capacity_scaling_max_flow,
141    center_nodes,
142    closeness_centrality,
143    complement,
144    // Connectivity analysis - stable for 1.0
145    connected_components,
146    cosine_similarity,
147
148    depth_first_search,
149    depth_first_search_digraph,
150    // Graph properties - stable for 1.0
151    diameter,
152    // Shortest path algorithms - stable for 1.0
153    dijkstra_path,
154    dinic_max_flow,
155    dinic_max_flow_full,
156    edge_subgraph,
157    edmonds_karp_max_flow,
158    eigenvector_centrality,
159    eulerian_type,
160    floyd_warshall,
161    floyd_warshall_digraph,
162    fluid_communities_result,
163    ford_fulkerson_max_flow,
164    // Girvan-Newman community detection
165    girvan_newman_communities_result,
166    girvan_newman_result,
167    greedy_coloring,
168    greedy_modularity_optimization_result,
169    hierarchical_communities_result,
170    hopcroft_karp,
171    infomap_communities,
172    is_bipartite,
173
174    isap_max_flow,
175    // Similarity measures - stable for 1.0
176    jaccard_similarity,
177    k_core_decomposition,
178
179    k_shortest_paths,
180
181    label_propagation_result,
182    line_digraph,
183    line_graph,
184    // Community detection algorithms - stable for 1.0
185    louvain_communities_result,
186    maximal_matching,
187    // Matching algorithms - stable for 1.0
188    maximum_bipartite_matching,
189    maximum_cardinality_matching,
190    min_cost_max_flow,
191    min_cost_max_flow_graph,
192    minimum_cut,
193
194    // Spanning tree algorithms - stable for 1.0
195    minimum_spanning_tree,
196
197    minimum_st_cut,
198    minimum_weight_bipartite_matching,
199    modularity,
200
201    modularity_optimization_result,
202    multi_commodity_flow,
203    multi_source_multi_sink_max_flow,
204    pagerank,
205    parallel_max_flow,
206    personalized_pagerank,
207
208    push_relabel_max_flow,
209    push_relabel_max_flow_full,
210    radius,
211    random_walk,
212    stable_marriage,
213
214    strongly_connected_components,
215    subdigraph,
216    // Graph transformations - stable for 1.0
217    subgraph,
218    tensor_product,
219    // Other algorithms - stable for 1.0
220    topological_sort,
221    transition_matrix,
222
223    weight_filtered_subgraph,
224
225    // Result types - stable for 1.0
226    AStarResult,
227    BipartiteMatching,
228    BipartiteResult,
229    CommunityResult,
230    CommunityStructure,
231    CostEdge,
232    DendrogramLevel,
233    EulerianType,
234    GirvanNewmanConfig,
235    GirvanNewmanResult,
236    GraphColoring,
237    HopcroftKarpResult,
238    InfomapResult,
239    MaxFlowResult,
240    MaximumMatching,
241    MinCostFlowResult,
242    MotifType,
243    MultiCommodityFlowResult,
244};
245
246// Parallel algorithms - stable for 1.0 when parallel feature is enabled
247#[cfg(feature = "parallel")]
248pub use algorithms::{
249    parallel_label_propagation_result, parallel_louvain_communities_result, parallel_modularity,
250};
251
252// Parallel spectral operations - stable for 1.0 when parallel feature is enabled
253#[cfg(feature = "parallel")]
254pub use spectral::{parallel_laplacian, parallel_spectral_clustering};
255
256// Experimental algorithms - unstable, may change in future versions
257pub use algorithms::{
258    // Isomorphism and advanced matching - experimental
259    are_graphs_isomorphic,
260    are_graphs_isomorphic_enhanced,
261    // Complex graph products - experimental
262    cartesian_product,
263
264    // NP-hard problems - experimental (may be moved or optimized)
265    chromatic_number,
266    find_isomorphism,
267    find_isomorphism_vf2,
268    find_motifs,
269    find_subgraph_matches,
270    graph_edit_distance,
271
272    has_hamiltonian_circuit,
273    has_hamiltonian_path,
274};
275
276// Advanced coloring algorithms
277pub use algorithms::coloring::{
278    chromatic_bounds, dsatur_coloring, edge_coloring, greedy_coloring_with_order, list_coloring,
279    verify_coloring, welsh_powell, ChromaticBounds, ColoringOrder, EdgeColoring, ListColoring,
280};
281
282// Advanced motif and subgraph analysis
283pub use algorithms::motifs::{
284    count_3node_motifs, count_4node_motifs, count_motif_frequencies, frequent_subgraph_mining,
285    graphlet_degree_distribution, sample_motif_frequencies, vf2_subgraph_isomorphism,
286    wl_subtree_kernel, FrequentPattern, GraphletDDResult, GraphletDegreeVector, VF2Result,
287    WLKernelResult,
288};
289
290// Link prediction algorithms
291pub use link_prediction::{
292    adamic_adar_all, adamic_adar_index, common_neighbors_all, common_neighbors_score, compute_auc,
293    evaluate_link_prediction, jaccard_coefficient, jaccard_coefficient_all, katz_similarity,
294    katz_similarity_all, preferential_attachment, preferential_attachment_all,
295    resource_allocation_all, resource_allocation_index, simrank, simrank_score,
296    LinkPredictionConfig, LinkPredictionEval, LinkScore,
297};
298
299// Core graph types - stable for 1.0
300pub use base::{
301    BipartiteGraph, DiGraph, Edge, EdgeWeight, Graph, Hyperedge, Hypergraph, IndexType,
302    MultiDiGraph, MultiGraph, Node,
303};
304
305// Error handling - stable for 1.0
306pub use error::{ErrorContext, GraphError, Result};
307
308// Graph generators - stable for 1.0
309pub use generators::{
310    barabasi_albert_graph, complete_graph, cycle_graph, erdos_renyi_graph, grid_2d_graph,
311    grid_3d_graph, hexagonal_lattice_graph, path_graph, planted_partition_model,
312    power_law_cluster_graph, random_geometric_graph, star_graph, stochastic_block_model,
313    triangular_lattice_graph, two_community_sbm, watts_strogatz_graph,
314};
315
316// Graph measures - stable for 1.0
317pub use measures::{
318    centrality, clustering_coefficient, graph_density, hits_algorithm, katz_centrality,
319    katz_centrality_digraph, pagerank_centrality, pagerank_centrality_digraph, CentralityType,
320    HitsScores,
321};
322
323// Parallel measures - stable for 1.0 when parallel feature is enabled
324#[cfg(feature = "parallel")]
325pub use measures::parallel_pagerank_centrality;
326
327// Spectral analysis - stable for 1.0
328pub use spectral::{laplacian, normalized_cut, spectral_radius};
329
330// Weighted operations - stable for 1.0
331pub use weighted::{
332    MultiWeight, NormalizationMethod, WeightStatistics, WeightTransform, WeightedOps,
333};
334
335// Attribute system - stable for 1.0
336pub use attributes::{
337    AttributeSummary, AttributeValue, AttributeView, AttributedDiGraph, AttributedGraph, Attributes,
338};
339
340// Memory optimization - stable for 1.0
341pub use memory::{
342    suggest_optimizations, BitPackedGraph, CSRGraph, CompressedAdjacencyList, FragmentationReport,
343    HybridGraph, MemoryProfiler, MemorySample, MemoryStats, OptimizationSuggestions,
344    OptimizedGraphBuilder,
345};
346
347// Performance monitoring - stable for 1.0
348pub use performance::{
349    LargeGraphIterator, LargeGraphOps, MemoryMetrics, ParallelConfig, PerformanceMonitor,
350    PerformanceReport, StreamingGraphProcessor,
351};
352
353// I/O operations - stable for 1.0
354pub use io::*;
355
356// Graph embedding algorithms
357pub use embeddings::{
358    DeepWalk, DeepWalkConfig, DeepWalkMode, Embedding, EmbeddingModel, LINEConfig, LINEOrder,
359    Node2Vec, Node2VecConfig, RandomWalk, RandomWalkGenerator, SpectralEmbedding,
360    SpectralEmbeddingConfig, SpectralLaplacianType, LINE,
361};
362
363pub use layout::{circular_layout, hierarchical_layout, spectral_layout, spring_layout, Position};
364
365// Stream-model temporal graph (f64 timestamps, centrality, motifs, community)
366pub use temporal::{
367    count_temporal_triangles, evolutionary_clustering, temporal_betweenness, temporal_closeness,
368    temporal_motif_count, temporal_pagerank, DynamicCommunity, TemporalEdge as StreamTemporalEdge,
369    TemporalGraph as StreamTemporalGraph, TemporalMotifCounts,
370};
371
372// Interval-model temporal graph (generic typed nodes, TimeInstant/TimeInterval)
373pub use temporal_interval::{
374    temporal_betweenness_centrality, temporal_reachability, TemporalGraph, TemporalPath,
375    TimeInstant, TimeInterval,
376};
377
378// Advanced mode optimizations - experimental but stable API
379pub use advanced::{
380    create_advanced_processor, execute_with_advanced, AdvancedConfig, AdvancedProcessor,
381    AdvancedStats, AlgorithmMetrics, GPUAccelerationContext, NeuralRLAgent, NeuromorphicProcessor,
382};
383
384// Graph memory profiling - experimental
385pub use graph_memory_profiler::{
386    AdvancedMemoryProfiler,
387    EfficiencyAnalysis,
388    MemoryProfile,
389    MemoryProfilerConfig,
390    MemoryStats as GraphMemoryStats, // Renamed to avoid conflict
391    OptimizationOpportunity,
392    OptimizationType,
393};
394
395// Numerical accuracy validation - experimental
396pub use numerical_accuracy_validation::{
397    create_comprehensive_validation_suite, run_quick_validation, AdvancedNumericalValidator,
398    ValidationAlgorithm, ValidationConfig, ValidationReport, ValidationResult,
399    ValidationTolerances,
400};
401
402// Compressed sparse row graph representation
403pub use compressed::{AdjacencyList, CsrGraph, CsrGraphBuilder, NeighborIter};
404
405#[cfg(feature = "cuda")]
406pub use gpu_cuda::{cuda_is_available, cuda_spmv_csr};
407
408// Parallel graph algorithms on CSR graphs
409pub use parallel_algorithms::{
410    bfs, connected_components as csr_connected_components, pagerank as csr_pagerank,
411    triangle_count, BfsResult, ComponentsResult, PageRankConfig, PageRankResult,
412    TriangleCountResult,
413};
414
415#[cfg(feature = "parallel")]
416pub use parallel_algorithms::{
417    parallel_bfs, parallel_connected_components, parallel_pagerank, parallel_triangle_count,
418};
419
420// Streaming graph processing
421pub use streaming::{
422    DegreeDistribution, DoulionTriangleCounter, EvictionStrategy, MascotTriangleCounter,
423    MemoryBoundedConfig, MemoryBoundedProcessor, SlidingWindowGraph, StreamEdge, StreamEvent,
424    StreamOp, StreamingGraph, TriangleCounterStats,
425};
426
427// Additional modules (previously orphaned, now wired)
428pub mod attributed_graph;
429pub mod compat;
430pub mod heterogeneous;
431pub mod knowledge_graph;
432pub mod network_statistics;
433pub mod sampling;
434pub mod social;
435pub mod traversal;
436pub mod visualization;
437
438// Previously orphaned subdirectory modules
439pub mod algebraic;
440pub mod centrality;
441pub mod community;
442pub mod diffusion;
443pub mod domination;
444pub mod dynamic;
445pub mod flow;
446pub mod hypergraph;
447pub mod isomorphism;
448pub mod planarity;
449pub mod reliability;
450pub mod signal_processing;