1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/src/work/akos/SimAnn.h Wed Sep 29 10:35:35 2004 +0000
1.3 @@ -0,0 +1,103 @@
1.4 +#ifndef SIMANN_H
1.5 +#define SIMANN_H
1.6 +
1.7 +#ifndef INFTY
1.8 +#define INFTY 1e24
1.9 +#endif
1.10 +
1.11 +#include <iostream>
1.12 +
1.13 +class SimAnnBase {
1.14 +public:
1.15 + friend class Controller;
1.16 + class Controller {
1.17 + public:
1.18 + SimAnnBase *sab;
1.19 + double T;
1.20 + void init(SimAnnBase *_sab) { sab = _sab; }
1.21 + bool next() {}
1.22 + bool accept(double cost) {}
1.23 + };
1.24 +protected:
1.25 + double CurrCost;
1.26 + double PrevCost;
1.27 + double BestCost;
1.28 +
1.29 + long Iter;
1.30 + long LastImpr;
1.31 +
1.32 + //friend class Controller;
1.33 + Controller *Ctrl;
1.34 +public:
1.35 + long getIter() { return Iter; }
1.36 + long getLastImpr() { return LastImpr; }
1.37 + double getBestCost() { return BestCost; }
1.38 + virtual void mutate() = 0;
1.39 + virtual void revert() = 0;
1.40 + virtual void saveAsBest() = 0;
1.41 + virtual void init() = 0;
1.42 +
1.43 + void run() {
1.44 + init();
1.45 + while (Ctrl->next()) {
1.46 + Iter++;
1.47 + std::cout << Iter << std::endl;
1.48 + mutate();
1.49 + if (Ctrl->accept(PrevCost - CurrCost) && (CurrCost < BestCost)) {
1.50 + LastImpr = Iter;
1.51 + saveAsBest();
1.52 + }
1.53 + else {
1.54 + revert();
1.55 + }
1.56 + }
1.57 + }
1.58 +};
1.59 +
1.60 +template <typename E>
1.61 +class SimAnn : public SimAnnBase {
1.62 +private:
1.63 + E *CurrEnt;
1.64 + E *PrevEnt;
1.65 + E *BestEnt;
1.66 +public:
1.67 + SimAnn() {
1.68 + CurrCost = PrevCost = BestCost = INFTY;
1.69 + Iter = LastImpr = 0;
1.70 + }
1.71 + void setController(Controller &_Ctrl) { Ctrl = &_Ctrl; }
1.72 + void setEnt(E &Ent) {
1.73 + CurrEnt = new E(Ent);
1.74 + PrevEnt = new E(Ent);
1.75 + BestEnt = new E(Ent);
1.76 + }
1.77 + E getBestEnt() { return *BestEnt; }
1.78 + void mutate() {
1.79 + *PrevEnt = *CurrEnt;
1.80 + PrevCost = CurrCost;
1.81 + CurrCost = CurrEnt->mutate();
1.82 + }
1.83 + void revert() {
1.84 + E *tmp = CurrEnt;
1.85 + CurrEnt = PrevEnt;
1.86 + PrevEnt = tmp;
1.87 + CurrCost = PrevCost;
1.88 + }
1.89 + void saveAsBest() {
1.90 + *BestEnt = *CurrEnt;
1.91 + BestCost = CurrCost;
1.92 + }
1.93 + void init() {
1.94 + Ctrl->init(this);
1.95 + CurrEnt->init();
1.96 + }
1.97 +};
1.98 +
1.99 +class EntitySkeleton {
1.100 +public:
1.101 + void init() {}
1.102 + // returns the new cost
1.103 + double mutate() { return 0.0; }
1.104 +};
1.105 +
1.106 +#endif