~ruther/ctu-fee-eoa

ref: 738df68495b38337d5bb4e1d9f5ffb9e9ecf4303 ctu-fee-eoa/codes/eoa_lib/src/fitness/mod.rs -rw-r--r-- 1.6 KiB
738df684 — Rutherther fix: tournament replacement strategy could be using wrong indices 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
63
64
use std::{convert::Infallible, error::Error, marker::PhantomData};

use nalgebra::{allocator::Allocator, DefaultAllocator, Dim, OVector};

use crate::binary_string::{BinaryString, BinaryStringConversionError};

pub mod labs;
pub mod one_max;
pub mod rosenbrock;
pub mod sphere;
pub mod real;

pub trait FitnessFunction {
    type In;
    type Out;
    type Err: Error + 'static;

    fn fit(self: &Self, inp: &Self::In) -> Result<Self::Out, Self::Err>;
}

pub struct BinaryFitnessWrapper<D, DString, TFitness>
where
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    min: OVector<f64, D>,
    max: OVector<f64, D>,
    fitting_function: TFitness,
    _phantom: PhantomData<DString>
}

impl<D, DString, TFitness> BinaryFitnessWrapper<D, DString, TFitness>
where
    DString: Dim,
    DefaultAllocator: Allocator<DString>,
    D: Dim,
    DefaultAllocator: Allocator<D>
{
    pub fn new(fitting_function: TFitness, min: OVector<f64, D>, max: OVector<f64, D>) -> Self {
        Self {
            fitting_function,
            min,
            max,
            _phantom: PhantomData
        }
    }
}

impl<D, DString, TFitness> FitnessFunction for BinaryFitnessWrapper<D, DString, TFitness>
where
    DString: Dim,
    DefaultAllocator: Allocator<DString>,
    D: Dim,
    DefaultAllocator: Allocator<D>,
    TFitness: FitnessFunction<In = OVector<f64, D>, Out = f64, Err = Infallible>
{
    type In = BinaryString<DString>;
    type Out = f64;
    type Err = BinaryStringConversionError;

    fn fit(self: &Self, inp: &BinaryString<DString>) -> Result<f64, BinaryStringConversionError> {
        Ok(self.fitting_function.fit(&inp.to_real(&self.min, &self.max)?).unwrap())
    }
}