sklears-datasets 0.1.0

Dataset utilities and generation for sklears
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
//! Dataset configuration templates and YAML/JSON support
//!
//! This module provides a comprehensive configuration system for dataset generation
//! using YAML and JSON templates. It supports parameter inheritance, validation,
//! and experiment tracking.

use crate::traits::{ConfigValue, GeneratorConfig};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use thiserror::Error;

/// Configuration system errors
#[derive(Error, Debug)]
pub enum ConfigTemplateError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("YAML parsing error: {0}")]
    Yaml(String),
    #[error("JSON parsing error: {0}")]
    Json(#[from] serde_json::Error),
    #[error("Template not found: {0}")]
    TemplateNotFound(String),
    #[error("Validation error: {0}")]
    Validation(String),
    #[error("Parameter override error: {0}")]
    ParameterOverride(String),
    #[error("Inheritance cycle detected: {0}")]
    InheritanceCycle(String),
    #[error("Missing required parameter: {0}")]
    MissingParameter(String),
}

pub type ConfigTemplateResult<T> = Result<T, ConfigTemplateError>;

/// Dataset template configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatasetTemplate {
    /// Template metadata
    pub metadata: TemplateMetadata,

    /// Base template to inherit from
    pub extends: Option<String>,

    /// Generator configuration
    pub generator: GeneratorTemplateConfig,

    /// Parameter definitions and constraints
    pub parameters: HashMap<String, ParameterTemplate>,

    /// Validation rules
    pub validation: Option<ValidationRules>,

    /// Export settings
    pub export: Option<ExportTemplate>,

    /// Experiment tracking settings
    pub experiment: Option<ExperimentTemplate>,
}

/// Template metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateMetadata {
    pub name: String,
    pub version: String,
    pub description: String,
    pub author: String,
    pub created: Option<String>,
    pub modified: Option<String>,
    pub tags: Vec<String>,
    pub category: Option<String>,
}

/// Generator configuration in template
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GeneratorTemplateConfig {
    pub name: String,
    pub n_samples: Option<usize>,
    pub n_features: Option<usize>,
    pub random_state: Option<u64>,
    pub parameters: HashMap<String, serde_yaml::Value>,
}

/// Parameter template with constraints
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParameterTemplate {
    pub description: String,
    pub param_type: ParameterTypeTemplate,
    pub required: bool,
    pub default: Option<serde_yaml::Value>,
    pub constraints: Option<ParameterConstraints>,
    pub dependencies: Vec<String>,
}

/// Parameter type definitions
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum ParameterTypeTemplate {
    /// Integer

    Integer {

        min: Option<i64>,

        max: Option<i64>,
    },
    /// Float

    Float {

        min: Option<f64>,

        max: Option<f64>,
    },
    /// String

    String {

        pattern: Option<String>,
    },
    Boolean,
    Array {
        element_type: Box<ParameterTypeTemplate>,
    },
    Enum {
        values: Vec<serde_yaml::Value>,
    },
    Object {
        properties: HashMap<String, ParameterTemplate>,
    },
}

/// Parameter constraints
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParameterConstraints {
    pub min_value: Option<f64>,
    pub max_value: Option<f64>,
    pub min_length: Option<usize>,
    pub max_length: Option<usize>,
    pub pattern: Option<String>,
    pub custom: Vec<String>,
}

/// Validation rules
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationRules {
    pub dataset_size: Option<DatasetSizeConstraints>,
    pub statistical: Option<StatisticalConstraints>,
    pub custom: Vec<String>,
}

/// Dataset size constraints
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatasetSizeConstraints {
    pub min_samples: Option<usize>,
    pub max_samples: Option<usize>,
    pub min_features: Option<usize>,
    pub max_features: Option<usize>,
    pub max_memory_mb: Option<usize>,
}

/// Statistical constraints
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatisticalConstraints {
    pub target_correlation: Option<f64>,
    pub noise_level: Option<f64>,
    pub class_balance: Option<ClassBalanceConstraints>,
}

/// Class balance constraints
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClassBalanceConstraints {
    pub min_ratio: f64,
    pub max_ratio: f64,
    pub enforce_balance: bool,
}

