optimizer 1.0.1

Bayesian and population-based optimization library with an Optuna-like API for hyperparameter tuning and black-box optimization
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
//! Parameter trait and five built-in parameter types.
//!
//! The [`Parameter`] trait provides a unified way to define search-space
//! dimensions and sample values from a [`Trial`]. Five implementations
//! cover the most common hyperparameter types:
//!
//! | Type | Sampled value | Typical use |
//! |------|---------------|-------------|
//! | [`FloatParam`] | `f64` | Learning rate, dropout probability |
//! | [`IntParam`] | `i64` | Layer count, batch size |
//! | [`CategoricalParam`] | `T: Clone` | Optimizer name, activation function |
//! | [`BoolParam`] | `bool` | Feature toggle |
//! | [`EnumParam`] | `T: Categorical` | Typed enum variant selection |
//!
//! All five types support `.name()` for a human-readable label and
//! `.suggest(&mut trial)` as a shorthand for `trial.suggest_param(&param)`.
//!
//! # Example
//!
//! ```
//! use optimizer::Trial;
//! use optimizer::parameter::{BoolParam, FloatParam, IntParam, Parameter};
//!
//! let mut trial = Trial::new(0);
//!
//! let lr = FloatParam::new(1e-5, 1e-1)
//!     .log_scale()
//!     .name("learning_rate")
//!     .suggest(&mut trial)
//!     .unwrap();
//! let layers = IntParam::new(1, 10)
//!     .name("n_layers")
//!     .suggest(&mut trial)
//!     .unwrap();
//! let dropout = BoolParam::new()
//!     .name("use_dropout")
//!     .suggest(&mut trial)
//!     .unwrap();
//! ```

use core::fmt::Debug;
use core::ops::RangeInclusive;
use core::sync::atomic::{AtomicU64, Ordering};

use crate::distribution::{
    CategoricalDistribution, Distribution, FloatDistribution, IntDistribution,
};
use crate::error::{Error, Result};
pub use crate::param::ParamValue;
use crate::trial::Trial;

static NEXT_PARAM_ID: AtomicU64 = AtomicU64::new(0);

/// A unique identifier for a parameter instance.
///
/// Each parameter is assigned a unique `ParamId` at creation time. Cloning a parameter
/// copies its `ParamId`, so clones refer to the same logical parameter.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ParamId(u64);

impl ParamId {
    /// Create a new unique `ParamId`.
    pub fn new() -> Self {
        Self(NEXT_PARAM_ID.fetch_add(1, Ordering::Relaxed))
    }
}

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

impl core::fmt::Display for ParamId {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "param_{}", self.0)
    }
}

/// Define a parameter type that can be suggested by a [`Trial`].
///
/// Implementors specify the distribution to sample from and how to convert
/// the raw [`ParamValue`] back into a typed value. See the five built-in
/// implementations: [`FloatParam`], [`IntParam`], [`CategoricalParam`],
/// [`BoolParam`], and [`EnumParam`].
pub trait Parameter: Debug {
    /// The typed value returned after sampling.
    type Value;

    /// Return the unique identifier for this parameter.
    fn id(&self) -> ParamId;

    /// Return the distribution that this parameter samples from.
    fn distribution(&self) -> Distribution;

    /// Convert a raw [`ParamValue`] into the typed value.
    ///
    /// # Errors
    ///
    /// Return an error if the `ParamValue` variant does not match what this parameter expects.
    fn cast_param_value(&self, param_value: &ParamValue) -> Result<Self::Value>;

    /// Validate the parameter configuration.
    ///
    /// Called before sampling. The default implementation accepts all configurations.
    ///
    /// # Errors
    ///
    /// Return an error if the parameter configuration is invalid.
    fn validate(&self) -> Result<()> {
        Ok(())
    }

    /// Return a human-readable label for this parameter.
    ///
    /// Defaults to the `Debug` output of the parameter. Override with
    /// the `.name()` builder method on concrete types.
    fn label(&self) -> String {
        format!("{self:?}")
    }

