Added changes mainly by Marc

This commit is contained in:
jmerelo 1999-11-22 09:47:32 +00:00
commit 91f5ddbdaa
28 changed files with 2400 additions and 1595 deletions

View file

@ -11,13 +11,14 @@ libeoincdir = $(includedir)/eo
libeoinc_HEADERS = EO.h eo eo1d.h eo2d.h eo2dVector.h eoAged.h eoAlgo.h\ libeoinc_HEADERS = EO.h eo eo1d.h eo2d.h eo2dVector.h eoAged.h eoAlgo.h\
eoAtomBitFlip.h eoAtomCreep.h eoAtomMutation.h eoAtomMutator.h \ eoAtomBitFlip.h eoAtomCreep.h eoAtomMutation.h eoAtomMutator.h \
eoAtomRandom.h eoBin.h eoBitOp.h eoBitOpFactory.h eoBreeder.h\ eoAtomRandom.h eoBin.h eoBitOp.h eoBitOpFactory.h eoBreeder.h\
eoData.h eoDup.h eoESChrom.h eoESFullChrom.h eoESFullMut.h eoEasyEA.h\ eoData.h eoDetTournament.h eoDup.h eoESChrom.h eoESFullChrom.h eoESFullMut.h eoEasyEA.h\
eoEvalFunc.h eoEvalFuncPtr.h eoEvaluator.h eoFitTerm.h eoFitness.h\ eoEvalFunc.h eoEvalFuncPtr.h eoFitTerm.h eoFitness.h\
eoGenTerm.h eoGeneration.h eoID.h eoInclusion.h eoInsertion.h\ eoGenTerm.h eoGeneration.h eoID.h eoInclusion.h eoInsertion.h\
eoKill.h eoLottery.h eoMultiMonOp.h eoMutation.h eoNegExp.h\ eoKill.h eoLottery.h eoMerge.h eoMultiBinOp.h eoMultiMonOp.h eoMutation.h eoNegExp.h\
eoNonUniform.h eoNormal.h eoObject.h eoOp.h eoOpSelector.h\ eoNonUniform.h eoNormal.h eoObject.h eoOp.h eoOpSelector.h\
eoParser.h eoPersistent.h eoPop.h eoPopOps.h eoPrintable.h\ eoParser.h eoPersistent.h eoPop.h eoPopOps.h eoPrintable.h\
eoProblem.h eoProportionalOpSel.h eoRNG.h eoRnd.h eoString.h\ eoProblem.h eoProportionalOpSel.h eoRNG.h eoRnd.h eoString.h\
eoTerm.h eoTranspose.h eoUniform.h eoVector.h eoXOver2.h eoStochTournament.h eoTerm.h eoTranspose.h eoUniform.h \
eoUniformSelect.h eoUniformXOver.h eoVector.h eoXOver2.h

View file

@ -48,21 +48,23 @@
#include <eoOp.h> #include <eoOp.h>
#include <eoMultiMonOp.h> #include <eoMultiMonOp.h>
#include <eoMultiBinOp.h>
#include <eoDup.h> #include <eoDup.h>
#include <eoKill.h> #include <eoKill.h>
#include <eoTranspose.h> #include <eoTranspose.h>
#include <eoXOver2.h> #include <eoXOver2.h>
#include <eoUniformXOver.h>
#include <eoMutation.h> #include <eoMutation.h>
#include <eoPop.h> #include <eoPop.h>
#include <eoPopOps.h> #include <eoPopOps.h>
#include <eoMerge.h>
#include <eoBitOp.h> #include <eoBitOp.h>
// Evaluation functions // Evaluation functions
#include <eoEvalFunc.h> #include <eoEvalFunc.h>
#include <eoEvalFuncPtr.h> #include <eoEvalFuncPtr.h>
#include <eoEvaluator.h>
// Terminators // Terminators
#include <eoTerm.h> #include <eoTerm.h>
@ -70,6 +72,9 @@
#include <eoFitTerm.h> #include <eoFitTerm.h>
// Selection and reproduction stuff // Selection and reproduction stuff
#include <eoUniformSelect.h>
#include <eoDetTournament.h>
#include <eoStochTournament.h>
#include <eoLottery.h> #include <eoLottery.h>
#include <eoBreeder.h> #include <eoBreeder.h>
#include <eoInsertion.h> #include <eoInsertion.h>

View file

@ -1,7 +1,7 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoAtomCreep.h // eoAtomBitFlip.h
// Increments or decrements by one a single element // Increments or decrements by one a single element
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
@ -22,8 +22,8 @@
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOATOMCREEP_H #ifndef _EOATOMBITFLIP_H
#define _EOATOMCREEP_H #define _EOATOMBITFLIP_H
/** Flips a single bit /** Flips a single bit
*/ */

View file

