lemon/simann.h
author ladanyi
Sun, 29 Jan 2006 22:10:06 +0000
changeset 1921 fb4a2a84d363
parent 1847 7cbc12e42482
child 1932 c65711e5a26d
permissions -rw-r--r--
test for simann
alpar@1633
     1
#ifndef LEMON_SIMANN_H
alpar@1633
     2
#define LEMON_SIMANN_H
alpar@1633
     3
alpar@1633
     4
/// \ingroup experimental
alpar@1633
     5
/// \file
alpar@1633
     6
/// \brief Simulated annealing framework.
alpar@1847
     7
///
alpar@1847
     8
/// \todo A test and some demo should be added
alpar@1847
     9
/// \todo Doc should be improved
alpar@1633
    10
/// \author Akos Ladanyi
alpar@1633
    11
alpar@1633
    12
#include <cstdlib>
alpar@1633
    13
#include <cmath>
ladanyi@1918
    14
#include <limits>
alpar@1633
    15
#include <lemon/time_measure.h>
alpar@1633
    16
alpar@1633
    17
namespace lemon {
alpar@1633
    18
alpar@1633
    19
/// \addtogroup experimental
alpar@1633
    20
/// @{
alpar@1633
    21
ladanyi@1918
    22
  /// \brief A base class for controllers.
alpar@1633
    23
  class ControllerBase {
ladanyi@1918
    24
  public:
alpar@1633
    25
    friend class SimAnnBase;
ladanyi@1918
    26
    /// \brief Pointer to the simulated annealing base class.
alpar@1633
    27
    SimAnnBase *simann;
ladanyi@1918
    28
    /// \brief Initializes the controller.
alpar@1633
    29
    virtual void init() {}
ladanyi@1918
    30
    /// \brief This is called by the simulated annealing class when a
ladanyi@1918
    31
    /// neighbouring state gets accepted.
alpar@1633
    32
    virtual void acceptEvent() {}
ladanyi@1918
    33
    /// \brief This is called by the simulated annealing class when the
ladanyi@1918
    34
    /// accepted neighbouring state's cost is less than the best found one's.
alpar@1633
    35
    virtual void improveEvent() {}
ladanyi@1918
    36
    /// \brief This is called by the simulated annealing class when a
ladanyi@1918
    37
    /// neighbouring state gets rejected.
alpar@1633
    38
    virtual void rejectEvent() {}
ladanyi@1918
    39
    /// \brief Decides whether to continue the annealing process or not.
alpar@1633
    40
    virtual bool next() = 0;
ladanyi@1918
    41
    /// \brief Decides whether to accept the current solution or not.
alpar@1633
    42
    virtual bool accept() = 0;
ladanyi@1918
    43
    /// \brief Destructor.
ladanyi@1918
    44
    virtual ~ControllerBase() {}
alpar@1633
    45
  };
alpar@1633
    46
ladanyi@1918
    47
  /// \brief Skeleton of an entity class.
alpar@1633
    48
  class EntityBase {
alpar@1633
    49
  public:
ladanyi@1918
    50
    /// \brief Makes a minor change to the entity.
ladanyi@1918
    51
    /// \return the new cost
alpar@1633
    52
    virtual double mutate() = 0;
ladanyi@1918
    53
    /// \brief Restores the entity to its previous state i.e. reverts the
ladanyi@1918
    54
    /// effects of the last mutate().
alpar@1633
    55
    virtual void revert() = 0;
ladanyi@1918
    56
    /// \brief Makes a copy of the entity.
alpar@1633
    57
    virtual EntityBase* clone() = 0;
ladanyi@1918
    58
    /// \brief Makes a major change to the entity.
alpar@1633
    59
    virtual void randomize() = 0;
ladanyi@1918
    60
    /// \brief Destructor.
ladanyi@1918
    61
    virtual ~EntityBase() {}
alpar@1633
    62
  };
alpar@1633
    63
ladanyi@1918
    64
  /// \brief Simulated annealing abstract base class.
ladanyi@1918
    65
  /// Can be used to derive a custom simulated annealing class if \ref SimAnn
ladanyi@1918
    66
  /// doesn't fit your needs.
alpar@1633
    67
  class SimAnnBase {
alpar@1633
    68
  private:
ladanyi@1918
    69
    /// \brief Pointer to the controller.
alpar@1633
    70
    ControllerBase *controller;
ladanyi@1918
    71
    /// \brief Cost of the current solution.
alpar@1633
    72
    double curr_cost;
ladanyi@1918
    73
    /// \brief Cost of the best solution.
alpar@1633
    74
    double best_cost;
ladanyi@1918
    75
    /// \brief Cost of the previous solution.
alpar@1633
    76
    double prev_cost;
ladanyi@1918
    77
    /// \brief Cost of the solution preceding the previous one.
alpar@1633
    78
    double prev_prev_cost;
ladanyi@1918
    79
    /// \brief Number of iterations.
alpar@1633
    80
    long iter;
ladanyi@1918
    81
    /// \brief Number of iterations which did not improve the solution since
ladanyi@1918
    82
    /// the last improvement.
alpar@1633
    83
    long last_impr;
alpar@1633
    84
  protected:
ladanyi@1918
    85
    /// \brief Step to a neighbouring state.
alpar@1633
    86
    virtual double mutate() = 0;
ladanyi@1918
    87
    /// \brief Reverts the last mutate().
alpar@1633
    88
    virtual void revert() = 0;
ladanyi@1918
    89
    /// \brief Saves the current solution as the best one.
alpar@1633
    90
    virtual void saveAsBest() = 0;
ladanyi@1918
    91
    /// \brief Does initializations before each run.
alpar@1633
    92
    virtual void init() {
alpar@1633
    93
      controller->init();
alpar@1633
    94
      curr_cost = prev_cost = prev_prev_cost = best_cost =
alpar@1633
    95
        std::numeric_limits<double>::infinity();
alpar@1633
    96
      iter = last_impr = 0;
alpar@1633
    97
    }
alpar@1633
    98
  public:
ladanyi@1918
    99
    /// \brief Sets the controller class to use.
alpar@1633
   100
    void setController(ControllerBase &_controller) {
alpar@1633
   101
      controller = &_controller;
alpar@1633
   102
      controller->simann = this;
alpar@1633
   103
    }
ladanyi@1918
   104
    /// \brief Returns the cost of the current solution.
alpar@1633
   105
    double getCurrCost() const { return curr_cost; }
ladanyi@1918
   106
    /// \brief Returns the cost of the previous solution.
alpar@1633
   107
    double getPrevCost() const { return prev_cost; }
ladanyi@1918
   108
    /// \brief Returns the cost of the best solution.
alpar@1633
   109
    double getBestCost() const { return best_cost; }
ladanyi@1918
   110
    /// \brief Returns the number of iterations done.
alpar@1633
   111
    long getIter() const { return iter; }
ladanyi@1918
   112
    /// \brief Returns the ordinal number of the last iteration when the
ladanyi@1918
   113
    /// solution was improved.
alpar@1633
   114
    long getLastImpr() const { return last_impr; }
ladanyi@1918
   115
    /// \brief Performs one iteration.
alpar@1633
   116
    bool step() {
alpar@1633
   117
      iter++;
alpar@1633
   118
      prev_prev_cost = prev_cost;
alpar@1633
   119
      prev_cost = curr_cost;
alpar@1633
   120
      curr_cost = mutate();
alpar@1633
   121
      if (controller->accept()) {
alpar@1633
   122
        controller->acceptEvent();
alpar@1633
   123
        last_impr = iter;
alpar@1633
   124
        if (curr_cost < best_cost) {
alpar@1633
   125
          best_cost = curr_cost;
alpar@1633
   126
          saveAsBest();
alpar@1633
   127
          controller->improveEvent();
alpar@1633
   128
        }
alpar@1633
   129
      }
alpar@1633
   130
      else {
alpar@1633
   131
        revert();
alpar@1633
   132
        curr_cost = prev_cost;
alpar@1633
   133
        prev_cost = prev_prev_cost;
alpar@1633
   134
        controller->rejectEvent();
alpar@1633
   135
      }
alpar@1633
   136
      return controller->next();
alpar@1633
   137
    }
ladanyi@1918
   138
    /// \brief Performs a given number of iterations.
ladanyi@1918
   139
    /// \param n the number of iterations
alpar@1633
   140
    bool step(int n) {
alpar@1633
   141
      for(; n > 0 && step(); --n) ;
alpar@1633
   142
      return !n;
alpar@1633
   143
    }
ladanyi@1918
   144
    /// \brief Starts the annealing process.
alpar@1633
   145
    void run() {
alpar@1633
   146
      init();
alpar@1633
   147
      do { } while (step());
alpar@1633
   148
    }
ladanyi@1918
   149
    /// \brief Destructor.
ladanyi@1918
   150
    virtual ~SimAnnBase() {}
alpar@1633
   151
  };
alpar@1633
   152
ladanyi@1918
   153
  /// \brief Simulated annealing class.
alpar@1633
   154
  class SimAnn : public SimAnnBase {
alpar@1633
   155
  private:
ladanyi@1918
   156
    /// \brief Pointer to the current entity.
alpar@1633
   157
    EntityBase *curr_ent;
ladanyi@1918
   158
    /// \brief Pointer to the best entity.
alpar@1633
   159
    EntityBase *best_ent;
ladanyi@1918
   160
    /// \brief Does initializations before each run.
alpar@1633
   161
    void init() {
alpar@1633
   162
      SimAnnBase::init();
alpar@1633
   163
      if (best_ent) delete best_ent;
alpar@1633
   164
      best_ent = NULL;
alpar@1633
   165
      curr_ent->randomize();
alpar@1633
   166
    }
alpar@1633
   167
  public:
ladanyi@1918
   168
    /// \brief Constructor.
alpar@1633
   169
    SimAnn() : curr_ent(NULL), best_ent(NULL) {}
ladanyi@1918
   170
    /// \brief Destructor.
alpar@1633
   171
    virtual ~SimAnn() {
alpar@1633
   172
      if (best_ent) delete best_ent;
alpar@1633
   173
    }
ladanyi@1918
   174
    /// \brief Step to a neighbouring state.
alpar@1633
   175
    double mutate() {
alpar@1633
   176
      return curr_ent->mutate();
alpar@1633
   177
    }
ladanyi@1918
   178
    /// \brief Reverts the last mutate().
alpar@1633
   179
    void revert() {
alpar@1633
   180
      curr_ent->revert();
alpar@1633
   181
    }
ladanyi@1918
   182
    /// \brief Saves the current solution as the best one.
alpar@1633
   183
    void saveAsBest() { 
alpar@1633
   184
      if (best_ent) delete best_ent;
alpar@1633
   185
      best_ent = curr_ent->clone();
alpar@1633
   186
    }
ladanyi@1918
   187
    /// \brief Sets the current entity.
alpar@1633
   188
    void setEntity(EntityBase &_ent) {
alpar@1633
   189
      curr_ent = &_ent;
alpar@1633
   190
    }
ladanyi@1918
   191
    /// \brief Returns a copy of the best found entity.
alpar@1633
   192
    EntityBase* getBestEntity() { return best_ent->clone(); }
alpar@1633
   193
  };
alpar@1633
   194
ladanyi@1918
   195
  /// \brief A simple controller for the simulated annealing class.
ladanyi@1918
   196
  /// This controller starts from a given initial temperature and evenly
ladanyi@1918
   197
  /// decreases it.
alpar@1633
   198
  class SimpleController : public ControllerBase {
ladanyi@1918
   199
  private:
ladanyi@1918
   200
    /// \brief Maximum number of iterations.
ladanyi@1918
   201
    long max_iter;
ladanyi@1918
   202
    /// \brief Maximum number of iterations which do not improve the
ladanyi@1918
   203
    /// solution.
ladanyi@1918
   204
    long max_no_impr;
ladanyi@1918
   205
    /// \brief Temperature.
ladanyi@1918
   206
    double temp;
ladanyi@1918
   207
    /// \brief Annealing factor.
ladanyi@1918
   208
    double ann_fact;
ladanyi@1918
   209
    /// \brief Constructor.
ladanyi@1918
   210
    /// \param _max_iter maximum number of iterations
ladanyi@1918
   211
    /// \param _max_no_impr maximum number of consecutive iterations which do
ladanyi@1918
   212
    ///        not yield a better solution
ladanyi@1918
   213
    /// \param _temp initial temperature
ladanyi@1918
   214
    /// \param _ann_fact annealing factor
alpar@1633
   215
  public:
alpar@1633
   216
    SimpleController(long _max_iter = 500000, long _max_no_impr = 20000,
alpar@1633
   217
    double _temp = 1000.0, double _ann_fact = 0.9999) : max_iter(_max_iter),
alpar@1633
   218
      max_no_impr(_max_no_impr), temp(_temp), ann_fact(_ann_fact)
alpar@1633
   219
    {
alpar@1633
   220
      srand48(time(0));
alpar@1633
   221
    }
ladanyi@1918
   222
    /// \brief This is called when a neighbouring state gets accepted.
alpar@1633
   223
    void acceptEvent() {}
ladanyi@1918
   224
    /// \brief This is called when the accepted neighbouring state's cost is
ladanyi@1918
   225
    /// less than the best found one's.
alpar@1633
   226
    void improveEvent() {}
ladanyi@1918
   227
    /// \brief This is called when a neighbouring state gets rejected.
alpar@1633
   228
    void rejectEvent() {}
ladanyi@1918
   229
    /// \brief Decides whether to continue the annealing process or not. Also
ladanyi@1918
   230
    /// decreases the temperature.
alpar@1633
   231
    bool next() {
alpar@1633
   232
      temp *= ann_fact;
alpar@1633
   233
      bool quit = (simann->getIter() > max_iter) ||
alpar@1633
   234
        (simann->getIter() - simann->getLastImpr() > max_no_impr);
alpar@1633
   235
      return !quit;
alpar@1633
   236
    }
ladanyi@1918
   237
    /// \brief Decides whether to accept the current solution or not.
alpar@1633
   238
    bool accept() {
ladanyi@1918
   239
      double cost_diff = simann->getCurrCost() - simann->getPrevCost();
ladanyi@1918
   240
      return (drand48() <= exp(-(cost_diff / temp)));
alpar@1633
   241
    }
ladanyi@1918
   242
    /// \brief Destructor.
ladanyi@1918
   243
    virtual ~SimpleController() {}
alpar@1633
   244
  };
alpar@1633
   245
ladanyi@1918
   246
  /// \brief A controller with preset running time for the simulated annealing
ladanyi@1918
   247
  /// class.
ladanyi@1918
   248
  /// With this controller you can set the running time of the annealing
ladanyi@1918
   249
  /// process in advance. It works the following way: the controller measures
ladanyi@1918
   250
  /// a kind of divergence. The divergence is the difference of the average
ladanyi@1918
   251
  /// cost of the recently found solutions the cost of the best found one. In
ladanyi@1918
   252
  /// case this divergence is greater than a given threshold, then we decrease
ladanyi@1918
   253
  /// the annealing factor, that is we cool the system faster. In case the
ladanyi@1918
   254
  /// divergence is lower than the threshold, then we increase the temperature.
ladanyi@1918
   255
  /// The threshold is a function of the elapsed time which reaches zero at the
ladanyi@1918
   256
  /// desired end time.
alpar@1633
   257
  class AdvancedController : public ControllerBase {
alpar@1633
   258
  private:
ladanyi@1918
   259
    /// \brief Timer class to measure the elapsed time.
alpar@1633
   260
    Timer timer;
ladanyi@1918
   261
    /// \brief Calculates the threshold value.
ladanyi@1918
   262
    /// \param time the elapsed time in seconds
alpar@1633
   263
    virtual double threshold(double time) {
alpar@1633
   264
      return (-1.0) * start_threshold / end_time * time + start_threshold;
alpar@1633
   265
    }
ladanyi@1918
   266
    /// \brief Parameter used to calculate the running average.
ladanyi@1918
   267
    double alpha;
ladanyi@1918
   268
    /// \brief Parameter used to decrease the annealing factor.
ladanyi@1918
   269
    double beta;
ladanyi@1918
   270
    /// \brief Parameter used to increase the temperature.
ladanyi@1918
   271
    double gamma;
ladanyi@1918
   272
    /// \brief The time at the end of the algorithm.
ladanyi@1918
   273
    double end_time;
ladanyi@1918
   274
    /// \brief The time at the start of the algorithm.
ladanyi@1918
   275
    double start_time;
ladanyi@1918
   276
    /// \brief Starting threshold.
ladanyi@1918
   277
    double start_threshold;
ladanyi@1918
   278
    /// \brief Average cost of recent solutions.
ladanyi@1918
   279
    double avg_cost;
ladanyi@1918
   280
    /// \brief Temperature.
ladanyi@1918
   281
    double temp;
ladanyi@1918
   282
    /// \brief Annealing factor.
ladanyi@1918
   283
    double ann_fact;
ladanyi@1918
   284
    /// \brief Initial annealing factor.
ladanyi@1918
   285
    double init_ann_fact;
ladanyi@1918
   286
    /// \brief True when the annealing process has been started.
ladanyi@1918
   287
    bool start;
alpar@1633
   288
  public:
ladanyi@1918
   289
    /// \brief Constructor.
ladanyi@1918
   290
    /// \param _end_time running time in seconds
ladanyi@1918
   291
    /// \param _alpha parameter used to calculate the running average
ladanyi@1918
   292
    /// \param _beta parameter used to decrease the annealing factor
ladanyi@1918
   293
    /// \param _gamma parameter used to increase the temperature
ladanyi@1918
   294
    /// \param _ann_fact initial annealing factor
alpar@1633
   295
    AdvancedController(double _end_time, double _alpha = 0.2,
alpar@1633
   296
    double _beta = 0.9, double _gamma = 1.6, double _ann_fact = 0.9999) :
alpar@1633
   297
    alpha(_alpha), beta(_beta), gamma(_gamma), end_time(_end_time),
ladanyi@1918
   298
    ann_fact(_ann_fact), init_ann_fact(_ann_fact), start(false)
alpar@1633
   299
    {
alpar@1633
   300
      srand48(time(0));
alpar@1633
   301
    }
ladanyi@1918
   302
    /// \brief Does initializations before each run.
alpar@1633
   303
    void init() {
alpar@1633
   304
      avg_cost = simann->getCurrCost();
alpar@1633
   305
    }
ladanyi@1918
   306
    /// \brief This is called when a neighbouring state gets accepted.
alpar@1633
   307
    void acceptEvent() {
alpar@1633
   308
      avg_cost = alpha * simann->getCurrCost() + (1.0 - alpha) * avg_cost;
ladanyi@1918
   309
      if (!start) {
alpar@1633
   310
        static int cnt = 0;
alpar@1633
   311
        cnt++;
alpar@1633
   312
        if (cnt >= 100) {
alpar@1633
   313
          // calculate starting threshold and starting temperature
alpar@1633
   314
          start_threshold = 5.0 * fabs(simann->getBestCost() - avg_cost);
alpar@1633
   315
          temp = 10000.0;
ladanyi@1918
   316
          start = true;
alpar@1847
   317
          timer.restart();
alpar@1633
   318
        }
alpar@1633
   319
      }
alpar@1633
   320
    }
ladanyi@1918
   321
    /// \brief Decides whether to continue the annealing process or not.
alpar@1633
   322
    bool next() {
ladanyi@1918
   323
      if (!start) {
alpar@1633
   324
        return true;
alpar@1633
   325
      }
alpar@1633
   326
      else {
ladanyi@1918
   327
        double elapsed_time = timer.realTime();
alpar@1633
   328
        if (fabs(avg_cost - simann->getBestCost()) > threshold(elapsed_time)) {
alpar@1633
   329
          // decrease the annealing factor
alpar@1633
   330
          ann_fact *= beta;
alpar@1633
   331
        }
alpar@1633
   332
        else {
alpar@1633
   333
          // increase the temperature
alpar@1633
   334
          temp *= gamma;
alpar@1633
   335
          // reset the annealing factor
alpar@1633
   336
          ann_fact = init_ann_fact;
alpar@1633
   337
        }
alpar@1633
   338
        temp *= ann_fact;
alpar@1633
   339
        return elapsed_time < end_time;
alpar@1633
   340
      }
alpar@1633
   341
    }
ladanyi@1918
   342
    /// \brief Decides whether to accept the current solution or not.
alpar@1633
   343
    bool accept() {
ladanyi@1918
   344
      if (!start) {
alpar@1633
   345
        return true;
alpar@1633
   346
      }
alpar@1633
   347
      else {
ladanyi@1918
   348
        double cost_diff = simann->getCurrCost() - simann->getPrevCost();
ladanyi@1918
   349
        return (drand48() <= exp(-(cost_diff / temp)));
alpar@1633
   350
      }
alpar@1633
   351
    }
ladanyi@1918
   352
    /// \brief Destructor.
ladanyi@1918
   353
    virtual ~AdvancedController() {}
alpar@1633
   354
  };
alpar@1633
   355
alpar@1633
   356
/// @}
alpar@1633
   357
alpar@1633
   358
}
alpar@1633
   359
alpar@1633
   360
#endif