From 91f5ddbdaadfd608ccad0ccfac798bc45343d841 Mon Sep 17 00:00:00 2001 From: jmerelo Date: Mon, 22 Nov 1999 09:47:32 +0000 Subject: [PATCH] Added changes mainly by Marc --- eo/src/Makefile.am | 9 +- eo/src/eo | 7 +- eo/src/eoAtomBitFlip.h | 6 +- eo/src/eoBitOp.h | 651 ++++++++++++++++++------------------- eo/src/eoBreeder.h | 185 ++++++----- eo/src/eoDetTournament.h | 78 +++++ eo/src/eoESFullChrom.h | 6 +- eo/src/eoESFullMut.h | 486 +++++++++++++-------------- eo/src/eoEasyEA.h | 6 +- eo/src/eoEvalFunc.h | 2 +- eo/src/eoEvaluator.h | 72 ---- eo/src/eoGeneration.h | 160 ++++----- eo/src/eoInclusion.h | 25 +- eo/src/eoInsertion.h | 175 +++++----- eo/src/eoLottery.h | 25 +- eo/src/eoMerge.h | 115 +++++++ eo/src/eoMultiBinOp.h | 99 ++++++ eo/src/eoOp.h | 408 +++++++++++------------ eo/src/eoParser.h | 2 +- eo/src/eoPop.h | 291 ++++++++--------- eo/src/eoPopOps.h | 284 ++++++++-------- eo/src/eoScheme.h | 360 ++++++++++++++++++++ eo/src/eoSelfEval.h | 23 ++ eo/src/eoSimpleEval.h | 76 ----- eo/src/eoStochTournament.h | 78 +++++ eo/src/eoUniformSelect.h | 64 ++++ eo/src/eoUniformXOver.h | 90 +++++ eo/src/eoXOver2.h | 212 ++++++------ 28 files changed, 2400 insertions(+), 1595 deletions(-) create mode 100644 eo/src/eoDetTournament.h delete mode 100644 eo/src/eoEvaluator.h create mode 100644 eo/src/eoMerge.h create mode 100644 eo/src/eoMultiBinOp.h create mode 100644 eo/src/eoScheme.h create mode 100644 eo/src/eoSelfEval.h delete mode 100644 eo/src/eoSimpleEval.h create mode 100644 eo/src/eoStochTournament.h create mode 100644 eo/src/eoUniformSelect.h create mode 100644 eo/src/eoUniformXOver.h diff --git a/eo/src/Makefile.am b/eo/src/Makefile.am index d7b9a928..23f08b5c 100644 --- a/eo/src/Makefile.am +++ b/eo/src/Makefile.am @@ -11,13 +11,14 @@ libeoincdir = $(includedir)/eo libeoinc_HEADERS = EO.h eo eo1d.h eo2d.h eo2dVector.h eoAged.h eoAlgo.h\ eoAtomBitFlip.h eoAtomCreep.h eoAtomMutation.h eoAtomMutator.h \ eoAtomRandom.h eoBin.h eoBitOp.h eoBitOpFactory.h eoBreeder.h\ - eoData.h eoDup.h eoESChrom.h eoESFullChrom.h eoESFullMut.h eoEasyEA.h\ - eoEvalFunc.h eoEvalFuncPtr.h eoEvaluator.h eoFitTerm.h eoFitness.h\ + eoData.h eoDetTournament.h eoDup.h eoESChrom.h eoESFullChrom.h eoESFullMut.h eoEasyEA.h\ + eoEvalFunc.h eoEvalFuncPtr.h eoFitTerm.h eoFitness.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\ eoParser.h eoPersistent.h eoPop.h eoPopOps.h eoPrintable.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 diff --git a/eo/src/eo b/eo/src/eo index 1f8423c9..4ec7688f 100644 --- a/eo/src/eo +++ b/eo/src/eo @@ -48,21 +48,23 @@ #include #include +#include #include #include #include #include +#include #include #include #include +#include #include // Evaluation functions #include #include -#include // Terminators #include @@ -70,6 +72,9 @@ #include // Selection and reproduction stuff +#include +#include +#include #include #include #include diff --git a/eo/src/eoAtomBitFlip.h b/eo/src/eoAtomBitFlip.h index b96d33a5..f9d769d0 100644 --- a/eo/src/eoAtomBitFlip.h +++ b/eo/src/eoAtomBitFlip.h @@ -1,7 +1,7 @@ // -*- 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 // (c) GeNeura Team, 1998 /* @@ -22,8 +22,8 @@ Contact: todos@geneura.ugr.es, http://geneura.ugr.es */ //----------------------------------------------------------------------------- -#ifndef _EOATOMCREEP_H -#define _EOATOMCREEP_H +#ifndef _EOATOMBITFLIP_H +#define _EOATOMBITFLIP_H /** Flips a single bit */ diff --git a/eo/src/eoBitOp.h b/eo/src/eoBitOp.h index bd21e937..cfe3d68d 100644 --- a/eo/src/eoBitOp.h +++ b/eo/src/eoBitOp.h @@ -1,16 +1,16 @@ -//----------------------------------------------------------------------------- -// eoBitOp.h -//----------------------------------------------------------------------------- - -#ifndef eoBitOp_h -#define eoBitOp_h - -//----------------------------------------------------------------------------- - -#include // swap_ranges -#include // eoUniform -#include // eoBin -#include // eoMonOp +//----------------------------------------------------------------------------- +// eoBitOp.h +//----------------------------------------------------------------------------- + +#ifndef eoBitOp_h +#define eoBitOp_h + +//----------------------------------------------------------------------------- + +#include // swap_ranges +#include // eoUniform +#include // eoBin +#include // eoMonOp /** @name BitWise Genetic operators @@ -24,334 +24,301 @@ have a factory that knows how to build them from a description @see eoBitOpFactory */ -//@{ +//@{ + +/** eoBinRandom --> mofify a chromosome in a random way */ + +template class eoBinRandom: public eoMonOp +{ + 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 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 eoBinBitFlip: public eoMonOp +{ + 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 uniform(0, chrom.size()); + unsigned i = uniform(); + chrom[i] = (chrom[i]) ? false : true; + } +}; + + +/** eoBinMutation --> classical mutation */ + +template class eoBinMutation: public eoMonOp +{ + 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 uniform; +}; + + +/** eoBinInversion: inverts the bits of the chromosome between an interval */ + +template class eoBinInversion: public eoMonOp +{ + 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 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 eoBinNext: public eoMonOp +{ + 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 eoBinPrev: public eoMonOp +{ + 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 eoBinCrossover: public eoBinOp +{ + 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 uniform(1, min(chrom1.size(), chrom2.size())); + swap_ranges(chrom1.begin(), chrom1.begin() + uniform(), chrom2.begin()); + } +}; + + +/** eoBinNxOver --> n-point crossover */ + +template class eoBinNxOver: public eoBinOp +{ + 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 points(max_size, false); + eoUniform 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 eoBinGxOver: public eoBinOp +{ + 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 points(max_genes, false); + eoUniform 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 eoBinRandom: public eoMonOp -{ - 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 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 eoBinBitFlip: public eoMonOp -{ - 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 uniform(0, chrom.size()); - unsigned i = uniform(); - chrom[i] = (chrom[i]) ? false : true; - } -}; - - -/** eoBinMutation --> classical mutation */ - -template class eoBinMutation: public eoMonOp -{ - 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 uniform; -}; - - -/** eoBinInversion: inverts the bits of the chromosome between an interval */ - -template class eoBinInversion: public eoMonOp -{ - 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 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 eoBinNext: public eoMonOp -{ - 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 eoBinPrev: public eoMonOp -{ - 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 eoBinCrossover: public eoBinOp -{ - 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 uniform(1, min(chrom1.size(), chrom2.size())); - swap_ranges(chrom1.begin(), chrom1.begin() + uniform(), chrom2.begin()); - } -}; - - -/** eoBinNxOver --> n-point crossover */ - -template class eoBinNxOver: public eoBinOp -{ - 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 points(max_size, false); - eoUniform 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 eoBinGxOver: public eoBinOp -{ - 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 points(max_genes, false); - eoUniform 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 eoBinUxOver: public eoBinOp -{ -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 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 +//----------------------------------------------------------------------------- +//@} +#endif eoBitOp_h diff --git a/eo/src/eoBreeder.h b/eo/src/eoBreeder.h index cd21f0ed..66eb0aed 100644 --- a/eo/src/eoBreeder.h +++ b/eo/src/eoBreeder.h @@ -1,82 +1,103 @@ -//----------------------------------------------------------------------------- -// eoBreeder.h -//----------------------------------------------------------------------------- - -#ifndef eoBreeder_h -#define eoBreeder_h - -//----------------------------------------------------------------------------- - -#include // vector -#include // eoUniform -#include // eoOp, eoMonOp, eoBinOp -#include // eoPop -#include // eoTransform -#include // eoOpSelector - -using namespace std; - -/***************************************************************************** - * eoBreeder: transforms a population using genetic operators. * - * For every operator there is a rated to be applyed. * - *****************************************************************************/ - -template class eoBreeder: public eoTransform -{ - public: - /// Default constructor. - eoBreeder( eoOpSelector& _opSel): opSel( _opSel ) {} - - /// Destructor. - virtual ~eoBreeder() {} - - /** - * Transforms a population. - * @param pop The population to be transformed. - */ - void operator()(eoPop& pop) - { - for (unsigned i = 0; i < pop.size(); i++) { - eoOp* op = opSel.Op(); - switch (op->readArity()) { - case unary: - { - eoMonOp* monop = static_cast* >(op); - (*monop)( pop[i] ); - break; - } - case binary: - { - eoBinOp* binop = static_cast* >(op); - eoUniform u(0, pop.size() ); - (*binop)(pop[i], pop[ u() ] ); - break; - } - case Nary: - { - eoNaryOp* Nop = static_cast* >(op); - eoUniform u(0, pop.size() ); - eoPop inVec, outVec; - inVec.push_back( pop[i] ); - 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& opSel; - -}; - -//----------------------------------------------------------------------------- - -#endif eoBreeder_h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoBreeder.h +// Takes two populations and mixes them +// (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 eoBreeder_h +#define eoBreeder_h + +//----------------------------------------------------------------------------- + +#include // vector +#include // eoUniform +#include // eoOp, eoMonOp, eoBinOp +#include // eoPop +#include // eoTransform +#include // eoOpSelector + +using namespace std; + +/***************************************************************************** + * eoBreeder: transforms a population using genetic operators. * + * For every operator there is a rated to be applyed. * + *****************************************************************************/ + +template class eoBreeder: public eoMonPopOp +{ + public: + /// Default constructor. + eoBreeder( eoOpSelector& _opSel): opSel( _opSel ) {} + + /// Destructor. + virtual ~eoBreeder() {} + + /** + * Transforms a population. + * @param pop The population to be transformed. + */ + void operator()(eoPop& pop) + { + for (unsigned i = 0; i < pop.size(); i++) { + eoOp* op = opSel.Op(); + switch (op->readArity()) { + case unary: + { + eoMonOp* monop = static_cast* >(op); + (*monop)( pop[i] ); + break; + } + case binary: + { + eoBinOp* binop = static_cast* >(op); + eoUniform u(0, pop.size() ); + (*binop)(pop[i], pop[ u() ] ); + break; + } + case Nary: + { + eoNaryOp* Nop = static_cast* >(op); + eoUniform u(0, pop.size() ); + eoPop inVec, outVec; + inVec.push_back( pop[i] ); + 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& opSel; + +}; + +//----------------------------------------------------------------------------- + +#endif eoBreeder_h diff --git a/eo/src/eoDetTournament.h b/eo/src/eoDetTournament.h new file mode 100644 index 00000000..a01fc080 --- /dev/null +++ b/eo/src/eoDetTournament.h @@ -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 // +#include // accumulate +#include // eoPop eoSelect MINFLOAT +#include + +//----------------------------------------------------------------------------- +/** eoDetTournament: a selection method that selects ONE individual by + deterministic tournament + -MS- 24/10/99 */ +//----------------------------------------------------------------------------- + +template class eoDetTournament: public eoSelectOne +{ + 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& pop) { + unsigned best = rng.random(pop.size()); // random individual + + for (unsigned i = 0; i { cout << "WARNING, Number of Standard Deviations > Number of Object Variables\nAdjusted!\n"; num_sigma = num_genes; // modify the Param value - so .status is OK - char sloc[20]; - sprintf(sloc, "%d", num_genes); - parser.setParamValue("--NbSigma", sloc); + ostrstream sloc; + sloc << num_genes; + parser.setParamValue("--NbSigma", sloc.str()); } // adjust the sizes!!! resize(num_genes); diff --git a/eo/src/eoESFullMut.h b/eo/src/eoESFullMut.h index c8bdcb28..d30232af 100644 --- a/eo/src/eoESFullMut.h +++ b/eo/src/eoESFullMut.h @@ -1,243 +1,243 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoESMute.h : ES mutation -// (c) GeNeura Team, 1998 for the EO part -// Th. Baeck 1994 and EEAAX 1999 for the ES part -/* - 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 - http://eeaax.cmap.polytchnique.fr/ - */ -//----------------------------------------------------------------------------- - - -#ifndef _EOESMUT_H -#define _EOESMUT_H - -#include -#include -#include // for exp - -#include -#include - -const double ES_SIGEPS = 1.0e-40; /* ES lower bound for sigma values */ -// should not be a parameter ... - -/** ES-style mutation in the large: Obviously, valid only for eoESInd -*/ -template -class eoESMutate: public eoMonOp< eoESFullChrom > { -public: - /// - eoESMutate( double _TauLcl, double _TauGlb, double _TauBeta ) - : eoMonOp< eoESFullChrom >( ), TauLcl(_TauLcl), TauGlb(_TauGlb), - TauBeta(_TauBeta) {}; - - /* The parser constructor - */ - eoESMutate(Parser & parser, unsigned _stdDevLength, unsigned _size, bool _correlated ): - eoMonOp< eoESFullChrom >( ) { - parser.AddTitle("Parameters of ES mutation (before renormalization)"); - try { // we know that there is at least 1 std dev. - if (_stdDevLength == 1) { - TauLcl = parser.getInt("-Ml", "--TauLcl", "1", - "TauLcl, Mutation rate for the only Std Dev." ); - // different normalization in that case -- Thomas Baeck - TauLcl /= sqrt((double) _size); - } - else { /* more than 1 std dev */ - TauLcl = parser.getFloat("-Ml", "--TauLcl", "1", - "Local mutation rate for Std Dev." ); - TauGlb = parser.getFloat("-Mg", "--TauGlb", "1", - "Global mutation rate for Std Dev." ); - // renormalization - TauLcl /= sqrt( 2.0 * sqrt( (double)_size ) ); - TauGlb /= sqrt( 2.0 * ( (double) _size ) ); - - if ( _correlated ) { // Correlated Mutations - TauBeta = parser.getFloat("-Mb", "--TauBeta", "0.0873", - "Mutation rate for corr. coeff." ); - // rotation angles: no normalization - } - } - } - catch (exception & e) - { - cout << e.what() << endl; - parser.printHelp(); - exit(1); - } - }; - - /// needed virtual dtor - virtual ~eoESMutate() {}; - - // virtual separation depending wether correlated mutations are present - virtual void operator() ( eoESFullChrom & _eo ) const { - if (_eo.CorCffLength()) - CorrelatedMutation(_eo); - else - StandardMutation(_eo); - } - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoESMutate";}; - -private: - /// mutations - standard et correlated - // ========= - /* - * Standard mutation of object variables and standard - * deviations in ESs. - * If there are fewer different standard deviations available - * than the dimension of the objective function requires, the - * last standard deviation is responsible for ALL remaining - * object variables. - * Schwefel 1977: Numerische Optimierung von Computer-Modellen - * mittels der Evolutionsstrategie, pp. 165 ff. - */ - - virtual void StandardMutation( eoESFullChrom & _eo ) const { - unsigned i,k; - double Glb, StdLoc; - - if (_eo.StdDevLength() == 1) { /* single StdDev -> No global factor */ - StdLoc = _eo.getStdDev(0); - StdLoc *= exp(TauLcl*rng.normal()); - if (StdLoc < ES_SIGEPS) - StdLoc = ES_SIGEPS; - _eo.setStdDev(0, StdLoc); - _eo.setGene( 0, _eo.getGene(0) + StdLoc*rng.normal()); - i = 1; - } - else { /* more than one std dev. */ - Glb = exp(TauGlb*rng.normal()); - for (i = 0; i < _eo.length() && i < _eo.StdDevLength(); i++) { - StdLoc = _eo.getStdDev(i); - StdLoc *= Glb * exp(TauLcl*rng.normal()); - if (StdLoc < ES_SIGEPS) - StdLoc = ES_SIGEPS; - _eo.setStdDev(i, StdLoc); - _eo.setGene( i, _eo.getGene(i) + StdLoc*rng.normal()); - } - } - // last object variables: same STdDev than the preceding one - for (k = i; k < _eo.length(); k++) { - _eo.setGene( k, _eo.getGene(k) + StdLoc*rng.normal() ); - } - } - - /* - * Correlated mutations in ESs, according to the following - * sources: - * H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80 - * p. 43, 1980 - * G. Rudolph: Globale Optimierung mit parallelen Evolutions- - * strategien, Diploma Thesis, University of Dortmund, 1990 - */ - - // Code from Thomas Baeck - - virtual void CorrelatedMutation( eoESFullChrom & _eo ) const { - - - int i, k, n1, n2, nq; - - double d1, d2, S, C, Glb; - double tmp; - /* - * First: mutate standard deviations (as above). - */ - - Glb = exp(TauGlb*rng.normal()); - for (i = 0; i < _eo.StdDevLength(); i++) { - tmp = _eo.getStdDev(i); - _eo.setStdDev( i, tmp*Glb*exp(TauLcl*rng.normal()) ); - } - - /* - * Mutate rotation angles. - */ - - for (i = 0; i < _eo.CorCffLength(); i++) { - tmp = _eo.getCorCff(i); - tmp += TauBeta*rng.normal(); - // danger of VERY long loops --MS-- - // while (CorCff[i] > M_PI) - // CorCff[i] -= 2.0 * M_PI; - // while (CorCff[i] < - M_PI) - // CorCff[i] += 2.0 * M_PI; - if ( fabs(tmp) > M_PI ) { - tmp -= M_PI * (int) (tmp/M_PI) ; - } - _eo.setCorCff(i, tmp); - } - - /* - * Perform correlated mutations. - */ - vector VarStp(_eo.size()); - for (i = 0; i < _eo.size() && i < _eo.StdDevLength(); i++) - VarStp[i] = _eo.getStdDev(i)*rng.normal(); - for (k = i; k < _eo.size(); k++) - VarStp[k] = _eo.getStdDev(i-1)*rng.normal(); - nq = _eo.CorCffLength() - 1; - for (k = _eo.size()-_eo.StdDevLength(); k < _eo.size()-1; k++) { - n1 = _eo.size() - k - 1; - n2 = _eo.size() - 1; - for (i = 0; i < k; i++) { - d1 = VarStp[n1]; - d2 = VarStp[n2]; - S = sin( _eo.getCorCff(nq) ); - C = cos( _eo.getCorCff(nq) ); - VarStp[n2] = d1 * S + d2 * C; - VarStp[n1] = d1 * C - d2 * S; - n2--; - nq--; - } - } - for (i = 0; i < _eo.size(); i++) - _eo[i] += VarStp[i]; - - } - // the data - //========= - double TauLcl; /* Local factor for mutation of std deviations */ - double TauGlb; /* Global factor for mutation of std deviations */ - double TauBeta; /* Factor for mutation of correlation parameters */ -}; - -/* - * Correlated mutations in ESs, according to the following - * sources: - * H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80 - * p. 43, 1980 - * G. Rudolph: Globale Optimierung mit parallelen Evolutions- - * strategien, Diploma Thesis, University of Dortmund, 1990 - */ -// Not yet implemented! - -#endif - +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoESMute.h : ES mutation +// (c) GeNeura Team, 1998 for the EO part +// Th. Baeck 1994 and EEAAX 1999 for the ES part +/* + 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 + http://eeaax.cmap.polytchnique.fr/ + */ +//----------------------------------------------------------------------------- + + +#ifndef _EOESMUT_H +#define _EOESMUT_H + +#include +#include +#include // for exp + +#include +#include + +const double ES_SIGEPS = 1.0e-40; /* ES lower bound for sigma values */ +// should not be a parameter ... + +/** ES-style mutation in the large: Obviously, valid only for eoESInd +*/ +template +class eoESMutate: public eoMonOp< eoESFullChrom > { +public: + /// + eoESMutate( double _TauLcl, double _TauGlb, double _TauBeta ) + : eoMonOp< eoESFullChrom >( ), TauLcl(_TauLcl), TauGlb(_TauGlb), + TauBeta(_TauBeta) {}; + + /* The parser constructor + */ + eoESMutate(Parser & parser, unsigned _stdDevLength, unsigned _size, bool _correlated ): + eoMonOp< eoESFullChrom >( ) { + parser.AddTitle("Parameters of ES mutation (before renormalization)"); + try { // we know that there is at least 1 std dev. + if (_stdDevLength == 1) { + TauLcl = parser.getInt("-Ml", "--TauLcl", "1", + "TauLcl, Mutation rate for the only Std Dev." ); + // different normalization in that case -- Thomas Baeck + TauLcl /= sqrt((double) _size); + } + else { /* more than 1 std dev */ + TauLcl = parser.getFloat("-Ml", "--TauLcl", "1", + "Local mutation rate for Std Dev." ); + TauGlb = parser.getFloat("-Mg", "--TauGlb", "1", + "Global mutation rate for Std Dev." ); + // renormalization + TauLcl /= sqrt( 2.0 * sqrt( (double)_size ) ); + TauGlb /= sqrt( 2.0 * ( (double) _size ) ); + + if ( _correlated ) { // Correlated Mutations + TauBeta = parser.getFloat("-Mb", "--TauBeta", "0.0873", + "Mutation rate for corr. coeff." ); + // rotation angles: no normalization + } + } + } + catch (exception & e) + { + cout << e.what() << endl; + parser.printHelp(); + exit(1); + } + }; + + /// needed virtual dtor + virtual ~eoESMutate() {}; + + // virtual separation depending wether correlated mutations are present + virtual void operator() ( eoESFullChrom & _eo ) const { + if (_eo.CorCffLength()) + CorrelatedMutation(_eo); + else + StandardMutation(_eo); + } + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoESMutate";}; + +private: + /// mutations - standard et correlated + // ========= + /* + * Standard mutation of object variables and standard + * deviations in ESs. + * If there are fewer different standard deviations available + * than the dimension of the objective function requires, the + * last standard deviation is responsible for ALL remaining + * object variables. + * Schwefel 1977: Numerische Optimierung von Computer-Modellen + * mittels der Evolutionsstrategie, pp. 165 ff. + */ + + virtual void StandardMutation( eoESFullChrom & _eo ) const { + unsigned i,k; + double Glb, StdLoc; + + if (_eo.StdDevLength() == 1) { /* single StdDev -> No global factor */ + StdLoc = _eo.getStdDev(0); + StdLoc *= exp(TauLcl*rng.normal()); + if (StdLoc < ES_SIGEPS) + StdLoc = ES_SIGEPS; + _eo.setStdDev(0, StdLoc); + _eo.setGene( 0, _eo.getGene(0) + StdLoc*rng.normal()); + i = 1; + } + else { /* more than one std dev. */ + Glb = exp(TauGlb*rng.normal()); + for (i = 0; i < _eo.length() && i < _eo.StdDevLength(); i++) { + StdLoc = _eo.getStdDev(i); + StdLoc *= Glb * exp(TauLcl*rng.normal()); + if (StdLoc < ES_SIGEPS) + StdLoc = ES_SIGEPS; + _eo.setStdDev(i, StdLoc); + _eo.setGene( i, _eo.getGene(i) + StdLoc*rng.normal()); + } + } + // last object variables: same STdDev than the preceding one + for (k = i; k < _eo.length(); k++) { + _eo.setGene( k, _eo.getGene(k) + StdLoc*rng.normal() ); + } + } + + /* + * Correlated mutations in ESs, according to the following + * sources: + * H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80 + * p. 43, 1980 + * G. Rudolph: Globale Optimierung mit parallelen Evolutions- + * strategien, Diploma Thesis, University of Dortmund, 1990 + */ + + // Code from Thomas Baeck + + virtual void CorrelatedMutation( eoESFullChrom & _eo ) const { + + + int i, k, n1, n2, nq; + + double d1, d2, S, C, Glb; + double tmp; + /* + * First: mutate standard deviations (as above). + */ + + Glb = exp(TauGlb*rng.normal()); + for (i = 0; i < _eo.StdDevLength(); i++) { + tmp = _eo.getStdDev(i); + _eo.setStdDev( i, tmp*Glb*exp(TauLcl*rng.normal()) ); + } + + /* + * Mutate rotation angles. + */ + + for (i = 0; i < _eo.CorCffLength(); i++) { + tmp = _eo.getCorCff(i); + tmp += TauBeta*rng.normal(); + // danger of VERY long loops --MS-- + // while (CorCff[i] > M_PI) + // CorCff[i] -= 2.0 * M_PI; + // while (CorCff[i] < - M_PI) + // CorCff[i] += 2.0 * M_PI; + if ( fabs(tmp) > M_PI ) { + tmp -= M_PI * (int) (tmp/M_PI) ; + } + _eo.setCorCff(i, tmp); + } + + /* + * Perform correlated mutations. + */ + vector VarStp(_eo.size()); + for (i = 0; i < _eo.size() && i < _eo.StdDevLength(); i++) + VarStp[i] = _eo.getStdDev(i)*rng.normal(); + for (k = i; k < _eo.size(); k++) + VarStp[k] = _eo.getStdDev(i-1)*rng.normal(); + nq = _eo.CorCffLength() - 1; + for (k = _eo.size()-_eo.StdDevLength(); k < _eo.size()-1; k++) { + n1 = _eo.size() - k - 1; + n2 = _eo.size() - 1; + for (i = 0; i < k; i++) { + d1 = VarStp[n1]; + d2 = VarStp[n2]; + S = sin( _eo.getCorCff(nq) ); + C = cos( _eo.getCorCff(nq) ); + VarStp[n2] = d1 * S + d2 * C; + VarStp[n1] = d1 * C - d2 * S; + n2--; + nq--; + } + } + for (i = 0; i < _eo.size(); i++) + _eo[i] += VarStp[i]; + + } + // the data + //========= + double TauLcl; /* Local factor for mutation of std deviations */ + double TauGlb; /* Global factor for mutation of std deviations */ + double TauBeta; /* Factor for mutation of correlation parameters */ +}; + +/* + * Correlated mutations in ESs, according to the following + * sources: + * H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80 + * p. 43, 1980 + * G. Rudolph: Globale Optimierung mit parallelen Evolutions- + * strategien, Diploma Thesis, University of Dortmund, 1990 + */ +// Not yet implemented! + +#endif + diff --git a/eo/src/eoEasyEA.h b/eo/src/eoEasyEA.h index 6c636649..49a905eb 100644 --- a/eo/src/eoEasyEA.h +++ b/eo/src/eoEasyEA.h @@ -41,9 +41,9 @@ template class eoEasyEA: public eoAlgo { public: /// Constructor. - eoEasyEA(eoSelect& _select, - eoTransform& _transform, - eoMerge& _replace, + eoEasyEA(eoBinPopOp& _select, + eoMonPopOp& _transform, + eoBinPopOp& _replace, eoEvalFunc& _evaluator, eoTerm& _terminator) :step(_select, _transform, _replace, _evaluator), diff --git a/eo/src/eoEvalFunc.h b/eo/src/eoEvalFunc.h index 266303d6..6ff28f2c 100644 --- a/eo/src/eoEvalFunc.h +++ b/eo/src/eoEvalFunc.h @@ -43,7 +43,7 @@ template struct eoEvalFunc { typedef typename EOT::Fitness EOFitT; #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; }; diff --git a/eo/src/eoEvaluator.h b/eo/src/eoEvaluator.h deleted file mode 100644 index 3ddae376..00000000 --- a/eo/src/eoEvaluator.h +++ /dev/null @@ -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 -#include - -//----------------------------------------------------------------------------- -/** Evaluator takes a vector of EOs and evaluates its fitness -* returning void. Template instances must be of fitness and EO type -*/ -template -class eoEvaluator: public eoTransform{ -public: - /// ctor - eoEvaluator( const eoEvalFunc< EOT> & _ef ) - : eoTransform(), 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 diff --git a/eo/src/eoGeneration.h b/eo/src/eoGeneration.h index 1bfec9a2..81c2f50b 100644 --- a/eo/src/eoGeneration.h +++ b/eo/src/eoGeneration.h @@ -1,80 +1,80 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoOp.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 eoGeneration_h -#define eoGeneration_h - -//----------------------------------------------------------------------------- - -#include // eoPop -#include -#include // eoSelect, eoTranform, eoMerge - -//----------------------------------------------------------------------------- -// eoGeneration -//----------------------------------------------------------------------------- - -template class eoGeneration: public eoAlgo -{ - public: - /// Constructor. - eoGeneration(eoSelect& _select, - eoTransform& _transform, - eoMerge& _replace, - eoEvalFunc& _evaluator): - select(_select), transform(_transform), - replace(_replace), evaluator( _evaluator) {}; - - /// Copy Constructor. - eoGeneration(eoGeneration& _gen): - select(_gen.select), transform(_gen.transform), - replace(_gen.replace), evaluator( _gen.evaluator ) {}; - - - /// Apply one generation of evolution to the population. - virtual void operator()(eoPop& pop) { - eoPop breeders; - select(pop, breeders); - transform(breeders); - eoPop::iterator i; - // Can't use foreach here since foreach takes the - // parameter by reference - for ( i = breeders.begin(); i != breeders.end(); i++) - evaluator(*i); - replace(breeders, pop); - } - - /// Class name. - string className() const { return "eoGeneration"; } - - private: - eoSelect& select; - eoTransform& transform; - eoMerge& replace; - eoEvalFunc& evaluator; -}; - -//----------------------------------------------------------------------------- - -#endif eoGeneration_h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoOp.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 eoGeneration_h +#define eoGeneration_h + +//----------------------------------------------------------------------------- + +#include // eoPop +#include +#include // eoSelect, eoTranform, eoMerge + +//----------------------------------------------------------------------------- +// eoGeneration +//----------------------------------------------------------------------------- + +template class eoGeneration: public eoAlgo +{ + public: + /// Constructor. + eoGeneration(eoBinPopOp& _select, + eoMonPopOp& _transform, + eoBinPopOp& _replace, + eoEvalFunc& _evaluator): + select(_select), transform(_transform), + replace(_replace), evaluator( _evaluator) {}; + + /// Copy Constructor. + eoGeneration(eoGeneration& _gen): + select(_gen.select), transform(_gen.transform), + replace(_gen.replace), evaluator( _gen.evaluator ) {}; + + + /// Apply one generation of evolution to the population. + virtual void operator()(eoPop& pop) { + eoPop breeders; + select(pop, breeders); + transform(breeders); + eoPop::iterator i; + // Can't use foreach here since foreach takes the + // parameter by reference + for ( i = breeders.begin(); i != breeders.end(); i++) + evaluator(*i); + replace(breeders, pop); + } + + /// Class name. + string className() const { return "eoGeneration"; } + + private: + eoBinPopOp& select; + eoMonPopOp& transform; + eoBinPopOp& replace; + eoEvalFunc& evaluator; +}; + +//----------------------------------------------------------------------------- + +#endif eoGeneration_h diff --git a/eo/src/eoInclusion.h b/eo/src/eoInclusion.h index 709cb0c0..c776aaaf 100644 --- a/eo/src/eoInclusion.h +++ b/eo/src/eoInclusion.h @@ -7,8 +7,11 @@ //----------------------------------------------------------------------------- -#include // eoPop -#include // eoMerge +#include + +// EO includes +#include +#include /***************************************************************************** * eoInclusion: A replacement algorithm. * @@ -20,7 +23,13 @@ template class eoInclusion: public eoMerge { public: /// (Default) Constructor. - eoInclusion(const float& _rate = 1.0): eoMerge(_rate) {} + eoInclusion(const float& _rate = 1.0): eoMerge( _rate ) {} + + /// Ctor from istream + eoInclusion( istream& _is): eoBinPopOp( _is ) {}; + + /// Dtor + virtual ~eoInclusion() {}; /** * Creates a new population based on breeders and original populations. @@ -38,6 +47,16 @@ template class eoInclusion: public eoMerge greater()); 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";}; + //@} }; //----------------------------------------------------------------------------- diff --git a/eo/src/eoInsertion.h b/eo/src/eoInsertion.h index 0e33cb74..4f1b8a20 100644 --- a/eo/src/eoInsertion.h +++ b/eo/src/eoInsertion.h @@ -1,79 +1,96 @@ -//----------------------------------------------------------------------------- -// eoInsertion.h -//----------------------------------------------------------------------------- - -#ifndef eoInsertion_h -#define eoInsertion_h - -//----------------------------------------------------------------------------- - -#include // eoPop -#include // eoMerge - -/****************************************************************************** - * eoInsertion: A replacement algorithm. - * Creates a new population with all the breeders and the best individuals - * from the original population. - *****************************************************************************/ - -template class eoInsertion: public eoMerge -{ - public: - /// (Default) Constructor. - eoInsertion(const float& _rate = 1.0): eoMerge(_rate) {} - - /** - * Creates a new population based on breeders and original populations. - * @param breeders The population of breeders. - * @param pop The original population. - */ - /*void operator()(eoPop& breeders, eoPop& pop) - { - int new_size = static_cast(pop.size() * rate()); - - if (new_size == breeders.size()) - { - pop = breeders; - } - else if (new_size < breeders.size()) - { - pop = breeders; - sort(pop.begin(), pop.end()); - pop.erase(pop.begin(), pop.begin() - new_size + pop.size()); - } - else - { - sort(pop.begin(), pop.end()); - pop.erase(pop.begin(), - pop.begin() + breeders.size() + pop.size() - new_size); - copy(breeders.begin(), breeders.end(), - back_insert_iterator >(pop)); - } - }*/ - - void operator()(eoPop& breeders, eoPop& pop) - { - unsigned target = static_cast(rint(pop.size() * rate())); - - pop.swap(breeders); - - if (target < pop.size()) - { - partial_sort(pop.begin(), pop.begin() + target, pop.end(), - greater()); - 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()); - copy(breeders.begin(), breeders.begin() + target, - back_insert_iterator >(pop)); - } - } -}; - -//----------------------------------------------------------------------------- - -#endif eoInsertion_h +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoInsertion.h +// Inserts new members into the population +// (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 eoInsertion_h +#define eoInsertion_h + +//----------------------------------------------------------------------------- + +#include + +// EO includes +#include // eoPop +#include // eoMerge + +/****************************************************************************** + * eoInsertion: A replacement algorithm. + * Creates a new population with all the breeders and the best individuals + * from the original population. + *****************************************************************************/ + +template class eoInsertion: public eoMerge +{ + public: + /// (Default) Constructor. + eoInsertion(const float& _rate = 1.0): eoMerge( _rate ) {} + + /// Ctor from istream + eoInsertion( istream& _is): eoBinPopOp( _is ) {}; + + /// Dtor + virtual ~eoInsertion() {}; + + /** + * 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& _breeders, eoPop& _pop) + { + unsigned target = static_cast(rint(_pop.size() * rate())); + + _pop.swap(_breeders); + + if (target < _pop.size()) + { + partial_sort(_pop.begin(), _pop.begin() + target, _pop.end(), + greater()); + _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()); + copy(_breeders.begin(), _breeders.begin() + target, + back_insert_iterator >(_pop)); + } + }; + + /** @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 diff --git a/eo/src/eoLottery.h b/eo/src/eoLottery.h index a009f0b1..60e8bc7a 100644 --- a/eo/src/eoLottery.h +++ b/eo/src/eoLottery.h @@ -1,5 +1,26 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + //----------------------------------------------------------------------------- // 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 @@ -16,14 +37,14 @@ /// requires Chrom::Fitness to be float castable //----------------------------------------------------------------------------- -template class eoLottery: public eoSelect +template class eoLottery: public eoBinPopOp { public: /// (Default) Constructor. eoLottery(const float& _rate = 1.0): rate(_rate) {} /// - void operator()(const eoPop& pop, eoPop& breeders) const + void operator()( eoPop& pop, eoPop& breeders) { // scores of chromosomes vector score(pop.size()); diff --git a/eo/src/eoMerge.h b/eo/src/eoMerge.h new file mode 100644 index 00000000..77b89d51 --- /dev/null +++ b/eo/src/eoMerge.h @@ -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 + +// EO includes +#include // eoPop +#include // eoMerge + +/** + * eoMerge: Base class for replacement algorithms + */ + +template class eoMerge: public eoBinPopOp +{ + public: + /// (Default) Constructor. + eoMerge(const float& _rate = 1.0): eoBinPopOp(), repRate( _rate ) {} + + /// Ctor from istream + eoMerge( istream& _is): eoBinPopOp() { 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& _breeders, eoPop& _pop) + { + unsigned target = static_cast(rint(_pop.size() * rate())); + + _pop.swap(_breeders); + + if (target < _pop.size()) + { + partial_sort(_pop.begin(), _pop.begin() + target, _pop.end(), + greater()); + _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()); + copy(_breeders.begin(), _breeders.begin() + target, + back_insert_iterator >(_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 diff --git a/eo/src/eoMultiBinOp.h b/eo/src/eoMultiBinOp.h new file mode 100644 index 00000000..ddb30c5d --- /dev/null +++ b/eo/src/eoMultiBinOp.h @@ -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 + +#include + +/** MultiMonOp combines several monary operators. By itself, it does nothing to the +EO itīs handled*/ +template +class eoMultiBinOp: public eoBinOp { +public: + /// Ctor from an already existing op + eoMultiBinOp( const eoBinOp* _op ) + : eoBinOp< EOT >( ), vOp(){ + vOp.push_back( _op ); + }; + + /// + eoMultiBinOp( ) + : eoBinOp< EOT >( ), vOp(){}; + + /// Ads a new operator + void adOp( const eoOp* _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* >::const_iterator i = vOp.begin(); + i != vOp.end(); i++ ) { + // Admits only unary or binary operator + switch ((*i)->readArity()) { + case unary: + { + const eoMonOp* monop = static_cast* >(*i); + (*monop)( _eo1 ); + (*monop)( _eo2 ); + break; + } + case binary: + { + const eoBinOp* binop = static_cast* >(*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* > vOp; +}; + +#endif diff --git a/eo/src/eoOp.h b/eo/src/eoOp.h index 5a1cb828..e046824a 100644 --- a/eo/src/eoOp.h +++ b/eo/src/eoOp.h @@ -1,204 +1,204 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoOp.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 _eoOp_H -#define _eoOp_H - -#include -#include -#include - -/** @name Genetic operators - -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 -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 -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. -@author GeNeura Team -@version 0.1 -@see eoOpFactory -*/ -//@{ - -/// -enum Arity { unary = 0, binary = 1, Nary = 2}; - -/** Abstract data types for EO operators. - * 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 - * can have its own operators - */ -template -class eoOp: public eoObject, public eoPrintable { -public: - - /// Ctor - eoOp( Arity _arity = unary ) - :arity( _arity ) {}; - - /// Copy Ctor - eoOp( const eoOp& _eop ) - :arity( _eop.arity ) {}; - - /// Needed virtual destructor - virtual ~eoOp(){}; - - /// Arity: number of operands - Arity readArity() const {return arity;}; - - /** @name Methods from eoObject */ - //@{ - - /** - * Write object. It's called printOn since it prints the object _on_ a stream. - * @param _os A ostream. - */ - virtual void printOn(ostream& _os) const { - _os << className(); -// _os << arity; - }; - - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoOp";}; - //@} - - -private: - /// arity is the number of operands it takes - Arity arity; - -}; - -/** Binary genetic operator: subclasses eoOp, and defines -basically the operator() with two operands -*/ -template -class eoBinOp: public eoOp { -public: - - /// Ctor - eoBinOp() - :eoOp( binary ) {}; - - /// Copy Ctor - eoBinOp( const eoBinOp& _ebop ) - : eoOp( _ebop ){}; - - /// Dtor - ~eoBinOp () {}; - - /** applies operator, to the object. Modifies both operands. - */ - virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoBinOp";}; - //@} - -}; - -/** eoMonOp is the monary operator: genetic operator that takes - only one EO -*/ -template -class eoMonOp: public eoOp { -public: - - /// Ctor - eoMonOp( ) - :eoOp( unary ) {}; - - /// Copy Ctor - eoMonOp( const eoMonOp& _emop ) - : eoOp( _emop ){}; - - /// Dtor - ~eoMonOp() {}; - - /** applies randomly operator, to the object. If arity is more than 1, - * keeps a copy of the operand in a cache. - */ - virtual void operator()( EOType& _eo1) const = 0; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoMonOp";}; - //@} - - -}; - -#include -/** 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 - that takes any number of inputs and spits out any number of outputs -*/ -template -class eoNaryOp: public eoOp { -public: - - /// Ctor - eoNaryOp( ) - :eoOp( Nary ) {}; - - /// Copy Ctor - eoNaryOp( const eoNaryOp& _emop ) - : eoOp( _emop ){}; - - /// Dtor - ~eoNaryOp() {}; - - /** applies randomly operator, to the object. - */ - virtual void operator()( const eoPop & _in, eoPop _out ) const = 0; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject. - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - string className() const {return "eoNaryOp";}; - //@} - -}; -//@} - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoOp.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 _eoOp_H +#define _eoOp_H + +#include +#include +#include + +/** @name Genetic operators + +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 +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 +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. +@author GeNeura Team +@version 0.1 +@see eoOpFactory +*/ +//@{ + +/// +enum Arity { unary = 0, binary = 1, Nary = 2}; + +/** Abstract data types for EO operators. + * 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 + * can have its own operators + */ +template +class eoOp: public eoObject, public eoPrintable { +public: + + /// Ctor + eoOp( Arity _arity = unary ) + :arity( _arity ) {}; + + /// Copy Ctor + eoOp( const eoOp& _eop ) + :arity( _eop.arity ) {}; + + /// Needed virtual destructor + virtual ~eoOp(){}; + + /// Arity: number of operands + Arity readArity() const {return arity;}; + + /** @name Methods from eoObject */ + //@{ + + /** + * Write object. It's called printOn since it prints the object _on_ a stream. + * @param _os A ostream. + */ + virtual void printOn(ostream& _os) const { + _os << className(); +// _os << arity; + }; + + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoOp";}; + //@} + + +private: + /// arity is the number of operands it takes + Arity arity; + +}; + +/** Binary genetic operator: subclasses eoOp, and defines +basically the operator() with two operands +*/ +template +class eoBinOp: public eoOp { +public: + + /// Ctor + eoBinOp() + :eoOp( binary ) {}; + + /// Copy Ctor + eoBinOp( const eoBinOp& _ebop ) + : eoOp( _ebop ){}; + + /// Dtor + ~eoBinOp () {}; + + /** applies operator, to the object. Modifies both operands. + */ + virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0; + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoBinOp";}; + //@} + +}; + +/** eoMonOp is the monary operator: genetic operator that takes + only one EO +*/ +template +class eoMonOp: public eoOp { +public: + + /// Ctor + eoMonOp( ) + :eoOp( unary ) {}; + + /// Copy Ctor + eoMonOp( const eoMonOp& _emop ) + : eoOp( _emop ){}; + + /// Dtor + ~eoMonOp() {}; + + /** applies randomly operator, to the object. If arity is more than 1, + * keeps a copy of the operand in a cache. + */ + virtual void operator()( EOType& _eo1) const = 0; + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoMonOp";}; + //@} + + +}; + +#include +/** 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 + that takes any number of inputs and spits out any number of outputs +*/ +template +class eoNaryOp: public eoOp { +public: + + /// Ctor + eoNaryOp( ) + :eoOp( Nary ) {}; + + /// Copy Ctor + eoNaryOp( const eoNaryOp& _emop ) + : eoOp( _emop ){}; + + /// Dtor + ~eoNaryOp() {}; + + /** applies randomly operator, to the object. + */ + virtual void operator()( const eoPop & _in, eoPop _out ) const = 0; + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoObject. + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoNaryOp";}; + //@} + +}; +//@} + +#endif diff --git a/eo/src/eoParser.h b/eo/src/eoParser.h index df6ed49c..7e110f4e 100644 --- a/eo/src/eoParser.h +++ b/eo/src/eoParser.h @@ -833,7 +833,7 @@ void InitRandom( Parser & parser) { } if (_seed == 0) { // use clock to get a "random" seed - _seed = unsigned long( time( 0 ) ); + _seed = (unsigned long)( time( 0 ) ); ostrstream s; 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 diff --git a/eo/src/eoPop.h b/eo/src/eoPop.h index 89c5c2ff..e6cf0aef 100644 --- a/eo/src/eoPop.h +++ b/eo/src/eoPop.h @@ -1,147 +1,144 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoPop.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 _EOPOP_H -#define _EOPOP_H - -#include -#include - -using namespace std; -// from file - -#include -#include - -/** Subpopulation: it is used to move parts of population - from one algorithm to another and one population to another. It is safer -to declare it as a separate object. I have no idea if a population can be -some other thing that a vector, but if somebody thinks of it, this concrete -implementation will be moved to "generic" and an abstract Population -interface will be provided. -It can be instantiated with anything, provided that it accepts a "size" and a -random generator in the ctor. This happens to all the eo1d chromosomes declared -so far. EOT must also have a copy ctor, since temporaries are created and copied -to the population. -@author Geneura Team -@version 0.0 -*/ - -template -class eoPop: public vector, public eoObject, public eoPersistent { - -/// Type is the type of each gene in the chromosome -#ifdef _MSC_VER - typedef EOT::Type Type; -#else - typedef typename EOT::Type Type; -#endif - - public: - /** Protected ctor. This is intended to avoid creation of void populations, except - from sibling classes - */ - eoPop() - :vector() {}; - - - /** Ctor for fixed-size chromosomes, with variable content - @param _popSize total population size - @param _eoSize chromosome size. EOT should accept a fixed-size ctor - @param _geneRdn random number generator for each of the genes - */ - eoPop( unsigned _popSize, unsigned _eoSize, eoRnd & _geneRnd ) - :vector() { - 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. - @param _geneRdn random number generator for each of the genes - */ - eoPop( unsigned _popSize, eoRnd & _sizeRnd, eoRnd & _geneRnd ) - :vector() { - for ( unsigned i = 0; i < _popSize; i ++ ){ - 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 - */ - eoPop( istream& _is ):vector() { - readFrom( _is ); - } - - /// - ~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. - - */ - virtual void readFrom(istream& _is) { - while( _is ) { // reads line by line, and creates an object per - // line - char line[MAXLINELENGTH]; - _is.getline( line, MAXLINELENGTH-1 ); - if (strlen( line ) ) { - 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, - but since it should be an eoObject anyways, it's no big deal. - */ - virtual void printOn(ostream& _os) const { - copy( begin(), end(), ostream_iterator( _os, "\n") ); - }; - - /** Inherited from eoObject. Returns the class name. - @see eoObject - */ - virtual string className() const {return "eoPop";}; - //@} - - protected: - -}; -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPop.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 _EOPOP_H +#define _EOPOP_H + +#include +#include + +// EO includes +#include +#include + +/** Subpopulation: it is used to move parts of population + from one algorithm to another and one population to another. It is safer +to declare it as a separate object. I have no idea if a population can be +some other thing that a vector, but if somebody thinks of it, this concrete +implementation will be moved to "generic" and an abstract Population +interface will be provided. +It can be instantiated with anything, provided that it accepts a "size" and a +random generator in the ctor. This happens to all the eo1d chromosomes declared +so far. EOT must also have a copy ctor, since temporaries are created and copied +to the population. +@author Geneura Team +@version 0.0 +*/ + +template +class eoPop: public vector, public eoObject, public eoPersistent { + +/// Type is the type of each gene in the chromosome +#ifdef _MSC_VER + typedef EOT::Type Type; +#else + typedef typename EOT::Type Type; +#endif + + public: + /** Protected ctor. This is intended to avoid creation of void populations, except + from sibling classes + */ + eoPop() :vector() {}; + + + /** Ctor for fixed-size chromosomes, with variable content + @param _popSize total population size + @param _eoSize chromosome size. EOT should accept a fixed-size ctor + @param _geneRdn random number generator for each of the genes + */ + eoPop( unsigned _popSize, unsigned _eoSize, eoRnd & _geneRnd ) + :vector() { + 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. + @param _geneRdn random number generator for each of the genes + */ + eoPop( unsigned _popSize, eoRnd & _sizeRnd, eoRnd & _geneRnd ) + :vector() { + for ( unsigned i = 0; i < _popSize; i ++ ){ + 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 + */ + eoPop( istream& _is ):vector() { + readFrom( _is ); + } + + /// + ~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. + + */ + virtual void readFrom(istream& _is) { + while( _is ) { // reads line by line, and creates an object per + // line + char line[MAXLINELENGTH]; + _is.getline( line, MAXLINELENGTH-1 ); + if (strlen( line ) ) { + 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, + but since it should be an eoObject anyways, it's no big deal. + */ + virtual void printOn(ostream& _os) const { + copy( begin(), end(), ostream_iterator( _os, "\n") ); + }; + + /** Inherited from eoObject. Returns the class name. + @see eoObject + */ + virtual string className() const {return "eoPop";}; + //@} + + protected: + +}; +#endif diff --git a/eo/src/eoPopOps.h b/eo/src/eoPopOps.h index 8e817749..6f2eb3b8 100644 --- a/eo/src/eoPopOps.h +++ b/eo/src/eoPopOps.h @@ -1,143 +1,141 @@ -// eoPopOps.h -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eo1d.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 _EOPOPOPS_H -#define _EOPOPOPS_H - -using namespace std; - -/** -@author Geneura Team -@version 0.0 -*/ - -//----------------------------------------------------------------------------- -#include - -//----------------------------------------------------------------------------- -/** eoTransform is a class that transforms or does something on a population. - */ -template -class eoTransform: public eoObject{ - - public: - /** ctor */ - eoTransform() {}; - - /// Dtor - virtual ~eoTransform(){}; - - /// Pure virtual transformation function. Does something on the population - virtual void operator () ( eoPop& _pop ) = 0; - - /** @name Methods from eoObject */ - //@{ - /** readFrom and printOn are not overriden - */ - /** Inherited from eoObject. Returns the class name. - @see eoObject - */ - virtual string className() const {return "eoTransform";}; - //@} - -}; - -//----------------------------------------------------------------------------- - -/** eoSelect usually takes elements from one population, with or without transformation, and transfers them to the other population */ -template -class eoSelect: public eoObject{ - - public: - /** ctor - */ - eoSelect() {}; - - /// Dtor - virtual ~eoSelect(){}; - - /** Pure virtual transformation function. Extracts something from the parents, - and transfers it to the siblings - @param _parents the initial generation. Will be kept constant - @param _siblings the created offspring. Will be usually an empty population - */ - virtual void operator () ( const eoPop& _parents, eoPop& _siblings ) const = 0; - - /** @name Methods from eoObject */ - //@{ - /** readFrom and printOn are not overriden - */ - /** Inherited from eoObject. Returns the class name. - @see eoObject - */ - virtual string className() const {return "eoSelect";}; - //@} - -}; - -/** eoMerge involves three populations, that can be merged and transformed to -give a third -*/ -template -class eoMerge: public eoObject{ - - public: - /// (Default) Constructor. - eoMerge(const float& _rate = 1.0): rep_rate(_rate) {} - - /// Dtor - virtual ~eoMerge() {} - - /** Pure virtual transformation function. Extracts something from breeders - * and transfers it to the pop - * @param breeders Tranformed individuals. - * @param pop The original population at the begining, the result at the end - */ - virtual void operator () ( eoPop& breeders, eoPop& pop ) = 0; - - /** @name Methods from eoObject */ - //@{ - /** readFrom and printOn are not overriden - */ - /** Inherited from eoObject. Returns the class name. - @see eoObject - */ - virtual string className() const {return "eoMerge";}; - //@} - - /// Return the rate to be selected from the original population - float rate() const { return rep_rate; } - - /// Set the rate to be obtained after replacement. - /// @param _rate The rate. - void rate(const float& _rate) { rep_rate = _rate; } - - private: - float rep_rate; -}; - -//----------------------------------------------------------------------------- - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPopOps.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 _EOPOPOPS_H +#define _EOPOPOPS_H + +using namespace std; + +/** +@author Geneura Team +@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 + (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: + EOT eoSelect::operator ( const eoPop& _parents, + const EOT& _first = 0) + added the optional second parameter to transform::operator() +*/ + +//----------------------------------------------------------------------------- +#include + +//----------------------------------------------------------------------------- +/** eoTransform is a class that transforms or does something on a population. + */ +template +class eoMonPopOp: public eoObject{ + + public: + /** ctor */ + eoMonPopOp() {}; + + /// Dtor + virtual ~eoMonPopOp(){}; + + /// Pure virtual transformation function. Does something on the population + virtual void operator () ( eoPop& _pop ) = 0; + + /** @name Methods from eoObject */ + //@{ + /** readFrom and printOn are not overriden + */ + /** Inherited from eoObject. Returns the class name. + @see eoObject + */ + virtual string className() const {return "eoMonPopOp";}; + //@} + +}; + +//----------------------------------------------------------------------------- + +/** eoSelect usually takes elements from one population, with or without transformation, and transfers them to the other population */ +template +class eoBinPopOp: public eoObject{ + + public: + /** ctor + */ + eoBinPopOp() {}; + + /// Dtor + virtual ~eoBinPopOp(){}; + + /** Pure virtual transformation function. Extracts something from the parents, + and transfers it to the siblings + @param _parents the initial generation. Will be kept constant + @param _siblings the created offspring. Will be usually an empty population + */ + virtual void operator () ( eoPop& _parents, eoPop& _siblings ) = 0; + + /** @name Methods from eoObject */ + //@{ + /** readFrom and printOn are not overriden + */ + /** Inherited from eoObject. Returns the class name. + @see eoObject + */ + virtual string className() const {return "eoBinPopOp";}; + //@} + +}; + +//----------------------------------------------------------------------------- + +/** eoSelect usually takes elements from one population, with or without transformation, and transfers them to the other population */ +template +class eoSelectOne: public eoObject{ + + public: + /** ctor + */ + eoSelectOne() {}; + + /// Dtor + virtual ~eoSelectOne(){}; + + /** Pure virtual transformation function. Extracts something from the parents, + and transfers it to the siblings + @param _parents the initial generation. Will be kept constant + @param _siblings the created offspring. Will be usually an empty population + */ + virtual const EOT& operator () ( const eoPop& _parents ) = 0; + + /** @name Methods from eoObject */ + //@{ + /** readFrom and printOn are not overriden + */ + /** Inherited from eoObject. Returns the class name. + @see eoObject + */ + virtual string className() const {return "eoSelectOne";}; + //@} + +}; +#endif diff --git a/eo/src/eoScheme.h b/eo/src/eoScheme.h new file mode 100644 index 00000000..be074e28 --- /dev/null +++ b/eo/src/eoScheme.h @@ -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 +#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 eoScheme: public eoAlgo{ + + 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 (); + ptselect_mate = new eoLottery (); + } + 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(rate); + ptselect_mate = new eoStochTournament(rate); + } else { // determeinistic tournament of size (int)rate + ptselect = new eoDetTournament((int)rate); + ptselect_mate = new eoDetTournament((int)rate); + } + } + // end choice of selection + ptreplace = new eoInclusion(); + // 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(_rate); + ptselect_mate = new eoStochTournament(_rate); + } else { // determeinistic tournament of size (int)rate + ptselect = new eoDetTournament((int)_rate); + ptselect_mate = new eoDetTournament((int)_rate); + } + } + catch (exception & e) + { + cout << e.what() << endl; + parser.printHelp(); + exit(1); + } + // end choice of selection + ptreplace = new eoInclusion(); + // 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(); + ptselect_mate = new eoUniformSelect(); + ptreplace = new eoESPlus(); + } + 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(); + ptselect_mate = new eoUniformSelect(); + ptreplace = new eoESComma(); + } + 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; /* no selection */ + ptselect_mate = new eoUniformSelect(); + /* What, crossover in EP :-) */ + unsigned tsize = parser.getInt("-ET", "--TournamentSize", "6", + "Size of stocahstic replacement tournament" ); + ptreplace = new eoEPTournament(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* PtSelect(){return ptselect;} + eoSelect* PtSelectMate(){return ptselect_mate;} + eoMerge* 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 * ptselect; + eoSelect* ptselect_mate; + eoMerge* 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& 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()); + Fitness oldBest = pop[0].fitness(); // store for elitism + eoPop fertilepop = pop; + if (nb_die_local) + erase(fertilepop.end()-nb_die_local, fertilepop.end()); + + eoPop offspring; // = select(fertilepop, nb_off_local); + select(fertilepop, offspring, nb_off_local); + + // now apply the operators to offspring + for (unsigned i=0; i* 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::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 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()); + if (elitism) { + if ( finalPop[0].fitness() < oldBest ) // best fitness has decreased! + copy(finalPop.end()-1, pop[0]); + } + // return finalPop; + } +*/ diff --git a/eo/src/eoSelfEval.h b/eo/src/eoSelfEval.h new file mode 100644 index 00000000..de4e7816 --- /dev/null +++ b/eo/src/eoSelfEval.h @@ -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 + */ +//----------------------------------------------------------------------------- diff --git a/eo/src/eoSimpleEval.h b/eo/src/eoSimpleEval.h deleted file mode 100644 index 40e735c6..00000000 --- a/eo/src/eoSimpleEval.h +++ /dev/null @@ -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 // for evalFunc -#include // 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 eoSimpleEval: public eoEvaluator { -public: - - /// Ctors/dtors - eoSimpleEval( eoEvalFunc & _ef ):eoEvaluator(_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::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 diff --git a/eo/src/eoStochTournament.h b/eo/src/eoStochTournament.h new file mode 100644 index 00000000..ad82e460 --- /dev/null +++ b/eo/src/eoStochTournament.h @@ -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 // +#include // accumulate +#include // eoPop eoSelect MINFLOAT +#include + +//----------------------------------------------------------------------------- +/** eoStochTournament: a selection method that selects ONE individual by + binary stochastic tournament + -MS- 24/10/99 */ +//----------------------------------------------------------------------------- + +template class eoStochTournament: public eoSelectOne +{ + 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& 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 diff --git a/eo/src/eoUniformSelect.h b/eo/src/eoUniformSelect.h new file mode 100644 index 00000000..8e71e0da --- /dev/null +++ b/eo/src/eoUniformSelect.h @@ -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 // +#include // accumulate +#include // eoPop eoSelect MINFLOAT +#include + +//----------------------------------------------------------------------------- +/** eoUniformSelect: a selection method that selects ONE individual randomly + -MS- 22/10/99 */ +//----------------------------------------------------------------------------- + +template class eoUniformSelect: public eoSelectOne +{ + public: + /// (Default) Constructor. + eoUniformSelect():eoSelectOne() {} + + /// not a big deal!!! + virtual const EOT& operator()(const eoPop& 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 diff --git a/eo/src/eoUniformXOver.h b/eo/src/eoUniformXOver.h new file mode 100644 index 00000000..cf4271c1 --- /dev/null +++ b/eo/src/eoUniformXOver.h @@ -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 +#else +#include +#endif + +// EO includes +#include +#include + +//----------------------------------------------------------------------------- +/** + * EOUniformCrossover: operator for binary chromosomes + * implementation of uniform crossover for EO + * swaps ranges of bits between the parents + */ +//----------------------------------------------------------------------------- + +template +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 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 diff --git a/eo/src/eoXOver2.h b/eo/src/eoXOver2.h index ddb6c41c..ca78bc20 100644 --- a/eo/src/eoXOver2.h +++ b/eo/src/eoXOver2.h @@ -1,106 +1,106 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoXOver2.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 _EOXOVER2_h -#define _EOXOVER2_h - - -// for swap -#if defined( __BORLANDC__ ) -#include -#else -#include -#endif - -// EO includes -#include -#include - -/** 2-point crossover: takes the genes in the central section of two EOs -and interchanges it -*/ -template -class eoXOver2: public eoBinOp { -public: - /// - eoXOver2() - : eoBinOp< EOT >(){}; - - /// - virtual ~eoXOver2() {}; - - /// - virtual void operator()( EOT& _eo1, - EOT& _eo2 ) const { - unsigned len1 = _eo1.length(), len2 = _eo2.length(), - len= (len1 > len2)?len2:len1; - eoUniform uniform( 0, len ); - unsigned pos1 = uniform(), pos2 = uniform() ; - - applyAt( _eo1, _eo2, pos1, pos2 ); - - } - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoOp - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - string className() const {return "eoXOver2";}; - //@} - -private: - -#ifdef _MSC_VER - typedef EOT::Type Type; -#else - typedef typename EOT::Type Type; -#endif - - /// applies operator to one gene in the EO - virtual void applyAt( EOT& _eo, EOT& _eo2, - unsigned _i, unsigned _j = 0) const { - - if ( _j < _i ) - swap( _i, _j ); - - unsigned len1 = _eo.length(), len2 = _eo2.length(), - len= (len1 > len2)?len2:len1; - - if ( (_j > len) || (_i> len ) ) - throw runtime_error( "xOver2: applying xOver past boundaries"); - - for ( unsigned i = _i; i < _j; i++ ) { - Type tmp = _eo.gene( i ); - _eo.gene( i ) = _eo2.gene( i ); - _eo2.gene( i ) = tmp ; - } - - } - -}; - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoXOver2.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 _EOXOVER2_h +#define _EOXOVER2_h + + +// for swap +#if defined( __BORLANDC__ ) +#include +#else +#include +#endif + +// EO includes +#include +#include + +/** 2-point crossover: takes the genes in the central section of two EOs +and interchanges it +*/ +template +class eoXOver2: public eoBinOp { +public: + /// + eoXOver2() + : eoBinOp< EOT >(){}; + + /// + virtual ~eoXOver2() {}; + + /// + virtual void operator()( EOT& _eo1, + EOT& _eo2 ) const { + unsigned len1 = _eo1.length(), len2 = _eo2.length(), + len= (len1 > len2)?len2:len1; + eoUniform uniform( 0, len ); + unsigned pos1 = uniform(), pos2 = uniform() ; + + applyAt( _eo1, _eo2, pos1, pos2 ); + + } + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eoOp + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoXOver2";}; + //@} + +private: + +#ifdef _MSC_VER + typedef EOT::Type Type; +#else + typedef typename EOT::Type Type; +#endif + + /// applies operator to one gene in the EO + virtual void applyAt( EOT& _eo, EOT& _eo2, + unsigned _i, unsigned _j = 0) const { + + if ( _j < _i ) + swap( _i, _j ); + + unsigned len1 = _eo.length(), len2 = _eo2.length(), + len= (len1 > len2)?len2:len1; + + if ( (_j > len) || (_i> len ) ) + throw runtime_error( "xOver2: applying xOver past boundaries"); + + for ( unsigned i = _i; i < _j; i++ ) { + Type tmp = _eo.gene( i ); + _eo.gene( i ) = _eo2.gene( i ); + _eo2.gene( i ) = tmp ; + } + + } + +}; + +#endif