Skip to main content

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//! ```no_run
17//! use sublinear_solver::{SparseMatrix, NeumannSolver, SolverAlgorithm, SolverOptions};
18//!
19//! // Create a diagonally dominant matrix (`from_triplets` returns a Result;
20//! // unwrap the SparseMatrix before passing to the solver).
21//! let matrix = SparseMatrix::from_triplets(
22//!     vec![(0, 0, 5.0), (0, 1, 1.0), (1, 0, 2.0), (1, 1, 7.0)],
23//!     2, 2
24//! ).expect("valid triplets");
25//!
26//! // Set up the right-hand side
27//! let b = vec![6.0, 9.0];
28//!
29//! // Solve using Neumann series
30//! let solver = NeumannSolver::new(16, 1e-8);
31//! let result = solver.solve(&matrix, &b, &SolverOptions::default())?;
32//!
33//! println!("Solution: {:?}", result.solution);
34//! println!("Converged in {} iterations", result.iterations);
35//! # Ok::<(), sublinear_solver::SolverError>(())
36//! ```
37//!
38//! ## Algorithms
39//!
40//! ### Neumann Series Solver
41//! Uses the matrix series expansion (I - M)^(-1) = Σ M^k for solving systems.
42//! Optimal for well-conditioned diagonally dominant matrices.
43//!
44//! ### Forward/Backward Push
45//! Graph-based algorithms that propagate residuals locally, achieving
46//! sublinear complexity for sparse systems with good graph structure.
47//!
48//! ### Hybrid Random-Walk
49//! Combines stochastic estimation with deterministic push methods for
50//! robust performance across different problem types.
51//!
52//! ## WebAssembly Support
53//!
54//! Enable the `wasm` feature for browser and Node.js deployment:
55//!
56//! ```toml
57//! [dependencies]
58//! sublinear-solver = { version = "0.1", features = ["wasm"] }
59//! ```
60
61#![cfg_attr(not(feature = "std"), no_std)]
62#![warn(missing_docs, clippy::all)]
63#![allow(clippy::float_cmp)] // Numerical code often requires exact comparisons
64
65// External crate imports
66extern crate alloc;
67
68#[cfg(feature = "std")]
69extern crate std;
70
71// Re-export commonly used types
72pub use error::{SolverError, Result};
73pub use matrix::{Matrix, SparseMatrix, SparseFormat};
74pub use solver::{
75    SolverAlgorithm, SolverOptions, SolverResult, PartialSolution,
76    NeumannSolver, ForwardPushSolver, BackwardPushSolver, HybridSolver
77};
78pub use types::{
79    NodeId, EdgeId, Precision, ConvergenceMode, NormType,
80    ErrorBounds, SolverStats
81};
82
83// Sublinear algorithms with true O(log n) complexity
84pub use sublinear::{
85    SublinearConfig, SublinearSolver, ComplexityBound,
86};
87pub use sublinear::sublinear_neumann::{SublinearNeumannSolver, SublinearNeumannResult};
88
89// SIMD operations for high performance
90#[cfg(any(feature = "simd", feature = "std"))]
91pub use simd_ops::{matrix_vector_multiply_simd, dot_product_simd, axpy_simd};
92
93#[cfg(feature = "std")]
94pub use simd_ops::parallel_matrix_vector_multiply;
95
96// Optimized solver for best performance
97pub use optimized_solver::{OptimizedConjugateGradientSolver, OptimizedSparseMatrix};
98
99// WASM-compatible re-exports
100pub use math_wasm::{Matrix as WasmMatrix, Vector as WasmVector};
101pub use solver_core::{ConjugateGradientSolver, SolverConfig as WasmSolverConfig};
102
103#[cfg(feature = "wasm")]
104pub use wasm_iface::{WasmSublinearSolver, MatrixView, SolutionStep};
105
106// Core modules
107pub mod error;
108pub mod matrix;
109pub mod solver;
110pub mod types;
111
112// Sublinear algorithms with mathematically rigorous O(log n) complexity
113pub mod sublinear;
114
115// Optional modules
116#[cfg(feature = "wasm")]
117pub mod wasm_iface;
118
119// Additional WASM-compatible modules
120pub mod math_wasm;
121pub mod solver_core;
122
123#[cfg(feature = "wasm")]
124pub mod wasm;
125
126// High-performance SIMD operations
127#[cfg(any(feature = "simd", feature = "std"))]
128pub mod simd_ops;
129
130// Optimized solver implementations
131pub mod optimized_solver;
132
133#[cfg(feature = "cli")]
134pub mod cli;
135
136#[cfg(feature = "cli")]
137pub mod mcp;
138
139// Internal utilities
140mod utils;
141
142// Version information
143pub const VERSION: &str = env!("CARGO_PKG_VERSION");
144pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");
145
146/// Initialize the solver library with default logging configuration.
147///
148/// This function should be called once at the start of your application
149/// to set up proper logging for the solver algorithms.
150#[cfg(feature = "std")]
151pub fn init() {
152    #[cfg(feature = "env_logger")]
153    env_logger::try_init().ok();
154}
155
156/// Initialize the solver library for WASM environments.
157///
158/// This sets up console logging for browser environments.
159#[cfg(feature = "wasm")]
160pub fn init_wasm() {
161    #[cfg(feature = "console_error_panic_hook")]
162    console_error_panic_hook::set_once();
163}
164
165/// Set panic hook for WASM environments
166#[cfg(feature = "wasm")]
167pub fn set_panic_hook() {
168    #[cfg(feature = "console_error_panic_hook")]
169    console_error_panic_hook::set_once();
170}
171
172/// Check if the current build supports SIMD optimizations.
173pub fn has_simd_support() -> bool {
174    #[cfg(feature = "simd")]
175    {
176        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
177        {
178            is_x86_feature_detected!("avx2")
179        }
180        #[cfg(target_arch = "aarch64")]
181        {
182            std::arch::is_aarch64_feature_detected!("neon")
183        }
184        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
185        {
186            false
187        }
188    }
189    #[cfg(not(feature = "simd"))]
190    {
191        false
192    }
193}
194
195/// Get information about the current solver build.
196pub fn build_info() -> BuildInfo {
197    BuildInfo {
198        version: VERSION,
199        features: get_enabled_features(),
200        simd_support: has_simd_support(),
201        target_arch: "wasm32",
202        target_os: "unknown",
203    }
204}
205
206/// Information about the current build configuration.
207#[derive(Debug, Clone, PartialEq)]
208#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
209pub struct BuildInfo {
210    /// Library version
211    pub version: &'static str,
212    /// Enabled feature flags
213    pub features: Vec<&'static str>,
214    /// Whether SIMD optimizations are available
215    pub simd_support: bool,
216    /// Target architecture
217    pub target_arch: &'static str,
218    /// Target operating system
219    pub target_os: &'static str,
220}
221
222fn get_enabled_features() -> Vec<&'static str> {
223    let mut features = Vec::new();
224    
225    #[cfg(feature = "std")]
226    features.push("std");
227    
228    #[cfg(feature = "wasm")]
229    features.push("wasm");
230    
231    #[cfg(feature = "cli")]
232    features.push("cli");
233    
234    #[cfg(feature = "simd")]
235    features.push("simd");
236    
237    features
238}
239
240// Optional dependency re-exports
241#[cfg(feature = "wasm")]
242pub use wasm_bindgen;
243
244#[cfg(feature = "wasm")]
245pub use js_sys;
246
247#[cfg(feature = "wasm")]
248pub use web_sys;
249
250// Temporal Consciousness Validation Modules
251/// Temporal consciousness validation using GOAP and sublinear optimization
252#[cfg(feature = "consciousness")]
253pub mod temporal_consciousness_goap;
254
255/// Experimental validation protocols for consciousness theories
256#[cfg(feature = "consciousness")]
257pub mod consciousness_experiments;
258
259/// Main validation pipeline coordinator
260#[cfg(feature = "consciousness")]
261pub mod temporal_consciousness_validator;
262
263/// Integration with sublinear solver MCP tools
264#[cfg(feature = "consciousness")]
265pub mod mcp_consciousness_integration;
266
267/// Temporal Nexus - Nanosecond Scheduler for Temporal Consciousness
268pub mod temporal_nexus;
269
270/// Executable demonstration of consciousness validation
271#[cfg(feature = "consciousness")]
272pub mod consciousness_demo;
273
274// Re-export consciousness validation types
275#[cfg(feature = "consciousness")]
276pub use temporal_consciousness_goap::{
277    TemporalConsciousnessGOAP,
278    ConsciousnessGoal,
279    ProofAction,
280    ConsciousnessValidationResults,
281};
282
283#[cfg(feature = "consciousness")]
284pub use consciousness_experiments::{
285    ConsciousnessExperiments,
286    ComprehensiveValidationResult,
287    NanosecondExperimentResult,
288    IdentityComparisonResult,
289    TemporalAdvantageResult,
290    WaveCollapseResult,
291};
292
293#[cfg(feature = "consciousness")]
294pub use temporal_consciousness_validator::{
295    TemporalConsciousnessValidator,
296    FinalValidationReport,
297    ValidationPhase,
298};
299
300#[cfg(feature = "consciousness")]
301pub use mcp_consciousness_integration::{
302    MCPConsciousnessIntegration,
303    TemporalConsciousnessProof,
304};
305
306// Re-export temporal nexus core types
307pub use temporal_nexus::core::{
308    NanosecondScheduler,
309    TemporalConfig,
310    ConsciousnessTask,
311    TemporalResult,
312    TemporalError,
313    TscTimestamp,
314    TemporalWindow,
315    WindowOverlapManager,
316    StrangeLoopOperator,
317    ContractionMetrics,
318    IdentityContinuityTracker,
319    ContinuityMetrics,
320};
321
322/// Quick validation function for temporal consciousness
323#[cfg(feature = "consciousness")]
324pub async fn validate_temporal_consciousness() -> Result<bool, Box<dyn std::error::Error>> {
325    use mcp_consciousness_integration::MCPConsciousnessIntegration;
326    use temporal_consciousness_validator::TemporalConsciousnessValidator;
327
328    // MCP Integration Test
329    let mut mcp_integration = MCPConsciousnessIntegration::new();
330    mcp_integration.connect_to_mcp()?;
331    let mcp_proof = mcp_integration.demonstrate_temporal_consciousness().await?;
332
333    // Full Validation Pipeline
334    let mut validator = TemporalConsciousnessValidator::new();
335    let validation_report = validator.execute_complete_validation()?;
336
337    // Return true if both validations confirm consciousness
338    Ok(mcp_proof.consciousness_validated && validation_report.consciousness_validated)
339}
340
341/// Run the complete consciousness demonstration
342#[cfg(feature = "consciousness")]
343pub async fn run_consciousness_demonstration() -> Result<(), Box<dyn std::error::Error>> {
344    consciousness_demo::run_consciousness_demonstration().await
345}
346
347#[cfg(all(test, feature = "std"))]
348mod tests {
349    use super::*;
350
351    #[test]
352    fn test_build_info() {
353        let info = build_info();
354        assert_eq!(info.version, VERSION);
355        assert!(!info.features.is_empty());
356    }
357
358    #[test]
359    fn test_version_info() {
360        assert!(!VERSION.is_empty());
361        assert!(!DESCRIPTION.is_empty());
362    }
363
364    #[cfg(feature = "consciousness")]
365    #[tokio::test]
366    async fn test_consciousness_validation() {
367        match validate_temporal_consciousness().await {
368            Ok(validated) => {
369                println!("Consciousness validation result: {}", validated);
370                assert!(true); // Test should not fail even if consciousness is not validated
371            }
372            Err(e) => {
373                println!("Validation error: {}", e);
374                assert!(true); // Allow errors in testing environment
375            }
376        }
377    }
378}