sublinear_solver/
lib.rs

1//! # Sublinear-Time Solver for Asymmetric Diagonally Dominant Systems
2//!
3//! This crate implements cutting-edge sublinear-time algorithms for solving linear systems
4//! of the form Ax = b where A is an asymmetric diagonally dominant matrix.
5//!
6//! ## Key Features
7//!
8//! - **Sublinear Time Complexity**: O(log^k n) for well-conditioned systems
9//! - **Multiple Algorithms**: Neumann series, forward/backward push, hybrid random-walk
10//! - **Incremental Updates**: Fast cost propagation for dynamic systems
11//! - **WASM Compatible**: Cross-platform deployment via WebAssembly
12//! - **High Performance**: SIMD optimization and cache-friendly data structures
13//!
14//! ## Quick Start
15//!
16//! ```rust
17//! use sublinear_solver::{SparseMatrix, NeumannSolver, SolverAlgorithm, SolverOptions};
18//!
19//! // Create a diagonally dominant matrix
20//! let matrix = SparseMatrix::from_triplets(
21//!     vec![(0, 0, 5.0), (0, 1, 1.0), (1, 0, 2.0), (1, 1, 7.0)],
22//!     2, 2
23//! );
24//!
25//! // Set up the right-hand side
26//! let b = vec![6.0, 9.0];
27//!
28//! // Solve using Neumann series
29//! let solver = NeumannSolver::new(16, 1e-8);
30//! let result = solver.solve(&matrix, &b, &SolverOptions::default())?;
31//!
32//! println!("Solution: {:?}", result.solution);
33//! println!("Converged in {} iterations", result.iterations);
34//! # Ok::<(), sublinear_solver::SolverError>(())
35//! ```
36//!
37//! ## Algorithms
38//!
39//! ### Neumann Series Solver
40//! Uses the matrix series expansion (I - M)^(-1) = Σ M^k for solving systems.
41//! Optimal for well-conditioned diagonally dominant matrices.
42//!
43//! ### Forward/Backward Push
44//! Graph-based algorithms that propagate residuals locally, achieving
45//! sublinear complexity for sparse systems with good graph structure.
46//!
47//! ### Hybrid Random-Walk
48//! Combines stochastic estimation with deterministic push methods for
49//! robust performance across different problem types.
50//!
51//! ## WebAssembly Support
52//!
53//! Enable the `wasm` feature for browser and Node.js deployment:
54//!
55//! ```toml
56//! [dependencies]
57//! sublinear-solver = { version = "0.1", features = ["wasm"] }
58//! ```
59
60#![cfg_attr(not(feature = "std"), no_std)]
61#![warn(missing_docs, clippy::all)]
62#![allow(clippy::float_cmp)] // Numerical code often requires exact comparisons
63
64// External crate imports
65extern crate alloc;
66
67#[cfg(feature = "std")]
68extern crate std;
69
70// Re-export commonly used types
71pub use error::{SolverError, Result};
72pub use matrix::{Matrix, SparseMatrix, SparseFormat};
73pub use solver::{
74    SolverAlgorithm, SolverOptions, SolverResult, PartialSolution,
75    NeumannSolver, ForwardPushSolver, BackwardPushSolver, HybridSolver
76};
77pub use types::{
78    NodeId, EdgeId, Precision, ConvergenceMode, NormType,
79    ErrorBounds, SolverStats
80};
81
82// SIMD operations for high performance
83#[cfg(any(feature = "simd", feature = "std"))]
84pub use simd_ops::{matrix_vector_multiply_simd, dot_product_simd, axpy_simd};
85
86#[cfg(feature = "std")]
87pub use simd_ops::parallel_matrix_vector_multiply;
88
89// Optimized solver for best performance
90pub use optimized_solver::{OptimizedConjugateGradientSolver, OptimizedSparseMatrix};
91
92// WASM-compatible re-exports
93pub use math_wasm::{Matrix as WasmMatrix, Vector as WasmVector};
94pub use solver_core::{ConjugateGradientSolver, SolverConfig as WasmSolverConfig};
95
96#[cfg(feature = "wasm")]
97pub use wasm_iface::{WasmSublinearSolver, MatrixView, SolutionStep};
98
99// Core modules
100pub mod error;
101pub mod matrix;
102pub mod solver;
103pub mod types;
104
105// Optional modules
106#[cfg(feature = "wasm")]
107pub mod wasm_iface;
108
109// Additional WASM-compatible modules
110pub mod math_wasm;
111pub mod solver_core;
112
113// High-performance SIMD operations
114#[cfg(any(feature = "simd", feature = "std"))]
115pub mod simd_ops;
116
117// Optimized solver implementations
118pub mod optimized_solver;
119
120#[cfg(feature = "cli")]
121pub mod cli;
122
123// Internal utilities
124mod utils;
125
126// Version information
127pub const VERSION: &str = env!("CARGO_PKG_VERSION");
128pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");
129
130/// Initialize the solver library with default logging configuration.
131///
132/// This function should be called once at the start of your application
133/// to set up proper logging for the solver algorithms.
134#[cfg(feature = "std")]
135pub fn init() {
136    #[cfg(feature = "env_logger")]
137    env_logger::try_init().ok();
138}
139
140/// Initialize the solver library for WASM environments.
141///
142/// This sets up console logging for browser environments.
143#[cfg(feature = "wasm")]
144pub fn init_wasm() {
145    #[cfg(feature = "console_error_panic_hook")]
146    console_error_panic_hook::set_once();
147}
148
149/// Set panic hook for WASM environments
150#[cfg(feature = "wasm")]
151pub fn set_panic_hook() {
152    #[cfg(feature = "console_error_panic_hook")]
153    console_error_panic_hook::set_once();
154}
155
156/// Check if the current build supports SIMD optimizations.
157pub fn has_simd_support() -> bool {
158    #[cfg(feature = "simd")]
159    {
160        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
161        {
162            is_x86_feature_detected!("avx2")
163        }
164        #[cfg(target_arch = "aarch64")]
165        {
166            std::arch::is_aarch64_feature_detected!("neon")
167        }
168        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
169        {
170            false
171        }
172    }
173    #[cfg(not(feature = "simd"))]
174    {
175        false
176    }
177}
178
179/// Get information about the current solver build.
180pub fn build_info() -> BuildInfo {
181    BuildInfo {
182        version: VERSION,
183        features: get_enabled_features(),
184        simd_support: has_simd_support(),
185        target_arch: "wasm32",
186        target_os: "unknown",
187    }
188}
189
190/// Information about the current build configuration.
191#[derive(Debug, Clone, PartialEq)]
192#[derive(serde::Serialize, serde::Deserialize)]
193pub struct BuildInfo {
194    /// Library version
195    pub version: &'static str,
196    /// Enabled feature flags
197    pub features: Vec<&'static str>,
198    /// Whether SIMD optimizations are available
199    pub simd_support: bool,
200    /// Target architecture
201    pub target_arch: &'static str,
202    /// Target operating system
203    pub target_os: &'static str,
204}
205
206fn get_enabled_features() -> Vec<&'static str> {
207    let mut features = Vec::new();
208    
209    #[cfg(feature = "std")]
210    features.push("std");
211    
212    #[cfg(feature = "wasm")]
213    features.push("wasm");
214    
215    #[cfg(feature = "cli")]
216    features.push("cli");
217    
218    #[cfg(feature = "simd")]
219    features.push("simd");
220    
221    features
222}
223
224// Optional dependency re-exports
225#[cfg(feature = "wasm")]
226pub use wasm_bindgen;
227
228#[cfg(feature = "wasm")]
229pub use js_sys;
230
231#[cfg(feature = "wasm")]
232pub use web_sys;
233
234#[cfg(all(test, feature = "std"))]
235mod tests {
236    use super::*;
237    
238    #[test]
239    fn test_build_info() {
240        let info = build_info();
241        assert_eq!(info.version, VERSION);
242        assert!(!info.features.is_empty());
243    }
244    
245    #[test]
246    fn test_version_info() {
247        assert!(!VERSION.is_empty());
248        assert!(!DESCRIPTION.is_empty());
249    }
250}