    /// Suggest a value for this parameter from the given trial.
    ///
    /// This is a convenience method that delegates to [`Trial::suggest_param`].
    ///
    /// # Examples
    ///
    /// ```
    /// use optimizer::Trial;
    /// use optimizer::parameter::{FloatParam, Parameter};
    ///
    /// let mut trial = Trial::new(0);
    /// let param = FloatParam::new(-5.0, 5.0).name("x");
    /// let value: f64 = param.suggest(&mut trial).unwrap();
    /// assert!((-5.0..=5.0).contains(&value));
    /// ```
    ///
    /// # Errors
    ///
    /// Return an error if validation fails, the parameter conflicts with
    /// a previously suggested parameter of the same id, or sampling fails.
    fn suggest(&self, trial: &mut Trial) -> Result<Self::Value>
    where
        Self: Sized,
    {
        trial.suggest_param(self)
    }
}

/// A floating-point parameter with optional log-scale and step size.
///
/// # Examples
///
/// ```
/// use optimizer::Trial;
/// use optimizer::parameter::{FloatParam, Parameter};
///
/// let mut trial = Trial::new(0);
///
/// // Simple range
/// let x = FloatParam::new(0.0, 1.0).suggest(&mut trial).unwrap();
///
/// // Log-scale with a human-readable name
/// let lr = FloatParam::new(1e-5, 1e-1)
///     .log_scale()
///     .name("learning_rate")
///     .suggest(&mut trial)
///     .unwrap();
///
/// // Stepped (values will be multiples of 0.25)
/// let step = FloatParam::new(0.0, 1.0)
///     .step(0.25)
///     .suggest(&mut trial)
///     .unwrap();
/// ```
#[derive(Clone, Debug)]
pub struct FloatParam {
    id: ParamId,
    low: f64,
    high: f64,
    log_scale: bool,
    step: Option<f64>,
    name: Option<String>,
}

impl FloatParam {
    /// Create a new float parameter sampling uniformly from `[low, high]`.
    #[must_use]
    pub fn new(low: f64, high: f64) -> Self {
        Self {
            id: ParamId::new(),
            low,
            high,
            log_scale: false,
            step: None,
            name: None,
        }
    }

    /// Enable log-scale sampling (bounds must be positive).
    #[must_use]
    pub fn log_scale(mut self) -> Self {
        self.log_scale = true;
        self
    }

    /// Set a step size for discretized sampling.
    #[must_use]
    pub fn step(mut self, step: f64) -> Self {
        self.step = Some(step);
        self
    }

    /// Set a human-readable name for this parameter.
    ///
    /// When set, this name is used as the parameter's label instead of
    /// the default `Debug` output.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }
}

impl From<RangeInclusive<f64>> for FloatParam {
    fn from(range: RangeInclusive<f64>) -> Self {
        FloatParam::new(*range.start(), *range.end())
    }
}

impl Parameter for FloatParam {
    type Value = f64;

    fn id(&self) -> ParamId {
        self.id
    }

    fn distribution(&self) -> Distribution {
        Distribution::Float(FloatDistribution {
            low: self.low,
            high: self.high,
            log_scale: self.log_scale,
            step: self.step,
        })
    }

    fn cast_param_value(&self, param_value: &ParamValue) -> Result<f64> {
        match param_value {
            ParamValue::Float(v) => Ok(*v),
            _ => Err(Error::Internal(
                "Float distribution should return Float value",
            )),
        }
    }

    fn validate(&self) -> Result<()> {
        if !self.low.is_finite() || !self.high.is_finite() {
            return Err(Error::InvalidBounds {
                low: self.low,
                high: self.high,
            });
        }
        if self.low > self.high {
            return Err(Error::InvalidBounds {
                low: self.low,
                high: self.high,
            });
        }
        if self.log_scale && self.low <= 0.0 {
            return Err(Error::InvalidLogBounds);
        }
        if let Some(step) = self.step
            && (!step.is_finite() || step <= 0.0)
        {
            return Err(Error::InvalidStep);
        }
        Ok(())
    }

