sklears-core 0.1.1

Core traits, types, and utilities for sklears machine learning library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
/// Custom lints for ML-specific patterns and best practices
///
/// This module provides custom linting rules that help enforce ML-specific
/// coding patterns and catch common mistakes in machine learning code.
///
/// # Lint Categories
///
/// - **Data Validation**: Ensure proper input validation
/// - **Memory Safety**: Check for potential memory issues in ML workloads
/// - **Performance**: Identify performance anti-patterns
use std::collections::HashMap;
/// - **API Usage**: Enforce proper API usage patterns
/// - **Numerical Stability**: Catch numerical stability issues
///
/// # Usage
///
/// These lints can be enabled with the `custom_lints` feature flag:
///
/// ```toml
/// [dependencies]
/// sklears-core = { version = "0.1", features = ["custom_lints"] }
/// ```
///
/// Individual lints can be configured in your Cargo.toml:
///
/// ```toml
/// [lints.rust]
/// sklears_data_validation = "warn"
/// sklears_memory_safety = "deny"
/// ```
/// Trait for defining custom lint rules
pub trait LintRule {
    /// Name of the lint rule
    fn name(&self) -> &'static str;

    /// Description of what the lint checks for
    fn description(&self) -> &'static str;

    /// Severity level of the lint
    fn severity(&self) -> LintSeverity;

    /// Category of the lint
    fn category(&self) -> LintCategory;

    /// Example of code that would trigger this lint
    fn example_violation(&self) -> &'static str;

    /// Example of how to fix the violation
    fn example_fix(&self) -> &'static str;

    /// Additional help text
    fn help_text(&self) -> Option<&'static str> {
        None
    }
}

/// Severity levels for lints
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LintSeverity {
    /// Allow the pattern (information only)
    Allow,
    /// Warn about the pattern
    Warn,
    /// Deny the pattern (error)
    Deny,
    /// Forbid the pattern (hard error)
    Forbid,
}

/// Categories of ML-specific lints
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LintCategory {
    /// Data validation and preprocessing
    DataValidation,
    /// Memory safety and management
    MemorySafety,
    /// Performance optimization
    Performance,
    /// API usage patterns
    ApiUsage,
    /// Numerical stability
    NumericalStability,
    /// Model lifecycle management
    ModelLifecycle,
    /// Feature engineering
    FeatureEngineering,
    /// Testing and validation
    Testing,
}

// =============================================================================
// Specific Lint Rules
// =============================================================================

/// Lint for missing data validation
pub struct DataValidationLint;

impl LintRule for DataValidationLint {
    fn name(&self) -> &'static str {
        "sklears_data_validation"
    }

    fn description(&self) -> &'static str {
        "Checks for missing input data validation in ML algorithms"
    }

    fn severity(&self) -> LintSeverity {
        LintSeverity::Warn
    }

    fn category(&self) -> LintCategory {
        LintCategory::DataValidation
    }

    fn example_violation(&self) -> &'static str {
        r#"
fn fit(&mut self, x: &Array2<f64>, y: &Array1<f64>) -> Result<()> {
    // Missing validation - should check shapes, NaN values, etc.
    self.train_model(x, y)
}
        "#
    }

    fn example_fix(&self) -> &'static str {
        r#"
fn fit(&mut self, x: &Array2<f64>, y: &Array1<f64>) -> Result<()> {
    // Validate input data
    if x.nrows() != y.len() {
        return Err(SklearsError::InvalidInput("Shape mismatch".to_string()));
    }
    if x.iter().any(|v| v.is_nan()) {
        return Err(SklearsError::InvalidInput("NaN values found".to_string()));
    }
    
    self.train_model(x, y)
}
        "#
    }

    fn help_text(&self) -> Option<&'static str> {
        Some(
            "Always validate input data before processing. Check for:\n\
              - Shape compatibility\n\
              - NaN or infinite values\n\
              - Empty datasets\n\
              - Data type consistency",
        )
    }
}

/// Lint for potential memory leaks in ML workloads
pub struct MemoryLeakLint;

