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// Complexity-class declarations — every public solver / sampler / analyser
113// declares its worst-case class via the `Complexity` trait. See
114// `docs/adr/ADR-001-complexity-as-architecture.md` for the strategic
115// context (complexity classes as architectural primitives in the broader
116// RuVector / RuView / Cognitum / Ruflo stack).
117pub mod complexity;
118pub use complexity::{Complexity, ComplexityClass, ComplexityIntrospect};
119
120// Coherence gate (ADR-001 roadmap item #3). Refuses polynomial-time solves
121// on near-singular systems. Opt-in via `SolverOptions::coherence_threshold`.
122pub mod coherence;
123pub use coherence::{coherence_score, check_coherence_or_reject};
124
125// Event-gated incremental solve (ADR-001 roadmap item #2). Warm-starts
126// the underlying iterative solver from the previous solution when only a
127// sparse delta of the RHS changed — central to the ADR's "intelligence
128// is sparse, event-driven activation" thesis.
129pub mod incremental;
130pub use incremental::{IncrementalSolver, SparseDelta, IncrementalConfig};
131
132// Contrastive search (ADR-001 roadmap item #6). Boundary-crossing primitive
133// for change-driven activation: which rows of the current solution diverged
134// most from baseline? Backbone of RuView / Cognitum wake-on-event.
135pub mod contrastive;
136pub use contrastive::{find_anomalous_rows, find_rows_above_threshold, AnomalyRow};
137
138// Sublinear algorithms with mathematically rigorous O(log n) complexity
139pub mod sublinear;
140
141// Optional modules
142#[cfg(feature = "wasm")]
143pub mod wasm_iface;
144
145// Additional WASM-compatible modules
146pub mod math_wasm;
147pub mod solver_core;
148
149#[cfg(feature = "wasm")]
150pub mod wasm;
151
152// High-performance SIMD operations
153#[cfg(any(feature = "simd", feature = "std"))]
154pub mod simd_ops;
155
156// Optimized solver implementations
157pub mod optimized_solver;
158
159#[cfg(feature = "cli")]
160pub mod cli;
161
162#[cfg(feature = "cli")]
163pub mod mcp;
164
165// Internal utilities
166mod utils;
167
168// Version information
169pub const VERSION: &str = env!("CARGO_PKG_VERSION");
170pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");
171
172/// Initialize the solver library with default logging configuration.
173///
174/// This function should be called once at the start of your application
175/// to set up proper logging for the solver algorithms.
176#[cfg(feature = "std")]
177pub fn init() {
178    #[cfg(feature = "env_logger")]
179    env_logger::try_init().ok();
180}
181
182/// Initialize the solver library for WASM environments.
183///
184/// This sets up console logging for browser environments.
185#[cfg(feature = "wasm")]
186pub fn init_wasm() {
187    #[cfg(feature = "console_error_panic_hook")]
188    console_error_panic_hook::set_once();
189}
190
191/// Set panic hook for WASM environments
192#[cfg(feature = "wasm")]
193pub fn set_panic_hook() {
194    #[cfg(feature = "console_error_panic_hook")]
195    console_error_panic_hook::set_once();
196}
197
198/// Check if the current build supports SIMD optimizations.
199pub fn has_simd_support() -> bool {
200    #[cfg(feature = "simd")]
201    {
202        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
203        {
204            is_x86_feature_detected!("avx2")
205        }
206        #[cfg(target_arch = "aarch64")]
207        {
208            std::arch::is_aarch64_feature_detected!("neon")
209        }
210        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
211        {
212            false
213        }
214    }
215    #[cfg(not(feature = "simd"))]
216    {
217        false
218    }
219}
220
221/// Get information about the current solver build.
222pub fn build_info() -> BuildInfo {
223    BuildInfo {
224        version: VERSION,
225        features: get_enabled_features(),
226        simd_support: has_simd_support(),
227        target_arch: "wasm32",
228        target_os: "unknown",
229    }
230}
231
232/// Information about the current build configuration.
233#[derive(Debug, Clone, PartialEq)]
234#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
235pub struct BuildInfo {
236    /// Library version
237    pub version: &'static str,
238    /// Enabled feature flags
239    pub features: Vec<&'static str>,
240    /// Whether SIMD optimizations are available
241    pub simd_support: bool,
242    /// Target architecture
243    pub target_arch: &'static str,
244    /// Target operating system
245    pub target_os: &'static str,
246}
247
248fn get_enabled_features() -> Vec<&'static str> {
249    let mut features = Vec::new();
250    
251    #[cfg(feature = "std")]
252    features.push("std");
253    
254    #[cfg(feature = "wasm")]
255    features.push("wasm");
256    
257    #[cfg(feature = "cli")]
258    features.push("cli");
259    
260    #[cfg(feature = "simd")]
261    features.push("simd");
262    
263    features
264}
265
266// Optional dependency re-exports
267#[cfg(feature = "wasm")]
268pub use wasm_bindgen;
269
270#[cfg(feature = "wasm")]
271pub use js_sys;
272
273#[cfg(feature = "wasm")]
274pub use web_sys;
275
276// Temporal Consciousness Validation Modules
277/// Temporal consciousness validation using GOAP and sublinear optimization
278#[cfg(feature = "consciousness")]
279pub mod temporal_consciousness_goap;
280
281/// Experimental validation protocols for consciousness theories
282#[cfg(feature = "consciousness")]
283pub mod consciousness_experiments;
284
285/// Main validation pipeline coordinator
286#[cfg(feature = "consciousness")]
287pub mod temporal_consciousness_validator;
288
289/// Integration with sublinear solver MCP tools
290#[cfg(feature = "consciousness")]
291pub mod mcp_consciousness_integration;
292
293/// Temporal Nexus - Nanosecond Scheduler for Temporal Consciousness
294pub mod temporal_nexus;
295
296/// Executable demonstration of consciousness validation
297#[cfg(feature = "consciousness")]
298pub mod consciousness_demo;
299
300// Re-export consciousness validation types
301#[cfg(feature = "consciousness")]
302pub use temporal_consciousness_goap::{
303    TemporalConsciousnessGOAP,
304    ConsciousnessGoal,
305    ProofAction,
306    ConsciousnessValidationResults,
307};
308
309#[cfg(feature = "consciousness")]
310pub use consciousness_experiments::{
311    ConsciousnessExperiments,
312    ComprehensiveValidationResult,
313    NanosecondExperimentResult,
314    IdentityComparisonResult,
315    TemporalAdvantageResult,
316    WaveCollapseResult,
317};
318
319#[cfg(feature = "consciousness")]
320pub use temporal_consciousness_validator::{
321    TemporalConsciousnessValidator,
322    FinalValidationReport,
323    ValidationPhase,
324};
325
326#[cfg(feature = "consciousness")]
327pub use mcp_consciousness_integration::{
328    MCPConsciousnessIntegration,
329    TemporalConsciousnessProof,
330};
331
332// Re-export temporal nexus core types
333pub use temporal_nexus::core::{
334    NanosecondScheduler,
335    TemporalConfig,
336    ConsciousnessTask,
337    TemporalResult,
338    TemporalError,
339    TscTimestamp,
340    TemporalWindow,
341    WindowOverlapManager,
342    StrangeLoopOperator,
343    ContractionMetrics,
344    IdentityContinuityTracker,
345    ContinuityMetrics,
346};
347
348/// Quick validation function for temporal consciousness
349#[cfg(feature = "consciousness")]
350pub async fn validate_temporal_consciousness() -> Result<bool, Box<dyn std::error::Error>> {
351    use mcp_consciousness_integration::MCPConsciousnessIntegration;
352    use temporal_consciousness_validator::TemporalConsciousnessValidator;
353
354    // MCP Integration Test
355    let mut mcp_integration = MCPConsciousnessIntegration::new();
356    mcp_integration.connect_to_mcp()?;
357    let mcp_proof = mcp_integration.demonstrate_temporal_consciousness().await?;
358
359    // Full Validation Pipeline
360    let mut validator = TemporalConsciousnessValidator::new();
361    let validation_report = validator.execute_complete_validation()?;
362
363    // Return true if both validations confirm consciousness
364    Ok(mcp_proof.consciousness_validated && validation_report.consciousness_validated)
365}
366
367/// Run the complete consciousness demonstration
368#[cfg(feature = "consciousness")]
369pub async fn run_consciousness_demonstration() -> Result<(), Box<dyn std::error::Error>> {
370    consciousness_demo::run_consciousness_demonstration().await
371}
372
373#[cfg(all(test, feature = "std"))]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn test_build_info() {
379        let info = build_info();
380        assert_eq!(info.version, VERSION);
381        assert!(!info.features.is_empty());
382    }
383
384    #[test]
385    fn test_version_info() {
386        assert!(!VERSION.is_empty());
387        assert!(!DESCRIPTION.is_empty());
388    }
389
390    #[cfg(feature = "consciousness")]
391    #[tokio::test]
392    async fn test_consciousness_validation() {
393        match validate_temporal_consciousness().await {
394            Ok(validated) => {
395                println!("Consciousness validation result: {}", validated);
396                assert!(true); // Test should not fail even if consciousness is not validated
397            }
398            Err(e) => {
399                println!("Validation error: {}", e);
400                assert!(true); // Allow errors in testing environment
401            }
402        }
403    }
404}