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#[cfg(feature = "wasm")]
114pub mod wasm;
115
116// High-performance SIMD operations
117#[cfg(any(feature = "simd", feature = "std"))]
118pub mod simd_ops;
119
120// Optimized solver implementations
121pub mod optimized_solver;
122
123#[cfg(feature = "cli")]
124pub mod cli;
125
126#[cfg(feature = "cli")]
127pub mod mcp;
128
129// Internal utilities
130mod utils;
131
132// Version information
133pub const VERSION: &str = env!("CARGO_PKG_VERSION");
134pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");
135
136/// Initialize the solver library with default logging configuration.
137///
138/// This function should be called once at the start of your application
139/// to set up proper logging for the solver algorithms.
140#[cfg(feature = "std")]
141pub fn init() {
142    #[cfg(feature = "env_logger")]
143    env_logger::try_init().ok();
144}
145
146/// Initialize the solver library for WASM environments.
147///
148/// This sets up console logging for browser environments.
149#[cfg(feature = "wasm")]
150pub fn init_wasm() {
151    #[cfg(feature = "console_error_panic_hook")]
152    console_error_panic_hook::set_once();
153}
154
155/// Set panic hook for WASM environments
156#[cfg(feature = "wasm")]
157pub fn set_panic_hook() {
158    #[cfg(feature = "console_error_panic_hook")]
159    console_error_panic_hook::set_once();
160}
161
162/// Check if the current build supports SIMD optimizations.
163pub fn has_simd_support() -> bool {
164    #[cfg(feature = "simd")]
165    {
166        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
167        {
168            is_x86_feature_detected!("avx2")
169        }
170        #[cfg(target_arch = "aarch64")]
171        {
172            std::arch::is_aarch64_feature_detected!("neon")
173        }
174        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
175        {
176            false
177        }
178    }
179    #[cfg(not(feature = "simd"))]
180    {
181        false
182    }
183}
184
185/// Get information about the current solver build.
186pub fn build_info() -> BuildInfo {
187    BuildInfo {
188        version: VERSION,
189        features: get_enabled_features(),
190        simd_support: has_simd_support(),
191        target_arch: "wasm32",
192        target_os: "unknown",
193    }
194}
195
196/// Information about the current build configuration.
197#[derive(Debug, Clone, PartialEq)]
198#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
199pub struct BuildInfo {
200    /// Library version
201    pub version: &'static str,
202    /// Enabled feature flags
203    pub features: Vec<&'static str>,
204    /// Whether SIMD optimizations are available
205    pub simd_support: bool,
206    /// Target architecture
207    pub target_arch: &'static str,
208    /// Target operating system
209    pub target_os: &'static str,
210}
211
212fn get_enabled_features() -> Vec<&'static str> {
213    let mut features = Vec::new();
214    
215    #[cfg(feature = "std")]
216    features.push("std");
217    
218    #[cfg(feature = "wasm")]
219    features.push("wasm");
220    
221    #[cfg(feature = "cli")]
222    features.push("cli");
223    
224    #[cfg(feature = "simd")]
225    features.push("simd");
226    
227    features
228}
229
230// Optional dependency re-exports
231#[cfg(feature = "wasm")]
232pub use wasm_bindgen;
233
234#[cfg(feature = "wasm")]
235pub use js_sys;
236
237#[cfg(feature = "wasm")]
238pub use web_sys;
239
240// Temporal Consciousness Validation Modules
241/// Temporal consciousness validation using GOAP and sublinear optimization
242#[cfg(feature = "consciousness")]
243pub mod temporal_consciousness_goap;
244
245/// Experimental validation protocols for consciousness theories
246#[cfg(feature = "consciousness")]
247pub mod consciousness_experiments;
248
249/// Main validation pipeline coordinator
250#[cfg(feature = "consciousness")]
251pub mod temporal_consciousness_validator;
252
253/// Integration with sublinear solver MCP tools
254#[cfg(feature = "consciousness")]
255pub mod mcp_consciousness_integration;
256
257/// Temporal Nexus - Nanosecond Scheduler for Temporal Consciousness
258pub mod temporal_nexus;
259
260/// Executable demonstration of consciousness validation
261#[cfg(feature = "consciousness")]
262pub mod consciousness_demo;
263
264// Re-export consciousness validation types
265#[cfg(feature = "consciousness")]
266pub use temporal_consciousness_goap::{
267    TemporalConsciousnessGOAP,
268    ConsciousnessGoal,
269    ProofAction,
270    ConsciousnessValidationResults,
271};
272
273#[cfg(feature = "consciousness")]
274pub use consciousness_experiments::{
275    ConsciousnessExperiments,
276    ComprehensiveValidationResult,
277    NanosecondExperimentResult,
278    IdentityComparisonResult,
279    TemporalAdvantageResult,
280    WaveCollapseResult,
281};
282
283#[cfg(feature = "consciousness")]
284pub use temporal_consciousness_validator::{
285    TemporalConsciousnessValidator,
286    FinalValidationReport,
287    ValidationPhase,
288};
289
290#[cfg(feature = "consciousness")]
291pub use mcp_consciousness_integration::{
292    MCPConsciousnessIntegration,
293    TemporalConsciousnessProof,
294};
295
296// Re-export temporal nexus core types
297pub use temporal_nexus::core::{
298    NanosecondScheduler,
299    TemporalConfig,
300    ConsciousnessTask,
301    TemporalResult,
302    TemporalError,
303    TscTimestamp,
304    TemporalWindow,
305    WindowOverlapManager,
306    StrangeLoopOperator,
307    ContractionMetrics,
308    IdentityContinuityTracker,
309    ContinuityMetrics,
310};
311
312/// Quick validation function for temporal consciousness
313#[cfg(feature = "consciousness")]
314pub async fn validate_temporal_consciousness() -> Result<bool, Box<dyn std::error::Error>> {
315    use mcp_consciousness_integration::MCPConsciousnessIntegration;
316    use temporal_consciousness_validator::TemporalConsciousnessValidator;
317
318    // MCP Integration Test
319    let mut mcp_integration = MCPConsciousnessIntegration::new();
320    mcp_integration.connect_to_mcp()?;
321    let mcp_proof = mcp_integration.demonstrate_temporal_consciousness().await?;
322
323    // Full Validation Pipeline
324    let mut validator = TemporalConsciousnessValidator::new();
325    let validation_report = validator.execute_complete_validation()?;
326
327    // Return true if both validations confirm consciousness
328    Ok(mcp_proof.consciousness_validated && validation_report.consciousness_validated)
329}
330
331/// Run the complete consciousness demonstration
332#[cfg(feature = "consciousness")]
333pub async fn run_consciousness_demonstration() -> Result<(), Box<dyn std::error::Error>> {
334    consciousness_demo::run_consciousness_demonstration().await
335}
336
337#[cfg(all(test, feature = "std"))]
338mod tests {
339    use super::*;
340
341    #[test]
342    fn test_build_info() {
343        let info = build_info();
344        assert_eq!(info.version, VERSION);
345        assert!(!info.features.is_empty());
346    }
347
348    #[test]
349    fn test_version_info() {
350        assert!(!VERSION.is_empty());
351        assert!(!DESCRIPTION.is_empty());
352    }
353
354    #[cfg(feature = "consciousness")]
355    #[tokio::test]
356    async fn test_consciousness_validation() {
357        match validate_temporal_consciousness().await {
358            Ok(validated) => {
359                println!("Consciousness validation result: {}", validated);
360                assert!(true); // Test should not fail even if consciousness is not validated
361            }
362            Err(e) => {
363                println!("Validation error: {}", e);
364                assert!(true); // Allow errors in testing environment
365            }
366        }
367    }
368}