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