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
//! Domain of parameter and objective values.
use crate::{Error, ErrorKind, Result};
use ordered_float::OrderedFloat;
use serde::{Deserialize, Serialize};
use std;
use std::hash::{Hash, Hasher};

/// Domain.
///
/// A `Domain` instance consists of a vector of `Variable`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Domain(Vec<Variable>);
impl Domain {
    /// Makes a new `Domain` instance.
    pub fn new(variables: Vec<VariableBuilder>) -> Result<Self> {
        track_assert!(!variables.is_empty(), ErrorKind::InvalidInput);

        let mut vars = Vec::<Variable>::new();
        for v in variables.into_iter() {
            let v = track!(v.finish())?;

            track_assert!(
                vars.iter().all(|var| v.name != var.name),
                ErrorKind::InvalidInput,
                "Duplicate name: {:?}",
                v.name
            );

            vars.push(v);
        }
        Ok(Self(vars))
    }

    /// Returns a reference to the variables in this domain.
    pub fn variables(&self) -> &[Variable] {
        &self.0
    }
}

/// Returns a `VariableBuilder` which was initialized with the given variable name.
///
/// This is equivalent to `VariableBuilder::new(name)`.
pub fn var(name: &str) -> VariableBuilder {
    VariableBuilder::new(name)
}

/// `Variable` builder.
#[derive(Debug)]
pub struct VariableBuilder {
    name: String,
    range: Range,
    distribution: Distribution,
    constraint: Option<Constraint>,
}
impl VariableBuilder {
    /// Makes a new `VariableBuilder` with the given variable name.
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_owned(),
            range: Range::Continuous {
                low: std::f64::NEG_INFINITY,
                high: std::f64::INFINITY,
            },
            distribution: Distribution::Uniform,
            constraint: None,
        }
    }

    /// Sets the distribution of this variable to `Distribution::Uniform`.
    ///
    /// Note that `Distribution::Uniform` is the default distribution.
    pub fn uniform(mut self) -> Self {
        self.distribution = Distribution::Uniform;
        self
    }

    /// Sets the distribution of this variable to `Distribution::LogUniform`.
    pub fn log_uniform(mut self) -> Self {
        self.distribution = Distribution::LogUniform;
        self
    }

    /// Sets the range of this variable to the given continuous numerical range.
    pub fn continuous(mut self, low: f64, high: f64) -> Self {
        self.range = Range::Continuous { low, high };
        self
    }

    /// Sets the range of this variable to the given discrete numerical range.
    pub fn discrete(mut self, low: i64, high: i64) -> Self {
        self.range = Range::Discrete { low, high };
        self
    }

    /// Sets the range of this variable to the given categorical range.
    pub fn categorical<I, T>(mut self, choices: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: AsRef<str>,
    {
        self.range = Range::Categorical {
            choices: choices.into_iter().map(|c| c.as_ref().to_owned()).collect(),
        };
        self
    }

    /// Sets the range of this variable to boolean.
    ///
    /// This is equivalent to `self.categorical(&["false", "true"])`.
    pub fn boolean(self) -> Self {
        self.categorical(&["false", "true"])
    }

    /// Sets the evaluation constraint to this variable.
    pub fn constraint(mut self, constraint: Constraint) -> Self {
        self.constraint = Some(constraint);
        self
    }

    /// Builds a `Variable` instance with the given settings.
    pub fn finish(self) -> Result<Variable> {
        match &self.range {
            Range::Continuous { low, high } => {
                track_assert!(low < high, ErrorKind::InvalidInput; self)
            }
            Range::Discrete { low, high } => {
                track_assert!(low < high, ErrorKind::InvalidInput; self)
            }
            Range::Categorical { choices } => {
                track_assert!(!choices.is_empty(), ErrorKind::InvalidInput; self)
            }
        }

        if self.distribution == Distribution::LogUniform {
            match self.range {
                Range::Continuous { low, .. } if 0.0 < low => {}
                Range::Discrete { low, .. } if 0 < low => {}
                _ => track_panic!(ErrorKind::InvalidInput; self),
            }
        }

        Ok(Variable {
            name: self.name,
            range: self.range,
            distribution: self.distribution,
            constraint: self.constraint,
        })
    }
}

/// A variable in a domain.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Variable {
    name: String,
    range: Range,
    distribution: Distribution,
    #[serde(default)]
    constraint: Option<Constraint>,
}
impl Variable {
    /// Returns the name of this variable.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the value range of this variable.
    pub fn range(&self) -> &Range {
        &self.range
    }

    /// Returns the prior distribution of the value of this variable.
    pub fn distribution(&self) -> Distribution {
        self.distribution
    }

    /// Returns the constraint required to evaluate this variable.
    pub fn constraint(&self) -> Option<&Constraint> {
        self.constraint.as_ref()
    }
}

/// Distribution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[allow(missing_docs)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Distribution {
    Uniform,
    LogUniform,
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_not_finite(x: &f64) -> bool {
    !x.is_finite()
}

