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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
use super::{PermutateConfig, PermutateState};
use crate::genotype::PermutableGenotype;
use crate::strategy::{StrategyState, STRATEGY_ACTIONS};
use num::BigUint;
use std::marker::PhantomData;

/// Reporter with event hooks in the Permutate process.
/// A new generation is simply handling a single new chromosome from the total population
///
/// # Example:
/// You are encouraged to take a look at the [PermutateReporterSimple](Simple) implementation, and
/// then roll your own like below:
/// ```rust
/// use genetic_algorithm::strategy::permutate::prelude::*;
/// use num::BigUint;
///
/// #[derive(Clone)]
/// pub struct CustomReporter { pub period: usize };
/// impl PermutateReporter for CustomReporter {
///     type Genotype = BinaryGenotype;
///
///     fn on_new_generation(&mut self, state: &PermutateState<Self::Genotype>, _config: &PermutateConfig) {
///         if state.current_generation() % self.period == 0 {
///             println!(
///                 "progress: {:2.2}%, current_generation: {}, best_generation: {}",
///                 BigUint::from(state.current_generation() * 100) / &state.total_population_size,
///                 state.current_generation(),
///                 state.best_generation(),
///             );
///         }
///     }
///
///     fn on_new_best_chromosome(&mut self, state: &PermutateState<Self::Genotype>, _config: &PermutateConfig) {
///         println!(
///             "new best - generation: {}, fitness_score: {:?}, genes: {:?}",
///             state.current_generation(),
///             state.best_fitness_score(),
///             state.best_chromosome_as_ref().genes,
///         );
///     }
///
///     fn on_finish(&mut self, state: &PermutateState<Self::Genotype>, _config: &PermutateConfig) {
///         println!("finish - generation: {}", state.current_generation());
///         STRATEGY_ACTIONS.iter().for_each(|action| {
///             if let Some(duration) = state.durations.get(action) {
///                 println!("  {:?}: {:?}", action, duration,);
///             }
///         });
///         println!("  Total: {:?}", &state.total_duration());
///     }
///
/// }
/// ```
pub trait Reporter: Clone + Send + Sync {
    type Genotype: PermutableGenotype;

    fn on_init(
        &mut self,
        _genotype: &Self::Genotype,
        _state: &PermutateState<Self::Genotype>,
        _config: &PermutateConfig,
    ) {
    }
    fn on_start(&mut self, _state: &PermutateState<Self::Genotype>, _config: &PermutateConfig) {}
    fn on_finish(&mut self, _state: &PermutateState<Self::Genotype>, _config: &PermutateConfig) {}
    fn on_new_generation(
        &mut self,
        _state: &PermutateState<Self::Genotype>,
        _config: &PermutateConfig,
    ) {
    }
    fn on_new_best_chromosome(
        &mut self,
        _state: &PermutateState<Self::Genotype>,
        _config: &PermutateConfig,
    ) {
    }
    fn on_new_best_chromosome_equal_fitness(
        &mut self,
        _state: &PermutateState<Self::Genotype>,
        _config: &PermutateConfig,
    ) {
    }
}

/// The noop reporter, silences reporting
#[derive(Clone)]
pub struct Noop<G: PermutableGenotype>(pub PhantomData<G>);
impl<G: PermutableGenotype> Default for Noop<G> {
    fn default() -> Self {
        Self(PhantomData)
    }
}
impl<G: PermutableGenotype> Noop<G> {
    pub fn new() -> Self {
        Self::default()
    }
}
impl<G: PermutableGenotype> Reporter for Noop<G> {
    type Genotype = G;
}

/// A Simple reporter generic over Genotype.
/// A report is triggered every period generations
#[derive(Clone)]
pub struct Simple<G: PermutableGenotype> {
    pub period: usize,
    pub show_genes: bool,
    _phantom: PhantomData<G>,
}
impl<G: PermutableGenotype> Default for Simple<G> {
    fn default() -> Self {
        Self {
            period: 1,
            show_genes: false,
            _phantom: PhantomData,
        }
    }
}
impl<G: PermutableGenotype> Simple<G> {
    pub fn new(period: usize) -> Self {
        Self {
            period,
            ..Default::default()
        }
    }
    pub fn new_with_flags(period: usize, show_genes: bool) -> Self {
        Self {
            period,
            show_genes,
            ..Default::default()
        }
    }
}
impl<G: PermutableGenotype> Reporter for Simple<G> {
    type Genotype = G;

    fn on_new_generation(
        &mut self,
        state: &PermutateState<Self::Genotype>,
        _config: &PermutateConfig,
    ) {
        if state.current_generation() % self.period == 0 {
            let width = state.total_population_size.to_string().len();
            println!(
                "progress: {:3.3}%, current_generation: {:>width$}, best_generation: {:>width$}",
                BigUint::from(state.current_generation() * 100) / &state.total_population_size,
                state.current_generation(),
                state.best_generation(),
            );
        }
    }

    fn on_new_best_chromosome(
        &mut self,
        state: &PermutateState<Self::Genotype>,
        _config: &PermutateConfig,
    ) {
        println!(
            "new best - generation: {}, fitness_score: {:?}, genes: {:?}",
            state.current_generation(),
            state.best_fitness_score(),
            if self.show_genes {
                Some(&state.best_chromosome_as_ref().genes)
            } else {
                None
            },
        );
    }

    fn on_finish(&mut self, state: &PermutateState<Self::Genotype>, _config: &PermutateConfig) {
        println!("finish - generation: {}", state.current_generation());
        STRATEGY_ACTIONS.iter().for_each(|action| {
            if let Some(duration) = state.durations.get(action) {
                println!("  {:?}: {:?}", action, duration,);
            }
        });
        println!("  Total: {:?}", &state.total_duration());
    }
}

/// A log-level based reporter for debug and trace, runs on each generation
#[derive(Clone)]
pub struct Log<G: PermutableGenotype>(pub PhantomData<G>);
impl<G: PermutableGenotype> Default for Log<G> {
    fn default() -> Self {
        Self(PhantomData)
    }
}
impl<G: PermutableGenotype> Log<G> {
    pub fn new() -> Self {
        Self::default()
    }
}
impl<G: PermutableGenotype> Reporter for Log<G> {
    type Genotype = G;

    fn on_new_generation(
        &mut self,
        state: &PermutateState<Self::Genotype>,
        _config: &PermutateConfig,
    ) {
        log::debug!(
            "progress: {:2.2}%, current_generation: {}, best_generation: {}, best_fitness_score: {:?}",
            BigUint::from(state.current_generation() * 100) / &state.total_population_size,
            state.current_generation(),
            state.best_generation(),
            state.best_fitness_score(),
        );

        log::trace!(
            "best - fitness score: {:?}, genes: {:?}",
            state.best_fitness_score(),
            state.best_chromosome_as_ref().genes,
        );
    }
}