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