@ -1,16 +1,16 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoBitOp.h // eoBitOp.h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef eoBitOp_h #ifndef eoBitOp_h
#define eoBitOp_h #define eoBitOp_h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <algorithm> // swap_ranges #include <algorithm> // swap_ranges
#include <eoUniform.h> // eoUniform #include <eoUniform.h> // eoUniform
#include <eoBin.h> // eoBin #include <eoBin.h> // eoBin
#include <eoOp.h> // eoMonOp #include <eoOp.h> // eoMonOp
/** @name BitWise Genetic operators /** @name BitWise Genetic operators
@ -24,334 +24,301 @@ have a factory that knows how to build them from a description
@see eoBitOpFactory @see eoBitOpFactory
*/ */
//@{ //@{
/** eoBinRandom --> mofify a chromosome in a random way */
template<class Chrom> class eoBinRandom: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinRandom"; }
/**
* Randomizes a cromosome.
* @param chrom The cromosome to be randomize.
*/
void operator()(Chrom& chrom) const
{
eoUniform<float> uniform(0.0, 1.0);
for (unsigned i = 0; i < chrom.size(); i++)
chrom[i] = (uniform() < 0.5) ? false : true;
}
};
/** eoBinBitFlip --> chages a bit */
template<class Chrom> class eoBinBitFlip: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinBitFlip"; }
/**
* Change one bit.
* @param chrom The cromosome which one bit is going to be changed.
*/
void operator()(Chrom& chrom) const
{
eoUniform<int> uniform(0, chrom.size());
unsigned i = uniform();
chrom[i] = (chrom[i]) ? false : true;
}
};
/** eoBinMutation --> classical mutation */
template<class Chrom> class eoBinMutation: public eoMonOp<Chrom>
{
public:
/**
* (Default) Constructor.
* @param _rate Rate of mutation.
*/
eoBinMutation(const double& _rate = 0.01): rate(_rate), uniform(0.0, 1.0) {}
/// The class name.
string className() const { return "eoBinMutation"; }
/**
* Mutate a chromosome.
* @param chrom The chromosome to be mutated.
*/
void operator()(Chrom& chrom) const
{
for (unsigned i = 0; i < chrom.size(); i++)
if (uniform() < rate)
chrom[i] = !chrom[i];
}
private:
double rate;
mutable eoUniform<float> uniform;
};
/** eoBinInversion: inverts the bits of the chromosome between an interval */
template<class Chrom> class eoBinInversion: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinInversion"; }
/**
* Inverts a range of bits in a binary chromosome.
* @param chrom The chromosome whos bits are going to be inverted (a range).
*/
void operator()(Chrom& chrom) const
{
eoUniform<unsigned> uniform(0, chrom.size() + 1);
unsigned u1 = uniform(), u2;
do u2 = uniform(); while (u1 == u2);
unsigned r1 = min(u1, u2), r2 = max(u1, u2);
reverse(chrom.begin() + r1, chrom.begin() + r2);
}
};
/** eoBinNext --> next binary value */
template<class Chrom> class eoBinNext: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinNext"; }
/**
* Change the bit string x to be x+1.
* @param chrom The chromosome to be added one.
*/
void operator()(Chrom& chrom) const
{
for (int i = chrom.size() - 1; i >= 0; i--)
if (chrom[i])
{
chrom[i] = 0;
continue;
}
else
{
chrom[i] = 1;
break;
}
}
};
/** eoBinPrev --> previos binary value */
template<class Chrom> class eoBinPrev: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinPrev"; }
/**
* Change the bit string x to be x-1.
* @param chrom The chromosome to be substracted one.
*/
void operator()(Chrom& chrom) const
{
for (int i = chrom.size() - 1; i >= 0; i--)
if (chrom[i])
{
chrom[i] = 0;
break;
}
else
{
chrom[i] = 1;
continue;
}
}
};
/** eoBinCrossover --> classic crossover */
template<class Chrom> class eoBinCrossover: public eoBinOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinCrossover"; }
/**
* 2-point crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
eoUniform<unsigned> uniform(1, min(chrom1.size(), chrom2.size()));
swap_ranges(chrom1.begin(), chrom1.begin() + uniform(), chrom2.begin());
}
};
/** eoBinNxOver --> n-point crossover */
template<class Chrom> class eoBinNxOver: public eoBinOp<Chrom>
{
public:
/// (Defualt) Constructor.
eoBinNxOver(const unsigned& _num_points = 2): num_points(_num_points)
{
if (num_points < 1)
runtime_error("NxOver --> invalid number of points");
}
/// The class name.
string className() const { return "eoBinNxOver"; }
/**
* n-point crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
unsigned max_size = min(chrom1.size(), chrom2.size());
unsigned max_points = min(max_size - 1, num_points);
vector<bool> points(max_size, false);
eoUniform<unsigned> uniform(1, max_size);
// select ranges of bits to swap
do {
unsigned bit = uniform();
if (points[bit])
continue;
else
{
points[bit] = true;
max_points--;
}
} while (max_points);
// swap bits between chromosomes
bool change = false;
for (unsigned bit = 1; bit < points.size(); bit++)
{
if (points[bit])
change = !change;
if (change)
swap(chrom1[bit], chrom2[bit]);
}
}
private:
unsigned num_points;
};
/** eoBinGxOver --> gene crossover */
template<class Chrom> class eoBinGxOver: public eoBinOp<Chrom>
{
public:
/// Constructor.
eoBinGxOver(const unsigned _gene_size, const unsigned _num_points = 2):
gene_size(_gene_size), num_points(_num_points)
{
if (gene_size < 1)
runtime_error("GxOver --> invalid gene size");
if (num_points < 1)
runtime_error("GxOver --> invalid number of points");
}
/// The class name
string className() const { return "eoBinGxOver"; }
/**
* Gene crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
unsigned max_genes = min(chrom1.size(), chrom2.size()) / gene_size;
unsigned cut_genes = min(max_genes, num_points);
vector<bool> points(max_genes, false);
eoUniform<unsigned> uniform(0, max_genes);
// selects genes to swap
do {
unsigned bit = uniform();
if (points[bit])
continue;
else
{
points[bit] = true;
cut_genes--;
}
} while (cut_genes);
// swaps genes
for (unsigned i = 0; i < points.size(); i++)
if (points[i])
swap_ranges(chrom1.begin() + i * gene_size,
chrom1.begin() + i * gene_size + gene_size,
chrom2.begin() + i * gene_size);
}
private:
unsigned gene_size;
unsigned num_points;
};
/** eoBinRandom --> mofify a chromosome in a random way */
template<class Chrom> class eoBinRandom: public eoMonOp<Chrom> //-----------------------------------------------------------------------------
{ //@}
public: #endif eoBitOp_h
/// The class name.
string className() const { return "eoBinRandom"; }
/**
* Randomizes a cromosome.
* @param chrom The cromosome to be randomize.
*/
void operator()(Chrom& chrom) const
{
eoUniform<float> uniform(0.0, 1.0);
for (unsigned i = 0; i < chrom.size(); i++)
chrom[i] = (uniform() < 0.5) ? false : true;
}
};
/** eoBinBitFlip --> chages a bit */
template<class Chrom> class eoBinBitFlip: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinBitFlip"; }
/**
* Change one bit.
* @param chrom The cromosome which one bit is going to be changed.
*/
void operator()(Chrom& chrom) const
{
eoUniform<int> uniform(0, chrom.size());
unsigned i = uniform();
chrom[i] = (chrom[i]) ? false : true;
}
};
/** eoBinMutation --> classical mutation */
template<class Chrom> class eoBinMutation: public eoMonOp<Chrom>
{
public:
/**
* (Default) Constructor.
* @param _rate Rate of mutation.
*/
eoBinMutation(const double& _rate = 0.01): rate(_rate), uniform(0.0, 1.0) {}
/// The class name.
string className() const { return "eoBinMutation"; }
/**
* Mutate a chromosome.
* @param chrom The chromosome to be mutated.
*/
void operator()(Chrom& chrom) const
{
for (unsigned i = 0; i < chrom.size(); i++)
if (uniform() < rate)
chrom[i] = !chrom[i];
}
private:
double rate;
mutable eoUniform<float> uniform;
};
/** eoBinInversion: inverts the bits of the chromosome between an interval */
template<class Chrom> class eoBinInversion: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinInversion"; }
/**
* Inverts a range of bits in a binary chromosome.
* @param chrom The chromosome whos bits are going to be inverted (a range).
*/
void operator()(Chrom& chrom) const
{
eoUniform<unsigned> uniform(0, chrom.size() + 1);
unsigned u1 = uniform(), u2;
do u2 = uniform(); while (u1 == u2);
unsigned r1 = min(u1, u2), r2 = max(u1, u2);
reverse(chrom.begin() + r1, chrom.begin() + r2);
}
};
/** eoBinNext --> next binary value */
template<class Chrom> class eoBinNext: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinNext"; }
/**
* Change the bit string x to be x+1.
* @param chrom The chromosome to be added one.
*/
void operator()(Chrom& chrom) const
{
for (int i = chrom.size() - 1; i >= 0; i--)
if (chrom[i])
{
chrom[i] = 0;
continue;
}
else
{
chrom[i] = 1;
break;
}
}
};
/** eoBinPrev --> previos binary value */
template<class Chrom> class eoBinPrev: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinPrev"; }
/**
* Change the bit string x to be x-1.
* @param chrom The chromosome to be substracted one.
*/
void operator()(Chrom& chrom) const
{
for (int i = chrom.size() - 1; i >= 0; i--)
if (chrom[i])
{
chrom[i] = 0;
break;
}
else
{
chrom[i] = 1;
continue;
}
}
};
/** eoBinCrossover --> classic crossover */
template<class Chrom> class eoBinCrossover: public eoBinOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinCrossover"; }
/**
* 2-point crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
eoUniform<unsigned> uniform(1, min(chrom1.size(), chrom2.size()));
swap_ranges(chrom1.begin(), chrom1.begin() + uniform(), chrom2.begin());
}
};
/** eoBinNxOver --> n-point crossover */
template<class Chrom> class eoBinNxOver: public eoBinOp<Chrom>
{
public:
/// (Defualt) Constructor.
eoBinNxOver(const unsigned& _num_points = 2): num_points(_num_points)
{
if (num_points < 1)
runtime_error("NxOver --> invalid number of points");
}
/// The class name.
string className() const { return "eoBinNxOver"; }
/**
* n-point crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
unsigned max_size = min(chrom1.size(), chrom2.size());
unsigned max_points = min(max_size - 1, num_points);
vector<bool> points(max_size, false);
eoUniform<unsigned> uniform(1, max_size);
// select ranges of bits to swap
do {
unsigned bit = uniform();
if (points[bit])
continue;
else
{
points[bit] = true;
max_points--;
}
} while (max_points);
// swap bits between chromosomes
bool change = false;
for (unsigned bit = 1; bit < points.size(); bit++)
{
if (points[bit])
change = !change;
if (change)
swap(chrom1[bit], chrom2[bit]);
}
}
private:
unsigned num_points;
};
/** eoBinGxOver --> gene crossover */
template<class Chrom> class eoBinGxOver: public eoBinOp<Chrom>
{
public:
/// Constructor.
eoBinGxOver(const unsigned _gene_size, const unsigned _num_points = 2):
gene_size(_gene_size), num_points(_num_points)
{
if (gene_size < 1)
runtime_error("GxOver --> invalid gene size");
if (num_points < 1)
runtime_error("GxOver --> invalid number of points");
}
/// The class name
string className() const { return "eoBinGxOver"; }
/**
* Gene crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
unsigned max_genes = min(chrom1.size(), chrom2.size()) / gene_size;
unsigned cut_genes = min(max_genes, num_points);
vector<bool> points(max_genes, false);
eoUniform<unsigned> uniform(0, max_genes);
// selects genes to swap
do {
unsigned bit = uniform();
if (points[bit])
continue;
else
{
points[bit] = true;
cut_genes--;
}
} while (cut_genes);
// swaps genes
for (unsigned i = 0; i < points.size(); i++)
if (points[i])
swap_ranges(chrom1.begin() + i * gene_size,
chrom1.begin() + i * gene_size + gene_size,
chrom2.begin() + i * gene_size);
}
private:
unsigned gene_size;
unsigned num_points;
};
/** eoBinUxOver --> uniform crossover */
template<class Chrom> class eoBinUxOver: public eoBinOp<Chrom>
{
public:
/// (Default) Constructor.
eoBinUxOver(const float _rate = 0.5): rate(_rate)
{
if (rate < 0 || rate > 1)
runtime_error("UxOver --> invalid rate");
}
/// The class name.
string className() const { return "eoBinUxOver"; }
/**
* Uniform crossover for binary chromosomes.
* @param chrom1 The first chromosome.
* @param chrom2 The first chromosome.
*/
void operator()(Chrom& chrom1, Chrom& chrom2) const
{
unsigned min_size = min(chrom1.size(), chrom2.size());
eoUniform<float> uniform(0, 1);
for (unsigned bit = 0; bit < min_size; bit++)
if (uniform() < rate)
swap(chrom1[bit], chrom2[bit]);
}
public:
float rate;
};
//-----------------------------------------------------------------------------
//@}
#endif eoBitOp_h

View file

@ -1,82 +1,103 @@
//----------------------------------------------------------------------------- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
// eoBreeder.h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoBreeder.h
#ifndef eoBreeder_h // Takes two populations and mixes them
#define eoBreeder_h // (c) GeNeura Team, 1998
/*
//----------------------------------------------------------------------------- This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
#include <vector> // vector License as published by the Free Software Foundation; either
#include <eoUniform.h> // eoUniform version 2 of the License, or (at your option) any later version.
#include <eoOp.h> // eoOp, eoMonOp, eoBinOp
#include <eoPop.h> // eoPop This library is distributed in the hope that it will be useful,
#include <eoPopOps.h> // eoTransform but WITHOUT ANY WARRANTY; without even the implied warranty of
#include <eoOpSelector.h> // eoOpSelector MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
using namespace std;
You should have received a copy of the GNU Lesser General Public
/***************************************************************************** License along with this library; if not, write to the Free Software
* eoBreeder: transforms a population using genetic operators. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* For every operator there is a rated to be applyed. *
*****************************************************************************/ Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
template<class Chrom> class eoBreeder: public eoTransform<Chrom> //-----------------------------------------------------------------------------
{
public: #ifndef eoBreeder_h
/// Default constructor. #define eoBreeder_h
eoBreeder( eoOpSelector<Chrom>& _opSel): opSel( _opSel ) {}
//-----------------------------------------------------------------------------
/// Destructor.
virtual ~eoBreeder() {} #include <vector> // vector
#include <eoUniform.h> // eoUniform
/** #include <eoOp.h> // eoOp, eoMonOp, eoBinOp
* Transforms a population. #include <eoPop.h> // eoPop
* @param pop The population to be transformed. #include <eoPopOps.h> // eoTransform
*/ #include <eoOpSelector.h> // eoOpSelector
void operator()(eoPop<Chrom>& pop)
{ using namespace std;
for (unsigned i = 0; i < pop.size(); i++) {
eoOp<Chrom>* op = opSel.Op(); /*****************************************************************************
switch (op->readArity()) { * eoBreeder: transforms a population using genetic operators. *
case unary: * For every operator there is a rated to be applyed. *
{ *****************************************************************************/
eoMonOp<Chrom>* monop = static_cast<eoMonOp<Chrom>* >(op);
(*monop)( pop[i] ); template<class Chrom> class eoBreeder: public eoMonPopOp<Chrom>
break; {
} public:
case binary: /// Default constructor.
{ eoBreeder( eoOpSelector<Chrom>& _opSel): opSel( _opSel ) {}
eoBinOp<Chrom>* binop = static_cast<eoBinOp<Chrom>* >(op);
eoUniform<unsigned> u(0, pop.size() ); /// Destructor.
(*binop)(pop[i], pop[ u() ] ); virtual ~eoBreeder() {}
break;
} /**
case Nary: * Transforms a population.
{ * @param pop The population to be transformed.
eoNaryOp<Chrom>* Nop = static_cast<eoNaryOp<Chrom>* >(op); */
eoUniform<unsigned> u(0, pop.size() ); void operator()(eoPop<Chrom>& pop)
eoPop<Chrom> inVec, outVec; {
inVec.push_back( pop[i] ); for (unsigned i = 0; i < pop.size(); i++) {
unsigned numberOfOperands = u(); eoOp<Chrom>* op = opSel.Op();
for ( unsigned i = 0; i < numberOfOperands; i ++ ) { switch (op->readArity()) {
inVec.push_back( pop[ u() ] ); case unary:
} {
(*Nop)( inVec, outVec ); eoMonOp<Chrom>* monop = static_cast<eoMonOp<Chrom>* >(op);
break; (*monop)( pop[i] );
} break;
} }
} case binary:
}; {
eoBinOp<Chrom>* binop = static_cast<eoBinOp<Chrom>* >(op);
/// The class name. eoUniform<unsigned> u(0, pop.size() );
string classname() const { return "eoBreeder"; } (*binop)(pop[i], pop[ u() ] );
break;
private: }
eoOpSelector<Chrom>& opSel; case Nary:
{
}; eoNaryOp<Chrom>* Nop = static_cast<eoNaryOp<Chrom>* >(op);
eoUniform<unsigned> u(0, pop.size() );
//----------------------------------------------------------------------------- eoPop<Chrom> inVec, outVec;
inVec.push_back( pop[i] );
#endif eoBreeder_h unsigned numberOfOperands = u();
for ( unsigned i = 0; i < numberOfOperands; i ++ ) {
inVec.push_back( pop[ u() ] );
}
(*Nop)( inVec, outVec );
break;
}
}
}
};
/// The class name.
string classname() const { return "eoBreeder"; }
private:
eoOpSelector<Chrom>& opSel;
};
//-----------------------------------------------------------------------------
#endif eoBreeder_h

78
eo/src/eoDetTournament.h Normal file
View file

@ -0,0 +1,78 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoDetTournament.h
// (c) GeNeura Team, 1998 - EEAAX 1999
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr
*/
//-----------------------------------------------------------------------------
#ifndef eoDetTournament_h
#define eoDetTournament_h
//-----------------------------------------------------------------------------
#include <functional> //
#include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include <eoRNG.h>
//-----------------------------------------------------------------------------
/** eoDetTournament: a selection method that selects ONE individual by
deterministic tournament
-MS- 24/10/99 */
//-----------------------------------------------------------------------------
template <class EOT> class eoDetTournament: public eoSelectOne<EOT>
{
public:
/// (Default) Constructor.
eoDetTournament(unsigned _Tsize = 2 ):eoSelectOne(), Tsize(_Tsize) {
// consistency check
if (Tsize < 2) {
cout << "Warning, Tournament size shoudl be >= 2\nAdjusted\n";
Tsize = 2;
}
}
/** DANGER: if you want to be able to minimize as well as maximizem
DON'T cast the fitness to a float, use the EOT comparator! */
virtual const EOT& operator()(const eoPop<EOT>& pop) {
unsigned best = rng.random(pop.size()); // random individual
for (unsigned i = 0; i<Tsize-1; i++) {
unsigned tmp = rng.random(pop.size());
if (pop[best] < pop[tmp])
best = tmp;
}
return pop[best] ;
}
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoDetTournament";};
private:
unsigned Tsize;
};
//-----------------------------------------------------------------------------
#endif eoDetTournament_h

