From 40ee7ad5aeadeb9823e1cd6e1218a1999c608a65 Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Mon, 9 Jul 2012 08:39:37 -0600 Subject: New libgenetic. Genetic algorithms, only good. --- src/phenotypebinary.cpp | 101 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 src/phenotypebinary.cpp (limited to 'src/phenotypebinary.cpp') diff --git a/src/phenotypebinary.cpp b/src/phenotypebinary.cpp new file mode 100644 index 0000000..d16588b --- /dev/null +++ b/src/phenotypebinary.cpp @@ -0,0 +1,101 @@ +#include "genetic/phenotypebinary.h" + +#include +#include + +using namespace Bu; + +// Bits per word +#define BPW (sizeof(uint_fast32_t)*8) +#define wordsForBits( x ) (((x)/BPW)+(((x)%BPW)?1:0)) +#define wordWithBit( x ) ((x)/BPW) + +Genetic::PhenotypeBinary::PhenotypeBinary( int iSize, bool bRandom ) : + iSize( iSize ), + iWords( wordsForBits(iSize) ), + aGenes( NULL ) +{ + aGenes = new uint_fast32_t[iWords]; + if( bRandom ) + randomize(); +} + +Genetic::PhenotypeBinary::~PhenotypeBinary() +{ + delete[] aGenes; +} + +Genetic::Phenotype &Genetic::PhenotypeBinary::randomize() +{ + for( int j = 0; j < iWords*sizeof(uint_fast32_t); j++ ) + { + ((uint8_t *)aGenes)[j] = (uint8_t)Bu::Random::rand(); + } + + return *this; +} + +void Genetic::PhenotypeBinary::mutate( int iLocation, float fMagnitude ) +{ + if( fMagnitude > -0.5 && fMagnitude < 0.5 ) + return; + + aGenes[wordWithBit(iLocation)] = + (aGenes[wordWithBit(iLocation)]&(~(1<<((iLocation)%BPW)))) | + ((~aGenes[wordWithBit(iLocation)])&((1<<((iLocation)%BPW)))); +} + +Genetic::Phenotype *Genetic::PhenotypeBinary::makeEmptyOffspring( + int iNewSize ) +{ + if( iNewSize < 0 ) + iNewSize = iSize; + + return new PhenotypeBinary( iSize ); +} + +Genetic::Phenotype &Genetic::PhenotypeBinary::copyFrom( const Phenotype &rSrc, + int iStart, int iCount, int iDest ) +{ + const PhenotypeBinary &rbSrc = + dynamic_cast(rSrc); + if( iDest < 0 ) + iDest = iStart; + + // Fist draft, very sloppy: bit by bit copy, this is stupid, but easy + for( int j = 0; j < iCount; j++ ) + { + int wd = wordWithBit(j+iDest); + int ws = wordWithBit(j+iStart); + if( (rbSrc.aGenes[ws]&(1<<((j+iStart)%BPW))) == 0) + { + aGenes[wd] &= ~(1<<((j+iDest)%BPW)); + } + else + { + aGenes[wd] |= (1<<((j+iDest)%BPW)); + } + } + + /* + iStart%BPW + int iWords = wordsForBits(iCount); + for( int j = wordWithBit(iStart); j < iWords; j++ ) + { + } + */ + + return *this; +} + +Bu::String Genetic::PhenotypeBinary::toString() +{ + Bu::String sRet; + for( int j = 0; j < iSize; j++ ) + { + sRet += (aGenes[j/BPW]&(1<<(j%BPW)))?'1':'0'; + } + + return sRet; +} + -- cgit v1.2.3