From 415b4196711991ddd3e73e331c8f5d0eda73191c Mon Sep 17 00:00:00 2001 From: evomarc Date: Fri, 9 Feb 2001 05:09:26 +0000 Subject: [PATCH] The BIG change of general operator interface I also changed - the eoQuadratic into eoQuad (as dicussed with Maarten) - the eoBin into eoBit, with more appropriate names for the "binary" operators (that can be unary!) as no one protested when I posted on eodev list --- eo/src/Makefile.am | 2 +- eo/src/eoEvolutionStrategy.h | 101 --- eo/src/eoGenOp.h | 160 +++++ eo/src/eoGeneralBreeder.h | 88 +++ eo/src/eoOp.h | 61 +- eo/src/eoOpContainer.h | 201 ++++++ eo/src/eoPopulator.h | 169 +++++ eo/src/eoProportionalCombinedOp.h | 12 +- eo/src/eoSGA.h | 6 +- eo/src/eoSGATransform.h | 10 +- eo/src/es/eoEsStdevXOver.h | 2 +- eo/src/es/eoGenericRealOp.h | 19 +- eo/src/es/eoRealOp.h | 6 +- eo/src/ga.h | 4 +- eo/src/ga/Makefile.am | 2 +- eo/src/ga/{eoBin.h => eoBit.h} | 22 +- eo/src/ga/eoBitOp.h | 110 ++-- eo/src/ga/eoBitOpFactory.h | 84 ++- eo/src/gp/eoParseTree.h | 42 +- eo/src/{ => obsolete}/eoBackInserter.h | 0 .../{ => obsolete}/eoDetTournamentInserter.h | 0 eo/src/{ => obsolete}/eoGOpBreeder.h | 0 eo/src/{ => obsolete}/eoGOpSelector.h | 0 eo/src/{ => obsolete}/eoIndiSelector.h | 0 eo/src/{ => obsolete}/eoInplaceTransform.h | 0 eo/src/{ => obsolete}/eoInserter.h | 0 eo/src/{ => obsolete}/eoOpFactory.h | 0 eo/src/{ => obsolete}/eoOpSelector.h | 0 eo/src/{ => obsolete}/eoProportionalGOpSel.h | 0 eo/src/{ => obsolete}/eoProportionalOpSel.h | 0 eo/src/{ => obsolete}/eoSequentialGOpSel.h | 0 eo/src/{ => obsolete}/eoSteadyStateEA.h | 0 eo/src/{ => obsolete}/eoSteadyStateInserter.h | 0 .../{ => obsolete}/eoSteadyStateTransform.h | 0 .../eoStochTournamentInserter.h | 0 eo/src/{ => obsolete}/eoWrappedOps.h | 0 eo/src/other/eoExternalOpFunctions.h | 4 +- eo/src/utils/eoParser.cpp | 1 - eo/test/t-eoGenOp.cpp | 359 ++++++++++ eo/tutorial/Lesson1/FirstBitGA.cpp | 11 +- eo/tutorial/Lesson1/FirstRealGA.cpp | 3 +- eo/tutorial/Lesson1/exercise1.3.cpp | 6 +- eo/tutorial/Lesson2/FirstBitEA.cpp | 13 +- eo/tutorial/Lesson2/FirstRealEA.cpp | 3 +- eo/tutorial/Lesson2/exercise2.3.cpp | 10 +- eo/tutorial/Lesson2/real_value.h | 6 +- eo/tutorial/Lesson3/SecondBitEA.cpp | 13 +- eo/tutorial/Lesson3/exercise3.1.cpp | 13 +- eo/tutorial/html/FirstBitEA.html | 616 +++++++++--------- eo/tutorial/html/FirstBitGA.html | 20 +- eo/tutorial/html/FirstRealEA.html | 42 +- eo/tutorial/html/FirstRealGA.html | 497 +++++++------- eo/tutorial/html/Firstmerge.html | 25 +- eo/tutorial/html/SecondBitEA.html | 14 +- eo/tutorial/html/eoCheckPoint.html | 124 ++++ eo/tutorial/html/eoEngine.html | 15 +- eo/tutorial/html/eoLesson1.html | 36 +- eo/tutorial/html/eoLesson2.html | 26 +- eo/tutorial/html/eoProgramming.html | 88 ++- eo/tutorial/html/eoTutorial.html | 4 +- 60 files changed, 2072 insertions(+), 978 deletions(-) delete mode 100644 eo/src/eoEvolutionStrategy.h create mode 100644 eo/src/eoGenOp.h create mode 100644 eo/src/eoGeneralBreeder.h create mode 100644 eo/src/eoOpContainer.h create mode 100644 eo/src/eoPopulator.h rename eo/src/ga/{eoBin.h => eoBit.h} (84%) rename eo/src/{ => obsolete}/eoBackInserter.h (100%) rename eo/src/{ => obsolete}/eoDetTournamentInserter.h (100%) rename eo/src/{ => obsolete}/eoGOpBreeder.h (100%) rename eo/src/{ => obsolete}/eoGOpSelector.h (100%) rename eo/src/{ => obsolete}/eoIndiSelector.h (100%) rename eo/src/{ => obsolete}/eoInplaceTransform.h (100%) rename eo/src/{ => obsolete}/eoInserter.h (100%) rename eo/src/{ => obsolete}/eoOpFactory.h (100%) rename eo/src/{ => obsolete}/eoOpSelector.h (100%) rename eo/src/{ => obsolete}/eoProportionalGOpSel.h (100%) rename eo/src/{ => obsolete}/eoProportionalOpSel.h (100%) rename eo/src/{ => obsolete}/eoSequentialGOpSel.h (100%) rename eo/src/{ => obsolete}/eoSteadyStateEA.h (100%) rename eo/src/{ => obsolete}/eoSteadyStateInserter.h (100%) rename eo/src/{ => obsolete}/eoSteadyStateTransform.h (100%) rename eo/src/{ => obsolete}/eoStochTournamentInserter.h (100%) rename eo/src/{ => obsolete}/eoWrappedOps.h (100%) create mode 100644 eo/test/t-eoGenOp.cpp create mode 100644 eo/tutorial/html/eoCheckPoint.html diff --git a/eo/src/Makefile.am b/eo/src/Makefile.am index 1aff3ab60..0fc3b2887 100644 --- a/eo/src/Makefile.am +++ b/eo/src/Makefile.am @@ -11,4 +11,4 @@ lib_LIBRARIES = libeo.a libeo_a_SOURCES = eoPrintable.cpp eoPersistent.cpp eoFunctorStore.cpp libeoincdir = $(includedir)/eo -libeoinc_HEADERS = eo EO.h apply.h eoAlgo.h eoBackInserter.h eoBreed.h eoCombinedContinue.h eoContinue.h eoCounter.h eoDetSelect.h eoDetTournamentInserter.h eoDetTournamentSelect.h eoEasyEA.h eoEvalFunc.h eoEvalFuncPtr.h eoEvolutionStrategy.h eoFactory.h eoFitContinue.h eoFitnessScalingSelect.h eoFixedLength.h eoFunctor.h eoFunctorStore.h eoGOpBreeder.h eoGOpSelector.h eoGenContinue.h eoGenericBinOp.h eoGenericMonOp.h eoGenericQuadOp.h eoIndiSelector.h eoInit.h eoInplaceTransform.h eoInserter.h eoMerge.h eoMergeReduce.h eoObject.h eoOp.h eoOpFactory.h eoOpSelMason.h eoOpSelector.h eoPersistent.h eoPop.h eoPrintable.h eoProportionalCombinedOp.h eoProportionalGOpSel.h eoProportionalOpSel.h eoProportionalSelect.h eoRandomSelect.h eoRankingSelect.h eoReduce.h eoReduceMerge.h eoReplacement.h eoSGA.h eoSGATransform.h eoScalarFitness.h eoSelect.h eoSelectFactory.h eoSelectMany.h eoSelectNumber.h eoSelectOne.h eoSelectPerc.h eoSequentialGOpSel.h eoSteadyFitContinue.h eoSteadyStateEA.h eoSteadyStateInserter.h eoSteadyStateTransform.h eoStochTournamentInserter.h eoStochTournamentSelect.h eoSurviveAndDie.h eoTransform.h eoVariableLength.h eoVariableLengthCrossover.h eoVariableLengthMutation.h eoWrappedOps.h es.h ga.h +libeoinc_HEADERS = eo EO.h apply.h eoAlgo.h eoBreed.h eoCombinedContinue.h eoContinue.h eoCounter.h eoDetSelect.h eoDetTournamentSelect.h eoEasyEA.h eoEvalFunc.h eoEvalFuncPtr.h eoEvolutionStrategy.h eoFactory.h eoFitContinue.h eoFitnessScalingSelect.h eoFixedLength.h eoFunctor.h eoFunctorStore.h eoGenContinue.h eoGenericBinOp.h eoGenericMonOp.h eoGenericQuadOp.h eoInit.h eoMerge.h eoMergeReduce.h eoObject.h eoOp.h eoOpSelMason.h eoPersistent.h eoPop.h eoPrintable.h eoProportionalCombinedOp.h eoProportionalSelect.h eoRandomSelect.h eoRankingSelect.h eoReduce.h eoReduceMerge.h eoReplacement.h eoSGA.h eoSGATransform.h eoScalarFitness.h eoSelect.h eoSelectFactory.h eoSelectMany.h eoSelectNumber.h eoSelectOne.h eoSelectPerc.h eoSteadyFitContinue.h eoStochTournamentSelect.h eoSurviveAndDie.h eoTransform.h eoVariableLength.h eoVariableLengthCrossover.h eoVariableLengthMutation.h es.h ga.h diff --git a/eo/src/eoEvolutionStrategy.h b/eo/src/eoEvolutionStrategy.h deleted file mode 100644 index b863ae8a4..000000000 --- a/eo/src/eoEvolutionStrategy.h +++ /dev/null @@ -1,101 +0,0 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoEvolutionStrategy.h -// (c) Maarten Keijzer 2000, 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 _eoEvolutionStrategy_h -#define _eoEvolutionStrategy_h - -//----------------------------------------------------------------------------- - -#include -#include -/** eoEvolutionStrategy: -*/ - -template -class eoEvolutionStrategy: public eoAlgo -{ - public: - struct plus_strategy{}; - struct comma_strategy{}; - - eoEvolutionStrategy( - eoContinue& _continuator, - eoEvalFunc& _eval, - eoGOpSelector& _opSel, - float _lambdaRate, - comma_strategy) - : selectPerc(randomSelect, _lambdaRate), - transform(_opSel), - easyEA(_continuator, _eval, selectPerc, transform, noElitism, truncate) - {} - - eoEvolutionStrategy( - eoContinue& _continuator, - eoEvalFunc& _eval, - eoGOpSelector& _opSel, - float _lambdaRate, - plus_strategy) - : selectPerc(randomSelect, _lambdaRate), - transform(_opSel), - easyEA(_continuator, _eval, selectPerc, transform, plus, truncate) - {} - - - /// Apply a few generation of evolution to the population. - virtual void operator()(eoPop& _pop) - { - easyEA(_pop); - } - - private: - - eoPlus plus; - eoNoElitism noElitism; - eoTruncate truncate; - eoRandomSelect randomSelect; - eoSelectPerc selectPerc; - eoInplaceTransform2 transform; - - /// easyEA is contained rather than a base because of member initialization order! - eoEasyEA easyEA; -}; - -template -eoEvolutionStrategy make_es(eoContinue& _continuator, - eoEvalFunc& _eval, - eoGOpSelector& _opSel, - float _lambdaRate, - bool _comma) - -{ - if (_comma) - return eoEvolutionStrategy(_continuator, _eval, _opSel, _lambdaRate, eoEvolutionStrategy::comma_strategy()); - //else - return eoEvolutionStrategy(_continuator, _eval, _opSel, _lambdaRate, eoEvolutionStrategy::plus_strategy()); -} - -//----------------------------------------------------------------------------- - -#endif eoSelectTransformReduce_h - diff --git a/eo/src/eoGenOp.h b/eo/src/eoGenOp.h new file mode 100644 index 000000000..badbde71c --- /dev/null +++ b/eo/src/eoGenOp.h @@ -0,0 +1,160 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoGenOp.h +// (c) Maarten Keijzer and Marc Schoenauer, 2001 +/* + 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: mkeijzer@dhi.dk + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _eoGenOp_H +#define _eoGenOp_H + +#include +#include + + +/** @name General variation operators + +a class that allows to use i->j operators for any i and j +thanks to the friend class eoPopulator + +@author Maarten Keijzer +@version 0.0 +*/ + + +/** The base class for General Operators + */ +template +class eoGenOp : public eoOp, public eoUF &, void> +{ + public : + /// Ctor that honors its superclass + eoGenOp(): eoOp( eoOp::general ) {} + + virtual unsigned max_production(void) = 0; + virtual string className() = 0; + void operator()(eoPopulator& _pop) + { + _pop.reserve(max_production()); + apply(_pop); + } + + protected : + /** the function that will do the work + */ + virtual void apply(eoPopulator& _pop) = 0; +}; + + +/** Wrapper for eoMonOp */ +template +class eoMonGenOp : public eoGenOp +{ + public: + eoMonGenOp(eoMonOp& _op) : op(_op) {} + + unsigned max_production(void) { return 1; } + + void apply(eoPopulator& _it) + { + op(*_it); // look how simple + + } + string className() {return op.className();} + private : + eoMonOp& op; +}; + +/** Wrapper for binop: here we use erase method of eoPopulator + * but we could also have an embedded selector to select the second parent + */ +template +class eoBinGenOp : public eoGenOp +{ + public: + eoBinGenOp(eoBinOp& _op) : op(_op) {} + + unsigned max_production(void) { return 1; } + + /** do the work: get 2 individuals from the population, modifies + only one (it's a eoBinOp) and erases the non-midified one + */ + void apply(eoPopulator& _pop) + { + EOT& a = *_pop; + EOT& b = *++_pop; + op(a, b); + _pop.erase(); + } + string className() {return op.className();} + + private : + eoBinOp& op; +}; + +/** wrapper for eoBinOp with a selector */ +template +class eoSelBinGenOp : public eoGenOp +{ + public: + eoSelBinGenOp(eoBinOp& _op, eoSelectOne& _sel) : + op(_op), sel(_sel) {} + + unsigned max_production(void) { return 1; } + + void apply(eoPopulator& _pop) + { // _pop.source() gets the original population, an eoVecOp can make use of this as well + op(*_pop, sel(_pop.source())); + } + string className() {return op.className();} + + private : + eoBinOp& op; + eoSelectOne& sel; +}; + + +/** Wrapper for quadop: easy as pie + */ +template +class eoQuadGenOp : public eoGenOp +{ + public: + eoQuadGenOp(eoQuadOp& _op) : op(_op) {} + + unsigned max_production(void) { return 2; } + + void apply(eoPopulator& _pop) + { + EOT& a = *_pop; + EOT& b = *++_pop; + + op(a, b); + } + string className() {return op.className();} + + private : + eoQuadOp& op; +}; + + +#endif + diff --git a/eo/src/eoGeneralBreeder.h b/eo/src/eoGeneralBreeder.h new file mode 100644 index 000000000..0c0e4c8fc --- /dev/null +++ b/eo/src/eoGeneralBreeder.h @@ -0,0 +1,88 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoGeneralBreeder.h +// (c) Maarten Keijzer and Marc Schoenauer, 2001 +/* + 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: mkeijzer@dhi.dk + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef eoGeneralBreeder_h +#define eoGeneralBreeder_h + +//----------------------------------------------------------------------------- + +/***************************************************************************** + * eoGeneralBreeder: transforms a population using the generalOp construct. + *****************************************************************************/ + +#include +#include + +/** + Base class for breeders using generalized operators. +*/ +template +class eoGeneralBreeder: public eoBreed +{ + public: + /** Ctor: + * + * @param _select a selectoOne, to be used for all selections + * @param _op a general operator (will generally be an eoOpContainer) + * @param _rate pour howMany, le nbre d'enfants a generer + * @param _interpret_as_rate explanation + */ + eoGeneralBreeder( eoSelectOne& _select, eoGenOp& _op, + double _rate=1.0, bool _interpret_as_rate = true) : + select( _select ), op(_op), howMany(_rate, _interpret_as_rate) {} + + /** The breeder: simply calls the genOp on a selective populator! + * + * @param _parents the initial population + * @param _offspring the resulting population (content -if any- is lost) + */ + void operator()(const eoPop& _parents, eoPop& _offspring) + { + unsigned target = howMany(_parents.size()); + + eoSelectivePopulator it(_parents, select); + + select.setup(_parents); + + while (it.size() < target) + { + op(it); + } + + swap(_offspring, it); + _offspring.resize(target); // you might have generated a few more + } + + /// The class name. + string className() const { return "eoGeneralBreeder"; } + + private: + eoSelectOne& select; + eoGenOp& op; + eoHowMany howMany; +}; + +#endif eoBreeder_h + diff --git a/eo/src/eoOp.h b/eo/src/eoOp.h index e1902a5d5..dfbaecab8 100644 --- a/eo/src/eoOp.h +++ b/eo/src/eoOp.h @@ -35,11 +35,22 @@ Genetic Operators are used for various purposes /** @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 and eoQuadraticOp (binary operators) as siblings). Nobody should subclass eoOp, you should subclass eoGeneralOp, eoBinOp, eoQuadraticOp 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. +What is a genetic algorithm without genetic operators? +There is a genetic operator hierarchy, with eoOp as father and +eoMonOp (monary or unary operator), eoBinOp and eoQuadOp (binary operators) +and eoGenOp (any number of inputs and outputs, see eoGenOp.h) +as subclasses. +Nobody should subclass eoOp, you should subclass eoGenOp, eoBinOp, eoQuadOp +or eoMonOp, those are the ones actually used here. -@author GeNeura Team -@version 0.1 -@see eoOpFactory +#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, Marten Keijzer and Marc Schoenauer +@version 0.9 +@see eoGenOp.h eoOpFactory */ @@ -102,17 +113,14 @@ public: virtual string className() const {return "eoBinOp";}; }; -// planning the change of name eoQuadraticOp --> eoQuadOp -#define eoQuadraticOp eoQuadOp - -/** Quadratic genetic operator: subclasses eoOp, and defines basically the +/** Quad genetic operator: subclasses eoOp, and defines basically the operator() with two operands, both can be modified. */ template -class eoQuadraticOp: public eoOp, public eoBF { +class eoQuadOp: public eoOp, public eoBF { public: /// Ctor - eoQuadraticOp() + eoQuadOp() :eoOp( eoOp::quadratic ) {}; virtual string className() const {return "eoQuadOp";}; }; @@ -145,38 +153,5 @@ private: eoQuadOp & quadOp; }; -// some forward declarations - -template - -class eoIndiSelector; - - -template - -class eoInserter; - - -/** - * eGeneralOp: General genetic operator; for objects used to transform sets - * of EOs. Nary ("orgy") operators should be derived from this class - - Derived from eoB(inary)F(unction) - Applies the genetic operator - to a individuals dispensed by an eoIndividualSelector, - and puts the results in the eoIndividualInserter. - Any number of inputs can be requested and any number of outputs - can be produced. - */ - -template - -class eoGeneralOp: public eoOp, public eoBF&, eoInserter&, void> -{ -public: - /// Ctor that honors its superclass - eoGeneralOp(): eoOp( eoOp::general ) {} -}; - #endif diff --git a/eo/src/eoOpContainer.h b/eo/src/eoOpContainer.h new file mode 100644 index 000000000..fd64289b9 --- /dev/null +++ b/eo/src/eoOpContainer.h @@ -0,0 +1,201 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoOpContainer.h +// (c) Maarten Keijzer and Marc Schoenauer, 2001 +/* + 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: mkeijzer@dhi.dk + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _eoOpContainer_H +#define _eoOpContainer_H + +#include + +/** eoOpContainer is a base class for the sequential and proportional selectors + * It takes care of wrapping the other operators, + * and deleting stuff that it has allocated + * + * Warning: all operators are added together with a rate (double) + * However, the meaning of this rate will be different in + * the differnet instances of eoOpContainer: + * an ***absolute*** probability in the sequential version, and + * a ***relative*** weight in the proportional version + */ +template +class eoOpContainer : public eoGenOp +{ + public : + /** Ctor: nothing much to do */ + eoOpContainer() : max_to_produce(0) {} + + /** Dtor: delete all the GenOps created when wrapping simple ops + */ + virtual ~eoOpContainer(void) + { + for (unsigned i = 0; i < owned_genops.size(); ++i) + delete owned_genops[i]; + } + + /** for memory management (doesn't have to be very precise */ + virtual unsigned max_production(void) + { + return max_to_produce; + } + + /** wraps then add a simple eoMonOp */ + void add(eoMonOp& _op, double _rate) + { + owned_genops.push_back(new eoMonGenOp(_op)); + ops.push_back(owned_genops.back()); + rates.push_back(_rate); + + max_to_produce = max(max_to_produce,unsigned(1)); + } + + /** wraps then add a simple eoBinOp + * First case, no selector + */ + void add(eoBinOp& _op, double _rate) + { + owned_genops.push_back(new eoBinGenOp(_op)); + ops.push_back(owned_genops.back()); + rates.push_back(_rate); + + max_to_produce = max(max_to_produce,unsigned(1)); + } + + /** wraps then add a simple eoBinOp + * Second case: a sepecific selector + */ + void add(eoBinOp& _op, eoSelectOne & _sel, double _rate) + { + owned_genops.push_back(new eoSelBinGenOp(_op, _sel)); + ops.push_back(owned_genops.back()); + rates.push_back(_rate); + + max_to_produce = max(max_to_produce,unsigned(1)); + } + + /** wraps then add a simple eoQuadOp */ + void add(eoQuadOp& _op, double _rate) + { + owned_genops.push_back(new eoQuadGenOp(_op)); + ops.push_back(owned_genops.back()); + rates.push_back(_rate); + + max_to_produce = max(max_to_produce,unsigned(2)); +} + + /** can add any GenOp */ + void add(eoGenOp& _op, double _rate) + { + ops.push_back(&_op); + rates.push_back(_rate); + + max_to_produce = max(max_to_produce,_op.max_production()); + } + + virtual string className() = 0; + + protected : + + vector rates; + vector*> ops; + + private : + vector*> owned_genops; + unsigned max_to_produce; +}; + +/** Sequential selection: + * note the mark, rewind, unmark cycle + * here operators are repeatedly applied on the same individual(s) + * not all too elegant, but it sort of works... + */ +template +class eoSequentialOp : public eoOpContainer +{ + public : + typedef unsigned position_type; + + + void apply(eoPopulator& _pop) + { + position_type pos = _pop.tellp(); + + for (size_t i = 0; i < rates.size(); ++i) + { + _pop.seekp(pos); + + do + { + if (eo::rng.flip(rates[i])) + { + // try + // { + // apply it to all the guys in the todo list + (*ops[i])(_pop); + // } + // check for out of individuals and do nothing with that... + // catch(eoPopulator::OutOfIndividuals&) + // { + // cout << "Warning: not enough individuals to handle\n"; + // return ; + // } + } + + if (!_pop.exhausted()) + ++_pop; + } + while (!_pop.exhausted()); + } + } + virtual string className() {return "SequentialOp";} + + private : + + vector to_apply; + vector production; +}; + + +/** The proportinoal verions: easy! */ +template +class eoProportionalOp : public eoOpContainer +{ + public : + + void apply(eoPopulator& _pop) + { + unsigned i = eo::rng.roulette_wheel(rates); + + try + { + (*ops[i])(_pop); + } + catch(eoPopulator::OutOfIndividuals&) + {} + } + virtual string className() {return "ProportionalOp";} +}; + + +#endif + diff --git a/eo/src/eoPopulator.h b/eo/src/eoPopulator.h new file mode 100644 index 000000000..eb4814608 --- /dev/null +++ b/eo/src/eoPopulator.h @@ -0,0 +1,169 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoPopulator.h +// (c) Maarten Keijzer and Marc Schoenauer, 2001 +/* + 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: mkeijzer@dhi.dk + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +#ifndef _eoPopulator_H +#define _eoPopulator_H + +#include +#include + +template +class eoPopulator : public eoPop +{ +public : + + eoPopulator(const eoPop& _src) : current(begin()), src(_src) {} + + struct OutOfIndividuals {}; + + /** a populator behaves like an iterator. Hence the operator* + * it returns the current individual -- eventually getting + * a new one through the operator++ if at the end + */ + EOT& operator*(void) + { + if (current == end()) + operator++(); + + return *current; + } + + /** only prefix increment defined + * if needed, adds a new individual using the embedded selector + * and set the current pointer to the newly inserted individual + * otherwise simply increment the current pointer + */ + eoPopulator& operator++() + { + if (current == end()) + { // get new individual from derived class select() + push_back(select()); + current = end(); + --current; + return *this; + } + // else + ++current; + return *this; + } + + /** mandatory for operators that generate more offspring than parents + * if such a thing exists ? + */ + void insert(const EOT& _eo) + { /* not really efficient, but its nice to have */ + current = eoPop::insert(current, _eo); + } + + /** useful for operators that generate less offspring than parents + * though there is another way - using a selector *within* + * the operator to get the extra parents from outside + */ + void erase() + { + current = eoPop::erase(current); + } + + /** just to make memory mangement more efficient + */ + void reserve(int how_many) + { + size_t sz = current - begin(); + eoPop::reserve(size() + how_many); + current = begin() + sz; + } + + /** can be useful for operators with embedded selectors + * e.g. your barin and my beauty -type + */ + const eoPop& source(void) { return src; } + + typedef unsigned position_type; + + /** this is a direct access container: tell position */ + position_type tellp() { return current - begin(); } + /** this is a direct access container: go to position */ + void seekp(position_type pos) { current = begin() + pos; } + /** no more individuals */ + bool exhausted(void) { return current == end(); } + +protected : + /** the pure virtual selection method - will be instanciated in + * eoSeqPopulator and eoPropPopulator + */ + virtual const EOT& select() = 0; + eoPop::iterator current; + const eoPop& src; +}; + + +/** SeqPopulator: an eoPopulator that sequentially goes through the population +is supposed to be used after a batch select of a whole bunch or genitors + */ +template +class eoSeqPopulator : public eoPopulator +{ +public : + + eoSeqPopulator(const eoPop& _pop) : + eoPopulator(_pop), src_it(_pop.begin()) {} + + const EOT& select(void) + { + if (src_it == src.end()) + { + throw OutOfIndividuals(); + } + + const EOT& res = *src_it++; + return res; + } + +private : + vector::const_iterator src_it; +}; + + +/** SelectivePopulator an eoPoplator that uses an eoSelectOne to select guys. +Supposedly, it is passed the initial population. + */ +template +class eoSelectivePopulator : public eoPopulator +{ +public : + eoSelectivePopulator(const eoPop& _pop, eoSelectOne& _sel) + : eoPopulator(_pop), sel(_sel) {} + + const EOT& select() + { + return sel(src); + } + +private : + eoSelectOne& sel; +}; + +#endif + diff --git a/eo/src/eoProportionalCombinedOp.h b/eo/src/eoProportionalCombinedOp.h index 5d52719b4..20b3eb7a9 100644 --- a/eo/src/eoProportionalCombinedOp.h +++ b/eo/src/eoProportionalCombinedOp.h @@ -172,21 +172,21 @@ std::vector rates; //// combined QuadOp ////////////////////////////////////////////////////// -/** Quadratic genetic operator: subclasses eoOp, and defines basically the +/** Quad genetic operator: subclasses eoOp, and defines basically the operator() with two operands, both can be modified. */ -/** COmbined quadratic genetic operator: +/** Combined quad genetic operator: * operator() has two operands, both can be modified * generic operators are now allowed: there are imbedded into * the corresponding "true" operator */ template -class eoPropCombinedQuadOp: public eoQuadraticOp +class eoPropCombinedQuadOp: public eoQuadOp { public: /// Ctor from a true operator - eoPropCombinedQuadOp(eoQuadraticOp & _first, const double _rate) + eoPropCombinedQuadOp(eoQuadOp & _first, const double _rate) { ops.push_back(&_first); rates.push_back(_rate); @@ -204,7 +204,7 @@ public: virtual string className() const { return "eoPropCombinedQuadOp"; } // addition of a true operator -virtual void add(eoQuadraticOp & _op, const double _rate, bool _verbose=false) +virtual void add(eoQuadOp & _op, const double _rate, bool _verbose=false) { ops.push_back(&_op); rates.push_back(_rate); @@ -242,7 +242,7 @@ virtual void add(eoGenericQuadOp & _op, const double _rate, bool _verbose=f (*ops[what])(_indi1, _indi2); // apply it } private: -std::vector*> ops; +std::vector*> ops; std::vector rates; }; diff --git a/eo/src/eoSGA.h b/eo/src/eoSGA.h index cb55fe4f8..53054658e 100644 --- a/eo/src/eoSGA.h +++ b/eo/src/eoSGA.h @@ -37,7 +37,7 @@ #include /** The Simple Genetic Algorithm, following Holland and Goldberg - * Needs a selector (class eoSelectOne) a crossover (eoQuadratic, + * Needs a selector (class eoSelectOne) a crossover (eoQuad, * i.e. a 2->2 operator) and a mutation with their respective rates, * of course an evaluation function (eoEvalFunc) and a continuator * (eoContinue) which gives the stopping criterion. Performs full @@ -53,7 +53,7 @@ public : // in the one above. Any objection :-) MS eoSGA( eoSelectOne& _select, - eoQuadraticOp& _cross, float _crate, + eoQuadOp& _cross, float _crate, eoMonOp& _mutate, float _mrate, eoEvalFunc& _eval, eoContinue& _cont) @@ -103,7 +103,7 @@ private : eoContinue& cont; eoMonOp& mutate; float mutationRate; - eoQuadraticOp& cross; + eoQuadOp& cross; float crossoverRate; eoSelectPerc select; eoEvalFunc& eval; diff --git a/eo/src/eoSGATransform.h b/eo/src/eoSGATransform.h index a3237b9b7..98af3dd50 100644 --- a/eo/src/eoSGATransform.h +++ b/eo/src/eoSGATransform.h @@ -48,7 +48,7 @@ template class eoSGATransform : public eoTransform public: /// Default constructor. - eoSGATransform(eoQuadraticOp& _cross, double _cProba, + eoSGATransform(eoQuadOp& _cross, double _cProba, eoMonOp& _mutate, double _mProba) : cross(_cross), crossoverProba(_cProba), @@ -84,7 +84,7 @@ template class eoSGATransform : public eoTransform }; private: - eoQuadraticOp& cross; + eoQuadOp& cross; double crossoverProba; eoMonOp& mutate; double mutationProba; @@ -102,7 +102,7 @@ template class eoDynSGATransform : public eoTransform public: /// Default constructor - receives values - eoDynSGATransform(eoQuadraticOp& _cross, double _cProba, + eoDynSGATransform(eoQuadOp& _cross, double _cProba, eoMonOp& _mutate, double _mProba) : cross(_cross), crossoverProbaHolder(_cProba), crossoverProba(crossoverProbaHolder), @@ -112,7 +112,7 @@ template class eoDynSGATransform : public eoTransform /// This constructor receives pointers // these will usually be some eoValueParam.value() // hence the ...Holder data will bever be used in this case - eoDynSGATransform(eoQuadraticOp& _cross, double* _cProbaRef, + eoDynSGATransform(eoQuadOp& _cross, double* _cProbaRef, eoMonOp& _mutate, double* _mProbaRef) : cross(_cross), crossoverProbaHolder(0), crossoverProba(*_cProbaRef), @@ -154,7 +154,7 @@ private: // difference with eoSGATransform: the operator probabilities // they can be passed by reference or by value. // hence we need here to use a reference, and to eventually store a value - eoQuadraticOp& cross; + eoQuadOp& cross; double crossoverProbaHolder; // the value, used only if ctor gets a value double& crossoverProba; // the reference, to be used in operator() eoMonOp& mutate; diff --git a/eo/src/es/eoEsStdevXOver.h b/eo/src/es/eoEsStdevXOver.h index fd3b37fcd..035cdf782 100644 --- a/eo/src/es/eoEsStdevXOver.h +++ b/eo/src/es/eoEsStdevXOver.h @@ -41,7 +41,7 @@ Simply calls a crossover for the object variables, */ template -class eoEsStdevXOver : public eoQuadraticOp +class eoEsStdevXOver : public eoQuadOp { public : eoEsStdevXOver(eoGenericQuadOp > & _objectXOver, diff --git a/eo/src/es/eoGenericRealOp.h b/eo/src/es/eoGenericRealOp.h index 37596f520..c29fd1629 100644 --- a/eo/src/es/eoGenericRealOp.h +++ b/eo/src/es/eoGenericRealOp.h @@ -47,7 +47,10 @@ MS January 25. 2001 /** eoUniformMutation --> changes all values of the vector by uniform choice with range epsilon with probability p_change per variable +\class eoUniformMutation eoRealOp.h Tutorial/eoRealOp.h +\ingroup parameteric */ + template class eoGenericUniformMutation: public eoGenericMonOp { public: @@ -110,6 +113,8 @@ private: /** eoDetUniformMutation --> changes exactly k values of the vector by uniform choice with range epsilon +\class eoDetUniformMutation eoRealOp.h Tutorial/eoRealOp.h +\ingroup parameteric */ template class eoGenericDetUniformMutation: @@ -168,10 +173,14 @@ private: }; +// two arithmetical crossovers /** eoSegmentCrossover --> uniform choice in segment - == arithmetical with same value along all coordinates + == arithmetical with same value along all coordinates +\class eoSegmentCrossover eoRealOp.h Tutorial/eoRealOp.h +\ingroup parameteric */ + template class eoGenericSegmentCrossover: public eoGenericQuadOp { public: @@ -257,8 +266,11 @@ protected: }; /** eoArithmeticCrossover --> uniform choice in hypercube - == arithmetical with different values for each coordinate + == arithmetical with different values for each coordinate +\class eoArithmeticCrossover eoRealOp.h Tutorial/eoRealOp.h +\ingroup parameteric */ + template class eoGenericArithmeticCrossover: public eoGenericQuadOp { @@ -354,7 +366,10 @@ protected: /** eoRealUxOver --> Uniform crossover, also termed intermediate crossover +\class eoRealUxOver eoRealOp.h Tutorial/eoRealOp.h +\ingroup parameteric */ + template class eoGenericRealUxOver: public eoGenericQuadOp { public: diff --git a/eo/src/es/eoRealOp.h b/eo/src/es/eoRealOp.h index 586453a52..052386715 100644 --- a/eo/src/es/eoRealOp.h +++ b/eo/src/es/eoRealOp.h @@ -168,7 +168,7 @@ private: \ingroup parameteric */ -template class eoSegmentCrossover: public eoQuadraticOp +template class eoSegmentCrossover: public eoQuadOp { public: /** @@ -259,7 +259,7 @@ protected: \ingroup parameteric */ -template class eoArithmeticCrossover: public eoQuadraticOp +template class eoArithmeticCrossover: public eoQuadOp { public: /** @@ -358,7 +358,7 @@ protected: \ingroup parameteric */ -template class eoRealUxOver: public eoQuadraticOp +template class eoRealUxOver: public eoQuadOp { public: /** diff --git a/eo/src/ga.h b/eo/src/ga.h index 4e2720795..cbb71d724 100644 --- a/eo/src/ga.h +++ b/eo/src/ga.h @@ -30,12 +30,12 @@ #define _ga_h // all bitstring-specific files -#include +#include // the operators #include -// #include +// #include to be corrected - thanks someone! //----------------------------------------------------------------------------- diff --git a/eo/src/ga/Makefile.am b/eo/src/ga/Makefile.am index 558e06443..12060fa5e 100644 --- a/eo/src/ga/Makefile.am +++ b/eo/src/ga/Makefile.am @@ -5,4 +5,4 @@ ############################################################################### libeoincdir = $(includedir)/eo/ga -libeoinc_HEADERS = eoBin.h eoBitOp.h eoBitOpFactory.h +libeoinc_HEADERS = eoBit.h eoBitOp.h eoBitOpFactory.h diff --git a/eo/src/ga/eoBin.h b/eo/src/ga/eoBit.h similarity index 84% rename from eo/src/ga/eoBin.h rename to eo/src/ga/eoBit.h index 40cd2e0c1..61be6e2f1 100644 --- a/eo/src/ga/eoBin.h +++ b/eo/src/ga/eoBit.h @@ -1,5 +1,5 @@ /* - eoBin.h + eoBit.h (c) GeNeura Team 1998, Marc Schoenauer 2000 This library is free software; you can redistribute it and/or @@ -24,10 +24,14 @@ Added the calls to base class I/O routines that print the fitness Left printing/reading of the size of the bitstring, for backward compatibility, and as it is a general practice in EO + + MS, Feb. 7, 2001 + replaced all ...Bin... names with ...Bit... names - for bitstring + as it was ambiguous with bin...ary things */ -#ifndef eoBin_h -#define eoBin_h +#ifndef eoBit_h +#define eoBit_h //----------------------------------------------------------------------------- @@ -43,12 +47,12 @@ Various functions for a bitstring representation */ -/** eoBin: implementation of binary chromosome. -\class eoBin eoBin.h ga/eoBin.h +/** eoBit: implementation of bitstring chromosome. +\class eoBit eoBit.h ga/eoBit.h \ingroup bitstring * based on STL's vector specialization. */ -template class eoBin: public eoFixedLength +template class eoBit: public eoFixedLength { public: @@ -56,13 +60,13 @@ template class eoBin: public eoFixedLength * (Default) Constructor. * @param size Size of the binary string. */ - eoBin(unsigned size = 0, bool value = false): + eoBit(unsigned size = 0, bool value = false): eoFixedLength(size, value) {} /// My class name. string className() const { - return "eoBin"; + return "eoBit"; } /** @@ -99,4 +103,4 @@ template class eoBin: public eoFixedLength //----------------------------------------------------------------------------- -#endif //eoBin_h +#endif //eoBit_h diff --git a/eo/src/ga/eoBitOp.h b/eo/src/ga/eoBitOp.h index e0df842db..c798d9914 100644 --- a/eo/src/ga/eoBitOp.h +++ b/eo/src/ga/eoBitOp.h @@ -40,7 +40,7 @@ // chrom[i] = (chrom[i]) ? false : true; // we were calling something like // specific_mutate(chrom[i]) -// all mutation would also be generic ... except those eoBinNext and eoBinPrev +// all mutation would also be generic ... except those eoBitNext and eoBitPrev // If anybody reads this and want to change that (I'm also testing to see // if someone ever reads the headers :-), drop me a mail @@ -57,19 +57,19 @@ #include // swap_ranges #include #include // eoMonOp -#include +#include -/** eoBinBitFlip --> changes 1 bit -\class eoBinBitFlip eoBitOp.h ga/eoBitOp.h +/** eoBitFlip --> changes 1 bit +\class eoBitBitFlip eoBitOp.h ga/eoBitOp.h \ingroup bitstring */ -template class eoBinBitFlip: public eoMonOp +template class eoOneBitFlip: public eoMonOp { public: /// The class name. - string className() const { return "eoBinBitFlip"; } + string className() const { return "eoOneBitFlip"; } /** * Change one bit. @@ -77,9 +77,9 @@ template class eoBinBitFlip: public eoMonOp */ void operator()(Chrom& chrom) { - chrom.invalidate(); - unsigned i = rng.random(chrom.size()); + unsigned i = eo::rng.random(chrom.size()); chrom[i] = (chrom[i]) ? false : true; + chrom.invalidate(); } }; @@ -94,7 +94,7 @@ template class eoDetBitFlip: public eoMonOp /** * (Default) Constructor. * @param _num_bit The number of bits to change - * default is one - equivalent to eoBinBitFlip then + * default is one - equivalent to eoOneBitFlip then */ eoDetBitFlip(const unsigned& _num_bit = 1): num_bit(_num_bit) {} @@ -107,35 +107,35 @@ template class eoDetBitFlip: public eoMonOp */ void operator()(Chrom& chrom) { - chrom.invalidate(); // does not check for duplicate: if someone volunteers .... for (unsigned k=0; k classical mutation -\class eoBinMutation eoBitOp.h ga/eoBitOp.h +/** eoBitMutation --> classical mutation +\class eoBitMutation eoBitOp.h ga/eoBitOp.h \ingroup bitstring */ -template class eoBinMutation: public eoMonOp +template class eoBitMutation: public eoMonOp { public: /** * (Default) Constructor. * @param _rate Rate of mutation. */ - eoBinMutation(const double& _rate = 0.01): rate(_rate) {} + eoBitMutation(const double& _rate = 0.01): rate(_rate) {} /// The class name. - string className() const { return "eoBinMutation"; } + string className() const { return "eoBitMutation"; } /** * Mutate a chromosome. @@ -145,7 +145,7 @@ template class eoBinMutation: public eoMonOp { bool changed_something = false; for (unsigned i = 0; i < chrom.size(); i++) - if (rng.flip(rate)) + if (eo::rng.flip(rate)) { chrom[i] = !chrom[i]; changed_something = true; @@ -160,16 +160,16 @@ template class eoBinMutation: public eoMonOp }; -/** eoBinInversion: inverts the bits of the chromosome between an interval -\class eoBinInversion eoBitOp.h ga/eoBitOp.h +/** eoBitInversion: inverts the bits of the chromosome between an interval +\class eoBitInversion eoBitOp.h ga/eoBitOp.h \ingroup bitstring */ -template class eoBinInversion: public eoMonOp +template class eoBitInversion: public eoMonOp { public: /// The class name. - string className() const { return "eoBinInversion"; } + string className() const { return "eoBitInversion"; } /** * Inverts a range of bits in a binary chromosome. @@ -178,8 +178,8 @@ template class eoBinInversion: public eoMonOp void operator()(Chrom& chrom) { - unsigned u1 = rng.random(chrom.size() + 1) , u2; - do u2 = rng.random(chrom.size() + 1); while (u1 == u2); + unsigned u1 = eo::rng.random(chrom.size() + 1) , u2; + do u2 = eo::rng.random(chrom.size() + 1); while (u1 == u2); unsigned r1 = min(u1, u2), r2 = max(u1, u2); reverse(chrom.begin() + r1, chrom.begin() + r2); @@ -188,16 +188,16 @@ template class eoBinInversion: public eoMonOp }; -/** eoBinNext --> next binary value -\class eoBinNext eoBitOp.h ga/eoBitOp.h +/** eoBitNext --> next value when bitstring considered as binary value +\class eoBitNext eoBitOp.h ga/eoBitOp.h \ingroup bitstring */ -template class eoBinNext: public eoMonOp +template class eoBitNext: public eoMonOp { public: /// The class name. - string className() const { return "eoBinNext"; } + string className() const { return "eoBitNext"; } /** * Change the bit string x to be x+1. @@ -222,16 +222,16 @@ template class eoBinNext: public eoMonOp }; -/** eoBinPrev --> previous binary value -\class eoBinPrev eoBitOp.h ga/eoBitOp.h +/** eoBitPrev --> previous value when bitstring treated as binary value +\class eoBitPrev eoBitOp.h ga/eoBitOp.h \ingroup bitstring */ -template class eoBinPrev: public eoMonOp +template class eoBitPrev: public eoMonOp { public: /// The class name. - string className() const { return "eoBinPrev"; } + string className() const { return "eoBitPrev"; } /** * Change the bit string x to be x-1. @@ -256,16 +256,16 @@ template class eoBinPrev: public eoMonOp }; -/** eoBinCrossover --> classic 1-point crossover -\class eoBinCrossover eoBitOp.h ga/eoBitOp.h +/** eo1PtBitXover --> classic 1-point crossover +\class eo1PtBitCrossover eoBitOp.h ga/eoBitOp.h \ingroup bitstring */ -template class eoBinCrossover: public eoQuadraticOp +template class eo1PtBitXover: public eoQuadOp { public: /// The class name. - string className() const { return "eoBinCrossover"; } + string className() const { return "eo1PtBitXover"; } /** * 1-point crossover for binary chromosomes. @@ -274,7 +274,7 @@ template class eoBinCrossover: public eoQuadraticOp */ void operator()(Chrom& chrom1, Chrom& chrom2) { - unsigned site = rng.random(min(chrom1.size(), chrom2.size())); + unsigned site = eo::rng.random(min(chrom1.size(), chrom2.size())); if (!std::equal(chrom1.begin(), chrom1.begin()+site, chrom2.begin())) { @@ -288,22 +288,22 @@ template class eoBinCrossover: public eoQuadraticOp }; -/** eoBinUxOver --> classic Uniform crossover -\class eoBinNxOver eoBitOp.h ga/eoBitOp.h +/** eoUBitXover --> classic Uniform crossover +\class eoUBitXover eoBitOp.h ga/eoBitOp.h \ingroup bitstring */ -template class eoBinUxOver: public eoQuadraticOp +template class eoUBitXover: public eoQuadOp { public: /// (Default) Constructor. - eoBinUxOver(const float& _preference = 0.5): preference(_preference) + eoUBitXover(const float& _preference = 0.5): preference(_preference) { if ( (_preference <= 0.0) || (_preference >= 1.0) ) runtime_error("UxOver --> invalid preference"); } /// The class name. - string className() const { return "eoBinUxOver"; } + string className() const { return "eoUBitXover"; } /** * Uniform crossover for binary chromosomes. @@ -318,7 +318,7 @@ template class eoBinUxOver: public eoQuadraticOp bool changed = false; for (unsigned int i=0; i class eoBinUxOver: public eoQuadraticOp }; -/** eoBinNxOver --> n-point crossover -\class eoBinNxOver eoBitOp.h ga/eoBitOp.h +/** eoNPtsBitXover --> n-point crossover +\class eoNPtsBitXover eoBitOp.h ga/eoBitOp.h \ingroup bitstring */ -template class eoBinNxOver: public eoQuadraticOp +template class eoNPtsBitXover: public eoQuadOp { public: /// (Default) Constructor. - eoBinNxOver(const unsigned& _num_points = 2): num_points(_num_points) + eoNPtsBitXover(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"; } + string className() const { return "eoNPtsBitXover"; } /** * n-point crossover for binary chromosomes. @@ -369,7 +369,7 @@ template class eoBinNxOver: public eoQuadraticOp // select ranges of bits to swap do { - unsigned bit = rng.random(max_size) + 1; + unsigned bit = eo::rng.random(max_size) + 1; if (points[bit]) continue; else @@ -401,16 +401,18 @@ template class eoBinNxOver: public eoQuadraticOp -/** eoBinGxOver --> gene crossover -\class eoBinGxOver eoBitOp.h ga/eoBitOp.h +/** eoBitGxOver --> Npts crossover when bistring considered + as a string of binary-encoded genes (exchanges genes) +Is anybody still using it apart from historians ??? :-) +\class eoBitGxOver eoBitOp.h ga/eoBitOp.h \ingroup bitstring */ -template class eoBinGxOver: public eoQuadraticOp +template class eoBitGxOver: public eoQuadOp { public: /// Constructor. - eoBinGxOver(const unsigned _gene_size, const unsigned _num_points = 2): + eoBitGxOver(const unsigned _gene_size, const unsigned _num_points = 2): gene_size(_gene_size), num_points(_num_points) { if (gene_size < 1) @@ -420,7 +422,7 @@ template class eoBinGxOver: public eoQuadraticOp } /// The class name - string className() const { return "eoBinGxOver"; } + string className() const { return "eoBitGxOver"; } /** * Gene crossover for binary chromosomes. @@ -436,7 +438,7 @@ template class eoBinGxOver: public eoQuadraticOp // selects genes to swap do { - unsigned bit = rng.random(max_genes); + unsigned bit = eo::rng.random(max_genes); if (points[bit]) continue; else diff --git a/eo/src/ga/eoBitOpFactory.h b/eo/src/ga/eoBitOpFactory.h index 46b35ff03..5c0273c40 100644 --- a/eo/src/ga/eoBitOpFactory.h +++ b/eo/src/ga/eoBitOpFactory.h @@ -26,8 +26,8 @@ #ifndef _EOBITOPFACTORY_H #define _EOBITOPFACTORY_H -#include -#include +#include +#include //----------------------------------------------------------------------------- @@ -36,7 +36,7 @@ on bitstring chromosomes. Only those chromosomes can instantiate the operators that are created here @see eoSelect*/ template< class EOT> -class eoBitOpFactory: public eoOpFactory +class eoBitOpFactory: public eoFactory { public: @@ -64,49 +64,97 @@ public: { eoOp * opPtr = NULL; try { - opPtr = eoOpFactory::make( _is ); + opPtr = eoFactory::make( _is ); } catch ( const string& objectTypeStr ) { - if ( objectTypeStr == "eoBinRandom") { - opPtr = new eoBinRandom(); - } if ( objectTypeStr == "eoBinBitFlip" ) { - opPtr = new eoBinBitFlip( ); + opPtr = new eoOneBitFlip( ); } + // handles old operator names as well as new ones + if ( objectTypeStr == "eoOneBitFlip" ) { + opPtr = new eoOneBitFlip( ); + } + + // Standard BitFilp Mutation if ( objectTypeStr == "eoBinMutation" ) { float rate; _is >> rate; - opPtr = new eoBinMutation( rate ); + opPtr = new eoBitMutation( rate ); } + if ( objectTypeStr == "eoBitMutation" ) { + float rate; + _is >> rate; + opPtr = new eoBitMutation( rate ); + } + + // Bit inversion if ( objectTypeStr == "eoBinInversion" ) { - opPtr = new eoBinInversion( ); + opPtr = new eoBitInversion( ); } + if ( objectTypeStr == "eoBitInversion" ) { + opPtr = new eoBitInversion( ); + } + + // Next binary value if ( objectTypeStr == "eoBinNext" ) { - opPtr = new eoBinNext( ); + opPtr = new eoBitNext( ); } + if ( objectTypeStr == "eoBitNext" ) { + opPtr = new eoBitNext( ); + } + + // Previous binary value if ( objectTypeStr == "eoBinPrev" ) { - opPtr = new eoBinPrev( ); + opPtr = new eoBitPrev( ); } - if ( objectTypeStr == "eoBinNext" ) { - opPtr = new eoBinNext( ); + if ( objectTypeStr == "eoBitPrev" ) { + opPtr = new eoBitPrev( ); } + + // 1 point Xover if ( objectTypeStr == "eoBinCrossover" ) { - opPtr = new eoBinCrossover( ); + opPtr = new eo1PtBitXover( ); } + if ( objectTypeStr == "eo1PtBitXover" ) { + opPtr = new eo1PtBitXover( ); + } + + // Npts Xover if ( objectTypeStr == "eoBinNxOver" ) { unsigned nPoints; _is >> nPoints; - opPtr = new eoBinNxOver( nPoints ); + opPtr = new eoNPtsBitXover( nPoints ); } + if ( objectTypeStr == "eoNPtsBitXover" ) { + unsigned nPoints; + _is >> nPoints; + opPtr = new eoNPtsBitXover( nPoints ); + } + + // Gene Xover (obsolete) if ( objectTypeStr == "eoBinGxOver" ) { unsigned geneSize, nPoints; _is >> geneSize >> nPoints; - opPtr = new eoBinGxOver( geneSize, nPoints ); + opPtr = new eoBitGxOver( geneSize, nPoints ); } + if ( objectTypeStr == "eoBitGxOver" ) { + unsigned geneSize, nPoints; + _is >> geneSize >> nPoints; + opPtr = new eoBitGxOver( geneSize, nPoints ); + } + + // Uniform Xover if ( objectTypeStr == "eoBinUxOver" ) { float rate; _is >> rate; - opPtr = new eoBinUxOver( rate ); + opPtr = new eoUBitXover( rate ); } + if ( objectTypeStr == "eoUBitXover" ) { + float rate; + _is >> rate; + opPtr = new eoUBitXover( rate ); + } + + // nothing read! if ( !opPtr ) { // to be caught by the upper level throw objectTypeStr; } diff --git a/eo/src/gp/eoParseTree.h b/eo/src/gp/eoParseTree.h index 061f030a4..fb6e55c24 100644 --- a/eo/src/gp/eoParseTree.h +++ b/eo/src/gp/eoParseTree.h @@ -5,8 +5,6 @@ #include #include -#include -#include #include #include @@ -154,47 +152,47 @@ private : }; template -class eoSubtreeXOver: public eoGeneralOp< eoParseTree > { +class eoSubtreeXOver: public eoQuadOp< eoParseTree > { public: typedef eoParseTree EoType; eoSubtreeXOver( unsigned _max_length) - : eoGeneralOp(), max_length(_max_length) {}; + : eoQuadOp(), max_length(_max_length) {}; virtual string className() const { return "eoSubtreeXOver"; }; /// Dtor virtual ~eoSubtreeXOver () {}; - void operator()(eoIndiSelector& _select, eoInserter& _insert ) + void operator()(EoType & _eo1, EoType & _eo2 ) { - EoType eo1 = _select(); - const EoType& eo2 = _select(); + int i = rng.random(_eo1.size()); + int j = rng.random(_eo2.size()); - int i = rng.random(eo1.size()); - int j = rng.random(eo2.size()); - - eo1[i] = eo2[j]; // insert subtree + parse_tree::subtree tmp = _eo2[j]; + _eo1[i] = _eo2[j]; // insert subtree + _eo2[j]=tmp; - eo1.pruneTree(max_length); + _eo1.pruneTree(max_length); + _eo2.pruneTree(max_length); - eo1.invalidate(); - _insert(eo1); + _eo1.invalidate(); + _eo2.invalidate(); } unsigned max_length; }; template -class eoBranchMutation: public eoGeneralOp< eoParseTree > +class eoBranchMutation: public eoMonOp< eoParseTree > { public: typedef eoParseTree EoType; eoBranchMutation(eoInit& _init, unsigned _max_length) - : eoGeneralOp(), max_length(_max_length), initializer(_init) + : eoMonOp(), max_length(_max_length), initializer(_init) {}; virtual string className() const { return "eoBranchMutation"; }; @@ -202,22 +200,20 @@ public: /// Dtor virtual ~eoBranchMutation() {}; - void operator()(eoIndiSelector& _select, eoInserter& _insert ) + void operator()(EoType& _eo1 ) { - EoType eo1 = _select(); - int i = rng.random(eo1.size()); + int i = rng.random(_eo1.size()); EoType eo2; initializer(eo2); int j = rng.random(eo2.size()); - eo1[i] = eo2[j]; // insert subtree + _eo1[i] = eo2[j]; // insert subtree - eo1.pruneTree(max_length); + _eo1.pruneTree(max_length); - eo1.invalidate(); - _insert(eo1); + _eo1.invalidate(); } private : diff --git a/eo/src/eoBackInserter.h b/eo/src/obsolete/eoBackInserter.h similarity index 100% rename from eo/src/eoBackInserter.h rename to eo/src/obsolete/eoBackInserter.h diff --git a/eo/src/eoDetTournamentInserter.h b/eo/src/obsolete/eoDetTournamentInserter.h similarity index 100% rename from eo/src/eoDetTournamentInserter.h rename to eo/src/obsolete/eoDetTournamentInserter.h diff --git a/eo/src/eoGOpBreeder.h b/eo/src/obsolete/eoGOpBreeder.h similarity index 100% rename from eo/src/eoGOpBreeder.h rename to eo/src/obsolete/eoGOpBreeder.h diff --git a/eo/src/eoGOpSelector.h b/eo/src/obsolete/eoGOpSelector.h similarity index 100% rename from eo/src/eoGOpSelector.h rename to eo/src/obsolete/eoGOpSelector.h diff --git a/eo/src/eoIndiSelector.h b/eo/src/obsolete/eoIndiSelector.h similarity index 100% rename from eo/src/eoIndiSelector.h rename to eo/src/obsolete/eoIndiSelector.h diff --git a/eo/src/eoInplaceTransform.h b/eo/src/obsolete/eoInplaceTransform.h similarity index 100% rename from eo/src/eoInplaceTransform.h rename to eo/src/obsolete/eoInplaceTransform.h diff --git a/eo/src/eoInserter.h b/eo/src/obsolete/eoInserter.h similarity index 100% rename from eo/src/eoInserter.h rename to eo/src/obsolete/eoInserter.h diff --git a/eo/src/eoOpFactory.h b/eo/src/obsolete/eoOpFactory.h similarity index 100% rename from eo/src/eoOpFactory.h rename to eo/src/obsolete/eoOpFactory.h diff --git a/eo/src/eoOpSelector.h b/eo/src/obsolete/eoOpSelector.h similarity index 100% rename from eo/src/eoOpSelector.h rename to eo/src/obsolete/eoOpSelector.h diff --git a/eo/src/eoProportionalGOpSel.h b/eo/src/obsolete/eoProportionalGOpSel.h similarity index 100% rename from eo/src/eoProportionalGOpSel.h rename to eo/src/obsolete/eoProportionalGOpSel.h diff --git a/eo/src/eoProportionalOpSel.h b/eo/src/obsolete/eoProportionalOpSel.h similarity index 100% rename from eo/src/eoProportionalOpSel.h rename to eo/src/obsolete/eoProportionalOpSel.h diff --git a/eo/src/eoSequentialGOpSel.h b/eo/src/obsolete/eoSequentialGOpSel.h similarity index 100% rename from eo/src/eoSequentialGOpSel.h rename to eo/src/obsolete/eoSequentialGOpSel.h diff --git a/eo/src/eoSteadyStateEA.h b/eo/src/obsolete/eoSteadyStateEA.h similarity index 100% rename from eo/src/eoSteadyStateEA.h rename to eo/src/obsolete/eoSteadyStateEA.h diff --git a/eo/src/eoSteadyStateInserter.h b/eo/src/obsolete/eoSteadyStateInserter.h similarity index 100% rename from eo/src/eoSteadyStateInserter.h rename to eo/src/obsolete/eoSteadyStateInserter.h diff --git a/eo/src/eoSteadyStateTransform.h b/eo/src/obsolete/eoSteadyStateTransform.h similarity index 100% rename from eo/src/eoSteadyStateTransform.h rename to eo/src/obsolete/eoSteadyStateTransform.h diff --git a/eo/src/eoStochTournamentInserter.h b/eo/src/obsolete/eoStochTournamentInserter.h similarity index 100% rename from eo/src/eoStochTournamentInserter.h rename to eo/src/obsolete/eoStochTournamentInserter.h diff --git a/eo/src/eoWrappedOps.h b/eo/src/obsolete/eoWrappedOps.h similarity index 100% rename from eo/src/eoWrappedOps.h rename to eo/src/obsolete/eoWrappedOps.h diff --git a/eo/src/other/eoExternalOpFunctions.h b/eo/src/other/eoExternalOpFunctions.h index 73620b412..906460fbb 100644 --- a/eo/src/other/eoExternalOpFunctions.h +++ b/eo/src/other/eoExternalOpFunctions.h @@ -153,11 +153,11 @@ class eoExternalBinOp : public eoBinOp The function should return true when it changed something, false otherwise */ template > -class eoExternalQuadraticOp : public eoQuadraticOp +class eoExternalQuadOp : public eoQuadOp { public : - eoExternalQuadraticOp(bool (*_quadop)(External&, External&)) : quadop(_quadop) {} + eoExternalQuadOp(bool (*_quadop)(External&, External&)) : quadop(_quadop) {} void operator()(ExternalEO& eo1, ExternalEO& eo2) { diff --git a/eo/src/utils/eoParser.cpp b/eo/src/utils/eoParser.cpp index b401db027..a069ff072 100644 --- a/eo/src/utils/eoParser.cpp +++ b/eo/src/utils/eoParser.cpp @@ -197,7 +197,6 @@ void eoParser::printOn(ostream& os) const std::string section = p->first; printSectionHeader(os, section); - //print every param with its value for (; p != params.end(); ++p) { diff --git a/eo/test/t-eoGenOp.cpp b/eo/test/t-eoGenOp.cpp new file mode 100644 index 000000000..88b04f429 --- /dev/null +++ b/eo/test/t-eoGenOp.cpp @@ -0,0 +1,359 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoGenOp.h +// (c) Maarten Keijzer and Marc Schoenauer, 2001 +/* + 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: mkeijzer@dhi.dk + Marc.Schoenauer@polytechnique.fr + */ +//----------------------------------------------------------------------------- + +/** test program for the general operator - millenium version! + * uses dummy individuals + */ +#include +#include +#include + +struct Dummy : public EO +{ + typedef double Type; + Dummy(std::string _s="") : s(_s) {} + + void printOn(ostream & _os) const + { + EO::printOn(_os); + _os << " - " << s ; + } + + string s; +}; + +typedef Dummy EOT; + +unsigned int pSize; // global to be used as marker in the fitness + +// DEFINITIONS of the eoOps +class monop : public eoMonOp +{ + public : + monop(char * _sig){sig=_sig;} + void operator()(EOT& _eo) + { + _eo.s = sig + "(" + _eo.s + ")"; + _eo.fitness(_eo.fitness()+pSize); + } + string className() {return sig;} + private: + string sig; +}; + +class binop: public eoBinOp +{ + public : + void operator()(EOT& _eo1, const EOT& _eo2) + { + _eo1.s = "bin(" + _eo1.s + "," + _eo2.s + ")"; + double f= (_eo1.fitness()+_eo2.fitness()) * pSize; + _eo1.fitness(_eo1.fitness()+f); + } + string className() {return "binop";} +}; + +class quadop: public eoQuadOp +{ + public : + string className() {return "quadop";} + void operator()(EOT& a, EOT& b) + { + EOT oi = a; + EOT oj = b; + + a.s = "quad1(" + oi.s + "," + oj.s + ")"; + b.s = "quad2(" + oj.s + "," + oi.s + ")"; + double f= (a.fitness()+b.fitness()+2*pSize) * pSize; + a.fitness(a.fitness()+f); + b.fitness(b.fitness()+f); + } +}; +// an eoQuadOp that does nothing +class quadClone: public eoQuadOp +{ + public : + string className() {return "quadclone";} + void operator()(EOT& , EOT& ) {} +}; + +// User defined General Operator... adapted from Marc's example + +class one2threeOp : public eoGenOp // :-) +{ + public: + unsigned max_production(void) { return 3; } + + void apply(eoPopulator& _plop) + { + EOT& eo = *_plop; // select the guy + ++_plop; // advance + + _plop.insert("v(" + eo.s + ", 1)"); + ++_plop; + _plop.insert("v(" + eo.s + ", 2)"); + eo.s = "v(" + eo.s + ", 0)"; // only now change the thing + // oh right, and invalidate fitnesses + } + virtual string className() {return "one2threeOp";} +}; + + +class two2oneOp : public eoGenOp // :-) +{ + public: + unsigned max_production(void) { return 1; } + + void apply(eoPopulator& _plop) + { + EOT& eo = *_plop; // select the guy + ++_plop; // advance + EOT& eo2 = *_plop; + eo.s = "221(" + eo.s + ", " + eo2.s + ")"; + _plop.erase(); + // oh right, and invalidate fitnesses + } + virtual string className() {return "two2oneOp";} +}; + + +// dummy intialization. Re-init if no pSize, resize first if pSize +void init(eoPop & _pop, unsigned _pSize) +{ + if (_pSize) + { + _pop.resize(_pSize); + } + else + { + throw runtime_error("init pop with 0 size"); + } + for (unsigned i=0; i<_pSize; i++) + { + char s[255]; + ostrstream os(s, 254); + os << i << ends; + _pop[i] = Dummy(s); + _pop[i].fitness(i); + } +} + +// ok, now for the real work +int the_main(int argc, char **argv) +{ + + eoParser parser(argc, argv); + eoValueParam parentSizeParam = parser.createParam(10, "parentSize", "Parent size",'P'); + pSize = parentSizeParam.value(); // global variable + + eoValueParam seedParam(time(0), "seed", "Random number seed", 'S'); + parser.processParam( seedParam ); + eo::rng.reseed(seedParam.value()); + + // do the following AFTER ALL PARAMETERS HAVE BEEN PROCESSED + // i.e. in case you need parameters somewhere else, postpone these + if (parser.userNeedsHelp()) + { + parser.printHelp(cout); + exit(1); + } + + ////////////////////////////////// define operators + monop mon("mon1"); + monop clone("clone"); + binop bin; + quadop quad; + quadClone quadclone; + + // our own operator + one2threeOp o2t; + two2oneOp t2o; + + + // a selector + eoDetTournamentSelect select; + // and a recognizable selector for testing the inbedded selector mechanism + eoBestSelect selectBest; + + // proportional selection between quad and bin + // so we either do a quad or a bin + eoProportionalOp pOp; + pOp.add(quad, 0.1); + pOp.add(bin, 0.1); + + // sequential selection between pOp and mon + eoSequentialOp sOp; + sOp.add(pOp, 0.9); + sOp.add(mon, 0.1); + + // with one2three op + eoSequentialOp sOp2; + sOp2.add(o2t, 1); + sOp2.add(quad, 1); + + eoSequentialOp sOp3; + // sOp3.add(t2o, 1); + sOp3.add(bin, 1); + sOp3.add(quad, 1); + // try adding quads and bins to see what results you'll get + + // now a sequential selection that is a simple "addition" + eoSequentialOp sOpQuadPlusMon; + sOpQuadPlusMon.add(quad, 1); + sOpQuadPlusMon.add(mon, 1); + + // this corresponds + eoProportionalOp pOpSAGLike; + pOpSAGLike.add(sOpQuadPlusMon, 0.24); + pOpSAGLike.add(quad, 0.56); + pOpSAGLike.add(mon, 0.06); + pOpSAGLike.add(clone, 0.14); + + // init + eoPop pop; + + init(pop, pSize); +// sort pop so seqPopulator is identical to SelectPopulator(SequentialSelect) + pop.sort(); + cout << "Population initiale\n" << pop << endl; + + // To simulate SGA: first a prop between quadOp and quadClone + eoProportionalOp pSGAOp; + pSGAOp.add(bin, 0.8); + pSGAOp.add(quadclone, 0.2); + // sequential selection between pSGAOp and mon + eoSequentialOp virtualSGA; + virtualSGA.add(pSGAOp, 1.0); + virtualSGA.add(mon, 0.3); + + eoSeqPopulator popit(pop); // no selection, a copy of pop + + // until we filled a new population + try + { + while (popit.size() < pop.size()) + { + virtualSGA(popit); + } + } + catch(eoPopulator::OutOfIndividuals&) + { + cout << "Warning: not enough individuals to handle\n"; + } + + + swap(pop, popit); + + // ok, now print + cout << "Apres virtualSGA \n" << pop << endl; + init(pop, pSize); + + cout << "=========================================================\n"; + cout << "Now the eoSelectPopulator version !" << endl; + + eoSequentialSelect seqSelect; + // select.init(); should be sorted out: is it the setup method??? + eoSelectivePopulator it_step3(pop, seqSelect); + + while (it_step3.size() < 2*pop.size()) + { + virtualSGA(it_step3); + } + + swap(pop, it_step3); + + // ok, now print + cout << "Apres SGA-like eoSelectivePopulator\n" << pop << endl; + + cout << "=========================================================\n"; + cout << "Now the pure addition !" << endl; + + init(pop, pSize); + eoSelectivePopulator it_step4(pop, seqSelect); + while (it_step4.size() < 2*pop.size()) + { + sOpQuadPlusMon(it_step4); + } + + swap(pop, it_step4); + + // ok, now print + cout << "Apres Quad+Mon ds un eoSelectivePopulator\n" << pop << endl; + + + return 1; +} + +int main(int argc, char **argv) +{ + try + { + the_main(argc, argv); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << endl; + } + + return 1; +} + +/* +If you want to build an SGA, you will need a copying quad op: + +class quadclone : ... +{ + operator(EOT& a, EOT& b) + { + // do nothing + } + +} + +Then the SGA operator will look like: + +quadop quad; +guadclone clone; + +ProportionalGenOp pOp; +pOp.add(quad, 0.8); +pOp.add(clone, 0.2); // so 80% xover rate + +SequentialGenOp sOp; +sOp.add(pOp, 1,0); // always try a xover (clone 20%) +sOp.add(mut, 0.1); // low mutation rate + +will result in an algorithm with: + +p_xover = 0.8 +p_mut = 0.1; + +p_reproduction = 0.2 * 0.9 = 0.18 + +this does not add up to 1 because xover and mutation can be applied to a single indi + +So what do you think? + +*/ diff --git a/eo/tutorial/Lesson1/FirstBitGA.cpp b/eo/tutorial/Lesson1/FirstBitGA.cpp index 1ea79a766..c1a41870e 100644 --- a/eo/tutorial/Lesson1/FirstBitGA.cpp +++ b/eo/tutorial/Lesson1/FirstBitGA.cpp @@ -13,13 +13,12 @@ // the general include for eo #include +#include // REPRESENTATION //----------------------------------------------------------------------------- -// Include the corresponding file -#include // bitstring representation & operators // define your individuals -typedef eoBin Indi; // A bitstring with fitness double +typedef eoBit Indi; // A bitstring with fitness double // EVAL //----------------------------------------------------------------------------- @@ -112,11 +111,11 @@ void main_function(int argc, char **argv) // The variation operators ////////////////////////////////////// // CROSSOVER - // 1-point mutation for bitstring - eoBinCrossover xover; + // 1-point crossover for bitstring + eo1PtBitXover xover; // MUTATION // standard bit-flip mutation for bitstring - eoBinMutation mutation(P_MUT_PER_BIT); + eoBitMutation mutation(P_MUT_PER_BIT); // STOP // CHECKPOINT diff --git a/eo/tutorial/Lesson1/FirstRealGA.cpp b/eo/tutorial/Lesson1/FirstRealGA.cpp index 5e1c69e4d..3a4f991a4 100644 --- a/eo/tutorial/Lesson1/FirstRealGA.cpp +++ b/eo/tutorial/Lesson1/FirstRealGA.cpp @@ -13,11 +13,10 @@ // the general include for eo #include +#include // REPRESENTATION //----------------------------------------------------------------------------- -// Include the corresponding file -#include // real-representation & operators // define your individuals typedef eoReal Indi; diff --git a/eo/tutorial/Lesson1/exercise1.3.cpp b/eo/tutorial/Lesson1/exercise1.3.cpp index f2e03652c..3a2cb8d22 100644 --- a/eo/tutorial/Lesson1/exercise1.3.cpp +++ b/eo/tutorial/Lesson1/exercise1.3.cpp @@ -20,7 +20,7 @@ // Include the corresponding file #include // bitstring representation & operators // define your individuals -typedef eoBin Indi; // A bitstring with fitness double +typedef eoBit Indi; // A bitstring with fitness double //----------------------------------------------------------------------------- /** a simple fitness function that computes the number of ones of a bitstring @@ -120,9 +120,9 @@ void main_function(int argc, char **argv) // The variation operators ////////////////////////////////////// // standard bit-flip mutation for bitstring - eoBinMutation mutation(P_MUT_PER_BIT); + eoBitMutation mutation(P_MUT_PER_BIT); // 1-point mutation for bitstring - eoBinCrossover xover; + eo1PtBitXover xover; ///////////////////////////////////////// // the algorithm diff --git a/eo/tutorial/Lesson2/FirstBitEA.cpp b/eo/tutorial/Lesson2/FirstBitEA.cpp index a5b3e0dee..d89e3e28a 100644 --- a/eo/tutorial/Lesson2/FirstBitEA.cpp +++ b/eo/tutorial/Lesson2/FirstBitEA.cpp @@ -13,13 +13,12 @@ // the general include for eo #include +#include // REPRESENTATION //----------------------------------------------------------------------------- -// Include the corresponding file -#include // bitstring representation & operators // define your individuals -typedef eoBin Indi; // A bitstring with fitness double +typedef eoBit Indi; // A bitstring with fitness double // EVALFUNC //----------------------------------------------------------------------------- @@ -112,11 +111,11 @@ void main_function(int argc, char **argv) ////////////////////////////////////// // CROSSOVER // 1-point crossover for bitstring - eoBinCrossover xover1; + eo1PtBitXover xover1; // uniform crossover for bitstring - eoBinUxOver xoverU; + eoUBitXover xoverU; // 2-pots xover - eoBinNxOver xover2(2); + eoNPtsBitXover xover2(2); // Combine them with relative rates eoPropCombinedQuadOp xover(xover1, onePointRate); xover.add(xoverU, URate); @@ -124,7 +123,7 @@ void main_function(int argc, char **argv) // MUTATION // standard bit-flip mutation for bitstring - eoBinMutation mutationBitFlip(P_MUT_PER_BIT); + eoBitMutation mutationBitFlip(P_MUT_PER_BIT); // mutate exactly 1 bit per individual eoDetBitFlip mutationOneBit; // Combine them with relative rates diff --git a/eo/tutorial/Lesson2/FirstRealEA.cpp b/eo/tutorial/Lesson2/FirstRealEA.cpp index 934fb0c35..a6f5e8e22 100644 --- a/eo/tutorial/Lesson2/FirstRealEA.cpp +++ b/eo/tutorial/Lesson2/FirstRealEA.cpp @@ -13,11 +13,10 @@ // the general include for eo #include +#include // REPRESENTATION //----------------------------------------------------------------------------- -// Include the corresponding file -#include // real-valued representation & operators // define your individuals typedef eoReal Indi; diff --git a/eo/tutorial/Lesson2/exercise2.3.cpp b/eo/tutorial/Lesson2/exercise2.3.cpp index 09b6bbc01..f7832bf0d 100644 --- a/eo/tutorial/Lesson2/exercise2.3.cpp +++ b/eo/tutorial/Lesson2/exercise2.3.cpp @@ -19,7 +19,7 @@ // Include the corresponding file #include // bitstring representation & operators // define your individuals -typedef eoBin Indi; // A bitstring with fitness double +typedef eoBit Indi; // A bitstring with fitness double // EVAL //----------------------------------------------------------------------------- @@ -118,11 +118,11 @@ void main_function(int argc, char **argv) ////////////////////////////////////// // CROSSOVER // 1-point crossover for bitstring - eoBinCrossover xover1; + eo1PtBitXover xover1; // uniform crossover for bitstring - eoBinUxOver xoverU; + eoUBitXover xoverU; // 2-pots xover - eoBinNxOver xover2(2); + eoNPtsBitXover xover2(2); // Combine them with relative rates eoPropCombinedQuadOp xover(xover1, onePointRate); xover.add(xoverU, URate); @@ -130,7 +130,7 @@ void main_function(int argc, char **argv) // MUTATION // standard bit-flip mutation for bitstring - eoBinMutation mutationBitFlip(P_MUT_PER_BIT); + eoBitMutation mutationBitFlip(P_MUT_PER_BIT); // mutate exactly 1 bit per individual eoDetBitFlip mutationOneBit; // Combine them with relative rates diff --git a/eo/tutorial/Lesson2/real_value.h b/eo/tutorial/Lesson2/real_value.h index 17d96ede0..c7a57c109 100644 --- a/eo/tutorial/Lesson2/real_value.h +++ b/eo/tutorial/Lesson2/real_value.h @@ -10,7 +10,11 @@ double real_value(const std::vector& _ind) { double sum = 0; for (unsigned i = 0; i < _ind.size(); i++) - sum += _ind[i] * _ind[i]; + { + if ( (_ind[i]<0) || (_ind[i]>1) ) + cout << "Sorti des bornes: " << _ind[i] << " "; + sum += _ind[i] * _ind[i]; + } return -sum; } diff --git a/eo/tutorial/Lesson3/SecondBitEA.cpp b/eo/tutorial/Lesson3/SecondBitEA.cpp index 60412fb18..b2eda1a56 100644 --- a/eo/tutorial/Lesson3/SecondBitEA.cpp +++ b/eo/tutorial/Lesson3/SecondBitEA.cpp @@ -14,16 +14,15 @@ // the general include for eo #include +#include // EVAL #include "binary_value.h" // REPRESENTATION //----------------------------------------------------------------------------- -// Include the corresponding file -#include // bitstring representation & operators // define your genotype and fitness types -typedef eoBin Indi; +typedef eoBit Indi; // the main_function: nothing changed(!), except variable initialization void main_function(int argc, char **argv) @@ -201,11 +200,11 @@ void main_function(int argc, char **argv) ////////////////////////////////////// // CROSSOVER // 1-point crossover for bitstring - eoBinCrossover xover1; + eo1PtBitXover xover1; // uniform crossover for bitstring - eoBinUxOver xoverU; + eoUBitXover xoverU; // 2-pots xover - eoBinNxOver xover2(2); + eoNPtsBitXover xover2(2); // Combine them with relative rates eoPropCombinedQuadOp xover(xover1, onePointRate); xover.add(xoverU, URate); @@ -213,7 +212,7 @@ void main_function(int argc, char **argv) // MUTATION // standard bit-flip mutation for bitstring - eoBinMutation mutationBitFlip(pMutPerBit); + eoBitMutation mutationBitFlip(pMutPerBit); // mutate exactly 1 bit per individual eoDetBitFlip mutationOneBit; // Combine them with relative rates diff --git a/eo/tutorial/Lesson3/exercise3.1.cpp b/eo/tutorial/Lesson3/exercise3.1.cpp index fa8500c8a..c8c3d2bd5 100644 --- a/eo/tutorial/Lesson3/exercise3.1.cpp +++ b/eo/tutorial/Lesson3/exercise3.1.cpp @@ -27,7 +27,7 @@ // Include the corresponding file #include // bitstring representation & operators // define your genotype and fitness types -typedef eoBin Indi; +typedef eoBit Indi; // the main_function: nothing changed(!), except variable initialization void main_function(int argc, char **argv) @@ -210,11 +210,11 @@ void main_function(int argc, char **argv) ////////////////////////////////////// // CROSSOVER // 1-point crossover for bitstring - eoBinCrossover xover1; + eo1PtBitXover xover1; // uniform crossover for bitstring - eoBinUxOver xoverU; + eoUBitXover xoverU; // 2-pots xover - eoBinNxOver xover2(2); + eoNPtsBitXover xover2(2); // Combine them with relative rates eoPropCombinedQuadOp xover(xover1, onePointRate); xover.add(xoverU, URate); @@ -222,7 +222,7 @@ void main_function(int argc, char **argv) // MUTATION // standard bit-flip mutation for bitstring - eoBinMutation mutationBitFlip(pMutPerBit); + eoBitMutation mutationBitFlip(pMutPerBit); // mutate exactly 1 bit per individual eoDetBitFlip mutationOneBit; // Combine them with relative rates @@ -314,6 +314,9 @@ void main_function(int argc, char **argv) gnuMonitor.add(bestStat); gnuMonitor.add(averageStat); + // send a scaling command to gnuplot + gnuMonitor.gnuplotCommand("set yrange [0:500]"); + // a specific plot monitor for FDC // first into a file (it adds everything ti itself eoFDCFileSnapshot fdcFileSnapshot(fdcStat); diff --git a/eo/tutorial/html/FirstBitEA.html b/eo/tutorial/html/FirstBitEA.html index 6b06faac6..4089c8ff8 100644 --- a/eo/tutorial/html/FirstBitEA.html +++ b/eo/tutorial/html/FirstBitEA.html @@ -2,9 +2,9 @@ - + FirstBitEA.cpp - + Back to Lesson 2 - Tutorial @@ -16,319 +16,345 @@ documentation

