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 "total starting energy bank (fitness dependant)");
00019 registerParameter(state, "coolingfactor", (voidP) new double (0.7), ECF::DOUBLE,
00020 "simulated annealing cooling factor");
00021 registerParameter(state, "elitism", (voidP) new uint (0), ECF::UINT,
00022 "is the best individual preserved");
00023 }
00024
00025
00026 bool GeneticAnnealing::initialize(StateP state)
00027 {
00028
00029 voidP p = getParameterValue(state, "energybank");
00030 this->energyBank_ = *((double*) p.get());
00031
00032 if(energyBank_ <= 0) {
00033 ECF_LOG(state, 1, "Error: GeneticAnnealing algorithm parameter 'energybank' must be greater than zero!");
00034 throw "";
00035 }
00036
00037 p = getParameterValue(state, "coolingfactor");
00038 this->coolingF_ = *((double*) p.get());
00039
00040 if ((coolingF_ < 0)||(coolingF_>=1)){
00041 ECF_LOG(state, 1, "Error: GeneticAnnealing algorithm parameter 'coolingfactor' must be in <0, 1]!");
00042 throw "";
00043 }
00044
00045 p = getParameterValue(state, "elitism");
00046 elitism_ = *((uint*) p.get()) ? true : false;
00047
00048 isFirstGeneration_ = true;
00049
00050 selBestOp_->initialize(state);
00051
00052 return true;
00053 }
00054
00055
00056 bool GeneticAnnealing::advanceGeneration(StateP state, DemeP deme)
00057 {
00058 uint N = (uint) deme->size();
00059 uint i;
00060 IndividualP mutant, ind;
00061
00062 IndividualP best = selBestOp_->select(*deme);
00063
00064 if (isFirstGeneration_){
00065 Th = (double *) malloc (N*sizeof(double));
00066 for (i = 0; i < N; i++){
00067 ind = deme->at(i);
00068 Th[i] = ind->fitness->getValue() + energyBank_/N;
00069 }
00070
00071 energyBank_ = 0;
00072 isFirstGeneration_ = false;
00073 }
00074
00075 for (i = 0; i < N; i++){
00076 ind = deme->at(i);
00077
00078 if(elitism_ && ind == best)
00079 continue;
00080
00081 mutant = (IndividualP) ind->copy();
00082 mutate (mutant);
00083 evaluate(mutant);
00084
00085 double eMutant = mutant->fitness->getValue();
00086
00087 if (eMutant <= Th[i]){
00088 energyBank_ = energyBank_ + Th[i] - eMutant;
00089 Th[i] = eMutant;
00090 replaceWith(ind, mutant);
00091 }
00092 }
00093
00094 dE_ = energyBank_ * coolingF_ / N;
00095 ECF_LOG(state, 4, "GeneticAnnealing: energy bank=" + dbl2str(energyBank_) + ", dE_=" + dbl2str(dE_));
00096
00097 energyBank_ = 0;
00098 for (i = 0; i < N; i++)
00099 Th[i] += dE_;
00100
00101 return true;
00102 }
00103
00104
00105