sublinear 0.3.3

High-performance sublinear-time solver for asymmetric diagonally dominant systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! # Sublinear-Time Solver for Asymmetric Diagonally Dominant Systems
//!
//! This crate implements cutting-edge sublinear-time algorithms for solving linear systems
//! of the form Ax = b where A is an asymmetric diagonally dominant matrix.
//!
//! ## Key Features
//!
//! - **Sublinear Time Complexity**: O(log^k n) for well-conditioned systems
//! - **Multiple Algorithms**: Neumann series, forward/backward push, hybrid random-walk
//! - **Incremental Updates**: Fast cost propagation for dynamic systems
//! - **WASM Compatible**: Cross-platform deployment via WebAssembly
//! - **High Performance**: SIMD optimization and cache-friendly data structures
//!
//! ## Quick Start
//!
//! ```no_run
//! use sublinear_solver::{SparseMatrix, NeumannSolver, SolverAlgorithm, SolverOptions};
//!
//! // Create a diagonally dominant matrix (`from_triplets` returns a Result;
//! // unwrap the SparseMatrix before passing to the solver).
//! let matrix = SparseMatrix::from_triplets(
//!     vec![(0, 0, 5.0), (0, 1, 1.0), (1, 0, 2.0), (1, 1, 7.0)],
//!     2, 2
//! ).expect("valid triplets");
//!
//! // Set up the right-hand side
//! let b = vec![6.0, 9.0];
//!
//! // Solve using Neumann series
//! let solver = NeumannSolver::new(16, 1e-8);
//! let result = solver.solve(&matrix, &b, &SolverOptions::default())?;
//!
//! println!("Solution: {:?}", result.solution);
//! println!("Converged in {} iterations", result.iterations);
//! # Ok::<(), sublinear_solver::SolverError>(())
//! ```
//!
//! ## Algorithms
//!
//! ### Neumann Series Solver
//! Uses the matrix series expansion (I - M)^(-1) = Σ M^k for solving systems.
//! Optimal for well-conditioned diagonally dominant matrices.
//!
//! ### Forward/Backward Push
//! Graph-based algorithms that propagate residuals locally, achieving
//! sublinear complexity for sparse systems with good graph structure.
//!
//! ### Hybrid Random-Walk
//! Combines stochastic estimation with deterministic push methods for
//! robust performance across different problem types.
//!
//! ## WebAssembly Support
//!
//! Enable the `wasm` feature for browser and Node.js deployment:
//!
//! ```toml
//! [dependencies]
//! sublinear-solver = { version = "0.1", features = ["wasm"] }
//! ```

#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs, clippy::all)]
#![allow(clippy::float_cmp)] // Numerical code often requires exact comparisons

// External crate imports
extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

// Re-export commonly used types
pub use error::{Result, SolverError};
pub use matrix::{Matrix, SparseFormat, SparseMatrix};
pub use solver::{
    BackwardPushSolver, ForwardPushSolver, HybridSolver, NeumannSolver, PartialSolution,
    SolverAlgorithm, SolverOptions, SolverResult,
};
pub use types::{ConvergenceMode, EdgeId, ErrorBounds, NodeId, NormType, Precision, SolverStats};

// Sublinear algorithms with true O(log n) complexity
pub use sublinear::sublinear_neumann::{SublinearNeumannResult, SublinearNeumannSolver};
pub use sublinear::{ComplexityBound, SublinearConfig, SublinearSolver};

// SIMD operations for high performance
#[cfg(any(feature = "simd", feature = "std"))]
pub use simd_ops::{axpy_simd, dot_product_simd, matrix_vector_multiply_simd};

#[cfg(feature = "std")]
pub use simd_ops::parallel_matrix_vector_multiply;

// Optimized solver for best performance
pub use optimized_solver::{OptimizedConjugateGradientSolver, OptimizedSparseMatrix};

// WASM-compatible re-exports
pub use math_wasm::{Matrix as WasmMatrix, Vector as WasmVector};
pub use solver_core::{ConjugateGradientSolver, SolverConfig as WasmSolverConfig};

#[cfg(feature = "wasm")]
pub use wasm_iface::{MatrixView, SolutionStep, WasmSublinearSolver};

// Core modules
pub mod error;
pub mod matrix;
pub mod solver;
pub mod types;

// Complexity-class declarations — every public solver / sampler / analyser
// declares its worst-case class via the `Complexity` trait. See
// `docs/adr/ADR-001-complexity-as-architecture.md` for the strategic
// context (complexity classes as architectural primitives in the broader
// RuVector / RuView / Cognitum / Ruflo stack).
pub mod complexity;
pub use complexity::{Complexity, ComplexityClass, ComplexityIntrospect};

// Coherence gate (ADR-001 roadmap item #3). Refuses polynomial-time solves
// on near-singular systems. Opt-in via `SolverOptions::coherence_threshold`.
pub mod coherence;
pub use coherence::{check_coherence_or_reject, coherence_score};

