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
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
use crate::construction::heuristics::InsertionContext;
use crate::construction::Quota;
use crate::models::{Problem, Solution};
use crate::solver::evolution::EvolutionConfig;
use crate::solver::mutation::*;
use crate::solver::termination::*;
use crate::solver::Solver;
use crate::utils::{DefaultRandom, TimeQuota};
use std::ops::Deref;
use std::sync::Arc;

/// Provides configurable way to build solver.
pub struct Builder {
    pub max_generations: Option<usize>,
    pub max_time: Option<usize>,
    pub cost_variation: Option<(usize, f64)>,
    pub config: EvolutionConfig,
}

impl Builder {
    pub fn new(problem: Arc<Problem>) -> Self {
        Self {
            max_generations: None,
            max_time: None,
            cost_variation: None,
            config: EvolutionConfig {
                problem: problem.clone(),
                mutation: Box::new(RuinAndRecreateMutation::new_from_problem(problem)),
                termination: Box::new(MaxTime::new(300.)),
                quota: None,
                population_size: 4,
                offspring_size: 4,
                elite_size: 2,
                initial_size: 2,
                initial_methods: vec![
                    (Box::new(RecreateWithCheapest::default()), 10),
                    (Box::new(RecreateWithRegret::default()), 10),
                    (Box::new(RecreateWithBlinks::<i32>::default()), 5),
                ],
                initial_individuals: vec![],
                random: Arc::new(DefaultRandom::default()),
                logger: Arc::new(|msg| println!("{}", msg)),
            },
        }
    }
}

impl Builder {
    /// Sets max generations to be run.
    /// Default is 2000.
    pub fn with_max_generations(mut self, limit: Option<usize>) -> Self {
        self.max_generations = limit;
        self
    }

    /// Sets cost variation termination criteria.
    /// Default is None.
    pub fn with_cost_variation(mut self, variation: Option<(usize, f64)>) -> Self {
        self.cost_variation = variation;
        self
    }

    /// Sets max running time limit.
    /// Default is 300 seconds.
    pub fn with_max_time(mut self, limit: Option<usize>) -> Self {
        self.max_time = limit;
        self
    }

    /// Sets initial methods.
    pub fn with_initial_methods(mut self, initial_methods: Vec<(Box<dyn Recreate>, usize)>) -> Self {
        self.config.initial_methods = initial_methods;
        self
    }

    /// Sets initial solutions.
    /// Default is none.
    pub fn with_solutions(mut self, solutions: Vec<Arc<Solution>>) -> Self {
        self.config.logger.deref()(format!("provided {} initial solutions to start with", solutions.len()));
        self.config.initial_individuals = solutions
            .iter()
            .map(|solution| {
                InsertionContext::new_from_solution(
                    self.config.problem.clone(),
                    (solution.clone(), None),
                    Arc::new(DefaultRandom::default()),
                )
            })
            .collect();
        self
    }

    /// Sets population size.
    /// Default is 4.
    pub fn with_population_size(mut self, size: usize) -> Self {
        self.config.logger.deref()(format!("configured to use population size: {} ", size));
        self.config.population_size = size;
        self
    }

    /// Sets offspring size.
    /// Default is 4.
    pub fn with_offspring_size(mut self, size: usize) -> Self {
        self.config.logger.deref()(format!("configured to use offspring size: {} ", size));
        self.config.offspring_size = size;
        self
    }

    /// Sets elite size.
    /// Default is 2.
    pub fn with_elite_size(mut self, size: usize) -> Self {
        self.config.logger.deref()(format!("configured to use elite size: {} ", size));
        self.config.elite_size = size;
        self
    }

    /// Sets initial population size. Each initial individual is constructed separately which
    /// used to take more time than normal refinement process.
    /// Default is 2.
    pub fn with_initial_size(mut self, size: usize) -> Self {
        self.config.logger.deref()(format!("configured to use initial population size: {} ", size));
        self.config.initial_size = size;
        self
    }

    /// Sets mutation algorithm.
    /// Default is ruin and recreate.
    pub fn with_mutation(mut self, mutation: Box<dyn Mutation>) -> Self {
        self.config.mutation = mutation;
        self
    }

    /// Sets termination algorithm.
    /// Default is max time and max generations.
    pub fn with_termination(mut self, termination: Box<dyn Termination>) -> Self {
        self.config.termination = termination;
        self
    }

    /// Builds solver with parameters specified.
    pub fn build(self) -> Result<Solver, String> {
        let problem = self.config.problem.clone();
        let mut config = self.config;

        let (criterias, quota): (Vec<Box<dyn Termination>>, _) =
            match (self.max_generations, self.max_time, self.cost_variation) {
                (None, None, None) => {
                    config.logger.deref()(
                        "configured to use default max-generations (2000) and max-time (300secs)".to_string(),
                    );
                    (vec![Box::new(MaxGeneration::new(2000)), Box::new(MaxTime::new(300.))], None)
                }
                _ => {
                    let mut criterias: Vec<Box<dyn Termination>> = vec![];

                    if let Some(limit) = self.max_generations {
                        config.logger.deref()(format!("configured to use max-generations: {}", limit));
                        criterias.push(Box::new(MaxGeneration::new(limit)))
                    }

                    let quota = if let Some(limit) = self.max_time {
                        config.logger.deref()(format!("configured to use max-time: {}s", limit));
                        criterias.push(Box::new(MaxTime::new(limit as f64)));
                        create_time_quota(limit)
                    } else {
                        None
                    };

                    if let Some((sample, threshold)) = self.cost_variation {
                        config.logger.deref()(format!(
                            "configured to use cost variation with sample: {}, threshold: {}",
                            sample, threshold
                        ));
                        criterias.push(Box::new(CostVariation::new(sample, threshold)))
                    }

                    (criterias, quota)
                }
            };

        config.termination = Box::new(CompositeTermination::new(criterias));
        config.quota = quota;

        Ok(Solver { problem, config })
    }
}

fn create_time_quota(limit: usize) -> Option<Box<dyn Quota + Sync + Send>> {
    Some(Box::new(TimeQuota::new(limit as f64)))
}