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
//! This module contains a hyper-heuristic logic.

mod dynamic_selective;
pub use self::dynamic_selective::*;

mod static_selective;
pub use self::static_selective::*;

use crate::models::Problem;
use crate::solver::population::Individual;
use crate::solver::{RefinementContext, Statistics};
use crate::utils::{Environment, Random};
use hashbrown::HashMap;
use std::sync::Arc;

/// Represents a hyper heuristic functionality.
pub trait HyperHeuristic {
    /// Performs a new search in solution space using individuals provided.
    fn search(&mut self, refinement_ctx: &RefinementContext, individuals: Vec<&Individual>) -> Vec<Individual>;
}

/// A selective heuristic which uses dynamic or static selective heuristic depending on search performance.
pub struct MultiSelective {
    inner: Box<dyn HyperHeuristic + Send + Sync>,
    is_slow_search: bool,
}

impl HyperHeuristic for MultiSelective {
    fn search(&mut self, refinement_ctx: &RefinementContext, individuals: Vec<&Individual>) -> Vec<Individual> {
        self.is_slow_search = match (self.is_slow_search, is_slow_search(&refinement_ctx.statistics)) {
            (false, true) => {
                self.inner = Box::new(StaticSelective::new_with_defaults(
                    refinement_ctx.problem.clone(),
                    refinement_ctx.environment.clone(),
                ));
                true
            }
            (true, true) => true,
            _ => false,
        };

        self.inner.search(refinement_ctx, individuals)
    }
}

impl MultiSelective {
    /// Creates an instance of `MultiSelective` heuristic.
    pub fn new_with_defaults(problem: Arc<Problem>, environment: Arc<Environment>) -> Self {
        MultiSelective {
            inner: Box::new(DynamicSelective::new_with_defaults(problem, environment)),
            is_slow_search: false,
        }
    }
}

fn is_slow_search(statistics: &Statistics) -> bool {
    statistics.termination_estimate > 0.1 && statistics.generation < 200
}