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
use {Space, BoundedSpace, FiniteSpace, Surjection, Span};
use rand::{ThreadRng, Rng};
use std::ops::Range;

/// A binary dimension.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
pub struct Binary;

impl Binary {
    pub fn new() -> Binary {
        Binary
    }
}

impl Space for Binary {
    type Value = bool;

    fn dim(&self) -> usize { 1 }

    fn span(&self) -> Span { Span::Finite(2) }

    fn sample(&self, rng: &mut ThreadRng) -> bool { rng.gen() }
}

impl BoundedSpace for Binary {
    type BoundValue = bool;

    fn lb(&self) -> &bool { &false }

    fn ub(&self) -> &bool { &true }

    fn contains(&self, _: Self::Value) -> bool { true }
}

impl FiniteSpace for Binary {
    fn range(&self) -> Range<Self::Value> { false..true }
}

impl Surjection<bool, bool> for Binary {
    fn map(&self, val: bool) -> bool { val }
}

impl Surjection<f64, bool> for Binary {
    fn map(&self, val: f64) -> bool { val > 0.0 }
}


#[cfg(test)]
mod tests {
    extern crate serde_test;

    use rand::thread_rng;
    use self::serde_test::{assert_tokens, Token};
    use super::*;

    #[test]
    fn test_span() {
        let d = Binary::new();

        assert_eq!(d.span(), Span::Finite(2));
    }

    #[test]
    fn test_sampling() {
        let d = Binary::new();
        let mut rng = thread_rng();

        for _ in 0..100 {
            let s = d.sample(&mut rng);

            assert!(s == false || s == true);
            assert!(d.contains(s));
        }
    }

    #[test]
    fn test_bounds() {
        let d = Binary::new();

        assert_eq!(d.lb(), &false);
        assert_eq!(d.ub(), &true);

        assert!(d.contains(false));
        assert!(d.contains(true));
    }

    #[test]
    fn test_range() {
        let d = Binary::new();
        let r = d.range();

        assert!(r == (false..true) || r == (true..false));
    }

    #[test]
    fn test_surjection() {
        let d = Binary::new();

        assert_eq!(d.map(true), true);
        assert_eq!(d.map(false), false);

        assert_eq!(d.map(1.0), true);
        assert_eq!(d.map(0.0), false);
    }

    #[test]
    fn test_serialisation() {
        let d = Binary::new();

        assert_tokens(&d, &[Token::UnitStruct { name: "Binary" }]);
    }
}