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
)
}
}