FirstBitEA.cpp

-Click on the figure to see the corresponding code. -
In the code, the colors are meaningfull -
The actual code is in boldface and the comment in normal face. -
-
+Click on the figure to see the corresponding code.
+In the code, the colors are meaningfull
+The actual code is in boldface and the comment in normal face. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
  + - +
//----------------------------------------------------------------------------- -
// FirstBitEA.cpp -
//----------------------------------------------------------------------------- -
//* -
// Still an instance of a VERY simple Bitstring -Genetic Algorithm  -
// (see FirstBitGA.cpp) but now with  -Breeder - and Combined Ops -
// -
//----------------------------------------------------------------------------- -
// standard includes -
#include <stdexcept>  // runtime_error  -
#include <iostream>    -// cout -
#include <strstream>  // ostrstream, -istrstream -
// the general include for eo -
#include <eo>
+//-----------------------------------------------------------------------------
+// FirstBitEA.cpp
+//-----------------------------------------------------------------------------
+//*
+// Still an instance of a VERY simple Bitstring Genetic Algorithm
+// (see FirstBitGA.cpp) but now with  Breeder - and Combined Ops
+//
+//-----------------------------------------------------------------------------
+// standard includes
+#include <stdexcept>  // runtime_error
+#include <iostream>    // cout
+#include <strstream>  // ostrstream, istrstream
+// the general include for eo
+#include <eo>
+
+
- - - - - -
//----------------------------------------------------------------------------- -
// Include the corresponding file  -
#include <ga.h>          -// bitstring representation & operators  -
// define your individuals -
typedef eoBin<double> Indi; // -A bitstring with fitness double
- - - - - -
//----------------------------------------------------------------------------- -
// a simple fitness function that computes -the number of ones of a bitstring -
// Now in a separate file, and declared as -binary_value(const vector<bool> &) -
#include "binary_value.h"
- - - - - -
//----------------------------------------------------------------------------- -
void main_function(int argc, char **argv) -
{
- - - - - -
 const unsigned int SEED = 42; // -seed for random number generator -
 const unsigned int T_SIZE = 3; // -size for tournament selection -
 const unsigned int VEC_SIZE = 8; -// Number of bits in genotypes -
 const unsigned int POP_SIZE = 20; -// Size of population -
 const unsigned int MAX_GEN = 500; -// Maximum number of generation before STOP -
 const float CROSS_RATE = 0.8; // -Crossover rate -
 const double P_MUT_PER_BIT = 0.01; -// probability of bit-flip mutation -
 const float MUT_RATE = 1.0; // -mutation rate -
 // some parameters for chosing -among different operators -
 const double onePointRate = 0.5;        -// rate for 1-pt Xover -
 const double twoPointsRate = 0.5;        -// rate for 2-pt Xover -
 const double URate = 0.5;                      -// rate for Uniform Xover -
 const double bitFlipRate = 0.5;          -// rate for bit-flip mutation -
 const double oneBitRate = 0.5;            -// rate for one-bit mutation
- - - - - -
 ////////////////////////// -
 //  Random seed -
 ////////////////////////// -
 //reproducible random seed: -if you don't change SEED above,  -
 // you'll aways get the same -result, NOT a random run -
 rng.reseed(SEED);
- - - - - -
 ///////////////////////////// -
 // Fitness function -
 //////////////////////////// -
 // Evaluation: from a plain -C++ fn to an EvalFunc Object -
 // you need to give the full -description of the function -
 eoEvalFuncPtr<Indi, double, const -vector<bool>& > eval(  binary_value );
- - - - - -
 //////////////////////////////// -
 // Initilisation of population -
 //////////////////////////////// -
 // based on boolean_generator -class (see utils/rnd_generator.h) -
 eoInitFixedLength<Indi, boolean_generator>  -
     random(VEC_SIZE, -boolean_generator()); -
 // Initialization of the population -
 eoPop<Indi> pop(POP_SIZE, random); -
 // and evaluate it in one line -
 apply<Indi>(eval, pop); // -STL syntax
- - - - - -
 // sort pop before printing -it! -
 pop.sort(); -
 // Print (sorted) intial population -(raw printout) -
 cout << "Initial Population" -<< endl; -
 cout << pop;
- - - - - -
 ///////////////////////////////////// -
 // selection and replacement -
 ////////////////////////////////////
- - - - - -
 // The robust tournament selection -
 eoDetTournamentSelect<Indi> selectOne(T_SIZE);            -// T_SIZE in [2,POP_SIZE] -
// -is now encapsulated in a eoSelectPerc (entage) -
 eoSelectPerc<Indi> select(selectOne);// -by default rate==1
- - - - - -
 // And we now have the full -slection/replacement - though with  -
 // no replacement (== generational -replacement) at the moment :-) -
 eoNoReplacement<Indi> replace; 
- - - - - -
 ////////////////////////////////////// -
 // The variation operators -
 //////////////////////////////////////
- - - - - -
 // 1-point crossover for bitstring -
 eoBinCrossover<Indi> xover1; -
 // uniform crossover for bitstring -
 eoBinUxOver<Indi> xoverU; -
 // 2-pots xover -
 eoBinNxOver<Indi> xover2(2); -
 // Combine them with relative -rates -
 eoPropCombinedQuadOp<Indi> xover(xover1, -onePointRate); -
 xover.add(xoverU, URate); -
 xover.add(xover2, twoPointsRate, -true);
- - +
+ +#include <ga.h>
+//-----------------------------------------------------------------------------
+// define your individuals
+typedef eoBit<double> Indi; // A bitstring with fitness double
+
+
-
 // standard bit-flip mutation -for bitstring -
 eoBinMutation<Indi>  mutationBitFlip(P_MUT_PER_BIT); -
 // mutate exactly 1 bit per -individual -
 eoDetBitFlip<Indi> mutationOneBit;  -
 // Combine them with relative -rates -
 eoPropCombinedMonOp<Indi> mutation(mutationBitFlip, -bitFlipRate); -
 mutation.add(mutationOneBit, oneBitRate, -true); -

// The operators -are  encapsulated into an eoTRansform object -
 eoSGATransform<Indi> transform(xover, -CROSS_RATE, mutation, MUT_RATE);

- - +
- +
+ +//-----------------------------------------------------------------------------
+// a simple fitness function that computes the number of ones of a bitstring
+// Now in a separate file, and declared as binary_value(const vector<bool> &)
+#include "binary_value.h"
+
+
- - +
- +
 ////////////////////////////////////// -
 // termination conditions: use -more than one -
 ///////////////////////////////////// -
 // stop after MAX_GEN generations -
 eoGenContinue<Indi> genCont(MAX_GEN); -
 // do MIN_GEN gen., then stop -after STEADY_GEN gen. without improvement -
 eoSteadyFitContinue<Indi> steadyCont(MIN_GEN, -STEADY_GEN); -
 // stop when fitness reaches -a target (here VEC_SIZE) -
 eoFitContinue<Indi> fitCont(0); -
 // do stop when one of the above -says so -
 eoCombinedContinue<Indi> continuator(genCont); -
 continuator.add(steadyCont); -
 continuator.add(fitCont);
+ +//-----------------------------------------------------------------------------
+void main_function(int argc, char **argv)
+{
+
+
- - +
- +
 ///////////////////////////////////////// -
 // the algorithm -
 //////////////////////////////////////// -
 // Easy EA requires  -
 // selection, transformation, -eval, replacement, and stopping criterion -
 eoEasyEA<Indi> gga(continuator, -eval, select, transform, replace); -
 // Apply algo to pop - that's -it! -
 gga(pop); -
 
+ +  const unsigned int SEED = 42; // seed for random number generator
+  const unsigned int T_SIZE = 3; // size for tournament selection
+  const unsigned int VEC_SIZE = 8; // Number of bits in genotypes
+  const unsigned int POP_SIZE = 20; // Size of population
+  const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP
+  const float CROSS_RATE = 0.8; // Crossover rate
+  const double P_MUT_PER_BIT = 0.01; // probability of bit-flip mutation
+  const float MUT_RATE = 1.0; // mutation rate
+  // some parameters for chosing among different operators
+  const double onePointRate = 0.5;        // rate for 1-pt Xover
+  const double twoPointsRate = 0.5;        // rate for 2-pt Xover
+  const double URate = 0.5;                      // rate for Uniform Xover
+  const double bitFlipRate = 0.5;          // rate for bit-flip mutation
+  const double oneBitRate = 0.5;            // rate for one-bit mutation
+
+
- - +
- +
 // Print (sorted) intial population -
 pop.sort(); -
 cout << "FINAL Population\n" -<< pop << endl;
+ +  //////////////////////////
+  //  Random seed
+  //////////////////////////
+  //reproducible random seed: if you don't change SEED above,
+  // you'll aways get the same result, NOT a random run
+  rng.reseed(SEED);
+
+
- - +
- + + +
} -
// A main that catches the exceptions -
int main(int argc, char **argv) -
{ -
#ifdef _MSC_VER -
 //  rng.reseed(42); -
     int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF); -
       flag -|= _CRTDBG_LEAK_CHECK_DF; -
     _CrtSetDbgFlag(flag); -
//    _CrtSetBreakAlloc(100); -
#endif -
     try -
     { -
             -main_function(argc, argv); -
     } -
     catch(exception& -e) -
     { -
             -cout << "Exception: " << e.what() << '\n'; -
     } -
     return 1; -
}
+ +  /////////////////////////////
+  // Fitness function
+  ////////////////////////////
+  // Evaluation: from a plain C++ fn to an EvalFunc Object
+  // you need to give the full description of the function
+  eoEvalFuncPtr<Indi, double, const vector<bool>& > eval(  binary_value );
+
+
+ + + + +
+ +  ////////////////////////////////
+  // Initilisation of population
+  ////////////////////////////////
+  // based on boolean_generator class (see utils/rnd_generator.h)
+  eoInitFixedLength<Indi, boolean_generator>
+      random(VEC_SIZE, boolean_generator());
+  // Initialization of the population
+  eoPop<Indi> pop(POP_SIZE, random);
+  // and evaluate it in one line
+  apply<Indi>(eval, pop); // STL syntax
+
+
+ + + + +
+ +  // sort pop before printing it!
+  pop.sort();
+  // Print (sorted) intial population (raw printout)
+  cout << "Initial Population" << endl;
+  cout << pop;
+
+
+ + + + +
+ +  /////////////////////////////////////
+  // selection and replacement
+  ////////////////////////////////////
+
+
+ + + + +
+ +  // The robust tournament selection
+  eoDetTournamentSelect<Indi> selectOne(T_SIZE);            // T_SIZE in [2,POP_SIZE]
+ +  // is now encapsulated in a eoSelectPerc (entage)
+  eoSelectPerc<Indi> select(selectOne);// by default rate==1
+
+
+ + + + +
+ +  // And we now have the full slection/replacement - though with
+  // no replacement (== generational replacement) at the moment :-)
+  eoNoReplacement<Indi> replace;
+
+
+ + + + +
+ +  //////////////////////////////////////
+  // The variation operators
+  //////////////////////////////////////
+
+
+ + + + +
+ +  // 1-point crossover for bitstring
+  eo1PtBitXover<Indi> xover1;
+  // uniform crossover for bitstring
+  eoUBitXover<Indi> xoverU;
+  // 2-pots xover
+  eoNPtsBitXover<Indi> xover2(2);
+  // Combine them with relative rates
+  eoPropCombinedQuadOp<Indi> xover(xover1, onePointRate);
+  xover.add(xoverU, URate);
+  xover.add(xover2, twoPointsRate, true);
+
+
+ + + + +
+ +  
+  // standard bit-flip mutation for bitstring
+  eoBitMutation<Indi>  mutationBitFlip(P_MUT_PER_BIT);
+  // mutate exactly 1 bit per individual
+  eoDetBitFlip<Indi> mutationOneBit;
+  // Combine them with relative rates
+  eoPropCombinedMonOp<Indi> mutation(mutationBitFlip, bitFlipRate);
+  mutation.add(mutationOneBit, oneBitRate, true);
+  
+ +  // The operators are  encapsulated into an eoTRansform object
+  eoSGATransform<Indi> transform(xover, CROSS_RATE, mutation, MUT_RATE);
+
+
+ + + + +
+ + +
+ + + + +
+ +  //////////////////////////////////////
+  // termination conditions: use more than one
+  /////////////////////////////////////
+  // stop after MAX_GEN generations
+  eoGenContinue<Indi> genCont(MAX_GEN);
+  // do MIN_GEN gen., then stop after STEADY_GEN gen. without improvement
+  eoSteadyFitContinue<Indi> steadyCont(MIN_GEN, STEADY_GEN);
+  // stop when fitness reaches a target (here VEC_SIZE)
+  eoFitContinue<Indi> fitCont(0);
+  // do stop when one of the above says so
+  eoCombinedContinue<Indi> continuator(genCont);
+  continuator.add(steadyCont);
+  continuator.add(fitCont);
+
+
+ + + + +
+ +  /////////////////////////////////////////
+  // the algorithm
+  ////////////////////////////////////////
+  // Easy EA requires
+  // selection, transformation, eval, replacement, and stopping criterion
+  eoEasyEA<Indi> gga(continuator, eval, select, transform, replace);
+  // Apply algo to pop - that's it!
+  gga(pop);
+  
+
+
+ + + + +
+ +  // Print (sorted) intial population
+  pop.sort();
+  cout << "FINAL Population\n" << pop << endl;
+
+
+ + +
+ +}
+// A main that catches the exceptions
+int main(int argc, char **argv)
+{
+#ifdef _MSC_VER
+  //  rng.reseed(42);
+      int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
+        flag |= _CRTDBG_LEAK_CHECK_DF;
+      _CrtSetDbgFlag(flag);
+//    _CrtSetBreakAlloc(100);
+#endif
+      try
+      {
+              main_function(argc, argv);
+      }
+      catch(exception& e)
+      {
+              cout << "Exception: " << e.what() << '\n';
+      }
+      return 1;
+}
+
-
Back to Lesson 2 - Tutorial main page - Algorithm-Based - Component-Based page - Programming hints - EO @@ -336,8 +362,8 @@ documentation
Marc Schoenauer
- -
Last modified: Sun Nov -19 22:26:27 2000 +
Last +modified: Sun Nov 19 22:26:27 2000 + diff --git a/eo/tutorial/html/FirstBitGA.html b/eo/tutorial/html/FirstBitGA.html index a7e5f1794..c0bb7467a 100644 --- a/eo/tutorial/html/FirstBitGA.html +++ b/eo/tutorial/html/FirstBitGA.html @@ -2,7 +2,7 @@ - + FirstBitGA.html @@ -15,7 +15,7 @@ documentation