impl LintRule for MemoryLeakLint {
    fn name(&self) -> &'static str {
        "sklears_memory_leak"
    }

    fn description(&self) -> &'static str {
        "Detects potential memory leaks in iterative ML algorithms"
    }

    fn severity(&self) -> LintSeverity {
        LintSeverity::Deny
    }

    fn category(&self) -> LintCategory {
        LintCategory::MemorySafety
    }

    fn example_violation(&self) -> &'static str {
        r#"
fn train_epochs(&mut self, data: &Dataset) -> Result<()> {
    for epoch in 0..self.max_epochs {
        let mut gradients = Vec::new();
        
        for batch in data.batches() {
            gradients.push(self.compute_gradients(batch));
            // Memory grows unbounded - gradients accumulate
        }
        
        self.apply_gradients(&gradients);
    }
    Ok(())
}
        "#
    }

    fn example_fix(&self) -> &'static str {
        r#"
fn train_epochs(&mut self, data: &Dataset) -> Result<()> {
    for epoch in 0..self.max_epochs {
        let mut accumulated_gradients = self.zero_gradients();
        
        for batch in data.batches() {
            let gradients = self.compute_gradients(batch);
            self.accumulate_gradients(&mut accumulated_gradients, &gradients);
            // Process gradients incrementally instead of storing all
        }
        
        self.apply_gradients(&accumulated_gradients);
    }
    Ok(())
}
        "#
    }

    fn help_text(&self) -> Option<&'static str> {
        Some(
            "In iterative algorithms, avoid accumulating large amounts of data.\n\
              Use streaming or incremental processing instead.",
        )
    }
}

/// Lint for inefficient array operations
pub struct ArrayPerformanceLint;

impl LintRule for ArrayPerformanceLint {
    fn name(&self) -> &'static str {
        "sklears_array_performance"
    }

    fn description(&self) -> &'static str {
        "Identifies inefficient array operations that could be optimized"
    }

    fn severity(&self) -> LintSeverity {
        LintSeverity::Warn
    }

    fn category(&self) -> LintCategory {
        LintCategory::Performance
    }

    fn example_violation(&self) -> &'static str {
        r#"
fn dot_product(&self, a: &Array1<f64>, b: &Array1<f64>) -> f64 {
    // Inefficient: manual loop instead of BLAS
    let mut result = 0.0;
    for i in 0..a.len() {
        result += a[i] * b[i];
    }
    result
}
        "#
    }

    fn example_fix(&self) -> &'static str {
        r#"
fn dot_product(&self, a: &Array1<f64>, b: &Array1<f64>) -> f64 {
    // Efficient: use optimized BLAS operations
    a.dot(b)
}
        "#
    }

    fn help_text(&self) -> Option<&'static str> {
        Some(
            "Use optimized BLAS operations instead of manual loops for:\n\
              - Matrix multiplication\n\
              - Vector operations\n\
              - Element-wise operations",
        )
    }
}

/// Lint for improper API usage patterns
pub struct ApiUsageLint;

impl LintRule for ApiUsageLint {
    fn name(&self) -> &'static str {
        "sklears_api_usage"
    }

    fn description(&self) -> &'static str {
        "Checks for improper usage of sklears APIs"
    }

    fn severity(&self) -> LintSeverity {
        LintSeverity::Warn
    }

    fn category(&self) -> LintCategory {
        LintCategory::ApiUsage
    }

    fn example_violation(&self) -> &'static str {
        r#"
// Using trained model before fitting
let model = LinearRegression::new();
let predictions = model.predict(&test_data)?; // Error: not fitted
        "#
    }

    fn example_fix(&self) -> &'static str {
        r#"
// Proper model lifecycle
let model = LinearRegression::new();
let fitted_model = model.fit(&train_x, &train_y)?;
let predictions = fitted_model.predict(&test_data)?;
        "#
    }

    fn help_text(&self) -> Option<&'static str> {
        Some(
            "Follow the proper ML model lifecycle:\n\
              1. Create model\n\
              2. Fit on training data\n\
              3. Use fitted model for prediction",
        )
    }
}

/// Lint for numerical stability issues
pub struct NumericalStabilityLint;