/// Export template configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportTemplate {
    pub formats: Vec<String>,
    pub filename_pattern: String,
    pub include_metadata: bool,
    pub compression: Option<String>,
}

/// Experiment tracking template
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExperimentTemplate {
    pub name: String,
    pub description: String,
    pub metrics: Vec<String>,
    pub track_parameters: bool,
    pub track_outputs: bool,
    pub storage_path: Option<String>,
}

/// Template library for managing collections of templates
pub struct TemplateLibrary {
    templates: HashMap<String, DatasetTemplate>,
    search_paths: Vec<String>,
}

impl TemplateLibrary {
    /// Create a new template library
    pub fn new() -> Self {
        Self {
            templates: HashMap::new(),
            search_paths: vec![
                "./templates".to_string(),
                "~/.sklears/templates".to_string(),
            ],
        }
    }

    /// Add a search path for templates
    pub fn add_search_path<P: AsRef<Path>>(&mut self, path: P) {
        self.search_paths
            .push(path.as_ref().to_string_lossy().to_string());
    }

    /// Load a template from file
    pub fn load_template<P: AsRef<Path>>(&mut self, path: P) -> ConfigTemplateResult<String> {
        let content = fs::read_to_string(&path)?;
        let template: DatasetTemplate = if path.as_ref().extension().and_then(|ext| ext.to_str())
            == Some("json")
        {
            serde_json::from_str(&content)?
        } else {
            serde_yaml::from_str(&content).map_err(|e| ConfigTemplateError::Yaml(e.to_string()))?
        };

        let name = template.metadata.name.clone();
        self.templates.insert(name.clone(), template);
        Ok(name)
    }

    /// Load all templates from a directory
    pub fn load_directory<P: AsRef<Path>>(&mut self, dir: P) -> ConfigTemplateResult<Vec<String>> {
        let mut loaded = Vec::new();

        if let Ok(entries) = fs::read_dir(dir) {
            for entry in entries {
                if let Ok(entry) = entry {
                    let path = entry.path();
                    if let Some(ext) = path.extension() {
                        if ext == "yaml" || ext == "yml" || ext == "json" {
                            if let Ok(name) = self.load_template(&path) {
                                loaded.push(name);
                            }
                        }
                    }
                }
            }
        }

        Ok(loaded)
    }

    /// Register a template programmatically
    pub fn register_template(&mut self, template: DatasetTemplate) {
        let name = template.metadata.name.clone();
        self.templates.insert(name, template);
    }

    /// Get a template by name
    pub fn get_template(&self, name: &str) -> Option<&DatasetTemplate> {
        self.templates.get(name)
    }

    /// List all available templates
    pub fn list_templates(&self) -> Vec<String> {
        self.templates.keys().cloned().collect()
    }

    /// Search templates by tag
    pub fn search_by_tag(&self, tag: &str) -> Vec<String> {
        self.templates
            .iter()
            .filter(|(_, template)| template.metadata.tags.contains(&tag.to_string()))
            .map(|(name, _)| name.clone())
            .collect()
    }

    /// Search templates by category
    pub fn search_by_category(&self, category: &str) -> Vec<String> {
        self.templates
            .iter()
            .filter(|(_, template)| {
                template.metadata.category.as_ref() == Some(&category.to_string())
            })
            .map(|(name, _)| name.clone())
            .collect()
    }

    /// Resolve template inheritance and create final configuration
    pub fn resolve_template(
        &self,
        name: &str,
        overrides: Option<HashMap<String, serde_yaml::Value>>,
    ) -> ConfigTemplateResult<GeneratorConfig> {
        let template = self
            .get_template(name)
            .ok_or_else(|| ConfigTemplateError::TemplateNotFound(name.to_string()))?;

        // Resolve inheritance chain
        let resolved = self.resolve_inheritance(template)?;

        // Create generator config
        let mut config = GeneratorConfig::new(
            resolved.generator.n_samples.unwrap_or(1000),
            resolved.generator.n_features.unwrap_or(10),
        );

        if let Some(seed) = resolved.generator.random_state {
            config = config.with_random_state(seed);
        }

        // Apply parameters from template
        for (key, value) in &resolved.generator.parameters {
            if let Ok(config_value) = self.convert_yaml_value(value) {
                config.set_parameter(key.clone(), config_value);
            }
        }

        // Apply overrides
        if let Some(overrides) = overrides {
            for (key, value) in overrides {
                if let Ok(config_value) = self.convert_yaml_value(&value) {
                    config.set_parameter(key, config_value);
                }
            }
        }

        // Validate configuration
        self.validate_config(&resolved, &config)?;

        Ok(config)
    }