    fn label(&self) -> String {
        self.name.clone().unwrap_or_else(|| format!("{self:?}"))
    }
}

/// An integer parameter with optional log-scale and step size.
///
/// # Examples
///
/// ```
/// use optimizer::Trial;
/// use optimizer::parameter::{IntParam, Parameter};
///
/// let mut trial = Trial::new(0);
///
/// // Simple range
/// let n = IntParam::new(1, 10)
///     .name("n_layers")
///     .suggest(&mut trial)
///     .unwrap();
///
/// // Log-scale
/// let batch = IntParam::new(1, 1024)
///     .log_scale()
///     .name("batch_size")
///     .suggest(&mut trial)
///     .unwrap();
///
/// // Stepped (multiples of 32)
/// let units = IntParam::new(32, 512).step(32).suggest(&mut trial).unwrap();
/// ```
#[derive(Clone, Debug)]
pub struct IntParam {
    id: ParamId,
    low: i64,
    high: i64,
    log_scale: bool,
    step: Option<i64>,
    name: Option<String>,
}

impl IntParam {
    /// Create a new integer parameter sampling uniformly from `[low, high]`.
    #[must_use]
    pub fn new(low: i64, high: i64) -> Self {
        Self {
            id: ParamId::new(),
            low,
            high,
            log_scale: false,
            step: None,
            name: None,
        }
    }

    /// Enable log-scale sampling (bounds must be ≥ 1).
    #[must_use]
    pub fn log_scale(mut self) -> Self {
        self.log_scale = true;
        self
    }

    /// Set a step size for discretized sampling.
    #[must_use]
    pub fn step(mut self, step: i64) -> Self {
        self.step = Some(step);
        self
    }

    /// Set a human-readable name for this parameter.
    ///
    /// When set, this name is used as the parameter's label instead of
    /// the default `Debug` output.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }
}

impl From<RangeInclusive<i64>> for IntParam {
    fn from(range: RangeInclusive<i64>) -> Self {
        IntParam::new(*range.start(), *range.end())
    }
}

impl Parameter for IntParam {
    type Value = i64;

    fn id(&self) -> ParamId {
        self.id
    }

    fn distribution(&self) -> Distribution {
        Distribution::Int(IntDistribution {
            low: self.low,
            high: self.high,
            log_scale: self.log_scale,
            step: self.step,
        })
    }

    #[allow(clippy::cast_precision_loss)]
    fn cast_param_value(&self, param_value: &ParamValue) -> Result<i64> {
        match param_value {
            ParamValue::Int(v) => Ok(*v),
            _ => Err(Error::Internal("Int distribution should return Int value")),
        }
    }

    #[allow(clippy::cast_precision_loss)]
    fn validate(&self) -> Result<()> {
        if self.low > self.high {
            return Err(Error::InvalidBounds {
                low: self.low as f64,
                high: self.high as f64,
            });
        }
        if self.log_scale && self.low < 1 {
            return Err(Error::InvalidLogBounds);
        }
        if let Some(step) = self.step
            && step <= 0
        {
            return Err(Error::InvalidStep);
        }
        Ok(())
    }

    fn label(&self) -> String {
        self.name.clone().unwrap_or_else(|| format!("{self:?}"))
    }
}

/// A categorical parameter that selects from a list of choices.
///
/// The generic type `T` is the element type of the choices vector.
/// The sampler picks an index and the corresponding element is returned.
///
/// # Examples
///
/// ```
/// use optimizer::Trial;
/// use optimizer::parameter::{CategoricalParam, Parameter};
///
/// let mut trial = Trial::new(0);
/// let opt = CategoricalParam::new(vec!["sgd", "adam", "rmsprop"])
///     .name("optimizer")
///     .suggest(&mut trial)
///     .unwrap();
/// ```
#[derive(Clone, Debug)]
pub struct CategoricalParam<T: Clone> {
    id: ParamId,
    choices: Vec<T>,
    name: Option<String>,
}