// Event-gated incremental solve (ADR-001 roadmap item #2). Warm-starts
// the underlying iterative solver from the previous solution when only a
// sparse delta of the RHS changed — central to the ADR's "intelligence
// is sparse, event-driven activation" thesis.
pub mod incremental;
pub use coherence::{
    approximate_spectral_radius, delta_below_solve_threshold, delta_inf_bound,
    optimal_neumann_terms, optimal_neumann_terms_with_rho, CoherenceCache,
};
pub use incremental::{
    solve_on_change_sublinear, solve_on_change_sublinear_auto,
    solve_on_change_sublinear_auto_with_rho, IncrementalConfig, IncrementalSolver,
    SolveOnChangeSublinearOp, SparseDelta,
};

// Bounding planning across chains of solves (ADR-001 #4 phase-3).
// MCP's enforceComplexityBudget gates one solve at a time; PlanBudget
// gates the *plan* — the chain of solves an agent intends to run.
pub mod budget;
pub use budget::{BudgetExhausted, PlanBudget};

// Sparse solve witness (ADR-001 open question #3). Per-entry residual
// audit restricted to the closure; same SubLinear complexity class as
// the orchestrator whose output it verifies.
pub mod witness;
pub use witness::{verify_sparse_solution, VerifySparseSolutionOp, WitnessReport};

// Streaming event iterator over the SubLinear orchestrator. The native
// surface RuView/Cognitum agents call to process sensor/log/metric
// event streams. Composes with stdlib Iterator + the skip gate +
// PlanBudget for end-to-end bounded processing.
pub mod stream;
pub use stream::{
    event_stream_iter, EventStatus, EventStreamConfig, EventStreamOp, ProcessedEvent,
};

// Contrastive search (ADR-001 roadmap item #6). Boundary-crossing primitive
// for change-driven activation: which rows of the current solution diverged
// most from baseline? Backbone of RuView / Cognitum wake-on-event.
pub mod contrastive;
pub use contrastive::{
    contrastive_solve_on_change, contrastive_solve_on_change_sublinear,
    contrastive_solve_on_change_sublinear_auto,
    contrastive_solve_on_change_sublinear_auto_with_rho, find_anomalous_rows,
    find_anomalous_rows_in_subset, find_rows_above_threshold, AnomalyRow,
    ContrastiveSolveOnChangeOp, ContrastiveSolveOnChangeSublinearOp,
};

// Bounded-depth row-graph closure (ADR-001 #6 phase-2A). Turns a sparse
// RHS delta into the candidate set of rows whose solution might have
// changed — the input to a true sub-linear contrastive solve. Composes
// with `incremental::SparseDelta` and `contrastive::find_anomalous_rows_in_subset`.
pub mod closure;
pub use closure::{closure_indices, ClosureIndicesOp};

// Single-entry sublinear Neumann (ADR-001 #6 phase-2B). Compute `x[i]`
// without materialising the full solution; SubLinear in `n` for sparse
// DD matrices with bounded depth. Inner primitive for the next-revision
// `contrastive_solve_on_change` that drops the orchestrator end-to-end
// to SubLinear.
pub mod entry;
pub use entry::{
    solve_single_entries_neumann, solve_single_entry_neumann, SolveSingleEntryNeumannOp,
};

// Sublinear algorithms with mathematically rigorous O(log n) complexity
pub mod sublinear;

// Optional modules
#[cfg(feature = "wasm")]
pub mod wasm_iface;

// Additional WASM-compatible modules
pub mod math_wasm;
pub mod solver_core;

#[cfg(feature = "wasm")]
pub mod wasm;

// High-performance SIMD operations
#[cfg(any(feature = "simd", feature = "std"))]
pub mod simd_ops;

// Optimized solver implementations
pub mod optimized_solver;

#[cfg(feature = "cli")]
pub mod cli;

#[cfg(feature = "cli")]
pub mod mcp;

// Internal utilities
mod utils;

// Version information
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");

/// Initialize the solver library with default logging configuration.
///
/// This function should be called once at the start of your application
/// to set up proper logging for the solver algorithms.
#[cfg(feature = "std")]
pub fn init() {
    #[cfg(feature = "env_logger")]
    env_logger::try_init().ok();
}

/// Initialize the solver library for WASM environments.
///
/// This sets up console logging for browser environments.
#[cfg(feature = "wasm")]
pub fn init_wasm() {
    #[cfg(feature = "console_error_panic_hook")]
    console_error_panic_hook::set_once();
}

/// Set panic hook for WASM environments
#[cfg(feature = "wasm")]
pub fn set_panic_hook() {
    #[cfg(feature = "console_error_panic_hook")]
    console_error_panic_hook::set_once();
}

/// Check if the current build supports SIMD optimizations.
pub fn has_simd_support() -> bool {
    #[cfg(feature = "simd")]
    {
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        {
            is_x86_feature_detected!("avx2")
        }
        #[cfg(target_arch = "aarch64")]
        {
            std::arch::is_aarch64_feature_detected!("neon")
        }
        #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
        {
            false
        }
    }
    #[cfg(not(feature = "simd"))]
    {
        false
    }
}

