~ruther/ctu-fee-eoa

ref: 8d13c2754c8d1738299b07c27193f6ecd2ddaf95 ctu-fee-eoa/codes/eoa_lib/src/fitness/sphere.rs -rw-r--r-- 1.3 KiB
8d13c275 — Rutherther chore: move env to codes/eoa_lib a month 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use std::convert::Infallible;
use nalgebra::{allocator::Allocator, DefaultAllocator, Dim, OVector};

use super::FitnessFunction;

pub struct Sphere<D>
where
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    offset: OVector<f64, D>
}

impl<D> Sphere<D>
where
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    pub fn new(offset: OVector<f64, D>) -> Self {
        Sphere {
            offset
        }
    }
}

impl<D> FitnessFunction for Sphere<D>
where
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    type In = OVector<f64, D>;
    type Out = f64;
    type Err = Infallible;

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

#[cfg(test)]
pub mod tests {
    use nalgebra::{Dyn, OVector};

    use crate::{fitness::{sphere::Sphere, FitnessFunction}, test_infra::load_test_file};

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

        for test in data {
            assert_eq!(
                Sphere::<Dyn>::new(OVector::<_, Dyn>::from_vec(vec![1.0; test.inp.len()]))
                    .fit(&OVector::<_, Dyn>::from_vec(test.inp)).unwrap(),
                test.out
            )
        }
    }
}