fn neg_infinity() -> f64 {
    std::f64::NEG_INFINITY
}

fn infinity() -> f64 {
    std::f64::INFINITY
}

/// Variable range.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(missing_docs)]
#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Range {
    /// Continuous numerical range: `[low..high)`.
    Continuous {
        #[serde(skip_serializing_if = "is_not_finite", default = "neg_infinity")]
        low: f64,

        #[serde(skip_serializing_if = "is_not_finite", default = "infinity")]
        high: f64,
    },

    /// Discrete numerical range: `[low..high)`.
    Discrete { low: i64, high: i64 },

    /// Categorical range.
    Categorical { choices: Vec<String> },
}
impl Range {
    /// Returns the inclusive lower bound of this range.
    pub fn low(&self) -> f64 {
        match self {
            Self::Continuous { low, .. } => *low,
            Self::Discrete { low, .. } => *low as f64,
            Self::Categorical { .. } => 0.0,
        }
    }

    /// Returns the exclusive upper bound of this range.
    pub fn high(&self) -> f64 {
        match self {
            Self::Continuous { high, .. } => *high,
            Self::Discrete { high, .. } => *high as f64,
            Self::Categorical { choices } => choices.len() as f64,
        }
    }

    /// Returns `true` if the given value is contained in this range.
    pub fn contains(&self, v: f64) -> bool {
        match self {
            Self::Continuous { low, high } => *low <= v && v < *high,
            Self::Discrete { low, high } => *low as f64 <= v && v < *high as f64,
            Self::Categorical { choices } => 0.0 <= v && v < choices.len() as f64,
        }
    }
}
impl PartialEq for Range {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Continuous { low: l0, high: h0 }, Self::Continuous { low: l1, high: h1 }) => {
                OrderedFloat(*l0) == OrderedFloat(*l1) && OrderedFloat(*h0) == OrderedFloat(*h1)
            }
            (Self::Discrete { low: l0, high: h0 }, Self::Discrete { low: l1, high: h1 }) => {
                l0 == l1 && h0 == h1
            }
            (Self::Categorical { choices: c0 }, Self::Categorical { choices: c1 }) => c0 == c1,
            _ => false,
        }
    }
}
impl Eq for Range {}
impl Hash for Range {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Self::Continuous { low, high } => {
                OrderedFloat(*low).hash(state);
                OrderedFloat(*high).hash(state);
            }
            Self::Discrete { low, high } => {
                low.hash(state);
                high.hash(state);
            }
            Self::Categorical { choices } => {
                choices.hash(state);
            }
        }
    }
}

/// Evaluation constraint.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Constraint {
    lua_script: String,
}
impl Constraint {
    /// Makes a new `Constraint` instance.
    ///
    /// `lua_script` is the Lua script code that represents the constraint.
    /// In this script, you can access the variables that are located before
    /// the constrainted variable as global variables.
    /// This script must return a boolean value.
    pub fn new(lua_script: &str) -> Self {
        Self {
            lua_script: lua_script.to_owned(),
        }
    }

    /// Returns `Ok(true)` if this constraint is satisfied, otherwise `Ok(false)` or an error.
    pub fn is_satisfied(&self, vars: &[Variable], vals: &[f64]) -> Result<bool> {
        use rlua::Lua;

        let lua = Lua::new();
        lua.context(|lua_ctx| {
            let globals = lua_ctx.globals();

            for (var, &val) in vars.iter().zip(vals.iter()) {
                if !val.is_finite() {
                    continue;
                }

                if let Range::Categorical { choices } = &var.range {
                    let val = choices[val as usize].as_str();
                    track!(globals.set(var.name.as_str(), val).map_err(Error::from))?;
                } else {
                    track!(globals.set(var.name.as_str(), val).map_err(Error::from))?;
                }
            }

            lua_ctx.load(&self.lua_script).eval().map_err(Error::from)
        })
    }
}

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

    #[test]
    fn constraint_test() -> trackable::result::TopLevelResult {
        let vars = vec![
            var("a").continuous(-10.0, 10.0).finish()?,
            var("b").discrete(0, 5).finish()?,
            var("c").categorical(&["foo", "bar", "baz"]).finish()?,
        ];

        let constraint = Constraint::new("(a + b) < 2");
        assert!(track!(constraint.is_satisfied(&vars, &[0.2, 1.0]))?);
        assert!(!track!(constraint.is_satisfied(&vars, &[1.1, 1.0]))?);

        let constraint = Constraint::new("c == \"bar\"");
        assert!(track!(constraint.is_satisfied(&vars, &[0.2, 1.0, 1.0]))?);
        assert!(!track!(constraint.is_satisfied(&vars, &[0.2, 1.0, 0.0]))?);
        assert!(!track!(constraint.is_satisfied(&vars, &[0.2, 1.0, 2.0]))?);

        Ok(())
    }
}