    /// Resolve template inheritance
    fn resolve_inheritance(
        &self,
        template: &DatasetTemplate,
    ) -> ConfigTemplateResult<DatasetTemplate> {
        let mut resolved = template.clone();
        let mut visited = std::collections::HashSet::new();

        self.resolve_inheritance_recursive(&mut resolved, &mut visited)?;
        Ok(resolved)
    }

    fn resolve_inheritance_recursive(
        &self,
        template: &mut DatasetTemplate,
        visited: &mut std::collections::HashSet<String>,
    ) -> ConfigTemplateResult<()> {
        if let Some(ref base_name) = template.extends.clone() {
            if visited.contains(base_name) {
                return Err(ConfigTemplateError::InheritanceCycle(base_name.clone()));
            }

            visited.insert(base_name.clone());

            let base_template = self
                .get_template(base_name)
                .ok_or_else(|| ConfigTemplateError::TemplateNotFound(base_name.clone()))?;

            let mut base = base_template.clone();
            self.resolve_inheritance_recursive(&mut base, visited)?;

            // Merge base into current template
            self.merge_templates(&mut base, template);
            *template = base;

            visited.remove(base_name);
        }

        Ok(())
    }

    /// Merge two templates (child overrides parent)
    fn merge_templates(&self, parent: &mut DatasetTemplate, child: &DatasetTemplate) {
        // Merge generator config
        if child.generator.n_samples.is_some() {
            parent.generator.n_samples = child.generator.n_samples;
        }
        if child.generator.n_features.is_some() {
            parent.generator.n_features = child.generator.n_features;
        }
        if child.generator.random_state.is_some() {
            parent.generator.random_state = child.generator.random_state;
        }

        // Merge parameters
        for (key, value) in &child.generator.parameters {
            parent
                .generator
                .parameters
                .insert(key.clone(), value.clone());
        }

        // Merge parameter definitions
        for (key, value) in &child.parameters {
            parent.parameters.insert(key.clone(), value.clone());
        }

        // Override other fields
        if child.validation.is_some() {
            parent.validation = child.validation.clone();
        }
        if child.export.is_some() {
            parent.export = child.export.clone();
        }
        if child.experiment.is_some() {
            parent.experiment = child.experiment.clone();
        }
    }

    /// Convert YAML value to ConfigValue
    fn convert_yaml_value(&self, value: &serde_yaml::Value) -> ConfigTemplateResult<ConfigValue> {
        match value {
            serde_yaml::Value::Number(n) => {
                if n.is_i64() {
                    Ok(ConfigValue::Int(n.as_i64().expect("operation should succeed")))
                } else if n.is_f64() {
                    Ok(ConfigValue::Float(n.as_f64().expect("operation should succeed")))
                } else {
                    Err(ConfigTemplateError::ParameterOverride(
                        "Invalid number type".to_string(),
                    ))
                }
            }
            serde_yaml::Value::String(s) => Ok(ConfigValue::String(s.clone())),
            serde_yaml::Value::Bool(b) => Ok(ConfigValue::Bool(*b)),
            serde_yaml::Value::Sequence(seq) => {
                let mut int_vec = Vec::new();
                let mut float_vec = Vec::new();
                let mut is_int = true;

                for item in seq {
                    match item {
                        serde_yaml::Value::Number(n) => {
                            if n.is_i64() {
                                int_vec.push(n.as_i64().expect("operation should succeed"));
                                float_vec.push(n.as_f64().expect("operation should succeed"));
                            } else if n.is_f64() {
                                is_int = false;
                                float_vec.push(n.as_f64().expect("operation should succeed"));
                            }
                        }
                        _ => {
                            return Err(ConfigTemplateError::ParameterOverride(
                                "Array must contain only numbers".to_string(),
                            ))
                        }
                    }
                }

                if is_int {
                    Ok(ConfigValue::IntArray(int_vec))
                } else {
                    Ok(ConfigValue::FloatArray(float_vec))
                }
            }
            _ => Err(ConfigTemplateError::ParameterOverride(
                "Unsupported value type".to_string(),
            )),
        }
    }

