Skip to main content

hyperopt_core/
suggest.rs

1use crate::TrialContext;
2
3/// The portable objective interface: exactly the operations a user objective
4/// performs on a trial (suggest parameters, report intermediate values, ask
5/// whether to prune).
6///
7/// [`TrialContext`] implements it for local execution, and the distributed
8/// worker's remote trial implements it too, so **the same objective closure can
9/// run unchanged locally or against a coordinator** — just write it against
10/// `&mut impl Suggest` instead of `&mut TrialContext`:
11///
12/// ```
13/// use hyperopt_core::Suggest;
14///
15/// fn objective(trial: &mut impl Suggest) -> f64 {
16///     let x = trial.suggest_float("x", -10.0, 10.0);
17///     let y = trial.suggest_int("y", 0, 5) as f64;
18///     (x - 2.0).powi(2) + y
19/// }
20/// ```
21pub trait Suggest {
22    /// Suggest a continuous value uniformly over `[low, high]`.
23    fn suggest_float(&mut self, name: &str, low: f64, high: f64) -> f64;
24    /// Suggest a continuous value log-uniformly over `[low, high]`.
25    fn suggest_loguniform(&mut self, name: &str, low: f64, high: f64) -> f64;
26    /// Suggest an integer uniformly over the inclusive range `[low, high]`.
27    fn suggest_int(&mut self, name: &str, low: i64, high: i64) -> i64;
28    /// Suggest one of `choices`, returning the chosen label.
29    fn suggest_categorical(&mut self, name: &str, choices: &[&str]) -> String;
30    /// Report an intermediate objective value at `step`, for pruners.
31    fn report(&mut self, step: usize, value: f64);
32    /// Ask whether this trial should stop early given what it has reported.
33    ///
34    /// Takes `&mut self` (unlike [`TrialContext::should_prune`], which only
35    /// reads) so a *remote* implementation can perform the round-trip to its
36    /// coordinator through the same connection; local implementations simply
37    /// ignore the mutability.
38    fn should_prune(&mut self) -> bool;
39}
40
41impl Suggest for TrialContext<'_> {
42    fn suggest_float(&mut self, name: &str, low: f64, high: f64) -> f64 {
43        TrialContext::suggest_float(self, name, low, high)
44    }
45    fn suggest_loguniform(&mut self, name: &str, low: f64, high: f64) -> f64 {
46        TrialContext::suggest_loguniform(self, name, low, high)
47    }
48    fn suggest_int(&mut self, name: &str, low: i64, high: i64) -> i64 {
49        TrialContext::suggest_int(self, name, low, high)
50    }
51    fn suggest_categorical(&mut self, name: &str, choices: &[&str]) -> String {
52        TrialContext::suggest_categorical(self, name, choices)
53    }
54    fn report(&mut self, step: usize, value: f64) {
55        TrialContext::report(self, step, value)
56    }
57    fn should_prune(&mut self) -> bool {
58        TrialContext::should_prune(self)
59    }
60}