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
#[cfg(test)]
#[path = "../../../tests/unit/solver/termination/min_variation_test.rs"]
mod min_variation_test;

use super::super::rand::prelude::SliceRandom;
use crate::algorithms::nsga2::MultiObjective;
use crate::algorithms::statistics::get_cv;
use crate::solver::population::SelectionPhase;
use crate::solver::termination::Termination;
use crate::solver::RefinementContext;
use crate::utils::{unwrap_from_result, CollectGroupBy};

/// A termination criteria which calculates coefficient variation in each objective and terminates
/// when min threshold is not reached.
pub struct MinVariation {
    interval_type: IntervalType,
    threshold: f64,
    is_global: bool,
    key: String,
}

enum IntervalType {
    Sample(usize),
    Period(u128),
}

impl MinVariation {
    /// Creates a new instance of `MinVariation` with sample interval type.
    pub fn new_with_sample(sample: usize, threshold: f64, is_global: bool) -> Self {
        assert_ne!(sample, 0);
        Self::new(IntervalType::Sample(sample), threshold, is_global)
    }

    /// Creates a new instance of `MinVariation` with period interval type.
    pub fn new_with_period(period: usize, threshold: f64, is_global: bool) -> Self {
        assert_ne!(period, 0);
        Self::new(IntervalType::Period(period as u128 * 1000), threshold, is_global)
    }

    fn new(interval_type: IntervalType, threshold: f64, is_global: bool) -> Self {
        Self { interval_type, threshold, is_global, key: "max_var".to_string() }
    }

    fn update_and_check(&self, refinement_ctx: &mut RefinementContext, fitness: Vec<f64>) -> bool {
        match &self.interval_type {
            IntervalType::Sample(sample) => {
                let values = refinement_ctx
                    .state
                    .entry(self.key.clone())
                    .or_insert_with(|| Box::new(vec![vec![0.; fitness.len()]; *sample]))
                    .downcast_mut::<Vec<Vec<f64>>>()
                    .unwrap();

                values[refinement_ctx.statistics.generation % sample] = fitness;

                if refinement_ctx.statistics.generation < (*sample - 1) {
                    false
                } else {
                    self.check_threshold(values.iter())
                }
            }
            IntervalType::Period(period) => {
                let values = refinement_ctx
                    .state
                    .entry(self.key.clone())
                    .or_insert_with(|| Box::new(Vec::<(u128, Vec<f64>)>::default()))
                    .downcast_mut::<Vec<(u128, Vec<f64>)>>()
                    .unwrap();

                let current = refinement_ctx.statistics.time.elapsed_millis();
                values.push((current, fitness));

                // NOTE try to keep collection under maintainable size
                if values.len() > 1000 {
                    let mut i = 0_usize;
                    values.shuffle(&mut refinement_ctx.environment.random.get_rng());
                    values.retain(|_| {
                        let result = i % 10 == 0;
                        i += 1;

                        result
                    });
                    values.sort_by(|(a, _), (b, _)| a.cmp(b));
                }

                if *period > current || values.len() < 2 {
                    false
                } else {
                    let earliest = current - *period;
                    let position = values.iter().rev().position(|(time, _)| *time < earliest);

                    let position = match position {
                        Some(position) if position < 2 && values.len() < 3 => 0,
                        Some(position) if position < 2 && values.len() > 3 => values.len() - 2,
                        Some(position) => values.len() - position,
                        _ => 0,
                    };

                    values.drain(0..position);

                    self.check_threshold(values.iter().map(|(_, fitness)| fitness))
                }
            }
        }
    }

    fn check_threshold<'a, I>(&self, values: I) -> bool
    where
        I: Iterator<Item = &'a Vec<f64>>,
    {
        unwrap_from_result(
            values.flat_map(|values| values.iter().cloned().enumerate()).collect_group_by().into_iter().try_fold(
                true,
                |_, (_, values)| {
                    let cv = get_cv(values.as_slice());
                    if cv > self.threshold {
                        Err(false)
                    } else {
                        Ok(true)
                    }
                },
            ),
        )
    }
}

impl Termination for MinVariation {
    fn is_termination(&self, refinement_ctx: &mut RefinementContext) -> bool {
        let first_individual = refinement_ctx.population.ranked().next();
        if let Some((first, _)) = first_individual {
            let objective = refinement_ctx.problem.objective.as_ref();
            let fitness = objective.objectives().map(|o| o.fitness(first)).collect::<Vec<_>>();
            let result = self.update_and_check(refinement_ctx, fitness);

            match (self.is_global, refinement_ctx.population.selection_phase()) {
                (true, _) => result,
                (false, SelectionPhase::Exploitation) => result,
                _ => false,
            }
        } else {
            false
        }
    }

    fn estimate(&self, _: &RefinementContext) -> f64 {
        0.
    }
}