~ruther/ctu-fee-eoa

ref: dfddcfde9cade6fd94ace5bca2f846f48c230e3c ctu-fee-eoa/env/src/fitness/sphere.rs -rw-r--r-- 815 bytes
dfddcfde — Rutherther chore: split types and functions to separate module files a day ago
                                                                                
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
use std::convert::Infallible;
use crate::test_infra::load_test_file;

use super::FitnessFunction;

pub struct Sphere {
    offset: Vec<f64>
}

impl Sphere {
    pub fn new(offset: Vec<f64>) -> Self {
        Sphere {
            offset
        }
    }
}

impl FitnessFunction for Sphere {
    type In = Vec<f64>;
    type Out = f64;
    type Err = Infallible;

    fn fit(self: &Self, chromosome: &Vec<f64>) -> Result<f64, Infallible> {
        Ok(chromosome
           .iter()
           .zip(&self.offset)
           .map(|(x, o)| (x - o).powi(2))
           .sum())
    }
}

#[test]
fn test_sphere() {
    let data = load_test_file::<f64, f64>("tests/sphere.txt");

    for test in data {
        assert_eq!(
            Sphere::new(vec![1.0; 10]).fit(&test.inp).unwrap(),
            test.out
        )
    }
}