impl LintRule for NumericalStabilityLint {
    fn name(&self) -> &'static str {
        "sklears_numerical_stability"
    }

    fn description(&self) -> &'static str {
        "Detects patterns that may cause numerical instability"
    }

    fn severity(&self) -> LintSeverity {
        LintSeverity::Warn
    }

    fn category(&self) -> LintCategory {
        LintCategory::NumericalStability
    }

    fn example_violation(&self) -> &'static str {
        r#"
fn log_softmax(&self, x: &Array1<f64>) -> Array1<f64> {
    let exp_x: Array1<f64> = x.mapv(|v| v.exp());
    let sum_exp = exp_x.sum();
    exp_x.mapv(|v| (v / sum_exp).ln()) // Numerically unstable
}
        "#
    }

    fn example_fix(&self) -> &'static str {
        r#"
fn log_softmax(&self, x: &Array1<f64>) -> Array1<f64> {
    let max_x = x.fold(f64::NEG_INFINITY, |a, &b| a.max(b));
    let shifted = x.mapv(|v| v - max_x);
    let log_sum_exp = shifted.mapv(|v| v.exp()).sum().ln();
    shifted.mapv(|v| v - log_sum_exp) // Numerically stable
}
        "#
    }

    fn help_text(&self) -> Option<&'static str> {
        Some(
            "Use numerically stable algorithms:\n\
              - Subtract max before exp() operations\n\
              - Use log-space arithmetic when possible\n\
              - Check for overflow/underflow conditions",
        )
    }
}

/// Lint for missing model validation
pub struct ModelValidationLint;

impl LintRule for ModelValidationLint {
    fn name(&self) -> &'static str {
        "sklears_model_validation"
    }

    fn description(&self) -> &'static str {
        "Ensures proper model validation and testing practices"
    }

    fn severity(&self) -> LintSeverity {
        LintSeverity::Warn
    }

    fn category(&self) -> LintCategory {
        LintCategory::Testing
    }

    fn example_violation(&self) -> &'static str {
        r#"
fn train_model(&mut self, data: &Dataset) -> Result<()> {
    self.fit(&data.features, &data.targets)?;
    // Missing: no validation or testing
    Ok(())
}
        "#
    }

    fn example_fix(&self) -> &'static str {
        r#"
fn train_model(&mut self, data: &Dataset) -> Result<()> {
    let (train, test) = data.train_test_split(0.8)?;
    
    self.fit(&train.features, &train.targets)?;
    
    // Validate model performance
    let predictions = self.predict(&test.features)?;
    let score = self.score(&test.features, &test.targets)?;
    
    if score < self.min_acceptable_score {
        return Err(SklearsError::InvalidOperation(
            "Model performance below threshold".to_string()
        ));
    }
    
    Ok(())
}
        "#
    }

    fn help_text(&self) -> Option<&'static str> {
        Some(
            "Always validate model performance:\n\
              - Use train/validation/test splits\n\
              - Implement cross-validation\n\
              - Monitor for overfitting",
        )
    }
}

// =============================================================================
// Lint Registry and Management
// =============================================================================

/// Registry of all available lints
pub struct LintRegistry {
    rules: HashMap<&'static str, Box<dyn LintRule>>,
    enabled_rules: HashMap<&'static str, LintSeverity>,
}

impl LintRegistry {
    /// Create a new lint registry with default rules
    pub fn new() -> Self {
        let mut registry = Self {
            rules: HashMap::new(),
            enabled_rules: HashMap::new(),
        };

        // Register default lint rules
        registry.register(Box::new(DataValidationLint));
        registry.register(Box::new(MemoryLeakLint));
        registry.register(Box::new(ArrayPerformanceLint));
        registry.register(Box::new(ApiUsageLint));
        registry.register(Box::new(NumericalStabilityLint));
        registry.register(Box::new(ModelValidationLint));

        registry
    }

    /// Register a new lint rule
    pub fn register(&mut self, rule: Box<dyn LintRule>) {
        let name = rule.name();
        let severity = rule.severity();
        self.enabled_rules.insert(name, severity);
        self.rules.insert(name, rule);
    }

