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
use super::*;

use crate::algorithms::nsga2::Objective;
use crate::utils::compare_floats;

/// An objective function which controls total amount of routes.
pub struct TotalRoutes {
    is_minimization: bool,
}

impl Default for TotalRoutes {
    fn default() -> Self {
        Self { is_minimization: true }
    }
}

impl TotalRoutes {
    /// Creates an instance of `TotalRoutes` with fleet minimization as a target.
    pub fn new_minimized() -> Self {
        Self { is_minimization: true }
    }

    /// Creates an instance of `TotalRoutes` with fleet maximization as a target.
    pub fn new_maximized() -> Self {
        Self { is_minimization: false }
    }
}

impl Objective for TotalRoutes {
    type Solution = InsertionContext;

    fn total_order(&self, a: &Self::Solution, b: &Self::Solution) -> Ordering {
        let fitness_a = a.solution.routes.len() as f64;
        let fitness_b = b.solution.routes.len() as f64;

        let (fitness_a, fitness_b) =
            if self.is_minimization { (fitness_a, fitness_b) } else { (-1. * fitness_a, -1. * fitness_b) };

        compare_floats(fitness_a, fitness_b)
    }

    fn distance(&self, a: &Self::Solution, b: &Self::Solution) -> f64 {
        a.solution.routes.len() as f64 - b.solution.routes.len() as f64
    }

    fn fitness(&self, solution: &Self::Solution) -> f64 {
        solution.solution.routes.len() as f64
    }
}