-FirstBitGA.html

+Code for FirstBitGA Click on the figure to see the corresponding code.
In the code, the colors are meaningfull
The actual code is in boldface and the comment in normal face. @@ -44,12 +44,10 @@ istrstream -
//----------------------------------------------------------------------------- -
// Include the corresponding file -
#include <ga.h>          -// bitstring representation & operators +
#include <ga.h>
+//-----------------------------------------------------------------------------
// define your individuals -
typedef eoBin<double> Indi;        +
typedef eoBit<double> Indi;        // A bitstring with fitness double
@@ -216,8 +214,8 @@ is needed - +
 // 1-point mutation for bitstring -
 eoBinCrossover<Indi> xover;
 // 1-point crossover for bitstring +
 eo1PtBitXover<Indi> xover;
@@ -226,10 +224,10 @@ is needed
 // standard bit-flip mutation for bitstring -
 eoBinMutation<Indi>  mutation(P_MUT_PER_BIT); +
 eoBitMutation<Indi>  mutation(P_MUT_PER_BIT); - + - + - + @@ -230,15 +226,15 @@ mutation(EPSILON);
eoArithmeticCrossover<Indi> xover; -
 ////////////////////////////////////// diff --git a/eo/tutorial/html/FirstRealEA.html b/eo/tutorial/html/FirstRealEA.html index 6b7575418..49652e6b9 100644 --- a/eo/tutorial/html/FirstRealEA.html +++ b/eo/tutorial/html/FirstRealEA.html @@ -34,9 +34,8 @@ Breeder - and Combined Ops
