00001 #include "ECF_base.h"
00002 #include "ECF_macro.h"
00003 #include "AlgGeneticAnnealing.h"
00004
00005
00006 GeneticAnnealing::GeneticAnnealing()
00007 {
00008
00009 name_ = "GeneticAnnealing";
00010
00011 selBestOp_ = static_cast<SelBestOpP> (new SelBestOp);
00012 }
00013
00014
00015 void GeneticAnnealing::registerParameters(StateP state)
00016 {
00017 registerParameter(state, "energybank", (voidP) new double(200), ECF::DOUBLE);
00018 registerParameter(state, "coolingfactor", (voidP) new double (0.7), ECF::DOUBLE);
00019 registerParameter(state, "elitism", (voidP) new uint (0), ECF::UINT);
00020 }
00021
00022
00023 bool GeneticAnnealing::initialize(StateP state)
00024 {
00025
00026 voidP p = getParameterValue(state, "energybank");
00027 this->energyBank_ = *((double*) p.get());
00028
00029 if(energyBank_ <= 0) {
00030 ECF_LOG(state, 1, "Error: GeneticAnnealing algorithm parameter 'energybank' must be greater than zero!");
00031 throw "";
00032 }
00033
00034 p = getParameterValue(state, "coolingfactor");
00035 this->coolingF_ = *((double*) p.get());
00036
00037 if ((coolingF_ < 0)||(coolingF_>=1)){
00038 ECF_LOG(state, 1, "Error: GeneticAnnealing algorithm parameter 'coolingfactor' must be in <0, 1]!");
00039 throw "";
00040 }
00041
00042 p = getParameterValue(state, "elitism");
00043 elitism_ = *((uint*) p.get()) ? true : false;
00044
00045 isFirstGeneration_ = true;
00046
00047 selBestOp_->initialize(state);
00048
00049 return true;
00050 }
00051
00052
00053 bool GeneticAnnealing::advanceGeneration(StateP state, DemeP deme)
00054 {
00055 uint N = (uint) deme->size();
00056 uint i;
00057 IndividualP mutant, ind;
00058
00059 IndividualP best = selBestOp_->select(*deme);
00060
00061 if (isFirstGeneration_){
00062 Th = (double *) malloc (N*sizeof(double));
00063 for (i = 0; i < N; i++){
00064 ind = deme->at(i);
00065 Th[i] = ind->fitness->getValue() + energyBank_/N;
00066 }
00067
00068 energyBank_ = 0;
00069 isFirstGeneration_ = false;
00070 }
00071
00072 for (i = 0; i < N; i++){
00073 ind = deme->at(i);
00074
00075 if(elitism_ && ind == best)
00076 continue;
00077
00078 mutant = (IndividualP) ind->copy();
00079 mutate (mutant);
00080 evaluate(mutant);
00081
00082 double eMutant = mutant->fitness->getValue();
00083
00084 if (eMutant <= Th[i]){
00085 energyBank_ = energyBank_ + Th[i] - eMutant;
00086 Th[i] = eMutant;
00087 replaceWith(ind, mutant);
00088 }
00089 }
00090
00091 dE_ = energyBank_ * coolingF_ / N;
00092 ECF_LOG(state, 4, "GeneticAnnealing: energy bank=" + dbl2str(energyBank_) + ", dE_=" + dbl2str(dE_));
00093
00094 energyBank_ = 0;
00095 for (i = 0; i < N; i++)
00096 Th[i] += dE_;
00097
00098 return true;
00099 }
00100
00101
00102