impl<T: Clone> CategoricalParam<T> {
    /// Create a new categorical parameter with the given choices.
    #[must_use]
    pub fn new(choices: Vec<T>) -> Self {
        Self {
            id: ParamId::new(),
            choices,
            name: None,
        }
    }

    /// Set a human-readable name for this parameter.
    ///
    /// When set, this name is used as the parameter's label instead of
    /// the default `Debug` output.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }
}

impl<T: Clone + Debug> Parameter for CategoricalParam<T> {
    type Value = T;

    fn id(&self) -> ParamId {
        self.id
    }

    fn distribution(&self) -> Distribution {
        Distribution::Categorical(CategoricalDistribution {
            n_choices: self.choices.len(),
        })
    }

    fn cast_param_value(&self, param_value: &ParamValue) -> Result<T> {
        match param_value {
            ParamValue::Categorical(index) => self
                .choices
                .get(*index)
                .cloned()
                .ok_or(Error::Internal("categorical index out of bounds")),
            _ => Err(Error::Internal(
                "Categorical distribution should return Categorical value",
            )),
        }
    }

    fn validate(&self) -> Result<()> {
        if self.choices.is_empty() {
            return Err(Error::EmptyChoices);
        }
        Ok(())
    }

    fn label(&self) -> String {
        self.name.clone().unwrap_or_else(|| format!("{self:?}"))
    }
}

/// A boolean parameter (equivalent to a two-choice categorical: `false` / `true`).
///
/// # Examples
///
/// ```
/// use optimizer::Trial;
/// use optimizer::parameter::{BoolParam, Parameter};
///
/// let mut trial = Trial::new(0);
/// let use_dropout = BoolParam::new()
///     .name("use_dropout")
///     .suggest(&mut trial)
///     .unwrap();
/// ```
#[derive(Clone, Debug)]
pub struct BoolParam {
    id: ParamId,
    name: Option<String>,
}

impl BoolParam {
    /// Create a new boolean parameter.
    #[must_use]
    pub fn new() -> Self {
        Self {
            id: ParamId::new(),
            name: None,
        }
    }

    /// Set a human-readable name for this parameter.
    ///
    /// When set, this name is used as the parameter's label instead of
    /// the default `Debug` output.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }
}

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

impl Parameter for BoolParam {
    type Value = bool;

    fn id(&self) -> ParamId {
        self.id
    }

    fn distribution(&self) -> Distribution {
        Distribution::Categorical(CategoricalDistribution { n_choices: 2 })
    }

    fn cast_param_value(&self, param_value: &ParamValue) -> Result<bool> {
        match param_value {
            ParamValue::Categorical(index) if *index < 2 => Ok(*index != 0),
            ParamValue::Categorical(_) => Err(Error::Internal("bool index out of bounds")),
            _ => Err(Error::Internal(
                "Categorical distribution should return Categorical value",
            )),
        }
    }

    fn label(&self) -> String {
        self.name.clone().unwrap_or_else(|| format!("{self:?}"))
    }
}

/// Map an enum type to sequential indices for use as a categorical parameter.
///
/// This trait converts enum variants to sequential indices and back. It can
/// be derived automatically for fieldless enums using `#[derive(Categorical)]`
/// when the `derive` feature is enabled.
///
/// # Example
///
/// Manual implementation:
///
/// ```
/// use optimizer::parameter::Categorical;
///
/// #[derive(Clone)]
/// enum Activation {
///     Relu,
///     Sigmoid,
///     Tanh,
/// }
///
/// impl Categorical for Activation {
///     const N_CHOICES: usize = 3;
///
///     fn from_index(index: usize) -> Self {
///         match index {
///             0 => Activation::Relu,
///             1 => Activation::Sigmoid,
///             2 => Activation::Tanh,
///             _ => panic!("invalid index"),
///         }
///     }
///
///     fn to_index(&self) -> usize {
///         match self {
///             Activation::Relu => 0,
///             Activation::Sigmoid => 1,
///             Activation::Tanh => 2,
///         }
///     }
/// }
/// ```
pub trait Categorical: Sized + Clone {
    /// The number of variants in the enum.
    const N_CHOICES: usize;