//-----------------------------------------------------------------------------
// standard includes
#include <stdexcept>  // runtime_error  -
#include <iostream>   -// -cout +
#include <iostream>    +// cout
#include <strstream>  // ostrstream, istrstream
// the general include for eo @@ -46,10 +45,8 @@ istrstream - @@ -81,16 +78,12 @@ seed for random number generator
 const unsigned int T_SIZE = 3; // size for tournament selection
 const unsigned int VEC_SIZE = 8; -// -Number of object variables in genotypes +// Number of object variables in genotypes
 const unsigned int POP_SIZE = 20; -// -Size of population +// Size of population
 const unsigned int MAX_GEN = 500; -// -Maximum number of generation before STOP -
 const unsigned int MIN_GEN = 10; - +// Maximum number of generation before STOP +
 const unsigned int MIN_GEN = 10;  // Minimum number of generation before ...
 const unsigned int STEADY_GEN = 50; // stop after STEADY_GEN gen. without improvelent @@ -105,17 +98,13 @@ SIGMA = 0.3;        // std dev. for normal mutation
 // some parameters for chosing among different operators -
 const double segmentRate = 0.5;   - +
 const double segmentRate = 0.5;    // relative weight for 1-pt Xover
 const double arithmeticRate = 0.5; -// -relative weight for 2-pt Xover +
