use std::convert::Infallible; use nalgebra::{allocator::Allocator, DefaultAllocator, Dim, OVector, SVector}; use super::FitnessFunction; pub struct Sphere where D: Dim, DefaultAllocator: Allocator { offset: OVector } impl Sphere where D: Dim, DefaultAllocator: Allocator { pub fn new(offset: OVector) -> Self { Sphere { offset } } } impl FitnessFunction for Sphere where D: Dim, DefaultAllocator: Allocator { type In = OVector; type Out = f64; type Err = Infallible; fn fit(self: &Self, chromosome: &OVector) -> Result { 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::("tests/sphere.txt"); for test in data { assert_eq!( Sphere::::new(OVector::<_, Dyn>::from_vec(vec![1.0; test.inp.len()])) .fit(&OVector::<_, Dyn>::from_vec(test.inp)).unwrap(), test.out ) } } }