00001 #include "ECF_base.h"
00002 #include "HallOfFame.h"
00003 #include <string>
00004 #include <sstream>
00005
00006
00007 HallOfFame::HallOfFame()
00008 {
00009 this->selectBest_ = static_cast<SelBestOpP> (new SelBestOp);
00010 hofSize_ = 1;
00011 }
00012
00013
00014 bool HallOfFame::initialize(StateP state)
00015 {
00016 state_ = state;
00017 bestIndividuals_.clear();
00018 bestIndividuals_.resize(hofSize_);
00019 bestGenerations_.clear();
00020 bestGenerations_.resize(hofSize_);
00021 bEmpty_ = true;
00022 lastChangeGen_ = 0;
00023
00024 return true;
00025 }
00026
00027
00031 bool HallOfFame::operate(StateP state)
00032 {
00033 PopulationP population = state->getPopulation();
00034
00035
00036 for(uint i = 0; i < population->size(); i++) {
00037 operate(*(population->at(i)));
00038 }
00039 return true;
00040 }
00041
00042
00046 bool HallOfFame::operate(const std::vector<IndividualP>& individuals)
00047 {
00048 uint ind = 0;
00049 IndividualP best;
00050
00051 while (ind < hofSize_) {
00052 best = selectBest_->select(individuals);
00053
00054
00055 if(bEmpty_ || best->fitness->isBetterThan(bestIndividuals_[ind]->fitness)) {
00056
00057 bestIndividuals_[ind] = (IndividualP) best->copy();
00058 bestGenerations_[ind] = state_->getGenerationNo();
00059 bEmpty_ = false;
00060 lastChangeGen_ = state_->getGenerationNo();
00061 }
00062 ++ind;
00063 }
00064
00065 return true;
00066 }
00067
00068
00069 void HallOfFame::write(XMLNode& xHoF)
00070 {
00071 xHoF = XMLNode::createXMLTopNode("HallOfFame");
00072 std::stringstream sValue;
00073 sValue << this->hofSize_;
00074 xHoF.addAttribute("size", uint2str(hofSize_).c_str());
00075
00076 XMLNode xInd;
00077 for(uint i = 0; i < hofSize_; i++) {
00078 bestIndividuals_[i]->write(xInd);
00079 xInd.addAttribute("gen", uint2str(bestGenerations_[i]).c_str());
00080 xHoF.addChild(xInd);
00081 }
00082 }
00083
00084
00085 void HallOfFame::read(XMLNode& xHof)
00086 {
00087 std::stringstream ss;
00088 ss << xHof.getAttribute("size");
00089 ss >> hofSize_;
00090 ss.clear(); ss.str("");
00091
00092 bestIndividuals_.resize(hofSize_);
00093 bestGenerations_.resize(hofSize_);
00094 bEmpty_ = false;
00095 lastChangeGen_ = 0;
00096
00097 XMLNode xInd;
00098 for(uint i = 0; i < hofSize_; i++) {
00099 xInd = xHof.getChildNode(i);
00100 ss << xInd.getAttribute("gen");
00101 ss >> bestGenerations_[i];
00102 ss.clear(); ss.str("");
00103 bestIndividuals_[i] = (IndividualP) state_->getIndividualObject()->copy();
00104 bestIndividuals_[i]->read(xInd);
00105
00106 if(lastChangeGen_ < bestGenerations_[i])
00107 lastChangeGen_ = bestGenerations_[i];
00108 }
00109 }