    /// Create an instance from a variant index.
    ///
    /// # Panics
    ///
    /// Panics if `index >= N_CHOICES`.
    fn from_index(index: usize) -> Self;

    /// Return the index of this variant.
    fn to_index(&self) -> usize;
}

/// A parameter that selects from the variants of an enum implementing [`Categorical`].
///
/// Prefer this over [`CategoricalParam`] when the choices map to a Rust enum,
/// because the returned value is already the correct variant — no string
/// matching required.
///
/// # Examples
///
/// ```
/// use optimizer::Trial;
/// use optimizer::parameter::{Categorical, EnumParam, Parameter};
///
/// #[derive(Clone, Debug)]
/// enum Optimizer {
///     Sgd,
///     Adam,
///     Rmsprop,
/// }
///
/// impl Categorical for Optimizer {
///     const N_CHOICES: usize = 3;
///     fn from_index(index: usize) -> Self {
///         match index {
///             0 => Optimizer::Sgd,
///             1 => Optimizer::Adam,
///             2 => Optimizer::Rmsprop,
///             _ => panic!("invalid index"),
///         }
///     }
///     fn to_index(&self) -> usize {
///         match self {
///             Optimizer::Sgd => 0,
///             Optimizer::Adam => 1,
///             Optimizer::Rmsprop => 2,
///         }
///     }
/// }
///
/// let mut trial = Trial::new(0);
/// let opt = EnumParam::<Optimizer>::new()
///     .name("optimizer")
///     .suggest(&mut trial)
///     .unwrap();
/// ```
#[derive(Clone, Debug)]
pub struct EnumParam<T: Categorical> {
    id: ParamId,
    name: Option<String>,
    _marker: core::marker::PhantomData<T>,
}

impl<T: Categorical> EnumParam<T> {
    /// Create a new enum parameter over all variants of `T`.
    #[must_use]
    pub fn new() -> Self {
        Self {
            id: ParamId::new(),
            name: None,
            _marker: core::marker::PhantomData,
        }
    }

    /// Set a human-readable name for this parameter.
    ///
    /// When set, this name is used as the parameter's label instead of
    /// the default `Debug` output.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }
}

impl<T: Categorical> Default for EnumParam<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Categorical + Debug> Parameter for EnumParam<T> {
    type Value = T;

    fn id(&self) -> ParamId {
        self.id
    }

    fn distribution(&self) -> Distribution {
        Distribution::Categorical(CategoricalDistribution {
            n_choices: T::N_CHOICES,
        })
    }

    fn cast_param_value(&self, param_value: &ParamValue) -> Result<T> {
        match param_value {
            ParamValue::Categorical(index) if *index < T::N_CHOICES => Ok(T::from_index(*index)),
            ParamValue::Categorical(_) => Err(Error::Internal("categorical index out of bounds")),
            _ => Err(Error::Internal(
                "Categorical distribution should return Categorical value",
            )),
        }
    }