// relative weight for 2-pt Xover

 const double uniformMutRate = 0.5; -// -relative weight for bit-flip mutation -
 const double detMutRate = 0.5;    - +// relative weight for bit-flip mutation +
 const double detMutRate = 0.5;     // relative weight for one-bit mutation
 const double normalMutRate = 0.5;  // relative weight for normal mutation @@ -193,8 +182,8 @@ it! @@ -307,7 +296,8 @@ eval, select, transform, replace); it!
 cout << "\n              Here we go\n\n"; -
 gga(pop); +
 gga(pop); +
 
//----------------------------------------------------------------------------- -
// Include the corresponding file  -
#include <es.h>          -// real-representation & operators  +
#include <es.h>
+//-----------------------------------------------------------------------------
// define your individuals
typedef eoReal<double> Indi; 
 // The robust tournament selection
 eoDetTournamentSelect<Indi> selectOne(T_SIZE); -
// is now -encapsulated in a eoSelectPerc (entage) +
// +is now encapsulated in a eoSelectPerc (entage)
 eoSelectPerc<Indi> select(selectOne);// by default rate==1
diff --git a/eo/tutorial/html/FirstRealGA.html b/eo/tutorial/html/FirstRealGA.html index b3687ec77..f06c178a9 100644 --- a/eo/tutorial/html/FirstRealGA.html +++ b/eo/tutorial/html/FirstRealGA.html @@ -2,9 +2,9 @@ - - ../FirstRealGA.html - + + FirstRealGA.html + Back to Lesson 1 - Tutorial @@ -15,294 +15,327 @@ documentation

