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