Skip to main content

sklears_core/
lib.rs

1//! # sklears-core - Core Traits and Utilities
2//!
3//! This crate provides the foundational traits, types, and utilities that power
4//! the entire sklears machine learning ecosystem.
5//!
6//! ## Overview
7//!
8//! `sklears-core` defines the essential building blocks for machine learning in Rust:
9//!
10//! - **Core Traits**: `Estimator`, `Fit`, `Predict`, `Transform`, `Score`
11//! - **Type System**: Type-safe state machines (Untrained/Trained)
12//! - **Error Handling**: Comprehensive error types with context
13//! - **Validation**: Input validation and consistency checks
14//! - **Utilities**: Common helper functions and types
15//! - **Parallel Processing**: Abstractions for parallel algorithms
16//! - **Dataset Handling**: Data loading, splitting, and manipulation
17//!
18//! ## Core Traits
19//!
20//! ### Estimator
21//!
22//! The base trait for all machine learning models:
23//!
24//! ```rust,ignore
25//! pub trait Estimator {
26//!     type Config;
27//!     type Error;
28//! }
29//! ```
30//!
31//! ### Fit
32//!
33//! Training an estimator on data:
34//!
35//! ```rust,ignore
36//! pub trait Fit<X, Y> {
37//!     type Fitted;
38//!     fn fit(self, x: &X, y: &Y) -> Result<Self::Fitted, Self::Error>;
39//! }
40//! ```
41//!
42//! ### Predict
43//!
44//! Making predictions with a trained model:
45//!
46//! ```rust,ignore
47//! pub trait Predict<X, Y> {
48//!     fn predict(&self, x: &X) -> Result<Y, Self::Error>;
49//! }
50//! ```
51//!
52//! ### Transform
53//!
54//! Transforming data (for preprocessing and dimensionality reduction):
55//!
56//! ```rust,ignore
57//! pub trait Transform<X> {
58//!     fn transform(&self, x: &X) -> Result<X, Self::Error>;
59//! }
60//! ```
61//!
62//! ## Type-Safe State Machines
63//!
64//! Models use phantom types to track training state at compile time:
65//!
66//! ```rust,ignore
67//! pub struct Untrained;
68//! pub struct Trained;
69//!
70//! pub struct Model<State = Untrained> {
71//!     config: ModelConfig,
72//!     state: PhantomData<State>,
73//!     weights: Option<Weights>, // Only Some in Trained state
74//! }
75//! ```
76//!
77//! This ensures:
78//! - ✅ Can't predict with an untrained model (compile error)
79//! - ✅ Can't accidentally re-train a trained model
80//! - ✅ Type system enforces correct usage patterns
81//!
82//! ## Error Handling
83//!
84//! Comprehensive error types with rich context:
85//!
86//! ```rust,ignore
87//! pub enum SklearsError {
88//!     InvalidInput(String),
89//!     ShapeMismatch { expected: Shape, got: Shape },
90//!     NotFitted,
91//!     ConvergenceError { iterations: usize },
92//!     // ... and many more
93//! }
94//! ```
95//!
96//! ## Validation
97//!
98//! Input validation utilities ensure data consistency:
99//!
100//! ```rust,ignore
101//! use sklears_core::error::validate;
102//! use sklears_core::types::arrays::validation as array_validation;
103//!
104//! // Check that X and y have compatible shapes
105//! validate::check_consistent_length(x, y)?;
106//!
107//! // Check for NaN/Inf values
108//! array_validation::check_finite(x)?;
109//!
110//! // Validate classification targets
111//! array_validation::check_classification_targets(y)?;
112//! ```
113//!
114//! ## Parallel Processing
115//!
116//! Abstractions for parallel algorithm execution:
117//!
118//! ```rust,ignore
119//! use sklears_core::parallel::ParallelConfig;
120//! use rayon::prelude::*;
121//!
122//! let config = ParallelConfig::new().n_jobs(-1); // Use all cores
123//!
124//! data.par_iter()
125//!     .map(|sample| process(sample))
126//!     .collect()
127//! ```
128//!
129//! ## Feature Flags
130//!
131//! - `simd` - Enable SIMD optimizations
132//! - `gpu_support` - GPU acceleration support
133//! - `arrow` - Apache Arrow interoperability
134//! - `binary` - Binary serialization support
135//!
136//! ## Examples
137//!
138//! See individual module documentation for detailed examples.
139//!
140//! ## Known Limitations
141//!
142//! The following test modules are disabled due to ndarray HRTB (Higher-Ranked Trait Bound)
143//! lifetime constraints introduced in ndarray 0.17. Planned for re-enabling in v0.2.0:
144//! - `property_tests` - Property-based tests requiring trait bound simplification
145//! - `test_utilities` - Test utilities requiring trait bound simplification
146//!
147//! ## Integration
148//!
149//! This crate is re-exported by the main `sklears` crate, so you typically don't
150//! need to depend on it directly unless you're building custom estimators.
151
152pub mod dataset;
153pub mod distributed;
154pub mod distributed_algorithms;
155pub mod error;
156pub mod parallel;
157pub mod system_info;
158pub mod traits;
159pub mod types;
160pub mod utils;
161pub mod validation;
162pub mod validation_examples;
163
164#[cfg(feature = "simd")]
165pub mod simd;
166
167#[cfg(feature = "gpu_support")]
168pub mod gpu;
169
170#[cfg(feature = "arrow")]
171pub mod arrow;
172
173#[cfg(feature = "binary")]
174pub mod binary;
175
176pub mod advanced_array_ops;
177pub mod advanced_benchmarking;
178pub mod algorithm_markers;
179pub mod async_traits;
180pub mod auto_benchmark_generation;
181pub mod autodiff;
182pub mod benchmarking;
183pub mod compatibility;
184pub mod compile_time_macros;
185pub mod compile_time_validation;
186pub mod contract_testing;
187pub mod contribution;
188pub mod dependent_types;
189pub mod derive_macros;
190pub mod dsl_impl;
191pub mod effect_types;
192pub mod ensemble_improvements;
193pub mod exhaustive_error_handling;
194pub mod exotic_hardware;
195pub mod exotic_hardware_impls;
196pub mod fallback_strategies;
197pub mod features;
198pub mod formal_verification;
199pub mod format_io;
200pub mod formatting;
201pub mod memory_safety;
202pub mod mock_objects;
203pub mod performance_profiling;
204pub mod performance_reporting;
205pub mod plugin;
206pub mod plugin_marketplace_impl;
207pub mod refinement_types;
208pub mod streaming_lifetimes;
209pub mod unsafe_audit;
210
211// Export the procedural macros for DSL support
212pub mod macros;
213
214// Modularized API reference system (refactored from api_reference_generator.rs)
215pub mod api_analyzers;
216pub mod api_data_structures;
217pub mod api_formatters;
218pub mod api_generator_config;
219
220// Rich API types consumed by the trait graph visualization system (distinct
221// from the modularized api_data_structures shape used above).
222pub mod api_reference_generator;
223
224pub mod interactive_api_reference;
225pub mod interactive_playground;
226pub mod search_engines;
227pub mod tutorial_examples;
228pub mod tutorial_system;
229pub mod wasm_playground_impl;
230
231// Trait explorer tool for interactive API navigation
232pub mod trait_explorer;
233
234// Public/private API boundaries
235mod private;
236pub mod public;
237
238// Custom lints for ML-specific patterns
239#[cfg(feature = "custom_lints")]
240pub mod lints;
241
242// Dependency audit and optimization
243pub mod dependency_audit;
244
245// Code coverage reporting and enforcement
246pub mod code_coverage;
247
248// Input sanitization for untrusted data
249pub mod input_sanitization;
250
251// KNOWN ISSUE (v0.1.0): Module disabled due to ndarray HRTB lifetime constraints. Planned for v0.2.1.
252// #[allow(non_snake_case)]
253// #[cfg(test)]
254// pub mod property_tests;
255
256// KNOWN ISSUE (v0.1.0): Module disabled due to ndarray HRTB lifetime constraints. Planned for v0.2.1.
257// #[allow(non_snake_case)]
258// #[cfg(test)]
259// pub mod test_utilities;
260
261pub mod prelude {
262    /// Convenient re-exports of the most commonly used types and traits
263    ///
264    /// This prelude is organized by stability guarantees:
265    /// - Stable APIs are always available
266    /// - Experimental APIs require explicit opt-in
267    /// - Deprecated APIs emit warnings
268    // === Stable Public APIs (Always Available) ===
269    // Core traits - guaranteed stable
270    pub use crate::public::stable::{
271        Estimator, Fit, FitPredict, FitTransform, PartialFit, Predict, Transform,
272    };
273
274    // Core types - guaranteed stable
275    pub use crate::public::stable::{
276        Array1, Array2, ArrayView1, ArrayView2, ArrayViewMut1, ArrayViewMut2, FeatureCount,
277        Features, Float, FloatBounds, Int, IntBounds, Labels, Numeric, Predictions, Probabilities,
278        Probability, SampleCount, Target,
279    };
280
281    // Error handling - guaranteed stable
282    pub use crate::public::stable::{ErrorChain, ErrorContext, Result, SklearsError};
283
284    // Validation - guaranteed stable
285    pub use crate::public::stable::{Validate, ValidationContext, ValidationRule};
286
287    // Dataset utilities - guaranteed stable
288    pub use crate::public::stable::{load_iris, make_blobs, make_regression, Dataset};
289
290    // === Experimental APIs (Require Opt-in) ===
291
292    #[cfg(feature = "experimental")]
293    pub use crate::public::experimental::*;
294
295    // === Additional Stable Exports ===
296
297    // Zero-copy utilities - stable
298    pub use crate::types::zero_copy::{
299        array_views, dataset_ops, ArrayPool, ZeroCopyArray, ZeroCopyDataset,
300    };
301    pub use crate::types::{
302        CowDataset, CowFeatures, CowLabels, CowPredictions, CowProbabilities, CowSampleWeight,
303        CowTarget, Distances, SampleWeight, Similarities, ZeroCopy, ZeroCopyFeatures,
304        ZeroCopyTarget,
305    };
306
307    // Validation utilities - stable
308    pub use crate::validation::{ml as validation_ml, ConfigValidation, ValidationRules};
309
310    // Compile-time validation - stable
311    pub use crate::compile_time_validation::{
312        CompileTimeValidated, DimensionValidator, LinearRegressionConfig,
313        LinearRegressionConfigBuilder, ParameterValidator, PositiveValidator, ProbabilityValidator,
314        RangeValidator, SolverCompatibility, ValidatedConfig,
315    };
316
317    // Memory-mapped datasets - stable when available
318    #[cfg(feature = "mmap")]
319    pub use crate::dataset::MmapDataset;
320
321    // Arrow integration - stable when available
322    #[cfg(feature = "arrow")]
323    pub use crate::arrow::{ArrowDataset, ColumnStats};
324
325    // Binary format support - stable when available
326    #[cfg(feature = "binary")]
327    pub use crate::binary::{
328        convenience, ArrayBinaryFormat, BinaryConfig, BinaryDeserialize, BinaryFileStorage,
329        BinaryFormat, BinaryMetadata, BinarySerialize, BinarySerializer, CompressionType,
330        StreamingBinaryReader, StreamingBinaryWriter,
331    };
332
333    // SIMD operations - experimental, requires feature flag
334    #[cfg(feature = "simd")]
335    pub use crate::simd::{SimdArrayOps, SimdOps};
336
337    // GPU acceleration - experimental, requires feature flag and CUDA
338    #[cfg(feature = "gpu_support")]
339    pub use crate::gpu::{
340        GpuArray, GpuBackend, GpuContext, GpuDeviceProperties, GpuMatrixOps, GpuMemoryInfo,
341        GpuUtils, MemoryTransferOpts, TransferStrategy,
342    };
343
344    // Parallel processing - stable
345    pub use crate::parallel::{
346        ParallelConfig, ParallelCrossValidation, ParallelCrossValidator, ParallelEnsemble,
347        ParallelEnsembleOps, ParallelFit, ParallelMatrixOps, ParallelPredict, ParallelTransform,
348    };
349
350    // Async traits - experimental
351    #[cfg(feature = "async_support")]
352    pub use crate::async_traits::{
353        AsyncConfig, AsyncCrossValidation, AsyncEnsemble, AsyncFitAdvanced,
354        AsyncHyperparameterOptimization, AsyncModelPersistence, AsyncPartialFit,
355        AsyncPredictAdvanced, AsyncTransformAdvanced, CancellationToken, ConfidenceInterval,
356        ProgressInfo,
357    };
358
359    // Plugin system - experimental
360    #[cfg(feature = "plugins")]
361    pub use crate::plugin::{
362        AlgorithmPlugin, ClusteringPlugin, LogLevel, Plugin, PluginCapability, PluginCategory,
363        PluginConfig, PluginConfigBuilder, PluginFactory, PluginLoader, PluginMetadata,
364        PluginParameter, PluginRegistry, RuntimeSettings, TransformerPlugin,
365    };
366
367    // API stability utilities
368    pub use crate::public::{
369        api_version_info, is_api_experimental, is_api_stable, ApiStability, ApiVersionInfo,
370        ExperimentalApi, PublicApiConfig, PublicApiConfigBuilder, StableApi,
371    };
372
373    // Custom lints for ML-specific patterns
374    #[cfg(feature = "custom_lints")]
375    pub use crate::lints::{
376        ApiUsageLint, ArrayPerformanceLint, DataValidationLint, LintCategory, LintConfig,
377        LintRegistry, LintRule, LintSeverity, MemoryLeakLint, ModelValidationLint,
378        NumericalStabilityLint,
379    };
380
381    // Dependency audit and optimization
382    pub use crate::dependency_audit::{
383        calculate_metrics, generate_dependency_graph, BinarySizeImpact, CompileTimeImpact,
384        DependencyAudit, DependencyCategory, DependencyInfo, DependencyRecommendation,
385        DependencyReport, RecommendationAction,
386    };
387
388    // Code coverage reporting and enforcement
389    pub use crate::code_coverage::{
390        CICoverageResult, CIDConfig, CoverageCI, CoverageCollector, CoverageConfig, CoverageReport,
391        CoverageTool, QualityGatesResult, RecommendationPriority,
392    };
393
394    // Input sanitization for untrusted data
395    pub use crate::input_sanitization::{
396        is_ml_data_safe, sanitize_ml_data, InputSanitizer, SafetyIssue, SanitizationConfig,
397        Sanitize,
398    };
399
400    // System memory statistics — real OS values, never fabricated
401    pub use crate::system_info::{process_rss_bytes, system_memory, SystemMemory};
402
403    // Advanced array operations for high-performance computing
404    pub use crate::advanced_array_ops::{ArrayStats, MatrixOps, MemoryOps};
405
406    // Re-export the error_context macro
407    pub use crate::error_context;
408
409    // Code quality and safety tools - stable
410    pub use crate::formatting::{
411        CodeFormatter, FormattingConfig, FormattingConfigBuilder, FormattingIssue,
412        FormattingReport, IssueSeverity, MLFormattingRules,
413    };
414
415    pub use crate::unsafe_audit::{
416        SafetyRecommendation, SafetySeverity, UnsafeAuditConfig, UnsafeAuditReport, UnsafeAuditor,
417        UnsafeFinding, UnsafePattern, UnsafeType,
418    };
419
420    // Memory safety guarantees and utilities - stable
421    pub use crate::memory_safety::{
422        MemoryPoolStats, MemorySafety, MemorySafetyGuarantee, SafeArrayOps, SafeMemoryPool,
423        SafePooledBuffer, SafePtr, SafeSharedModel, UnsafeValidationResult,
424    };
425
426    // Benchmarking utilities - stable
427    pub use crate::benchmarking::{
428        AccuracyComparison, AlgorithmBenchmark, AlgorithmType, AutomatedBenchmarkRunner,
429        BenchmarkConfig, BenchmarkDataset, BenchmarkResults, BenchmarkRunResult, BenchmarkSuite,
430        MemoryStatistics, TimingStatistics,
431    };
432
433    // Mock objects for testing - now enabled and working
434    pub use crate::mock_objects::{
435        MockBehavior, MockConfig, MockEnsemble, MockErrorType, MockEstimator, MockEstimatorBuilder,
436        MockStateSnapshot, MockTransformConfig, MockTransformType, MockTransformer,
437        MockTransformerBuilder, TrainedMockEstimator, VotingStrategy,
438    };
439
440    // Contract testing framework
441    pub use crate::contract_testing::{
442        ContractTestConfig, ContractTestResult, ContractTestSummary, ContractTester,
443        PropertyTestStats, TestCase, TraitLaws,
444    };
445
446    // Compatibility layers for popular ML libraries - stable
447    pub use crate::compatibility::{
448        numpy::NumpyArray,
449        pandas::{DataFrame, DataValue},
450        pytorch::{ndarray_to_pytorch_tensor, TensorMetadata},
451        serialization::{CrossPlatformModel, ModelFormat, ModelSerialization},
452        sklearn::{FittedScikitLearnModel, ParamValue, ScikitLearnModel, SklearnCompatible},
453    };
454
455    // Standard format readers and writers - stable
456    pub use crate::format_io::{
457        CsvOptions, DataFormat, FormatDetector, FormatOptions, FormatReader, FormatWriter,
458        Hdf5Options, JsonOptions, NumpyOptions, ParquetOptions, StreamingReader,
459    };
460
461    // Contribution guidelines and review process - stable
462    pub use crate::contribution::{
463        AlgorithmicCriteria, ClippyLevel, CodeQualityCriteria, ContributionChecker,
464        ContributionConfig, ContributionResult, ContributionWorkflow, DocumentationCriteria,
465        GateResult, PerformanceCriteria, QualityGate, QualityGateType, ReviewCriteria,
466        TestingCriteria, WorkflowStep,
467    };
468
469    // Automated performance reporting system - stable
470    pub use crate::performance_reporting::{
471        AlertConfig, AnalysisResult, AnalysisType, HealthStatus, OutputFormat, PerformanceAnalyzer,
472        PerformanceReport, PerformanceReporter, RegressionThreshold, ReportConfig, TimeRange,
473        TrendDirection,
474    };
475
476    // Modularized API reference system - stable
477    pub use crate::api_analyzers::{
478        CrossReferenceBuilder as ModularCrossReferenceBuilder, ExampleValidator,
479        TraitAnalyzer as ModularTraitAnalyzer, TypeExtractor as ModularTypeExtractor,
480    };
481    pub use crate::api_data_structures::{
482        ApiReference as ModularApiReference, CodeExample as ModularCodeExample,
483        TraitInfo as ModularTraitInfo, TypeInfo as ModularTypeInfo,
484    };
485    pub use crate::api_formatters::{
486        ApiReferenceGenerator as ModularApiReferenceGenerator, DocumentFormatter,
487    };
488    pub use crate::api_generator_config::{
489        GeneratorConfig as ModularGeneratorConfig, OutputFormat as ModularOutputFormat,
490        ValidationConfig,
491    };
492    pub use crate::interactive_playground::{
493        LiveCodeRunner, UIComponentBuilder, WasmPlaygroundManager,
494    };
495    pub use crate::search_engines::{
496        AutocompleteTrie, SearchQuery, SearchResult, SemanticSearchEngine,
497    };
498    pub use crate::tutorial_system::{
499        LearningPath, ProgressTracker, Tutorial, TutorialBuilder, TutorialSystem,
500    };
501
502    // Trait explorer tool for interactive API navigation - stable
503    pub use crate::trait_explorer::{
504        CompilationImpact, DependencyAnalysis, DependencyAnalyzer, EdgeType, ExampleCategory,
505        ExampleDifficulty, ExampleGenerator, ExplorerConfig, GraphExportFormat, MemoryFootprint,
506        PerformanceAnalysis, RuntimeOverhead, SimilarTrait, TraitExplorationResult, TraitExplorer,
507        TraitGraph, TraitGraphEdge, TraitGraphGenerator, TraitGraphMetadata, TraitGraphNode,
508        TraitNodeType, TraitPerformanceAnalyzer, TraitRegistry, UsageExample,
509    };
510
511    // Exotic hardware support - experimental (TPU, FPGA, Quantum)
512    #[cfg(feature = "exotic_hardware")]
513    pub use crate::exotic_hardware::{
514        ActivationType, ComputationGraph, ComputationMetadata, ComputationNode, ComputationResult,
515        ExoticHardware, ExoticHardwareManager, FpgaDevice, FpgaVendor, HardwareCapabilities,
516        HardwareCompiler, HardwareComputation, HardwareId, HardwareMemoryManager, HardwareStatus,
517        HardwareType, MemoryHandle, MemoryStats, Operation, PerformanceEstimate, Precision,
518        QuantumBackend, QuantumDevice, TensorSpec, TpuDevice, TpuVersion, ValidationReport,
519    };
520
521    // Effect type system - experimental (compile-time effect tracking)
522    #[cfg(feature = "effect_types")]
523    pub use crate::effect_types::{
524        AsyncEffect, Capability, Combined, Effect, EffectAnalyzer, EffectBuilder, EffectMetadata,
525        EffectType, Fallible, FallibleIOEffect, GPUMemoryEffect, IORandomEffect, Linear, Memory,
526        MemoryIOEffect, Pure, Random, GPU, IO,
527    };
528
529    // Automatic differentiation - experimental (forward/reverse mode AD)
530    #[cfg(feature = "autodiff")]
531    pub use crate::autodiff::{
532        ADMode, AutodiffConfig, ComputationNode as ADNode, Dual, SymbolicExpression, Variable,
533        VariableId,
534    };
535
536    // Distributed computing support - experimental (cluster-aware ML) - TEMPORARILY DISABLED
537    // #[cfg(feature = "distributed")]
538    // pub use crate::distributed::{
539    //     ClusterInfo, ClusterNode, DistributedCluster, DistributedDataset, DistributedEstimator,
540    //     DistributedMessage, DistributedMetrics, DistributedOptimizer, DistributedTraining,
541    //     FaultTolerance, GradientAggregation, MessagePassing, NodeId, ParameterServer,
542    // };
543
544    // Compile-time macros and verification - experimental (model verification) - TEMPORARILY DISABLED
545    // #[cfg(feature = "compile_time_macros")]
546    // pub use crate::compile_time_macros::{
547    //     validate_performance, verify_dimensions, verify_model, BenchmarkConfig as CompileTimeBenchmarkConfig,
548    //     CompileTimeVerifiable, ComplexityAnalysis, DimensionVerifiable, MathematicallyVerifiable,
549    //     OptimizationSuggestion, PerformanceTargets, ScalingBehavior, VerificationConfig,
550    //     VerificationEngine, VerificationResult,
551    // };
552
553    // Automatic benchmark generation - experimental (performance testing)
554    #[cfg(feature = "auto_benchmarks")]
555    pub use crate::auto_benchmark_generation::{
556        generate_benchmarks_for_type, AutoBenchmarkConfig, BenchmarkExecutor, BenchmarkGenerator,
557        BenchmarkResult, BenchmarkType, ComplexityClass, GeneratedBenchmark,
558        PerformanceEstimate as AutoBenchmarkPerformanceEstimate, RegressionDetector,
559        ScalingDimension,
560    };
561
562    // Advanced ensemble method improvements - now enabled and working
563    pub use crate::ensemble_improvements::{
564        AggregationMethod, BaseEstimator, BaseEstimatorConfig, BaseEstimatorType,
565        DistributedConfig, DistributedEnsemble, EnsembleConfig, EnsembleType,
566        LoadBalancingStrategy, NodeRole, ParallelConfig as EnsembleParallelConfig,
567        ParallelEnsemble as AdvancedParallelEnsemble, SamplingStrategy, TrainedBaseModel,
568        TrainedParallelEnsemble, TrainingState,
569    };
570}