View file

@ -119,9 +119,9 @@ class eoESFullChrom : public eoVector<double, fitT> {
cout << "WARNING, Number of Standard Deviations > Number of Object Variables\nAdjusted!\n"; cout << "WARNING, Number of Standard Deviations > Number of Object Variables\nAdjusted!\n";
num_sigma = num_genes; num_sigma = num_genes;
// modify the Param value - so .status is OK // modify the Param value - so .status is OK
char sloc[20]; ostrstream sloc;
sprintf(sloc, "%d", num_genes); sloc << num_genes;
parser.setParamValue("--NbSigma", sloc); parser.setParamValue("--NbSigma", sloc.str());
} }
// adjust the sizes!!! // adjust the sizes!!!
resize(num_genes); resize(num_genes);

View file

@ -1,243 +1,243 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoESMute.h : ES mutation // eoESMute.h : ES mutation
// (c) GeNeura Team, 1998 for the EO part // (c) GeNeura Team, 1998 for the EO part
// Th. Baeck 1994 and EEAAX 1999 for the ES part // Th. Baeck 1994 and EEAAX 1999 for the ES part
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
marc.schoenauer@polytechnique.fr marc.schoenauer@polytechnique.fr
http://eeaax.cmap.polytchnique.fr/ http://eeaax.cmap.polytchnique.fr/
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOESMUT_H #ifndef _EOESMUT_H
#define _EOESMUT_H #define _EOESMUT_H
#include <eoParser.h> #include <eoParser.h>
#include <eoRNG.h> #include <eoRNG.h>
#include <cmath> // for exp #include <cmath> // for exp
#include <eoESFullChrom.h> #include <eoESFullChrom.h>
#include <eoOp.h> #include <eoOp.h>
const double ES_SIGEPS = 1.0e-40; /* ES lower bound for sigma values */ const double ES_SIGEPS = 1.0e-40; /* ES lower bound for sigma values */
// should not be a parameter ... // should not be a parameter ...
/** ES-style mutation in the large: Obviously, valid only for eoESInd /** ES-style mutation in the large: Obviously, valid only for eoESInd
*/ */
template <class fitT> template <class fitT>
class eoESMutate: public eoMonOp< eoESFullChrom<fitT> > { class eoESMutate: public eoMonOp< eoESFullChrom<fitT> > {
public: public:
/// ///
eoESMutate( double _TauLcl, double _TauGlb, double _TauBeta ) eoESMutate( double _TauLcl, double _TauGlb, double _TauBeta )
: eoMonOp< eoESFullChrom<fitT> >( ), TauLcl(_TauLcl), TauGlb(_TauGlb), : eoMonOp< eoESFullChrom<fitT> >( ), TauLcl(_TauLcl), TauGlb(_TauGlb),
TauBeta(_TauBeta) {}; TauBeta(_TauBeta) {};
/* The parser constructor /* The parser constructor
*/ */
eoESMutate(Parser & parser, unsigned _stdDevLength, unsigned _size, bool _correlated ): eoESMutate(Parser & parser, unsigned _stdDevLength, unsigned _size, bool _correlated ):
eoMonOp< eoESFullChrom<fitT> >( ) { eoMonOp< eoESFullChrom<fitT> >( ) {
parser.AddTitle("Parameters of ES mutation (before renormalization)"); parser.AddTitle("Parameters of ES mutation (before renormalization)");
try { // we know that there is at least 1 std dev. try { // we know that there is at least 1 std dev.
if (_stdDevLength == 1) { if (_stdDevLength == 1) {
TauLcl = parser.getInt("-Ml", "--TauLcl", "1", TauLcl = parser.getInt("-Ml", "--TauLcl", "1",
"TauLcl, Mutation rate for the only Std Dev." ); "TauLcl, Mutation rate for the only Std Dev." );
// different normalization in that case -- Thomas Baeck // different normalization in that case -- Thomas Baeck
TauLcl /= sqrt((double) _size); TauLcl /= sqrt((double) _size);
} }
else { /* more than 1 std dev */ else { /* more than 1 std dev */
TauLcl = parser.getFloat("-Ml", "--TauLcl", "1", TauLcl = parser.getFloat("-Ml", "--TauLcl", "1",
"Local mutation rate for Std Dev." ); "Local mutation rate for Std Dev." );
TauGlb = parser.getFloat("-Mg", "--TauGlb", "1", TauGlb = parser.getFloat("-Mg", "--TauGlb", "1",
"Global mutation rate for Std Dev." ); "Global mutation rate for Std Dev." );
// renormalization // renormalization
TauLcl /= sqrt( 2.0 * sqrt( (double)_size ) ); TauLcl /= sqrt( 2.0 * sqrt( (double)_size ) );
TauGlb /= sqrt( 2.0 * ( (double) _size ) ); TauGlb /= sqrt( 2.0 * ( (double) _size ) );
if ( _correlated ) { // Correlated Mutations if ( _correlated ) { // Correlated Mutations
TauBeta = parser.getFloat("-Mb", "--TauBeta", "0.0873", TauBeta = parser.getFloat("-Mb", "--TauBeta", "0.0873",
"Mutation rate for corr. coeff." ); "Mutation rate for corr. coeff." );
// rotation angles: no normalization // rotation angles: no normalization
} }
} }
} }
catch (exception & e) catch (exception & e)
{ {
cout << e.what() << endl; cout << e.what() << endl;
parser.printHelp(); parser.printHelp();
exit(1); exit(1);
} }
}; };
/// needed virtual dtor /// needed virtual dtor
virtual ~eoESMutate() {}; virtual ~eoESMutate() {};
// virtual separation depending wether correlated mutations are present // virtual separation depending wether correlated mutations are present
virtual void operator() ( eoESFullChrom<fitT> & _eo ) const { virtual void operator() ( eoESFullChrom<fitT> & _eo ) const {
if (_eo.CorCffLength()) if (_eo.CorCffLength())
CorrelatedMutation(_eo); CorrelatedMutation(_eo);
else else
StandardMutation(_eo); StandardMutation(_eo);
} }
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject readFrom and printOn are directly inherited from eoObject
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
virtual string className() const {return "eoESMutate";}; virtual string className() const {return "eoESMutate";};
private: private:
/// mutations - standard et correlated /// mutations - standard et correlated
// ========= // =========
/* /*
* Standard mutation of object variables and standard * Standard mutation of object variables and standard
* deviations in ESs. * deviations in ESs.
* If there are fewer different standard deviations available * If there are fewer different standard deviations available
* than the dimension of the objective function requires, the * than the dimension of the objective function requires, the
* last standard deviation is responsible for ALL remaining * last standard deviation is responsible for ALL remaining
* object variables. * object variables.
* Schwefel 1977: Numerische Optimierung von Computer-Modellen * Schwefel 1977: Numerische Optimierung von Computer-Modellen
* mittels der Evolutionsstrategie, pp. 165 ff. * mittels der Evolutionsstrategie, pp. 165 ff.
*/ */
virtual void StandardMutation( eoESFullChrom<fitT> & _eo ) const { virtual void StandardMutation( eoESFullChrom<fitT> & _eo ) const {
unsigned i,k; unsigned i,k;
double Glb, StdLoc; double Glb, StdLoc;
if (_eo.StdDevLength() == 1) { /* single StdDev -> No global factor */ if (_eo.StdDevLength() == 1) { /* single StdDev -> No global factor */
StdLoc = _eo.getStdDev(0); StdLoc = _eo.getStdDev(0);
StdLoc *= exp(TauLcl*rng.normal()); StdLoc *= exp(TauLcl*rng.normal());
if (StdLoc < ES_SIGEPS) if (StdLoc < ES_SIGEPS)
StdLoc = ES_SIGEPS; StdLoc = ES_SIGEPS;
_eo.setStdDev(0, StdLoc); _eo.setStdDev(0, StdLoc);
_eo.setGene( 0, _eo.getGene(0) + StdLoc*rng.normal()); _eo.setGene( 0, _eo.getGene(0) + StdLoc*rng.normal());
i = 1; i = 1;
} }
else { /* more than one std dev. */ else { /* more than one std dev. */
Glb = exp(TauGlb*rng.normal()); Glb = exp(TauGlb*rng.normal());
for (i = 0; i < _eo.length() && i < _eo.StdDevLength(); i++) { for (i = 0; i < _eo.length() && i < _eo.StdDevLength(); i++) {
StdLoc = _eo.getStdDev(i); StdLoc = _eo.getStdDev(i);
StdLoc *= Glb * exp(TauLcl*rng.normal()); StdLoc *= Glb * exp(TauLcl*rng.normal());
if (StdLoc < ES_SIGEPS) if (StdLoc < ES_SIGEPS)
StdLoc = ES_SIGEPS; StdLoc = ES_SIGEPS;
_eo.setStdDev(i, StdLoc); _eo.setStdDev(i, StdLoc);
_eo.setGene( i, _eo.getGene(i) + StdLoc*rng.normal()); _eo.setGene( i, _eo.getGene(i) + StdLoc*rng.normal());
} }
} }
// last object variables: same STdDev than the preceding one // last object variables: same STdDev than the preceding one
for (k = i; k < _eo.length(); k++) { for (k = i; k < _eo.length(); k++) {
_eo.setGene( k, _eo.getGene(k) + StdLoc*rng.normal() ); _eo.setGene( k, _eo.getGene(k) + StdLoc*rng.normal() );
} }
} }
/* /*
* Correlated mutations in ESs, according to the following * Correlated mutations in ESs, according to the following
* sources: * sources:
* H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80 * H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80
* p. 43, 1980 * p. 43, 1980
* G. Rudolph: Globale Optimierung mit parallelen Evolutions- * G. Rudolph: Globale Optimierung mit parallelen Evolutions-
* strategien, Diploma Thesis, University of Dortmund, 1990 * strategien, Diploma Thesis, University of Dortmund, 1990
*/ */
// Code from Thomas Baeck // Code from Thomas Baeck
virtual void CorrelatedMutation( eoESFullChrom<fitT> & _eo ) const { virtual void CorrelatedMutation( eoESFullChrom<fitT> & _eo ) const {
int i, k, n1, n2, nq; int i, k, n1, n2, nq;
double d1, d2, S, C, Glb; double d1, d2, S, C, Glb;
double tmp; double tmp;
/* /*
* First: mutate standard deviations (as above). * First: mutate standard deviations (as above).
*/ */
Glb = exp(TauGlb*rng.normal()); Glb = exp(TauGlb*rng.normal());
for (i = 0; i < _eo.StdDevLength(); i++) { for (i = 0; i < _eo.StdDevLength(); i++) {
tmp = _eo.getStdDev(i); tmp = _eo.getStdDev(i);
_eo.setStdDev( i, tmp*Glb*exp(TauLcl*rng.normal()) ); _eo.setStdDev( i, tmp*Glb*exp(TauLcl*rng.normal()) );
} }
/* /*
* Mutate rotation angles. * Mutate rotation angles.
*/ */
for (i = 0; i < _eo.CorCffLength(); i++) { for (i = 0; i < _eo.CorCffLength(); i++) {
tmp = _eo.getCorCff(i); tmp = _eo.getCorCff(i);
tmp += TauBeta*rng.normal(); tmp += TauBeta*rng.normal();
// danger of VERY long loops --MS-- // danger of VERY long loops --MS--
// while (CorCff[i] > M_PI) // while (CorCff[i] > M_PI)
// CorCff[i] -= 2.0 * M_PI; // CorCff[i] -= 2.0 * M_PI;
// while (CorCff[i] < - M_PI) // while (CorCff[i] < - M_PI)
// CorCff[i] += 2.0 * M_PI; // CorCff[i] += 2.0 * M_PI;
if ( fabs(tmp) > M_PI ) { if ( fabs(tmp) > M_PI ) {
tmp -= M_PI * (int) (tmp/M_PI) ; tmp -= M_PI * (int) (tmp/M_PI) ;
} }
_eo.setCorCff(i, tmp); _eo.setCorCff(i, tmp);
} }
/* /*
* Perform correlated mutations. * Perform correlated mutations.
*/ */
vector<double> VarStp(_eo.size()); vector<double> VarStp(_eo.size());
for (i = 0; i < _eo.size() && i < _eo.StdDevLength(); i++) for (i = 0; i < _eo.size() && i < _eo.StdDevLength(); i++)
VarStp[i] = _eo.getStdDev(i)*rng.normal(); VarStp[i] = _eo.getStdDev(i)*rng.normal();
for (k = i; k < _eo.size(); k++) for (k = i; k < _eo.size(); k++)
VarStp[k] = _eo.getStdDev(i-1)*rng.normal(); VarStp[k] = _eo.getStdDev(i-1)*rng.normal();
nq = _eo.CorCffLength() - 1; nq = _eo.CorCffLength() - 1;
for (k = _eo.size()-_eo.StdDevLength(); k < _eo.size()-1; k++) { for (k = _eo.size()-_eo.StdDevLength(); k < _eo.size()-1; k++) {
n1 = _eo.size() - k - 1; n1 = _eo.size() - k - 1;
n2 = _eo.size() - 1; n2 = _eo.size() - 1;
for (i = 0; i < k; i++) { for (i = 0; i < k; i++) {
d1 = VarStp[n1]; d1 = VarStp[n1];
d2 = VarStp[n2]; d2 = VarStp[n2];
S = sin( _eo.getCorCff(nq) ); S = sin( _eo.getCorCff(nq) );
C = cos( _eo.getCorCff(nq) ); C = cos( _eo.getCorCff(nq) );
VarStp[n2] = d1 * S + d2 * C; VarStp[n2] = d1 * S + d2 * C;
VarStp[n1] = d1 * C - d2 * S; VarStp[n1] = d1 * C - d2 * S;
n2--; n2--;
nq--; nq--;
} }
} }
for (i = 0; i < _eo.size(); i++) for (i = 0; i < _eo.size(); i++)
_eo[i] += VarStp[i]; _eo[i] += VarStp[i];
} }
// the data // the data
//========= //=========
double TauLcl; /* Local factor for mutation of std deviations */ double TauLcl; /* Local factor for mutation of std deviations */
double TauGlb; /* Global factor for mutation of std deviations */ double TauGlb; /* Global factor for mutation of std deviations */
double TauBeta; /* Factor for mutation of correlation parameters */ double TauBeta; /* Factor for mutation of correlation parameters */
}; };
/* /*
* Correlated mutations in ESs, according to the following * Correlated mutations in ESs, according to the following
* sources: * sources:
* H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80 * H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80
* p. 43, 1980 * p. 43, 1980
* G. Rudolph: Globale Optimierung mit parallelen Evolutions- * G. Rudolph: Globale Optimierung mit parallelen Evolutions-
* strategien, Diploma Thesis, University of Dortmund, 1990 * strategien, Diploma Thesis, University of Dortmund, 1990
*/ */
// Not yet implemented! // Not yet implemented!
#endif #endif

