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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
//! This crate exposes a generalized hyper heuristics and some helper functionality which can be
//! used to build a solver for optimization problems.
//!
//!
//! # Examples
//!
//! This example demonstrates the usage of example models and heuristics to minimize Rosenbrock function.
//! For the sake of minimalism, there is a pre-built solver and heuristic operator models. Check
//! example module to see how to use functionality of the crate for an arbitrary domain.
//!
//! ```
//! # use std::sync::Arc;
//! use rosomaxa::prelude::*;
//! use rosomaxa::example::*;
//!
//! let random = Arc::new(DefaultRandom::default());
//! // examples of heuristic operator, they are domain specific. Essentially, heuristic operator
//! // is responsible to produce a new, potentially better solution from the given one.
//! let noise_op = VectorHeuristicOperatorMode::JustNoise(Noise::new_with_ratio(1., (-0.1, 0.1), random));
//! let delta_op = VectorHeuristicOperatorMode::JustDelta(-0.1..0.1);
//! let delta_power_op = VectorHeuristicOperatorMode::JustDelta(-0.5..0.5);
//!
//! // add some configuration and run the solver
//! let (solutions, _) = Solver::default()
//!     .with_fitness_fn(create_rosenbrock_function())
//!     .with_init_solutions(vec![vec![2., 2.]])
//!     .with_search_operator(noise_op, "noise", 1.)
//!     .with_search_operator(delta_op, "delta", 0.2)
//!     .with_diversify_operator(delta_power_op)
//!     .with_termination(Some(5), Some(1000), None, None)
//!     .solve()
//!     .expect("cannot build and use solver");
//!
//! // expecting at least one solution with fitness close to 0
//! assert_eq!(solutions.len(), 1);
//! let (_, fitness) = solutions.first().unwrap();
//! assert!(*fitness < 0.001);
//!
//! # Ok::<(), GenericError>(())
//! ```
//!

#![warn(missing_docs)]
#![forbid(unsafe_code)]

#[cfg(test)]
#[path = "../tests/helpers/mod.rs"]
#[macro_use]
pub mod helpers;

pub mod algorithms;
pub mod evolution;
pub mod example;
pub mod hyper;
pub mod population;
pub mod prelude;
pub mod termination;
pub mod utils;

use crate::algorithms::math::RemedianUsize;
use crate::algorithms::nsga2::MultiObjective;
use crate::evolution::{Telemetry, TelemetryMetrics, TelemetryMode};
use crate::population::*;
use crate::utils::Timer;
use crate::utils::{Environment, GenericError};
use std::hash::Hash;
use std::sync::Arc;

/// Represents solution in population defined as actual solution.
pub trait HeuristicSolution: Send + Sync {
    /// Get fitness values of a given solution.
    fn fitness<'a>(&'a self) -> Box<dyn Iterator<Item = f64> + 'a>;
    /// Creates a deep copy of the solution.
    fn deep_copy(&self) -> Self;
}

/// Represents a heuristic objective function.
pub trait HeuristicObjective: MultiObjective + Send + Sync {}
/// Specifies a dynamically dispatched type for heuristic population.
pub type DynHeuristicPopulation<O, S> = dyn HeuristicPopulation<Objective = O, Individual = S> + Send + Sync;
/// Specifies a heuristic result type.
pub type HeuristicResult<O, S> = Result<(Box<DynHeuristicPopulation<O, S>>, Option<TelemetryMetrics>), GenericError>;

/// Represents heuristic context.
pub trait HeuristicContext: Send + Sync {
    /// A heuristic objective function type.
    type Objective: HeuristicObjective<Solution = Self::Solution>;
    /// A heuristic solution type.
    type Solution: HeuristicSolution;

    /// Returns objective function used by the population.
    fn objective(&self) -> &Self::Objective;

    /// Returns selected solutions base on current context.
    fn selected<'a>(&'a self) -> Box<dyn Iterator<Item = &Self::Solution> + 'a>;

    /// Returns subset of solutions within their rank sorted according their quality.
    fn ranked<'a>(&'a self) -> Box<dyn Iterator<Item = (&Self::Solution, usize)> + 'a>;

    /// Returns current statistic used to track the search progress.
    fn statistics(&self) -> &HeuristicStatistics;

    /// Returns selection phase.
    fn selection_phase(&self) -> SelectionPhase;

    /// Returns environment.
    fn environment(&self) -> &Environment;

    /// Updates population with initial solution.
    fn on_initial(&mut self, solution: Self::Solution, item_time: Timer);

    /// Updates population with a new offspring.
    fn on_generation(&mut self, offspring: Vec<Self::Solution>, termination_estimate: f64, generation_time: Timer);

    /// Returns final population and telemetry metrics
    fn on_result(self) -> HeuristicResult<Self::Objective, Self::Solution>;
}

/// A refinement statistics to track evolution progress.
#[derive(Clone)]
pub struct HeuristicStatistics {
    /// A number which specifies refinement generation.
    pub generation: usize,

    /// Elapsed seconds since algorithm start.
    pub time: Timer,

    /// A current refinement speed.
    pub speed: HeuristicSpeed,

    /// An improvement ratio from beginning.
    pub improvement_all_ratio: f64,

    /// An improvement ratio over last 1000 iterations.
    pub improvement_1000_ratio: f64,

    /// A progress till algorithm's termination.
    pub termination_estimate: f64,
}