    fn label(&self) -> String {
        self.name.clone().unwrap_or_else(|| format!("{self:?}"))
    }
}

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

    #[test]
    fn float_param_distribution() {
        let param = FloatParam::new(0.0, 1.0);
        assert_eq!(
            param.distribution(),
            Distribution::Float(FloatDistribution {
                low: 0.0,
                high: 1.0,
                log_scale: false,
                step: None,
            })
        );
    }

    #[test]
    fn float_param_log_scale() {
        let param = FloatParam::new(1e-5, 1e-1).log_scale();
        assert_eq!(
            param.distribution(),
            Distribution::Float(FloatDistribution {
                low: 1e-5,
                high: 1e-1,
                log_scale: true,
                step: None,
            })
        );
    }

    #[test]
    fn float_param_step() {
        let param = FloatParam::new(0.0, 1.0).step(0.25);
        assert_eq!(
            param.distribution(),
            Distribution::Float(FloatDistribution {
                low: 0.0,
                high: 1.0,
                log_scale: false,
                step: Some(0.25),
            })
        );
    }

    #[test]
    fn float_param_validate_invalid_bounds() {
        let param = FloatParam::new(1.0, 0.0);
        assert!(param.validate().is_err());
    }

    #[test]
    fn float_param_validate_invalid_log() {
        let param = FloatParam::new(-1.0, 1.0).log_scale();
        assert!(param.validate().is_err());
    }

    #[test]
    fn float_param_validate_invalid_step() {
        let param = FloatParam::new(0.0, 1.0).step(-0.1);
        assert!(param.validate().is_err());
    }

    #[test]
    fn float_param_validate_nan() {
        assert!(FloatParam::new(f64::NAN, 1.0).validate().is_err());
        assert!(FloatParam::new(0.0, f64::NAN).validate().is_err());
        assert!(FloatParam::new(f64::NAN, f64::NAN).validate().is_err());
    }

    #[test]
    fn float_param_validate_infinity() {
        assert!(FloatParam::new(f64::INFINITY, 1.0).validate().is_err());
        assert!(FloatParam::new(0.0, f64::NEG_INFINITY).validate().is_err());
    }

    #[test]
    fn float_param_validate_nan_step() {
        assert!(FloatParam::new(0.0, 1.0).step(f64::NAN).validate().is_err());
        assert!(
            FloatParam::new(0.0, 1.0)
                .step(f64::INFINITY)
                .validate()
                .is_err()
        );
    }

    #[test]
    #[allow(clippy::float_cmp)]
    fn float_param_cast_param_value() {
        let param = FloatParam::new(0.0, 1.0);
        assert_eq!(
            param.cast_param_value(&ParamValue::Float(0.5)).unwrap(),
            0.5
        );
        assert!(param.cast_param_value(&ParamValue::Int(1)).is_err());
    }

    #[test]
    fn int_param_distribution() {
        let param = IntParam::new(1, 100);
        assert_eq!(
            param.distribution(),
            Distribution::Int(IntDistribution {
                low: 1,
                high: 100,
                log_scale: false,
                step: None,
            })
        );
    }

    #[test]
    fn int_param_log_scale() {
        let param = IntParam::new(1, 1024).log_scale();
        assert_eq!(
            param.distribution(),
            Distribution::Int(IntDistribution {
                low: 1,
                high: 1024,
                log_scale: true,
                step: None,
            })
        );
    }

    #[test]
    fn int_param_step() {
        let param = IntParam::new(100, 500).step(50);
        assert_eq!(
            param.distribution(),
            Distribution::Int(IntDistribution {
                low: 100,
                high: 500,
                log_scale: false,
                step: Some(50),
            })
        );
    }

    #[test]
    fn int_param_validate_invalid_bounds() {
        let param = IntParam::new(10, 1);
        assert!(param.validate().is_err());
    }

    #[test]
    fn int_param_validate_invalid_log() {
        let param = IntParam::new(0, 10).log_scale();
        assert!(param.validate().is_err());
    }

    #[test]
    fn int_param_validate_invalid_step() {
        let param = IntParam::new(0, 10).step(-1);
        assert!(param.validate().is_err());
    }

    #[test]
    fn int_param_cast_param_value() {
        let param = IntParam::new(1, 10);
        assert_eq!(param.cast_param_value(&ParamValue::Int(5)).unwrap(), 5);
        assert!(param.cast_param_value(&ParamValue::Float(1.0)).is_err());
    }

    #[test]
    fn categorical_param_distribution() {
        let param = CategoricalParam::new(vec!["a", "b", "c"]);
        assert_eq!(
            param.distribution(),
            Distribution::Categorical(CategoricalDistribution { n_choices: 3 })
        );
    }

    #[test]
    fn categorical_param_validate_empty() {
        let param = CategoricalParam::<&str>::new(vec![]);
        assert!(param.validate().is_err());
    }

    #[test]
    fn categorical_param_cast_param_value() {
        let param = CategoricalParam::new(vec!["sgd", "adam", "rmsprop"]);
        assert_eq!(
            param.cast_param_value(&ParamValue::Categorical(1)).unwrap(),
            "adam"
        );
        assert!(param.cast_param_value(&ParamValue::Float(1.0)).is_err());
    }

    #[test]
    fn categorical_param_cast_out_of_bounds() {
        let param = CategoricalParam::new(vec!["sgd", "adam", "rmsprop"]);
        assert!(param.cast_param_value(&ParamValue::Categorical(3)).is_err());
        assert!(
            param
                .cast_param_value(&ParamValue::Categorical(usize::MAX))
                .is_err()
        );
    }

    #[test]
    fn bool_param_distribution() {
        let param = BoolParam::new();
        assert_eq!(
            param.distribution(),
            Distribution::Categorical(CategoricalDistribution { n_choices: 2 })
        );
    }

    #[test]
    fn bool_param_cast_param_value() {
        let param = BoolParam::new();
        assert!(!param.cast_param_value(&ParamValue::Categorical(0)).unwrap());
        assert!(param.cast_param_value(&ParamValue::Categorical(1)).unwrap());
        assert!(param.cast_param_value(&ParamValue::Float(1.0)).is_err());
    }

    #[test]
    fn bool_param_cast_out_of_bounds() {
        let param = BoolParam::new();
        assert!(param.cast_param_value(&ParamValue::Categorical(2)).is_err());
        assert!(param.cast_param_value(&ParamValue::Categorical(5)).is_err());
    }

    #[derive(Clone, Debug, PartialEq)]
    enum TestEnum {
        A,
        B,
        C,
    }

    impl Categorical for TestEnum {
        const N_CHOICES: usize = 3;

        fn from_index(index: usize) -> Self {
            match index {
                0 => TestEnum::A,
                1 => TestEnum::B,
                2 => TestEnum::C,
                _ => panic!("invalid index"),
            }
        }

        fn to_index(&self) -> usize {
            match self {
                TestEnum::A => 0,
                TestEnum::B => 1,
                TestEnum::C => 2,
            }
        }
    }

    #[test]
    fn enum_param_distribution() {
        let param = EnumParam::<TestEnum>::new();
        assert_eq!(
            param.distribution(),
            Distribution::Categorical(CategoricalDistribution { n_choices: 3 })
        );
    }

    #[test]
    fn enum_param_cast_param_value() {
        let param = EnumParam::<TestEnum>::new();
        assert_eq!(
            param.cast_param_value(&ParamValue::Categorical(0)).unwrap(),
            TestEnum::A
        );
        assert_eq!(
            param.cast_param_value(&ParamValue::Categorical(2)).unwrap(),
            TestEnum::C
        );
        assert!(param.cast_param_value(&ParamValue::Float(1.0)).is_err());
    }

    #[test]
    fn enum_param_cast_out_of_bounds() {
        let param = EnumParam::<TestEnum>::new();
        assert!(param.cast_param_value(&ParamValue::Categorical(3)).is_err());
        assert!(
            param
                .cast_param_value(&ParamValue::Categorical(usize::MAX))
                .is_err()
        );
    }

    #[test]
    fn float_param_suggest_via_trial() {
        let param = FloatParam::new(0.0, 1.0);
        let mut trial = Trial::new(0);
        let x = param.suggest(&mut trial).unwrap();
        assert!((0.0..=1.0).contains(&x));

        // Cached value (same param id) - exact equality expected for cached values
        let x2 = param.suggest(&mut trial).unwrap();
        assert!((x - x2).abs() < f64::EPSILON);
    }

    #[test]
    fn int_param_suggest_via_trial() {
        let param = IntParam::new(1, 10);
        let mut trial = Trial::new(0);
        let n = param.suggest(&mut trial).unwrap();
        assert!((1..=10).contains(&n));

        // Cached value
        let n2 = param.suggest(&mut trial).unwrap();
        assert_eq!(n, n2);
    }

    #[test]
    fn categorical_param_suggest_via_trial() {
        let choices = vec!["sgd", "adam", "rmsprop"];
        let param = CategoricalParam::new(choices.clone());
        let mut trial = Trial::new(0);
        let opt = param.suggest(&mut trial).unwrap();
        assert!(choices.contains(&opt));

        // Cached value
        let opt2 = param.suggest(&mut trial).unwrap();
        assert_eq!(opt, opt2);
    }

    #[test]
    fn bool_param_suggest_via_trial() {
        let param = BoolParam::new();
        let mut trial = Trial::new(0);
        let val = param.suggest(&mut trial).unwrap();
        let _ = val; // just check it doesn't error

        // Cached value
        let val2 = param.suggest(&mut trial).unwrap();
        assert_eq!(val, val2);
    }

    #[test]
    fn enum_param_suggest_via_trial() {
        let param = EnumParam::<TestEnum>::new();
        let mut trial = Trial::new(0);
        let val = param.suggest(&mut trial).unwrap();
        assert!([TestEnum::A, TestEnum::B, TestEnum::C].contains(&val));

        // Cached value
        let val2 = param.suggest(&mut trial).unwrap();
        assert_eq!(val, val2);
    }

    #[test]
    fn parameter_conflict_detection() {
        let param_float = FloatParam::new(0.0, 1.0);
        let param_int = IntParam::new(0, 10);
        let mut trial = Trial::new(0);
        let _ = param_float.suggest(&mut trial).unwrap();

        // Different param with different distribution but same id won't happen
        // since each param gets a unique id. But different param object = different id = no conflict.
        let result = param_int.suggest(&mut trial);
        assert!(result.is_ok()); // Different id, no conflict
    }

    #[test]
    fn float_param_validation_prevents_suggest() {
        let param = FloatParam::new(1.0, 0.0);
        let mut trial = Trial::new(0);
        let result = param.suggest(&mut trial);
        assert!(result.is_err());
    }

    #[test]
    fn categorical_trait_roundtrip() {
        for i in 0..TestEnum::N_CHOICES {
            let val = TestEnum::from_index(i);
            assert_eq!(val.to_index(), i);
        }
    }

    #[test]
    fn param_id_uniqueness() {
        let id1 = ParamId::new();
        let id2 = ParamId::new();
        assert_ne!(id1, id2);
    }

    #[test]
    fn param_clone_preserves_id() {
        let param = FloatParam::new(0.0, 1.0);
        let cloned = param.clone();
        assert_eq!(param.id(), cloned.id());
    }

    #[test]
    fn float_param_from_range() {
        let param = FloatParam::from(0.0..=1.0);
        assert_eq!(
            param.distribution(),
            Distribution::Float(FloatDistribution {
                low: 0.0,
                high: 1.0,
                log_scale: false,
                step: None,
            })
        );
        assert_eq!(param.label(), format!("{param:?}"));
    }

    #[test]
    fn int_param_from_range() {
        let param = IntParam::from(1..=10);
        assert_eq!(
            param.distribution(),
            Distribution::Int(IntDistribution {
                low: 1,
                high: 10,
                log_scale: false,
                step: None,
            })
        );
        assert_eq!(param.label(), format!("{param:?}"));
    }
}