View file

@ -41,9 +41,9 @@ template<class Chrom> class eoEasyEA: public eoAlgo<Chrom>
{ {
public: public:
/// Constructor. /// Constructor.
eoEasyEA(eoSelect<Chrom>& _select, eoEasyEA(eoBinPopOp<Chrom>& _select,
eoTransform<Chrom>& _transform, eoMonPopOp<Chrom>& _transform,
eoMerge<Chrom>& _replace, eoBinPopOp<Chrom>& _replace,
eoEvalFunc<Chrom>& _evaluator, eoEvalFunc<Chrom>& _evaluator,
eoTerm<Chrom>& _terminator) eoTerm<Chrom>& _terminator)
:step(_select, _transform, _replace, _evaluator), :step(_select, _transform, _replace, _evaluator),

View file

@ -43,7 +43,7 @@ template<class EOT> struct eoEvalFunc {
typedef typename EOT::Fitness EOFitT; typedef typename EOT::Fitness EOFitT;
#endif #endif
/// Effectively applies the evaluation function to an EO or urEO /// Effectively applies the evaluation function to an EO
virtual void operator() ( EOT & _eo ) const = 0; virtual void operator() ( EOT & _eo ) const = 0;
}; };

View file

@ -1,72 +0,0 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoEvaluator.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOEVALUATOR_H
#define _EOEVALUATOR_H
//-----------------------------------------------------------------------------
#include <eoPopOps.h>
#include <eoEvalFunc.h>
//-----------------------------------------------------------------------------
/** Evaluator takes a vector of EOs and evaluates its fitness
* returning void. Template instances must be of fitness and EO type
*/
template<class EOT>
class eoEvaluator: public eoTransform<EOT>{
public:
/// ctor
eoEvaluator( const eoEvalFunc< EOT> & _ef )
: eoTransform<EOT>(), repEF( _ef ){};
/// Needed virtual destructor
virtual ~eoEvaluator() {};
/* Sets the evaluation function
virtual void EF( const eoEvalFunc< EOT> & _ef ) { repEF= _ef;};*/
/// Gets the evaluation function
virtual const eoEvalFunc< EOT>& EF() { return repEF;};
/** This is the actual function operator(); it is left without implementation.
It takes a vector of pointers to eo
* @param _vEO is a vector of pointers to eo, that will be evaluated
*/
virtual void operator() ( EOT& _eot ) const = 0;
///@name eoObject methods
//@{
/** Return the class id */
virtual string className() const { return "eoEvaluator"; }
/** Read and print are left without implementation */
//@}
private:
const eoEvalFunc< EOT> & repEF;
};
//@}
#endif

View file

@ -1,80 +1,80 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoOp.h // eoOp.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef eoGeneration_h #ifndef eoGeneration_h
#define eoGeneration_h #define eoGeneration_h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <eoAlgo.h> // eoPop #include <eoAlgo.h> // eoPop
#include <eoEvalFunc.h> #include <eoEvalFunc.h>
#include <eoPopOps.h> // eoSelect, eoTranform, eoMerge #include <eoPopOps.h> // eoSelect, eoTranform, eoMerge
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoGeneration // eoGeneration
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
template<class Chrom> class eoGeneration: public eoAlgo<Chrom> template<class Chrom> class eoGeneration: public eoAlgo<Chrom>
{ {
public: public:
/// Constructor. /// Constructor.
eoGeneration(eoSelect<Chrom>& _select, eoGeneration(eoBinPopOp<Chrom>& _select,
eoTransform<Chrom>& _transform, eoMonPopOp<Chrom>& _transform,
eoMerge<Chrom>& _replace, eoBinPopOp<Chrom>& _replace,
eoEvalFunc<Chrom>& _evaluator): eoEvalFunc<Chrom>& _evaluator):
select(_select), transform(_transform), select(_select), transform(_transform),
replace(_replace), evaluator( _evaluator) {}; replace(_replace), evaluator( _evaluator) {};
/// Copy Constructor. /// Copy Constructor.
eoGeneration(eoGeneration<Chrom>& _gen): eoGeneration(eoGeneration<Chrom>& _gen):
select(_gen.select), transform(_gen.transform), select(_gen.select), transform(_gen.transform),
replace(_gen.replace), evaluator( _gen.evaluator ) {}; replace(_gen.replace), evaluator( _gen.evaluator ) {};
/// Apply one generation of evolution to the population. /// Apply one generation of evolution to the population.
virtual void operator()(eoPop<Chrom>& pop) { virtual void operator()(eoPop<Chrom>& pop) {
eoPop<Chrom> breeders; eoPop<Chrom> breeders;
select(pop, breeders); select(pop, breeders);
transform(breeders); transform(breeders);
eoPop<Chrom>::iterator i; eoPop<Chrom>::iterator i;
// Can't use foreach here since foreach takes the // Can't use foreach here since foreach takes the
// parameter by reference // parameter by reference
for ( i = breeders.begin(); i != breeders.end(); i++) for ( i = breeders.begin(); i != breeders.end(); i++)
evaluator(*i); evaluator(*i);
replace(breeders, pop); replace(breeders, pop);
} }
/// Class name. /// Class name.
string className() const { return "eoGeneration"; } string className() const { return "eoGeneration"; }
private: private:
eoSelect<Chrom>& select; eoBinPopOp<Chrom>& select;
eoTransform<Chrom>& transform; eoMonPopOp<Chrom>& transform;
eoMerge<Chrom>& replace; eoBinPopOp<Chrom>& replace;
eoEvalFunc<Chrom>& evaluator; eoEvalFunc<Chrom>& evaluator;
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif eoGeneration_h #endif eoGeneration_h

View file

@ -7,8 +7,11 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <eoPop.h> // eoPop #include <iostream>
#include <eoPopOps.h> // eoMerge
// EO includes
#include <eoPop.h>
#include <eoMerge.h>
/***************************************************************************** /*****************************************************************************
* eoInclusion: A replacement algorithm. * * eoInclusion: A replacement algorithm. *
@ -20,7 +23,13 @@ template<class Chrom> class eoInclusion: public eoMerge<Chrom>
{ {
public: public:
/// (Default) Constructor. /// (Default) Constructor.
eoInclusion(const float& _rate = 1.0): eoMerge<Chrom>(_rate) {} eoInclusion(const float& _rate = 1.0): eoMerge<Chrom>( _rate ) {}
/// Ctor from istream
eoInclusion( istream& _is): eoBinPopOp<Chrom>( _is ) {};
/// Dtor
virtual ~eoInclusion() {};
/** /**
* Creates a new population based on breeders and original populations. * Creates a new population based on breeders and original populations.
@ -38,6 +47,16 @@ template<class Chrom> class eoInclusion: public eoMerge<Chrom>
greater<Chrom>()); greater<Chrom>());
pop.erase(pop.begin() + target, pop.end()); pop.erase(pop.begin() + target, pop.end());
} }
/** @name Methods from eoObject */
//@{
/** readFrom and printOn inherited from eoMerge */
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
virtual string className() const {return "eoMerge";};
//@}
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------

View file

@ -1,79 +1,96 @@
//----------------------------------------------------------------------------- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
// eoInsertion.h
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoInsertion.h
#ifndef eoInsertion_h // Inserts new members into the population
#define eoInsertion_h // (c) GeNeura Team, 1998
/*
//----------------------------------------------------------------------------- This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
#include <eoPop.h> // eoPop License as published by the Free Software Foundation; either
#include <eoPopOps.h> // eoMerge version 2 of the License, or (at your option) any later version.
/****************************************************************************** This library is distributed in the hope that it will be useful,
* eoInsertion: A replacement algorithm. but WITHOUT ANY WARRANTY; without even the implied warranty of
* Creates a new population with all the breeders and the best individuals MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* from the original population. Lesser General Public License for more details.
*****************************************************************************/
You should have received a copy of the GNU Lesser General Public
template<class Chrom> class eoInsertion: public eoMerge<Chrom> License along with this library; if not, write to the Free Software
{ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
public:
/// (Default) Constructor. Contact: todos@geneura.ugr.es, http://geneura.ugr.es
eoInsertion(const float& _rate = 1.0): eoMerge<Chrom>(_rate) {} */
//-----------------------------------------------------------------------------
/**
* Creates a new population based on breeders and original populations. #ifndef eoInsertion_h
* @param breeders The population of breeders. #define eoInsertion_h
* @param pop The original population.
*/ //-----------------------------------------------------------------------------
/*void operator()(eoPop<Chrom>& breeders, eoPop<Chrom>& pop)
{ #include <iostream>
int new_size = static_cast<int>(pop.size() * rate());
// EO includes
if (new_size == breeders.size()) #include <eoPop.h> // eoPop
{ #include <eoMerge.h> // eoMerge
pop = breeders;
} /******************************************************************************
else if (new_size < breeders.size()) * eoInsertion: A replacement algorithm.
{ * Creates a new population with all the breeders and the best individuals
pop = breeders; * from the original population.
sort(pop.begin(), pop.end()); *****************************************************************************/
pop.erase(pop.begin(), pop.begin() - new_size + pop.size());
} template<class Chrom> class eoInsertion: public eoMerge<Chrom>
else {
{ public:
sort(pop.begin(), pop.end()); /// (Default) Constructor.
pop.erase(pop.begin(), eoInsertion(const float& _rate = 1.0): eoMerge<Chrom>( _rate ) {}
pop.begin() + breeders.size() + pop.size() - new_size);
copy(breeders.begin(), breeders.end(), /// Ctor from istream
back_insert_iterator<eoPop<Chrom> >(pop)); eoInsertion( istream& _is): eoBinPopOp<Chrom>( _is ) {};
}
}*/ /// Dtor
virtual ~eoInsertion() {};
void operator()(eoPop<Chrom>& breeders, eoPop<Chrom>& pop)
{ /**
unsigned target = static_cast<unsigned>(rint(pop.size() * rate())); * Creates a new population based on breeders and original populations.
* @param breeders The population of breeders. Should be sorted to work correctly
pop.swap(breeders); * @param pop The original population.
*/
if (target < pop.size()) void operator()( eoPop<Chrom>& _breeders, eoPop<Chrom>& _pop)
{ {
partial_sort(pop.begin(), pop.begin() + target, pop.end(), unsigned target = static_cast<unsigned>(rint(_pop.size() * rate()));
greater<Chrom>());
pop.erase(pop.begin() + target, pop.end()); _pop.swap(_breeders);
}
else if (target < _pop.size())
{ {
target = min(target - pop.size(), breeders.size()); partial_sort(_pop.begin(), _pop.begin() + target, _pop.end(),
partial_sort(breeders.begin(), breeders.begin() + target, greater<Chrom>());
breeders.end(), greater<Chrom>()); _pop.erase(_pop.begin() + target, _pop.end());
copy(breeders.begin(), breeders.begin() + target, }
back_insert_iterator<eoPop<Chrom> >(pop)); else
} {
} target = min(target - _pop.size(), _breeders.size());
}; partial_sort(_breeders.begin(), _breeders.begin() + target,
_breeders.end(), greater<Chrom>());
//----------------------------------------------------------------------------- copy(_breeders.begin(), _breeders.begin() + target,
back_insert_iterator<eoPop<Chrom> >(_pop));
#endif eoInsertion_h }
};
/** @name Methods from eoObject */
//@{
/** readFrom and printOn inherited from eoMerge */
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
virtual string className() const {return "eoInsertion";};
//@}
};
//-----------------------------------------------------------------------------
#endif eoInsertion_h

View file

@ -1,5 +1,26 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoLottery.h // eoLottery.h
// Implements the lottery procedure for selection
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef eoLottery_h #ifndef eoLottery_h
@ -16,14 +37,14 @@
/// requires Chrom::Fitness to be float castable /// requires Chrom::Fitness to be float castable
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
template<class Chrom> class eoLottery: public eoSelect<Chrom> template<class Chrom> class eoLottery: public eoBinPopOp<Chrom>
{ {
public: public:
/// (Default) Constructor. /// (Default) Constructor.
eoLottery(const float& _rate = 1.0): rate(_rate) {} eoLottery(const float& _rate = 1.0): rate(_rate) {}
/// ///
void operator()(const eoPop<Chrom>& pop, eoPop<Chrom>& breeders) const void operator()( eoPop<Chrom>& pop, eoPop<Chrom>& breeders)
{ {
// scores of chromosomes // scores of chromosomes
vector<float> score(pop.size()); vector<float> score(pop.size());

115
eo/src/eoMerge.h Normal file
View file

@ -0,0 +1,115 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoMerge.h
// Base class for population-merging classes
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef eoMerge_h
#define eoMerge_h
//-----------------------------------------------------------------------------
#include <iostream>
// EO includes
#include <eoPop.h> // eoPop
#include <eoPopOps.h> // eoMerge
/**
* eoMerge: Base class for replacement algorithms
*/
template<class Chrom> class eoMerge: public eoBinPopOp<Chrom>
{
public:
/// (Default) Constructor.
eoMerge(const float& _rate = 1.0): eoBinPopOp<Chrom>(), repRate( _rate ) {}
/// Ctor from istream
eoMerge( istream& _is): eoBinPopOp<Chrom>() { readFrom( _is ); };
/**
* Creates a new population based on breeders and original populations.
* @param breeders The population of breeders. Should be sorted to work correctly
* @param pop The original population.
*/
void operator()( eoPop<Chrom>& _breeders, eoPop<Chrom>& _pop)
{
unsigned target = static_cast<unsigned>(rint(_pop.size() * rate()));
_pop.swap(_breeders);
if (target < _pop.size())
{
partial_sort(_pop.begin(), _pop.begin() + target, _pop.end(),
greater<Chrom>());
_pop.erase(_pop.begin() + target, _pop.end());
}
else
{
target = min(target - _pop.size(), _breeders.size());
partial_sort(_breeders.begin(), _breeders.begin() + target,
_breeders.end(), greater<Chrom>());
copy(_breeders.begin(), _breeders.begin() + target,
back_insert_iterator<eoPop<Chrom> >(_pop));
}
};
/** @name Methods from eoObject */
//@{
/**
* Read object. The EOT class must have a ctor from a stream;
in this case, a strstream is used.
* @param _is A istream.
*/
virtual void readFrom(istream& _is) {
_is >> repRate;
}
/**
* Write object. Prints relevant parameters to standard output
* @param _os A ostream. In this case, prints the population to
standard output. The EOT class must hav standard output with cout,
but since it should be an eoObject anyways, it's no big deal.
*/
virtual void printOn(ostream& _os) const {
_os << repRate;
};
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
virtual string className() const {return "eoMerge";};
//@}
protected:
float rate() { return repRate;};
private:
float repRate;
};
//-----------------------------------------------------------------------------
#endif eoInsertion_h

99
eo/src/eoMultiBinOp.h Normal file
View file

@ -0,0 +1,99 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoMultiBinOp.h
// Class that combines several binary or unary operators
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOMULTIBINOP_h
#define _EOMULTIBINOP_h
#include <iterator>
#include <eoOp.h>
/** MultiMonOp combines several monary operators. By itself, it does nothing to the
EO it´s handled*/
template <class EOT>
class eoMultiBinOp: public eoBinOp<EOT> {
public:
/// Ctor from an already existing op
eoMultiBinOp( const eoBinOp<EOT>* _op )
: eoBinOp< EOT >( ), vOp(){
vOp.push_back( _op );
};
///
eoMultiBinOp( )
: eoBinOp< EOT >( ), vOp(){};
/// Ads a new operator
void adOp( const eoOp<EOT>* _op ){
vOp.push_back( _op );
};
/// needed virtual dtor
virtual ~eoMultiBinOp() {};
///
/// Applies all operators to the EO
virtual void operator()( EOT& _eo1, EOT& _eo2 ) const {
if ( vOp.begin() != vOp.end() ) { // which would mean it's empty
for ( vector< const eoOp<EOT>* >::const_iterator i = vOp.begin();
i != vOp.end(); i++ ) {
// Admits only unary or binary operator
switch ((*i)->readArity()) {
case unary:
{
const eoMonOp<EOT>* monop = static_cast<const eoMonOp<EOT>* >(*i);
(*monop)( _eo1 );
(*monop)( _eo2 );
break;
}
case binary:
{
const eoBinOp<EOT>* binop = static_cast<const eoBinOp<EOT>* >(*i);
(*binop)( _eo1, _eo2 );
break;
}
}
}
}
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoMultiBinOp";};
//@}
private:
/// uses pointers to base class since operators can be unary or binary
vector< const eoOp<EOT>* > vOp;
};
#endif

View file

@ -1,204 +1,204 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoOp.h // eoOp.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _eoOp_H #ifndef _eoOp_H
#define _eoOp_H #define _eoOp_H
#include <vector> #include <vector>
#include <eoObject.h> #include <eoObject.h>
#include <eoPrintable.h> #include <eoPrintable.h>
/** @name Genetic operators /** @name Genetic operators
What is a genetic algorithm without genetic operators? There is a genetic operator hierarchy, with What is a genetic algorithm without genetic operators? There is a genetic operator hierarchy, with
eoOp as father and eoMonOp (monary or unary operator) and eoBinOp (binary operator) as siblings. Nobody eoOp as father and eoMonOp (monary or unary operator) and eoBinOp (binary operator) as siblings. Nobody
should subclass eoOp, you should subclass eoBinOp or eoMonOp, those are the ones actually used here.\\ should subclass eoOp, you should subclass eoBinOp or eoMonOp, those are the ones actually used here.\\
#eoOp#s are only printable objects, so if you want to build them from a file, it has to #eoOp#s are only printable objects, so if you want to build them from a file, it has to
be done in another class, namely factories. Each hierarchy of #eoOp#s should have its own be done in another class, namely factories. Each hierarchy of #eoOp#s should have its own
factory, which know how to build them from a description in a file. factory, which know how to build them from a description in a file.
@author GeNeura Team @author GeNeura Team
@version 0.1 @version 0.1
@see eoOpFactory @see eoOpFactory
*/ */
//@{ //@{
/// ///
enum Arity { unary = 0, binary = 1, Nary = 2}; enum Arity { unary = 0, binary = 1, Nary = 2};
/** Abstract data types for EO operators. /** Abstract data types for EO operators.
* Genetic operators act on chromosomes, changing them. The type to instantiate them should * Genetic operators act on chromosomes, changing them. The type to instantiate them should
* be an eoObject, but in any case, they are type-specific; each kind of evolvable object * be an eoObject, but in any case, they are type-specific; each kind of evolvable object
* can have its own operators * can have its own operators
*/ */
template<class EOType> template<class EOType>
class eoOp: public eoObject, public eoPrintable { class eoOp: public eoObject, public eoPrintable {
public: public:
/// Ctor /// Ctor
eoOp( Arity _arity = unary ) eoOp( Arity _arity = unary )
:arity( _arity ) {}; :arity( _arity ) {};
/// Copy Ctor /// Copy Ctor
eoOp( const eoOp& _eop ) eoOp( const eoOp& _eop )
:arity( _eop.arity ) {}; :arity( _eop.arity ) {};
/// Needed virtual destructor /// Needed virtual destructor
virtual ~eoOp(){}; virtual ~eoOp(){};
/// Arity: number of operands /// Arity: number of operands
Arity readArity() const {return arity;}; Arity readArity() const {return arity;};
/** @name Methods from eoObject */ /** @name Methods from eoObject */
//@{ //@{
/** /**
* Write object. It's called printOn since it prints the object _on_ a stream. * Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A ostream. * @param _os A ostream.
*/ */
virtual void printOn(ostream& _os) const { virtual void printOn(ostream& _os) const {
_os << className(); _os << className();
// _os << arity; // _os << arity;
}; };
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
virtual string className() const {return "eoOp";}; virtual string className() const {return "eoOp";};
//@} //@}
private: private:
/// arity is the number of operands it takes /// arity is the number of operands it takes
Arity arity; Arity arity;
}; };
/** Binary genetic operator: subclasses eoOp, and defines /** Binary genetic operator: subclasses eoOp, and defines
basically the operator() with two operands basically the operator() with two operands
*/ */
template<class EOType> template<class EOType>
class eoBinOp: public eoOp<EOType> { class eoBinOp: public eoOp<EOType> {
public: public:
/// Ctor /// Ctor
eoBinOp() eoBinOp()
:eoOp<EOType>( binary ) {}; :eoOp<EOType>( binary ) {};
/// Copy Ctor /// Copy Ctor
eoBinOp( const eoBinOp& _ebop ) eoBinOp( const eoBinOp& _ebop )
: eoOp<EOType>( _ebop ){}; : eoOp<EOType>( _ebop ){};
/// Dtor /// Dtor
~eoBinOp () {}; ~eoBinOp () {};
/** applies operator, to the object. Modifies both operands. /** applies operator, to the object. Modifies both operands.
*/ */
virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0; virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0;
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject readFrom and printOn are directly inherited from eoObject
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
virtual string className() const {return "eoBinOp";}; virtual string className() const {return "eoBinOp";};
//@} //@}
}; };
/** eoMonOp is the monary operator: genetic operator that takes /** eoMonOp is the monary operator: genetic operator that takes
only one EO only one EO
*/ */
template <class EOType> template <class EOType>
class eoMonOp: public eoOp<EOType> { class eoMonOp: public eoOp<EOType> {
public: public:
/// Ctor /// Ctor
eoMonOp( ) eoMonOp( )
:eoOp<EOType>( unary ) {}; :eoOp<EOType>( unary ) {};
/// Copy Ctor /// Copy Ctor
eoMonOp( const eoMonOp& _emop ) eoMonOp( const eoMonOp& _emop )
: eoOp<EOType>( _emop ){}; : eoOp<EOType>( _emop ){};
/// Dtor /// Dtor
~eoMonOp() {}; ~eoMonOp() {};
/** applies randomly operator, to the object. If arity is more than 1, /** applies randomly operator, to the object. If arity is more than 1,
* keeps a copy of the operand in a cache. * keeps a copy of the operand in a cache.
*/ */
virtual void operator()( EOType& _eo1) const = 0; virtual void operator()( EOType& _eo1) const = 0;
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject readFrom and printOn are directly inherited from eoObject
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
virtual string className() const {return "eoMonOp";}; virtual string className() const {return "eoMonOp";};
//@} //@}
}; };
#include <eoPop.h> #include <eoPop.h>
/** eoNaryOp is the N-ary operator: genetic operator that takes /** eoNaryOp is the N-ary operator: genetic operator that takes
several EOs. It could be called an {\em orgy} operator. It's a general operator several EOs. It could be called an {\em orgy} operator. It's a general operator
that takes any number of inputs and spits out any number of outputs that takes any number of inputs and spits out any number of outputs
*/ */
template <class EOType> template <class EOType>
class eoNaryOp: public eoOp<EOType> { class eoNaryOp: public eoOp<EOType> {
public: public:
/// Ctor /// Ctor
eoNaryOp( ) eoNaryOp( )
:eoOp<EOType>( Nary ) {}; :eoOp<EOType>( Nary ) {};
/// Copy Ctor /// Copy Ctor
eoNaryOp( const eoNaryOp& _emop ) eoNaryOp( const eoNaryOp& _emop )
: eoOp<EOType>( _emop ){}; : eoOp<EOType>( _emop ){};
/// Dtor /// Dtor
~eoNaryOp() {}; ~eoNaryOp() {};
/** applies randomly operator, to the object. /** applies randomly operator, to the object.
*/ */
virtual void operator()( const eoPop<EOType> & _in, eoPop<EOType> _out ) const = 0; virtual void operator()( const eoPop<EOType> & _in, eoPop<EOType> _out ) const = 0;
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eoObject. readFrom and printOn are directly inherited from eoObject.
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
string className() const {return "eoNaryOp";}; string className() const {return "eoNaryOp";};
//@} //@}
}; };
//@} //@}
#endif #endif

View file

@ -833,7 +833,7 @@ void InitRandom( Parser & parser) {
} }
if (_seed == 0) { // use clock to get a "random" seed if (_seed == 0) { // use clock to get a "random" seed
_seed = unsigned long( time( 0 ) ); _seed = (unsigned long)( time( 0 ) );
ostrstream s; ostrstream s;
s << _seed; s << _seed;
parser.setParamValue("--seed", s.str()); // so it will be printed out in the status file, and canbe later re-used to re-run EXACTLY the same run parser.setParamValue("--seed", s.str()); // so it will be printed out in the status file, and canbe later re-used to re-run EXACTLY the same run

View file

@ -1,147 +1,144 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoPop.h // eoPop.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOPOP_H #ifndef _EOPOP_H
#define _EOPOP_H #define _EOPOP_H
#include <vector> #include <vector>
#include <strstream> #include <strstream>
using namespace std; // EO includes
// from file #include <eoRnd.h>
#include <eoPersistent.h>
#include <eoRnd.h>
#include <eoPersistent.h> /** Subpopulation: it is used to move parts of population
from one algorithm to another and one population to another. It is safer
/** Subpopulation: it is used to move parts of population to declare it as a separate object. I have no idea if a population can be
from one algorithm to another and one population to another. It is safer some other thing that a vector, but if somebody thinks of it, this concrete
to declare it as a separate object. I have no idea if a population can be implementation will be moved to "generic" and an abstract Population
some other thing that a vector, but if somebody thinks of it, this concrete interface will be provided.
implementation will be moved to "generic" and an abstract Population It can be instantiated with anything, provided that it accepts a "size" and a
interface will be provided. random generator in the ctor. This happens to all the eo1d chromosomes declared
It can be instantiated with anything, provided that it accepts a "size" and a so far. EOT must also have a copy ctor, since temporaries are created and copied
random generator in the ctor. This happens to all the eo1d chromosomes declared to the population.
so far. EOT must also have a copy ctor, since temporaries are created and copied @author Geneura Team
to the population. @version 0.0
@author Geneura Team */
@version 0.0
*/ template<class EOT>
class eoPop: public vector<EOT>, public eoObject, public eoPersistent {
template<class EOT>
class eoPop: public vector<EOT>, public eoObject, public eoPersistent { /// Type is the type of each gene in the chromosome
#ifdef _MSC_VER
/// Type is the type of each gene in the chromosome typedef EOT::Type Type;
#ifdef _MSC_VER #else
typedef EOT::Type Type; typedef typename EOT::Type Type;
#else #endif
typedef typename EOT::Type Type;
#endif public:
/** Protected ctor. This is intended to avoid creation of void populations, except
public: from sibling classes
/** Protected ctor. This is intended to avoid creation of void populations, except */
from sibling classes eoPop() :vector<EOT>() {};
*/
eoPop()
:vector<EOT>() {}; /** Ctor for fixed-size chromosomes, with variable content
@param _popSize total population size
@param _eoSize chromosome size. EOT should accept a fixed-size ctor
/** Ctor for fixed-size chromosomes, with variable content @param _geneRdn random number generator for each of the genes
@param _popSize total population size */
@param _eoSize chromosome size. EOT should accept a fixed-size ctor eoPop( unsigned _popSize, unsigned _eoSize, eoRnd<Type> & _geneRnd )
@param _geneRdn random number generator for each of the genes :vector<EOT>() {
*/ for ( unsigned i = 0; i < _popSize; i ++ ){
eoPop( unsigned _popSize, unsigned _eoSize, eoRnd<Type> & _geneRnd ) EOT tmpEOT( _eoSize, _geneRnd);
:vector<EOT>() { push_back( tmpEOT );
for ( unsigned i = 0; i < _popSize; i ++ ){ }
EOT tmpEOT( _eoSize, _geneRnd); };
push_back( tmpEOT );
} /** Ctor for variable-size chromosomes, with variable content
}; @param _popSize total population size
@param _sizeRnd RNG for the chromosome size. This will be added 1, just in case.
/** Ctor for variable-size chromosomes, with variable content @param _geneRdn random number generator for each of the genes
@param _popSize total population size */
@param _sizeRnd RNG for the chromosome size. This will be added 1, just in case. eoPop( unsigned _popSize, eoRnd<unsigned> & _sizeRnd, eoRnd<Type> & _geneRnd )
@param _geneRdn random number generator for each of the genes :vector<EOT>() {
*/ for ( unsigned i = 0; i < _popSize; i ++ ){
eoPop( unsigned _popSize, eoRnd<unsigned> & _sizeRnd, eoRnd<Type> & _geneRnd ) unsigned size = 1 + _sizeRnd();
:vector<EOT>() { EOT tmpEOT( size, _geneRnd);
for ( unsigned i = 0; i < _popSize; i ++ ){ push_back( tmpEOT );
unsigned size = 1 + _sizeRnd(); }
EOT tmpEOT( size, _geneRnd); };
push_back( tmpEOT );
} /** Ctor from an istream; reads the population from a stream,
}; each element should be in different lines
@param _is the stream
/** Ctor from an istream; reads the population from a stream, */
each element should be in different lines eoPop( istream& _is ):vector<EOT>() {
@param _is the stream readFrom( _is );
*/ }
eoPop( istream& _is ):vector<EOT>() {
readFrom( _is ); ///
} ~eoPop() {};
/// /** @name Methods from eoObject */
~eoPop() {}; //@{
/**
/** @name Methods from eoObject */ * Read object. The EOT class must have a ctor from a stream;
//@{ in this case, a strstream is used.
/** * @param _is A istream.
* Read object. The EOT class must have a ctor from a stream;
in this case, a strstream is used. */
* @param _is A istream. virtual void readFrom(istream& _is) {
while( _is ) { // reads line by line, and creates an object per
*/ // line
virtual void readFrom(istream& _is) { char line[MAXLINELENGTH];
while( _is ) { // reads line by line, and creates an object per _is.getline( line, MAXLINELENGTH-1 );
// line if (strlen( line ) ) {
char line[MAXLINELENGTH]; istrstream s( line );
_is.getline( line, MAXLINELENGTH-1 ); EOT thisEOT( s );
if (strlen( line ) ) { push_back( thisEOT );
istrstream s( line ); }
EOT thisEOT( s ); }
push_back( thisEOT ); }
}
} /**
} * Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A ostream. In this case, prints the population to
/** standard output. The EOT class must hav standard output with cout,
* Write object. It's called printOn since it prints the object _on_ a stream. but since it should be an eoObject anyways, it's no big deal.
* @param _os A ostream. In this case, prints the population to */
standard output. The EOT class must hav standard output with cout, virtual void printOn(ostream& _os) const {
but since it should be an eoObject anyways, it's no big deal. copy( begin(), end(), ostream_iterator<EOT>( _os, "\n") );
*/ };
virtual void printOn(ostream& _os) const {
copy( begin(), end(), ostream_iterator<EOT>( _os, "\n") ); /** Inherited from eoObject. Returns the class name.
}; @see eoObject
*/
/** Inherited from eoObject. Returns the class name. virtual string className() const {return "eoPop";};
@see eoObject //@}
*/
virtual string className() const {return "eoPop";}; protected:
//@}
};
protected: #endif
};
#endif

View file

@ -1,143 +1,141 @@
// eoPopOps.h // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
//----------------------------------------------------------------------------- // eoPopOps.h
// eo1d.h // (c) GeNeura Team, 1998
// (c) GeNeura Team, 1998 /*
/* This library is free software; you can redistribute it and/or
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either
License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software
License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Contact: todos@geneura.ugr.es, http://geneura.ugr.es */
*/ //-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#ifndef _EOPOPOPS_H
#ifndef _EOPOPOPS_H #define _EOPOPOPS_H
#define _EOPOPOPS_H
using namespace std;
using namespace std;
/**
/** @author Geneura Team
@author Geneura Team @version 0.0
@version 0.0
*/ @version 0.1 : -MS- 22/10/99
added the added the derived class eoSelectOne for which you only have
//----------------------------------------------------------------------------- to define the selection of 1 individual
#include <eoPop.h> (e.g. for tournament, age selection in SSGA, ...)
added at the BASE level (after all it's themost frequen case)
//----------------------------------------------------------------------------- the pure virtual operator that selects one single individual:
/** eoTransform is a class that transforms or does something on a population. EOT eoSelect::operator ( const eoPop<EOT>& _parents,
*/ const EOT& _first = 0)
template<class EOT> added the optional second parameter to transform::operator()
class eoTransform: public eoObject{ */
public: //-----------------------------------------------------------------------------
/** ctor */ #include <eoPop.h>
eoTransform() {};
//-----------------------------------------------------------------------------
/// Dtor /** eoTransform is a class that transforms or does something on a population.
virtual ~eoTransform(){}; */
template<class EOT>
/// Pure virtual transformation function. Does something on the population class eoMonPopOp: public eoObject{
virtual void operator () ( eoPop<EOT>& _pop ) = 0;
public:
/** @name Methods from eoObject */ /** ctor */
//@{ eoMonPopOp() {};
/** readFrom and printOn are not overriden
*/ /// Dtor
/** Inherited from eoObject. Returns the class name. virtual ~eoMonPopOp(){};
@see eoObject
*/ /// Pure virtual transformation function. Does something on the population
virtual string className() const {return "eoTransform";}; virtual void operator () ( eoPop<EOT>& _pop ) = 0;
//@}
/** @name Methods from eoObject */
}; //@{
/** readFrom and printOn are not overriden
//----------------------------------------------------------------------------- */
/** Inherited from eoObject. Returns the class name.
/** eoSelect usually takes elements from one population, with or without transformation, and transfers them to the other population */ @see eoObject
template<class EOT> */
class eoSelect: public eoObject{ virtual string className() const {return "eoMonPopOp";};
//@}
public:
/** ctor };
*/
eoSelect() {}; //-----------------------------------------------------------------------------
/// Dtor /** eoSelect usually takes elements from one population, with or without transformation, and transfers them to the other population */
virtual ~eoSelect(){}; template<class EOT>
class eoBinPopOp: public eoObject{
/** Pure virtual transformation function. Extracts something from the parents,
and transfers it to the siblings public:
@param _parents the initial generation. Will be kept constant /** ctor
@param _siblings the created offspring. Will be usually an empty population */
*/ eoBinPopOp() {};
virtual void operator () ( const eoPop<EOT>& _parents, eoPop<EOT>& _siblings ) const = 0;
/// Dtor
/** @name Methods from eoObject */ virtual ~eoBinPopOp(){};
//@{
/** readFrom and printOn are not overriden /** Pure virtual transformation function. Extracts something from the parents,
*/ and transfers it to the siblings
/** Inherited from eoObject. Returns the class name. @param _parents the initial generation. Will be kept constant
@see eoObject @param _siblings the created offspring. Will be usually an empty population
*/ */
virtual string className() const {return "eoSelect";}; virtual void operator () ( eoPop<EOT>& _parents, eoPop<EOT>& _siblings ) = 0;
//@}
/** @name Methods from eoObject */
}; //@{
/** readFrom and printOn are not overriden
/** eoMerge involves three populations, that can be merged and transformed to */
give a third /** Inherited from eoObject. Returns the class name.
*/ @see eoObject
template<class EOT> */
class eoMerge: public eoObject{ virtual string className() const {return "eoBinPopOp";};
//@}
public:
/// (Default) Constructor. };
eoMerge(const float& _rate = 1.0): rep_rate(_rate) {}
//-----------------------------------------------------------------------------
/// Dtor
virtual ~eoMerge() {} /** eoSelect usually takes elements from one population, with or without transformation, and transfers them to the other population */
template<class EOT>
/** Pure virtual transformation function. Extracts something from breeders class eoSelectOne: public eoObject{
* and transfers it to the pop
* @param breeders Tranformed individuals. public:
* @param pop The original population at the begining, the result at the end /** ctor
*/ */
virtual void operator () ( eoPop<EOT>& breeders, eoPop<EOT>& pop ) = 0; eoSelectOne() {};
/** @name Methods from eoObject */ /// Dtor
//@{ virtual ~eoSelectOne(){};
/** readFrom and printOn are not overriden
*/ /** Pure virtual transformation function. Extracts something from the parents,
/** Inherited from eoObject. Returns the class name. and transfers it to the siblings
@see eoObject @param _parents the initial generation. Will be kept constant
*/ @param _siblings the created offspring. Will be usually an empty population
virtual string className() const {return "eoMerge";}; */
//@} virtual const EOT& operator () ( const eoPop<EOT>& _parents ) = 0;
/// Return the rate to be selected from the original population /** @name Methods from eoObject */
float rate() const { return rep_rate; } //@{
/** readFrom and printOn are not overriden
/// Set the rate to be obtained after replacement. */
/// @param _rate The rate. /** Inherited from eoObject. Returns the class name.
void rate(const float& _rate) { rep_rate = _rate; } @see eoObject
*/
private: virtual string className() const {return "eoSelectOne";};
float rep_rate; //@}
};
};
//----------------------------------------------------------------------------- #endif
#endif

360
eo/src/eoScheme.h Normal file
View file

@ -0,0 +1,360 @@
// eoScheme.h
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoScheme.h
// (c) GeNeura Team, 1998 - EEAAX 1999
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOSCHEME_H
#define _EOSCHEME_H
using namespace std;
/**
@author Geneura Team -- EEAAX 99
@version 0.0
Evolution scheme
It seems to me that some important conceptual object is missing
(and God knows I hate turning everything into objects!
So here is the evolution scheme:
regroups selection (nb of offspring to generate AND selection method
and replacement (from parents + offspring)
allows to include elitism, eugenism of the worst, ... more easily
a generation is then simply an evolution scheme and some operators
and a full algo is a generation + a termination condition
this is mainly a container class
*/
//-----------------------------------------------------------------------------
#include <eoPopOps.h>
#include "eoStochTournament.h"
#include "eoDetTournament.h"
#include "eoLottery.h"
#include "eoUniformSelect.h"
#include "eoInclusion.h"
#include "eoESReplace.h"
#include "eoEPTournament.h"
/** eoScheme is a class that does more sophisticated evolution that eoEasyEA
*/
template<class EOT>
class eoScheme: public eoAlgo<EOT>{
public:
// Dtor
virtual ~eoScheme() {};
// copy ctor is impossible because of pointers to pure virual types.
// any idea???? --- leave the default copy ctor -- JJ
/** the Parser-based constructor
these switch cases could be turned into as many subclasses
- but how do you return the subclass to the caller of the constructor???
*/
eoScheme(Parser & parser) {
// read the popsize
parser.AddTitle("Description of evolution");
string Evol;
string SelectString;
// temporary
float rate_offspring;
try {
Evol = parser.getString("-EE", "--evolution", "GGA",
"Evolution scheme (GGA, SSGA, ESPlus, ESComma, EP, General)" );
popsize = parser.getInt("-EP", "--population", "10",
"Population size" );
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
// now the big switch
if (! strcasecmp(Evol.c_str(), "GGA") ) {
// GGA parameters: popsize, selection method (and its parameters)
nb_offspring = 0;
rate_offspring = 1.0; // generational replacement: #offspring=popsize
try {
// parser.AddTitle("GGA Parameters");
SelectString = parser.getString("-ES", "--selection", "Tournament",
"Selection method (Roulette, tournament)" );
if (! strcasecmp(SelectString.c_str(), "roulette") ) {
ptselect = new eoLottery<EOT> ();
ptselect_mate = new eoLottery<EOT> ();
}
if (! strcasecmp(SelectString.c_str(), "tournament") ) {
float rate = parser.getFloat("-Et", "--TselectSize", "2",
"Tournament size or rate" );
if (rate < 0.5)
throw out_of_range("Invalid tournament rate");
else if ( rate < 1 ) { // binary stochastic tournament
ptselect = new eoStochTournament<EOT>(rate);
ptselect_mate = new eoStochTournament<EOT>(rate);
} else { // determeinistic tournament of size (int)rate
ptselect = new eoDetTournament<EOT>((int)rate);
ptselect_mate = new eoDetTournament<EOT>((int)rate);
}
}
// end choice of selection
ptreplace = new eoInclusion<EOT>();
// put here the choice of elitism
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
} // end of GGA
// SSGA - standard, one offspring only at the moment
if (! strcasecmp(Evol.c_str(), "SSGA") ) {
// SSGA parameters: popsize, selection tournament size
// the replacement is limited to repace_worst, though
// it could be easy to add the anti-tournament replacement method
nb_offspring = 1;
// NOTE: of course it's a bit of a waste to use the standard loop
// for one single offspring ...
try {
// parser.AddTitle("SSGA Parameters");
float _rate = parser.getFloat("-ET", "--TSelectSize", "2",
"Selection tournament size" );
if ( _rate < 1 ) { // binary stochastic tournament
ptselect = new eoStochTournament<EOT>(_rate);
ptselect_mate = new eoStochTournament<EOT>(_rate);
} else { // determeinistic tournament of size (int)rate
ptselect = new eoDetTournament<EOT>((int)_rate);
ptselect_mate = new eoDetTournament<EOT>((int)_rate);
}
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
// end choice of selection
ptreplace = new eoInclusion<EOT>();
// put here the choice of elitism
} // end of SSGA
if (! strcasecmp(Evol.c_str(), "ESPlus") ) {
// ES evolution parameters: lambda = _nb_offspring
try {
// parser.AddTitle("ES Scheme parameters");
nb_offspring = parser.getInt("-EL", "--lambda", "50",
"Lambda" );
ptselect = new eoUniformSelect<EOT>();
ptselect_mate = new eoUniformSelect<EOT>();
ptreplace = new eoESPlus<EOT>();
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
} // end of ESPlus
if (! strcasecmp(Evol.c_str(), "ESComma") ) {
// ES evolution parameters: lambda = _nb_offspring
try {
// parser.AddTitle("ES Scheme parameters");
nb_offspring = parser.getInt("-EL", "--lambda", "50",
"Lambda" );
ptselect = new eoUniformSelect<EOT>();
ptselect_mate = new eoUniformSelect<EOT>();
ptreplace = new eoESComma<EOT>();
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
} // end of ESCOmma
if (! strcasecmp(Evol.c_str(), "EP") ) {
// EP evoltion scheme: only the EP-tournament replacement size is neede
try {
// parser.AddTitle("EP Scheme parameters");
nb_offspring = popsize;
ptselect = new eoCopySelect<EOT>; /* no selection */
ptselect_mate = new eoUniformSelect<EOT>();
/* What, crossover in EP :-) */
unsigned tsize = parser.getInt("-ET", "--TournamentSize", "6",
"Size of stocahstic replacement tournament" );
ptreplace = new eoEPTournament<EOT>(tsize);
}
catch (exception & e)
{
cout << e.what() << endl;
parser.printHelp();
exit(1);
}
} // end of EP
// everyting is read: now the consistency checks and other preliminary steps
nb_offspring = (nb_offspring ? nb_offspring :
(int) rint (rate_offspring * popsize) );
if (!nb_offspring)
nb_offspring = 1; /* al least one offspring */
}
// accessors
unsigned PopSize(){return popsize;}
unsigned NbOffspring(){return nb_offspring ;}
eoSelect<EOT>* PtSelect(){return ptselect;}
eoSelect<EOT>* PtSelectMate(){return ptselect_mate;}
eoMerge<EOT>* PtMerge() {return ptreplace;}
// NOTE: need pointers otherwise you have many warnings when initializing
/** @name Methods from eoObject */
//@{
/** Inherited from eoObject. Returns the class name.
@see eoObject
*/
string className() const {return "eoScheme";};
//@}
private:
unsigned popsize; /* but should it be here ??? */
unsigned nb_offspring; /* to generate through selection+operators */
// these are provisional for later use
// float rate_offspring; /* or rate */
// unsigned nb_survive; /* the best guys that are transmitted anyway */
// float rate_survive; /* or rate */
// unsigned nb_die; /* the worst guys that do not enev enter selection */
// float rate_die; /* or rate */
eoSelect<EOT> * ptselect;
eoSelect<EOT>* ptselect_mate;
eoMerge<EOT>* ptreplace;
bool elitism; /* put back old best in the new population if necessary */
};
/* examples:
for most populat schemes, nb_survive = nb_die = 0
in GGA and EP, nb_offspring = pop.size()
in ES, nb_offspring = lambda
in SSGA, nb_offspring = 1 (usually)
elitism can be used anywhere - though stupid in ES, EP and SSGA who are
elist by definition
*/
#endif _EOSCHEME_H
/*
/////////////////////////////////
/// Applies one generation of evolution to the population.
virtual void operator()(eoPop<EOT>& pop) {
// Determine the number of offspring to create
// either prescribed, or given as a rate
unsigned nb_off_local = (nb_offspring ? nb_offspring :
(int) rint (rate_offspring * pop.size()) );
nb_off_local = (nb_off_local ? nb_off_local : 1); // in case it is rounded to 0!
// the worst die immediately
unsigned nb_die_local = (nb_die ? nb_die :
(int) rint (rate_die * pop.size()) );
// and the best will survive without selection
unsigned nb_survive_local = (nb_survive ? nb_survive :
(int) rint (rate_survive * pop.size()) );
// before selection, erase the one to die
// sort old pop - just in case!
sort(pop.begin(), pop.end(), greater<EOT>());
Fitness oldBest = pop[0].fitness(); // store for elitism
eoPop<EOT> fertilepop = pop;
if (nb_die_local)
erase(fertilepop.end()-nb_die_local, fertilepop.end());
eoPop<EOT> offspring; // = select(fertilepop, nb_off_local);
select(fertilepop, offspring, nb_off_local);
// now apply the operators to offspring
for (unsigned i=0; i<nb_local; i++) {
EOT tmp = offspring[i];
unsigned id = 0; // first operator
eoOp<EOT>* op = seqselop.Op(&id);
while (op) { // NULL if no more operator
EOT mate;
if (op->readArity() == binary) // can eventually be skipped
mate = select_mate(pop, tmp); // though useless ig mutation
else
mate = tmp; // assumed: mate will not be used!
cout << op->className() << " for offspring " << i << endl;
tmp = (*op)( tmp, mate, pop );
op = seqselop.Op(&id);
}
offspring[i]=tmp; //* where it belongs
}
eoPop<EOT>::iterator i;
// Can't use foreach here since foreach takes the
// parameter by reference
for ( i = offspring.begin(); i != offspring.end(); i++)
evaluator(*i);
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// not exact - later!!!
// -MS-
// first, copy the ones that need to survive
// assumed: pop is still sorted!
eoPop<EOT> finalPop;
// and the best survive without selection
if (nb_survive_local) {
finalPop.resize(nb_survive_local);
copy( finalPop.begin(), fertilepop.begin(),
fertilepop.begin()+nb_survive_local );
}
// now call the replacement method
replace(finalPop, tmpPop);
// handle elitlism
sort(finalPop.begin(), finalPop.end(), greater<EOT>());
if (elitism) {
if ( finalPop[0].fitness() < oldBest ) // best fitness has decreased!
copy(finalPop.end()-1, pop[0]);
}
// return finalPop;
}
*/

23
eo/src/eoSelfEval.h Normal file
View file

@ -0,0 +1,23 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// EO.h
// (c) GeNeura Team 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------

View file

@ -1,76 +0,0 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoSimpleEval.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOSimpleEval_H
#define _EOSimpleEval_H
#include <eoEvaluator.h> // for evalFunc
#include <algorithm> // For sort
/** Particular instantiation of the EOEvaluator class
It takes each member in the population, and evaluates it, applying
the evaluation function it´s been initialized with
*/
template<class EOT>
class eoSimpleEval: public eoEvaluator<EOT> {
public:
/// Ctors/dtors
eoSimpleEval( eoEvalFunc<EOT> & _ef ):eoEvaluator<EOT>(_ef) {};
///
virtual ~eoSimpleEval() {};
#ifdef _MSC_VER
typedef EOT::Fitness EOFitT;
#else
typedef typename EOT::Fitness EOFitT;
#endif
/** Applies evaluation function to all members in the population, and sets
their fitnesses
Reference is non-const since it orders the population by any order
it´s been defined
@param _vEO the population whose fitness is going to be computed*/
virtual void operator() ( eoPop< EOT >& _vEO ) {
for ( eoPop<EOT>::iterator i = _vEO.begin(); i != _vEO.end(); i ++ ){
i->fitness( EF().evaluate( *i ) );
}
sort( _vEO.begin(), _vEO.end() );
};
///@name eoObject methods
//@{
///
void printOn( ostream& _os ) const {};
///
void readFrom( istream& _is ){};
///
string className() { return "eoSimpleEval";};
//@}
};
#endif

View file

@ -0,0 +1,78 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoStochTournament.h
// (c) GeNeura Team, 1998 - EEAAX 1999
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr
*/
//-----------------------------------------------------------------------------
#ifndef eoStochTournament_h
#define eoStochTournament_h
//-----------------------------------------------------------------------------
#include <functional> //
#include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include <eoRNG.h>
//-----------------------------------------------------------------------------
/** eoStochTournament: a selection method that selects ONE individual by
binary stochastic tournament
-MS- 24/10/99 */
//-----------------------------------------------------------------------------
template <class EOT> class eoStochTournament: public eoSelectOne<EOT>
{
public:
///
eoStochTournament(float _Trate = 1.0 ):eoSelectOne(), Trate(_Trate) {
// consistency check
if (Trate < 0.5) {
cerr << "Warning, Tournament rate should be > 0.5\nAdjusted to 0.55\n";
Trate = 0.55;
}
}
/** DANGER: if you want to be able to minimize as well as maximizem
DON'T cast the fitness to a float, use the EOT comparator! */
virtual const EOT& operator()(const eoPop<EOT>& pop) {
unsigned i1 = rng.random(pop.size()),
i2 = rng.random(pop.size());
bool ok = ( rng.flip(Trate) );
if (pop[i1] < pop[ i2 ] ) {
if (ok) return pop[ i2 ];
else return pop[ i1 ];
}
else {
if (ok) return pop[ i1 ];
else return pop[ i2 ];
}
}
private:
float Trate;
};
//-----------------------------------------------------------------------------
#endif eoDetTournament_h

64
eo/src/eoUniformSelect.h Normal file
View file

@ -0,0 +1,64 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoUniformSelect.h
// (c) GeNeura Team, 1998 - EEAAX 1999
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr
*/
//-----------------------------------------------------------------------------
#ifndef eoUniformSelect_h
#define eoUniformSelect_h
// WARNING: 2 classes in this one - eoUniformSelect and eoCopySelect
//-----------------------------------------------------------------------------
#include <functional> //
#include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include <eoRNG.h>
//-----------------------------------------------------------------------------
/** eoUniformSelect: a selection method that selects ONE individual randomly
-MS- 22/10/99 */
//-----------------------------------------------------------------------------
template <class EOT> class eoUniformSelect: public eoSelectOne<EOT>
{
public:
/// (Default) Constructor.
eoUniformSelect():eoSelectOne() {}
/// not a big deal!!!
virtual const EOT& operator()(const eoPop<EOT>& pop) {
return pop[rng.random(pop.size())] ;
}
/// Methods inherited from eoObject
//@{
/** Return the class id.
* @return the class name as a string
*/
virtual string className() const { return "eoUniformSelect"; };
private:
};
#endif eoUniformSelect_h

90
eo/src/eoUniformXOver.h Normal file
View file

@ -0,0 +1,90 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//-----------------------------------------------------------------------------
// eoUniformXOver.h
// (c) GeNeura Team, 1998
/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/
//-----------------------------------------------------------------------------
#ifndef _EOUNIFORMXOVER_h
#define _EOUNIFORMXOVER_h
// for swap
#if defined( __BORLANDC__ )
#include <algorith>
#else
#include <algorithm>
#endif
// EO includes
#include <eoOp.h>
#include <eoUniform.h>
//-----------------------------------------------------------------------------
/**
* EOUniformCrossover: operator for binary chromosomes
* implementation of uniform crossover for EO
* swaps ranges of bits between the parents
*/
//-----------------------------------------------------------------------------
template<class EOT>
class eoUniformXOver: public eoBinOp< EOT >
{
public:
///
eoUniformXOver( float _rate = 0.5 ):
eoBinOp< EOT > ( ), rate( _rate ) {
if (rate < 0 || rate > 1)
runtime_error("UxOver --> invalid rate");
}
///
void operator() ( EOT& chrom1, EOT& chrom2 ) const {
unsigned end = min(chrom1.length(),chrom2.length()) - 1;
// select bits to change
eoUniform<float> rnd(0, 1);
// aply changes
for (unsigned bit = 0; bit < end; bit++)
if (rnd() < rate)
swap(chrom1[ bit], chrom2[ bit]);
}
/** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp
*/
//@{
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoUniformXOver";};
//@}
private:
float rate; /// rate of uniform crossover
};
//-----------------------------------------------------------------------------
#endif

View file

@ -1,106 +1,106 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoXOver2.h // eoXOver2.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifndef _EOXOVER2_h #ifndef _EOXOVER2_h
#define _EOXOVER2_h #define _EOXOVER2_h
// for swap // for swap
#if defined( __BORLANDC__ ) #if defined( __BORLANDC__ )
#include <algorith> #include <algorith>
#else #else
#include <algorithm> #include <algorithm>
#endif #endif
// EO includes // EO includes
#include <eoOp.h> #include <eoOp.h>
#include <eoUniform.h> #include <eoUniform.h>
/** 2-point crossover: takes the genes in the central section of two EOs /** 2-point crossover: takes the genes in the central section of two EOs
and interchanges it and interchanges it
*/ */
template <class EOT> template <class EOT>
class eoXOver2: public eoBinOp<EOT> { class eoXOver2: public eoBinOp<EOT> {
public: public:
/// ///
eoXOver2() eoXOver2()
: eoBinOp< EOT >(){}; : eoBinOp< EOT >(){};
/// ///
virtual ~eoXOver2() {}; virtual ~eoXOver2() {};
/// ///
virtual void operator()( EOT& _eo1, virtual void operator()( EOT& _eo1,
EOT& _eo2 ) const { EOT& _eo2 ) const {
unsigned len1 = _eo1.length(), len2 = _eo2.length(), unsigned len1 = _eo1.length(), len2 = _eo2.length(),
len= (len1 > len2)?len2:len1; len= (len1 > len2)?len2:len1;
eoUniform<unsigned> uniform( 0, len ); eoUniform<unsigned> uniform( 0, len );
unsigned pos1 = uniform(), pos2 = uniform() ; unsigned pos1 = uniform(), pos2 = uniform() ;
applyAt( _eo1, _eo2, pos1, pos2 ); applyAt( _eo1, _eo2, pos1, pos2 );
} }
/** @name Methods from eoObject /** @name Methods from eoObject
readFrom and printOn are directly inherited from eoOp readFrom and printOn are directly inherited from eoOp
*/ */
//@{ //@{
/** Inherited from eoObject /** Inherited from eoObject
@see eoObject @see eoObject
*/ */
string className() const {return "eoXOver2";}; string className() const {return "eoXOver2";};
//@} //@}
private: private:
#ifdef _MSC_VER #ifdef _MSC_VER
typedef EOT::Type Type; typedef EOT::Type Type;
#else #else
typedef typename EOT::Type Type; typedef typename EOT::Type Type;
#endif #endif
/// applies operator to one gene in the EO /// applies operator to one gene in the EO
virtual void applyAt( EOT& _eo, EOT& _eo2, virtual void applyAt( EOT& _eo, EOT& _eo2,
unsigned _i, unsigned _j = 0) const { unsigned _i, unsigned _j = 0) const {
if ( _j < _i ) if ( _j < _i )
swap( _i, _j ); swap( _i, _j );
unsigned len1 = _eo.length(), len2 = _eo2.length(), unsigned len1 = _eo.length(), len2 = _eo2.length(),
len= (len1 > len2)?len2:len1; len= (len1 > len2)?len2:len1;
if ( (_j > len) || (_i> len ) ) if ( (_j > len) || (_i> len ) )
throw runtime_error( "xOver2: applying xOver past boundaries"); throw runtime_error( "xOver2: applying xOver past boundaries");
for ( unsigned i = _i; i < _j; i++ ) { for ( unsigned i = _i; i < _j; i++ ) {
Type tmp = _eo.gene( i ); Type tmp = _eo.gene( i );
_eo.gene( i ) = _eo2.gene( i ); _eo.gene( i ) = _eo2.gene( i );
_eo2.gene( i ) = tmp ; _eo2.gene( i ) = tmp ;
} }
} }
}; };
#endif #endif