    /// Enable a lint rule with specified severity
    pub fn enable_rule(&mut self, name: &str, severity: LintSeverity) -> Result<(), String> {
        if let Some(rule) = self.rules.get(name) {
            let static_name = rule.name(); // Get the static name from the rule
            self.enabled_rules.insert(static_name, severity);
            Ok(())
        } else {
            Err(format!("Unknown lint rule: {name}"))
        }
    }

    /// Disable a lint rule
    pub fn disable_rule(&mut self, name: &str) {
        if let Some(rule) = self.rules.get(name) {
            let static_name = rule.name(); // Get the static name from the rule
            self.enabled_rules.remove(static_name);
        }
    }

    /// Get all available lint rules
    pub fn available_rules(&self) -> Vec<&str> {
        self.rules.keys().copied().collect()
    }

    /// Get enabled lint rules
    pub fn enabled_rules(&self) -> &HashMap<&'static str, LintSeverity> {
        &self.enabled_rules
    }

    /// Get lint rule by name
    pub fn get_rule(&self, name: &str) -> Option<&dyn LintRule> {
        self.rules.get(name).map(|r| r.as_ref())
    }

    /// Get lint rules by category
    pub fn rules_by_category(&self, category: LintCategory) -> Vec<&dyn LintRule> {
        self.rules
            .values()
            .filter(|rule| rule.category() == category)
            .map(|rule| rule.as_ref())
            .collect()
    }

    /// Generate lint configuration for Cargo.toml
    pub fn generate_cargo_config(&self) -> String {
        let mut config = String::new();
        config.push_str("[lints.rust]\n");

        for (name, severity) in &self.enabled_rules {
            let severity_str = match severity {
                LintSeverity::Allow => "allow",
                LintSeverity::Warn => "warn",
                LintSeverity::Deny => "deny",
                LintSeverity::Forbid => "forbid",
            };
            config.push_str(&format!("{name} = \"{severity_str}\"\n"));
        }

        config
    }

    /// Generate lint documentation
    pub fn generate_documentation(&self) -> String {
        let mut doc = String::new();
        doc.push_str("# SKLears Custom Lints\n\n");

        // Group by category
        let mut categories: HashMap<LintCategory, Vec<&dyn LintRule>> = HashMap::new();
        for rule in self.rules.values() {
            categories
                .entry(rule.category())
                .or_default()
                .push(rule.as_ref());
        }

        for (category, rules) in categories {
            doc.push_str(&format!("## {category:?} Lints\n\n"));

            for rule in rules {
                doc.push_str(&format!("### {}\n\n", rule.name()));
                doc.push_str(&format!("**Description**: {}\n\n", rule.description()));
                doc.push_str(&format!("**Severity**: {:?}\n\n", rule.severity()));

                if let Some(help) = rule.help_text() {
                    doc.push_str(&format!("**Help**: {help}\n\n"));
                }

                doc.push_str("**Example violation**:\n");
                doc.push_str("```rust\n");
                doc.push_str(rule.example_violation());
                doc.push_str("\n```\n\n");

                doc.push_str("**Example fix**:\n");
                doc.push_str("```rust\n");
                doc.push_str(rule.example_fix());
                doc.push_str("\n```\n\n");
            }
        }

        doc
    }
}

impl Default for LintRegistry {
    fn default() -> Self {
        Self::new()
    }
}

/// Configuration for lint enforcement
#[derive(Debug, Clone)]
pub struct LintConfig {
    /// Whether to enable custom lints
    pub enabled: bool,
    /// Default severity for new lints
    pub default_severity: LintSeverity,
    /// Whether to fail build on lint violations
    pub fail_on_violations: bool,
    /// Maximum number of violations before failing
    pub max_violations: Option<usize>,
}

impl Default for LintConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            default_severity: LintSeverity::Warn,
            fail_on_violations: false,
            max_violations: Some(100),
        }
    }
}

// =============================================================================
// Lint Utilities
// =============================================================================

/// Utility functions for working with lints
pub mod utils {
    use super::*;

    /// Check if a lint should be applied based on configuration
    pub fn should_apply_lint(
        rule_name: &str,
        config: &LintConfig,
        registry: &LintRegistry,
    ) -> bool {
        if !config.enabled {
            return false;
        }

        registry.enabled_rules().contains_key(rule_name)
    }

