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
use crate::point::*;
use crate::simplex::*;
use crate::search_space::*;
use priority_queue::PriorityQueue;
use ordered_float::OrderedFloat;
use num_traits::Float;
use std::rc::Rc;

/// Stores the parameters and current state of a search.
///
/// - `ValueFloat` is the float type used to represent the evaluations (such as f64)
/// - `CoordFloat` is the float type used to represent the coordinates (such as f32)
pub struct Optimizer<'f_lifetime, CoordFloat: Float, ValueFloat: Float>
{
   exploration_depth: ValueFloat,
   search_space: SearchSpace<'f_lifetime, CoordFloat, ValueFloat>,
   best_point: Rc<Point<CoordFloat, ValueFloat>>,
   min_value: ValueFloat,
   queue: PriorityQueue<Simplex<CoordFloat, ValueFloat>, OrderedFloat<ValueFloat>>
}

impl<'f_lifetime, CoordFloat: Float, ValueFloat: Float> Optimizer<'f_lifetime, CoordFloat, ValueFloat>
{
   /// Creates a new optimizer to explore the given search space with the iterator interface.
   ///
   /// Takes a function, a vector of intervals describing the input and a boolean describing wether it is a minimization problem (as oppozed to a miximization problem).
   /// Each cal to the `.next()` function (cf iterator trait) will run an iteration of search and output the best result so far.
   ///
   /// **Warning:** In d dimenssions, this function will perform d+1 evaluation (call to f) for the initialisation of the search (those should be taken into account when counting iterations).
   ///
   /// ```rust
   /// # use simplers_optimization::Optimizer;
   /// # fn main() {
   /// let f = |v:&[f64]| v[0] * v[1];
   /// let input_interval = vec![(-10., 10.), (-20., 20.)];
   /// let should_minimize = true;
   ///
   /// // runs the search for 30 iterations
   /// // then waits until we find a point good enough
   /// // finally stores the best value so far
   /// let (min_value, coordinates) = Optimizer::new(&f, &input_interval, should_minimize)
   ///                                          .skip(30)
   ///                                          .skip_while(|(value,coordinates)| *value > 1. )
   ///                                          .next().unwrap();
   ///
   /// println!("min value: {} found in [{}, {}]", min_value, coordinates[0], coordinates[1]);
   /// # }
   /// ```
   pub fn new(f: &'f_lifetime impl Fn(&[CoordFloat]) -> ValueFloat,
              input_interval: &[(CoordFloat, CoordFloat)],
              should_minimize: bool)
              -> Self
   {
      // builds initial conditions
      let search_space = SearchSpace::new(f, input_interval, should_minimize);
      let initial_simplex = Simplex::initial_simplex(&search_space);

      // various values track through the iterations
      let best_point = initial_simplex.corners
                                      .iter()
                                      .max_by_key(|c| OrderedFloat(c.value))
                                      .expect("You need at least one dimension!")
                                      .clone();
      let min_value = initial_simplex.corners
                                     .iter()
                                     .map(|c| c.value)
                                     .min_by_key(|&v| OrderedFloat(v))
                                     .expect("You need at least one dimension!");

      // initialize priority queue
      // no need to evaluate the initial simplex as it will be poped immediatly
      let mut queue: PriorityQueue<Simplex<CoordFloat, ValueFloat>, OrderedFloat<ValueFloat>> =
         PriorityQueue::new();
      queue.push(initial_simplex, OrderedFloat(ValueFloat::zero()));

      let exploration_depth = ValueFloat::from(6.).unwrap();
      Optimizer { exploration_depth, search_space, best_point, min_value, queue }
   }

   /// Sets the exploration depth for the algorithm, useful when using the iterator interface.
   ///
   /// `exploration_depth` represents the number of splits we can exploit before requiring higher-level exploration.
   /// As long as one stays in a reasonable range (5-10), the algorithm should not be very sensible to the parameter :
   ///
   /// - 0 represents full exploration (similar to grid search)
   /// - high numbers focus on exploitation (no need to go very high)
   /// - 5 appears to be a good default value
   ///
   /// **WARNING**: this function should not be used before after an iteration
   /// (as it will not update the score of already computed points for the next iterations
   /// which will degrade the quality of the algorithm)
   ///
   /// ```rust
   /// # use simplers_optimization::Optimizer;
   /// # fn main() {
   /// let f = |v:&[f64]| v[0] * v[1];
   /// let input_interval = vec![(-10., 10.), (-20., 20.)];
   /// let should_minimize = true;
   ///
   /// // sets exploration_depth to be very greedy
   /// let (min_value_greedy, _) = Optimizer::new(&f, &input_interval, should_minimize)
   ///                                          .set_exploration_depth(20)
   ///                                          .skip(100)
   ///                                          .next().unwrap();
   ///
   /// // sets exploration_depth to focus on exploration
   /// let (min_value_explore, _) = Optimizer::new(&f, &input_interval, should_minimize)
   ///                                          .set_exploration_depth(0)
   ///                                          .skip(100)
   ///                                          .next().unwrap();
   ///
   /// println!("greedy result : {} vs exploration result : {}", min_value_greedy, min_value_explore);
   /// # }
   /// ```
   pub fn set_exploration_depth(mut self, exploration_depth: usize) -> Self
   {
      self.exploration_depth = ValueFloat::from(exploration_depth + 1).unwrap();
      self
   }