-../FirstRealGA.html

-Click on the figure to see the corresponding code. -
In the code, the colors are meaningfull -
The actual code is in boldface and the comment in normal face. -
-
+Code for FirstRealGA +Click on the figure to see the corresponding code.
+In the code, the colors are meaningfull
+The actual code is in boldface and the comment in normal face. +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
  + - +
//----------------------------------------------------------------------------- -
// FirstRealGA.cpp -
//----------------------------------------------------------------------------- -
//* -
// An instance of a VERY simple Real-coded -Genetic Algorithm -
// -
//----------------------------------------------------------------------------- -
// standard includes -
#include <stdexcept>  // runtime_error  -
#include <iostream>    -// cout -
#include <strstream>  // ostrstream, -istrstream -
// the general include for eo -
#include <eo>
+//-----------------------------------------------------------------------------
+// FirstRealGA.cpp
+//-----------------------------------------------------------------------------
+//*
+// An instance of a VERY simple Real-coded Genetic Algorithm
+//
+//-----------------------------------------------------------------------------
+// standard includes
+#include <stdexcept>  // runtime_error
+#include <iostream>    // cout
+#include <strstream>  // ostrstream, istrstream
+// the general include for eo
+#include <eo>
+
+
- - +
- +
//----------------------------------------------------------------------------- -
// Include the corresponding file -
#include <es.h>          -// real-representation & operators -
// define your individuals -
typedef eoReal<double> Indi;
+ +#include <es.h>
+//-----------------------------------------------------------------------------
+// define your individuals
+ typedef eoReal<double> Indi;
+
+
- - +
//----------------------------------------------------------------------------- -
// a simple fitness function that computes -the euclidian norm of a real vector -
//      @param _indi -A real-valued individual  -
double real_value(const -Indi & _indi) -
{ -
 double sum = 0; -
 for (unsigned i = 0; i < _indi.size(); -i++) -
         -sum += _indi[i]*_indi[i]; -
 return (-sum);                      -// maximizing only -
}
+ +//-----------------------------------------------------------------------------
+// a simple fitness function that computes the euclidian norm of a real vector
+//      @param _indi A real-valued individual
+ +double real_value(const Indi & _indi)
+{
+  double sum = 0;
+  for (unsigned i = 0; i < _indi.size(); i++)
+          sum += _indi[i]*_indi[i];
+  return (-sum);                      // maximizing only
+}
+
+
- - +
- +
//----------------------------------------------------------------------------- -
void main_function(int argc, char **argv) -
{
+ +//-----------------------------------------------------------------------------
+void main_function(int argc, char **argv)
+{
+
+
- - +
- +
 // all parameters are hard-coded! -
 const unsigned int SEED = 42; // -seed for random number generator -
 const unsigned int VEC_SIZE = 8; -// Number of object variables in genotypes -
 const unsigned int POP_SIZE = 20; -// Size of population -
 const unsigned int T_SIZE = 3; // -size for tournament selection -
 const unsigned int MAX_GEN = 500; -// Maximum number of generation before STOP -
 const float CROSS_RATE = 0.8; // -Crossover rate -
 const double EPSILON = 0.01;  -// range for real uniform mutation -
 const float MUT_RATE = 0.5;    -// mutation rate
+ +  // all parameters are hard-coded!
+  const unsigned int SEED = 42; // seed for random number generator
+  const unsigned int VEC_SIZE = 8; // Number of object variables in genotypes
+  const unsigned int POP_SIZE = 20; // Size of population
+  const unsigned int T_SIZE = 3; // size for tournament selection
+  const unsigned int MAX_GEN = 500; // Maximum number of generation before STOP
+  const float CROSS_RATE = 0.8; // Crossover rate
+  const double EPSILON = 0.01;  // range for real uniform mutation
+  const float MUT_RATE = 0.5;    // mutation rate
+
+
- - +
- +
////////////////////////// -
 //  Random seed -
 ////////////////////////// -
 //reproducible random seed: -if you don't change SEED above,  -
 // you'll aways get the same -result, NOT a random run -
 rng.reseed(SEED);
+ + +  //////////////////////////
+  //  Random seed
+  //////////////////////////
+  //reproducible random seed: if you don't change SEED above,
+  // you'll aways get the same result, NOT a random run
+  rng.reseed(SEED);
+
+
- - +
- +
 ///////////////////////////// -
 // Fitness function -
 //////////////////////////// -
 // Evaluation: from a plain -C++ fn to an EvalFunc Object -
 eoEvalFuncPtr<Indi> eval(  -real_value );
+ +  /////////////////////////////
+  // Fitness function
+  ////////////////////////////
+  // Evaluation: from a plain C++ fn to an EvalFunc Object
+  eoEvalFuncPtr<Indi> eval(  real_value );
+
+
- - +
- +
 //////////////////////////////// -
 // Initilisation of population -
 //////////////////////////////// -
 // declare the population -
 eoPop<Indi> pop; -
 // fill it! -
 for (unsigned int igeno=0; igeno<POP_SIZE; -igeno++) -
     { -
         -Indi v;                  -// void individual, to be filled -
         -for (unsigned ivar=0; ivar<VEC_SIZE; ivar++) -
             -{ -
                 -double r = 2*rng.uniform() - 1; // new value, random in [-1,1) -
                 -v.push_back(r);            -// append that random value to v -
             -} -
         -eval(v);                                  -// evaluate it -
         -pop.push_back(v);                -// and put it in the population -
     }
+ +  ////////////////////////////////
+  // Initilisation of population
+  ////////////////////////////////
+  // declare the population
+  eoPop<Indi> pop;
+  // fill it!
+  for (unsigned int igeno=0; igeno<POP_SIZE; igeno++)
+      {
+          Indi v;                  // void individual, to be filled
+          for (unsigned ivar=0; ivar<VEC_SIZE; ivar++)
+              {
+                  double r = 2*rng.uniform() - 1; // new value, random in [-1,1)
+                  v.push_back(r);            // append that random value to v
+              }
+          eval(v);                                  // evaluate it
+          pop.push_back(v);                // and put it in the population
+      }
+
+
- - +
- +
 // sort pop before printing -it! -
 pop.sort(); -
 // Print (sorted) intial population -(raw printout) -
 cout << "Initial Population" -<< endl; -
 cout << pop;
+ +  // sort pop before printing it!
+  pop.sort();
+  // Print (sorted) intial population (raw printout)
+  cout << "Initial Population" << endl;
+  cout << pop;
+
+
- - +
- +
 ///////////////////////////////////// -
 // selection and replacement -
 ////////////////////////////////////
+ +  /////////////////////////////////////
+  // selection and replacement
+  ////////////////////////////////////
+
+
- - +
- +
 // The robust tournament selection -
 eoDetTournamentSelect<Indi> select(T_SIZE);            -// T_SIZE in [2,POP_SIZE]
+ +  // The robust tournament selection
+  eoDetTournamentSelect<Indi> select(T_SIZE);            // T_SIZE in [2,POP_SIZE]
+
+
- - +
- +
 // eoSGA uses generational replacement -by default -
 // so no replacement procedure -has to be given
+ +  // eoSGA uses generational replacement by default
+  // so no replacement procedure has to be given
+
+
- - +
- +
+ + +
- - +
- +
 ////////////////////////////////////// -
 // termination condition -
 ///////////////////////////////////// -
 // stop after MAX_GEN generations -
 eoGenContinue<Indi> continuator(MAX_GEN); -
 
+ +  //////////////////////////////////////
+  // termination condition
+  /////////////////////////////////////
+  // stop after MAX_GEN generations
+  eoGenContinue<Indi> continuator(MAX_GEN);
+  
+
+
- - +
- +
 ////////////////////////////////////// -
 // The variation operators -
 //////////////////////////////////////
+ +  //////////////////////////////////////
+  // The variation operators
+  //////////////////////////////////////
+
+
- - +
- +
 // offspring(i) uniformly chosen -in [parent(i)-epsilon, parent(i)+epsilon] -
 eoUniformMutation<Indi>  -mutation(EPSILON); 
+ +  // offspring(i) uniformly chosen in [parent(i)-epsilon, parent(i)+epsilon]
+  eoUniformMutation<Indi>  mutation(EPSILON);
+
+
- - +
- +
 // offspring(i) is a linear -combination of parent(i) -
 eoArithmeticCrossover<Indi> xover;
+ +  // offspring(i) is a linear combination of parent(i)
+  eoArithmeticCrossover<Indi> xover;
+
+
- - +
- +
 ///////////////////////////////////////// -
 // the algorithm -
 //////////////////////////////////////// -
 // standard Generational GA -requires -
 // selection, evaluation, crossover -and mutation, stopping criterion -

 eoSGA<Indi> gga(select, xover, -CROSS_RATE, mutation, MUT_RATE,  -
                                   -eval, continuator); -
 // Apply algo to pop - that's -it! -
 gga(pop); -
 

+ +  /////////////////////////////////////////
+  // the algorithm
+  ////////////////////////////////////////
+  // standard Generational GA requires
+  // selection, evaluation, crossover and mutation, stopping criterion
+
+  eoSGA<Indi> gga(select, xover, CROSS_RATE, mutation, MUT_RATE,
+                                    eval, continuator);
+  // Apply algo to pop - that's it!
+  gga(pop);
+  
+
+
- - +
- +
 // Print (sorted) intial population -
 pop.sort(); -
 cout << "FINAL Population\n" -<< pop << endl;
+ +  // Print (sorted) intial population
+  pop.sort();
+  cout << "FINAL Population\n" << pop << endl;
+
+
- - +
- +
} -
// A main that catches the exceptions -
int main(int argc, char **argv) -
{ -
#ifdef _MSC_VER -
 //  rng.reseed(42); -
     int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF); -
       flag -|= _CRTDBG_LEAK_CHECK_DF; -
     _CrtSetDbgFlag(flag); -
//    _CrtSetBreakAlloc(100); -
#endif -
     try -
     { -
             -main_function(argc, argv); -
     } -
     catch(exception& -e) -
     { -
             -cout << "Exception: " << e.what() << '\n'; -
     } -
     return 1; -
}
+ +}
+// A main that catches the exceptions
+int main(int argc, char **argv)
+{
+#ifdef _MSC_VER
+  //  rng.reseed(42);
+      int flag = _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
+        flag |= _CRTDBG_LEAK_CHECK_DF;
+      _CrtSetDbgFlag(flag);
+//    _CrtSetBreakAlloc(100);
+#endif
+      try
+      {
+              main_function(argc, argv);
+      }
+      catch(exception& e)
+      {
+              cout << "Exception: " << e.what() << '\n';
+      }
+      return 1;
+}
+
-
Back to Lesson 1 - Tutorial main page - Algorithm-Based - Component-Based page - Programming hints - EO @@ -310,8 +343,8 @@ documentation
Marc Schoenauer
- -
Last modified: Sun Nov -19 08:31:29 2000 +
Last +modified: Sun Nov 19 08:31:29 2000 + diff --git a/eo/tutorial/html/Firstmerge.html b/eo/tutorial/html/Firstmerge.html index d71236b3a..61da23f44 100644 --- a/eo/tutorial/html/Firstmerge.html +++ b/eo/tutorial/html/Firstmerge.html @@ -2,7 +2,7 @@ - + Differences @@ -57,15 +57,11 @@ the parameter for the mutation).
#include -<es.h> -
typedef eoReal<double> -Indi;
#include <es.h>
+typedef eoReal<double> Indi;
#include -<ga.h> -
typedef eoBin<double> -Indi;
#include <ga.h>
+typedef eoBit<double> Indi;
eoBinMutation<Indi>  +eoBitMutation<Indi>  mutation(P_MUT_PER_BIT); -
eoBinCrossover<Indi> +
eo1PtBitXover<Indi> xover;
-
eoSGA<Indi> +eoSGA<Indi> gga(select, xover, CROSS_RATE,
                mutation, MUT_RATE, eval, continuator); @@ -255,11 +251,10 @@ code removed]

}
-
eoSGA<Indi> +eoSGA<Indi> gga(select, xover, CROSS_RATE,
                -mutation, MUT_RATE, -
eval, continuator); +mutation, MUT_RATE, eval, continuator);