impl Default for HeuristicStatistics {
    fn default() -> Self {
        Self {
            generation: 0,
            time: Timer::start(),
            speed: HeuristicSpeed::Unknown,
            improvement_all_ratio: 0.,
            improvement_1000_ratio: 0.,
            termination_estimate: 0.,
        }
    }
}

/// A default heuristic context implementation which uses telemetry to track search progression parameters.
pub struct TelemetryHeuristicContext<O, S>
where
    O: HeuristicObjective<Solution = S>,
    S: HeuristicSolution,
{
    objective: Arc<O>,
    population: Box<DynHeuristicPopulation<O, S>>,
    telemetry: Telemetry<O, S>,
    environment: Arc<Environment>,
}

impl<O, S> TelemetryHeuristicContext<O, S>
where
    O: HeuristicObjective<Solution = S>,
    S: HeuristicSolution,
{
    /// Creates a new instance of `TelemetryHeuristicContext`.
    pub fn new(
        objective: Arc<O>,
        population: Box<DynHeuristicPopulation<O, S>>,
        telemetry_mode: TelemetryMode,
        environment: Arc<Environment>,
    ) -> Self {
        let telemetry = Telemetry::new(telemetry_mode);
        Self { objective, population, telemetry, environment }
    }

    /// Adds solution to population.
    pub fn add_solution(&mut self, solution: S) {
        self.population.add(solution);
    }
}

impl<O, S> HeuristicContext for TelemetryHeuristicContext<O, S>
where
    O: HeuristicObjective<Solution = S>,
    S: HeuristicSolution,
{
    type Objective = O;
    type Solution = S;

    fn objective(&self) -> &Self::Objective {
        &self.objective
    }

    fn selected<'a>(&'a self) -> Box<dyn Iterator<Item = &Self::Solution> + 'a> {
        self.population.select()
    }

    fn ranked<'a>(&'a self) -> Box<dyn Iterator<Item = (&Self::Solution, usize)> + 'a> {
        self.population.ranked()
    }

    fn statistics(&self) -> &HeuristicStatistics {
        self.telemetry.get_statistics()
    }

    fn selection_phase(&self) -> SelectionPhase {
        self.population.selection_phase()
    }

    fn environment(&self) -> &Environment {
        self.environment.as_ref()
    }

    fn on_initial(&mut self, solution: Self::Solution, item_time: Timer) {
        self.telemetry.on_initial(&solution, item_time);
        self.population.add(solution);
    }

    fn on_generation(&mut self, offspring: Vec<Self::Solution>, termination_estimate: f64, generation_time: Timer) {
        let is_improved = self.population.add_all(offspring);
        self.telemetry.on_generation(
            self.objective.as_ref(),
            self.population.as_ref(),
            termination_estimate,
            generation_time,
            is_improved,
        );
        self.population.on_generation(self.telemetry.get_statistics());
    }

    fn on_result(self) -> Result<(Box<DynHeuristicPopulation<O, S>>, Option<TelemetryMetrics>), GenericError> {
        let mut telemetry = self.telemetry;

        telemetry.on_result(self.objective.as_ref(), self.population.as_ref());

        Ok((self.population, telemetry.take_metrics()))
    }
}

/// Defines instant refinement speed type.
#[derive(Clone, Debug)]
pub enum HeuristicSpeed {
    /// Not yet calculated
    Unknown,

    /// Slow speed.
    Slow {
        /// Ratio.
        ratio: f64,
        /// Average refinement speed in generations per second.
        average: f64,
        /// Median estimation of running time for each generation (in ms).
        median: Option<usize>,
    },

    /// Moderate speed.
    Moderate {
        /// Average refinement speed in generations per second.
        average: f64,
        /// Median estimation of running time for each generation (in ms).
        median: Option<usize>,
    },
}

impl HeuristicSpeed {
    /// Returns a median estimation of running time for each generation (in ms)
    pub fn get_median(&self) -> Option<usize> {
        match self {
            HeuristicSpeed::Unknown => None,
            HeuristicSpeed::Slow { median, .. } => *median,
            HeuristicSpeed::Moderate { median, .. } => *median,
        }
    }
}

/// A trait which specifies object with state behavior.
pub trait Stateful {
    /// A key type.
    type Key: Hash + Eq;

    /// Saves state using given key.
    fn set_state<T: 'static + Send + Sync>(&mut self, key: Self::Key, state: T);

    /// Tries to get state using given key.
    fn get_state<T: 'static + Send + Sync>(&self, key: &Self::Key) -> Option<&T>;

    /// Gets state as mutable, inserts if not exists.
    fn state_mut<T: 'static + Send + Sync, F: Fn() -> T>(&mut self, key: Self::Key, inserter: F) -> &mut T;
}

/// Gets default population selection size.
pub fn get_default_selection_size(environment: &Environment) -> usize {
    environment.parallelism.available_cpus().min(8)
}

/// Gets default population algorithm.
pub fn get_default_population<O, S>(
    objective: Arc<O>,
    environment: Arc<Environment>,
    selection_size: usize,
) -> Box<dyn HeuristicPopulation<Objective = O, Individual = S> + Send + Sync>
where
    O: HeuristicObjective<Solution = S> + Shuffled + 'static,
    S: HeuristicSolution + RosomaxaWeighted + DominanceOrdered + 'static,
{
    if selection_size == 1 {
        Box::new(Greedy::new(objective, 1, None))
    } else {
        let config = RosomaxaConfig::new_with_defaults(selection_size);
        let population =
            Rosomaxa::new(objective, environment, config).expect("cannot create rosomaxa with default configuration");

        Box::new(population)
    }
}