    /// Validate configuration against template constraints
    fn validate_config(
        &self,
        template: &DatasetTemplate,
        config: &GeneratorConfig,
    ) -> ConfigTemplateResult<()> {
        // Validate required parameters
        for (param_name, param_def) in &template.parameters {
            if param_def.required && config.get_parameter(param_name).is_none() {
                return Err(ConfigTemplateError::MissingParameter(param_name.clone()));
            }
        }

        // Validate parameter constraints
        for (param_name, param_def) in &template.parameters {
            if let Some(value) = config.get_parameter(param_name) {
                self.validate_parameter_value(param_def, value)?;
            }
        }

        // Validate dataset size constraints
        if let Some(validation) = &template.validation {
            if let Some(size_constraints) = &validation.dataset_size {
                self.validate_size_constraints(size_constraints, config)?;
            }
        }

        Ok(())
    }

    /// Validate parameter value against constraints
    fn validate_parameter_value(
        &self,
        param_def: &ParameterTemplate,
        value: &ConfigValue,
    ) -> ConfigTemplateResult<()> {
        match (&param_def.param_type, value) {
            (ParameterTypeTemplate::Integer { min, max }, ConfigValue::Int(v)) => {
                if let Some(min_val) = min {
                    if *v < *min_val {
                        return Err(ConfigTemplateError::Validation(format!(
                            "Value {} below minimum {}",
                            v, min_val
                        )));
                    }
                }
                if let Some(max_val) = max {
                    if *v > *max_val {
                        return Err(ConfigTemplateError::Validation(format!(
                            "Value {} above maximum {}",
                            v, max_val
                        )));
                    }
                }
            }
            (ParameterTypeTemplate::Float { min, max }, ConfigValue::Float(v)) => {
                if let Some(min_val) = min {
                    if *v < *min_val {
                        return Err(ConfigTemplateError::Validation(format!(
                            "Value {} below minimum {}",
                            v, min_val
                        )));
                    }
                }
                if let Some(max_val) = max {
                    if *v > *max_val {
                        return Err(ConfigTemplateError::Validation(format!(
                            "Value {} above maximum {}",
                            v, max_val
                        )));
                    }
                }
            }
            (ParameterTypeTemplate::Boolean, ConfigValue::Bool(_)) => {
                // Always valid
            }
            _ => {
                // Type mismatch - could add more detailed checking
            }
        }

        Ok(())
    }

    /// Validate size constraints
    fn validate_size_constraints(
        &self,
        constraints: &DatasetSizeConstraints,
        config: &GeneratorConfig,
    ) -> ConfigTemplateResult<()> {
        if let Some(min_samples) = constraints.min_samples {
            if config.n_samples < min_samples {
                return Err(ConfigTemplateError::Validation(format!(
                    "n_samples {} below minimum {}",
                    config.n_samples, min_samples
                )));
            }
        }

        if let Some(max_samples) = constraints.max_samples {
            if config.n_samples > max_samples {
                return Err(ConfigTemplateError::Validation(format!(
                    "n_samples {} above maximum {}",
                    config.n_samples, max_samples
                )));
            }
        }

        if let Some(min_features) = constraints.min_features {
            if config.n_features < min_features {
                return Err(ConfigTemplateError::Validation(format!(
                    "n_features {} below minimum {}",
                    config.n_features, min_features
                )));
            }
        }

        if let Some(max_features) = constraints.max_features {
            if config.n_features > max_features {
                return Err(ConfigTemplateError::Validation(format!(
                    "n_features {} above maximum {}",
                    config.n_features, max_features
                )));
            }
        }

        Ok(())
    }

    /// Export template to YAML
    pub fn export_template_yaml(&self, name: &str) -> ConfigTemplateResult<String> {
        let template = self
            .get_template(name)
            .ok_or_else(|| ConfigTemplateError::TemplateNotFound(name.to_string()))?;

        serde_yaml::to_string(template).map_err(|e| ConfigTemplateError::Yaml(e.to_string()))
    }

