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::{Result, SolverError};
73pub use matrix::{Matrix, SparseFormat, SparseMatrix};
74pub use solver::{
75    BackwardPushSolver, ForwardPushSolver, HybridSolver, NeumannSolver, PartialSolution,
76    SolverAlgorithm, SolverOptions, SolverResult,
77};
78pub use types::{ConvergenceMode, EdgeId, ErrorBounds, NodeId, NormType, Precision, SolverStats};
79
80// Sublinear algorithms with true O(log n) complexity
81pub use sublinear::sublinear_neumann::{SublinearNeumannResult, SublinearNeumannSolver};
82pub use sublinear::{ComplexityBound, SublinearConfig, SublinearSolver};
83
84// SIMD operations for high performance
85#[cfg(any(feature = "simd", feature = "std"))]
86pub use simd_ops::{axpy_simd, dot_product_simd, matrix_vector_multiply_simd};
87
88#[cfg(feature = "std")]
89pub use simd_ops::parallel_matrix_vector_multiply;
90
91// Optimized solver for best performance
92pub use optimized_solver::{OptimizedConjugateGradientSolver, OptimizedSparseMatrix};
93
94// WASM-compatible re-exports
95pub use math_wasm::{Matrix as WasmMatrix, Vector as WasmVector};
96pub use solver_core::{ConjugateGradientSolver, SolverConfig as WasmSolverConfig};
97
98#[cfg(feature = "wasm")]
99pub use wasm_iface::{MatrixView, SolutionStep, WasmSublinearSolver};
100
101// Core modules
102pub mod error;
103pub mod matrix;
104pub mod solver;
105pub mod types;
106
107// Complexity-class declarations — every public solver / sampler / analyser
108// declares its worst-case class via the `Complexity` trait. See
109// `docs/adr/ADR-001-complexity-as-architecture.md` for the strategic
110// context (complexity classes as architectural primitives in the broader
111// RuVector / RuView / Cognitum / Ruflo stack).
112pub mod complexity;
113pub use complexity::{Complexity, ComplexityClass, ComplexityIntrospect};
114
115// Coherence gate (ADR-001 roadmap item #3). Refuses polynomial-time solves
116// on near-singular systems. Opt-in via `SolverOptions::coherence_threshold`.
117pub mod coherence;
118pub use coherence::{check_coherence_or_reject, coherence_score};
119
120// Event-gated incremental solve (ADR-001 roadmap item #2). Warm-starts
121// the underlying iterative solver from the previous solution when only a
122// sparse delta of the RHS changed — central to the ADR's "intelligence
123// is sparse, event-driven activation" thesis.
124pub mod incremental;
125pub use coherence::{
126    approximate_spectral_radius, delta_below_solve_threshold, delta_inf_bound,
127    optimal_neumann_terms, optimal_neumann_terms_with_rho, CoherenceCache,
128};
129pub use incremental::{
130    solve_on_change_sublinear, solve_on_change_sublinear_auto,
131    solve_on_change_sublinear_auto_with_rho, IncrementalConfig, IncrementalSolver,
132    SolveOnChangeSublinearOp, SparseDelta,
133};
134
135// Bounding planning across chains of solves (ADR-001 #4 phase-3).
136// MCP's enforceComplexityBudget gates one solve at a time; PlanBudget
137// gates the *plan* — the chain of solves an agent intends to run.
138pub mod budget;
139pub use budget::{BudgetExhausted, PlanBudget};
140
141// Sparse solve witness (ADR-001 open question #3). Per-entry residual
142// audit restricted to the closure; same SubLinear complexity class as
143// the orchestrator whose output it verifies.
144pub mod witness;
145pub use witness::{verify_sparse_solution, VerifySparseSolutionOp, WitnessReport};
146
147// Streaming event iterator over the SubLinear orchestrator. The native
148// surface RuView/Cognitum agents call to process sensor/log/metric
149// event streams. Composes with stdlib Iterator + the skip gate +
150// PlanBudget for end-to-end bounded processing.
151pub mod stream;
152pub use stream::{
153    event_stream_iter, EventStatus, EventStreamConfig, EventStreamOp, ProcessedEvent,
154};
155
156// Contrastive search (ADR-001 roadmap item #6). Boundary-crossing primitive
157// for change-driven activation: which rows of the current solution diverged
158// most from baseline? Backbone of RuView / Cognitum wake-on-event.
159pub mod contrastive;
160pub use contrastive::{
161    contrastive_solve_on_change, contrastive_solve_on_change_sublinear,
162    contrastive_solve_on_change_sublinear_auto,
163    contrastive_solve_on_change_sublinear_auto_with_rho, find_anomalous_rows,
164    find_anomalous_rows_in_subset, find_rows_above_threshold, AnomalyRow,
165    ContrastiveSolveOnChangeOp, ContrastiveSolveOnChangeSublinearOp,
166};
167
168// Bounded-depth row-graph closure (ADR-001 #6 phase-2A). Turns a sparse
169// RHS delta into the candidate set of rows whose solution might have
170// changed — the input to a true sub-linear contrastive solve. Composes
171// with `incremental::SparseDelta` and `contrastive::find_anomalous_rows_in_subset`.
172pub mod closure;
173pub use closure::{closure_indices, ClosureIndicesOp};
174
175// Single-entry sublinear Neumann (ADR-001 #6 phase-2B). Compute `x[i]`
176// without materialising the full solution; SubLinear in `n` for sparse
177// DD matrices with bounded depth. Inner primitive for the next-revision
178// `contrastive_solve_on_change` that drops the orchestrator end-to-end
179// to SubLinear.
180pub mod entry;
181pub use entry::{
182    solve_single_entries_neumann, solve_single_entry_neumann, SolveSingleEntryNeumannOp,
183};
184
185// Sublinear algorithms with mathematically rigorous O(log n) complexity
186pub mod sublinear;
187
188// Optional modules
189#[cfg(feature = "wasm")]
190pub mod wasm_iface;
191
192// Additional WASM-compatible modules
193pub mod math_wasm;
194pub mod solver_core;
195
196#[cfg(feature = "wasm")]
197pub mod wasm;
198
199// High-performance SIMD operations
200#[cfg(any(feature = "simd", feature = "std"))]
201pub mod simd_ops;
202
203// Optimized solver implementations
204pub mod optimized_solver;
205
206#[cfg(feature = "cli")]
207pub mod cli;
208
209#[cfg(feature = "cli")]
210pub mod mcp;
211
212// Internal utilities
213mod utils;
214
215// Version information
216pub const VERSION: &str = env!("CARGO_PKG_VERSION");
217pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");
218
219/// Initialize the solver library with default logging configuration.
220///
221/// This function should be called once at the start of your application
222/// to set up proper logging for the solver algorithms.
223#[cfg(feature = "std")]
224pub fn init() {
225    #[cfg(feature = "env_logger")]
226    env_logger::try_init().ok();
227}
228
229/// Initialize the solver library for WASM environments.
230///
231/// This sets up console logging for browser environments.
232#[cfg(feature = "wasm")]
233pub fn init_wasm() {
234    #[cfg(feature = "console_error_panic_hook")]
235    console_error_panic_hook::set_once();
236}
237
238/// Set panic hook for WASM environments
239#[cfg(feature = "wasm")]
240pub fn set_panic_hook() {
241    #[cfg(feature = "console_error_panic_hook")]
242    console_error_panic_hook::set_once();
243}
244
245/// Check if the current build supports SIMD optimizations.
246pub fn has_simd_support() -> bool {
247    #[cfg(feature = "simd")]
248    {
249        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
250        {
251            is_x86_feature_detected!("avx2")
252        }
253        #[cfg(target_arch = "aarch64")]
254        {
255            std::arch::is_aarch64_feature_detected!("neon")
256        }
257        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
258        {
259            false
260        }
261    }
262    #[cfg(not(feature = "simd"))]
263    {
264        false
265    }
266}
267
268/// Get information about the current solver build.
269pub fn build_info() -> BuildInfo {
270    BuildInfo {
271        version: VERSION,
272        features: get_enabled_features(),
273        simd_support: has_simd_support(),
274        target_arch: "wasm32",
275        target_os: "unknown",
276    }
277}
278
279/// Information about the current build configuration.
280#[derive(Debug, Clone, PartialEq)]
281#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
282pub struct BuildInfo {
283    /// Library version
284    pub version: &'static str,
285    /// Enabled feature flags
286    pub features: Vec<&'static str>,
287    /// Whether SIMD optimizations are available
288    pub simd_support: bool,
289    /// Target architecture
290    pub target_arch: &'static str,
291    /// Target operating system
292    pub target_os: &'static str,
293}
294
295fn get_enabled_features() -> Vec<&'static str> {
296    let mut features = Vec::new();
297
298    #[cfg(feature = "std")]
299    features.push("std");
300
301    #[cfg(feature = "wasm")]
302    features.push("wasm");
303
304    #[cfg(feature = "cli")]
305    features.push("cli");
306
307    #[cfg(feature = "simd")]
308    features.push("simd");
309
310    features
311}
312
313// Optional dependency re-exports
314#[cfg(feature = "wasm")]
315pub use wasm_bindgen;
316
317#[cfg(feature = "wasm")]
318pub use js_sys;
319
320#[cfg(feature = "wasm")]
321pub use web_sys;
322
323// Temporal Consciousness Validation Modules
324/// Temporal consciousness validation using GOAP and sublinear optimization
325#[cfg(feature = "consciousness")]
326pub mod temporal_consciousness_goap;
327
328/// Experimental validation protocols for consciousness theories
329#[cfg(feature = "consciousness")]
330pub mod consciousness_experiments;
331
332/// Main validation pipeline coordinator
333#[cfg(feature = "consciousness")]
334pub mod temporal_consciousness_validator;
335
336/// Integration with sublinear solver MCP tools
337#[cfg(feature = "consciousness")]
338pub mod mcp_consciousness_integration;
339
340/// Temporal Nexus - Nanosecond Scheduler for Temporal Consciousness
341pub mod temporal_nexus;
342
343/// Executable demonstration of consciousness validation
344#[cfg(feature = "consciousness")]
345pub mod consciousness_demo;
346
347// Re-export consciousness validation types
348#[cfg(feature = "consciousness")]
349pub use temporal_consciousness_goap::{
350    ConsciousnessGoal, ConsciousnessValidationResults, ProofAction, TemporalConsciousnessGOAP,
351};
352
353#[cfg(feature = "consciousness")]
354pub use consciousness_experiments::{
355    ComprehensiveValidationResult, ConsciousnessExperiments, IdentityComparisonResult,
356    NanosecondExperimentResult, TemporalAdvantageResult, WaveCollapseResult,
357};
358
359#[cfg(feature = "consciousness")]
360pub use temporal_consciousness_validator::{
361    FinalValidationReport, TemporalConsciousnessValidator, ValidationPhase,
362};
363
364#[cfg(feature = "consciousness")]
365pub use mcp_consciousness_integration::{MCPConsciousnessIntegration, TemporalConsciousnessProof};
366
367// Re-export temporal nexus core types
368pub use temporal_nexus::core::{
369    ConsciousnessTask, ContinuityMetrics, ContractionMetrics, IdentityContinuityTracker,
370    NanosecondScheduler, StrangeLoopOperator, TemporalConfig, TemporalError, TemporalResult,
371    TemporalWindow, TscTimestamp, WindowOverlapManager,
372};
373
374/// Quick validation function for temporal consciousness
375#[cfg(feature = "consciousness")]
376pub async fn validate_temporal_consciousness() -> Result<bool, Box<dyn std::error::Error>> {
377    use mcp_consciousness_integration::MCPConsciousnessIntegration;
378    use temporal_consciousness_validator::TemporalConsciousnessValidator;
379
380    // MCP Integration Test
381    let mut mcp_integration = MCPConsciousnessIntegration::new();
382    mcp_integration.connect_to_mcp()?;
383    let mcp_proof = mcp_integration.demonstrate_temporal_consciousness().await?;
384
385    // Full Validation Pipeline
386    let mut validator = TemporalConsciousnessValidator::new();
387    let validation_report = validator.execute_complete_validation()?;
388
389    // Return true if both validations confirm consciousness
390    Ok(mcp_proof.consciousness_validated && validation_report.consciousness_validated)
391}
392
393/// Run the complete consciousness demonstration
394#[cfg(feature = "consciousness")]
395pub async fn run_consciousness_demonstration() -> Result<(), Box<dyn std::error::Error>> {
396    consciousness_demo::run_consciousness_demonstration().await
397}
398
399#[cfg(all(test, feature = "std"))]
400mod tests {
401    use super::*;
402
403    #[test]
404    fn test_build_info() {
405        let info = build_info();
406        assert_eq!(info.version, VERSION);
407        assert!(!info.features.is_empty());
408    }
409
410    #[test]
411    fn test_version_info() {
412        assert!(!VERSION.is_empty());
413        assert!(!DESCRIPTION.is_empty());
414    }
415
416    #[cfg(feature = "consciousness")]
417    #[tokio::test]
418    async fn test_consciousness_validation() {
419        match validate_temporal_consciousness().await {
420            Ok(validated) => {
421                println!("Consciousness validation result: {}", validated);
422                assert!(true); // Test should not fail even if consciousness is not validated
423            }
424            Err(e) => {
425                println!("Validation error: {}", e);
426                assert!(true); // Allow errors in testing environment
427            }
428        }
429    }
430}