00001 #ifndef BitString_h
00002 #define BitString_h
00003
00004 #include "../Genotype.h"
00005 #include "BitStringCrsOnePoint.h"
00006 #include "BitStringMutSimple.h"
00007 #include "BitStringMutMix.h"
00008 #include "BitStringCrsUniform.h"
00009 #include<sstream>
00010
00011 namespace BitString
00012 {
00013
00017 class BitString : public Genotype
00018 {
00019 protected:
00020 uint nBits_;
00021
00022 public:
00023 std::vector<bool> bits;
00024
00025 BitString(uint nBits = 0)
00026 { name_ = "BitString";
00027 nBits_ = nBits;
00028 }
00029
00030 void registerParameters(StateP state)
00031 {
00032 if(nBits_ == 0)
00033 nBits_ = 10;
00034 registerParameter(state, "size", (voidP) new uint(nBits_), ECF::UINT);
00035 }
00036
00037 bool initialize(StateP state)
00038 {
00039 if(!isParameterDefined(state, "size")) {
00040 state->getLogger()->log(1, "Error: BitString genotype size not defined!");
00041 throw("");
00042 }
00043
00044 voidP sizep = getParameterValue(state, "size");
00045 nBits_ = *((uint*) sizep.get());
00046
00047 if(nBits_ < 1) {
00048 state->getLogger()->log(1, "Error: invalid size for BitString genotype!");
00049 throw("");
00050 }
00051
00052 bits.resize(nBits_);
00053 for(uint i = 0; i < bits.size(); i++){
00054 bits[i] = rand() % 2 ? true:false;
00055 }
00056 return true;
00057 }
00058
00059 BitString* copy()
00060 {
00061 BitString *newObject = new BitString(*this);
00062 return newObject;
00063 }
00064
00065 std::vector<CrossoverOpP> getCrossoverOp()
00066 {
00067 std::vector<CrossoverOpP> crx;
00068 crx.push_back(static_cast<CrossoverOpP> (new BitStringCrsOnePoint));
00069 crx.push_back(static_cast<CrossoverOpP> (new BitStringCrsUniform));
00070 return crx;
00071 }
00072
00073 std::vector<MutationOpP> getMutationOp()
00074 {
00075 std::vector<MutationOpP> mut;
00076 mut.push_back(static_cast<MutationOpP> (new BitStringMutSimple));
00077 mut.push_back(static_cast<MutationOpP> (new BitStringMutMix));
00078 return mut;
00079 }
00080
00081 void write(XMLNode &xBitString)
00082 {
00083 xBitString = XMLNode::createXMLTopNode("BitString");
00084 std::stringstream sValue;
00085 sValue << bits.size();
00086 xBitString.addAttribute("size", sValue.str().c_str());
00087
00088 sValue.str("");
00089 for(uint iBit = 0; iBit < bits.size(); iBit++)
00090 sValue << ((bits[iBit] == true) ? '1' : '0');
00091 xBitString.addText(sValue.str().c_str());
00092 }
00093
00094 void read(XMLNode &xBitString)
00095 {
00096 XMLCSTR xBits = xBitString.getText();
00097 for(uint iBit = 0; iBit < bits.size(); iBit++)
00098 bits[iBit] = (xBits[iBit] == '0') ? false : true;
00099 }
00100 };
00101 }
00102
00103 typedef boost::shared_ptr<BitString::BitString> BitStringP;
00104
00105 #endif // BitString_h
00106