/// Get information about the current solver build.
pub fn build_info() -> BuildInfo {
    BuildInfo {
        version: VERSION,
        features: get_enabled_features(),
        simd_support: has_simd_support(),
        target_arch: "wasm32",
        target_os: "unknown",
    }
}

/// Information about the current build configuration.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BuildInfo {
    /// Library version
    pub version: &'static str,
    /// Enabled feature flags
    pub features: Vec<&'static str>,
    /// Whether SIMD optimizations are available
    pub simd_support: bool,
    /// Target architecture
    pub target_arch: &'static str,
    /// Target operating system
    pub target_os: &'static str,
}

fn get_enabled_features() -> Vec<&'static str> {
    let mut features = Vec::new();

    #[cfg(feature = "std")]
    features.push("std");

    #[cfg(feature = "wasm")]
    features.push("wasm");

    #[cfg(feature = "cli")]
    features.push("cli");

    #[cfg(feature = "simd")]
    features.push("simd");

    features
}

// Optional dependency re-exports
#[cfg(feature = "wasm")]
pub use wasm_bindgen;

#[cfg(feature = "wasm")]
pub use js_sys;

#[cfg(feature = "wasm")]
pub use web_sys;

// Temporal Consciousness Validation Modules
/// Temporal consciousness validation using GOAP and sublinear optimization
#[cfg(feature = "consciousness")]
pub mod temporal_consciousness_goap;

/// Experimental validation protocols for consciousness theories
#[cfg(feature = "consciousness")]
pub mod consciousness_experiments;

/// Main validation pipeline coordinator
#[cfg(feature = "consciousness")]
pub mod temporal_consciousness_validator;

/// Integration with sublinear solver MCP tools
#[cfg(feature = "consciousness")]
pub mod mcp_consciousness_integration;

/// Temporal Nexus - Nanosecond Scheduler for Temporal Consciousness
pub mod temporal_nexus;

/// Executable demonstration of consciousness validation
#[cfg(feature = "consciousness")]
pub mod consciousness_demo;

// Re-export consciousness validation types
#[cfg(feature = "consciousness")]
pub use temporal_consciousness_goap::{
    ConsciousnessGoal, ConsciousnessValidationResults, ProofAction, TemporalConsciousnessGOAP,
};

#[cfg(feature = "consciousness")]
pub use consciousness_experiments::{
    ComprehensiveValidationResult, ConsciousnessExperiments, IdentityComparisonResult,
    NanosecondExperimentResult, TemporalAdvantageResult, WaveCollapseResult,
};

#[cfg(feature = "consciousness")]
pub use temporal_consciousness_validator::{
    FinalValidationReport, TemporalConsciousnessValidator, ValidationPhase,
};

#[cfg(feature = "consciousness")]
pub use mcp_consciousness_integration::{MCPConsciousnessIntegration, TemporalConsciousnessProof};

// Re-export temporal nexus core types
pub use temporal_nexus::core::{
    ConsciousnessTask, ContinuityMetrics, ContractionMetrics, IdentityContinuityTracker,
    NanosecondScheduler, StrangeLoopOperator, TemporalConfig, TemporalError, TemporalResult,
    TemporalWindow, TscTimestamp, WindowOverlapManager,
};

/// Quick validation function for temporal consciousness
#[cfg(feature = "consciousness")]
pub async fn validate_temporal_consciousness() -> Result<bool, Box<dyn std::error::Error>> {
    use mcp_consciousness_integration::MCPConsciousnessIntegration;
    use temporal_consciousness_validator::TemporalConsciousnessValidator;

    // MCP Integration Test
    let mut mcp_integration = MCPConsciousnessIntegration::new();
    mcp_integration.connect_to_mcp()?;
    let mcp_proof = mcp_integration.demonstrate_temporal_consciousness().await?;

    // Full Validation Pipeline
    let mut validator = TemporalConsciousnessValidator::new();
    let validation_report = validator.execute_complete_validation()?;

    // Return true if both validations confirm consciousness
    Ok(mcp_proof.consciousness_validated && validation_report.consciousness_validated)
}

/// Run the complete consciousness demonstration
#[cfg(feature = "consciousness")]
pub async fn run_consciousness_demonstration() -> Result<(), Box<dyn std::error::Error>> {
    consciousness_demo::run_consciousness_demonstration().await
}

#[cfg(all(test, feature = "std"))]
mod tests {
    use super::*;

    #[test]
    fn test_build_info() {
        let info = build_info();
        assert_eq!(info.version, VERSION);
        assert!(!info.features.is_empty());
    }

    #[test]
    fn test_version_info() {
        assert!(!VERSION.is_empty());
        assert!(!DESCRIPTION.is_empty());
    }

    #[cfg(feature = "consciousness")]
    #[tokio::test]
    async fn test_consciousness_validation() {
        match validate_temporal_consciousness().await {
            Ok(validated) => {
                println!("Consciousness validation result: {}", validated);
                assert!(true); // Test should not fail even if consciousness is not validated
            }
            Err(e) => {
                println!("Validation error: {}", e);
                assert!(true); // Allow errors in testing environment
            }
        }
    }
}