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.4.2", 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, RngExt};
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.4.2**
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 api_reference;
380pub mod apiversioning;
381#[cfg(feature = "array")]
382pub mod array;
383pub mod array_protocol;
384#[cfg(feature = "arrow")]
385pub mod arrow_compat;
386#[cfg(feature = "types")]
387pub mod batch_conversions;
388/// Bioinformatics utilities: sequence analysis, alignment, statistics, phylogenetics.
389pub mod bioinformatics;
390#[cfg(feature = "cache")]
391pub mod cache;
392pub mod cache_ops;
393pub mod chunking;
394#[cfg(feature = "cloud")]
395pub mod cloud;
396pub mod concurrent;
397pub mod config;
398pub mod constants;
399pub mod distributed;
400pub mod ecosystem;
401pub mod error;
402pub mod out_of_core;
403pub mod streaming_stats;
404// Financial computing extensions (v0.3.0) — option pricing, fixed income, risk, portfolio analytics
405pub mod finance;
406// Computational physics tools (v0.3.0) — classical, thermodynamics, electrodynamics, quantum
407pub mod physics;
408// C ABI FFI module for calling SciRS2 from C, Julia, and other languages (v0.3.0)
409#[cfg(feature = "ffi")]
410pub mod ffi;
411// Cross-module integration framework (v0.2.0)
412#[cfg(feature = "gpu")]
413pub mod gpu;
414#[cfg(feature = "gpu")]
415pub mod gpu_registry;
416pub mod integration;
417pub mod io;
418#[cfg(feature = "jit")]
419pub mod jit;
420#[cfg(feature = "linalg")]
421pub mod linalg;
422#[cfg(feature = "logging")]
423pub mod logging;
424#[cfg(feature = "memory_management")]
425pub mod memory;
426#[cfg(feature = "memory_efficient")]
427pub mod memory_efficient;
428pub mod metrics;
429#[cfg(feature = "ml_pipeline")]
430pub mod ml_pipeline;
431pub mod ndarray;
432pub mod ndarray_ext;
433pub mod numeric;
434#[cfg(feature = "parallel")]
435pub mod parallel;
436#[cfg(feature = "parallel")]
437pub mod parallel_ops;
438pub mod performance;
439pub mod performance_optimization;
440#[cfg(feature = "profiling")]
441pub mod profiling;
442#[cfg(feature = "python")]
443pub mod python;
444#[cfg(feature = "random")]
445pub mod random;
446pub mod resource;
447// Cross-language serialization protocol for .scirs2 files (v0.3.0 Phase 9.2)
448#[cfg(feature = "serialization")]
449pub mod serialization;
450#[cfg(feature = "simd")]
451pub mod simd;
452pub mod simd_aligned;
453pub mod simd_ops;
454#[cfg(feature = "simd")]
455pub mod simd_ops_polynomial;
456#[cfg(feature = "testing")]
457pub mod testing;
458// Universal Functions (ufuncs) module
459pub mod error_templates;
460pub mod safe_ops;
461#[cfg(feature = "types")]
462pub mod types;
463#[cfg(feature = "ufuncs")]
464pub mod ufuncs;
465pub mod units;
466pub mod utils;
467pub mod validation;
468
469// Data preprocessing, splitting, type conversions, and string processing (v0.3.0)
470pub mod data_split;
471pub mod preprocessing;
472pub mod string_ops;
473pub mod type_convert;
474
475// IDE integration: ergonomic builder patterns for array construction (v0.3.0)
476pub mod builders;
477
478// IDE integration: shorthand matrix/vector operations (v0.3.0)
479pub mod ops;
480
481// Embedded systems support (v0.2.0)
482#[cfg(feature = "embedded")]
483pub mod embedded;
484#[cfg(feature = "fixed-point")]
485pub mod fixed_point;
486
487// Production-level features for enterprise deployments
488pub mod enterprise;
489pub mod observability;
490pub mod stability;
491pub mod versioning;
492
493// Advanced optimization and AI features
494pub mod neural_architecture_search;
495pub mod quantum_optimization;
496
497// Advanced Mode Ecosystem Integration
498pub mod advanced_ecosystem_integration;
499
500// Advanced JIT Compilation Framework
501pub mod advanced_jit_compilation;
502
503// Advanced Distributed Computing Framework
504pub mod advanced_distributed_computing;
505
506// Advanced Cloud Storage Framework
507// pub mod distributed_storage; // Module not implemented yet
508
509// Advanced Tensor Cores and Automatic Kernel Tuning Framework
510pub mod advanced_tensor_cores;
511
512// Tensor cores optimization modules
513#[cfg(feature = "gpu")]
514pub mod tensor_cores;
515
516// Benchmarking module
517#[cfg(feature = "benchmarking")]
518pub mod benchmarking;
519
520// Lightweight benchmarking utilities (always available, no feature gate)
521pub mod bench_utils;
522
523// Progress tracking for iterative algorithms (always available, no feature gate)
524pub mod progress;
525
526// SciPy/NumPy migration guide and equivalence reference.
527pub mod scipy_migration;
528
529// Arithmetic operations
530pub mod arithmetic;
531// Concurrent/lock-free collections (RRB-vector, bit vector, flat map, tiny vec)
532pub mod collections;
533// Advanced data structures (RRB-tree persistent vector, etc.)
534pub mod data_structures;
535// Reactive signals and dataflow
536pub mod reactive;
537// Task dependency graph with scheduling
538pub mod task_graph;
539// Lock-free concurrent data structures (skiplist, B-tree)
540pub mod lock_free;
541// GPU/CPU memory pool management
542pub mod memory_pool;
543// NUMA-aware task scheduling
544pub mod numa_scheduler;
545// Platform compatibility utilities
546pub mod platform_compat;
547// Structured logging framework
548pub mod structured_logging;
549
550// Re-exports
551#[cfg(feature = "cache")]
552pub use crate::cache::*;
553#[cfg(feature = "cloud")]
554pub use crate::cloud::{
555    CloudConfig, CloudCredentials, CloudError, CloudObjectMetadata, CloudProvider,
556    CloudStorageClient, EncryptionConfig, EncryptionMethod, HttpMethod, ListResult,
557    TransferOptions,
558};
559pub use crate::config::production as config_production;
560pub use crate::config::unified as config_unified;
561pub use crate::config::{get_config, get_config_value, set_config_value, Config, ConfigValue};
562pub use crate::constants::{math, physical, prefixes};
563#[allow(ambiguous_glob_reexports)]
564pub use crate::error::*;
565
566// Re-export the array! macro for convenient array creation
567// This addresses the common pain point where users expect array! to be available
568// directly from scirs2_core instead of requiring import from scirs2_autograd
569//
570// # Example
571//
572// ```rust
573// use scirs2_core::array;
574//
575// let matrix = array![[1, 2, 3], [4, 5, 6]];
576// assert_eq!(matrix.shape(), &[2, 3]);
577// ```
578#[cfg(feature = "gpu")]
579pub use crate::gpu::*;
580pub use crate::io::*;
581#[cfg(feature = "jit")]
582pub use crate::jit::DataType as JitDataType;
583#[cfg(feature = "jit")]
584pub use crate::jit::{
585    CompiledKernel, ExecutionProfile, JitBackend, JitCompiler, JitConfig, JitError, KernelLanguage,
586    KernelSource, OptimizationLevel, TargetArchitecture,
587};
588#[cfg(feature = "logging")]
589pub use crate::logging::*;
590#[cfg(feature = "memory_management")]
591pub use crate::memory::{
592    format_memory_report, generate_memory_report, global_buffer_pool, track_allocation,
593    track_deallocation, track_resize, BufferPool, ChunkProcessor, ChunkProcessor2D,
594    GlobalBufferPool, ZeroCopyView,
595};
596
597#[cfg(feature = "mmap")]
598pub use crate::memory::{MmapArray, MmapElement, MmapError};
599// Legacy re-export from ndarray_ext (kept for backward compatibility)
600pub use crate::ndarray_ext::array as array_legacy;
601
602// Complete ndarray functionality through the unified module
603// Use ndarray_ext which has the correct re-exports from ::ndarray
604pub use crate::ndarray_ext::{
605    arr1,
606    arr2,
607    // Essential macros - now available at crate root
608    array,
609    s,
610    // Common types for convenience
611    Array,
612    Array1,
613    Array2,
614    ArrayD,
615    ArrayView,
616    ArrayView1,
617    ArrayView2,
618    ArrayViewMut,
619    Axis,
620    Ix1,
621    Ix2,
622    IxDyn,
623};
624
625#[cfg(feature = "leak_detection")]
626pub use crate::memory::{
627    LeakCheckGuard, LeakDetectionConfig, LeakDetector, LeakReport, LeakType, MemoryCheckpoint,
628    MemoryLeak, ProfilerTool,
629};
630
631#[cfg(feature = "memory_efficient")]
632pub use crate::memory_efficient::{
633    chunk_wise_binary_op, chunk_wise_op, chunk_wise_reduce, create_disk_array, create_mmap,
634    create_temp_mmap, diagonal_view, evaluate, load_chunks, open_mmap, register_fusion,
635    transpose_view, view_as, view_mut_as, AccessMode, AdaptiveChunking, AdaptiveChunkingBuilder,
636    AdaptiveChunkingParams, AdaptiveChunkingResult, ArithmeticOps, BroadcastOps, ChunkIter,
637    ChunkedArray, ChunkingStrategy, DiskBackedArray, FusedOp, LazyArray, LazyOp, LazyOpKind,
638    MemoryMappedArray, MemoryMappedChunkIter, MemoryMappedChunks, MemoryMappedSlice,
639    MemoryMappedSlicing, OpFusion, OutOfCoreArray, ViewMut, ZeroCopyOps,
640};
641
642// Compression-related types are only available with the memory_compression feature
643#[cfg(feature = "memory_compression")]
644pub use crate::memory_efficient::{
645    CompressedMemMapBuilder, CompressedMemMappedArray, CompressionAlgorithm,
646};
647
648// Re-export the parallel memory-mapped array capabilities
649#[cfg(all(feature = "memory_efficient", feature = "parallel"))]
650pub use crate::memory_efficient::MemoryMappedChunksParallel;
651
652#[cfg(feature = "array")]
653pub use crate::array::{
654    is_masked, mask_array, masked_equal, masked_greater, masked_inside, masked_invalid,
655    masked_less, masked_outside, masked_where, record_array_from_typed_arrays,
656    record_array_fromrecords, ArrayError, FieldValue, MaskedArray, Record, RecordArray, NOMASK,
657};
658
659#[cfg(feature = "memory_metrics")]
660pub use crate::memory::metrics::{
661    clear_snapshots,
662    compare_snapshots,
663    // Utility functions
664    format_bytes,
665    format_duration,
666    take_snapshot,
667    MemoryEvent,
668    MemoryEventType,
669    // Core metrics types
670    MemoryMetricsCollector,
671    MemoryMetricsConfig,
672    // Memory snapshots and leak detection
673    MemorySnapshot,
674    SnapshotDiff,
675    // Tracked memory components
676    TrackedBufferPool,
677    TrackedChunkProcessor,
678    TrackedChunkProcessor2D,
679};
680
681#[cfg(feature = "types")]
682pub use crate::batch_conversions::{
683    utils as batch_utils, BatchConversionConfig, BatchConversionResult, BatchConverter,
684    ElementConversionError,
685};
686#[cfg(all(feature = "memory_metrics", feature = "gpu"))]
687pub use crate::memory::metrics::{setup_gpu_memory_tracking, TrackedGpuBuffer, TrackedGpuContext};
688pub use crate::metrics::{
689    global_healthmonitor, global_metrics_registry, Counter, Gauge, HealthCheck, HealthMonitor,
690    Histogram, MetricPoint, MetricType, MetricValue, Timer,
691};
692#[cfg(feature = "ml_pipeline")]
693pub use crate::ml_pipeline::DataType as MLDataType;
694#[cfg(feature = "ml_pipeline")]
695pub use crate::ml_pipeline::{
696    DataBatch, DataSample, FeatureConstraint, FeatureSchema, FeatureTransformer, FeatureValue,
697    MLPipeline, MLPipelineError, ModelPredictor, ModelType, PipelineConfig, PipelineMetrics,
698    PipelineNode, TransformType,
699};
700pub use crate::numeric::*;
701#[cfg(feature = "parallel")]
702pub use crate::parallel::*;
703#[cfg(feature = "parallel")]
704pub use crate::parallel_ops::{
705    is_parallel_enabled, num_threads, par_chunks, par_chunks_mut, par_join, par_scope,
706};
707// Re-export all parallel traits and types
708#[cfg(feature = "parallel")]
709pub use crate::parallel_ops::*;
710#[cfg(feature = "profiling")]
711pub use crate::profiling::{profiling_memory_tracker, Profiler};
712#[cfg(feature = "random")]
713#[allow(ambiguous_glob_reexports)]
714pub use crate::random::*;
715pub use crate::resource::{
716    get_available_memory, get_performance_tier, get_recommended_chunk_size,
717    get_recommended_thread_count, get_system_resources, get_total_memory, is_gpu_available,
718    is_simd_supported, DiscoveryConfig, PerformanceTier, ResourceDiscovery, SystemResources,
719};
720#[cfg(feature = "simd")]
721pub use crate::simd::*;
722#[cfg(feature = "testing")]
723pub use crate::testing::{TestConfig, TestResult, TestRunner, TestSuite};
724#[cfg(feature = "types")]
725pub use crate::types::{convert, ComplexConversionError, ComplexExt, ComplexOps};
726
727// Re-export complex number types for SCIRS2 POLICY compliance
728pub use num_complex::{Complex, Complex32, Complex64};
729
730// Re-export RNG types for SCIRS2 POLICY compliance
731pub use crate::units::{
732    convert, global_unit_registry, unit_value, Dimension, UnitDefinition, UnitRegistry, UnitSystem,
733    UnitValue,
734};
735pub use crate::utils::*;
736pub use crate::validation::production as validation_production;
737pub use crate::validation::{
738    check_finite, check_in_bounds, check_positive, checkarray_finite, checkshape,
739};
740pub use rand_chacha::{ChaCha12Rng, ChaCha20Rng, ChaCha8Rng};
741
742// ================================
743// IDE Integration: Builder Patterns
744// ================================
745
746// Re-export builders at crate root for ergonomic access
747pub use crate::builders::{ArrayBuilder, MatrixBuilder, VectorBuilder};
748
749// ================================
750// IDE Integration: Ergonomic Ops
751// ================================
752
753// Re-export matrix/vector ops at crate root for ergonomic access
754pub use crate::ops::{block_diag, dot as mat_dot, hstack, kron, outer, vstack};
755
756// ================================
757// Prelude Module
758// ================================
759
760/// Convenient re-exports of commonly used items
761///
762/// Import this module to get quick access to the most frequently used
763/// types, traits, and functions in the SciRS2 ecosystem without needing
764/// to remember specific import paths.
765///
766/// # Example
767///
768/// ```rust
769/// use scirs2_core::prelude::*;
770///
771/// let data = array![[1.0, 2.0], [3.0, 4.0]];
772/// ```
773pub mod prelude;
774
775#[cfg(feature = "data_validation")]
776pub use crate::validation::data::DataType as ValidationDataType;
777#[cfg(feature = "data_validation")]
778pub use crate::validation::data::{
779    Constraint, FieldDefinition, ValidationConfig, ValidationError, ValidationResult,
780    ValidationRule, ValidationSchema, Validator,
781};
782
783// Production-level feature re-exports
784pub use crate::observability::{audit, tracing};
785pub use crate::stability::{
786    global_stability_manager, ApiContract, BreakingChange, BreakingChangeType, ConcurrencyContract,
787    MemoryContract, NumericalContract, PerformanceContract, StabilityGuaranteeManager,
788    StabilityLevel, UsageContext,
789};
790pub use crate::versioning::{
791    compatibility, deprecation, migration, negotiation, semantic, ApiVersion, CompatibilityLevel,
792    SupportStatus, Version, VersionManager,
793};
794
795// Advanced optimization and AI feature re-exports
796pub use crate::neural_architecture_search::{
797    ActivationType, Architecture, ArchitecturePerformance, ConnectionType, HardwareConstraints,
798    LayerType, NASStrategy, NeuralArchitectureSearch, OptimizationObjectives, OptimizerType,
799    SearchResults, SearchSpace,
800};
801pub use crate::quantum_optimization::{
802    OptimizationResult, QuantumOptimizer, QuantumParameters, QuantumState, QuantumStrategy,
803};
804
805// Cross-module integration re-exports (v0.2.0)
806pub use crate::integration::{
807    // Configuration
808    config::{
809        global_config, update_global_config, DiagnosticsConfig, EcosystemConfig,
810        EcosystemConfigBuilder, LogLevel, MemoryConfig, ModuleConfig, NumericConfig,
811        ParallelConfig, Precision, PrecisionConfig,
812    },
813    // Type conversion
814    conversion::{
815        ArrayConvert, ConversionError, ConversionOptions, ConversionResult, CrossModuleConvert,
816        DataFlowConverter, LosslessConvert, LossyConvert, TypeAdapter,
817    },
818    // Interface traits
819    traits::{
820        ApiVersion as IntegrationApiVersion, Capability, Composable, Configurable,
821        CrossModuleOperator, DataConsumer, DataProvider, Diagnosable, DiagnosticInfo,
822        DiagnosticLevel, Identifiable, ModuleCapability, ModuleInterface, ResourceAware,
823        ResourceUsage, Serializable, VersionedInterface,
824    },
825    // Zero-copy operations
826    zero_copy::{
827        Alignment, ArrayBridge, BorrowedArray, BufferMut, BufferRef, ContiguousMemory,
828        MemoryLayout, OwnedArray, SharedArrayView, SharedArrayViewMut, TypedBuffer, ZeroCopyBuffer,
829        ZeroCopySlice,
830    },
831    // Error types
832    IntegrationError,
833    IntegrationResult,
834};
835
836// Advanced JIT Compilation re-exports
837// pub use crate::advanced_jit_compilation::{
838//     AdaptiveCodeGenerator, CompilationStatistics, JitAnalytics, JitCompilerConfig, JitProfiler,
839//     KernelCache, KernelMetadata, KernelPerformance, LlvmCompilationEngine, OptimizationResults,
840//     PerformanceImprovement, RuntimeOptimizer, advancedJitCompiler,
841// }; // Missing module
842
843// Advanced Cloud Storage re-exports
844// pub use crate::distributed_storage::{
845//     AdaptiveStreamingEngine, CloudPerformanceAnalytics, CloudProviderConfig, CloudProviderId,
846//     CloudProviderType, CloudSecurityManager, CloudStorageMonitoring, CloudStorageProvider,
847//     DataOptimizationEngine, DownloadRequest, DownloadResponse, IntelligentCacheSystem,
848//     ParallelTransferManager, StreamRequest, advancedCloudConfig,
849//     advancedCloudStorageCoordinator, UploadRequest, UploadResponse,
850// };
851
852// Benchmarking re-exports
853#[cfg(feature = "benchmarking")]
854pub use crate::benchmarking::{
855    BenchmarkConfig, BenchmarkMeasurement, BenchmarkResult, BenchmarkRunner, BenchmarkStatistics,
856    BenchmarkSuite,
857};
858
859/// ``SciRS2`` core version information
860pub const fn _version() -> &'static str {
861    env!("CARGO_PKG_VERSION")
862}
863
864/// Initialize the library (called automatically)
865#[doc(hidden)]
866#[allow(dead_code)]
867pub fn __init() {
868    use std::sync::Once;
869    static INIT: Once = Once::new();
870
871    INIT.call_once(|| {
872        // Initialize API freeze registry
873        crate::api_freeze::initialize_api_freeze();
874    });
875}
876
877// Ensure initialization happens
878#[doc(hidden)]
879#[used]
880#[cfg_attr(target_os = "linux", link_section = ".init_array")]
881#[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_init_func")]
882#[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")]
883static INIT: extern "C" fn() = {
884    extern "C" fn __init_wrapper() {
885        __init();
886    }
887    __init_wrapper
888};