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.4.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.4.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 streaming;
90pub mod temporal;
91pub mod temporal_graph;
92pub mod temporal_interval;
93pub mod weighted;
94
95// Graph alignment (IsoRank)
96pub mod alignment;
97// Graph condensation (coreset, distillation, evaluation)
98pub mod condensation;
99// Distributed graph algorithms
100pub mod distributed;
101// GPU-accelerated graph operations
102pub mod gpu;
103// Graph transformers (GraphGPS, Graphormer)
104pub mod graph_transformer;
105// Graph partitioning (METIS, FENNEL)
106pub mod partitioning;
107// Signed and directed graph embeddings
108pub mod signed_directed;
109// Self-supervised learning on graphs
110pub mod ssl;
111
112// Graph Neural Network layers and transformers
113pub mod gnn;
114
115// SIMD-accelerated graph operations
116#[cfg(feature = "simd")]
117pub mod simd_ops;
118
119// Re-export stable APIs for 1.0
120pub use algorithms::{
121    articulation_points,
122    astar_search,
123    astar_search_digraph,
124    // Centrality measures - stable for 1.0
125    betweenness_centrality,
126    bidirectional_search,
127    bidirectional_search_digraph,
128
129    // Core traversal algorithms - stable for 1.0
130    breadth_first_search,
131    breadth_first_search_digraph,
132    bridges,
133    // Flow algorithms - stable for 1.0
134    capacity_scaling_max_flow,
135    center_nodes,
136    closeness_centrality,
137    complement,
138    // Connectivity analysis - stable for 1.0
139    connected_components,
140    cosine_similarity,
141
142    depth_first_search,
143    depth_first_search_digraph,
144    // Graph properties - stable for 1.0
145    diameter,
146    // Shortest path algorithms - stable for 1.0
147    dijkstra_path,
148    dinic_max_flow,
149    dinic_max_flow_full,
150    edge_subgraph,
151    edmonds_karp_max_flow,
152    eigenvector_centrality,
153    eulerian_type,
154    floyd_warshall,
155    floyd_warshall_digraph,
156    fluid_communities_result,
157    ford_fulkerson_max_flow,
158    // Girvan-Newman community detection
159    girvan_newman_communities_result,
160    girvan_newman_result,
161    greedy_coloring,
162    greedy_modularity_optimization_result,
163    hierarchical_communities_result,
164    hopcroft_karp,
165    infomap_communities,
166    is_bipartite,
167
168    isap_max_flow,
169    // Similarity measures - stable for 1.0
170    jaccard_similarity,
171    k_core_decomposition,
172
173    k_shortest_paths,
174
175    label_propagation_result,
176    line_digraph,
177    line_graph,
178    // Community detection algorithms - stable for 1.0
179    louvain_communities_result,
180    maximal_matching,
181    // Matching algorithms - stable for 1.0
182    maximum_bipartite_matching,
183    maximum_cardinality_matching,
184    min_cost_max_flow,
185    min_cost_max_flow_graph,
186    minimum_cut,
187
188    // Spanning tree algorithms - stable for 1.0
189    minimum_spanning_tree,
190
191    minimum_st_cut,
192    minimum_weight_bipartite_matching,
193    modularity,
194
195    modularity_optimization_result,
196    multi_commodity_flow,
197    multi_source_multi_sink_max_flow,
198    pagerank,
199    parallel_max_flow,
200    personalized_pagerank,
201
202    push_relabel_max_flow,
203    push_relabel_max_flow_full,
204    radius,
205    random_walk,
206    stable_marriage,
207
208    strongly_connected_components,
209    subdigraph,
210    // Graph transformations - stable for 1.0
211    subgraph,
212    tensor_product,
213    // Other algorithms - stable for 1.0
214    topological_sort,
215    transition_matrix,
216
217    weight_filtered_subgraph,
218
219    // Result types - stable for 1.0
220    AStarResult,
221    BipartiteMatching,
222    BipartiteResult,
223    CommunityResult,
224    CommunityStructure,
225    CostEdge,
226    DendrogramLevel,
227    EulerianType,
228    GirvanNewmanConfig,
229    GirvanNewmanResult,
230    GraphColoring,
231    HopcroftKarpResult,
232    InfomapResult,
233    MaxFlowResult,
234    MaximumMatching,
235    MinCostFlowResult,
236    MotifType,
237    MultiCommodityFlowResult,
238};
239
240// Parallel algorithms - stable for 1.0 when parallel feature is enabled
241#[cfg(feature = "parallel")]
242pub use algorithms::{
243    parallel_label_propagation_result, parallel_louvain_communities_result, parallel_modularity,
244};
245
246// Parallel spectral operations - stable for 1.0 when parallel feature is enabled
247#[cfg(feature = "parallel")]
248pub use spectral::{parallel_laplacian, parallel_spectral_clustering};
249
250// Experimental algorithms - unstable, may change in future versions
251pub use algorithms::{
252    // Isomorphism and advanced matching - experimental
253    are_graphs_isomorphic,
254    are_graphs_isomorphic_enhanced,
255    // Complex graph products - experimental
256    cartesian_product,
257
258    // NP-hard problems - experimental (may be moved or optimized)
259    chromatic_number,
260    find_isomorphism,
261    find_isomorphism_vf2,
262    find_motifs,
263    find_subgraph_matches,
264    graph_edit_distance,
265
266    has_hamiltonian_circuit,
267    has_hamiltonian_path,
268};
269
270// Advanced coloring algorithms
271pub use algorithms::coloring::{
272    chromatic_bounds, dsatur_coloring, edge_coloring, greedy_coloring_with_order, list_coloring,
273    verify_coloring, welsh_powell, ChromaticBounds, ColoringOrder, EdgeColoring, ListColoring,
274};
275
276// Advanced motif and subgraph analysis
277pub use algorithms::motifs::{
278    count_3node_motifs, count_4node_motifs, count_motif_frequencies, frequent_subgraph_mining,
279    graphlet_degree_distribution, sample_motif_frequencies, vf2_subgraph_isomorphism,
280    wl_subtree_kernel, FrequentPattern, GraphletDDResult, GraphletDegreeVector, VF2Result,
281    WLKernelResult,
282};
283
284// Link prediction algorithms
285pub use link_prediction::{
286    adamic_adar_all, adamic_adar_index, common_neighbors_all, common_neighbors_score, compute_auc,
287    evaluate_link_prediction, jaccard_coefficient, jaccard_coefficient_all, katz_similarity,
288    katz_similarity_all, preferential_attachment, preferential_attachment_all,
289    resource_allocation_all, resource_allocation_index, simrank, simrank_score,
290    LinkPredictionConfig, LinkPredictionEval, LinkScore,
291};
292
293// Core graph types - stable for 1.0
294pub use base::{
295    BipartiteGraph, DiGraph, Edge, EdgeWeight, Graph, Hyperedge, Hypergraph, IndexType,
296    MultiDiGraph, MultiGraph, Node,
297};
298
299// Error handling - stable for 1.0
300pub use error::{ErrorContext, GraphError, Result};
301
302// Graph generators - stable for 1.0
303pub use generators::{
304    barabasi_albert_graph, complete_graph, cycle_graph, erdos_renyi_graph, grid_2d_graph,
305    grid_3d_graph, hexagonal_lattice_graph, path_graph, planted_partition_model,
306    power_law_cluster_graph, random_geometric_graph, star_graph, stochastic_block_model,
307    triangular_lattice_graph, two_community_sbm, watts_strogatz_graph,
308};
309
310// Graph measures - stable for 1.0
311pub use measures::{
312    centrality, clustering_coefficient, graph_density, hits_algorithm, katz_centrality,
313    katz_centrality_digraph, pagerank_centrality, pagerank_centrality_digraph, CentralityType,
314    HitsScores,
315};
316
317// Parallel measures - stable for 1.0 when parallel feature is enabled
318#[cfg(feature = "parallel")]
319pub use measures::parallel_pagerank_centrality;
320
321// Spectral analysis - stable for 1.0
322pub use spectral::{laplacian, normalized_cut, spectral_radius};
323
324// Weighted operations - stable for 1.0
325pub use weighted::{
326    MultiWeight, NormalizationMethod, WeightStatistics, WeightTransform, WeightedOps,
327};
328
329// Attribute system - stable for 1.0
330pub use attributes::{
331    AttributeSummary, AttributeValue, AttributeView, AttributedDiGraph, AttributedGraph, Attributes,
332};
333
334// Memory optimization - stable for 1.0
335pub use memory::{
336    suggest_optimizations, BitPackedGraph, CSRGraph, CompressedAdjacencyList, FragmentationReport,
337    HybridGraph, MemoryProfiler, MemorySample, MemoryStats, OptimizationSuggestions,
338    OptimizedGraphBuilder,
339};
340
341// Performance monitoring - stable for 1.0
342pub use performance::{
343    LargeGraphIterator, LargeGraphOps, MemoryMetrics, ParallelConfig, PerformanceMonitor,
344    PerformanceReport, StreamingGraphProcessor,
345};
346
347// I/O operations - stable for 1.0
348pub use io::*;
349
350// Graph embedding algorithms
351pub use embeddings::{
352    DeepWalk, DeepWalkConfig, DeepWalkMode, Embedding, EmbeddingModel, LINEConfig, LINEOrder,
353    Node2Vec, Node2VecConfig, RandomWalk, RandomWalkGenerator, SpectralEmbedding,
354    SpectralEmbeddingConfig, SpectralLaplacianType, LINE,
355};
356
357pub use layout::{circular_layout, hierarchical_layout, spectral_layout, spring_layout, Position};
358
359// Stream-model temporal graph (f64 timestamps, centrality, motifs, community)
360pub use temporal::{
361    count_temporal_triangles, evolutionary_clustering, temporal_betweenness, temporal_closeness,
362    temporal_motif_count, temporal_pagerank, DynamicCommunity, TemporalEdge as StreamTemporalEdge,
363    TemporalGraph as StreamTemporalGraph, TemporalMotifCounts,
364};
365
366// Interval-model temporal graph (generic typed nodes, TimeInstant/TimeInterval)
367pub use temporal_interval::{
368    temporal_betweenness_centrality, temporal_reachability, TemporalGraph, TemporalPath,
369    TimeInstant, TimeInterval,
370};
371
372// Advanced mode optimizations - experimental but stable API
373pub use advanced::{
374    create_advanced_processor, execute_with_advanced, AdvancedConfig, AdvancedProcessor,
375    AdvancedStats, AlgorithmMetrics, GPUAccelerationContext, NeuralRLAgent, NeuromorphicProcessor,
376};
377
378// Graph memory profiling - experimental
379pub use graph_memory_profiler::{
380    AdvancedMemoryProfiler,
381    EfficiencyAnalysis,
382    MemoryProfile,
383    MemoryProfilerConfig,
384    MemoryStats as GraphMemoryStats, // Renamed to avoid conflict
385    OptimizationOpportunity,
386    OptimizationType,
387};
388
389// Numerical accuracy validation - experimental
390pub use numerical_accuracy_validation::{
391    create_comprehensive_validation_suite, run_quick_validation, AdvancedNumericalValidator,
392    ValidationAlgorithm, ValidationConfig, ValidationReport, ValidationResult,
393    ValidationTolerances,
394};
395
396// Compressed sparse row graph representation
397pub use compressed::{AdjacencyList, CsrGraph, CsrGraphBuilder, NeighborIter};
398
399// Parallel graph algorithms on CSR graphs
400pub use parallel_algorithms::{
401    bfs, connected_components as csr_connected_components, pagerank as csr_pagerank,
402    triangle_count, BfsResult, ComponentsResult, PageRankConfig, PageRankResult,
403    TriangleCountResult,
404};
405
406#[cfg(feature = "parallel")]
407pub use parallel_algorithms::{
408    parallel_bfs, parallel_connected_components, parallel_pagerank, parallel_triangle_count,
409};
410
411// Streaming graph processing
412pub use streaming::{
413    DegreeDistribution, DoulionTriangleCounter, EvictionStrategy, MascotTriangleCounter,
414    MemoryBoundedConfig, MemoryBoundedProcessor, SlidingWindowGraph, StreamEdge, StreamEvent,
415    StreamOp, StreamingGraph, TriangleCounterStats,
416};