gga(pop);
pop.sort();
cout << diff --git a/eo/tutorial/html/SecondBitEA.html b/eo/tutorial/html/SecondBitEA.html index dc56d4917..914f8ec6b 100644 --- a/eo/tutorial/html/SecondBitEA.html +++ b/eo/tutorial/html/SecondBitEA.html @@ -63,11 +63,8 @@ the number of ones of a bitstring +
typedef eoBit<double> Indi;
//----------------------------------------------------------------------------- -
// Include the corresponding file -
#include <ga.h>          -// bitstring representation & operators
// define your genotype and fitness types -
typedef eoBin<double> Indi;
@@ -314,6 +311,7 @@ of initializatio of the population
 // The robust tournament selection
 eoDetTournamentSelect<Indi> selectOne(tSize);       + // tSize in [2,POPSIZE]
 // is now encapsulated in a eoSelectPerc (entage) @@ -346,11 +344,11 @@ replace; 
 // 1-point crossover for bitstring -
 eoBinCrossover<Indi> xover1; +
 eo1PtBitXover<Indi> xover1;
 // uniform crossover for bitstring -
 eoBinUxOver<Indi> xoverU; +
 eoUBitXover<Indi> xoverU;
 // 2-pots xover -
 eoBinNxOver<Indi> xover2(2); +
 eoNPtsBitXover<Indi> xover2(2);
 // Combine them with relative rates
 eoPropCombinedQuadOp<Indi> xover(xover1, @@ -365,7 +363,7 @@ true);
 // standard bit-flip mutation for bitstring -
 eoBinMutation<Indi>  mutationBitFlip(pMutPerBit); +
 eoBitMutation<Indi>  mutationBitFlip(pMutPerBit);
 // mutate exactly 1 bit per individual
 eoDetBitFlip<Indi> mutationOneBit;  diff --git a/eo/tutorial/html/eoCheckPoint.html b/eo/tutorial/html/eoCheckPoint.html new file mode 100644 index 000000000..aaf8cb486 --- /dev/null +++ b/eo/tutorial/html/eoCheckPoint.html @@ -0,0 +1,124 @@ + + + + + + Variation Operators + + +General: Algorithm-Based +- Component-Based - Programming +hints - EO +documentation +