    /// Export template to JSON
    pub fn export_template_json(&self, name: &str) -> ConfigTemplateResult<String> {
        let template = self
            .get_template(name)
            .ok_or_else(|| ConfigTemplateError::TemplateNotFound(name.to_string()))?;

        Ok(serde_json::to_string_pretty(template)?)
    }
}

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

/// Template builder for programmatic template creation
pub struct TemplateBuilder {
    template: DatasetTemplate,
}

impl TemplateBuilder {
    /// Create a new template builder
    pub fn new(name: &str) -> Self {
        Self {
            template: DatasetTemplate {
                metadata: TemplateMetadata {
                    name: name.to_string(),
                    version: "1.0.0".to_string(),
                    description: "".to_string(),
                    author: "".to_string(),
                    created: None,
                    modified: None,
                    tags: Vec::new(),
                    category: None,
                },
                extends: None,
                generator: GeneratorTemplateConfig {
                    name: "classification".to_string(),
                    n_samples: Some(1000),
                    n_features: Some(10),
                    random_state: None,
                    parameters: HashMap::new(),
                },
                parameters: HashMap::new(),
                validation: None,
                export: None,
                experiment: None,
            },
        }
    }

    /// Set metadata
    pub fn metadata(mut self, metadata: TemplateMetadata) -> Self {
        self.template.metadata = metadata;
        self
    }

    /// Set generator
    pub fn generator(mut self, generator: GeneratorTemplateConfig) -> Self {
        self.template.generator = generator;
        self
    }

    /// Add parameter definition
    pub fn parameter(mut self, name: String, param: ParameterTemplate) -> Self {
        self.template.parameters.insert(name, param);
        self
    }

    /// Set validation rules
    pub fn validation(mut self, validation: ValidationRules) -> Self {
        self.template.validation = Some(validation);
        self
    }

    /// Set inheritance
    pub fn extends(mut self, base: String) -> Self {
        self.template.extends = Some(base);
        self
    }

    /// Build the template
    pub fn build(self) -> DatasetTemplate {
        self.template
    }
}

/// Convenience functions for creating common templates
pub fn create_classification_template() -> DatasetTemplate {
    TemplateBuilder::new("classification_basic")
        .metadata(TemplateMetadata {
            name: "classification_basic".to_string(),
            version: "1.0.0".to_string(),
            description: "Basic classification dataset template".to_string(),
            author: "sklears".to_string(),
            created: None,
            modified: None,
            tags: vec!["classification".to_string(), "basic".to_string()],
            category: Some("classification".to_string()),
        })
        .parameter(
            "n_classes".to_string(),
            ParameterTemplate {
                description: "Number of classes".to_string(),
                param_type: ParameterTypeTemplate::Integer {
                    min: Some(2),
                    max: Some(10),
                },
                required: false,
                default: Some(serde_yaml::Value::Number(serde_yaml::Number::from(2))),
                constraints: None,
                dependencies: vec![],
            },
        )
        .parameter(
            "n_informative".to_string(),
            ParameterTemplate {
                description: "Number of informative features".to_string(),
                param_type: ParameterTypeTemplate::Integer {
                    min: Some(1),
                    max: None,
                },
                required: false,
                default: None,
                constraints: None,
                dependencies: vec![],
            },
        )
        .build()
}

