00001 #include "ECF_base.h"
00002 #include<sstream>
00003
00004
00005 Individual::Individual(StateP state)
00006 {
00007 cid = 0;
00008 initialize(state);
00009 }
00010
00011
00012 bool Individual::initialize(StateP state)
00013 {
00014 state_ = state;
00015 this->clear();
00016
00017
00018 for(uint i = 0; i < state->getGenotypes().size(); i++) {
00019 this->push_back(static_cast<GenotypeP> (state->getGenotypes()[i]->copy()));
00020 (*this)[i]->setGenotypeId(i);
00021 }
00022
00023
00024 for(uint i = 0; i < this->size(); i++)
00025 (*this)[i]->initialize(state);
00026
00027 return true;
00028 }
00029
00030
00031 Individual* Individual::copy()
00032 {
00033 Individual *c = new Individual;
00034 c->state_ = state_;
00035 c->cid = cid;
00036 if(fitness)
00037 c->fitness = (FitnessP) this->fitness->copy();
00038 for(uint i = 0; i < this->size(); i++)
00039 c->push_back((GenotypeP) (this->at(i)->copy()));
00040 return c;
00041 }
00042
00043
00044 GenotypeP Individual::getGenotype(uint index)
00045 {
00046 return this->at(index);
00047 }
00048
00049
00056 void Individual::write(XMLNode &xIndividual)
00057 {
00058 xIndividual = XMLNode::createXMLTopNode("Individual");
00059 std::stringstream sValue;
00060 sValue << this->size();
00061 xIndividual.addAttribute("size", sValue.str().c_str());
00062
00063 if (fitness) {
00064 XMLNode xFitness;
00065 fitness->write(xFitness);
00066 xIndividual.addChild(xFitness);
00067 } else {
00068 XMLNode xFitness = XMLNode::createXMLTopNode("Fitness");
00069 xIndividual.addChild(xFitness);
00070 }
00071
00072 XMLNode xGenotype;
00073 for(uint i = 0; i < this->size(); i++) {
00074 this->at(i)->write(xGenotype);
00075 xIndividual.addChild(xGenotype);
00076 }
00077 }
00078
00079
00080 std::string Individual::toString()
00081 {
00082 XMLNode xInd;
00083 write(xInd);
00084 char *s = xInd.createXMLString();
00085 std::string out(s);
00086 freeXMLString(s);
00087 return out;
00088 }
00089
00090
00097 void Individual::read(XMLNode &xIndividual)
00098 {
00099 XMLNode xFit = xIndividual.getChildNode(0);
00100
00101 if(!fitness)
00102 fitness = static_cast<FitnessP> (state_->getFitnessObject()->copy());
00103 this->fitness->read(xFit);
00104
00105 for(uint i = 0; i < this->size(); i++) {
00106 XMLNode xGen = xIndividual.getChildNode(i + 1);
00107 this->at(i)->read(xGen);
00108 }
00109 }