    /// Format a lint violation message
    pub fn format_violation(rule: &dyn LintRule, location: &str, message: &str) -> String {
        format!(
            "[{}] {}: {} ({})",
            rule.name(),
            location,
            message,
            rule.description()
        )
    }

    /// Generate a quick-fix suggestion
    pub fn suggest_fix(rule: &dyn LintRule) -> String {
        let mut suggestion = String::new();
        suggestion.push_str("Suggested fix:\n");
        suggestion.push_str(rule.example_fix());

        if let Some(help) = rule.help_text() {
            suggestion.push_str("\n\nAdditional help:\n");
            suggestion.push_str(help);
        }

        suggestion
    }
}

// =============================================================================
// Tests
// =============================================================================

#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_lint_registry() {
        let mut registry = LintRegistry::new();

        // Test that default rules are registered
        assert!(!registry.available_rules().is_empty());
        assert!(registry
            .available_rules()
            .contains(&"sklears_data_validation"));

        // Test enabling/disabling rules
        assert!(registry
            .enable_rule("sklears_data_validation", LintSeverity::Deny)
            .is_ok());
        assert!(registry
            .enable_rule("nonexistent_rule", LintSeverity::Warn)
            .is_err());

        registry.disable_rule("sklears_data_validation");
        assert!(!registry
            .enabled_rules()
            .contains_key("sklears_data_validation"));
    }

    #[test]
    fn test_lint_rules() {
        let data_lint = DataValidationLint;
        assert_eq!(data_lint.name(), "sklears_data_validation");
        assert_eq!(data_lint.category(), LintCategory::DataValidation);
        assert_eq!(data_lint.severity(), LintSeverity::Warn);
        assert!(!data_lint.example_violation().is_empty());
        assert!(!data_lint.example_fix().is_empty());
    }

    #[test]
    fn test_rules_by_category() {
        let registry = LintRegistry::new();
        let data_rules = registry.rules_by_category(LintCategory::DataValidation);
        assert!(!data_rules.is_empty());

        for rule in data_rules {
            assert_eq!(rule.category(), LintCategory::DataValidation);
        }
    }

    #[test]
    fn test_cargo_config_generation() {
        let mut registry = LintRegistry::new();
        registry
            .enable_rule("sklears_data_validation", LintSeverity::Warn)
            .expect("expected valid value");
        registry
            .enable_rule("sklears_memory_leak", LintSeverity::Deny)
            .expect("expected valid value");

        let config = registry.generate_cargo_config();
        assert!(config.contains("sklears_data_validation = \"warn\""));
        assert!(config.contains("sklears_memory_leak = \"deny\""));
    }

    #[test]
    fn test_documentation_generation() {
        let registry = LintRegistry::new();
        let doc = registry.generate_documentation();

        assert!(doc.contains("# SKLears Custom Lints"));
        assert!(doc.contains("sklears_data_validation"));
        assert!(doc.contains("Example violation"));
        assert!(doc.contains("Example fix"));
    }

    #[test]
    fn test_lint_config() {
        let config = LintConfig::default();
        assert!(config.enabled);
        assert_eq!(config.default_severity, LintSeverity::Warn);
    }

    #[test]
    fn test_lint_utils() {
        let registry = LintRegistry::new();
        let config = LintConfig::default();

        // Test lint application check
        assert!(utils::should_apply_lint(
            "sklears_data_validation",
            &config,
            &registry
        ));

        let disabled_config = LintConfig {
            enabled: false,
            ..Default::default()
        };
        assert!(!utils::should_apply_lint(
            "sklears_data_validation",
            &disabled_config,
            &registry
        ));

        // Test formatting
        let rule = DataValidationLint;
        let message = utils::format_violation(&rule, "src/main.rs:42", "Missing validation");
        assert!(message.contains("sklears_data_validation"));
        assert!(message.contains("src/main.rs:42"));

        // Test fix suggestion
        let suggestion = utils::suggest_fix(&rule);
        assert!(suggestion.contains("Suggested fix"));
    }
}