   /// Self contained optimization algorithm.
   ///
   /// Takes a function to maximize, a vector of intervals describing the input and a number of iterations.
   ///
   /// ```rust
   /// # use simplers_optimization::Optimizer;
   /// # fn main() {
   /// let f = |v:&[f64]| v[0] + v[1];
   /// let input_interval = vec![(-10., 10.), (-20., 20.)];
   /// let nb_iterations = 100;
   ///
   /// let (max_value, coordinates) = Optimizer::maximize(&f, &input_interval, nb_iterations);
   /// println!("max value: {} found in [{}, {}]", max_value, coordinates[0], coordinates[1]);
   /// # }
   /// ```
   pub fn maximize(f: &'f_lifetime impl Fn(&[CoordFloat]) -> ValueFloat,
                   input_interval: &[(CoordFloat, CoordFloat)],
                   nb_iterations: usize)
                   -> (ValueFloat, Coordinates<CoordFloat>)
   {
      let initial_iteration_number = input_interval.len() + 1;
      let should_minimize = false;
      Optimizer::new(f, input_interval, should_minimize).skip(nb_iterations - initial_iteration_number)
                                                        .next()
                                                        .unwrap()
   }

   /// Self contained optimization algorithm.
   ///
   /// Takes a function to minimize, a vector of intervals describing the input and a number of iterations.
   ///
   /// ```rust
   /// # use simplers_optimization::Optimizer;
   /// # fn main() {
   /// let f = |v:&[f64]| v[0] * v[1];
   /// let input_interval = vec![(-10., 10.), (-20., 20.)];
   /// let nb_iterations = 100;
   ///
   /// let (min_value, coordinates) = Optimizer::minimize(&f, &input_interval, nb_iterations);
   /// println!("min value: {} found in [{}, {}]", min_value, coordinates[0], coordinates[1]);
   /// # }
   /// ```
   pub fn minimize(f: &'f_lifetime impl Fn(&[CoordFloat]) -> ValueFloat,
                   input_interval: &[(CoordFloat, CoordFloat)],
                   nb_iterations: usize)
                   -> (ValueFloat, Coordinates<CoordFloat>)
   {
      let initial_iteration_number = input_interval.len() + 1;
      let should_minimize = true;
      Optimizer::new(f, input_interval, should_minimize).skip(nb_iterations - initial_iteration_number)
                                                        .next()
                                                        .unwrap()
   }
}

/// implements iterator for the Optimizer to give full control on the stopping condition to the user
impl<'f_lifetime, CoordFloat: Float, ValueFloat: Float> Iterator
   for Optimizer<'f_lifetime, CoordFloat, ValueFloat>
{
   type Item = (ValueFloat, Coordinates<CoordFloat>);

   /// runs an iteration of the optimization algorithm and returns the best result so far
   fn next(&mut self) -> Option<Self::Item>
   {
      // gets the exploration depth for later use
      let exploration_depth = self.exploration_depth;

      // gets an up to date simplex
      let mut simplex = self.queue.pop().expect("Impossible: The queue cannot be empty!").0;
      let current_difference = self.best_point.value - self.min_value;
      while simplex.difference != current_difference
      {
         // updates the simplex and pushes it back into the queue
         simplex.difference = current_difference;
         let new_evaluation = simplex.evaluate(exploration_depth);
         self.queue.push(simplex, OrderedFloat(new_evaluation));
         // pops a new simplex
         simplex = self.queue.pop().expect("Impossible: The queue cannot be empty!").0;
      }

      // evaluate the center of the simplex
      let coordinates = simplex.center.clone();
      let value = self.search_space.evaluate(&coordinates);
      let new_point = Rc::new(Point { coordinates, value });

      // splits the simplex around its center and push the subsimplex into the queue
      simplex.split(new_point.clone(), current_difference)
             .into_iter()
             .map(|s| (OrderedFloat(s.evaluate(exploration_depth)), s))
             .for_each(|(e, s)| {
                self.queue.push(s, e);
             });

      // updates the difference
      if value > self.best_point.value
      {
         self.best_point = new_point;
      }
      else if value < self.min_value
      {
         self.min_value = value;
      }

      // gets the best value so far
      let best_value =
         if self.search_space.minimize { -self.best_point.value } else { self.best_point.value };
      let best_coordinate = self.search_space.to_hypercube(self.best_point.coordinates.clone());
      Some((best_value, best_coordinate))
   }
}