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
//! The interface of the problem for black-box optimization.
use crate::domain::{Distribution, Domain, Range, VariableBuilder};
use crate::registry::FactoryRegistry;
use crate::rng::ArcRng;
use crate::solver::{Capabilities, Capability};
use crate::trial::{Params, Values};
use crate::{ErrorKind, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
use structopt::StructOpt;

/// `ProblemSpec` builder.
#[derive(Debug)]
pub struct ProblemSpecBuilder {
    name: String,
    attrs: BTreeMap<String, String>,
    params: Vec<VariableBuilder>,
    values: Vec<VariableBuilder>,
    steps: Vec<u64>,
}
impl ProblemSpecBuilder {
    /// Makes a new `ProblemSpecBuilder` instance.
    pub fn new(problem_name: &str) -> Self {
        Self {
            name: problem_name.to_owned(),
            attrs: BTreeMap::new(),
            params: Vec::new(),
            values: Vec::new(),
            steps: vec![1],
        }
    }

    /// Sets an attribute of this problem.
    pub fn attr(mut self, key: &str, value: &str) -> Self {
        self.attrs.insert(key.to_owned(), value.to_owned());
        self
    }

    /// Adds a variable to the parameter domain of this problem.
    pub fn param(mut self, var: VariableBuilder) -> Self {
        self.params.push(var);
        self
    }

    /// Sets variables of the parameter domain of this problem.
    pub fn params(mut self, vars: Vec<VariableBuilder>) -> Self {
        self.params = vars;
        self
    }

    /// Adds a variable to the value domain of this problem.
    pub fn value(mut self, var: VariableBuilder) -> Self {
        self.values.push(var);
        self
    }

    /// Sets the evaluable steps of this problem.
    pub fn steps<I>(mut self, steps: I) -> Self
    where
        I: IntoIterator<Item = u64>,
    {
        self.steps = steps.into_iter().collect();
        self
    }

    /// Builds a `ProblemSpec` with the given settings.
    pub fn finish(self) -> Result<ProblemSpec> {
        let params_domain = track!(Domain::new(self.params))?;
        let values_domain = track!(Domain::new(self.values))?;
        let steps = track!(EvaluableSteps::new(self.steps))?;

        Ok(ProblemSpec {
            name: self.name,
            attrs: self.attrs,
            params_domain,
            values_domain,
            steps,
        })
    }
}

/// Problem specification.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ProblemSpec {
    /// Problem name.
    pub name: String,

    /// Problem attributes.
    #[serde(default)]
    pub attrs: BTreeMap<String, String>,

    /// Domain of the parameters.
    pub params_domain: Domain,

    /// Domain of the objective values.
    pub values_domain: Domain,

    /// List of steps.
    ///
    /// This problem can evaluate a given parameter set at a step in this list.
    pub steps: EvaluableSteps,
}
impl ProblemSpec {
    /// Returns the capabilities required to solver to handle this problem.
    pub fn requirements(&self) -> Capabilities {
        let mut c = Capabilities::empty();

        if self.values_domain.variables().len() > 1 {
            c.add_capability(Capability::MultiObjective);
        }

        for v in self.params_domain.variables() {
            if v.constraint().is_some() {
                c.add_capability(Capability::Conditional);
            }

            match (v.range(), v.distribution()) {
                (Range::Continuous { .. }, Distribution::Uniform) => {
                    c.add_capability(Capability::UniformContinuous);
                }
                (Range::Continuous { .. }, Distribution::LogUniform) => {
                    c.add_capability(Capability::LogUniformContinuous);
                }
                (Range::Discrete { .. }, Distribution::Uniform) => {
                    c.add_capability(Capability::UniformDiscrete);
                }
                (Range::Discrete { .. }, Distribution::LogUniform) => {
                    c.add_capability(Capability::LogUniformDiscrete);
                }
                (Range::Categorical { .. }, _) => {
                    c.add_capability(Capability::Categorical);
                }
            }
        }

        c
    }
}

/// Recipe of a problem.
pub trait ProblemRecipe: Clone + Send + StructOpt + Serialize + for<'a> Deserialize<'a> {
    /// The type of the factory creating problem instances from this recipe.
    type Factory: ProblemFactory;

    /// Creates a problem factory.
    fn create_factory(&self, registry: &FactoryRegistry) -> Result<Self::Factory>;
}

/// This trait allows creating instances of a problem.
pub trait ProblemFactory: Send {
    /// The type of the problem instance created by this factory.
    type Problem: Problem;

    /// Returns the specification of the problem created by this factory.
    fn specification(&self) -> Result<ProblemSpec>;

    /// Creates a problem instance.
    fn create_problem(&self, rng: ArcRng) -> Result<Self::Problem>;
}

enum ProblemFactoryCall {
    Specification,
    CreateProblem(ArcRng),
}

enum ProblemFactoryReturn {
    Specification(ProblemSpec),
    CreateProblem(BoxProblem),
}

