Skip to main content

hyperopt_rs/
lib.rs

1//! # hyperopt
2//!
3//! `hyperopt-rs` — an Optuna-shaped hyperparameter optimization framework for
4//! Rust. This is the ergonomic facade crate: it re-exports the core types and
5//! every sampler, pruner, and storage backend, and adds a [`StudyBuilder`] so a
6//! study can be assembled in one fluent expression.
7//!
8//! ```no_run
9//! use hyperopt_rs::prelude::*;
10//!
11//! # fn main() -> Result<(), HyperoptError> {
12//! let study = StudyBuilder::new("quadratic")
13//!     .direction(Direction::Minimize)
14//!     .sampler(TpeSampler::seeded(42))
15//!     .build()?;
16//!
17//! study.optimize(|trial| {
18//!     let x = trial.suggest_float("x", -10.0, 10.0);
19//!     let y = trial.suggest_float("y", -10.0, 10.0);
20//!     Ok((x - 2.0).powi(2) + (y + 3.0).powi(2))
21//! }, 200)?;
22//!
23//! println!("best = {:?}", study.best_trial()?);
24//! # Ok(()) }
25//! ```
26
27pub use hyperopt_core::{
28    Direction, Distribution, HyperoptError, ObjectiveError, ObjectiveResult, ParamRecord, Pruner,
29    Sampler, Storage, StorageError, Study, StudyMetadata, StudyState, Trial, TrialContext,
30    TrialState, Value,
31};
32pub use hyperopt_pruners::{MedianPruner, NopPruner, SuccessiveHalvingPruner};
33pub use hyperopt_samplers::{BoundHandling, CmaEsSampler, GridSampler, RandomSampler, TpeSampler};
34pub use hyperopt_storage::InMemoryStorage;
35#[cfg(feature = "sqlite")]
36pub use hyperopt_storage::SqliteStorage;
37
38/// Fluent builder for a [`Study`], with sensible defaults: a
39/// [`RandomSampler`], a [`NopPruner`], an [`InMemoryStorage`], and
40/// [`Direction::Minimize`]. Override any of them before calling
41/// [`StudyBuilder::build`].
42pub struct StudyBuilder {
43    name: String,
44    direction: Direction,
45    sampler: Option<Box<dyn Sampler>>,
46    pruner: Option<Box<dyn Pruner>>,
47    storage: Option<Box<dyn Storage>>,
48}
49
50impl StudyBuilder {
51    /// Start building a study with the given name.
52    pub fn new(name: impl Into<String>) -> Self {
53        StudyBuilder {
54            name: name.into(),
55            direction: Direction::Minimize,
56            sampler: None,
57            pruner: None,
58            storage: None,
59        }
60    }
61
62    /// Set the optimization direction (default [`Direction::Minimize`]).
63    pub fn direction(mut self, direction: Direction) -> Self {
64        self.direction = direction;
65        self
66    }
67
68    /// Set the search algorithm (default [`RandomSampler`]).
69    pub fn sampler(mut self, sampler: impl Sampler + 'static) -> Self {
70        self.sampler = Some(Box::new(sampler));
71        self
72    }
73
74    /// Set the early-stopping policy (default [`NopPruner`]).
75    pub fn pruner(mut self, pruner: impl Pruner + 'static) -> Self {
76        self.pruner = Some(Box::new(pruner));
77        self
78    }
79
80    /// Set the storage backend (default [`InMemoryStorage`]).
81    pub fn storage(mut self, storage: impl Storage + 'static) -> Self {
82        self.storage = Some(Box::new(storage));
83        self
84    }
85
86    /// Assemble the [`Study`], applying defaults for anything not set.
87    pub fn build(self) -> Result<Study, HyperoptError> {
88        let sampler = self
89            .sampler
90            .unwrap_or_else(|| Box::new(RandomSampler::new()));
91        let pruner = self.pruner.unwrap_or_else(|| Box::new(NopPruner::new()));
92        let storage = self
93            .storage
94            .unwrap_or_else(|| Box::new(InMemoryStorage::new()));
95        Study::new(self.name, self.direction, sampler, pruner, storage)
96    }
97}
98
99/// Common imports for using the framework: the builder, the study/trial types,
100/// direction, error/objective types, and all samplers and pruners.
101pub mod prelude {
102    pub use crate::StudyBuilder;
103    pub use hyperopt_core::{
104        Direction, Distribution, HyperoptError, ObjectiveError, ObjectiveResult, Pruner, Sampler,
105        Storage, Study, Trial, TrialContext, TrialState, Value,
106    };
107    pub use hyperopt_pruners::{MedianPruner, NopPruner, SuccessiveHalvingPruner};
108    pub use hyperopt_samplers::{
109        BoundHandling, CmaEsSampler, GridSampler, RandomSampler, TpeSampler,
110    };
111    pub use hyperopt_storage::InMemoryStorage;
112    #[cfg(feature = "sqlite")]
113    pub use hyperopt_storage::SqliteStorage;
114}