moonlander_gp/genetic/
fitness.rs

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
use super::super::num::Number;
use std::cmp::Ordering;
use std::ops::Add;

/// Trait that models fitness for an individual
///
/// Write a custom implementation that retains some additional state about the
/// evaluation if you want to.
///
/// Provides some helper classes to record scores.
pub trait Fitness: Send {
    fn score_card(&self) -> &ScoreCard;
}

/// Simple fitness result that only consists of a ScoreCard.
///
/// In case you don't need to retain any additional state, you can use this struct.
pub struct SimpleFitness {
    score_card: ScoreCard
}

impl SimpleFitness {
    pub fn new(scores: Scores) -> SimpleFitness {
        SimpleFitness { score_card: ScoreCard::new(scores) }
    }
}

impl Fitness for SimpleFitness {
    fn score_card(&self) -> &ScoreCard { &self.score_card }
}

pub type Score = (&'static str, Number);

/// List of tuples of a score label and a score value.
pub type Scores = Vec<Score>;

/// Immutable tagged list of scores.
///
/// The final score of an individual can be composed of many labeled subscores
/// (for manual evaluation later on). Pass the scoresas a list of tuples with a
/// static string and a score. The final score is the total of all subscores.
///
/// Example:
///
/// ```
/// # use moonlander_gp::ScoreCard;
/// let score = ScoreCard::new(vec![
///     ("food", 10.0),
///     ("thirst", -5.0)
/// ]);
/// ```
#[derive(Clone,RustcEncodable)]
pub struct ScoreCard(Scores, Number);

impl ScoreCard {
    pub fn new(scores: Scores) -> ScoreCard {
        let sum = scores.iter().map(|&(_, x)| x).fold(0.0, Add::add);
        ScoreCard(scores, sum)
    }

    pub fn add(self, scores: Scores) -> ScoreCard {
        let mut xs = self.0;
        xs.extend(scores);
        ScoreCard::new(xs)
    }

    pub fn scores(&self) -> &Scores {
        &self.0
    }

    pub fn total_score(&self) -> Number {
        self.1
    }

    pub fn is_empty(&self) -> bool {
        self.0.len() == 0
    }
}

impl PartialEq for ScoreCard {
    fn eq(&self, other: &Self) -> bool {
        return self.1.eq(&other.1);
    }
}

impl Eq for ScoreCard {
}

impl PartialOrd for ScoreCard {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        return self.1.partial_cmp(&other.1);
    }
}

impl Ord for ScoreCard {
    fn cmp(&self, other: &Self) -> Ordering {
        if Number::is_nan(self.1) && Number::is_nan(other.1) { return Ordering::Equal; }
        if Number::is_nan(self.1) { return Ordering::Less; }
        if Number::is_nan(other.1) { return Ordering::Greater; }

        return self.1.partial_cmp(&other.1).unwrap();
    }
}

fn find_rec<'a>(scores: &'a mut Scores, name: &'static str) -> Option<&'a mut Score> {
    for x in scores.iter_mut() {
        if x.0 == name {
            return Some(x);
        }
    }
    None
}

impl Add<ScoreCard> for ScoreCard {
    type Output = ScoreCard;

    fn add(mut self, rhs: ScoreCard) -> Self::Output {
        self += &rhs;
        self
    }
}

impl <'a> ::std::ops::AddAssign<&'a ScoreCard> for ScoreCard {
    fn add_assign(&mut self, rhs: &'a ScoreCard) {
        for &(name, value) in rhs.0.iter() {
            let mut increased = false;
            match find_rec(&mut self.0, name) {
                Some(rec) => { rec.1 += value; increased = true; },
                None => { /* Moved outside match because borrow checker can't end scope early */ }
            }
            if !increased {
                self.0.push((name, value));
            }
            self.1 += value;
        }
    }
}

impl ::std::ops::Div<Number> for ScoreCard {
    type Output = ScoreCard;

    fn div(self, rhs: Number) -> Self::Output {
        ScoreCard(
            self.0.into_iter().map(|(n, v)| (n, v / rhs)).collect(),
            self.1 / rhs
        )
    }
}

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

    #[test]
    fn add_scorecards_matching_keys() {
        let one = ScoreCard::new(vec![("a", 1.0)]);
        let two = ScoreCard::new(vec![("a", 1.0)]);

        let added = one + two;

        assert_eq!(vec![("a", 2.0)], added.0);
        assert_eq!(2.0, added.total_score());
    }

    #[test]
    fn add_scorecards_different_keys() {
        let one = ScoreCard::new(vec![("a", 1.0)]);
        let two = ScoreCard::new(vec![("b", 1.0)]);

        let added = one + two;

        assert_eq!(vec![("a", 1.0),("b", 1.0)], added.0);
        assert_eq!(2.0, added.total_score());
    }
}