Skip to main content

scirs2_core/
lib.rs

1// Embedded systems support (v0.2.0) - no_std compatibility
2// Enable no_std by default, opt-in to std with the "std" feature
3#![cfg_attr(not(feature = "std"), no_std)]
4#![recursion_limit = "512"]
5// TODO: Remove dead code or justify why it's kept
6#![allow(dead_code)]
7// Clippy allow attributes for non-critical warnings
8#![allow(clippy::empty_line_after_outer_attribute)]
9#![allow(clippy::empty_line_after_doc_comments)]
10#![allow(clippy::manual_clamp)]
11#![allow(clippy::redundant_closure)]
12#![allow(clippy::useless_format)]
13#![allow(clippy::result_large_err)]
14#![allow(clippy::manual_is_multiple_of)]
15#![allow(clippy::manual_div_ceil)]
16#![allow(clippy::enumerate_and_ignore)]
17#![allow(clippy::redundant_pattern_matching)]
18#![allow(clippy::or_fun_call)]
19#![allow(clippy::unnecessary_lazy_evaluations)]
20#![allow(clippy::needless_borrow)]
21#![allow(clippy::derivable_impls)]
22#![allow(clippy::new_without_default)]
23#![allow(clippy::ptr_arg)]
24#![allow(clippy::get_first)]
25#![allow(clippy::needless_range_loop)]
26#![allow(clippy::type_complexity)]
27#![allow(clippy::assertions_on_constants)]
28#![allow(clippy::needless_return)]
29#![allow(clippy::unnecessary_cast)]
30#![allow(clippy::manual_range_contains)]
31#![allow(clippy::empty_line_after_outer_attribute_doc)]
32#![allow(clippy::upper_case_acronyms)]
33#![allow(clippy::excessive_precision)]
34#![allow(clippy::needless_borrows_for_generic_args)]
35#![allow(clippy::empty_line_after_outer_attr)]
36#![allow(clippy::unused_enumerate_index)]
37#![allow(clippy::unwrap_or_default)]
38
39//! # SciRS2 Core - Foundation for Scientific Computing in Rust
40//!
41//! **scirs2-core** is the foundational crate for the SciRS2 scientific computing ecosystem,
42//! providing essential utilities, abstractions, and optimizations used by all SciRS2 modules.
43//!
44//! ## 🎯 Design Philosophy
45//!
46//! - **Zero-Cost Abstractions**: Performance without compromising safety
47//! - **Layered Architecture**: Clear separation between interface and implementation
48//! - **Policy Compliance**: Enforce [SciRS2 POLICY](https://github.com/cool-japan/scirs/blob/master/SCIRS2_POLICY.md) - only scirs2-core uses external dependencies directly
49//! - **Production Ready**: Enterprise-grade error handling, diagnostics, and stability guarantees
50//!
51//! ## 🚀 Key Features
52//!
53//! ### Performance Acceleration
54//!
55//! - **SIMD Operations**: CPU vector instructions (SSE, AVX, NEON) for array operations
56//! - **Parallel Processing**: Multi-threaded execution with intelligent load balancing
57//! - **GPU Acceleration**: Unified interface for CUDA, Metal, OpenCL, and WebGPU
58//! - **Memory Efficiency**: Zero-copy views, memory-mapped arrays, adaptive chunking
59//!
60//! ### Core Utilities
61//!
62//! - **Error Handling**: ML-inspired diagnostics with recovery strategies
63//! - **Validation**: Input checking with informative error messages
64//! - **Caching**: Memoization and result caching for expensive computations
65//! - **Profiling**: Performance monitoring and bottleneck detection
66//!
67//! ### Scientific Infrastructure
68//!
69//! - **Constants**: Physical and mathematical constants (via [`constants`] module)
70//! - **Random Number Generation**: Consistent RNG interface across the ecosystem
71//! - **Complex Numbers**: Type-safe complex arithmetic
72//! - **Array Protocol**: Unified array interface for interoperability
73//!
74//! ## 📦 Module Overview
75//!
76//! ### Performance & Optimization
77//!
78//! | Module | Description |
79//! |--------|-------------|
80//! | `simd_ops` | SIMD-accelerated operations with platform detection |
81//! | `parallel_ops` | Parallel processing primitives |
82//! | `gpu` | GPU acceleration abstractions |
83//! | `memory` | Memory management (buffer pools, zero-copy views) |
84//! | `memory_efficient` | Memory-mapped arrays and lazy evaluation |
85//!
86//! ### Error Handling & Diagnostics
87//!
88//! | Module | Description |
89//! |--------|-------------|
90//! | `error` | Error types and traits |
91//! | `validation` | Input validation utilities |
92//! | `logging` | Structured logging for diagnostics |
93//! | `profiling` | Performance profiling tools |
94//!
95//! ### Scientific Computing Basics
96//!
97//! | Module | Description |
98//! |--------|-------------|
99//! | `ndarray` | Unified ndarray interface (re-exports with SciRS2 extensions) |
100//! | `numeric` | Generic numerical operations |
101//! | `random` | Random number generation |
102//! | `constants` | Mathematical and physical constants |
103//!
104//! ### Infrastructure
105//!
106//! | Module | Description |
107//! |--------|-------------|
108//! | `config` | Configuration management |
109//! | `cache` | Result caching and memoization |
110//! | `io` | I/O utilities |
111//! | `cloud` | Cloud storage integration (S3, GCS, Azure) |
112//!
113//! ## 🚀 Quick Start
114//!
115//! ### Installation
116//!
117//! ```toml
118//! [dependencies]
119//! scirs2-core = { version = "0.1.5", features = ["simd", "parallel"] }
120//! ```
121//!
122//! ### SIMD Operations
123//!
124//! ```rust
125//! use scirs2_core::simd_ops::SimdUnifiedOps;
126//! use ::ndarray::array;
127//!
128//! // Automatic SIMD acceleration based on CPU capabilities
129//! let a = array![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
130//! let b = array![8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0];
131//!
132//! // SIMD-accelerated element-wise addition
133//! let result = f64::simd_add(&a.view(), &b.view());
134//! ```
135//!
136//! ### Parallel Processing
137//!
138//! ```rust
139//! # #[cfg(feature = "parallel")]
140//! # {
141//! use scirs2_core::parallel_ops::*;
142//!
143//! // Parallel iteration over chunks
144//! let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
145//! par_chunks(&data, 3).for_each(|chunk| {
146//!     // Process each chunk in parallel
147//!     let sum: i32 = chunk.iter().sum();
148//!     println!("Chunk sum: {}", sum);
149//! });
150//! # }
151//! ```
152//!
153//! ### Input Validation
154//!
155//! ```rust
156//! use scirs2_core::validation::*;
157//! use scirs2_core::error::CoreResult;
158//! use ::ndarray::Array2;
159//!
160//! fn process_matrix(data: &Array2<f64>, k: usize) -> CoreResult<()> {
161//!     // Validate inputs
162//!     check_positive(k, "k")?;
163//!     checkarray_finite(data, "data")?;
164//!     checkshape(data, &[2, 3], "data")?;
165//!
166//!     // Process data...
167//!     Ok(())
168//! }
169//! # let data = Array2::<f64>::zeros((2, 3));
170//! # let _ = process_matrix(&data, 5);
171//! ```
172//!
173//! ### Constants
174//!
175//! ```rust
176//! use scirs2_core::constants::{math, physical};
177//!
178//! // Mathematical constants
179//! let pi = math::PI;
180//! let e = math::E;
181//!
182//! // Physical constants
183//! let c = physical::SPEED_OF_LIGHT;
184//! let h = physical::PLANCK;
185//! ```
186//!
187//! ### Random Number Generation
188//!
189//! ```rust
190//! # #[cfg(feature = "random")]
191//! # {
192//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
193//! use scirs2_core::random::*;
194//! use rand::Rng;
195//!
196//! // Standard distributions
197//! let mut rng = rand::rng();
198//! let normal = Normal::new(0.0, 1.0)?;
199//! let samples: Vec<f64> = (0..1000).map(|_| normal.sample(&mut rng)).collect();
200//!
201//! let uniform = Uniform::new(0.0, 1.0)?;
202//! let samples: Vec<f64> = (0..1000).map(|_| uniform.sample(&mut rng)).collect();
203//! # Ok(())
204//! # }
205//! # }
206//! ```
207//!
208//! ### Memory-Efficient Operations
209//!
210//! ```rust,no_run
211//! # #[cfg(feature = "memory_efficient")]
212//! # {
213//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
214//! use scirs2_core::memory_efficient::*;
215//! use std::path::Path;
216//! use ::ndarray::Array2;
217//!
218//! // Memory-mapped array for large datasets
219//! let data = Array2::<f64>::zeros((1000, 1000));
220//! let path = Path::new("/path/to/large_file.dat");
221//! let mmap = create_mmap(&data, path, AccessMode::ReadWrite, 0)?;
222//!
223//! // Chunked operations for out-of-core processing
224//! let result = chunk_wise_op(&data, |chunk| {
225//!     chunk.mapv(|x| x * 2.0)
226//! }, ChunkingStrategy::Fixed(10000))?;
227//! # Ok(())
228//! # }
229//! # }
230//! ```
231//!
232//! ## 🏗️ Architecture
233//!
234//! ```text
235//! ┌─────────────────────────────────────────┐
236//! │     SciRS2 Ecosystem Modules            │
237//! │  (linalg, stats, neural, vision, etc.)  │
238//! └─────────────────────────────────────────┘
239//!              ▼
240//! ┌─────────────────────────────────────────┐
241//! │         scirs2-core (This Crate)        │
242//! │  ┌────────────────────────────────────┐ │
243//! │  │  High-Level Abstractions           │ │
244//! │  │  - SIMD Operations                 │ │
245//! │  │  - Parallel Processing             │ │
246//! │  │  - GPU Acceleration                │ │
247//! │  │  - Error Handling                  │ │
248//! │  └────────────────────────────────────┘ │
249//! │  ┌────────────────────────────────────┐ │
250//! │  │  Core Utilities                    │ │
251//! │  │  - Array Protocol                  │ │
252//! │  │  - Validation                      │ │
253//! │  │  - Memory Management               │ │
254//! │  │  - Configuration                   │ │
255//! │  └────────────────────────────────────┘ │
256//! └─────────────────────────────────────────┘
257//!              ▼
258//! ┌─────────────────────────────────────────┐
259//! │     External Dependencies               │
260//! │  (ndarray, rayon, BLAS, etc.)           │
261//! │  ⚠️  Only scirs2-core depends directly  │
262//! └─────────────────────────────────────────┘
263//! ```
264//!
265//! ## 🎨 Feature Flags
266//!
267//! ### Performance Features
268//!
269//! - `simd` - SIMD acceleration (SSE, AVX, NEON)
270//! - `parallel` - Multi-threaded execution via Rayon
271//! - `gpu` - GPU acceleration (CUDA, Metal, OpenCL)
272//!
273//! ### Memory Management
274//!
275//! - `memory_management` - Advanced memory management (buffer pools, tracking)
276//! - `memory_efficient` - Memory-mapped arrays and lazy evaluation
277//! - `memory_metrics` - Memory usage tracking and profiling
278//!
279//! ### Scientific Computing
280//!
281//! - `array` - Scientific array types (MaskedArray, RecordArray)
282//! - `random` - Random number generation
283//! - `linalg` - Linear algebra with BLAS/LAPACK
284//!
285//! ### Development & Debugging
286//!
287//! - `validation` - Input validation (recommended for development)
288//! - `logging` - Structured logging
289//! - `profiling` - Performance profiling
290//! - `testing` - Testing utilities
291//!
292//! ### Advanced Features
293//!
294//! - `cloud` - Cloud storage (S3, GCS, Azure)
295//! - `jit` - Just-in-time compilation with LLVM
296//! - `ml_pipeline` - ML pipeline integration
297//!
298//! ### Convenience
299//!
300//! - `default` - Commonly used features (parallel, validation)
301//! - `all` - All features except backend-specific ones
302//!
303//! ## 🔒 SciRS2 Policy Compliance
304//!
305//! **Important**: scirs2-core is the **only** crate in the SciRS2 ecosystem that directly
306//! depends on external crates like `ndarray`, `rand`, `rayon`, etc.
307//!
308//! All other SciRS2 crates **must** use abstractions provided by scirs2-core:
309//!
310//! ```rust,ignore
311//! // ✅ CORRECT: Use scirs2-core abstractions
312//! use scirs2_core::crate::ndarray::Array2;
313//! use scirs2_core::random::Normal;
314//! use scirs2_core::parallel_ops::*;
315//!
316//! // ❌ WRONG: Don't import external deps directly in other crates
317//! // use ::ndarray::Array2;       // NO!
318//! // use rand_distr::Normal;    // NO!
319//! // use rayon::prelude::*;     // NO!
320//! ```
321//!
322//! This policy ensures:
323//! - Consistent APIs across the ecosystem
324//! - Centralized version management
325//! - Easy addition of SciRS2-specific extensions
326//! - Better compile times through reduced duplication
327//!
328//! ## 📊 Performance
329//!
330//! scirs2-core provides multiple optimization levels:
331//!
332//! | Feature | Speedup | Use Case |
333//! |---------|---------|----------|
334//! | SIMD | 2-8x | Array operations, numerical computations |
335//! | Parallel | 2-16x | Large datasets, independent operations |
336//! | GPU | 10-100x | Massive parallelism, deep learning |
337//! | Memory-mapped | ∞ | Out-of-core processing, datasets larger than RAM |
338//!
339//! ### Platform Detection
340//!
341//! Automatic CPU feature detection for optimal SIMD usage:
342//!
343//! ```rust
344//! use scirs2_core::simd_ops::PlatformCapabilities;
345//!
346//! let caps = PlatformCapabilities::detect();
347//! println!("SIMD available: {}", caps.simd_available);
348//! println!("AVX2 available: {}", caps.avx2_available);
349//! println!("GPU available: {}", caps.gpu_available);
350//! ```
351//!
352//! ## 🔗 Integration
353//!
354//! scirs2-core integrates seamlessly with the Rust ecosystem:
355//!
356//! - **ndarray**: Core array operations
357//! - **num-traits**: Generic numeric operations
358//! - **rayon**: Parallel processing
359//! - **BLAS/LAPACK**: Optimized linear algebra
360//!
361//! ## 🔒 Version
362//!
363//! Current version: **0.1.5** (Released January 15, 2026)
364//!
365//! ## 📚 Examples
366//!
367//! See the [examples directory](https://github.com/cool-japan/scirs/tree/master/scirs2-core/examples)
368//! for more detailed usage examples.
369
370// Use alloc when available but not in std mode
371#[cfg(all(feature = "alloc", not(feature = "std")))]
372extern crate alloc;
373
374// Re-export std as alloc when std is enabled for compatibility
375#[cfg(feature = "std")]
376extern crate std;
377
378pub mod api_freeze;
379pub mod apiversioning;
380#[cfg(feature = "array")]
381pub mod array;
382pub mod array_protocol;
383#[cfg(feature = "arrow")]
384pub mod arrow_compat;
385#[cfg(feature = "types")]
386pub mod batch_conversions;
387/// Bioinformatics utilities: sequence analysis, alignment, statistics, phylogenetics.
388pub mod bioinformatics;
389#[cfg(feature = "cache")]
390pub mod cache;
391pub mod cache_ops;
392pub mod chunking;
393#[cfg(feature = "cloud")]
394pub mod cloud;
395pub mod config;
396pub mod constants;
397pub mod distributed;
398pub mod ecosystem;
399pub mod error;
400pub mod out_of_core;
401pub mod streaming_stats;
402// Financial computing extensions (v0.3.0) — option pricing, fixed income, risk, portfolio analytics
403pub mod finance;
404// Computational physics tools (v0.3.0) — classical, thermodynamics, electrodynamics, quantum
405pub mod physics;
406// C ABI FFI module for calling SciRS2 from C, Julia, and other languages (v0.3.0)
407#[cfg(feature = "ffi")]
408pub mod ffi;
409// Cross-module integration framework (v0.2.0)
410#[cfg(feature = "gpu")]
411pub mod gpu;
412#[cfg(feature = "gpu")]
413pub mod gpu_registry;
414pub mod integration;
415pub mod io;
416#[cfg(feature = "jit")]
417pub mod jit;
418#[cfg(feature = "linalg")]
419pub mod linalg;
420#[cfg(feature = "logging")]
421pub mod logging;
422#[cfg(feature = "memory_management")]
423pub mod memory;
424#[cfg(feature = "memory_efficient")]
425pub mod memory_efficient;
426pub mod metrics;
427#[cfg(feature = "ml_pipeline")]
428pub mod ml_pipeline;
429pub mod ndarray;
430pub mod ndarray_ext;
431pub mod numeric;
432#[cfg(feature = "parallel")]
433pub mod parallel;
434#[cfg(feature = "parallel")]
435pub mod parallel_ops;
436pub mod performance;
437pub mod performance_optimization;
438#[cfg(feature = "profiling")]
439pub mod profiling;
440#[cfg(feature = "python")]
441pub mod python;
442#[cfg(feature = "random")]
443pub mod random;
444pub mod resource;
445// Cross-language serialization protocol for .scirs2 files (v0.3.0 Phase 9.2)
446#[cfg(feature = "serialization")]
447pub mod serialization;
448#[cfg(feature = "simd")]
449pub mod simd;
450pub mod simd_aligned;
451pub mod simd_ops;
452#[cfg(feature = "simd")]
453pub mod simd_ops_polynomial;
454#[cfg(feature = "testing")]
455pub mod testing;
456// Universal Functions (ufuncs) module
457pub mod error_templates;
458pub mod safe_ops;
459#[cfg(feature = "types")]
460pub mod types;
461#[cfg(feature = "ufuncs")]
462pub mod ufuncs;
463pub mod units;
464pub mod utils;
465pub mod validation;
466
467// Data preprocessing, splitting, type conversions, and string processing (v0.3.0)
468pub mod data_split;
469pub mod preprocessing;
470pub mod string_ops;
471pub mod type_convert;
472
473// IDE integration: ergonomic builder patterns for array construction (v0.3.0)
474pub mod builders;
475
476// IDE integration: shorthand matrix/vector operations (v0.3.0)
477pub mod ops;
478
479// Embedded systems support (v0.2.0)
480#[cfg(feature = "embedded")]
481pub mod embedded;
482#[cfg(feature = "fixed-point")]
483pub mod fixed_point;
484
485// Production-level features for enterprise deployments
486pub mod observability;
487pub mod stability;
488pub mod versioning;
489
490// Advanced optimization and AI features
491pub mod neural_architecture_search;
492pub mod quantum_optimization;
493
494// Advanced Mode Ecosystem Integration
495pub mod advanced_ecosystem_integration;
496
497// Advanced JIT Compilation Framework
498pub mod advanced_jit_compilation;
499
500// Advanced Distributed Computing Framework
501pub mod advanced_distributed_computing;
502
503// Advanced Cloud Storage Framework
504// pub mod distributed_storage; // Module not implemented yet
505
506// Advanced Tensor Cores and Automatic Kernel Tuning Framework
507pub mod advanced_tensor_cores;
508
509// Tensor cores optimization modules
510#[cfg(feature = "gpu")]
511pub mod tensor_cores;
512
513// Benchmarking module
514#[cfg(feature = "benchmarking")]
515pub mod benchmarking;
516
517// Lightweight benchmarking utilities (always available, no feature gate)
518pub mod bench_utils;
519
520// Progress tracking for iterative algorithms (always available, no feature gate)
521pub mod progress;
522
523// Re-exports
524#[cfg(feature = "cache")]
525pub use crate::cache::*;
526#[cfg(feature = "cloud")]
527pub use crate::cloud::{
528    CloudConfig, CloudCredentials, CloudError, CloudObjectMetadata, CloudProvider,
529    CloudStorageClient, EncryptionConfig, EncryptionMethod, HttpMethod, ListResult,
530    TransferOptions,
531};
532pub use crate::config::production as config_production;
533pub use crate::config::unified as config_unified;
534pub use crate::config::{get_config, get_config_value, set_config_value, Config, ConfigValue};
535pub use crate::constants::{math, physical, prefixes};
536#[allow(ambiguous_glob_reexports)]
537pub use crate::error::*;
538
539// Re-export the array! macro for convenient array creation
540// This addresses the common pain point where users expect array! to be available
541// directly from scirs2_core instead of requiring import from scirs2_autograd
542//
543// # Example
544//
545// ```rust
546// use scirs2_core::array;
547//
548// let matrix = array![[1, 2, 3], [4, 5, 6]];
549// assert_eq!(matrix.shape(), &[2, 3]);
550// ```
551#[cfg(feature = "gpu")]
552pub use crate::gpu::*;
553pub use crate::io::*;
554#[cfg(feature = "jit")]
555pub use crate::jit::DataType as JitDataType;
556#[cfg(feature = "jit")]
557pub use crate::jit::{
558    CompiledKernel, ExecutionProfile, JitBackend, JitCompiler, JitConfig, JitError, KernelLanguage,
559    KernelSource, OptimizationLevel, TargetArchitecture,
560};
561#[cfg(feature = "logging")]
562pub use crate::logging::*;
563#[cfg(feature = "memory_management")]
564pub use crate::memory::{
565    format_memory_report, generate_memory_report, global_buffer_pool, track_allocation,
566    track_deallocation, track_resize, BufferPool, ChunkProcessor, ChunkProcessor2D,
567    GlobalBufferPool, ZeroCopyView,
568};
569
570#[cfg(feature = "mmap")]
571pub use crate::memory::{MmapArray, MmapElement, MmapError};
572// Legacy re-export from ndarray_ext (kept for backward compatibility)
573pub use crate::ndarray_ext::array as array_legacy;
574
575// Complete ndarray functionality through the unified module
576// Use ndarray_ext which has the correct re-exports from ::ndarray
577pub use crate::ndarray_ext::{
578    arr1,
579    arr2,
580    // Essential macros - now available at crate root
581    array,
582    s,
583    // Common types for convenience
584    Array,
585    Array1,
586    Array2,
587    ArrayD,
588    ArrayView,
589    ArrayView1,
590    ArrayView2,
591    ArrayViewMut,
592    Axis,
593    Ix1,
594    Ix2,
595    IxDyn,
596};
597
598#[cfg(feature = "leak_detection")]
599pub use crate::memory::{
600    LeakCheckGuard, LeakDetectionConfig, LeakDetector, LeakReport, LeakType, MemoryCheckpoint,
601    MemoryLeak, ProfilerTool,
602};
603
604#[cfg(feature = "memory_efficient")]
605pub use crate::memory_efficient::{
606    chunk_wise_binary_op, chunk_wise_op, chunk_wise_reduce, create_disk_array, create_mmap,
607    create_temp_mmap, diagonal_view, evaluate, load_chunks, open_mmap, register_fusion,
608    transpose_view, view_as, view_mut_as, AccessMode, AdaptiveChunking, AdaptiveChunkingBuilder,
609    AdaptiveChunkingParams, AdaptiveChunkingResult, ArithmeticOps, BroadcastOps, ChunkIter,
610    ChunkedArray, ChunkingStrategy, DiskBackedArray, FusedOp, LazyArray, LazyOp, LazyOpKind,
611    MemoryMappedArray, MemoryMappedChunkIter, MemoryMappedChunks, MemoryMappedSlice,
612    MemoryMappedSlicing, OpFusion, OutOfCoreArray, ViewMut, ZeroCopyOps,
613};
614
615// Compression-related types are only available with the memory_compression feature
616#[cfg(feature = "memory_compression")]
617pub use crate::memory_efficient::{
618    CompressedMemMapBuilder, CompressedMemMappedArray, CompressionAlgorithm,
619};
620
621// Re-export the parallel memory-mapped array capabilities
622#[cfg(all(feature = "memory_efficient", feature = "parallel"))]
623pub use crate::memory_efficient::MemoryMappedChunksParallel;
624
625#[cfg(feature = "array")]
626pub use crate::array::{
627    is_masked, mask_array, masked_equal, masked_greater, masked_inside, masked_invalid,
628    masked_less, masked_outside, masked_where, record_array_from_typed_arrays,
629    record_array_fromrecords, ArrayError, FieldValue, MaskedArray, Record, RecordArray, NOMASK,
630};
631
632#[cfg(feature = "memory_metrics")]
633pub use crate::memory::metrics::{
634    clear_snapshots,
635    compare_snapshots,
636    // Utility functions
637    format_bytes,
638    format_duration,
639    take_snapshot,
640    MemoryEvent,
641    MemoryEventType,
642    // Core metrics types
643    MemoryMetricsCollector,
644    MemoryMetricsConfig,
645    // Memory snapshots and leak detection
646    MemorySnapshot,
647    SnapshotDiff,
648    // Tracked memory components
649    TrackedBufferPool,
650    TrackedChunkProcessor,
651    TrackedChunkProcessor2D,
652};
653
654#[cfg(feature = "types")]
655pub use crate::batch_conversions::{
656    utils as batch_utils, BatchConversionConfig, BatchConversionResult, BatchConverter,
657    ElementConversionError,
658};
659#[cfg(all(feature = "memory_metrics", feature = "gpu"))]
660pub use crate::memory::metrics::{setup_gpu_memory_tracking, TrackedGpuBuffer, TrackedGpuContext};
661pub use crate::metrics::{
662    global_healthmonitor, global_metrics_registry, Counter, Gauge, HealthCheck, HealthMonitor,
663    Histogram, MetricPoint, MetricType, MetricValue, Timer,
664};
665#[cfg(feature = "ml_pipeline")]
666pub use crate::ml_pipeline::DataType as MLDataType;
667#[cfg(feature = "ml_pipeline")]
668pub use crate::ml_pipeline::{
669    DataBatch, DataSample, FeatureConstraint, FeatureSchema, FeatureTransformer, FeatureValue,
670    MLPipeline, MLPipelineError, ModelPredictor, ModelType, PipelineConfig, PipelineMetrics,
671    PipelineNode, TransformType,
672};
673pub use crate::numeric::*;
674#[cfg(feature = "parallel")]
675pub use crate::parallel::*;
676#[cfg(feature = "parallel")]
677pub use crate::parallel_ops::{
678    is_parallel_enabled, num_threads, par_chunks, par_chunks_mut, par_join, par_scope,
679};
680// Re-export all parallel traits and types
681#[cfg(feature = "parallel")]
682pub use crate::parallel_ops::*;
683#[cfg(feature = "profiling")]
684pub use crate::profiling::{profiling_memory_tracker, Profiler};
685#[cfg(feature = "random")]
686#[allow(ambiguous_glob_reexports)]
687pub use crate::random::*;
688pub use crate::resource::{
689    get_available_memory, get_performance_tier, get_recommended_chunk_size,
690    get_recommended_thread_count, get_system_resources, get_total_memory, is_gpu_available,
691    is_simd_supported, DiscoveryConfig, PerformanceTier, ResourceDiscovery, SystemResources,
692};
693#[cfg(feature = "simd")]
694pub use crate::simd::*;
695#[cfg(feature = "testing")]
696pub use crate::testing::{TestConfig, TestResult, TestRunner, TestSuite};
697#[cfg(feature = "types")]
698pub use crate::types::{convert, ComplexConversionError, ComplexExt, ComplexOps};
699
700// Re-export complex number types for SCIRS2 POLICY compliance
701pub use num_complex::{Complex, Complex32, Complex64};
702
703// Re-export RNG types for SCIRS2 POLICY compliance
704pub use crate::units::{
705    convert, global_unit_registry, unit_value, Dimension, UnitDefinition, UnitRegistry, UnitSystem,
706    UnitValue,
707};
708pub use crate::utils::*;
709pub use crate::validation::production as validation_production;
710pub use crate::validation::{
711    check_finite, check_in_bounds, check_positive, checkarray_finite, checkshape,
712};
713pub use rand_chacha::{ChaCha12Rng, ChaCha20Rng, ChaCha8Rng};
714
715// ================================
716// IDE Integration: Builder Patterns
717// ================================
718
719// Re-export builders at crate root for ergonomic access
720pub use crate::builders::{ArrayBuilder, MatrixBuilder, VectorBuilder};
721
722// ================================
723// IDE Integration: Ergonomic Ops
724// ================================
725
726// Re-export matrix/vector ops at crate root for ergonomic access
727pub use crate::ops::{block_diag, dot as mat_dot, hstack, kron, outer, vstack};
728
729// ================================
730// Prelude Module
731// ================================
732
733/// Convenient re-exports of commonly used items
734///
735/// Import this module to get quick access to the most frequently used
736/// types, traits, and functions in the SciRS2 ecosystem without needing
737/// to remember specific import paths.
738///
739/// # Example
740///
741/// ```rust
742/// use scirs2_core::prelude::*;
743///
744/// let data = array![[1.0, 2.0], [3.0, 4.0]];
745/// ```
746pub mod prelude;
747
748#[cfg(feature = "data_validation")]
749pub use crate::validation::data::DataType as ValidationDataType;
750#[cfg(feature = "data_validation")]
751pub use crate::validation::data::{
752    Constraint, FieldDefinition, ValidationConfig, ValidationError, ValidationResult,
753    ValidationRule, ValidationSchema, Validator,
754};
755
756// Production-level feature re-exports
757pub use crate::observability::{audit, tracing};
758pub use crate::stability::{
759    global_stability_manager, ApiContract, BreakingChange, BreakingChangeType, ConcurrencyContract,
760    MemoryContract, NumericalContract, PerformanceContract, StabilityGuaranteeManager,
761    StabilityLevel, UsageContext,
762};
763pub use crate::versioning::{
764    compatibility, deprecation, migration, negotiation, semantic, ApiVersion, CompatibilityLevel,
765    SupportStatus, Version, VersionManager,
766};
767
768// Advanced optimization and AI feature re-exports
769pub use crate::neural_architecture_search::{
770    ActivationType, Architecture, ArchitecturePerformance, ConnectionType, HardwareConstraints,
771    LayerType, NASStrategy, NeuralArchitectureSearch, OptimizationObjectives, OptimizerType,
772    SearchResults, SearchSpace,
773};
774pub use crate::quantum_optimization::{
775    OptimizationResult, QuantumOptimizer, QuantumParameters, QuantumState, QuantumStrategy,
776};
777
778// Cross-module integration re-exports (v0.2.0)
779pub use crate::integration::{
780    // Configuration
781    config::{
782        global_config, update_global_config, DiagnosticsConfig, EcosystemConfig,
783        EcosystemConfigBuilder, LogLevel, MemoryConfig, ModuleConfig, NumericConfig,
784        ParallelConfig, Precision, PrecisionConfig,
785    },
786    // Type conversion
787    conversion::{
788        ArrayConvert, ConversionError, ConversionOptions, ConversionResult, CrossModuleConvert,
789        DataFlowConverter, LosslessConvert, LossyConvert, TypeAdapter,
790    },
791    // Interface traits
792    traits::{
793        ApiVersion as IntegrationApiVersion, Capability, Composable, Configurable,
794        CrossModuleOperator, DataConsumer, DataProvider, Diagnosable, DiagnosticInfo,
795        DiagnosticLevel, Identifiable, ModuleCapability, ModuleInterface, ResourceAware,
796        ResourceUsage, Serializable, VersionedInterface,
797    },
798    // Zero-copy operations
799    zero_copy::{
800        Alignment, ArrayBridge, BorrowedArray, BufferMut, BufferRef, ContiguousMemory,
801        MemoryLayout, OwnedArray, SharedArrayView, SharedArrayViewMut, TypedBuffer, ZeroCopyBuffer,
802        ZeroCopySlice,
803    },
804    // Error types
805    IntegrationError,
806    IntegrationResult,
807};
808
809// Advanced JIT Compilation re-exports
810// pub use crate::advanced_jit_compilation::{
811//     AdaptiveCodeGenerator, CompilationStatistics, JitAnalytics, JitCompilerConfig, JitProfiler,
812//     KernelCache, KernelMetadata, KernelPerformance, LlvmCompilationEngine, OptimizationResults,
813//     PerformanceImprovement, RuntimeOptimizer, advancedJitCompiler,
814// }; // Missing module
815
816// Advanced Cloud Storage re-exports
817// pub use crate::distributed_storage::{
818//     AdaptiveStreamingEngine, CloudPerformanceAnalytics, CloudProviderConfig, CloudProviderId,
819//     CloudProviderType, CloudSecurityManager, CloudStorageMonitoring, CloudStorageProvider,
820//     DataOptimizationEngine, DownloadRequest, DownloadResponse, IntelligentCacheSystem,
821//     ParallelTransferManager, StreamRequest, advancedCloudConfig,
822//     advancedCloudStorageCoordinator, UploadRequest, UploadResponse,
823// };
824
825// Benchmarking re-exports
826#[cfg(feature = "benchmarking")]
827pub use crate::benchmarking::{
828    BenchmarkConfig, BenchmarkMeasurement, BenchmarkResult, BenchmarkRunner, BenchmarkStatistics,
829    BenchmarkSuite,
830};
831
832/// ``SciRS2`` core version information
833pub const fn _version() -> &'static str {
834    env!("CARGO_PKG_VERSION")
835}
836
837/// Initialize the library (called automatically)
838#[doc(hidden)]
839#[allow(dead_code)]
840pub fn __init() {
841    use std::sync::Once;
842    static INIT: Once = Once::new();
843
844    INIT.call_once(|| {
845        // Initialize API freeze registry
846        crate::api_freeze::initialize_api_freeze();
847    });
848}
849
850// Ensure initialization happens
851#[doc(hidden)]
852#[used]
853#[cfg_attr(target_os = "linux", link_section = ".init_array")]
854#[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_init_func")]
855#[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")]
856static INIT: extern "C" fn() = {
857    extern "C" fn __init_wrapper() {
858        __init();
859    }
860    __init_wrapper
861};