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.0", 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.0**
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// Reactive signals and dataflow
534pub mod reactive;
535// Task dependency graph with scheduling
536pub mod task_graph;
537// Lock-free concurrent data structures (skiplist, B-tree)
538pub mod lock_free;
539// GPU/CPU memory pool management
540pub mod memory_pool;
541// NUMA-aware task scheduling
542pub mod numa_scheduler;
543// Platform compatibility utilities
544pub mod platform_compat;
545// Structured logging framework
546pub mod structured_logging;
547
548// Re-exports
549#[cfg(feature = "cache")]
550pub use crate::cache::*;
551#[cfg(feature = "cloud")]
552pub use crate::cloud::{
553 CloudConfig, CloudCredentials, CloudError, CloudObjectMetadata, CloudProvider,
554 CloudStorageClient, EncryptionConfig, EncryptionMethod, HttpMethod, ListResult,
555 TransferOptions,
556};
557pub use crate::config::production as config_production;
558pub use crate::config::unified as config_unified;
559pub use crate::config::{get_config, get_config_value, set_config_value, Config, ConfigValue};
560pub use crate::constants::{math, physical, prefixes};
561#[allow(ambiguous_glob_reexports)]
562pub use crate::error::*;
563
564// Re-export the array! macro for convenient array creation
565// This addresses the common pain point where users expect array! to be available
566// directly from scirs2_core instead of requiring import from scirs2_autograd
567//
568// # Example
569//
570// ```rust
571// use scirs2_core::array;
572//
573// let matrix = array![[1, 2, 3], [4, 5, 6]];
574// assert_eq!(matrix.shape(), &[2, 3]);
575// ```
576#[cfg(feature = "gpu")]
577pub use crate::gpu::*;
578pub use crate::io::*;
579#[cfg(feature = "jit")]
580pub use crate::jit::DataType as JitDataType;
581#[cfg(feature = "jit")]
582pub use crate::jit::{
583 CompiledKernel, ExecutionProfile, JitBackend, JitCompiler, JitConfig, JitError, KernelLanguage,
584 KernelSource, OptimizationLevel, TargetArchitecture,
585};
586#[cfg(feature = "logging")]
587pub use crate::logging::*;
588#[cfg(feature = "memory_management")]
589pub use crate::memory::{
590 format_memory_report, generate_memory_report, global_buffer_pool, track_allocation,
591 track_deallocation, track_resize, BufferPool, ChunkProcessor, ChunkProcessor2D,
592 GlobalBufferPool, ZeroCopyView,
593};
594
595#[cfg(feature = "mmap")]
596pub use crate::memory::{MmapArray, MmapElement, MmapError};
597// Legacy re-export from ndarray_ext (kept for backward compatibility)
598pub use crate::ndarray_ext::array as array_legacy;
599
600// Complete ndarray functionality through the unified module
601// Use ndarray_ext which has the correct re-exports from ::ndarray
602pub use crate::ndarray_ext::{
603 arr1,
604 arr2,
605 // Essential macros - now available at crate root
606 array,
607 s,
608 // Common types for convenience
609 Array,
610 Array1,
611 Array2,
612 ArrayD,
613 ArrayView,
614 ArrayView1,
615 ArrayView2,
616 ArrayViewMut,
617 Axis,
618 Ix1,
619 Ix2,
620 IxDyn,
621};
622
623#[cfg(feature = "leak_detection")]
624pub use crate::memory::{
625 LeakCheckGuard, LeakDetectionConfig, LeakDetector, LeakReport, LeakType, MemoryCheckpoint,
626 MemoryLeak, ProfilerTool,
627};
628
629#[cfg(feature = "memory_efficient")]
630pub use crate::memory_efficient::{
631 chunk_wise_binary_op, chunk_wise_op, chunk_wise_reduce, create_disk_array, create_mmap,
632 create_temp_mmap, diagonal_view, evaluate, load_chunks, open_mmap, register_fusion,
633 transpose_view, view_as, view_mut_as, AccessMode, AdaptiveChunking, AdaptiveChunkingBuilder,
634 AdaptiveChunkingParams, AdaptiveChunkingResult, ArithmeticOps, BroadcastOps, ChunkIter,
635 ChunkedArray, ChunkingStrategy, DiskBackedArray, FusedOp, LazyArray, LazyOp, LazyOpKind,
636 MemoryMappedArray, MemoryMappedChunkIter, MemoryMappedChunks, MemoryMappedSlice,
637 MemoryMappedSlicing, OpFusion, OutOfCoreArray, ViewMut, ZeroCopyOps,
638};
639
640// Compression-related types are only available with the memory_compression feature
641#[cfg(feature = "memory_compression")]
642pub use crate::memory_efficient::{
643 CompressedMemMapBuilder, CompressedMemMappedArray, CompressionAlgorithm,
644};
645
646// Re-export the parallel memory-mapped array capabilities
647#[cfg(all(feature = "memory_efficient", feature = "parallel"))]
648pub use crate::memory_efficient::MemoryMappedChunksParallel;
649
650#[cfg(feature = "array")]
651pub use crate::array::{
652 is_masked, mask_array, masked_equal, masked_greater, masked_inside, masked_invalid,
653 masked_less, masked_outside, masked_where, record_array_from_typed_arrays,
654 record_array_fromrecords, ArrayError, FieldValue, MaskedArray, Record, RecordArray, NOMASK,
655};
656
657#[cfg(feature = "memory_metrics")]
658pub use crate::memory::metrics::{
659 clear_snapshots,
660 compare_snapshots,
661 // Utility functions
662 format_bytes,
663 format_duration,
664 take_snapshot,
665 MemoryEvent,
666 MemoryEventType,
667 // Core metrics types
668 MemoryMetricsCollector,
669 MemoryMetricsConfig,
670 // Memory snapshots and leak detection
671 MemorySnapshot,
672 SnapshotDiff,
673 // Tracked memory components
674 TrackedBufferPool,
675 TrackedChunkProcessor,
676 TrackedChunkProcessor2D,
677};
678
679#[cfg(feature = "types")]
680pub use crate::batch_conversions::{
681 utils as batch_utils, BatchConversionConfig, BatchConversionResult, BatchConverter,
682 ElementConversionError,
683};
684#[cfg(all(feature = "memory_metrics", feature = "gpu"))]
685pub use crate::memory::metrics::{setup_gpu_memory_tracking, TrackedGpuBuffer, TrackedGpuContext};
686pub use crate::metrics::{
687 global_healthmonitor, global_metrics_registry, Counter, Gauge, HealthCheck, HealthMonitor,
688 Histogram, MetricPoint, MetricType, MetricValue, Timer,
689};
690#[cfg(feature = "ml_pipeline")]
691pub use crate::ml_pipeline::DataType as MLDataType;
692#[cfg(feature = "ml_pipeline")]
693pub use crate::ml_pipeline::{
694 DataBatch, DataSample, FeatureConstraint, FeatureSchema, FeatureTransformer, FeatureValue,
695 MLPipeline, MLPipelineError, ModelPredictor, ModelType, PipelineConfig, PipelineMetrics,
696 PipelineNode, TransformType,
697};
698pub use crate::numeric::*;
699#[cfg(feature = "parallel")]
700pub use crate::parallel::*;
701#[cfg(feature = "parallel")]
702pub use crate::parallel_ops::{
703 is_parallel_enabled, num_threads, par_chunks, par_chunks_mut, par_join, par_scope,
704};
705// Re-export all parallel traits and types
706#[cfg(feature = "parallel")]
707pub use crate::parallel_ops::*;
708#[cfg(feature = "profiling")]
709pub use crate::profiling::{profiling_memory_tracker, Profiler};
710#[cfg(feature = "random")]
711#[allow(ambiguous_glob_reexports)]
712pub use crate::random::*;
713pub use crate::resource::{
714 get_available_memory, get_performance_tier, get_recommended_chunk_size,
715 get_recommended_thread_count, get_system_resources, get_total_memory, is_gpu_available,
716 is_simd_supported, DiscoveryConfig, PerformanceTier, ResourceDiscovery, SystemResources,
717};
718#[cfg(feature = "simd")]
719pub use crate::simd::*;
720#[cfg(feature = "testing")]
721pub use crate::testing::{TestConfig, TestResult, TestRunner, TestSuite};
722#[cfg(feature = "types")]
723pub use crate::types::{convert, ComplexConversionError, ComplexExt, ComplexOps};
724
725// Re-export complex number types for SCIRS2 POLICY compliance
726pub use num_complex::{Complex, Complex32, Complex64};
727
728// Re-export RNG types for SCIRS2 POLICY compliance
729pub use crate::units::{
730 convert, global_unit_registry, unit_value, Dimension, UnitDefinition, UnitRegistry, UnitSystem,
731 UnitValue,
732};
733pub use crate::utils::*;
734pub use crate::validation::production as validation_production;
735pub use crate::validation::{
736 check_finite, check_in_bounds, check_positive, checkarray_finite, checkshape,
737};
738pub use rand_chacha::{ChaCha12Rng, ChaCha20Rng, ChaCha8Rng};
739
740// ================================
741// IDE Integration: Builder Patterns
742// ================================
743
744// Re-export builders at crate root for ergonomic access
745pub use crate::builders::{ArrayBuilder, MatrixBuilder, VectorBuilder};
746
747// ================================
748// IDE Integration: Ergonomic Ops
749// ================================
750
751// Re-export matrix/vector ops at crate root for ergonomic access
752pub use crate::ops::{block_diag, dot as mat_dot, hstack, kron, outer, vstack};
753
754// ================================
755// Prelude Module
756// ================================
757
758/// Convenient re-exports of commonly used items
759///
760/// Import this module to get quick access to the most frequently used
761/// types, traits, and functions in the SciRS2 ecosystem without needing
762/// to remember specific import paths.
763///
764/// # Example
765///
766/// ```rust
767/// use scirs2_core::prelude::*;
768///
769/// let data = array![[1.0, 2.0], [3.0, 4.0]];
770/// ```
771pub mod prelude;
772
773#[cfg(feature = "data_validation")]
774pub use crate::validation::data::DataType as ValidationDataType;
775#[cfg(feature = "data_validation")]
776pub use crate::validation::data::{
777 Constraint, FieldDefinition, ValidationConfig, ValidationError, ValidationResult,
778 ValidationRule, ValidationSchema, Validator,
779};
780
781// Production-level feature re-exports
782pub use crate::observability::{audit, tracing};
783pub use crate::stability::{
784 global_stability_manager, ApiContract, BreakingChange, BreakingChangeType, ConcurrencyContract,
785 MemoryContract, NumericalContract, PerformanceContract, StabilityGuaranteeManager,
786 StabilityLevel, UsageContext,
787};
788pub use crate::versioning::{
789 compatibility, deprecation, migration, negotiation, semantic, ApiVersion, CompatibilityLevel,
790 SupportStatus, Version, VersionManager,
791};
792
793// Advanced optimization and AI feature re-exports
794pub use crate::neural_architecture_search::{
795 ActivationType, Architecture, ArchitecturePerformance, ConnectionType, HardwareConstraints,
796 LayerType, NASStrategy, NeuralArchitectureSearch, OptimizationObjectives, OptimizerType,
797 SearchResults, SearchSpace,
798};
799pub use crate::quantum_optimization::{
800 OptimizationResult, QuantumOptimizer, QuantumParameters, QuantumState, QuantumStrategy,
801};
802
803// Cross-module integration re-exports (v0.2.0)
804pub use crate::integration::{
805 // Configuration
806 config::{
807 global_config, update_global_config, DiagnosticsConfig, EcosystemConfig,
808 EcosystemConfigBuilder, LogLevel, MemoryConfig, ModuleConfig, NumericConfig,
809 ParallelConfig, Precision, PrecisionConfig,
810 },
811 // Type conversion
812 conversion::{
813 ArrayConvert, ConversionError, ConversionOptions, ConversionResult, CrossModuleConvert,
814 DataFlowConverter, LosslessConvert, LossyConvert, TypeAdapter,
815 },
816 // Interface traits
817 traits::{
818 ApiVersion as IntegrationApiVersion, Capability, Composable, Configurable,
819 CrossModuleOperator, DataConsumer, DataProvider, Diagnosable, DiagnosticInfo,
820 DiagnosticLevel, Identifiable, ModuleCapability, ModuleInterface, ResourceAware,
821 ResourceUsage, Serializable, VersionedInterface,
822 },
823 // Zero-copy operations
824 zero_copy::{
825 Alignment, ArrayBridge, BorrowedArray, BufferMut, BufferRef, ContiguousMemory,
826 MemoryLayout, OwnedArray, SharedArrayView, SharedArrayViewMut, TypedBuffer, ZeroCopyBuffer,
827 ZeroCopySlice,
828 },
829 // Error types
830 IntegrationError,
831 IntegrationResult,
832};
833
834// Advanced JIT Compilation re-exports
835// pub use crate::advanced_jit_compilation::{
836// AdaptiveCodeGenerator, CompilationStatistics, JitAnalytics, JitCompilerConfig, JitProfiler,
837// KernelCache, KernelMetadata, KernelPerformance, LlvmCompilationEngine, OptimizationResults,
838// PerformanceImprovement, RuntimeOptimizer, advancedJitCompiler,
839// }; // Missing module
840
841// Advanced Cloud Storage re-exports
842// pub use crate::distributed_storage::{
843// AdaptiveStreamingEngine, CloudPerformanceAnalytics, CloudProviderConfig, CloudProviderId,
844// CloudProviderType, CloudSecurityManager, CloudStorageMonitoring, CloudStorageProvider,
845// DataOptimizationEngine, DownloadRequest, DownloadResponse, IntelligentCacheSystem,
846// ParallelTransferManager, StreamRequest, advancedCloudConfig,
847// advancedCloudStorageCoordinator, UploadRequest, UploadResponse,
848// };
849
850// Benchmarking re-exports
851#[cfg(feature = "benchmarking")]
852pub use crate::benchmarking::{
853 BenchmarkConfig, BenchmarkMeasurement, BenchmarkResult, BenchmarkRunner, BenchmarkStatistics,
854 BenchmarkSuite,
855};
856
857/// ``SciRS2`` core version information
858pub const fn _version() -> &'static str {
859 env!("CARGO_PKG_VERSION")
860}
861
862/// Initialize the library (called automatically)
863#[doc(hidden)]
864#[allow(dead_code)]
865pub fn __init() {
866 use std::sync::Once;
867 static INIT: Once = Once::new();
868
869 INIT.call_once(|| {
870 // Initialize API freeze registry
871 crate::api_freeze::initialize_api_freeze();
872 });
873}
874
875// Ensure initialization happens
876#[doc(hidden)]
877#[used]
878#[cfg_attr(target_os = "linux", link_section = ".init_array")]
879#[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_init_func")]
880#[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")]
881static INIT: extern "C" fn() = {
882 extern "C" fn __init_wrapper() {
883 __init();
884 }
885 __init_wrapper
886};