/// Boxed problem factory.
pub struct BoxProblemFactory(
    Box<dyn Fn(ProblemFactoryCall) -> Result<ProblemFactoryReturn> + Send>,
);
impl BoxProblemFactory {
    /// Makes a new `BoxProblemFactory` instance.
    pub fn new<T>(problem: T) -> Self
    where
        T: 'static + ProblemFactory,
    {
        Self(Box::new(move |call| match call {
            ProblemFactoryCall::Specification => problem
                .specification()
                .map(ProblemFactoryReturn::Specification),
            ProblemFactoryCall::CreateProblem(rng) => problem
                .create_problem(rng)
                .map(BoxProblem::new)
                .map(ProblemFactoryReturn::CreateProblem),
        }))
    }
}
impl ProblemFactory for BoxProblemFactory {
    type Problem = BoxProblem;

    fn specification(&self) -> Result<ProblemSpec> {
        let v = track!((self.0)(ProblemFactoryCall::Specification))?;
        if let ProblemFactoryReturn::Specification(v) = v {
            Ok(v)
        } else {
            unreachable!()
        }
    }

    fn create_problem(&self, rng: ArcRng) -> Result<Self::Problem> {
        let v = track!((self.0)(ProblemFactoryCall::CreateProblem(rng)))?;
        if let ProblemFactoryReturn::CreateProblem(v) = v {
            Ok(v)
        } else {
            unreachable!()
        }
    }
}
impl fmt::Debug for BoxProblemFactory {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "BoxProblemFactory {{ .. }}")
    }
}

/// Problem.
pub trait Problem: Send {
    /// The type of the evaluator of this problem.
    type Evaluator: Evaluator;

    /// Creates an evaluator that evaluates the given parameters.
    fn create_evaluator(&self, params: Params) -> Result<Self::Evaluator>;
}

/// Boxed problem.
pub struct BoxProblem(Box<dyn Fn(Params) -> Result<BoxEvaluator> + Send>);
impl BoxProblem {
    /// Makes a new `BoxProblem` instance.
    pub fn new<T>(problem: T) -> Self
    where
        T: 'static + Problem,
    {
        Self(Box::new(move |params| {
            problem.create_evaluator(params).map(BoxEvaluator::new)
        }))
    }
}
impl Problem for BoxProblem {
    type Evaluator = BoxEvaluator;

    fn create_evaluator(&self, params: Params) -> Result<Self::Evaluator> {
        track!((self.0)(params))
    }
}
impl fmt::Debug for BoxProblem {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "BoxProblem {{ .. }}")
    }
}

/// This trait allows evaluating a parameter set of a problem.
pub trait Evaluator: Send {
    /// Procedes the evaluation of the parameter set given to `Problem::create_evaluator` method until reaches to `next_step..
    ///
    /// The first element of the result tuple means the current step of the evaluation.
    /// Although it's desirable that the current step matches to `next_step`,
    /// it's allowed to exceed `next_step`.
    fn evaluate(&mut self, next_step: u64) -> Result<(u64, Values)>;
}
impl<T: Evaluator + ?Sized> Evaluator for Box<T> {
    fn evaluate(&mut self, next_step: u64) -> Result<(u64, Values)> {
        (**self).evaluate(next_step)
    }
}

/// Boxed evaluator.
pub struct BoxEvaluator(Box<dyn Evaluator>);
impl BoxEvaluator {
    /// Makes a new `BoxEvaluator` instance.
    pub fn new<T>(evaluator: T) -> Self
    where
        T: 'static + Evaluator,
    {
        Self(Box::new(evaluator))
    }
}
impl Evaluator for BoxEvaluator {
    fn evaluate(&mut self, next_step: u64) -> Result<(u64, Values)> {
        self.0.evaluate(next_step)
    }
}
impl fmt::Debug for BoxEvaluator {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "BoxEvaluator {{ .. }}")
    }
}

/// Evaluable steps of a problem.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EvaluableSteps(EvaluableStepsInner);
impl EvaluableSteps {
    /// Makes a new `EvaluableSteps` instance.
    pub fn new(steps: Vec<u64>) -> Result<Self> {
        track!(EvaluableStepsInner::new(steps)).map(Self)
    }

    /// Returns the last evaluation step.
    pub fn last(&self) -> u64 {
        self.0.last()
    }

    /// Returns an iterator that iterates over all the steps.
    pub fn iter<'a>(&'a self) -> impl 'a + Iterator<Item = u64> {
        self.0.iter()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
enum EvaluableStepsInner {
    Max(u64),
    Steps(Vec<u64>),
}
impl EvaluableStepsInner {
    fn new(steps: Vec<u64>) -> Result<Self> {
        track_assert!(!steps.is_empty(), ErrorKind::InvalidInput);
        track_assert!(steps[0] > 0, ErrorKind::InvalidInput);

        for (a, b) in steps.iter().zip(steps.iter().skip(1)) {
            track_assert!(a < b, ErrorKind::InvalidInput);
        }

        let last = steps[steps.len() - 1];
        if last == steps.len() as u64 {
            Ok(Self::Max(last))
        } else {
            Ok(Self::Steps(steps))
        }
    }

    fn last(&self) -> u64 {
        match self {
            Self::Max(n) => *n,
            Self::Steps(ns) => ns[ns.len() - 1],
        }
    }

    fn iter<'a>(&'a self) -> impl 'a + Iterator<Item = u64> {
        match self {
            Self::Max(n) => itertools::Either::Left(1..=*n),
            Self::Steps(ns) => itertools::Either::Right(ns.iter().copied()),
        }
    }
}