+
+
Local: Introduction +- Continuators - Combined +continuators - Checkpoints - Statistics +- Monitors - Updaters +
+
+
+

+CheckPointing

+What +is Checkpointing about? +
Evolutionary Algorithms are ticked +

EO classes described in this page: +

    +
  • +Base classes: eoCheckPoint, eoContinue, +eoStat, eoSortedStat, eoMonitor, eoUpdater
  • + +
  • +Derived classes: eoCombinedContinue,
  • + +
  • +Related classes: eoGnuPlot
  • +
+ +
  +

+


Continuators: +
  +

Continuators are functors that compute stopping critera. They receive +a population and return a boolean value which is set to false only when +some stopping vriterion is met. All algorithms in EO have a loop that goes +while(continuator(pop) +{ ... } which means that the algorithm stops only when +the continuator returns false. +

Interface: +
  +

Using a continuator: +
You can find an first example of using a continuator in the code for +FirstBitEA in Lesson2. +
If you want to find out how it is used inside an algorithm, go and +see for instance in eoSGA, the simplest EA within EO. +

Writing a +continuator: +
There are only two things to modify in the template +class definitions provided (apart from the name of the class you are +creating!) +

    +
  • +The constructor, where you pass to the object +any useful parameter (see the private data at end of class definition).
  • + +
  • +The operator() method, which performs the +actual test on the population.
  • +
+Don't forget to return false +when the stopping criterion is met! +

+


Combining +continuators: +

+


CheckPoints: +

Interface: +

Using a checkpoint: An eoCheckPoint +being an eoContinue, its usage is exactly the same. However, an eoCheckPoint +will actually do many more things than an eoContinue before returning its +boolean result as an eoContinue. +

Writing a +checkpoint: +
This is something you should never have to do. However, should you +fell you have to do it, please do - and send us both the reasons that lead +you to that (wqhat is it you couldn't do with existing eoCheckPoint), and +the resulting code, of course. +
+


Statistics: +

Interface: +

Using statistics: +

Writing a statitic: +
+


Monitors: +

Interface: +

Using monitors: +

Writing a monitor: +

+


Updater: +

Interface: +

Using updaters: +

Writing an updater: +
  +

+


Local: Introduction +- Continuators - Combined +continuators - Checkpoints - Statistics +- Monitors - Updaters +
+
General: Algorithm-Based +- Component-Based - Programming +hints -EO +documentation +
+
+
+Marc Schoenauer
+ +
Last +modified: Fri Dec. 8 2000  +
  + + diff --git a/eo/tutorial/html/eoEngine.html b/eo/tutorial/html/eoEngine.html index 468d4191b..35ae194c1 100644 --- a/eo/tutorial/html/eoEngine.html +++ b/eo/tutorial/html/eoEngine.html @@ -159,12 +159,9 @@ paradigm).

Note: some procedures for selecting a single individual require some pre-processing of the whole population that takes place before any selection, and will be repeated identically -for every individual. The encapsulation of an eoSelectOne -into an eoSelectMany allows to call such technical -processing only once through a call to the setup method of class eoSelectOne. -This method does nothing by default, but is implemented for instance in -eoProportionalSelect (the roulette wheel-selection) to compute only once -the total of the fitnesses of all individuals in the population. +for every individual. The encapsulation of an  into an  allows +to call such technical processing only once through the use of method setup +of class . This method does nothing by default, but is mandatory



eoSelect: Other @@ -244,8 +241,6 @@ and you can probably guess what each of them actually does :-)
 

  -
  -
 

Available instances of eoMergeReduce replacement include