ew/lib.rs
1//! The crate for global optimization algorithms.
2//! The crate uses common traits for easy switch between algorithms.
3extern crate num;
4
5pub mod genetic;
6pub mod particleswarm;
7pub mod tools;
8
9type GoalValue = f64;
10
11/// First item is current solution in search space,
12/// second item is current goal value
13type Solution<T> = (T, GoalValue);
14
15/// Common Optimizer trait.
16///
17/// `T` - type of a point in search space for goal function.
18pub trait Optimizer<T> {
19 /// Run an algorithm.
20 ///
21 /// Returns `Some((x: &T, goal: GoalValue))`, where `x` - result of optimization,
22 /// `goal` - value of goal function. Returns `None` if an algoritm can't find minimum of a goal function.
23 ///
24 /// # Remarks
25 /// All algorithms with `Optimizer` must search minimum of a goal function.
26 fn find_min(&mut self) -> Option<Solution<T>>;
27}
28
29/// The trait for iterative algorithms.
30///
31/// `T` - type of a point in search space for goal function.
32pub trait IterativeOptimizer<T> {
33 /// The method can be called after algorithm initialization.
34 fn next_iterations(&mut self) -> Option<Solution<T>>;
35}
36
37/// The trait for a struct with information about current algorithm state.
38/// For example: population for genetic algorithm, swarm for particle swarm algorithm etc
39///
40/// `T` - type of a point in search space for goal function.
41pub trait AlgorithmState<T> {
42 fn get_best_solution(&self) -> Option<Solution<T>>;
43 fn get_iteration(&self) -> usize;
44}
45
46/// The trait for algotithms where use agents (genetic algorithm, partical swarm algorithm etc).
47///
48/// `T` - type of a point in search space for goal function.
49pub trait AgentsState<T>: AlgorithmState<T> {
50 type Agent: Agent<T>;
51
52 /// Returns vector with references to all agents
53 fn get_agents(&self) -> Vec<&Self::Agent>;
54}
55
56/// The trait for single point in search space. The trait used with `AlgorithmWithAgents`.
57///
58/// `T` - type of a point in search space for goal function.
59pub trait Agent<T> {
60 /// Returns parameter (point in search space) of the agent.
61 fn get_parameter(&self) -> &T;
62
63 /// Returns value of a goal function for current agent.
64 fn get_goal(&self) -> GoalValue;
65}
66
67/// The trait for the goal function.
68pub trait Goal<T> {
69 /// Must return value of goal function for the point in the search space (x).
70 fn get(&mut self, x: &T) -> GoalValue;
71}
72
73/// Struct to convert (wrap) function to `Goal` trait.
74pub struct GoalFromFunction<T> {
75 function: fn(&T) -> GoalValue,
76}
77
78impl<T> GoalFromFunction<T> {
79 /// Constructor.
80 pub fn new(function: fn(&T) -> GoalValue) -> Self {
81 Self { function }
82 }
83}
84
85impl<T> Goal<T> for GoalFromFunction<T> {
86 fn get(&mut self, x: &T) -> GoalValue {
87 (self.function)(x)
88 }
89}