pub fn create_regression_template() -> DatasetTemplate {
    TemplateBuilder::new("regression_basic")
        .metadata(TemplateMetadata {
            name: "regression_basic".to_string(),
            version: "1.0.0".to_string(),
            description: "Basic regression dataset template".to_string(),
            author: "sklears".to_string(),
            created: None,
            modified: None,
            tags: vec!["regression".to_string(), "basic".to_string()],
            category: Some("regression".to_string()),
        })
        .generator(GeneratorTemplateConfig {
            name: "regression".to_string(),
            n_samples: Some(1000),
            n_features: Some(5),
            random_state: Some(42),
            parameters: HashMap::new(),
        })
        .parameter(
            "noise".to_string(),
            ParameterTemplate {
                description: "Standard deviation of gaussian noise".to_string(),
                param_type: ParameterTypeTemplate::Float {
                    min: Some(0.0),
                    max: Some(1.0),
                },
                required: false,
                default: Some(serde_yaml::Value::Number(serde_yaml::Number::from(0.1))),
                constraints: None,
                dependencies: vec![],
            },
        )
        .build()
}

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

    #[test]
    fn test_template_builder() {
        let template = TemplateBuilder::new("test_template")
            .metadata(TemplateMetadata {
                name: "test_template".to_string(),
                version: "1.0.0".to_string(),
                description: "Test template".to_string(),
                author: "Test".to_string(),
                created: None,
                modified: None,
                tags: vec!["test".to_string()],
                category: Some("test".to_string()),
            })
            .build();

        assert_eq!(template.metadata.name, "test_template");
        assert_eq!(template.metadata.version, "1.0.0");
    }

    #[test]
    fn test_template_library() {
        let mut library = TemplateLibrary::new();

        // Register a template
        let template = create_classification_template();
        library.register_template(template);

        // Check if registered
        assert!(library.get_template("classification_basic").is_some());
        assert!(library
            .list_templates()
            .contains(&"classification_basic".to_string()));

        // Search by tag
        let classification_templates = library.search_by_tag("classification");
        assert!(classification_templates.contains(&"classification_basic".to_string()));
    }

    #[test]
    fn test_template_resolution() {
        let mut library = TemplateLibrary::new();
        library.register_template(create_classification_template());

        // Resolve template
        let config = library
            .resolve_template("classification_basic", None)
            .expect("operation should succeed");
        assert_eq!(config.n_samples, 1000);
        assert_eq!(config.n_features, 10);

        // Test with overrides
        let mut overrides = HashMap::new();
        overrides.insert(
            "n_classes".to_string(),
            serde_yaml::Value::Number(serde_yaml::Number::from(5)),
        );

        let config_with_overrides = library
            .resolve_template("classification_basic", Some(overrides))
            .expect("operation should succeed");

        if let Some(crate::traits::ConfigValue::Int(n_classes)) =
            config_with_overrides.get_parameter("n_classes")
        {
            assert_eq!(*n_classes, 5);
        }
    }

    #[test]
    fn test_yaml_serialization() {
        let template = create_regression_template();
        let yaml = serde_yaml::to_string(&template).expect("operation should succeed");

        // Verify it can be parsed back
        let parsed: DatasetTemplate = serde_yaml::from_str(&yaml).expect("parsing should succeed");
        assert_eq!(parsed.metadata.name, "regression_basic");
    }

    #[test]
    fn test_template_inheritance() {
        let mut library = TemplateLibrary::new();

        // Create base template
        let base = create_classification_template();
        library.register_template(base);

        // Create derived template
        let derived = TemplateBuilder::new("classification_advanced")
            .extends("classification_basic".to_string())
            .generator(GeneratorTemplateConfig {
                name: "classification".to_string(),
                n_samples: Some(5000), // Override
                n_features: Some(20),  // Override
                random_state: Some(123),
                parameters: HashMap::new(),
            })
            .build();

        library.register_template(derived);

        // Resolve derived template
        let config = library
            .resolve_template("classification_advanced", None)
            .expect("operation should succeed");
        assert_eq!(config.n_samples, 5000); // Should be overridden
        assert_eq!(config.n_features, 20); // Should be overridden
    }

    #[test]
    fn test_parameter_validation() {
        let mut library = TemplateLibrary::new();
        library.register_template(create_classification_template());

        // Test valid override
        let mut valid_overrides = HashMap::new();
        valid_overrides.insert(
            "n_classes".to_string(),
            serde_yaml::Value::Number(serde_yaml::Number::from(3)),
        );

        assert!(library
            .resolve_template("classification_basic", Some(valid_overrides))
            .is_ok());

        // Test invalid override (out of range)
        let mut invalid_overrides = HashMap::new();
        invalid_overrides.insert(
            "n_classes".to_string(),
            serde_yaml::Value::Number(serde_yaml::Number::from(15)), // Above max of 10
        );

        assert!(library
            .resolve_template("classification_basic", Some(invalid_overrides))
            .is_err());
    }
}