From 6d8e3a65043d7cf56a699c5a64d63c5ea4659ef1 Mon Sep 17 00:00:00 2001 From: mac Date: Thu, 10 Aug 2000 14:18:34 +0000 Subject: [PATCH] Extreme cleanup, see src/obsolete for details --- eo/Makefile.am | 7 +- eo/doc/eo.cfg | 4 +- eo/src/EO.h | 1 + eo/src/Makefile.am | 7 +- eo/src/apply.h | 41 +++ eo/src/eo | 83 ++++-- eo/src/eoAlgo.h | 22 +- eo/src/eoBreed.h | 69 +++++ eo/src/eoCombinedContinue.h | 59 ++++ ...eoExternalOpFunctions.cpp => eoContinue.h} | 38 ++- eo/src/eoCopyElite.h | 110 ++++++++ eo/src/eoCounter.h | 219 +++++++++++++++ eo/src/eoDetTournament.h | 12 +- eo/src/eoDetTournamentInserter.h | 1 - eo/src/eoEasyEA.h | 150 +++++++--- eo/src/eoEvalFunc.h | 24 +- eo/src/eoEvalFuncPtr.h | 12 +- eo/src/eoEvolutionStrategy.h | 87 ++++++ eo/src/eoFitContinue.h | 58 ++++ eo/src/eoFixedLength.h | 14 +- eo/src/eoFunctor.h | 144 ++++++++++ eo/src/eoFunctorStore.cpp | 11 + eo/src/eoFunctorStore.h | 60 ++++ eo/src/eoGOpBreeder.h | 14 +- eo/src/eoGOpSelector.h | 2 +- eo/src/eoGenContinue.h | 78 ++++++ eo/src/eoIndiSelector.h | 68 ++--- eo/src/eoInit.h | 84 +++++- eo/src/eoInplaceTransform.h | 193 +++++++++++++ eo/src/eoInserter.h | 15 +- eo/src/eoMerge.h | 135 +++++---- eo/src/eoObject.h | 10 +- eo/src/eoOp.h | 170 +++--------- eo/src/eoPop.h | 192 ++++++++++--- eo/src/eoProportional.h | 73 +++++ eo/src/eoReduce.h | 58 ++++ eo/src/eoReplacement.h | 111 ++++++++ eo/src/eoSGA.h | 101 +++++++ eo/src/eoScalarFitness.h | 27 +- eo/src/eoSelect.h | 43 +++ eo/src/eoSelectOne.h | 49 ++++ eo/src/eoSelectPerc.h | 72 +++++ .../{eoUniformSelect.h => eoSelectRandom.h} | 35 +-- ...tialGOpSelector.h => eoSequentialGOpSel.h} | 31 +-- eo/src/eoSteadyStateEA.h | 29 +- eo/src/eoSteadyStateInserter.h | 6 +- ...eGeneration.h => eoSteadyStateTransform.h} | 35 ++- eo/src/eoStochTournament.h | 7 +- eo/src/eoStochTournamentInserter.h | 1 - eo/src/eoTransform.h | 41 +++ eo/src/eoVariableLength.h | 38 ++- eo/src/eoWrappedOps.h | 197 ++++++------- eo/src/es/Makefile.am | 5 +- eo/src/es/eoESFullMut.h | 253 ----------------- eo/src/es/eoEsChromInit.h | 9 +- eo/src/es/eoEsMutate.h | 14 +- eo/src/ga/eoBin.h | 27 +- eo/src/ga/eoBitOp.h | 95 +++---- eo/src/ga/eoBitOpFactory.h | 6 +- eo/src/gp/eoParseTree.h | 20 +- eo/src/gp/node_pool.h | 28 ++ eo/src/gp/parse_tree.h | 30 +- eo/src/{ => obsolete}/eo1d.h | 0 eo/src/{ => obsolete}/eo1dWDistance.h | 0 eo/src/{ => obsolete}/eo2d.h | 0 eo/src/{ => obsolete}/eo2dVector.h | 0 eo/src/{ => obsolete}/eoAtomBitFlip.h | 115 ++++---- eo/src/{ => obsolete}/eoAtomCreep.h | 0 eo/src/{ => obsolete}/eoAtomMutation.h | 0 eo/src/{ => obsolete}/eoAtomMutator.h | 34 +-- eo/src/{ => obsolete}/eoAtomRandom.h | 6 +- eo/src/obsolete/eoBin.h | 89 ++++++ eo/src/{ => obsolete}/eoBreeder.h | 14 +- .../eoDetTournamentIndiSelector.h | 0 eo/src/{ => obsolete}/eoDistance.h | 0 eo/src/{ => obsolete}/eoDup.h | 18 +- eo/src/obsolete/eoES.h | 164 +++++++++++ eo/src/{es => obsolete}/eoESChrom.h | 46 ++- eo/src/{es => obsolete}/eoESFullChrom.h | 18 +- eo/src/obsolete/eoESFullMut.h | 261 ++++++++++++++++++ eo/src/{ => obsolete}/eoEvalFuncPtrCnt.h | 0 eo/src/{ => obsolete}/eoFitTerm.h | 40 ++- eo/src/{ => obsolete}/eoFitness.h | 0 eo/src/{ => obsolete}/eoGenTerm.h | 27 +- eo/src/{ => obsolete}/eoGeneration.h | 5 +- eo/src/{ => obsolete}/eoID.h | 0 eo/src/{ => obsolete}/eoInclusion.h | 0 eo/src/{ => obsolete}/eoInsertion.h | 4 +- eo/src/{ => obsolete}/eoKill.h | 0 eo/src/{ => obsolete}/eoLottery.h | 5 +- eo/src/{ => obsolete}/eoMutation.h | 0 eo/src/{ => obsolete}/eoNegExp.h | 0 eo/src/{ => obsolete}/eoNonUniform.h | 0 eo/src/{ => obsolete}/eoNormal.h | 0 eo/src/{ => obsolete}/eoPopOps.h | 0 eo/src/{ => obsolete}/eoRandomBreed.h | 0 eo/src/{ => obsolete}/eoRandomIndiSelector.h | 0 eo/src/{ => obsolete}/eoRandomSelect.h | 0 eo/src/{ => obsolete}/eoRank.h | 36 +-- eo/src/{ => obsolete}/eoRnd.h | 0 eo/src/{ => obsolete}/eoScheme.h | 0 eo/src/{other => obsolete}/eoStringMutation.h | 5 +- eo/src/{ => obsolete}/eoTerm.h | 0 eo/src/{ => obsolete}/eoTournament.h | 0 eo/src/{ => obsolete}/eoTranspose.h | 97 +++---- eo/src/{ => obsolete}/eoUniform.h | 0 eo/src/{ => obsolete}/eoUniformXOver.h | 0 eo/src/{ => obsolete}/eoVector.h | 0 eo/src/{ => obsolete}/eoXOver2.h | 0 eo/src/other/eoExternalEO.h | 2 - eo/src/other/eoExternalOpFunctions.h | 91 +++--- eo/src/other/eoString.h | 92 +----- eo/src/utils/Makefile.am | 6 +- eo/src/utils/checkpointing | 1 + eo/src/utils/eoCheckPoint.h | 14 +- eo/src/utils/eoFileMonitor.cpp | 8 +- eo/src/utils/eoMonitor.h | 14 +- eo/src/utils/eoParam.h | 6 +- eo/src/utils/eoRNG.cpp | 2 + eo/src/utils/eoRNG.h | 59 +--- eo/src/utils/eoStat.h | 5 +- eo/src/utils/eoStdoutMonitor.cpp | 37 +++ eo/src/utils/eoStdoutMonitor.h | 49 ++++ eo/src/utils/eoUpdater.h | 18 +- eo/src/utils/rnd_generators.h | 48 +++- eo/test/Makefile.am | 122 +------- eo/test/real_value.h | 4 +- eo/test/t-eoBaseFunctions.cpp | 26 ++ eo/test/t-eoCheckpointing.cpp | 5 +- eo/test/t-eoESFull.cpp | 64 ++--- eo/test/t-eoExternalEO.cpp | 16 +- eo/test/t-eoFunctor.cpp | 53 ++++ eo/test/t-eoStateAndParser.cpp | 1 - eo/test/t-eobin.cpp | 87 ++++-- eo/test/t-eobreeder.cpp | 2 +- eo/test/t-eofitness.cpp | 156 +++-------- eo/win/eo.dsp | 4 + eo/win/eo_win.dsw | 15 + eo/win/esfull.dsp | 12 +- eo/win/t_eoFunctor.dsp | 104 +++++++ eo/win/t_eobin.dsp | 2 +- 141 files changed, 3933 insertions(+), 1811 deletions(-) create mode 100644 eo/src/apply.h create mode 100644 eo/src/eoBreed.h create mode 100644 eo/src/eoCombinedContinue.h rename eo/src/{other/eoExternalOpFunctions.cpp => eoContinue.h} (56%) create mode 100644 eo/src/eoCopyElite.h create mode 100644 eo/src/eoCounter.h create mode 100644 eo/src/eoEvolutionStrategy.h create mode 100644 eo/src/eoFitContinue.h create mode 100644 eo/src/eoFunctor.h create mode 100644 eo/src/eoFunctorStore.cpp create mode 100644 eo/src/eoFunctorStore.h create mode 100644 eo/src/eoGenContinue.h create mode 100644 eo/src/eoInplaceTransform.h create mode 100644 eo/src/eoProportional.h create mode 100644 eo/src/eoReduce.h create mode 100644 eo/src/eoReplacement.h create mode 100644 eo/src/eoSGA.h create mode 100644 eo/src/eoSelect.h create mode 100644 eo/src/eoSelectOne.h create mode 100644 eo/src/eoSelectPerc.h rename eo/src/{eoUniformSelect.h => eoSelectRandom.h} (64%) rename eo/src/{eoSequentialGOpSelector.h => eoSequentialGOpSel.h} (74%) rename eo/src/{eoSteadyStateGeneration.h => eoSteadyStateTransform.h} (77%) create mode 100644 eo/src/eoTransform.h delete mode 100644 eo/src/es/eoESFullMut.h rename eo/src/{ => obsolete}/eo1d.h (100%) rename eo/src/{ => obsolete}/eo1dWDistance.h (100%) rename eo/src/{ => obsolete}/eo2d.h (100%) rename eo/src/{ => obsolete}/eo2dVector.h (100%) rename eo/src/{ => obsolete}/eoAtomBitFlip.h (96%) rename eo/src/{ => obsolete}/eoAtomCreep.h (100%) rename eo/src/{ => obsolete}/eoAtomMutation.h (100%) rename eo/src/{ => obsolete}/eoAtomMutator.h (73%) rename eo/src/{ => obsolete}/eoAtomRandom.h (95%) create mode 100644 eo/src/obsolete/eoBin.h rename eo/src/{ => obsolete}/eoBreeder.h (92%) rename eo/src/{ => obsolete}/eoDetTournamentIndiSelector.h (100%) rename eo/src/{ => obsolete}/eoDistance.h (100%) rename eo/src/{ => obsolete}/eoDup.h (80%) create mode 100644 eo/src/obsolete/eoES.h rename eo/src/{es => obsolete}/eoESChrom.h (77%) rename eo/src/{es => obsolete}/eoESFullChrom.h (94%) create mode 100644 eo/src/obsolete/eoESFullMut.h rename eo/src/{ => obsolete}/eoEvalFuncPtrCnt.h (100%) rename eo/src/{ => obsolete}/eoFitTerm.h (59%) rename eo/src/{ => obsolete}/eoFitness.h (100%) rename eo/src/{ => obsolete}/eoGenTerm.h (76%) rename eo/src/{ => obsolete}/eoGeneration.h (96%) rename eo/src/{ => obsolete}/eoID.h (100%) rename eo/src/{ => obsolete}/eoInclusion.h (100%) rename eo/src/{ => obsolete}/eoInsertion.h (94%) rename eo/src/{ => obsolete}/eoKill.h (100%) rename eo/src/{ => obsolete}/eoLottery.h (94%) rename eo/src/{ => obsolete}/eoMutation.h (100%) rename eo/src/{ => obsolete}/eoNegExp.h (100%) rename eo/src/{ => obsolete}/eoNonUniform.h (100%) rename eo/src/{ => obsolete}/eoNormal.h (100%) rename eo/src/{ => obsolete}/eoPopOps.h (100%) rename eo/src/{ => obsolete}/eoRandomBreed.h (100%) rename eo/src/{ => obsolete}/eoRandomIndiSelector.h (100%) rename eo/src/{ => obsolete}/eoRandomSelect.h (100%) rename eo/src/{ => obsolete}/eoRank.h (83%) rename eo/src/{ => obsolete}/eoRnd.h (100%) rename eo/src/{ => obsolete}/eoScheme.h (100%) rename eo/src/{other => obsolete}/eoStringMutation.h (94%) rename eo/src/{ => obsolete}/eoTerm.h (100%) rename eo/src/{ => obsolete}/eoTournament.h (100%) rename eo/src/{ => obsolete}/eoTranspose.h (51%) rename eo/src/{ => obsolete}/eoUniform.h (100%) rename eo/src/{ => obsolete}/eoUniformXOver.h (100%) rename eo/src/{ => obsolete}/eoVector.h (100%) rename eo/src/{ => obsolete}/eoXOver2.h (100%) create mode 100644 eo/src/utils/eoStdoutMonitor.cpp create mode 100644 eo/src/utils/eoStdoutMonitor.h create mode 100644 eo/test/t-eoBaseFunctions.cpp create mode 100644 eo/test/t-eoFunctor.cpp create mode 100644 eo/win/t_eoFunctor.dsp diff --git a/eo/Makefile.am b/eo/Makefile.am index e1c123c03..af9864ab2 100644 --- a/eo/Makefile.am +++ b/eo/Makefile.am @@ -6,10 +6,9 @@ SUBDIRS = src test win doc #Directory for documents +DOCDIR = ~/public_html/eodocs #Directory for indices -- not useful for the user IDXDIR = ~/index -EXTRA_DIST=LICENSE - -docs: - doxygen doc/eo.cfg +EXTRA_DIST=LICENSE + diff --git a/eo/doc/eo.cfg b/eo/doc/eo.cfg index b5e7023cf..19e35db3f 100644 --- a/eo/doc/eo.cfg +++ b/eo/doc/eo.cfg @@ -179,7 +179,7 @@ INLINE_INFO = YES # alphabetically by member name. If set to NO the members will appear in # declaration order. -SORT_MEMBER_DOCS = YES +SORT_MEMBER_DOCS = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. @@ -214,7 +214,7 @@ RECURSIVE = YES # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. -EXCLUDE = +EXCLUDE = ../src/obsolete ../src/gp # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude diff --git a/eo/src/EO.h b/eo/src/EO.h index 626c662c9..05e394915 100644 --- a/eo/src/EO.h +++ b/eo/src/EO.h @@ -84,6 +84,7 @@ public: @return true if the fitness is higher */ bool operator<(const EO& _eo2) const { return fitness() < _eo2.fitness(); } + bool operator>(const EO& _eo2) const { return !(fitness() <= _eo2.fitness()); } /// Methods inherited from eoObject //@{ diff --git a/eo/src/Makefile.am b/eo/src/Makefile.am index 14129385d..ffa36a768 100644 --- a/eo/src/Makefile.am +++ b/eo/src/Makefile.am @@ -4,10 +4,11 @@ ## ############################################################################### -SUBDIRS = es ga gp obsolete utils other +SUBDIRS = es ga utils other lib_LIBRARIES = libeo.a -libeo_a_SOURCES = eoPrintable.cpp eoPersistent.cpp +libeo_a_SOURCES = eoPrintable.cpp eoPersistent.cpp eoFunctorStore.cpp libeoincdir = $(includedir)/eo -libeoinc_HEADERS = eo EO.h eoDup.h eoKill.h eoTournament.h eo1d.h eoEasyEA.h eoLottery.h eoProportionalOpSel.h eoTranspose.h eo1dWDistance.h eoEvalFunc.h eoMerge.h eoRandomBreed.h eoUniform.h eo2d.h eoEvalFuncPtr.h eoMutation.h eoRandomIndiSelector.h eoUniformSelect.h eo2dVector.h eoEvalFuncPtrCnt.h eoNegExp.h eoRandomSelect.h eoUniformXOver.h eoAlgo.h eoFactory.h eoNonUniform.h eoRank.h eoVector.h eoAtomBitFlip.h eoFitTerm.h eoNormal.h eoRnd.h eoWrappedOps.h eoAtomCreep.h eoFitness.h eoObject.h eoScalarFitness.h eoXOver2.h eoAtomMutation.h eoGOpBreeder.h eoOp.h eoScheme.h eoAtomMutator.h eoGOpSelector.h eoOpFactory.h eoSelectFactory.h eoBreeder.h eoID.h eoPersistent.h eoSteadyStateGeneration.h eoAtomRandom.h eoGenTerm.h eoOpSelMason.h eoSequentialGOpSelector.h eoBackInserter.h eoGeneration.h eoOpSelector.h eoSteadyStateEA.h eoDetTournament.h eoInclusion.h eoInit.h eoPop.h eoSteadyStateInserter.h eoDetTournamentIndiSelector.h eoIndiSelector.h eoPopOps.h eoStochTournament.h eoDetTournamentInserter.h eoInserter.h eoPrintable.h eoStochTournamentInserter.h eoDistance.h eoInsertion.h eoProportionalGOpSel.h eoTerm.h +libeoinc_HEADERS = eo EO.h apply.h eoAlgo.h eoBackInserter.h eoBreed.h eoCombinedContinue.h eoContinue.h eoCopyElite.h eoCounter.h eoDetTournament.h eoDetTournamentInserter.h eoEasyEA.h eoEvalFunc.h eoEvalFuncPtr.h eoEvolutionStrategy.h eoFactory.h eoFitContinue.h eoFixedLength.h eoFunctor.h eoFunctorStore.h eoGOpBreeder.h eoGOpSelector.h eoGenContinue.h eoIndiSelector.h eoInit.h eoInplaceTransform.h eoInserter.h eoMerge.h eoObject.h eoOp.h eoOpFactory.h eoOpSelMason.h eoOpSelector.h eoPersistent.h eoPop.h eoPrintable.h eoProportional.h eoProportionalGOpSel.h eoProportionalOpSel.h eoReduce.h eoReplacement.h eoSGA.h eoScalarFitness.h eoSelect.h eoSelectFactory.h eoSelectOne.h eoSelectPerc.h eoSelectRandom.h eoSequentialGOpSel.h eoSteadyStateEA.h eoSteadyStateInserter.h eoSteadyStateTransform.h eoStochTournament.h eoStochTournamentInserter.h eoTransform.h eoVariableLength.h eoWrappedOps.h + diff --git a/eo/src/apply.h b/eo/src/apply.h new file mode 100644 index 000000000..c0ad8a076 --- /dev/null +++ b/eo/src/apply.h @@ -0,0 +1,41 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoApply.h +// (c) Maarten Keijzer 2000 +/* + 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 + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _apply_h +#define _apply_h + +#include +#include + +template +void apply(eoUnaryFunctor& _proc, std::vector& _pop) +{ + for (unsigned i = 0; i < _pop.size(); ++i) + { + _proc(_pop[i]); + } +} + +#endif \ No newline at end of file diff --git a/eo/src/eo b/eo/src/eo index 0e37aa9db..e269e9688 100644 --- a/eo/src/eo +++ b/eo/src/eo @@ -20,6 +20,11 @@ */ //----------------------------------------------------------------------------- +#ifndef __GNUG__ +// to avoid long name warnings +#pragma warning(disable:4786) +#endif // __GNUG__ + #ifndef _eo_ #define _eo_ @@ -29,68 +34,88 @@ #include #include #include -#include +#include #include -#include +#include +#include +#include -#include -#include +// eo's +#include +#include + +//#include + +//#include +//#include #include #include -#include -#include -#include -#include +#include +//#include +//#include +//#include #include -#include -#include -#include -#include -#include -#include +//#include +//#include +//#include +//#include +//#include +//#include #include -#include -#include #include // Evaluation functions #include #include -// Terminators -#include -#include -#include +// Continuators +#include +#include +#include +#include // Selection and reproduction stuff -#include +#include +#include #include +#include #include -#include -#include -#include -#include -#include #include +#include +#include + +//#include +//#include +//#include +//#include +//#include + +//#include // Algorithms #include +#include +#include +#include + +// Utils +#include // aliens -#include +//#include //----------------------------------------------------------------------------- // to be continued ... //----------------------------------------------------------------------------- /* -#include -#include +//#include +//#include */ //----------------------------------------------------------------------------- diff --git a/eo/src/eoAlgo.h b/eo/src/eoAlgo.h index 87dcaad2c..ac9307a50 100644 --- a/eo/src/eoAlgo.h +++ b/eo/src/eoAlgo.h @@ -26,30 +26,18 @@ #define _EOALGO_H #include // for population +#include -/** This is a generic class for population-transforming algorithms. There +/** + This is a generic class for population-transforming algorithms. There is only one operator defined, which takes a population and does stuff to it. It needn't be a complete algorithm, can be also a step of an algorithm. This class just gives a common interface to linear population-transforming algorithms. - @author GeNeura Team - @version 0.0 */ template< class EOT > -class eoAlgo { -public: +class eoAlgo : public eoUnaryFunctor&> +{}; - /// Dtor - virtual ~eoAlgo() {}; - - /** Run the algorithm on a population. This operation is not constant, - because somebody would want to change stuff in the algorithm each - time it's applied. - * @param _pop is the population that the algorithm is acting on - */ - virtual void operator() ( eoPop& _pop ) = 0; - -}; - #endif diff --git a/eo/src/eoBreed.h b/eo/src/eoBreed.h new file mode 100644 index 000000000..e57f5d893 --- /dev/null +++ b/eo/src/eoBreed.h @@ -0,0 +1,69 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoBreed.h + (c) Maarten Keijzer, GeNeura Team, 2000 + + 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 _eoBreed_h +#define _eoBreed_h + + +//----------------------------------------------------------------------------- +#include +#include +//----------------------------------------------------------------------------- + +/** +eoBreed: breeding is thought of a combination of selecting and transforming +a population. For efficiency reasons you might want to build your own +eoBreed derived class rather than relying on a seperate select and transform +function. + + @see eoSelect, eoTransform, eoSelectTransform +*/ +template +class eoBreed : public eoBinaryFunctor&, eoPop&> +{}; + +/** +eoSelectTransform: special breeder that is just an application of an embedded select, +followed by an embedded transform +*/ +template +class eoSelectTransform : public eoBreed +{ + public: + eoSelectTransform(eoSelect& _select, eoTransform& _transform) : + select(_select), transform(_transform) + {} + + void operator()(const eoPop& _parents, eoPop& _offspring) + { + select(_parents, _offspring); + transform(_offspring); + } + + private : + eoSelect& select; + eoTransform& transform; +}; + +#endif diff --git a/eo/src/eoCombinedContinue.h b/eo/src/eoCombinedContinue.h new file mode 100644 index 000000000..157ca3fa9 --- /dev/null +++ b/eo/src/eoCombinedContinue.h @@ -0,0 +1,59 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoCombinedContinue.h +// (c) Maarten Keijzer, GeNeura Team, 1999, 2000 +/* + 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 _eoCombinedContinue_h +#define _eoCombinedContinue_h + +#include + +/** +Fitness continuation: + + Continues until one of the embedded continuators says halt! +*/ +template< class EOT> +class eoCombinedContinue: public eoContinue { +public: + + /// Define Fitness + typedef typename EOT::Fitness FitnessType; + + /// Ctor + eoCombinedContinue( eoContinue& _arg1, eoContinue& _arg2) + : eoContinue (), arg1(_arg1), arg2(_arg2) {}; + + /** Returns false when one of the embedded continuators say so (logical and) + */ + virtual bool operator() ( const eoPop& _pop ) + { + return arg1(_pop) && arg2(_pop); + } + +private: + eoContinue& arg1; + eoContinue& arg2; +}; + +#endif + diff --git a/eo/src/other/eoExternalOpFunctions.cpp b/eo/src/eoContinue.h similarity index 56% rename from eo/src/other/eoExternalOpFunctions.cpp rename to eo/src/eoContinue.h index 80d59c61b..0576d5d91 100644 --- a/eo/src/other/eoExternalOpFunctions.cpp +++ b/eo/src/eoContinue.h @@ -1,13 +1,9 @@ -/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - ----------------------------------------------------------------------------- - eoExternalOpFunc.h - Defines eoExternalInitOpFunc, eoExternalMonOpFunc, eoExternalBinOpFunc, eoExternalQuadOpFunc - that are used to wrap a function pointer to externally defined initialization - and 'genetic' operators - - (c) Maarten Keijzer (mkeijzer@mad.scientist.com) and GeNeura Team, 1999, 2000 - +//----------------------------------------------------------------------------- +// eoContinue.h +// (c) Maarten Keijzer, Geneura Team, 1999, 2000 +/* 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 @@ -24,20 +20,20 @@ Contact: todos@geneura.ugr.es, http://geneura.ugr.es */ +//----------------------------------------------------------------------------- -#ifndef eoExternalOpFunc_h -#define eoExternalOpFunc_h +#ifndef _eoContinue_h +#define _eoContinue_h -#include -#include -#include +#include +#include -template -class eoExternalInitFunc -{ - -public : - -}; +/** Termination condition for the genetic algorithm + * Takes the population as input, returns true for continue, + * false for termination + */ +template< class EOT> +class eoContinue : public eoUnaryFunctor&> {}; #endif + diff --git a/eo/src/eoCopyElite.h b/eo/src/eoCopyElite.h new file mode 100644 index 000000000..cb27500b5 --- /dev/null +++ b/eo/src/eoCopyElite.h @@ -0,0 +1,110 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoCopyElite.h +// Base class for elitist-merging classes +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef eoCopyElite_h +#define eoCopyElite_h + +//----------------------------------------------------------------------------- + +// EO includes +#include // eoPop +#include // eoCopyElite + +/** + * eoCopyElite: Base class for elitist replacement algorithms. + * Merges the old population (first argument), with the new generation + * + * Its signature is exactly + * that of the selection base eoSelect, but its purpose is to merge the + * two populations into one (the second argument). + * Note that the algorithms assume that the second argument denotes the + * next generation. +*/ + +template class eoCopyElite: public eoBinaryFunctor&, eoPop&> +{}; + +/** +Straightforward elitism class, specify the number of individuals to copy +into new geneneration +*/ +template class eoElitism : public eoCopyElite +{ + public : + eoElitism(unsigned _howmany) : howmany(_howmany) {} + + void operator()(const eoPop& _pop, eoPop& offspring) + { + if (howmany == 0) + return; + + if (howmany > _pop.size()) + throw logical_error("Elite larger than population"); + + vector result; + _pop.nth_element(howmany, result); + + for (int i = 0; i < result.size(); ++i) + { + offspring.push_back(*result[i]); + } + } + + private : + unsigned howmany; +}; + +/** +No elite +*/ +template class eoNoElitism : public eoElitism +{ + public : + eoNoElitism() : eoElitism(0) {} +} + +/** +Very elitist class, copies entire population into next gen +*/ +template class eoPlus : public eoCopyElite +{ + public : + void operator()(const eoPop& _pop, eoPop& offspring) + { + offspring.reserve(offspring.size() + _pop.size()); + + for (int i = 0; i < _pop.size(); ++i) + { + offspring.push_back(*result[i]); + } + } + + private : + unsigned howmany; +}; + +//----------------------------------------------------------------------------- + +#endif diff --git a/eo/src/eoCounter.h b/eo/src/eoCounter.h new file mode 100644 index 000000000..ea82d3240 --- /dev/null +++ b/eo/src/eoCounter.h @@ -0,0 +1,219 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoCounter.h +// (c) Maarten Keijzer 2000 +/* + 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 + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoCounter_h +#define _eoCounter_h + +#include +#include +#include + +/** + Generic counter class that counts the number of times + a procedure is used. Add a procedure through its ctor and + use this class instead of it. + + It is derived from eoValueParam so you can add it to a monitor. +*/ +template +class eoProcedureCounter : public Procedure, public eoValueParam +{ + public: + + eoProcedureCounter(Procedure& _proc, std::string _name = "proc_counter") + : proc(_proc), eoValueParam(0, _name) {} + + /** Calls the embedded function and increments the counter + + Note for MSVC users, if this code does not compile, you are quite + likely trying to count a function that has a non-void return type. + Don't look at us, look at the MSVC builders. Code like "return void;" + is perfectly legal according to the ANSI standard, but the guys at + Microsoft didn't get to implementing it yet. + + We had two choices: assuming (and compiling ) code that returns void or code that returns non-void. + Given that in EO most functors return void, it was chosen to support void. + + But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite + capable of compiling return void; type of code. We'll try to change the signature then. + + You happy GNU (and other compiler) users will not have a problem with this.. + */ + typename Procedure::result_type operator()(void) + { + value()++; +#ifdef _MSC_VER + proc(); +#else + return proc(); +#endif + } + + private : + + Procedure& proc; +}; + +/** + Generic counter class that counts the number of times + a unary function is used. Add a unary function through its ctor and + use this class instead of it. + + It is derived from eoValueParam so you can add it to a monitor. + + Example: suppose you have an eoEvalFunc called myeval, to count the + number of evaluations, just define: + + eoUnaryFunctorCounter evalCounter(myeval); + + and use evalCounter now instead of myeval. +*/ + +template +class eoUnaryFunctorCounter : public UnaryFunctor, public eoValueParam +{ + public: + eoUnaryFunctorCounter(UnaryFunctor& _func, std::string _name = "uf_counter") + : func(_func), eoValueParam(0, _name) {} + + /** Calls the embedded function and increments the counter + + Note for MSVC users, if this code does not compile, you are quite + likely trying to count a function that has a non-void return type. + Don't look at us, look at the MSVC builders. Code like "return void;" + is perfectly legal according to the ANSI standard, but the guys at + Microsoft didn't get to implementing it yet. + + We had two choices: assuming (and compiling ) code that returns void or code that returns non-void. + Given that in EO most functors return void, it was chosen to support void. + + But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite + capable of compiling return void; type of code. We'll try to change the signature then. + + You happy GNU (and other compiler) users will not have a problem with this. + */ + typename UnaryFunctor::result_type operator() + (typename UnaryFunctor::first_argument_type _arg1) + { + value()++; +#ifdef _MSC_VER + func(_arg1); +#else + return func(_arg1); +#endif + } + + private : + + UnaryFunctor& func; +}; + +/** + Generic counter class that counts the number of times + a binary function is used. Add a binary function through its ctor and + use this class instead of it. + + It is derived from eoValueParam so you can add it to a monitor. + +*/ +template +class eoBinaryFunctorCounter : public BinaryFunctor, public eoValueParam +{ + public: + eoBinaryFunctorCounter(BinaryFunctor& _func, std::string _name = "proc_counter") + : func(_func), eoValueParam(0, _name) {} + + /** Calls the embedded function and increments the counter + + Note for MSVC users, if this code does not compile, you are quite + likely trying to count a function that has a non-void return type. + Don't look at us, look at the MSVC builders. Code like "return void;" + is perfectly legal according to the ANSI standard, but the guys at + Microsoft didn't get to implementing it yet. + + We had two choices: assuming (and compiling ) code that returns void or code that returns non-void. + Given that in EO most functors return void, it was chosen to support void. + + + But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite + capable of compiling return void; type of code. We'll try to change the signature then. + + You happy GNU (and other compiler) users will not have a problem with this. + */ + typename BinaryFunctor::result_type operator() + (typename BinaryFunctor::first_argument_type _arg1, + typename BinaryFunctor::second_argument_type _arg2) + { + value()++; +#ifdef _MSC_VER + func(_arg1, _arg2); +#else + return func(_arg1, _arg2); +#endif + } + + private : + + BinaryFunctor& func; +}; + +/** make_counter: overloaded function to make a counter out of a function + + how it works... + + by using the xxx_function_tag structure defined in eoFunctionBase, you + can easily create a counter from a general class (say eoEval), by + simply stating: + + eoEval& myCounted = make_counter(functor_category(myEval), myEval, store) + + @see eoFunctorBase, functor_category, eoFunctorStore + +*/ +template +eoProcedureCounter& make_counter(eoFunctorBase::procedure_tag, Procedure& _proc, eoFunctorStore& store, std::string _name = "proc_counter") +{ + eoProcedureCounter* result = new eoProcedureCounter(_proc, _name); + store.add(result); + return *result; +} + +template +eoUnaryFunctorCounter& make_counter(eoFunctorBase::unary_function_tag, UnaryFunctor& _proc, eoFunctorStore& store, std::string _name = "uf_counter") +{ + eoUnaryFunctorCounter* result = new eoUnaryFunctorCounter(_proc, _name); + store.add(result); + return *result; +} + +template +eoBinaryFunctorCounter& make_counter(eoFunctorBase::binary_function_tag, BinaryFunctor& _proc, eoFunctorStore& store, std::string _name = "uf_counter") +{ + eoBinaryFunctorCounter* result = new eoBinaryFunctorCounter(_proc, _name); + store.add(result); + return *result; +} + +#endif \ No newline at end of file diff --git a/eo/src/eoDetTournament.h b/eo/src/eoDetTournament.h index 5af8bb8e4..e4697b7cc 100644 --- a/eo/src/eoDetTournament.h +++ b/eo/src/eoDetTournament.h @@ -30,8 +30,10 @@ #include // #include // accumulate -#include "eoPopOps.h" // eoPop eoSelect MINFLOAT -#include "utils/selectors.h" + +#include +#include +#include //----------------------------------------------------------------------------- /** eoDetTournament: a selection method that selects ONE individual by @@ -51,15 +53,11 @@ template class eoDetTournament: public eoSelectOne } } + /// Perform deterministic tournament virtual const EOT& operator()(const eoPop& pop) { return deterministic_tournament(pop, Tsize); } - - /** Inherited from eoObject - @see eoObject - */ - string className() const {return "eoDetTournament";}; private: unsigned Tsize; diff --git a/eo/src/eoDetTournamentInserter.h b/eo/src/eoDetTournamentInserter.h index 845a7b381..95bd0b34a 100644 --- a/eo/src/eoDetTournamentInserter.h +++ b/eo/src/eoDetTournamentInserter.h @@ -57,7 +57,6 @@ public : EOT& eo = inverse_deterministic_tournament(pop(), t_size); eo = _eot; // overwrite loser of tournament - eo.invalidate(); // This line should probably be removed when all genetic operators do this themselves eval(eo); // Evaluate after insert return *this; } diff --git a/eo/src/eoEasyEA.h b/eo/src/eoEasyEA.h index ecd95c8e2..070452c0c 100644 --- a/eo/src/eoEasyEA.h +++ b/eo/src/eoEasyEA.h @@ -27,59 +27,139 @@ //----------------------------------------------------------------------------- -#include // eoPop -#include +#include +#include +#include +#include +#include +#include +#include +#include -/** EOEasyEA: +/** eoEasyEA: An easy-to-use evolutionary algorithm; you can use any chromosome, and any selection transformation, merging and evaluation algorithms; you can even change in runtime parameters of those sub-algorithms */ -template class eoEasyEA: public eoAlgo +template class eoEasyEA: public eoAlgo { public: - /// Constructor. - eoEasyEA(eoBinPopOp& _select, - eoMonPopOp& _transform, - eoBinPopOp& _replace, - eoEvalFunc& _evaluator, - eoTerm& _terminator) - :step(_select, _transform, _replace, _evaluator), - terminator( _terminator){}; - /// Constructor from an already created generation - eoEasyEA(eoGeneration& _gen, - eoTerm& _terminator): - step(_gen), - terminator( _terminator){}; - - /// Apply one generation of evolution to the population. - virtual void operator()(eoPop& pop) { - while ( terminator( pop ) ) { + /// Ctor taking a breed and merge. + eoEasyEA( + eoContinue& _continuator, + eoEvalFunc& _eval, + eoBreed& _breed, + eoReplacement& _replace + ) : continuator(_continuator), + eval(_eval), + selectTransform(0), + breed(_breed), + mergeReduce(0), + replace(_replace) + {} + + /// Ctor eoBreed, eoMerge and eoReduce. + eoEasyEA( + eoContinue& _continuator, + eoEvalFunc& _eval, + eoBreed& _breed, + eoMerge& _merge, + eoReduce& _reduce + ) : continuator(_continuator), + eval(_eval), + selectTransform(0), + breed(_breed), + mergeReduce(new eoMergeReduce(_merge, _reduce)), + replace(mergeReduce) + {} + + /// Ctor eoSelect, eoTransform, and eoReplacement + eoEasyEA( + eoContinue& _continuator, + eoEvalFunc& _eval, + eoSelect& _select, + eoTransform& _transform, + eoReplacement& _replace + ) : continuator(_continuator), + eval(_eval), + selectTransform(new eoSelectTransform(_select, _transform)), + breed(selectTransform), + mergeReduce(0), + replace(_replace) + {} + + /// Ctor eoSelect, eoTransform, eoMerge and eoReduce. + eoEasyEA( + eoContinue& _continuator, + eoEvalFunc& _eval, + eoSelect& _select, + eoTransform& _transform, + eoMerge& _merge, + eoReduce& _reduce + ) : continuator(_continuator), + eval(_eval), + selectTransform(new eoSelectTransform(_select, _transform)), + breed(*selectTransform), + mergeReduce(new eoMergeReduce(_merge, _reduce)), + replace(*mergeReduce) + {} + + + + + ~eoEasyEA() { delete selectTransform; delete mergeReduce; } + + /// Apply a few generation of evolution to the population. + virtual void operator()(eoPop& _pop) + { + eoPop offspring; + + while ( continuator( _pop ) ) + { try - { - step(pop); - } + { + breed(_pop, offspring); + + apply(eval, offspring); + + replace(_pop, offspring); + + if (offspring.size() < _pop.size()) + throw runtime_error("Population shrinking!"); + else if (offspring.size() > _pop.size()) + throw runtime_error("Population growing!"); + + _pop.swap(offspring); + + } catch (exception& e) - { - string s = e.what(); - s.append( " in eoEasyEA "); - throw runtime_error( s ); - } + { + string s = e.what(); + s.append( " in eoSelectTransformReduce "); + throw runtime_error( s ); + } } // while } - /// Class name. - string className() const { return "eoEasyEA"; } - private: - eoGeneration step; - eoTerm& terminator; + + /// dissallow copying cuz of pointer stuff + eoEasyEA(const eoEasyEA&); + /// dissallow copying cuz of pointer stuff + const eoEasyEA& operator=(const eoEasyEA&); + + eoContinue& continuator; + eoEvalFunc& eval; + eoSelectTransform* selectTransform; + eoBreed& breed; + eoMergeReduce* mergeReduce; + eoReplacement& replace; }; //----------------------------------------------------------------------------- -#endif eoEasyEA_h +#endif eoSelectTransformReduce_h diff --git a/eo/src/eoEvalFunc.h b/eo/src/eoEvalFunc.h index 0f90532b5..0b1744266 100644 --- a/eo/src/eoEvalFunc.h +++ b/eo/src/eoEvalFunc.h @@ -25,6 +25,8 @@ #ifndef eoEvalFunc_H #define eoEvalFunc_H +#include + /** Evaluate: takes one EO and sets its "fitness" property * returning this fitness also. That is why EOT is passed by * non-const reference: it must be altered within evaluate.\\ @@ -35,25 +37,11 @@ on it. If you subclass this abstract class, and use it to evaluate an EO, the requirements on this EO will depend on the evaluator. */ -template struct eoEvalFunc { -#ifdef _MSC_VER - typedef EOT::Fitness EOFitT; -#else +template class eoEvalFunc : public eoUnaryFunctor +{ + public : typedef typename EOT::Fitness EOFitT; -#endif - - /// Effectively applies the evaluation function to an EO - virtual void operator() ( EOT & _eo ) const = 0; - - template - void range(It begin, It end) const - { - for (;begin != end; ++begin) - { - operator()(*begin); - } - } }; -#endif +#endif \ No newline at end of file diff --git a/eo/src/eoEvalFuncPtr.h b/eo/src/eoEvalFuncPtr.h index 04cd6de83..8c28a721d 100644 --- a/eo/src/eoEvalFuncPtr.h +++ b/eo/src/eoEvalFuncPtr.h @@ -35,7 +35,7 @@ * function class. That way, old style C or C++ functions can be adapted to EO * function classes. */ -template< class EOT > +template< class EOT, class FitT = typename EOT::Fitness, class FunctionArg = const EOT& > struct eoEvalFuncPtr: public eoEvalFunc { /** Applies the function to the chromosome and sets the fitness of the @@ -44,16 +44,18 @@ struct eoEvalFuncPtr: public eoEvalFunc { argument and returns the fitness @return the evaluated fitness for that object. */ - eoEvalFuncPtr( EOFitT (* _eval)( const EOT& ) ) + eoEvalFuncPtr( FitT (* _eval)( FunctionArg ) ) : eoEvalFunc(), evalFunc( _eval ) {}; /// Effectively applies the evaluation function to an EO - virtual void operator() ( EOT & _eo ) const { - _eo.fitness((*evalFunc)( _eo )); + virtual void operator() ( EOT & _eo ) + { + if (_eo.invalid()) + _eo.fitness((*evalFunc)( _eo )); }; private: - EOFitT (* evalFunc )( const EOT& ); + FitT (* evalFunc )( FunctionArg ); }; #endif diff --git a/eo/src/eoEvolutionStrategy.h b/eo/src/eoEvolutionStrategy.h new file mode 100644 index 000000000..08309deae --- /dev/null +++ b/eo/src/eoEvolutionStrategy.h @@ -0,0 +1,87 @@ +// -*- 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; + eoSelectRandom randomSelect; + eoSelectPerc selectPerc; + eoInplaceTransform2 transform; + + /// easyEA is contained rather than a base because of member initialization order! + eoEasyEA easyEA; +}; + +//----------------------------------------------------------------------------- + +#endif eoSelectTransformReduce_h + diff --git a/eo/src/eoFitContinue.h b/eo/src/eoFitContinue.h new file mode 100644 index 000000000..42d7ae5e1 --- /dev/null +++ b/eo/src/eoFitContinue.h @@ -0,0 +1,58 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoFitContinue.h +// (c) Maarten Keijzer, GeNeura Team, 1999, 2000 +/* + 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 _eoFitContinue_h +#define _eoFitContinue_h + +#include + +/** +Fitness continuation: + + Continues until the maximum fitness level is reached. +*/ +template< class EOT> +class eoFitContinue: public eoContinue { +public: + + /// Define Fitness + typedef typename EOT::Fitness FitnessType; + + /// Ctor + eoFitContinue( const FitnessType _maximum) + : eoContinue (), maximum( _maximum ) {}; + + /** Returns false when a fitness criterium is + * reached. Assumes pop is not sorted! */ + virtual bool operator() ( const eoPop& _pop ) + { + return (_pop.nth_element_fitness(0) < maximum); + } + +private: + FitnessType maximum; +}; + +#endif + diff --git a/eo/src/eoFixedLength.h b/eo/src/eoFixedLength.h index da570e7d3..17073952a 100644 --- a/eo/src/eoFixedLength.h +++ b/eo/src/eoFixedLength.h @@ -28,7 +28,7 @@ #define _eoFixedLength_h #include - +#include /** Base class for fixed length chromosomes, just derives from EO and vector and @@ -40,7 +40,11 @@ class eoFixedLength : public EO, public std::vector { public : - typedef GeneType Type; + typedef GeneType AtomType; + typedef std::vector ContainerType; + + eoFixedLength(unsigned size = 0, GeneType value = GeneType()) : EO(), std::vector(size, value) + {} /// to avoid conflicts between EO::operator< and vector::operator< bool operator<(const eoFixedLength& _eo) const @@ -71,7 +75,11 @@ class eoFixedLength : public EO, public std::vector unsigned i; for (i = 0; i < sz; ++i) - is >> operator[](i); + { + AtomType atom; + is >> atom; + operator[](i) = atom; + } } }; diff --git a/eo/src/eoFunctor.h b/eo/src/eoFunctor.h new file mode 100644 index 000000000..41125f2f1 --- /dev/null +++ b/eo/src/eoFunctor.h @@ -0,0 +1,144 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoFunctor.h +// (c) Maarten Keijzer 2000 +/* + 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 + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoFunctor_h +#define _eoFunctor_h + +/// Base class for functors to get a nice hierarchy diagram +class eoFunctorBase +{ +public : + virtual ~eoFunctorBase() {} + + /// tag to identify a procedure in compile time function selection @see functor_category + struct procedure_tag {}; + /// tag to identify a unary function in compile time function selection @see functor_category + struct unary_function_tag {}; + /// tag to identify a binary function in compile time function selection @see functor_category + struct binary_function_tag {}; +}; + +/** + Basic Procedure. Derive from this class when defining + any procedure. It defines a result_type that can be used + to determine the return type + Argument and result types can be any type including void for + result_type +**/ +template +class eoProcedure : public eoFunctorBase +{ +public : + + /// virtual dtor here so there is no need to define it in derived classes + virtual ~eoProcedure() {} + + typedef R result_type; + + /// The pure virtual function that needs to be implemented by the subclass + virtual R operator()() = 0; +}; + +/** + Overloaded function that can help in the compile time detection + of the type of functor we are dealing with + + @see eoCounter, make_counter +*/ +template +eoFunctorBase::procedure_tag functor_category(const eoProcedure&) +{ + return eoFunctorBase::procedure_tag(); +} + +/** + Basic Unary Functor. Derive from this class when defining + any unary function. First template argument is result_type, second + is first_argument_type. + Argument and result types can be any type including void for + result_type +**/ +template +class eoUnaryFunctor : public eoFunctorBase +{ +public : + + /// virtual dtor here so there is no need to define it in derived classes + virtual ~eoUnaryFunctor() {} + + typedef R result_type; + typedef A1 first_argument_type; + + /// The pure virtual function that needs to be implemented by the subclass + virtual R operator()(A1) = 0; +}; + +/** + Overloaded function that can help in the compile time detection + of the type of functor we are dealing with + @see eoCounter, make_counter +*/ +template +eoFunctorBase::unary_function_tag functor_category(const eoUnaryFunctor&) +{ + return eoFunctorBase::unary_function_tag(); +} + + +/** + Basic Binary Functor. Derive from this class when defining + any binary function. First template argument is result_type, second + is first_argument_type, third is second_argument_type. + Argument and result types can be any type including void for + result_type +**/ +template +class eoBinaryFunctor : public eoFunctorBase +{ +public : + /// virtual dtor here so there is no need to define it in derived classes + virtual ~eoBinaryFunctor() {} + + typedef R result_type; + typedef A1 first_argument_type; + typedef A2 second_argument_type; + + /// The pure virtual function that needs to be implemented by the subclass + virtual R operator()(A1, A2) = 0; +}; + +/** + Overloaded function that can help in the compile time detection + of the type of functor we are dealing with + @see eoCounter, make_counter +*/ +template +eoFunctorBase::binary_function_tag functor_category(const eoBinaryFunctor&) +{ + return eoFunctorBase::binary_function_tag(); +} + + +#endif \ No newline at end of file diff --git a/eo/src/eoFunctorStore.cpp b/eo/src/eoFunctorStore.cpp new file mode 100644 index 000000000..4c118236c --- /dev/null +++ b/eo/src/eoFunctorStore.cpp @@ -0,0 +1,11 @@ +#include +#include + +/// clears the memory +eoFunctorStore::~eoFunctorStore() +{ + for (int i = 0; i < vec.size(); ++i) + { + delete vec[i]; + } +} diff --git a/eo/src/eoFunctorStore.h b/eo/src/eoFunctorStore.h new file mode 100644 index 000000000..5f591e99f --- /dev/null +++ b/eo/src/eoFunctorStore.h @@ -0,0 +1,60 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoFunctorStore.h +// (c) Maarten Keijzer 2000, GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoFunctorStore_h +#define _eoFunctorStore_h + +#include + +class eoFunctorBase; + +/** +eoFunctorStore is a class that stores functors that are allocated on the +heap. This class can be used in factories to store allocated memory for +dynamically created functors. +*/ +class eoFunctorStore +{ + public : + + eoFunctorStore() {} + + ~eoFunctorStore(); + + /// Add an eoFunctorBase to the store + void add(eoFunctorBase* r) { vec.push_back(r); } + + private : + + /// no copying allowed + eoFunctorStore(const eoFunctorStore&); + + /// no copying allowed + eoFunctorStore operator=(const eoFunctorStore&); + std::vector vec; +}; + +#endif \ No newline at end of file diff --git a/eo/src/eoGOpBreeder.h b/eo/src/eoGOpBreeder.h index e48037404..913d4a5ff 100644 --- a/eo/src/eoGOpBreeder.h +++ b/eo/src/eoGOpBreeder.h @@ -12,13 +12,14 @@ * For every operator there is a rated to be applyed. * *****************************************************************************/ -#include "eoPopOps.h" -#include "eoGOpSelector.h" -#include "eoIndiSelector.h" -#include "eoBackInserter.h" +#include +#include +#include +#include +#include template -class eoGOpBreeder: public eoMonPopOp +class eoGOpBreeder: public eoUnaryFunctor&> { public: /// Default constructor. @@ -27,9 +28,6 @@ class eoGOpBreeder: public eoMonPopOp : opSel( _opSel ), selector(_selector) {} - /// Destructor. - virtual ~eoGOpBreeder() {} - /** * Enlarges the population. * @param pop The population to be transformed. diff --git a/eo/src/eoGOpSelector.h b/eo/src/eoGOpSelector.h index 06dafc96f..c47cadd20 100644 --- a/eo/src/eoGOpSelector.h +++ b/eo/src/eoGOpSelector.h @@ -124,7 +124,7 @@ inline eoOpSelector::ID eoGOpSelector::addOp( eoOp& _op, // and keep it on a list to delete them afterwards // will use auto_ptr when they're readily available - switch(_op.getType()) + switch(_op.getType()) { case eoOp::unary : op= new eoWrappedMonOp(static_cast&>(_op)); diff --git a/eo/src/eoGenContinue.h b/eo/src/eoGenContinue.h new file mode 100644 index 000000000..a546702d0 --- /dev/null +++ b/eo/src/eoGenContinue.h @@ -0,0 +1,78 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoGenContinue.h +// (c) GeNeura Team, 1999 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef _eoGenContinue_h +#define _eoGenContinue_h + +#include + +/** + Generational continuator: continues until a number of generations is reached +*/ +template< class EOT> +class eoGenContinue: public eoContinue +{ +public: + + /// Ctor for setting a + eoGenContinue( unsigned _totalGens) + : repTotalGenerations( _totalGens ), + thisGenerationPlaceHolder(0), + thisGeneration(thisGenerationPlaceHolder){}; + + /// Ctor for enabling the save/load the no. of generations counted + eoGenContinue( unsigned _totalGens, unsigned& _currentGen) + : repTotalGenerations( _totalGens ), + thisGenerationPlaceHolder(0), + thisGeneration(_currentGen){}; + + /** Returns false when a certain number of generations is + * reached */ + virtual bool operator() ( const eoPop& _vEO ) { + thisGeneration++; + // cout << " [" << thisGeneration << "] "; + return (thisGeneration < repTotalGenerations) ; // for the postincrement + } + + /** Sets the number of generations to reach + and sets the current generation to 0 (the begin)*/ + virtual void totalGenerations( unsigned _tg ) { + repTotalGenerations = _tg; + thisGeneration = 0; + }; + + /** Returns the number of generations to reach*/ + virtual unsigned totalGenerations( ) + { + return repTotalGenerations; + }; + +private: + unsigned repTotalGenerations; + unsigned thisGenerationPlaceHolder; + unsigned& thisGeneration; +}; + +#endif + diff --git a/eo/src/eoIndiSelector.h b/eo/src/eoIndiSelector.h index 26ffe476e..0d96514d0 100644 --- a/eo/src/eoIndiSelector.h +++ b/eo/src/eoIndiSelector.h @@ -30,11 +30,18 @@ #ifndef eoIndiSelector_h #define eoIndiSelector_h +#include + /** - * eoIndividualSelector: This class defines the interface + * eoIndividualSelector: This class defines the interface. This + * interface is used by the eoGeneralOp to get new individuals + * from a pop, a subpop or a remote pop + * for convenience when implementing an nary operator a size() and operator[] + * need to be implemented. */ + template -class eoIndiSelector +class eoIndiSelector : public eoProcedure { public : @@ -51,48 +58,37 @@ public : return the specified individual, the size_t argument should be between 0 and eoIndiSelector::size() */ virtual const EOT& operator[](size_t i) const = 0; - - /** - Select an individual, maybe from an underlying population (see eoPopIndiSelector) - */ - virtual const EOT& operator()(void) = 0; - - /// default implementation just calls operator() a couple of times - /// this can be overridden in favour of a more efficient implementation - virtual vector select(size_t _how_many) - { vector result(_how_many); - - for (unsigned i = 0; i < _how_many; ++i) - { - result[i] = &operator()(); - } - - return result; - } }; + +#include + /** - * eoPopIndiSelector: Intermediate class for dispensing populations + * eoSelectOneAdaptor: Adaptor class for dispensing individuals. + + It produces the eoIndiSelector interface and an eoSelectOne implementation + This class can then be used for general operators + various useful things can be done with this class: you can specify how many of the population can ever be dispensed to the operators, but you can also specify a preference to the first guy being dispensed. This is useful if you want to perform the operator on a specific individual. + + @see eoSelectOne, eoIndiSelector */ template -class eoPopIndiSelector : public eoIndiSelector +class eoSelectOneIndiSelector : public eoIndiSelector { public : - eoPopIndiSelector(void) : eoIndiSelector(), pop(0), last(0), firstChoice(-1), secondChoice(-1) {} - - virtual ~eoPopIndiSelector(void) {} - + eoSelectOneIndiSelector(eoSelectOne& _select) : pop(0), last(0), firstChoice(-1), secondChoice(-1), select(_select) {} + struct eoUnitializedException{}; /** Initialization function, binds the population to the selector, can also be used to specify an optional end */ - eoPopIndiSelector& bind(const eoPop& _pop, int _end = -1) + eoSelectOneIndiSelector& bind(const eoPop& _pop, int _end = -1) { pop = &_pop; last = _end; @@ -101,6 +97,8 @@ class eoPopIndiSelector : public eoIndiSelector { last = pop->size(); } + + select.setup(*pop); return *this; } @@ -108,7 +106,7 @@ class eoPopIndiSelector : public eoIndiSelector /** Bias function to bias the selection function to select specific individuals first before applying a selection algorithm defined in derived classes */ - eoPopIndiSelector& bias(int _first, int _second = -1) + eoSelectOneIndiSelector& bias(int _first, int _second = -1) { firstChoice = _first; secondChoice = _second; @@ -122,17 +120,16 @@ class eoPopIndiSelector : public eoIndiSelector eoPop::const_iterator begin(void) const { valid(); return pop->begin(); } eoPop::const_iterator end(void) const { valid(); return pop->end(); } - /// operator() does the work. Note that it is not virtual. It calls do_select that needs to be implemented by the derived classes const EOT& operator()(void) { valid(); - if (firstChoice < 0 || firstChoice >= (int) size()) + if (firstChoice < 0 || firstChoice >= last) { // see if we have a second choice - if (secondChoice < 0 || secondChoice >= (int) size()) + if (secondChoice < 0 || secondChoice >= last) { - return do_select(); // let the child figure out what to do + return select(*pop); // let the embedded selector figure out what to do } const EOT& result = pop->operator[](secondChoice); @@ -145,12 +142,6 @@ class eoPopIndiSelector : public eoIndiSelector return result; } - /** - do_select, abstract member re-implemented by derived classes - This function will get called by operator() when it ran out of choices - */ - virtual const EOT& do_select(void) = 0; - private : void valid(void) const @@ -163,6 +154,7 @@ class eoPopIndiSelector : public eoIndiSelector int last; int firstChoice; int secondChoice; + eoSelectOne& select; }; #endif diff --git a/eo/src/eoInit.h b/eo/src/eoInit.h index 48568a13b..b6372299d 100644 --- a/eo/src/eoInit.h +++ b/eo/src/eoInit.h @@ -27,17 +27,91 @@ #ifndef _eoInit_H #define _eoInit_H +#include + /** - Base class for Initialization of chromosomes, used in a population - contructor + Base (name) class for Initialization of chromosomes, used in a population + contructor. It is derived from eoMonOp, so it can be used + inside the algorithm as well. @see eoPop */ + template -class eoInit +class eoInit : public eoUnaryFunctor +{}; + +/** + Initializor for fixed length representations with a single type +*/ +template +class eoInitFixedLength: public eoInit { -public : - virtual EOT operator()(void) = 0; + public: + eoInitFixedLength(unsigned _howmany, Gen _generator = Gen()) + : howmany(_howmany), generator(_generator) {} + + void operator()(EOT& chrom) + { + chrom.resize(howmany); + generate(chrom.begin(), chrom.end(), generator); + chrom.invalidate(); + } + + private : + unsigned howmany; + Gen generator; +}; + +/** + Initializor for variable length representations with a single type +*/ +template +class eoInitVariableLength: public eoInit +{ + public: + eoInitVariableLength(unsigned _minSize, unsigned _maxSize, Gen _generator = Gen()) + : offset(_minSize), extent(_maxSize - _minSize), generator(_generator) + { + if (_minSize >= _maxSize) + throw logical_error("eoInitVariableLength: minSize larger or equal to maxSize"); + } + + void operator()(EOT& chrom) + { + unsigned howmany = offset + rng.random(extent); + chrom.resize(howmany); + generate(chrom.begin(), chrom.end(), generator); + chrom.invalidate(); + } + + private : + unsigned offset; + unsigned extent; + Gen generator; +}; + + +/** + eoInitAdaptor changes the place in the hierarchy + from eoInit to eoMonOp. This is mainly a type conversion, + nothing else + . + @see eoInit, eoMonOp +*/ +template +class eoInitAdaptor : public eoMonOp +{ + public : + eoInitAdaptor(eoInit& _init) : init(_init) {} + + void operator()(EOT& _eot) + { + init(_eot); + } + private : + + eoInit& init; }; #endif \ No newline at end of file diff --git a/eo/src/eoInplaceTransform.h b/eo/src/eoInplaceTransform.h new file mode 100644 index 000000000..f1462408c --- /dev/null +++ b/eo/src/eoInplaceTransform.h @@ -0,0 +1,193 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoInplaceTransform.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef eoInplaceTransform_h +#define eoInplaceTransform_h + +//----------------------------------------------------------------------------- + +#include // vector +#include +#include // eoOp, eoMonOp, eoBinOp +#include // eoPop +#include // eoOpSelector +#include +#include +#include + +/***************************************************************************** + * eoInplaceTransform1: transforms a population using genetic operators. * + * It does it in an SGA like manner + *****************************************************************************/ +template class eoInplaceTransform1 : public eoTransform +{ + public: + + /// Default constructor. + eoInplaceTransform1( eoOpSelector& _opSel): opSel( _opSel ), select(defaultSelect) {} + eoInplaceTransform1( eoOpSelector& _opSel, eoSelectOne& _select) + : opSel(_opSel), select(_select) {} + /** + * Transforms a population. + * @param pop The population to be transformed. + */ + void operator()(eoPop& pop) + { + // copy the guys in a newpop + // because otherwise eoSelectRandom might select freshly created individuals + eoPop newpop; + newpop.reserve(pop.size()); + + // Set up general op helper classes + eoSelectOneIndiSelector inplace(select); + eoBackInserter inserter; + + // set up selection routine + select.setup(pop); + + for (unsigned i = 0; i < pop.size(); i++) + { + eoOp* op = opSel.Op(); + + switch (op->getType()) + { + case eoOp::unary: + { + eoMonOp* monop = static_cast* >(op); + newpop.push_back(pop[i]); + (*monop)( newpop.back() ); + break; + } + case eoOp::binary: + { + eoBinOp* binop = static_cast* >(op); + newpop.push_back(pop[i]); + (*binop)(newpop[i], select(pop)); + break; + } + case eoOp::quadratic: + { + + eoQuadraticOp* Qop = static_cast* >(op); + + newpop.push_back(pop[i]); + Chrom& indy1 = newpop.back(); + + if (++i == pop.size()) + newpop.push_back(select(pop)); + else + newpop.push_back(pop[i]); + + (*Qop)(indy1, newpop.back() ); + break; + } + case eoOp::general : + { + eoGeneralOp* Gop = static_cast* >(op); + + inplace.bind(pop); + inplace.bias(i,i + 1); + + inserter.bind(newpop); + unsigned orgsize = newpop.size(); + (*Gop)(inplace, inserter); + unsigned diff = newpop.size() - orgsize; + i = i + (diff-1); + break; + } + } + pop.swap(newpop); // overwrite existing pop + } + }; + + private: + eoOpSelector& opSel; + eoSelectRandom defaultSelect; + eoSelectOne& select; + +}; + +#include + +/***************************************************************************** + * eoInplaceTransform2: transforms a population using general genetic operators. * + * It does it in an SGA like manner + *****************************************************************************/ +template class eoInplaceTransform2 : public eoTransform +{ + public: + + /// Default constructor. + eoInplaceTransform2( eoGOpSelector& _opSel): opSel( _opSel ), select(defaultSelect) {} + eoInplaceTransform2( eoGOpSelector& _opSel, eoSelectOne& _select) + : opSel(_opSel), select(_select) {} + /** + * Transforms a population. + * @param pop The population to be transformed. + */ + void operator()(eoPop& pop) + { + // copy the guys in a newpop + // because otherwise eoSelectRandom might select freshly created individuals + eoPop newpop; + newpop.reserve(pop.size()); + + // Set up general op helper classes + eoSelectOneIndiSelector inplace(select); + eoBackInserter inserter; + + // set up selection routine + select.setup(pop); + + for (unsigned i = 0; i < pop.size(); i++) + { + eoGeneralOp& Gop = opSel.selectOp(); + + inplace.bind(pop); + inplace.bias(i,i + 1); + + inserter.bind(newpop); + unsigned orgsize = newpop.size(); + Gop(inplace, inserter); + + // see how many have been inserted and add that to i (minus one ofcourse) + unsigned diff = newpop.size() - orgsize; + i = i + (diff-1); + } + + pop.swap(newpop); // overwrite existing pop + } + + private: + eoGOpSelector& opSel; + eoSelectRandom defaultSelect; + eoSelectOne& select; + +}; + + +//----------------------------------------------------------------------------- + +#endif eoBreeder_h + diff --git a/eo/src/eoInserter.h b/eo/src/eoInserter.h index d2758bea2..e49057cf6 100644 --- a/eo/src/eoInserter.h +++ b/eo/src/eoInserter.h @@ -30,23 +30,20 @@ #ifndef eoInserter_h #define eoInserter_h -#include "eoPop.h" -/** +#include +#include + + /** * eoInserter: Interface class that enables an operator to insert - new individuals into the (intermediate) population. + new individuals into the (intermediate) population for example. */ template -class eoInserter +class eoInserter : public eoUnaryFunctor&, const EOT&> { public : virtual ~eoInserter() {} struct eoInserterException{}; - - /** - insert argument somewhere (quite likely a population) - */ - virtual eoInserter& operator()(const EOT&) = 0; // can throw an eoInserterException }; /** diff --git a/eo/src/eoMerge.h b/eo/src/eoMerge.h index 82cf0768e..2a0c30b83 100644 --- a/eo/src/eoMerge.h +++ b/eo/src/eoMerge.h @@ -2,7 +2,7 @@ //----------------------------------------------------------------------------- // eoMerge.h -// Base class for population-merging classes +// Base class for elitist-merging classes // (c) GeNeura Team, 1998 /* This library is free software; you can redistribute it and/or @@ -28,88 +28,85 @@ //----------------------------------------------------------------------------- -#include +#include // EO includes #include // eoPop -#include // eoMerge +#include // eoMerge /** - * eoMerge: Base class for replacement algorithms - */ + * eoMerge: Base class for elitist replacement algorithms. + * Merges the old population (first argument), with the new generation + * + * Its signature is exactly + * that of the selection base eoSelect, but its purpose is to merge the + * two populations into one (the second argument). + * Note that the algorithms assume that the second argument denotes the + * next generation. +*/ -template class eoMerge: public eoBinPopOp +template class eoMerge: public eoBinaryFunctor&, eoPop&> +{}; + +/** +Straightforward elitism class, specify the number of individuals to copy +into new geneneration +*/ +template class eoElitism : public eoMerge { - public: - /// (Default) Constructor. - eoMerge(const float& _rate = 1.0): eoBinPopOp(), repRate( _rate ) {} + public : + eoElitism(unsigned _howmany) : howmany(_howmany) {} - /// Ctor from istream - eoMerge( istream& _is): eoBinPopOp() { readFrom( _is ); }; - - /** - * Creates a new population based on breeders and original populations. - * @param breeders The population of breeders. Should be sorted to work correctly - * @param pop The original population. - */ - void operator()( eoPop& _breeders, eoPop& _pop) - { - unsigned target = static_cast(_pop.size() * rate()); - - _pop.swap(_breeders); - - if (target < _pop.size()) - { - partial_sort(_pop.begin(), _pop.begin() + target, _pop.end(), - greater()); - _pop.erase(_pop.begin() + target, _pop.end()); - } - else - { - target = min(target - _pop.size(), _breeders.size()); - partial_sort(_breeders.begin(), _breeders.begin() + target, - _breeders.end(), greater()); - copy(_breeders.begin(), _breeders.begin() + target, - back_insert_iterator >(_pop)); - } - }; + void operator()(const eoPop& _pop, eoPop& offspring) + { + if (howmany == 0) + return; - /** @name Methods from eoObject */ - //@{ - /** - * Read object. The EOT class must have a ctor from a stream; - in this case, a strstream is used. - * @param _is A istream. - - */ - virtual void readFrom(istream& _is) { - _is >> repRate; - } - - /** - * Write object. Prints relevant parameters to standard output - * @param _os A ostream. In this case, prints the population to - standard output. The EOT class must hav standard output with cout, - but since it should be an eoObject anyways, it's no big deal. - */ - virtual void printOn(ostream& _os) const { - _os << repRate; - }; + if (howmany > _pop.size()) + throw std::logic_error("Elite larger than population"); - /** Inherited from eoObject. Returns the class name. - @see eoObject - */ - virtual string className() const {return "eoMerge";}; - //@} + vector result; + _pop.nth_element(howmany, result); - protected: - float rate() { return repRate;}; + for (int i = 0; i < result.size(); ++i) + { + offspring.push_back(*result[i]); + } + } - private: - float repRate; + private : + unsigned howmany; +}; +/** +No elite +*/ +template class eoNoElitism : public eoElitism +{ + public : + eoNoElitism() : eoElitism(0) {} +}; + +/** +Very elitist class, copies entire population into next gen +*/ +template class eoPlus : public eoMerge +{ + public : + void operator()(const eoPop& _pop, eoPop& offspring) + { + offspring.reserve(offspring.size() + _pop.size()); + + for (int i = 0; i < _pop.size(); ++i) + { + offspring.push_back(_pop[i]); + } + } + + private : + unsigned howmany; }; //----------------------------------------------------------------------------- -#endif eoInsertion_h +#endif diff --git a/eo/src/eoObject.h b/eo/src/eoObject.h index b3630de76..544e82517 100644 --- a/eo/src/eoObject.h +++ b/eo/src/eoObject.h @@ -39,9 +39,11 @@ using namespace std; // eoObject //----------------------------------------------------------------------------- /** -This is the base class for the whole hierarchy; an eoObject defines -basically an interface for the whole hierarchy: each object should -know its name (#className#). Previously, this object defined a print and read +eoObject used to be the base class for the whole hierarchy, but this has +changed. eoObject is used to define a name (#className#) +that is used when loading or saving the state. + +Previously, this object also defined a print and read interface, but it´s been moved to eoPrintable and eoPersistent. It is recommended that you only derive from eoObject in concrete classes. @@ -49,7 +51,7 @@ Some parts of EO do not implement this yet, but that will change in the future. eoObject, together with eoPersistent and eoPrintable provide a simple persistence framework that is only needed when the classes have state that changes at runtime. - @see eoPersistent eoPrintable + @see eoPersistent eoPrintable, eoState */ class eoObject diff --git a/eo/src/eoOp.h b/eo/src/eoOp.h index 6d4b147c3..d9f0bffff 100644 --- a/eo/src/eoOp.h +++ b/eo/src/eoOp.h @@ -26,6 +26,7 @@ #include #include +#include /** \defgroup operators @@ -47,13 +48,13 @@ What is a genetic algorithm without genetic operators? There is a genetic operat * instantiate them should be an eoObject, but in any case, they are * type-specific; each kind of evolvable object can have its own operators */ - template -class eoOp: public eoObject, public eoPrintable { +class eoOp +{ public: //@{ - enum OpType { unary = 0, binary = 1, quadratic = 2, general = 3}; + enum OpType { init = 0, unary = 1, binary = 2, quadratic = 3, general = 4}; /// /// Ctor @@ -70,147 +71,48 @@ public: /// getType: number of operands it takes and individuals it produces OpType getType() const {return opType;}; - /** @name Methods from eoObject */ - - //@{ - - /** - * Write object. It's called printOn since it prints the object _on_ a stream. - * @param _os A ostream. - */ - virtual void printOn(ostream& _os) const { - _os << className(); - // _os << arity; - }; - - /** Inherited from eoObject - @see eoObject - */ - - virtual string className() const {return "eoOp";}; - //@} - private: /// OpType is the type of the operator: how many operands it takes and how many it produces - OpType opType; }; - - -/** Binary genetic operator: subclasses eoOp, and defines basically the - * operator() with two operands - */ - -template - -class eoBinOp: public eoOp { +/** eoMonOp is the monary operator: genetic operator that takes only one EO */ +template +class eoMonOp: public eoOp, public eoUnaryFunctor +{ public: /// Ctor - eoBinOp() - :eoOp( binary ) {}; - - /// Copy Ctor - eoBinOp( const eoBinOp& _ebop ) - : eoOp( _ebop ){}; - - /// Dtor - ~eoBinOp () {}; - - /** applies operator, to the object. Modifies only the first operand. - */ - virtual void operator()( EOType& _eo1, const EOType& _eo2 ) const = 0; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoBinOp";}; - - //@} + eoMonOp() + : eoOp( eoOp::unary ) {}; }; +/** Binary genetic operator: subclasses eoOp, and defines basically the + * operator() with two operands, only the first one can be modified + */ +template +class eoBinOp: public eoOp, public eoBinaryFunctor +{ +public: + /// Ctor + eoBinOp() + :eoOp( eoOp::binary ) {}; +}; /** Quadratic genetic operator: subclasses eoOp, and defines basically the - operator() with two operands + operator() with two operands, both can be modified. */ template - -class eoQuadraticOp: public eoOp { +class eoQuadraticOp: public eoOp, public eoBinaryFunctor { public: /// Ctor eoQuadraticOp() :eoOp( eoOp::quadratic ) {}; - - /// Copy Ctor - eoQuadraticOp( const eoQuadraticOp& _ebop ) - : eoOp( _ebop ){}; - - /// Dtor - ~eoQuadraticOp() {}; - - /** applies operator, to the object. Modifies both operands. - */ - virtual void operator()( EOType& _eo1, EOType& _eo2 ) const = 0; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject - */ - - //@{ - /** Inherited from eoObject - @see eoObject - - */ - virtual string className() const {return "eoBinOp";}; - - //@} }; - -/** eoMonOp is the monary operator: genetic operator that takes only one EO */ - -template - -class eoMonOp: public eoOp { -public: - /// Ctor - eoMonOp( ) - : eoOp( eoOp::unary ) {}; - - /// Copy Ctor - eoMonOp( const eoMonOp& _emop ) - : eoOp( _emop ){}; - - /// Dtor - ~eoMonOp() {}; - - /** applies randomly operator, to the object. If arity is more than 1, - * keeps a copy of the operand in a cache. - */ - virtual void operator()( EOType& _eo1) const = 0; - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject - */ - - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoMonOp";}; - //@} -}; - - - // some forward declarations template @@ -226,30 +128,22 @@ class eoInserter; /** * eGeneralOp: General genetic operator; for objects used to transform sets * of EOs. Nary ("orgy") operators should be derived from this class - */ -template - -class eoGeneralOp: public eoOp -{ -public: - /// Ctor that honors its superclass - eoGeneralOp(): eoOp( eoOp::general ) {} - - /// Virtual dtor - virtual ~eoGeneralOp () {} - - /** Method that really does the stuff. Applies the genetic operator + Derived from eoBinaryFunctor + 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. - */ + */ - virtual void operator()( eoIndiSelector& _in, - eoInserter& _out) const = 0; +template - virtual string className() const {return "eoGeneralOp";} +class eoGeneralOp: public eoOp, public eoBinaryFunctor&, eoInserter&> +{ +public: + /// Ctor that honors its superclass + eoGeneralOp(): eoOp( eoOp::general ) {} }; #endif diff --git a/eo/src/eoPop.h b/eo/src/eoPop.h index e5abfc83e..72a214a71 100644 --- a/eo/src/eoPop.h +++ b/eo/src/eoPop.h @@ -29,9 +29,9 @@ #include // EO includes -#include -#include +#include // for eoInit #include +#include /** Subpopulation: it is used to move parts of population from one algorithm to another and one population to another. It is safer @@ -39,68 +39,42 @@ to declare it as a separate object. I have no idea if a population can be some other thing that a vector, but if somebody thinks of it, this concrete implementation will be moved to "generic" and an abstract Population interface will be provided. + It can be instantiated with anything, provided that it accepts a "size" and a random generator in the ctor. This happens to all the eo1d chromosomes declared so far. EOT must also have a copy ctor, since temporaries are created and copied to the population. + +It can also be instantiated with a "size" and an eoInit derived object. +This object must supply a full chromosome (or something the ctor of the EO +will accept). + @author Geneura Team @version 0.0 */ template -class eoPop: public vector, public eoObject, public eoPersistent { - -/// Type is the type of each gene in the chromosome -#ifdef _MSC_VER - typedef EOT::Type Type; -#else - typedef typename EOT::Type Type; -#endif +class eoPop: public vector, public eoObject, public eoPersistent +{ public: - /** Protected ctor. This is intended to avoid creation of void populations, except - from sibling classes + typedef typename EOT::Fitness Fitness; + /** Default ctor. Creates empty pop */ - eoPop() :vector() {}; + eoPop() : vector(), eoObject(), eoPersistent() {}; - - /** Ctor for fixed-size chromosomes, with variable content + /** Ctor for the initialization of chromosomes + @param _popSize total population size - @param _eoSize chromosome size. EOT should accept a fixed-size ctor - @param _geneRdn random number generator for each of the genes + @param _chromRnd Initialization routine, produces EO's, needs to be an eoInit */ - eoPop( unsigned _popSize, unsigned _eoSize, eoRnd & _geneRnd ) - :vector() { - for ( unsigned i = 0; i < _popSize; i ++ ){ - EOT tmpEOT( _eoSize, _geneRnd); - push_back( tmpEOT ); - } - }; - - /** Ctor for variable-size chromosomes, with variable content - @param _popSize total population size - @param _sizeRnd RNG for the chromosome size. This will be added 1, just in case. - @param _geneRdn random number generator for each of the genes - */ - eoPop( unsigned _popSize, eoRnd & _sizeRnd, eoRnd & _geneRnd ) - :vector() { - for ( unsigned i = 0; i < _popSize; i ++ ){ - unsigned size = 1 + _sizeRnd(); - EOT tmpEOT( size, _geneRnd); - push_back( tmpEOT ); - } - }; - - /** Ctor for user-defined chromosomes, - @param _popSize total population size - @param _chromRnd Initialization routine, produces EO's - */ - eoPop( unsigned _popSize, eoInit & _chromRnd ) + eoPop( unsigned _popSize, eoInit& _chromInit ) :vector() { + resize(_popSize); for ( unsigned i = 0; i < _popSize; i++ ) { - push_back( _chromRnd() ); + _chromInit(operator[](i)); } }; @@ -133,6 +107,60 @@ class eoPop: public vector, public eoObject, public eoPersistent { push_back( thisEOT ); } } + + /** + sort the population. Use this member to sort in order + of descending Fitness, so the first individual is the best! + */ + void sort(void) + { + std::sort(begin(), end(), greater >()); + } + + /** + slightly faster algorithm than sort to find all individuals that are better + than the nth individual + */ + eoPop::iterator nth_element(int nth) + { + iterator it = begin() + nth; + std::nth_element(begin(), it, end(), greater >()); + return it; + } + + struct GetFitness { Fitness operator()(const EOT& _eo) const { return _eo.fitness(); } }; + + Fitness nth_element_fitness(int which) const + { + vector fitness(size()); + std::transform(begin(), end(), fitness.begin(), GetFitness()); + + vector::iterator it = fitness.begin(); + std::nth_element(fitness.begin(), it, fitness.end(), greater()); + return *it; + } + + struct Ref { const EOT* operator()(const EOT& eot) { return &eot;}}; + struct Cmp { + bool operator()(const EO* a, const EO* b) const + { return b->operator<(*a); } + }; + /// const nth_element function, returns pointers to sorted individuals + void nth_element(int which, vector& result) const + { + + result.resize(size()); + std::transform(begin(), end(), result.begin(), Ref()); + + vector::iterator it = result.begin() + which; + + std::nth_element(result.begin(), it, result.end(), Cmp()); + } + + void swap(eoPop& other) + { + std::swap(static_cast& >(*this), static_cast& >(other)); + } /** * Write object. It's called printOn since it prints the object _on_ a stream. @@ -151,5 +179,79 @@ class eoPop: public vector, public eoObject, public eoPersistent { protected: }; + +/** + Keeps and calculates information about a population such + as the sum of fitnesses and whether the population is sorted. + It can be used to cache information about a population between + calls of functors, see for instance how this makes eoProportional + just this tat more efficient + + @see eoSelectOne, eoSelect, eoProportional + +template +class eoPopStats +{ +public : + typedef typename EOT::Fitness FitnessType; + + /// Initialize by stating nothing is known + eoPopStats() : + sum_fitness_calculated(false), + pop_sorted_calculated(false) + {} + + /// Call this function after the pop might have/is changed + void reset() + { + sum_fitness_calculated = false; + pop_sorted_calculated = false; + } + + /// Calculate sum_fitness or return cached value + FitnessType get_sum_fitness(const eoPop& _pop) + { + if (sum_fitness_calculated) + return sum_fitness; + + sum_fitness = 0.0; + + for (int i = 0; i < _pop.size(); ++i) + { + sum_fitness += _pop[i].fitness(); + } + + sum_fitness_calculated = true; + return sum_fitness; + } + + /// Check if the pop is sorted or return cached_value + bool is_pop_sorted(const eoPop& _pop) + { + if (pop_sorted_calculated) + return pop_sorted; + + int i; + for (i = 1; i < _pop.size(); ++i) + { + if (!(_pop[i-1] < _pop[i])) + { // not in sort order + break; + } + } + + pop_sorted = (i == _pop.size()); + pop_sorted_calculated = true; + return pop_sorted; + } + + bool sum_fitness_calculated; + FitnessType sum_fitness; + + bool pop_sorted_calculated; + bool pop_sorted; +}; +*/ + #endif diff --git a/eo/src/eoProportional.h b/eo/src/eoProportional.h new file mode 100644 index 000000000..f47cbba82 --- /dev/null +++ b/eo/src/eoProportional.h @@ -0,0 +1,73 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoProportional.h +// (c) GeNeura Team, 1998 - EEAAX 1999, Maarten Keijzer 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef eoProportional_h +#define eoProportional_h + +//----------------------------------------------------------------------------- + +#include +#include +#include + +//----------------------------------------------------------------------------- +/** eoProportional: select an individual proportional to her stored fitness +value + +*/ +//----------------------------------------------------------------------------- + +template class eoProportional: public eoSelectOne +{ +public: + + /// Sanity check + eoProportional(void) : total(-1.0) + { + if (minimizing_fitness()) + { + throw logic_error("eoProportional: minimizing fitness"); + } + } + + void setup(const eoPop& _pop) + { + total = sum_fitness(_pop); + } + + /** do the selection, call roulette_wheel. + */ + const EOT& operator()(const eoPop& _pop) + { + return roulette_wheel(_pop, total) ; + } + +private : + typename EOT::Fitness total; +}; + +#endif + diff --git a/eo/src/eoReduce.h b/eo/src/eoReduce.h new file mode 100644 index 000000000..e1fb6eb15 --- /dev/null +++ b/eo/src/eoReduce.h @@ -0,0 +1,58 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoReduce.h +// Base class for population-merging classes +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + +#ifndef eoReduce_h +#define eoReduce_h + +//----------------------------------------------------------------------------- + +#include + +// EO includes +#include // eoPop +#include // eoReduce + +/** + * eoReduce: .reduce the new generation to the specified size +*/ + +template class eoReduce: public eoBinaryFunctor&, unsigned> +{}; + +template class eoTruncate : public eoReduce +{ + void operator()(eoPop& _newgen, unsigned _newsize) + { + if (_newgen.size() == _newsize) + return; + + _newgen.nth_element(_newsize); + _newgen.resize(_newsize); + } +}; + +//----------------------------------------------------------------------------- + +#endif //eoInsertion_h diff --git a/eo/src/eoReplacement.h b/eo/src/eoReplacement.h new file mode 100644 index 000000000..43b8347df --- /dev/null +++ b/eo/src/eoReplacement.h @@ -0,0 +1,111 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoReplacement.h + (c) Maarten Keijzer, GeNeura Team, 2000 + + 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 _eoReplacement_h +#define _eoReplacement_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +#include +//----------------------------------------------------------------------------- + +/** +eoReplacement: High level strategy for creating a new generation +from parents and offspring. This is a combination of eoMerge and eoReduce, +so there is an implementation called eoMergeReduce that can be found below + + @see eoMerge, eoReduce, eoMergeReduce +*/ +template +class eoReplacement : public eoBinaryFunctor&, eoPop&> +{}; + +/** +no replacement +*/ +template +class eoNoReplacement : public eoReplacement +{ + public : + /// do nothing + void operator()(const eoPop&, eoPop&) + {} +}; + +/** +eoMergeReduce: special replacement strategy that is just an application of an embedded merge, +followed by an embedded reduce +*/ +template +class eoMergeReduce : public eoReplacement +{ + public: + eoMergeReduce(eoMerge& _merge, eoReduce& _reduce) : + merge(_merge), reduce(_reduce) + {} + + void operator()(const eoPop& _parents, eoPop& _offspring) + { + merge(_parents, _offspring); + reduce(_offspring, _parents.size()); + } + + private : + eoMerge& merge; + eoReduce& reduce; +}; + +/** +ES type of replacement strategy: first add parents to population, then truncate +*/ +template +class eoPlusReplacement : public eoMergeReduce +{ + public : + eoPlusReplacement() : eoMergeReduce(plus, truncate) {} + + private : + eoPlus plus; + eoTruncate truncate; +}; + +/** +ES type of replacement strategy: ignore parents, truncate offspring +*/ +template +class eoCommaReplacement : public eoMergeReduce +{ + public : + eoCommaReplacement() : eoMergeReduce(no_elite, truncate) {} + + private : + eoNoElitism no_elite; + eoTruncate truncate; +}; + + +#endif diff --git a/eo/src/eoSGA.h b/eo/src/eoSGA.h new file mode 100644 index 000000000..79a402d14 --- /dev/null +++ b/eo/src/eoSGA.h @@ -0,0 +1,101 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoSGA.h +// (c) GeNeura Team, 2000 - EEAAX 1999 - Maarten Keijzer 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mak@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoSGA_h +#define _eoSGA_h + +#include +#include +#include +#include +#include +#include +#include + +template +class eoSGA : public eoAlgo +{ +public : + eoSGA( + eoContinue& _cont, + eoMonOp& _mutate, float _mrate, + eoQuadraticOp& _cross, float _crate, + eoSelectOne& _select, + eoEvalFunc& _eval) + : cont(_cont), + mutate(_mutate), + mutationRate(_mrate), + cross(_cross), + crossoverRate(_crate), + select(_select), + eval(_eval) {} + + void operator()(eoPop& _pop) + { + eoPop offspring; + + do + { + select(_pop, offspring); + + unsigned i; + + for (i=0; i<_pop.size()/2; i++) + { + if ( rng.flip(crossoverRate) ) + { + // this crossover generates 2 offspring from two parents + cross(offspring[2*i], offspring[2*i+1]); + } + } + + for (i=0; i < _pop.size(); i++) + { + if (rng.flip(mutationRate) ) + { + mutate(offspring[i]); + } + + eval(offspring[i]); + } + + _pop.swap(offspring); + + } while (cont(_pop)); + } + +private : + + eoContinue& cont; + eoMonOp& mutate; + float mutationRate; + eoQuadraticOp& cross; + float crossoverRate; + eoSelectPerc select; + eoEvalFunc& eval; +}; + +#endif diff --git a/eo/src/eoScalarFitness.h b/eo/src/eoScalarFitness.h index 58e4a33cd..e10369c7f 100644 --- a/eo/src/eoScalarFitness.h +++ b/eo/src/eoScalarFitness.h @@ -26,18 +26,23 @@ #ifndef eoScalarFitness_h #define eoScalarFitness_h +#include +#include + /** * eoScalarFitness >: * Wraps a scalar fitness values such as a double or int, with the option of - * maximizing (using less) or miniziming (using greater) - * this quantity in EO. + * maximizing (using less) or minimizing (using greater) + * + * + * * * It overrides operator<() to use the Compare template argument * * Suitable constructors and assignments and casts are defined to work * with this quantity as if it were a ScalarType. */ -template > +template class eoScalarFitness { public : @@ -57,10 +62,24 @@ class eoScalarFitness bool operator<(const eoScalarFitness& other) const { return Compare()(value, other.value); } + // implementation of the other operators + bool operator>( const eoScalarFitness& y ) const { return y < *this; } + // implementation of the other operators + bool operator<=( const eoScalarFitness& y ) const { return !(*this > y); } + // implementation of the other operators + bool operator>=(const eoScalarFitness& y ) const { return !(*this < y); } + + private : ScalarType value; }; +/** +Typedefs for fitness comparison, +*/ +typedef eoScalarFitness > eoMaximizingFitness; +typedef eoScalarFitness > eoMinimizingFitness; + template std::ostream& operator<<(std::ostream& os, const eoScalarFitness& f) { @@ -69,7 +88,7 @@ std::ostream& operator<<(std::ostream& os, const eoScalarFitness& f) } template -std::istream& operator>>(istream& is, eoScalarFitness& f) +std::istream& operator>>(std::istream& is, eoScalarFitness& f) { F value; is >> value; diff --git a/eo/src/eoSelect.h b/eo/src/eoSelect.h new file mode 100644 index 000000000..2ba9adb56 --- /dev/null +++ b/eo/src/eoSelect.h @@ -0,0 +1,43 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoSelect.h + (c) Maarten Keijzer, GeNeura Team, 2000 + + 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 _eoSelect_h +#define _eoSelect_h + + +//----------------------------------------------------------------------------- +#include +//----------------------------------------------------------------------------- + +/** +eoSelect selects a number of individuals from the first argument and +puts it in the second. To emphasize that it should not try to enlarge +the population, the second argument is an eoPopRange, a simple struct +that holds a begin and end iterator to the population +*/ +template +class eoSelect : public eoBinaryFunctor&, eoPop&> +{}; + +#endif diff --git a/eo/src/eoSelectOne.h b/eo/src/eoSelectOne.h new file mode 100644 index 000000000..07d3a65ff --- /dev/null +++ b/eo/src/eoSelectOne.h @@ -0,0 +1,49 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoSelectOne.h + (c) Maarten Keijzer, GeNeura Team, 2000 + + 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 _eoSelectOne_h +#define _eoSelectOne_h + + +//----------------------------------------------------------------------------- +#include +#include +//----------------------------------------------------------------------------- + +/** eoSelectOne selects only one element from a whole population. + Most selection techniques are simply repeated applications + of eoSelectOne. + + @see eoSelectMany, eoSelectRandom, eoDetTournament, eoStochTournament, eoProportional +*/ +template +class eoSelectOne : public eoUnaryFunctor&> +{ + public : + + /// virtual function to setup some population stats (for instance eoProportional can benefit greatly from this) + virtual void setup(const eoPop&) {} +}; + +#endif diff --git a/eo/src/eoSelectPerc.h b/eo/src/eoSelectPerc.h new file mode 100644 index 000000000..f74adb370 --- /dev/null +++ b/eo/src/eoSelectPerc.h @@ -0,0 +1,72 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoSelectPerc.h + (c) Maarten Keijzer, GeNeura Team, 2000 + + 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 _eoSelectPerc_h +#define _eoSelectPerc_h + + +//----------------------------------------------------------------------------- +#include +#include +#include +//----------------------------------------------------------------------------- + +/** eoSelectPerc selects many individuals using eoSelectOne as it's + mechanism. Therefore eoSelectPerc needs an eoSelectOne in its ctor + + It will select floor(rate*pop.size()) individuals and pushes them to + the back of the destination population. +*/ +template +class eoSelectPerc : public eoSelect +{ + public: + /// init + eoSelectPerc(eoSelectOne& _select, float _rate = 1.0) + : select(_select), rate(_rate) {} + + /** + The implementation selects a percentage + + @param _source the source population + @param _dest the resulting population (size of this population is the number of times eoSelectOne is called. It empties the destination and adds the selection into it) + */ + virtual void operator()(const eoPop& _source, eoPop& _dest) + { + size_t target = static_cast(floor(rate * _source.size())); + + _dest.resize(target); + + select.setup(_source); + + for (int i = 0; i < _dest.size(); ++i) + _dest[i] = select(_source); + } + + private : + eoSelectOne& select; + float rate; +}; + +#endif diff --git a/eo/src/eoUniformSelect.h b/eo/src/eoSelectRandom.h similarity index 64% rename from eo/src/eoUniformSelect.h rename to eo/src/eoSelectRandom.h index 0c4707ee7..84ea72f81 100644 --- a/eo/src/eoUniformSelect.h +++ b/eo/src/eoSelectRandom.h @@ -1,8 +1,8 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- -// eoUniformSelect.h -// (c) GeNeura Team, 1998 - EEAAX 1999 +// eoSelectRandom.h +// (c) GeNeura Team, 1998 - EEAAX 1999, Maarten Keijzer 2000 /* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -20,46 +20,33 @@ Contact: todos@geneura.ugr.es, http://geneura.ugr.es Marc.Schoenauer@polytechnique.fr + mak@dhi.dk */ //----------------------------------------------------------------------------- -#ifndef eoUniformSelect_h -#define eoUniformSelect_h -// WARNING: 2 classes in this one - eoUniformSelect and eoCopySelect +#ifndef eoSelectRandom_h +#define eoSelectRandom_h //----------------------------------------------------------------------------- -#include // -#include // accumulate -#include // eoPop eoSelect MINFLOAT #include +#include //----------------------------------------------------------------------------- -/** eoUniformSelect: a selection method that selects ONE individual randomly +/** eoSelectRandom: a selection method that selects ONE individual randomly -MS- 22/10/99 */ //----------------------------------------------------------------------------- -template class eoUniformSelect: public eoSelectOne +template class eoSelectRandom: public eoSelectOne { public: - /// (Default) Constructor. - eoUniformSelect():eoSelectOne() {} /// not a big deal!!! - virtual const EOT& operator()(const eoPop& pop) { + virtual const EOT& operator()(const eoPop& pop) + { return pop[rng.random(pop.size())] ; } - - /// Methods inherited from eoObject - //@{ - - /** Return the class id. - * @return the class name as a string - */ - virtual string className() const { return "eoUniformSelect"; }; - - private: }; -#endif eoUniformSelect_h +#endif eoSelectRandom_h diff --git a/eo/src/eoSequentialGOpSelector.h b/eo/src/eoSequentialGOpSel.h similarity index 74% rename from eo/src/eoSequentialGOpSelector.h rename to eo/src/eoSequentialGOpSel.h index e77bdec7a..11c3c4692 100644 --- a/eo/src/eoSequentialGOpSelector.h +++ b/eo/src/eoSequentialGOpSel.h @@ -1,7 +1,7 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoSequentialGOpSelector.h + eoSequentialGOpSel.h Sequential Generalized Operator Selector. (c) Maarten Keijzer (mkeijzer@mad.scientist.com), GeNeura Team 1998, 1999, 2000 @@ -23,35 +23,28 @@ Contact: todos@geneura.ugr.es, http://geneura.ugr.es */ -#ifndef eoSequentialGOpSelector_h -#define eoSequentialGOpSelector_h +#ifndef eoSequentialGOpSel_h +#define eoSequentialGOpSel_h //----------------------------------------------------------------------------- -#include "eoGOpSelector.h" -/** eoSequentialGOpSel: do proportional selection, but return a sequence of - operations to be applied one after the other. +#include +/** eoSequentialGOpSel: return a sequence of + operations to be applied one after the other. The order of the + operators is significant. If for instance you first add a + quadratic operator and then a mutation operator, + + @see eoGeneralOp, eoCombinedOp */ template class eoSequentialGOpSel : public eoGOpSelector { public : - virtual ~eoSequentialGOpSel(void) {} + eoSequentialGOpSel(void) : combined(*this, getRates()) {} virtual eoGeneralOp& selectOp() - { - combined.clear(); - - for (unsigned i = 0; i < size(); ++i) - { - if (operator[](i) == 0) - continue; - - if (rng.flip(getRates()[i])) - combined.addOp(operator[](i)); - } - + { return combined; } diff --git a/eo/src/eoSteadyStateEA.h b/eo/src/eoSteadyStateEA.h index 824c67a73..7be4870ff 100644 --- a/eo/src/eoSteadyStateEA.h +++ b/eo/src/eoSteadyStateEA.h @@ -27,8 +27,8 @@ //----------------------------------------------------------------------------- -#include "eoSteadyStateGeneration.h" // eoPop -#include +#include +#include /** EOSteadyStateEA: An easy-to-use evolutionary algorithm, just supply @@ -42,19 +42,19 @@ template class eoSteadyStateEA: public eoAlgo /// Constructor. eoSteadyStateEA( eoGOpSelector& _opSelector, - eoPopIndiSelector& _selector, + eoSelectOne& _selector, eoSteadyStateInserter& _inserter, - eoTerm& _terminator, + eoContinue& _continuator, unsigned _steps = 0 ) - : step(_opSelector, _selector, _inserter), - terminator( _terminator) + : step(_opSelector, _selector, _inserter, _steps), + continuator( _continuator) {}; /// Constructor from an already created generation - eoSteadyStateEA(eoSteadyStateGeneration& _gen, - eoTerm& _terminator): + eoSteadyStateEA(eoSteadyStateTransform& _gen, + eoContinue& _continuator): step(_gen), - terminator( _terminator){}; + continuator( _continuator){}; /// Apply one generation of evolution to the population. virtual void operator()(eoPop& pop) { @@ -69,16 +69,13 @@ template class eoSteadyStateEA: public eoAlgo s.append( " in eoSteadyStateEA "); throw runtime_error( s ); } - } while ( terminator( pop ) ); + } while ( continuator( pop ) ); } - - /// Class name. - string className() const { return "eoSteadyStateEA"; } - + private: - eoSteadyStateGeneration step; - eoTerm& terminator; + eoSteadyStateTransform step; + eoContinue& continuator; }; //----------------------------------------------------------------------------- diff --git a/eo/src/eoSteadyStateInserter.h b/eo/src/eoSteadyStateInserter.h index 83ae0d57b..57fd187e4 100644 --- a/eo/src/eoSteadyStateInserter.h +++ b/eo/src/eoSteadyStateInserter.h @@ -34,19 +34,19 @@ /** * eoSteadyStateInserter: Interface class that enables an operator to update - * a population with a new individual... it contains an eoEvalFunc object to + * a population with a new individual... it contains an eoEvalFunc derived object to * make sure that every individual is evaluated before it is inserted */ template class eoSteadyStateInserter : public eoPopInserter { public : - eoSteadyStateInserter(eoEvalFunc& _eval): + eoSteadyStateInserter(eoEvalFunc& _eval): eoPopInserter(), eval(_eval) {} protected : - eoEvalFunc& eval; + eoEvalFunc& eval; }; diff --git a/eo/src/eoSteadyStateGeneration.h b/eo/src/eoSteadyStateTransform.h similarity index 77% rename from eo/src/eoSteadyStateGeneration.h rename to eo/src/eoSteadyStateTransform.h index c055b1076..82d9b4715 100644 --- a/eo/src/eoSteadyStateGeneration.h +++ b/eo/src/eoSteadyStateTransform.h @@ -1,8 +1,8 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- -// eoSteadyStateGeneration.h -// (c) GeNeura Team, 1998 +// eoSteadyStateTransform.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 @@ -22,33 +22,32 @@ */ //----------------------------------------------------------------------------- -#ifndef eoSteadyStateGeneration_h -#define eoSteadyStateGeneration_h +#ifndef eoSteadyStateTransform_h +#define eoSteadyStateTransform_h //----------------------------------------------------------------------------- #include // eoPop #include -#include // eoSelect, eoTranform, eoMerge -#include "eoGOpSelector.h" -#include "eoIndiSelector.h" -#include "eoSteadyStateInserter.h" +#include +#include +#include //----------------------------------------------------------------------------- -/** eoSteadyStateGeneration +/** eoSteadyStateTransform * Single step of a steady state evolutionary algorithm. * Proceeds by updating one individual at a time, by first selecting parents, * creating one or more children and subsequently overwrite (a) bad individual(s) */ -template class eoSteadyStateGeneration: public eoAlgo +template class eoSteadyStateTransform: public eoTransform { public: /// Constructor. - eoSteadyStateGeneration( + eoSteadyStateTransform( eoGOpSelector& _opSelector, - eoPopIndiSelector& _selector, + eoSelectOne& _selector, eoSteadyStateInserter& _inserter, unsigned _steps = 0) : opSelector(_opSelector), @@ -66,19 +65,19 @@ template class eoSteadyStateGeneration: public eoAlgo nSteps = pop.size(); // make a 'generation equivalent' } - for (unsigned i = 0; i < nSteps; ++i) + for (unsigned i = 0; i < steps; ++i) { - opSelector.selectOp()(selector(pop), inserter(pop)); + selector.bind(pop); + inserter.bind(pop); + + opSelector.selectOp()(selector, inserter); } } - /// Class name. - string className() const { return "eoSteadyStateGeneration"; } - private: eoGOpSelector& opSelector; - eoPopIndiSelector& selector; + eoSelectOneIndiSelector& selector; eoSteadyStateInserter& inserter; unsigned steps; }; diff --git a/eo/src/eoStochTournament.h b/eo/src/eoStochTournament.h index 215ca3a58..29ec31c00 100644 --- a/eo/src/eoStochTournament.h +++ b/eo/src/eoStochTournament.h @@ -30,7 +30,6 @@ #include // #include // accumulate -#include // eoPop eoSelect MINFLOAT #include //----------------------------------------------------------------------------- @@ -44,7 +43,8 @@ template class eoStochTournament: public eoSelectOne public: /// - eoStochTournament(float _Trate = 1.0 ):eoSelectOne(), Trate(_Trate) { + eoStochTournament(float _Trate = 1.0 ) : eoSelectOne(), Trate(_Trate) + { // consistency check if (Trate < 0.5) { cerr << "Warning, Tournament rate should be > 0.5\nAdjusted to 0.55\n"; @@ -52,8 +52,7 @@ template class eoStochTournament: public eoSelectOne } } - /** DANGER: if you want to be able to minimize as well as maximizem - DON'T cast the fitness to a float, use the EOT comparator! */ + /** Perform the stochastic tournament */ virtual const EOT& operator()(const eoPop& pop) { return stochastic_tournament(pop, Trate); diff --git a/eo/src/eoStochTournamentInserter.h b/eo/src/eoStochTournamentInserter.h index a68556056..002f3d9c1 100644 --- a/eo/src/eoStochTournamentInserter.h +++ b/eo/src/eoStochTournamentInserter.h @@ -63,7 +63,6 @@ public : eo = _eot; // overwrite loser of tournament eo.invalidate(); - eval(eo); // Evaluate after insert return *this; } diff --git a/eo/src/eoTransform.h b/eo/src/eoTransform.h new file mode 100644 index 000000000..f10440249 --- /dev/null +++ b/eo/src/eoTransform.h @@ -0,0 +1,41 @@ +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + + ----------------------------------------------------------------------------- + eoTransform.h + (c) Maarten Keijzer, GeNeura Team, 2000 + + 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 _eoTransform_h +#define _eoTransform_h + + +//----------------------------------------------------------------------------- +#include +//----------------------------------------------------------------------------- + +/** +eoTransform transforms a population by applying genetic operators on +it. +*/ +template +class eoTransform : public eoUnaryFunctor&> +{}; + +#endif diff --git a/eo/src/eoVariableLength.h b/eo/src/eoVariableLength.h index 9bf952a09..6cd823f32 100644 --- a/eo/src/eoVariableLength.h +++ b/eo/src/eoVariableLength.h @@ -30,8 +30,9 @@ #include /** - Base class for variable length chromosomes, just derives from EO and list and - redirects the smaller than operator to EO (fitness based comparison) + Base class for variable length chromosomes. Derives from EO and list, + redirects the smaller than operator to EO (fitness based comparison), + and implements the virtual functions printOn() and readFrom() */ template @@ -39,8 +40,39 @@ class eoVariableLength : public EO, public std::list { public : - typedef typename GeneType Type; + typedef GeneType AtomType; + typedef std::list ContainerType; + /// printing... + void printOn(ostream& os) const + { + EO::printOn(os); + os << ' '; + + os << size() << ' '; + + std::copy(begin(), end(), ostream_iterator(os)); + } + + /// reading... + void readFrom(istream& is) + { + EO::readFrom(is); + + unsigned sz; + is >> sz; + + resize(0); + unsigned i; + unsigned gene; + + for (i = 0; i < sz; ++i) + { + is >> gene; + push_back(gene); + } + } + /// to avoid conflicts between EO::operator< and vector::operator< bool operator<(const eoVariableLength& _eo) const { diff --git a/eo/src/eoWrappedOps.h b/eo/src/eoWrappedOps.h index 881db6e71..7ef717f63 100644 --- a/eo/src/eoWrappedOps.h +++ b/eo/src/eoWrappedOps.h @@ -42,25 +42,22 @@ class eoWrappedMonOp : public eoGeneralOp { public : /// - eoWrappedMonOp(const eoMonOp& _op) : eoGeneralOp(), op(_op) {}; + eoWrappedMonOp(eoMonOp& _op) : eoGeneralOp(), op(_op) {}; /// virtual ~eoWrappedMonOp() {} /// Instantiates the abstract method void operator()( eoIndiSelector& _in, - eoInserter& _out) const { + eoInserter& _out) + { EOT result = _in(); op( result ); _out(result); } - /// - virtual string className() const {return "eoWrappedMonOp";}; - - private : - const eoMonOp& op; + eoMonOp& op; }; @@ -70,25 +67,23 @@ class eoWrappedBinOp : public eoGeneralOp { public : /// - eoWrappedBinOp(const eoBinOp& _op) : eoGeneralOp(), op(_op) {} + eoWrappedBinOp(eoBinOp& _op) : eoGeneralOp(), op(_op) {} /// virtual ~eoWrappedBinOp() {} /// Instantiates the abstract method. EOT should have copy ctor. void operator()(eoIndiSelector& _in, - eoInserter& _out) const { + eoInserter& _out) + { EOT out1 = _in(); const EOT& out2 = _in(); op(out1, out2); _out(out1); } - - /// - virtual string className() const {return "eoWrappedBinOp";}; private : - const eoBinOp& op; + eoBinOp& op; }; /// Wraps Quadratic operators @@ -97,125 +92,105 @@ class eoWrappedQuadraticOp : public eoGeneralOp { public : /// - eoWrappedQuadraticOp(const eoQuadraticOp& _op) : eoGeneralOp(), op(_op) {} + eoWrappedQuadraticOp(eoQuadraticOp& _op) : eoGeneralOp(), op(_op) {} /// virtual ~eoWrappedQuadraticOp() {} /// Instantiates the abstract method. EOT should have copy ctor. void operator()(eoIndiSelector& _in, - eoInserter& _out) const { + eoInserter& _out) + { EOT out1 = _in(); EOT out2 = _in(); op(out1, out2); _out(out1)(out2); } - /// - virtual string className() const {return "eoWrappedQuadraticOp";}; - private : - const eoQuadraticOp& op; + eoQuadraticOp& op; }; -/// Combines several ops -template +#include + +template class eoCombinedOp : public eoGeneralOp { -public : - - /// - eoCombinedOp() : eoGeneralOp() {} + public : + eoCombinedOp(const std::vector*>& _ops, const std::vector& rates) + : ops(_ops), rates(_rates) {} - /// - virtual ~eoCombinedOp() {} - - /// Adds a new operator to the combined Op - void addOp(eoGeneralOp* _op) - { - ops.push_back(_op); - } - - - /// Erases all operators added so far - void clear(void) { - ops.resize(0); - } - - /// Helper class to make sure that stuff that is inserted will be used again with the next operator - class eoIndiSelectorInserter : public eoIndiSelector, public eoInserter - { - public : - eoIndiSelectorInserter(eoIndiSelector& _in) - : eoIndiSelector(), eoInserter(), in(_in) - {} - - size_t size() const { return in.size(); } - const EOT& operator[](size_t _n) const { return in[_n]; } - - const EOT& operator()(void) - { - if (results.empty()) - { - return in(); - } - // else we use the previously inserted individual, - // an iterator to it is stored in 'results', but the memory - // is kept by 'intermediate'. - - list::iterator it = *results.begin(); - results.pop_front(); - return *it; - } - - eoInserter& operator()(const EOT& _eot) - { - intermediate.push_front(_eot); - results.push_front(intermediate.begin()); - return *this; - } - - void fill(eoInserter& _out) - { - typedef list::iterator>::iterator Iterator; - - for (Iterator it = results.begin(); it != results.end(); ++it) - { - _out(**it); - } - - results.clear(); - intermediate.clear(); // reclaim memory - } - - private : - - eoIndiSelector& in; - - // using lists as we need to push and pop a lot - // 'results' are iterators to the contents of 'intermediate' - // to prevent copying to and from intermediate... - list::iterator> results; - list intermediate; - }; - - /// Applies all ops in the combined op - void operator()( eoIndiSelector& _in, - eoInserter& _out ) const { - - eoIndiSelectorInserter in_out(_in); - - for (size_t i = 0; i < ops.size(); ++i) + class eoDelayedSelector : public eoIndiSelector { - (*ops[i])(in_out, in_out); - } + public : + eoDelayedSelector(eoIndiSelector& _select, const eoPop& _pop) : select(_select), pop(_pop), it(pop.begin()) {} + + unsigned size() const { return select.size();} + const EOT& operator[](size_t i) const { return select[i]; } - in_out.fill(_out); + /// will first dispense all previously selected individuals before returning new ones + const EOT& operator()(void) + { + if (it == pop.end()) + { + return select(); + } + // else + return *it++; + } + + eoPop::const_iterator get_it(void) const { return it; } + private : + eoIndiSelector& select; + const eoPop& pop; + eoPop::const_iterator it; + }; + + /** Applies all ops in the combined op + It works in the following way + */ + void operator()( eoIndiSelector& _in, + eoInserter& _out ) + { + eoPop intermediate; + eoPop next; + unsigned i; + + for (i = 0; i < ops.size(); ++i) + { + eoDelayedSelector delay(_in, intermediate); + inserter.bind(next); + + unsigned counter = 0; + + // apply operators until we have as many outputs as inputs + do + { + if (flip(rates[i])) // should this flip be here? + (*ops[i])(delayedSelector, inserter); + + counter++; + if (counter > 1000) + { + throw logical_error("eoCombinedOp: no termination after 1000 tries, did you forget to insert individuals in your eoGeneralOp?"); + } + } + while (next.size() < intermediate.size()); + + intermediate.swap(next); + next.resize(0); + } + + // after last swap, results can be found in intermediate + for (i = 0; i < intermediate.size(); ++i) + _out(intermediate[i]); } - -private : - vector* > ops; + + private : + const std::vector*>& ops; + const std::vector rates; + eoBackInserter inserter; }; -#endif eoGeneral_h +#endif diff --git a/eo/src/es/Makefile.am b/eo/src/es/Makefile.am index b72b66d15..6b89d98a6 100644 --- a/eo/src/es/Makefile.am +++ b/eo/src/es/Makefile.am @@ -5,4 +5,7 @@ ############################################################################### libeoincdir = $(includedir)/eo/es -libeoinc_HEADERS = eoESFullChrom.h eoESChrom.h eoESFullMut.h evolution_strategies eoEsObjectiveBounds.h eoEsSimple.h eoEsStdev.h eoEsFull.h eoEsChromInit.h eoEsMutationInit.h eoEsMutate.h \ No newline at end of file +libeoinc_HEADERS = evolution_strategies eoEsChromInit.h eoEsFull.h eoEsMutate.h eoEsMutationInit.h eoEsObjectiveBounds.h eoEsSimple.h eoEsStdev.h + + + diff --git a/eo/src/es/eoESFullMut.h b/eo/src/es/eoESFullMut.h deleted file mode 100644 index d4cc7ce72..000000000 --- a/eo/src/es/eoESFullMut.h +++ /dev/null @@ -1,253 +0,0 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoESMute.h : ES mutation -// (c) GeNeura Team, 1998 for the EO part -// Th. Baeck 1994 and EEAAX 1999 for the ES part -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - marc.schoenauer@polytechnique.fr - http://eeaax.cmap.polytchnique.fr/ - */ -//----------------------------------------------------------------------------- - - -#ifndef _EOESMUT_H -#define _EOESMUT_H - -#include -#include -#include // for exp - -#include -#include - -#ifndef M_PI -#define M_PI 3.1415926535897932384626433832795 -#endif - -const double ES_SIGEPS = 1.0e-40; /* ES lower bound for sigma values */ -// should not be a parameter ... - -/** ES-style mutation in the large: Obviously, valid only for eoESInd -*/ -template -class eoESMutate: public eoMonOp< eoESFullChrom > { -public: - eoESMutate(double n) - { - TauLcl = 1/sqrt(2*sqrt(n)); - TauGlb= 1 / sqrt(2 * n); - TauBeta = 0.0873; - }/// - - eoESMutate( double _TauLcl, double _TauGlb, double _TauBeta ) - : eoMonOp< eoESFullChrom >( ), TauLcl(_TauLcl), TauGlb(_TauGlb), - TauBeta(_TauBeta) {}; - - /* The parser constructor - */ - eoESMutate(Parser & parser, unsigned _stdDevLength, unsigned _size, bool _correlated ): - eoMonOp< eoESFullChrom >( ) { - parser.AddTitle("Parameters of ES mutation (before renormalization)"); - try { // we know that there is at least 1 std dev. - if (_stdDevLength == 1) { - TauLcl = parser.getInt("-Ml", "--TauLcl", "1", - "TauLcl, Mutation rate for the only Std Dev." ); - // different normalization in that case -- Thomas Baeck - TauLcl /= sqrt((double) _size); - } - else { /* more than 1 std dev */ - TauLcl = parser.getFloat("-Ml", "--TauLcl", "1", - "Local mutation rate for Std Dev." ); - TauGlb = parser.getFloat("-Mg", "--TauGlb", "1", - "Global mutation rate for Std Dev." ); - // renormalization - TauLcl /= sqrt( 2.0 * sqrt( (double)_size ) ); - TauGlb /= sqrt( 2.0 * ( (double) _size ) ); - - if ( _correlated ) { // Correlated Mutations - TauBeta = parser.getFloat("-Mb", "--TauBeta", "0.0873", - "Mutation rate for corr. coeff." ); - // rotation angles: no normalization - } - } - } - catch (exception & e) - { - cout << e.what() << endl; - parser.printHelp(); - exit(1); - } - }; - - /// needed virtual dtor - virtual ~eoESMutate() {}; - - // virtual separation depending wether correlated mutations are present - virtual void operator() ( eoESFullChrom & _eo ) const { - if (_eo.CorCffLength()) - CorrelatedMutation(_eo); - else - StandardMutation(_eo); - } - - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - virtual string className() const {return "eoESMutate";}; - -private: - /// mutations - standard et correlated - // ========= - /* - * Standard mutation of object variables and standard - * deviations in ESs. - * If there are fewer different standard deviations available - * than the dimension of the objective function requires, the - * last standard deviation is responsible for ALL remaining - * object variables. - * Schwefel 1977: Numerische Optimierung von Computer-Modellen - * mittels der Evolutionsstrategie, pp. 165 ff. - */ - - virtual void StandardMutation( eoESFullChrom & _eo ) const { - unsigned i,k; - double Glb, StdLoc; - - if (_eo.StdDevLength() == 1) { /* single StdDev -> No global factor */ - StdLoc = _eo.getStdDev(0); - StdLoc *= exp(TauLcl*rng.normal()); - if (StdLoc < ES_SIGEPS) - StdLoc = ES_SIGEPS; - _eo.setStdDev(0, StdLoc); - _eo.setGene( 0, _eo.getGene(0) + StdLoc*rng.normal()); - i = 1; - } - else { /* more than one std dev. */ - Glb = exp(TauGlb*rng.normal()); - for (i = 0; i < _eo.length() && i < _eo.StdDevLength(); i++) { - StdLoc = _eo.getStdDev(i); - StdLoc *= Glb * exp(TauLcl*rng.normal()); - if (StdLoc < ES_SIGEPS) - StdLoc = ES_SIGEPS; - _eo.setStdDev(i, StdLoc); - _eo.setGene( i, _eo.getGene(i) + StdLoc*rng.normal()); - } - } - // last object variables: same STdDev than the preceding one - for (k = i; k < _eo.length(); k++) { - _eo.setGene( k, _eo.getGene(k) + StdLoc*rng.normal() ); - } - } - - /* - * Correlated mutations in ESs, according to the following - * sources: - * H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80 - * p. 43, 1980 - * G. Rudolph: Globale Optimierung mit parallelen Evolutions- - * strategien, Diploma Thesis, University of Dortmund, 1990 - */ - - // Code from Thomas Baeck - - virtual void CorrelatedMutation( eoESFullChrom & _eo ) const { - - - int i, k, n1, n2, nq; - - double d1, d2, S, C, Glb; - double tmp; - /* - * First: mutate standard deviations (as above). - */ - - Glb = exp(TauGlb*rng.normal()); - for (i = 0; i < _eo.StdDevLength(); i++) { - tmp = _eo.getStdDev(i); - _eo.setStdDev( i, tmp*Glb*exp(TauLcl*rng.normal()) ); - } - - /* - * Mutate rotation angles. - */ - - for (i = 0; i < _eo.CorCffLength(); i++) { - tmp = _eo.getCorCff(i); - tmp += TauBeta*rng.normal(); - // danger of VERY long loops --MS-- - // while (CorCff[i] > M_PI) - // CorCff[i] -= 2.0 * M_PI; - // while (CorCff[i] < - M_PI) - // CorCff[i] += 2.0 * M_PI; - if ( fabs(tmp) > M_PI ) { - tmp -= M_PI * (int) (tmp/M_PI) ; - } - _eo.setCorCff(i, tmp); - } - - /* - * Perform correlated mutations. - */ - vector VarStp(_eo.size()); - for (i = 0; i < _eo.size() && i < _eo.StdDevLength(); i++) - VarStp[i] = _eo.getStdDev(i)*rng.normal(); - for (k = i; k < _eo.size(); k++) - VarStp[k] = _eo.getStdDev(i-1)*rng.normal(); - nq = _eo.CorCffLength() - 1; - for (k = _eo.size()-_eo.StdDevLength(); k < _eo.size()-1; k++) { - n1 = _eo.size() - k - 1; - n2 = _eo.size() - 1; - for (i = 0; i < k; i++) { - d1 = VarStp[n1]; - d2 = VarStp[n2]; - S = sin( _eo.getCorCff(nq) ); - C = cos( _eo.getCorCff(nq) ); - VarStp[n2] = d1 * S + d2 * C; - VarStp[n1] = d1 * C - d2 * S; - n2--; - nq--; - } - } - for (i = 0; i < _eo.size(); i++) - _eo[i] += VarStp[i]; - - } - // the data - //========= - double TauLcl; /* Local factor for mutation of std deviations */ - double TauGlb; /* Global factor for mutation of std deviations */ - double TauBeta; /* Factor for mutation of correlation parameters */ -}; - -/* - * Correlated mutations in ESs, according to the following - * sources: - * H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80 - * p. 43, 1980 - * G. Rudolph: Globale Optimierung mit parallelen Evolutions- - * strategien, Diploma Thesis, University of Dortmund, 1990 - */ -// Not yet implemented! - -#endif - diff --git a/eo/src/es/eoEsChromInit.h b/eo/src/es/eoEsChromInit.h index e9485d2b0..d5f058a0e 100644 --- a/eo/src/es/eoEsChromInit.h +++ b/eo/src/es/eoEsChromInit.h @@ -33,7 +33,7 @@ #include #include -#include +#include #ifndef M_PI #define M_PI 3.1415926535897932384626433832795 @@ -42,7 +42,7 @@ /** \ingroup EvolutionStrategies - Random Es-chromosome initializer (therefore derived from eoRnd) + Random Es-chromosome initializer (therefore derived from eoInit) This class can initialize three types of Es's: @@ -62,10 +62,9 @@ public : eoEsChromInit(eoEsObjectiveBounds& _bounds) : bounds(_bounds) {} - EOT operator()() + void operator()(EOT& _eo) { - EOT eo; - return create(eo); + create(_eo); } private : diff --git a/eo/src/es/eoEsMutate.h b/eo/src/es/eoEsMutate.h index 8f46d1406..54c406fe5 100644 --- a/eo/src/es/eoEsMutate.h +++ b/eo/src/es/eoEsMutate.h @@ -30,7 +30,7 @@ #define _EOESMUTATE_H #include -#include +#include #include // for exp #include @@ -89,7 +89,7 @@ public: /** Mutate eoEsSimple */ - virtual void operator()( eoEsSimple& _eo) const + virtual void operator()( eoEsSimple& _eo) { _eo.stdev *= exp(TauLcl * rng.normal()); @@ -104,6 +104,8 @@ public: } keepInBounds(_eo); + + _eo.invalidate(); } /// mutations - standard and correlated @@ -119,7 +121,7 @@ public: * mittels der Evolutionsstrategie, pp. 165 ff. */ - virtual void operator()( eoEsStdev& _eo ) const + virtual void operator()( eoEsStdev& _eo ) { double global = exp(TauGlb * rng.normal()); for (unsigned i = 0; i < _eo.size(); i++) @@ -135,6 +137,8 @@ public: } keepInBounds(_eo); + + _eo.invalidate(); } /* @@ -148,7 +152,7 @@ public: // Code from Thomas Baeck - virtual void operator()( eoEsFull & _eo ) const + virtual void operator()( eoEsFull & _eo ) { /* @@ -216,6 +220,8 @@ public: _eo[i] += VarStp[i]; keepInBounds(_eo); + + _eo.invalidate(); } void keepInBounds(eoFixedLength& _eo) const diff --git a/eo/src/ga/eoBin.h b/eo/src/ga/eoBin.h index 6ff794416..51fac67ec 100644 --- a/eo/src/ga/eoBin.h +++ b/eo/src/ga/eoBin.h @@ -27,7 +27,8 @@ #include // ostream, istream #include // bind2nd #include // string -#include // EO + +#include /** \defgroup bitstring @@ -38,9 +39,9 @@ /** eoBin: implementation of binary chromosome. \class eoBin eoBin.h ga/eoBin.h \ingroup bitstring - * based on STL's bit_vector (vector). + * based on STL's vector specialization. */ -template class eoBin: public eoVector +template class eoBin: public eoFixedLength { public: @@ -49,21 +50,8 @@ template class eoBin: public eoVector * @param size Size of the binary string. */ eoBin(unsigned size = 0, bool value = false): - eoVector(size, value) {} - - /** - * Constructor. - * @param size Size of the binary string. - */ - eoBin(unsigned size, const eoRnd& rnd): eoVector(size) - { - generate(begin(), end(), rnd); - } - - /** Constructor from istream. - @param is The istream to read from.*/ - eoBin(istream& _is):eoVector(_is){}; - + eoFixedLength(size, value) {} + /// My class name. string className() const { @@ -76,6 +64,7 @@ template class eoBin: public eoVector */ void printOn(ostream& os) const { + os << size() << ' '; copy(begin(), end(), ostream_iterator(os)); } @@ -98,4 +87,4 @@ template class eoBin: public eoVector //----------------------------------------------------------------------------- -#endif eoBin_h +#endif //eoBin_h diff --git a/eo/src/ga/eoBitOp.h b/eo/src/ga/eoBitOp.h index 3e4c1ae7c..7179b52d2 100644 --- a/eo/src/ga/eoBitOp.h +++ b/eo/src/ga/eoBitOp.h @@ -9,45 +9,8 @@ #include // swap_ranges #include -#include // eoBin -#include // eoMonOp - - -/** @name BitWise Genetic operators - -\class eoBinRandom eoBitOp.h ga/eoBitOp.h -\ingroup bitstring - -Even as these operators might seem general, they are particular versions of genetic -operators useful only for binary operators. As any set of genetic operators, it must -have a factory that knows how to build them from a description -@author GeNeura Team -@version 0.1 -@see eoBin -@see eoBitOpFactory -*/ - -//@{ - -/** eoBinRandom --> mofify a chromosome in a random way */ - -template class eoBinRandom: public eoMonOp -{ - public: - /// The class name. - string className() const { return "eoBinRandom"; } - - /** - * Randomizes a cromosome. - * @param chrom The cromosome to be randomize. - */ - void operator()(Chrom& chrom) const - { - for (unsigned i = 0; i < chrom.size(); i++) - chrom[i] = rng.flip(0.5) ? false : true; - } -}; - +#include // eoMonOp +#include /** eoBinBitFlip --> changes a bit \class eoBinBitFlip eoBitOp.h ga/eoBitOp.h @@ -64,8 +27,9 @@ template class eoBinBitFlip: public eoMonOp * Change one bit. * @param chrom The cromosome which one bit is going to be changed. */ - void operator()(Chrom& chrom) const + void operator()(Chrom& chrom) { + chrom.invalidate(); unsigned i = rng.random(chrom.size()); chrom[i] = (chrom[i]) ? false : true; } @@ -93,11 +57,18 @@ template class eoBinMutation: public eoMonOp * Mutate a chromosome. * @param chrom The chromosome to be mutated. */ - void operator()(Chrom& chrom) const + void operator()(Chrom& chrom) { + bool changed_something = false; for (unsigned i = 0; i < chrom.size(); i++) - if (rng.flip(rate)) - chrom[i] = !chrom[i]; + if (rng.flip(rate)) + { + chrom[i] = !chrom[i]; + changed_something = true; + } + + if (changed_something) + chrom.invalidate(); } private: @@ -120,7 +91,7 @@ template class eoBinInversion: public eoMonOp * Inverts a range of bits in a binary chromosome. * @param chrom The chromosome whos bits are going to be inverted (a range). */ - void operator()(Chrom& chrom) const + void operator()(Chrom& chrom) { unsigned u1 = rng.random(chrom.size() + 1) , u2; @@ -128,6 +99,7 @@ template class eoBinInversion: public eoMonOp unsigned r1 = min(u1, u2), r2 = max(u1, u2); reverse(chrom.begin() + r1, chrom.begin() + r2); + chrom.invalidate(); } }; @@ -147,7 +119,7 @@ template class eoBinNext: public eoMonOp * Change the bit string x to be x+1. * @param chrom The chromosome to be added one. */ - void operator()(Chrom& chrom) const + void operator()(Chrom& chrom) { for (int i = chrom.size() - 1; i >= 0; i--) if (chrom[i]) @@ -160,6 +132,8 @@ template class eoBinNext: public eoMonOp chrom[i] = 1; break; } + + chrom.invalidate(); } }; @@ -179,7 +153,7 @@ template class eoBinPrev: public eoMonOp * Change the bit string x to be x-1. * @param chrom The chromosome to be substracted one. */ - void operator()(Chrom& chrom) const + void operator()(Chrom& chrom) { for (int i = chrom.size() - 1; i >= 0; i--) if (chrom[i]) @@ -192,6 +166,8 @@ template class eoBinPrev: public eoMonOp chrom[i] = 1; continue; } + + chrom.invalidate(); } }; @@ -212,10 +188,19 @@ template class eoBinCrossover: public eoQuadraticOp * @param chrom1 The first chromosome. * @param chrom2 The first chromosome. */ - void operator()(Chrom& chrom1, Chrom& chrom2) const + void operator()(Chrom& chrom1, Chrom& chrom2) { - swap_ranges(chrom1.begin(), chrom1.begin() + rng.random(min(chrom1.size(), chrom2.size())), chrom2.begin()); - } + unsigned site = rng.random(min(chrom1.size(), chrom2.size())); + + if (std::equal(chrom1.begin(), chrom1.begin()+site, chrom2.begin())) + { + + swap_ranges(chrom1.begin(), chrom1.begin() + site, chrom2.begin()); + + chrom1.invalidate(); + chrom2.invalidate(); + } + } }; @@ -242,7 +227,7 @@ template class eoBinNxOver: public eoQuadraticOp * @param chrom1 The first chromosome. * @param chrom2 The first chromosome. */ - void operator()(Chrom& chrom1, Chrom& chrom2) const + void operator()(Chrom& chrom1, Chrom& chrom2) { unsigned max_size = min(chrom1.size(), chrom2.size()); unsigned max_points = min(max_size - 1, num_points); @@ -272,6 +257,9 @@ template class eoBinNxOver: public eoQuadraticOp if (change) swap(chrom1[bit], chrom2[bit]); } + + chrom1.invalidate(); + chrom2.invalidate(); } private: @@ -305,7 +293,7 @@ template class eoBinGxOver: public eoQuadraticOp * @param chrom1 The first chromosome. * @param chrom2 The first chromosome. */ - void operator()(Chrom& chrom1, Chrom& chrom2) const + void operator()(Chrom& chrom1, Chrom& chrom2) { unsigned max_genes = min(chrom1.size(), chrom2.size()) / gene_size; unsigned cut_genes = min(max_genes, num_points); @@ -330,7 +318,10 @@ template class eoBinGxOver: public eoQuadraticOp swap_ranges(chrom1.begin() + i * gene_size, chrom1.begin() + i * gene_size + gene_size, chrom2.begin() + i * gene_size); - } + + chrom1.invalidate(); + chrom2.invalidate(); + } private: unsigned gene_size; diff --git a/eo/src/ga/eoBitOpFactory.h b/eo/src/ga/eoBitOpFactory.h index 8d70c7e4e..46b35ff03 100644 --- a/eo/src/ga/eoBitOpFactory.h +++ b/eo/src/ga/eoBitOpFactory.h @@ -36,7 +36,8 @@ 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 eoOpFactory +{ public: @@ -59,7 +60,8 @@ public: @param _is an stream from where a single line will be read @throw runtime_exception if the object type is not known */ - virtual eoOp* make(istream& _is) { + virtual eoOp* make(istream& _is) + { eoOp * opPtr = NULL; try { opPtr = eoOpFactory::make( _is ); diff --git a/eo/src/gp/eoParseTree.h b/eo/src/gp/eoParseTree.h index 7bac61254..7be7c2021 100644 --- a/eo/src/gp/eoParseTree.h +++ b/eo/src/gp/eoParseTree.h @@ -3,12 +3,12 @@ #include -#include "EO.h" -#include "eoOp.h" -#include "eoInserter.h" -#include "eoIndiSelector.h" -#include "parse_tree.h" -#include "eoRnd.h" +#include +#include +#include +#include +#include +#include using namespace gp_parse_tree; using namespace std; @@ -90,7 +90,7 @@ std::istream& operator>>(std::istream& is, eoParseTree& eot) template -class eoGpDepthInitializer : public eoRnd< eoParseTree::Type > +class eoGpDepthInitializer : public eoInit< eoParseTree > { public : @@ -109,15 +109,13 @@ class eoGpDepthInitializer : public eoRnd< eoParseTree::Type > virtual string className() const { return "eoDepthInitializer"; }; - EoType::Type operator()(void) + void operator()(EoType& _tree) { list sequence; generate(sequence, max_depth); - parse_tree tree(sequence.begin(), sequence.end()); - - return tree.root(); + _tree = parse_tree(sequence.begin(), sequence.end()); } void generate(list& sequence, int the_max, int last_terminal = -1) diff --git a/eo/src/gp/node_pool.h b/eo/src/gp/node_pool.h index f541d5f0c..ef5c4b42d 100644 --- a/eo/src/gp/node_pool.h +++ b/eo/src/gp/node_pool.h @@ -1,3 +1,31 @@ +/** + + * Pool allocator for the subtree and parse tree classes (homebrew and not compliant to ANSI allocator requirements) + * (c) copyright Maarten Keijzer 1999, 2000 + + * Permission to copy, use, modify, sell and distribute this software is granted provided + * this copyright notice appears in all copies. This software is provided "as is" without + * express or implied warranty, and with no claim as to its suitability for + * any purpose. + + * Permission to modify the code and to distribute modified code is granted, + * provided the above notices are retained, and a notice that the code was + * modified is included with the above copyright notice. + + + * Special disclaimer and political statement: + + * In contrast with the rest of the EO package where you might have found this code, this software + * does NOT fall under the GNU Lesser Public License or the GNU Public License, nor is anyone allowed + * by the copyright holder (that's me) to put it under either license. + * Doing this would limit my and your freedom to use this software in any way + * you or I see fit, including but not limited to closed-source software. I personally do not adher to + * virus-like qualities of the GPL and therefore take the liberty to open this code as wide as I can. + * Furthermore, as this work was carried out in an academic environment and thus paid by the public + * I do not see the need for the same public (which includes commercial companies) + * to be limited in any way to use this software. + +*/ #ifndef node_pool_h #define node_pool_h diff --git a/eo/src/gp/parse_tree.h b/eo/src/gp/parse_tree.h index ea971bbf3..1ac2cf66d 100644 --- a/eo/src/gp/parse_tree.h +++ b/eo/src/gp/parse_tree.h @@ -4,24 +4,26 @@ /** * Parse_tree and subtree classes - * (c) Maarten Keijzer 1999, 2000 + * (c) copyright Maarten Keijzer 1999, 2000 - * These classes may be used for educational and - * other non-commercial purposes only. Even if I - * wanted to, I am not at liberty to place this file - * under the GNU Lesser Public Library License, as this - * would limit my and my institution's freedom to use - * this file in closed-source software. + * Permission to copy, use, modify, sell and distribute this software is granted provided + * this copyright notice appears in all copies. This software is provided "as is" without + * express or implied warranty, and with no claim as to its suitability for + * any purpose. - * This material is provided "as is", with absolutely no warranty expressed - * or implied. Any use is at your own risk. - * - * Permission to use or copy this software for non-commercial purpose is hereby granted - * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, - * provided the above notices are retained, and a notice that the code was + * provided the above notices as well as this one are retained, and a notice that the code was * modified is included with the above copyright notice. - * + + + * Special disclaimer and political statement: + + * In contrast with the rest of the EO package where you might have found this code, this software + * does NOT fall under the GNU Lesser Public License or the GNU Public License, nor is anyone allowed + * by the copyright holder (that's me) to put it under either license. + * Doing this would limit my and your freedom to use this software in any way + * you or I see fit, including but not limited to closed-source software. + Usage information. diff --git a/eo/src/eo1d.h b/eo/src/obsolete/eo1d.h similarity index 100% rename from eo/src/eo1d.h rename to eo/src/obsolete/eo1d.h diff --git a/eo/src/eo1dWDistance.h b/eo/src/obsolete/eo1dWDistance.h similarity index 100% rename from eo/src/eo1dWDistance.h rename to eo/src/obsolete/eo1dWDistance.h diff --git a/eo/src/eo2d.h b/eo/src/obsolete/eo2d.h similarity index 100% rename from eo/src/eo2d.h rename to eo/src/obsolete/eo2d.h diff --git a/eo/src/eo2dVector.h b/eo/src/obsolete/eo2dVector.h similarity index 100% rename from eo/src/eo2dVector.h rename to eo/src/obsolete/eo2dVector.h diff --git a/eo/src/eoAtomBitFlip.h b/eo/src/obsolete/eoAtomBitFlip.h similarity index 96% rename from eo/src/eoAtomBitFlip.h rename to eo/src/obsolete/eoAtomBitFlip.h index f9d769d05..99bf4acb8 100644 --- a/eo/src/eoAtomBitFlip.h +++ b/eo/src/obsolete/eoAtomBitFlip.h @@ -1,57 +1,58 @@ -// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - -//----------------------------------------------------------------------------- -// eoAtomBitFlip.h -// Increments or decrements by one a single element -// (c) GeNeura Team, 1998 -/* - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - Contact: todos@geneura.ugr.es, http://geneura.ugr.es - */ -//----------------------------------------------------------------------------- -#ifndef _EOATOMBITFLIP_H -#define _EOATOMBITFLIP_H - -/** Flips a single bit -*/ -template -class eoAtomBitFlip: public eoAtomMutator { -public: - - /// - eoAtomBitFlip() {}; - - /// - virtual ~eoAtomBitFlip() {}; - - /// - virtual void operator()( T& _val ) const { - _val = !val; - } - - /** @name Methods from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - string className() const {return "eoAtomBitFlip";}; - //@} - -}; - - -#endif +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoAtomBitFlip.h +// Increments or decrements by one a single element +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- +#ifndef _EOATOMBITFLIP_H +#define _EOATOMBITFLIP_H + +/** Flips a single bit +*/ +template +class eoAtomBitFlip: public eoAtomMutator { +public: + + /// + eoAtomBitFlip() {}; + + /// + virtual ~eoAtomBitFlip() {}; + + /// + virtual void operator()( T& _val ) const { + _val = !val; + } + + /** @name Methods from eoObject + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoAtomBitFlip";}; + //@} + +}; + + +#endif + diff --git a/eo/src/eoAtomCreep.h b/eo/src/obsolete/eoAtomCreep.h similarity index 100% rename from eo/src/eoAtomCreep.h rename to eo/src/obsolete/eoAtomCreep.h diff --git a/eo/src/eoAtomMutation.h b/eo/src/obsolete/eoAtomMutation.h similarity index 100% rename from eo/src/eoAtomMutation.h rename to eo/src/obsolete/eoAtomMutation.h diff --git a/eo/src/eoAtomMutator.h b/eo/src/obsolete/eoAtomMutator.h similarity index 73% rename from eo/src/eoAtomMutator.h rename to eo/src/obsolete/eoAtomMutator.h index 7303f16db..ff4eedf4c 100644 --- a/eo/src/eoAtomMutator.h +++ b/eo/src/obsolete/eoAtomMutator.h @@ -24,38 +24,16 @@ #ifndef _EOATOMMUTATOR_H #define _EOATOMMUTATOR_H +#include + /** Abstract base class for functors that modify a single element in an EO that is composed of several atomic components. An atom would, for instance, flip - a bit, or change a real number, or things like that. + a bit, or change a real number, or things like that. The header is completely + empty and thus just provides a name rather than functionality. */ + template -class eoAtomMutator: public eoPrintable { -public: - - /// - eoAtomMutator() {}; - - /// - virtual ~eoAtomMutator() {}; - - /// - virtual void operator()( T& _val ) const = 0; - - /** @name Methods from eoObject - */ - //@{ - /** Inherited from eoObject - @see eoObject - */ - /// - virtual string className() const {return "eoAtomMutator";}; - - /// - void printOn(ostream& _os) const { _os << className() << endl; }; - - //@} - -}; +class eoAtomMutator: public eoUnaryFunctor {}; #endif diff --git a/eo/src/eoAtomRandom.h b/eo/src/obsolete/eoAtomRandom.h similarity index 95% rename from eo/src/eoAtomRandom.h rename to eo/src/obsolete/eoAtomRandom.h index 07d2eb98d..18ca49a8c 100644 --- a/eo/src/eoAtomRandom.h +++ b/eo/src/obsolete/eoAtomRandom.h @@ -36,14 +36,14 @@ class eoAtomRandom: public eoAtomMutator { public: /// - eoAtomRandom( eoRnd& _rng): rng( _rng ) {}; + eoAtomRandom( eoRnd& _rng): rnd( _rng ) {}; /// virtual ~eoAtomRandom() {}; /// Adds the value generated by the RNG to the former value virtual void operator()( T& _val ) const { - _val += rng(); + _val += rnd(); } /** @name Methods from eoObject @@ -56,7 +56,7 @@ public: //@} private: - eoRnd& rng; + eoRnd& rnd; }; diff --git a/eo/src/obsolete/eoBin.h b/eo/src/obsolete/eoBin.h new file mode 100644 index 000000000..544c3bb3b --- /dev/null +++ b/eo/src/obsolete/eoBin.h @@ -0,0 +1,89 @@ +/* + eoBin.h + (c) GeNeura Team 1998 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es +*/ + +#ifndef eoBin_h +#define eoBin_h + +//----------------------------------------------------------------------------- + +#include // ostream, istream +#include // bind2nd +#include // string + +#include + +/** +\defgroup bitstring + + Various functions for a bitstring representation +*/ + +/** eoBin: implementation of binary chromosome. +\class eoBin eoBin.h ga/eoBin.h +\ingroup bitstring + * based on STL's bit_vector (vector). +*/ +template class eoBin: public eoFixedLength +{ + public: + + /** + * (Default) Constructor. + * @param size Size of the binary string. + */ + eoBin(unsigned size = 0, bool value = false): + eoVector(size, value) {} + + /// My class name. + string className() const + { + return "eoBin"; + } + + /** + * To print me on a stream. + * @param os The ostream. + */ + void printOn(ostream& os) const + { + copy(begin(), end(), ostream_iterator(os)); + } + + /** + * To read me from a stream. + * @param is The istream. + */ + void readFrom(istream& is) + { + string bits; + is >> bits; + if (is) + { + resize(bits.size()); + transform(bits.begin(), bits.end(), begin(), + bind2nd(equal_to(), '1')); + } + } +}; + +//----------------------------------------------------------------------------- + +#endif eoBin_h diff --git a/eo/src/eoBreeder.h b/eo/src/obsolete/eoBreeder.h similarity index 92% rename from eo/src/eoBreeder.h rename to eo/src/obsolete/eoBreeder.h index bab14f52c..1cacd7e6a 100644 --- a/eo/src/eoBreeder.h +++ b/eo/src/obsolete/eoBreeder.h @@ -32,9 +32,10 @@ #include #include // eoOp, eoMonOp, eoBinOp #include // eoPop -#include // eoTransform #include // eoOpSelector +#include + #include #include @@ -45,7 +46,8 @@ using namespace std; * For every operator there is a rated to be applyed. * *****************************************************************************/ -template class eoBreeder: public eoMonPopOp +template class eoBreeder: public eoTransform +//eoUnaryFunctor&> { public: /// Default constructor. @@ -62,9 +64,11 @@ template class eoBreeder: public eoMonPopOp { size_t orgsize = pop.size(); - for (unsigned i = 0; i < pop.size(); i++) { - eoOp* op = opSel.Op(); - switch (op->getType()) { + for (unsigned i = 0; i < pop.size(); i++) + { + eoOp* op = opSel.Op(); + switch (op->getType()) + { case eoOp::unary: { eoMonOp* monop = static_cast* >(op); diff --git a/eo/src/eoDetTournamentIndiSelector.h b/eo/src/obsolete/eoDetTournamentIndiSelector.h similarity index 100% rename from eo/src/eoDetTournamentIndiSelector.h rename to eo/src/obsolete/eoDetTournamentIndiSelector.h diff --git a/eo/src/eoDistance.h b/eo/src/obsolete/eoDistance.h similarity index 100% rename from eo/src/eoDistance.h rename to eo/src/obsolete/eoDistance.h diff --git a/eo/src/eoDup.h b/eo/src/obsolete/eoDup.h similarity index 80% rename from eo/src/eoDup.h rename to eo/src/obsolete/eoDup.h index a3ec97665..b41cb7a50 100644 --- a/eo/src/eoDup.h +++ b/eo/src/obsolete/eoDup.h @@ -31,8 +31,8 @@ #include /// Dup or duplicate: duplicates a gene in a chromosome -template -class eoDup: public eoMonOp { +template +class eoDup: public eoMonOp > { public: /// eoDup( ) @@ -42,11 +42,17 @@ public: virtual ~eoDup() {}; /// - virtual void operator()( EOT& _eo ) const + virtual void operator()(eoVariableLength& _eo ) const { - unsigned pos = rng.random(_eo.length()); - _eo.insertGene( pos, _eo.gene(pos) ); - } + unsigned pos = rng.random(_eo.size()); + eoVariableLength::iterator it = begin(); + + while (pos--) {++it;} + + _eo.insert(it, 1, *it); + + _eo.invalidate(); + } /** @name Methods from eoObject diff --git a/eo/src/obsolete/eoES.h b/eo/src/obsolete/eoES.h new file mode 100644 index 000000000..fdc258c3b --- /dev/null +++ b/eo/src/obsolete/eoES.h @@ -0,0 +1,164 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoESChrom.h +// (c) GeNeura Team, 1998 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + */ +//----------------------------------------------------------------------------- + + +#ifndef _eoESCHROM_H +#define _eoESCHROM_H + +// STL libraries +#include // For vector<> +#include +#include +#include // for ostream + +// EO includes +#include + +/**@name Chromosomes for evolution strategies +Each chromosome in an evolution strategies is composed of a vector of floating point +values plus a vector of sigmas, that are added to them during mutation +*/ +//@{ + +/** +\class eoESValue + +*/ +template +struct eoESValue +{ + T value; + + /** + The gene has a mutate member because this particular gaussian mutation + is paradigmatic for an evolution strategy. + */ + void mutate(double sigma, T minimum = T(), T maximum = T()) + { + value += rng.normal(0.0, sigma); + + if (minimum > value) + value = minimum; + if (value > maximum) + value = maximum; + } +}; + +/** +\class eoESGene eoESGene.h es/eoESGene.h +Each gene in an Evolution Strategies is composed of a value plus an standard +deviation, sigma, used for mutation*/ +template +struct eoESGene : public eoESValue +{ + double sigma; + + eoESGene( double _val = 0, double _sigma = 1.0 ): eoESValue( _val ), sigma( _sigma ) {}; + + /** + The gene has a mutate member because the sigma member implies + that the updating routine should use a normal distribution + */ + void mutate(T minimum, T maximum) + { + mutate(sigma, minimum, maximum); + } +}; + +/// Tricky operator to avoid errors in some VC++ systems, namely VC 5.0 SP3 +bool operator < ( eoESGene _e1, eoESGene _e2 ) { + return _e1.val < _e2.val; +} + +/// Tricky operator to avoid errors in some VC++ systems +bool operator == ( eoESGene _e1, eoESGene _e2 ) { + return ( _e1.val == _e2.val ) && ( _e1.sigma == _e2.sigma ) ; +} + +/// +ostream & operator << ( ostream& _s, const eoESGene& _e ) { + _s << _e.val << ", " << _e.sigma << " | "; + return _s; +} + +/// Dummy >> +istream & operator >> ( istream& _s, const eoESGene& _e ) { + _s >> _e.val; + _s >> _e.sigma; + return _s; +} + + +/** Basic chromosome for evolution strategies (ES), as defined by Rechenberg and +Schwefel. Each chromosomes is composed of "genes"; each one of then is an eoESGene +@see eoESGene +*/ +template +class eoESChrom: public eoVector { +public: + /// Basic ctor + eoESChrom( ):eoVector() {}; + + /** Ctor using a couple of random number generators + @param _size Lineal length of the object + @param _rnd a random number generator, which returns a random value each time it´s called. + @param _rndS another one, for the sigma + */ + eoESChrom( unsigned _size, eoRnd& _rnd, eoRnd& _rndS ) + : eoVector( _size ){ + for ( iterator i = begin(); i != end(); i ++ ) { + i->val = _rnd(); + i->sigma = _rndS(); + } + }; + + /// Copy ctor + eoESChrom( const eoESChrom& _eoes): eoVector( _eoes ) {}; + + /// Assignment operator + const eoESChrom& operator =( const eoESChrom & _eoes ) { + if ( this != &_eoes ){ + eoVector::operator=( _eoes ); + } + return *this; + } + + /// + ~eoESChrom() {}; + + /** @name Methods from eoObject + readFrom and printOn are directly inherited from eo1d + */ + //@{ + /** Inherited from eoObject + @see eoObject + */ + string className() const {return "eoESChrom";}; + //@} + +}; + +//@} +#endif + diff --git a/eo/src/es/eoESChrom.h b/eo/src/obsolete/eoESChrom.h similarity index 77% rename from eo/src/es/eoESChrom.h rename to eo/src/obsolete/eoESChrom.h index 495a9ba6c..dc51db0de 100644 --- a/eo/src/es/eoESChrom.h +++ b/eo/src/obsolete/eoESChrom.h @@ -41,11 +41,49 @@ values plus a vector of sigmas, that are added to them during mutation */ //@{ -/** Each gene in an Evolution Strategies is composed of a value plus an standard +/** +\class eoESValue + +*/ +template +struct eoESValue +{ + T value; + + /** + The gene has a mutate member because this particular gaussian mutation + is paradigmatic for an evolution strategy. + */ + void mutate(double sigma, T minimum, T maximum) + { + value += rng.normal(0.0, sigma); + + if (minimum > value) + value = minimum; + if (value > maximum) + value = maximum; + } +}; + +/** +\class eoESGene eoESGene.h es/eoESGene.h +Each gene in an Evolution Strategies is composed of a value plus an standard deviation, sigma, used for mutation*/ -struct eoESGene { - double val, sigma; - eoESGene( double _val = 0, double _sigma = 0 ): val( _val ), sigma( _sigma ) {}; +template +struct eoESGene : public eoESValue +{ + double sigma; + + eoESGene( double _val = 0, double _sigma = 1.0 ): eoESValue( _val ), sigma( _sigma ) {}; + + /** + The gene has a mutate member because the sigma member implies + that the updating routine should use a normal distribution + */ + void mutate(T minimum, T maximum) + { + mutate(sigma, minimum, maximum); + } }; /// Tricky operator to avoid errors in some VC++ systems, namely VC 5.0 SP3 diff --git a/eo/src/es/eoESFullChrom.h b/eo/src/obsolete/eoESFullChrom.h similarity index 94% rename from eo/src/es/eoESFullChrom.h rename to eo/src/obsolete/eoESFullChrom.h index 04090c466..e8e674573 100644 --- a/eo/src/es/eoESFullChrom.h +++ b/eo/src/obsolete/eoESFullChrom.h @@ -48,7 +48,7 @@ Each individual in an evolution strategy is composed of a vector of std deviations a vector of rotation angles (for correlated mutations) -THese individuals CANNOT BE IMPLEMENTED as vectors of anything +These individuals CANNOT BE IMPLEMENTED as vectors of anything at least in the case of correlated mutations */ //@{ @@ -69,18 +69,11 @@ class eoESFullChrom : public eoVector { verbose( _verbose ), ObjMin( _ObjMin ), ObjMax(_ObjMax ), - StdDevInit( _StdDevInit ) {} + StdDevInit( _StdDevInit ) + { // check consistency + } - /// copy constructor - eoESFullChrom( const eoESFullChrom& _eo ): - eoVector ( _eo ), // ObjVar ( _eo.ObjVar ), - StdDev ( _eo.StdDev ), CorCff( _eo.CorCff ), verbose( _eo.verbose ), - ObjMin( _eo.ObjMin ), ObjMax(_eo.ObjMax ), StdDevInit( _eo.StdDevInit ) {} - - /* another constructor, for compatibility reasons */ - eoESFullChrom(istream& _s) { cout << "Not Yet implemented\n";exit(1);}; - /* And now the useful constructor: from a parser (should be in the factory, if such a thing exists one day for eoESFullChrom */ @@ -266,6 +259,9 @@ private: }; + + + #endif diff --git a/eo/src/obsolete/eoESFullMut.h b/eo/src/obsolete/eoESFullMut.h new file mode 100644 index 000000000..5d2d2fa78 --- /dev/null +++ b/eo/src/obsolete/eoESFullMut.h @@ -0,0 +1,261 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoESMute.h : ES mutation +// (c) Maarten Keijzer 2000 & GeNeura Team, 1998 for the EO part +// Th. Baeck 1994 and EEAAX 1999 for the ES part +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + marc.schoenauer@polytechnique.fr + http://eeaax.cmap.polytchnique.fr/ + */ +//----------------------------------------------------------------------------- + + +#ifndef _EOESMUT_H +#define _EOESMUT_H + +#include +#include +#include // for exp + +#include +#include +#include + +#ifndef M_PI +#define M_PI 3.1415926535897932384626433832795 +#endif + +/** ES-style mutation in the large: Obviously, valid only for eoES* + + It is currently valid for three types of ES chromosomes: + + eoEsSimple: only 1 std deviation + eoEsStdev: as many standard deviations as object variables + eoEsFull: The whole guacemole: correlations, stdevs and object variables + + Each of these three variant has it's own operator() in eoEsMutate +*/ + +template +class eoESMutate: public eoMonOp< EOT > { +public: + + typedef EOT::Fitness FitT; + + /** Initialization + parameters: + + @param _init proxy class for initializating the three parameters eoEsMutate needs + @param _bounds the bounds for the objective variables + */ + eoESMutate(eoESMutationInit& _init, eoESObjectiveBounds& _bounds) : bounds(_bounds) + { + unsigned size = bounds.chromSize(); + + if (eoEsInfo::single_stdev) + { + TauLcl = _init.TauLcl(); + TauLcl /= sqrt((double) size); + } + else + { + TauLcl = _init.TauLcl(); + TauGlb = _init.TauGlb(); + + // renormalization + TauLcl /= sqrt( 2.0 * sqrt( (double)size ) ); + TauGlb /= sqrt( 2.0 * ( (double) size ) ); + + if (eoEsInfo::has_correlation) + { // Correlated Mutations + TauBeta = _init.TauBeta(); + } + } + } + + /// needed virtual dtor + virtual ~eoESMutate() {}; + + /** Inherited from eoObject + @see eoObject + */ + virtual string className() const {return "eoESMutate";}; + + /** + Mutate eoEsSimple + */ + virtual void operator()( eoEsSimple& _eo) const + { + _eo.stdev *= exp(TauLcl * rng.normal()); + + if (_eo.stdev < eoEsInfo::stdev_eps) + _eo.stdev = eoEsInfo::stdev_eps; + + // now apply to all + + for (unsigned i = 0; i < _eo.size(); ++i) + { + _eo[i] += _eo.stdev * rng.normal(); + } + + keepInBounds(_eo); + } + + /// mutations - standard and correlated + // ========= + /* + * Standard mutation of object variables and standard + * deviations in ESs. + * If there are fewer different standard deviations available + * than the dimension of the objective function requires, the + * last standard deviation is responsible for ALL remaining + * object variables. + * Schwefel 1977: Numerische Optimierung von Computer-Modellen + * mittels der Evolutionsstrategie, pp. 165 ff. + */ + + virtual void operator()( eoESStdev& _eo ) const + { + double global = exp(TauGlb * rng.normal()); + for (unsigned i = 0; i < _eo.size(); i++) + { + double stdev = _eo.stdevs[i]; + stdev *= global * exp(TauLcl * rng.normal()); + + if (stdev < eoEsInfo::stdev_eps) + stdev = eoEsInfo::stdev_eps; + + _eo.stdevs[i] = stdev; + _eo[i] += stdev * rng.normal(); + } + + keepInBounds(_eo); + } + + /* + * Correlated mutations in ESs, according to the following + * sources: + * H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80 + * p. 43, 1980 + * G. Rudolph: Globale Optimierung mit parallelen Evolutions- + * strategien, Diploma Thesis, University of Dortmund, 1990 + */ + + // Code from Thomas Baeck + + virtual void operator()( eoEsFull & _eo ) const + { + + /* + * First: mutate standard deviations (as above). + */ + + double global = exp(TauGlb * rng.normal()); + for (unsigned i = 0; i < _eo.size(); i++) + { + double stdev = _eo.stdevs[i]; + stdev *= global * exp(TauLcl * rng.normal()); + + if (stdev < eoEsInfo::stdev_eps) + stdev = eoEsInfo::stdev_eps; + + _eo.stdevs[i] = stdev; + } + + + /* + * Mutate rotation angles. + */ + + for (i = 0; i < _eo.correlations.size(); i++) + { + _eo.correlations[i] += TauBeta * rng.normal(); + if ( fabs(_eo.correlations[i]) > M_PI ) + { + _eo.correlations[i] -= M_PI * (int) (_eo.correlations[i]/M_PI) ; + } + } + + /* + * Perform correlated mutations. + */ + unsigned i,k; + + vector VarStp(_eo.size()); + for (i = 0; i < _eo.size(); i++) + VarStp[i] = _eo.stdevs[i] * rng.normal(); + + unsigned nq = _eo.correlations.size() - 1; + + for (k = 0; k < _eo.size()-1; k++) + { + n1 = _eo.size() - k - 1; + n2 = _eo.size() - 1; + + for (i = 0; i < k; i++) + { + d1 = VarStp[n1]; + d2 = VarStp[n2]; + S = sin( _eo.correlations[nq] ); + C = cos( _eo.correlations[nq] ); + VarStp[n2] = d1 * S + d2 * C; + VarStp[n1] = d1 * C - d2 * S; + n2--; + nq--; + } + } + + for (i = 0; i < _eo.size(); i++) + _eo[i] += VarStp[i]; + + keepInBounds(_eo); + } + + void keepInBounds(EOT& _eo) const + { + for (unsigned i = 0; i < _eo.size(); ++i) + { + if (_eo[i] < bounds.minimum(i)) + _eo[i] = bounds.minimum(i); + else if (_eo[i] > bounds.maximum(i)) + _eo[i] = bounds.maximum(i); + } + } + + private : + // the data + //========= + double TauLcl; /* Local factor for mutation of std deviations */ + double TauGlb; /* Global factor for mutation of std deviations */ + double TauBeta; /* Factor for mutation of correlation parameters */ + + eoESObjectiveBounds& bounds; +}; + +/* + * Correlated mutations in ESs, according to the following + * sources: + * H.-P. Schwefel: Internal Report of KFA Juelich, KFA-STE-IB-3/80 + * p. 43, 1980 + * G. Rudolph: Globale Optimierung mit parallelen Evolutions- + * strategien, Diploma Thesis, University of Dortmund, 1990 + */ + +#endif + diff --git a/eo/src/eoEvalFuncPtrCnt.h b/eo/src/obsolete/eoEvalFuncPtrCnt.h similarity index 100% rename from eo/src/eoEvalFuncPtrCnt.h rename to eo/src/obsolete/eoEvalFuncPtrCnt.h diff --git a/eo/src/eoFitTerm.h b/eo/src/obsolete/eoFitTerm.h similarity index 59% rename from eo/src/eoFitTerm.h rename to eo/src/obsolete/eoFitTerm.h index 503756cda..4dded6092 100644 --- a/eo/src/eoFitTerm.h +++ b/eo/src/obsolete/eoFitTerm.h @@ -25,42 +25,34 @@ #ifndef _EOFITTERM_H #define _EOFITTERM_H -#include +#include -/** Fitness termination: terminates after a the difference between the -fitness of the best individual and a maximum fitness to achieve is less -than certain number called epsilon., i.e., |maximum-fitness| -class eoFitTerm: public eoTerm { +class eoFitContinue: public eoContinue { public: - /// Ctors/dtors - eoFitTerm( const float _maximum, const float _epsilon ) - : eoTerm (), maximum( _maximum ), epsilon(_epsilon){}; + /// Define Fitness + typedef typename EOT::Fitness FitnessType; - /// Copy ctor - eoFitTerm( const eoFitTerm& _t ) - : eoTerm ( _t ), maximum( _t.maximum ), - epsilon(_t.epsilon){}; - - /// - virtual ~eoFitTerm() {}; + /// Ctor + eoFitContinue( const FitnessType _maximum) + : eoContinuator (), maximum( _maximum ) {}; /** Returns false when a fitness criterium is - * reached */ - virtual bool operator() ( const eoPop& _vEO ) { - float bestFitness=_vEO[0].fitness(); - float dif=bestFitness-maximum; - dif=(dif<0)?-dif:dif; - return (dif>epsilon ) || (bestFitness > maximum); + * reached, assumes sorted population */ + virtual bool operator() ( const eoPop& _vEO ) + { + return (bestFitness < maximum); } - std::string className(void) const { return "eoFitTerm"; } - private: - float maximum, epsilon; + FitnessType maximum; }; #endif diff --git a/eo/src/eoFitness.h b/eo/src/obsolete/eoFitness.h similarity index 100% rename from eo/src/eoFitness.h rename to eo/src/obsolete/eoFitness.h diff --git a/eo/src/eoGenTerm.h b/eo/src/obsolete/eoGenTerm.h similarity index 76% rename from eo/src/eoGenTerm.h rename to eo/src/obsolete/eoGenTerm.h index a3a0ef19a..6a52cdb8e 100644 --- a/eo/src/eoGenTerm.h +++ b/eo/src/obsolete/eoGenTerm.h @@ -25,36 +25,19 @@ #ifndef _EOGENTERM_H #define _EOGENTERM_H -#include +#include -/** Generational termination: terminates after a number of generations +/** Generational continuator: continues until a number of generations is reached */ template< class EOT> -class eoGenTerm: public eoTerm { +class eoGenContinue: public eoContinue { public: /// Ctors/dtors - eoGenTerm( unsigned _totalGens) - : eoTerm (), repTotalGenerations( _totalGens ), + eoGenContinue( unsigned _totalGens) + : repTotalGenerations( _totalGens ), thisGeneration(0){}; - /// Copy Ctor - eoGenTerm( const eoGenTerm& _t) - : eoTerm ( _t ), repTotalGenerations( _t.repTotalGenerations ), - thisGeneration(0){}; - - /// Assignment Operator - const eoGenTerm& operator = ( const eoGenTerm& _t) { - if ( &_t != this ) { - repTotalGenerations = _t.repTotalGenerations; - thisGeneration = 0; - } - return *this; - } - - /// Dtor - virtual ~eoGenTerm() {}; - /** Returns false when a certain number of generations is * reached */ virtual bool operator() ( const eoPop& _vEO ) { diff --git a/eo/src/eoGeneration.h b/eo/src/obsolete/eoGeneration.h similarity index 96% rename from eo/src/eoGeneration.h rename to eo/src/obsolete/eoGeneration.h index 01d2bbf25..93cdfd3be 100644 --- a/eo/src/eoGeneration.h +++ b/eo/src/obsolete/eoGeneration.h @@ -26,7 +26,6 @@ #define eoGeneration_h //----------------------------------------------------------------------------- -#include #include // eoPop #include #include // eoSelect, eoTranform, eoMerge @@ -41,8 +40,8 @@ template class eoGeneration: public eoAlgo { public: /// Constructor. - eoGeneration(eoBinPopOp& _select, - eoMonPopOp& _transform, + eoGeneration(eoSelect& _select, + eoBreeder& _breeder, eoBinPopOp& _replace, eoEvalFunc& _evaluator): select(_select), transform(_transform), diff --git a/eo/src/eoID.h b/eo/src/obsolete/eoID.h similarity index 100% rename from eo/src/eoID.h rename to eo/src/obsolete/eoID.h diff --git a/eo/src/eoInclusion.h b/eo/src/obsolete/eoInclusion.h similarity index 100% rename from eo/src/eoInclusion.h rename to eo/src/obsolete/eoInclusion.h diff --git a/eo/src/eoInsertion.h b/eo/src/obsolete/eoInsertion.h similarity index 94% rename from eo/src/eoInsertion.h rename to eo/src/obsolete/eoInsertion.h index 6f9616a8e..39c65b1ae 100644 --- a/eo/src/eoInsertion.h +++ b/eo/src/obsolete/eoInsertion.h @@ -40,7 +40,7 @@ * from the original population. *****************************************************************************/ -template class eoInsertion: public eoMerge +template class eoInsertion: public eoBinaryFunctor&, const eoPop&> { public: /// (Default) Constructor. @@ -57,7 +57,7 @@ template class eoInsertion: public eoMerge * @param breeders The population of breeders. Should be sorted to work correctly * @param pop The original population. */ - void operator()( eoPop& _breeders, eoPop& _pop) + void operator()( eoPop& _breeders, const eoPop& _pop) { unsigned target = static_cast((_pop.size() * rate())); diff --git a/eo/src/eoKill.h b/eo/src/obsolete/eoKill.h similarity index 100% rename from eo/src/eoKill.h rename to eo/src/obsolete/eoKill.h diff --git a/eo/src/eoLottery.h b/eo/src/obsolete/eoLottery.h similarity index 94% rename from eo/src/eoLottery.h rename to eo/src/obsolete/eoLottery.h index a79b83da6..a96c54e46 100644 --- a/eo/src/eoLottery.h +++ b/eo/src/obsolete/eoLottery.h @@ -30,6 +30,7 @@ #include // logic_error #include // sum_fitness +#include // #include // // #include // accumulate @@ -44,7 +45,7 @@ */ //----------------------------------------------------------------------------- -template class eoLottery: public eoBinPopOp +template class eoLottery: public eoBinaryFunctor&, eoPop& > { public: /// (Default) Constructor. @@ -61,7 +62,7 @@ template class eoLottery: public eoBinPopOp * BUT what happens if breeders is already too big? * Too big for what? */ - void operator()( eoPop& pop, eoPop& breeders) + void operator()(const eoPop& pop, eoPop& breeders) { size_t target = static_cast(rate_ * pop.size()); diff --git a/eo/src/eoMutation.h b/eo/src/obsolete/eoMutation.h similarity index 100% rename from eo/src/eoMutation.h rename to eo/src/obsolete/eoMutation.h diff --git a/eo/src/eoNegExp.h b/eo/src/obsolete/eoNegExp.h similarity index 100% rename from eo/src/eoNegExp.h rename to eo/src/obsolete/eoNegExp.h diff --git a/eo/src/eoNonUniform.h b/eo/src/obsolete/eoNonUniform.h similarity index 100% rename from eo/src/eoNonUniform.h rename to eo/src/obsolete/eoNonUniform.h diff --git a/eo/src/eoNormal.h b/eo/src/obsolete/eoNormal.h similarity index 100% rename from eo/src/eoNormal.h rename to eo/src/obsolete/eoNormal.h diff --git a/eo/src/eoPopOps.h b/eo/src/obsolete/eoPopOps.h similarity index 100% rename from eo/src/eoPopOps.h rename to eo/src/obsolete/eoPopOps.h diff --git a/eo/src/eoRandomBreed.h b/eo/src/obsolete/eoRandomBreed.h similarity index 100% rename from eo/src/eoRandomBreed.h rename to eo/src/obsolete/eoRandomBreed.h diff --git a/eo/src/eoRandomIndiSelector.h b/eo/src/obsolete/eoRandomIndiSelector.h similarity index 100% rename from eo/src/eoRandomIndiSelector.h rename to eo/src/obsolete/eoRandomIndiSelector.h diff --git a/eo/src/eoRandomSelect.h b/eo/src/obsolete/eoRandomSelect.h similarity index 100% rename from eo/src/eoRandomSelect.h rename to eo/src/obsolete/eoRandomSelect.h diff --git a/eo/src/eoRank.h b/eo/src/obsolete/eoRank.h similarity index 83% rename from eo/src/eoRank.h rename to eo/src/obsolete/eoRank.h index 1412bc8a9..67d6707f3 100644 --- a/eo/src/eoRank.h +++ b/eo/src/obsolete/eoRank.h @@ -48,21 +48,14 @@ */ template -class eoRank: public eoSelect{ +class eoRank: public eoSelect, public eoObject, public eoPrintable +{ public: /// Ctor eoRank( unsigned _newPopSize, eoOpSelector& _opSelector) - :eoSelect(), opSelector( _opSelector ), repNewPopSize( _newPopSize ) {}; - - /** Copy ctor - * Needs a copy ctor for the EO operators */ - eoRank( const eoRank& _rankBreeder) - :eoSelect( _rankBreeder), - - opSelector( _rankBreeder.opSelector ), repNewPopSize( _rankBreeder.repNewPopSize ) {}; - + /// Dtor virtual ~eoRank() {}; @@ -79,12 +72,10 @@ class eoRank: public eoSelect{ for ( unsigned i = 0; i < repNewPopSize; i ++ ) { // Create a copy of a random input EO with copy ctor. The members of the - // population will be selected by rank, with a certain probability of - // being selected several times if the new population is bigger than the - // old + EOT newEO = _ptVeo[ i%inLen ]; // Choose operator @@ -128,22 +119,9 @@ class eoRank: public eoSelect{ virtual string className() const { return "eoRank"; }; - - - /** Print itself: inherited from eoObject implementation. Declared virtual so that - - it can be reimplemented anywhere. Instance from base classes are processed in - - base classes, so you don´t have to worry about, for instance, fitness. - - @param _s the ostream in which things are written*/ - - virtual void printOn( ostream& _s ) const{ - - _s << opSelector; - - _s << repNewPopSize; - + virtual void printOn( ostream& _s ) const + { + _s << repNewPopSize; }; diff --git a/eo/src/eoRnd.h b/eo/src/obsolete/eoRnd.h similarity index 100% rename from eo/src/eoRnd.h rename to eo/src/obsolete/eoRnd.h diff --git a/eo/src/eoScheme.h b/eo/src/obsolete/eoScheme.h similarity index 100% rename from eo/src/eoScheme.h rename to eo/src/obsolete/eoScheme.h diff --git a/eo/src/other/eoStringMutation.h b/eo/src/obsolete/eoStringMutation.h similarity index 94% rename from eo/src/other/eoStringMutation.h rename to eo/src/obsolete/eoStringMutation.h index 5cebc8ebc..ee8590dea 100644 --- a/eo/src/other/eoStringMutation.h +++ b/eo/src/obsolete/eoStringMutation.h @@ -28,7 +28,7 @@ #include // EO includes #include -#include +#include #include /** Mutation of an eoString. @@ -65,9 +65,8 @@ class eoStringMutation: public eoMutation { /// applies operator to one gene in the EO. It increments or decrements the value of that gene by one. virtual void applyAt( EOT& _eo, unsigned _i ) const { - eoUniform uniform( 0, 1 ); if( rate < uniform() ) { - _eo.gene(_i) += ( uniform()>=0.5 )? (1) : (-1) ; + _eo.gene(_i) += ( rng.flip(0.5))? (1) : (-1) ; } } diff --git a/eo/src/eoTerm.h b/eo/src/obsolete/eoTerm.h similarity index 100% rename from eo/src/eoTerm.h rename to eo/src/obsolete/eoTerm.h diff --git a/eo/src/eoTournament.h b/eo/src/obsolete/eoTournament.h similarity index 100% rename from eo/src/eoTournament.h rename to eo/src/obsolete/eoTournament.h diff --git a/eo/src/eoTranspose.h b/eo/src/obsolete/eoTranspose.h similarity index 51% rename from eo/src/eoTranspose.h rename to eo/src/obsolete/eoTranspose.h index 111da025a..7d2a8d74c 100644 --- a/eo/src/eoTranspose.h +++ b/eo/src/obsolete/eoTranspose.h @@ -2,7 +2,7 @@ //----------------------------------------------------------------------------- // eoTranspose.h -// (c) GeNeura Team, 1998 +// (c) GeNeura Team, 1998 Maarten Keijzer 2000 /* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -25,66 +25,69 @@ #ifndef _EOTRANSPOSE_h #define _EOTRANSPOSE_h +#include +#include + #include - #include - -/** Transposition operator: interchanges the position of two genes -of an EO. These positions must be defined by an only index, that is, -EOT must subclass eo1d +#include +#include +/** +Transposition operator: interchanges the position of two genes +of an EO. */ template -class eoTranspose: public eoMonOp { +class eoTranspose: public eoMonOp +{ public: - /// - eoTranspose() - : eoMonOp< EOT >( ){}; - /// needed virtual dtor - virtual ~eoTranspose() {}; + // Specialization for a vector + void operator()(eoFixedLength& _eo ) + { + unsigned pos1 = rng.random(_eo.size()), + pos2 = rng.random(_eo.size()); - /// - virtual void operator()( EOT& _eo ) const { - unsigned pos1 = uniform(), - pos2 = rng.random(_eo.length()); - applyAt( _eo, pos1, pos2 ); + if (pos1 != pos2) + swap(_eo[pos1], _eo[pos2]); + + if (_eo[pos1] != _eo[pos2]) + _eo.invalidate(); + } + + // Specialization for a list + void operator()(eoVariableLength& _eo ) + { + unsigned pos1 = rng.random(_eo.size()), + pos2 = rng.random(_eo.size()); + + if (pos1 == pos2) + return; + + if (pos1 > pos2) + swap(pos1,pos2); + + pos2 -= pos1; + + typename EOT::iterator it1 = _eo.begin(); + + while (pos1--) {it1++;} + + typename EOT::iterator it2 = it1; + + while (pos2--) {it2++;} + + swap(*it1, *it2); + + if (*it1 != *it2) + _eo.invalidate(); } - /** @name Methods from eoObject - readFrom and printOn are directly inherited from eoOp - */ - //@{ /** Inherited from eoObject @see eoObject */ virtual string className() const {return "eoTranspose";}; //@} - -private: - -#ifdef _MSC_VER - typedef EOT::Type Type; -#else - typedef typename EOT::Type Type; -#endif - - /** applies operator to one gene in the EO - @param _eo victim of transposition - @param i, j positions of the genes that are going to be changed - @throw runtime_exception if the positions to write are incorrect - */ - virtual void applyAt( EOT& _eo, unsigned _i, unsigned _j) const { - try { - Type tmp = _eo.gene( _i ); - _eo.gene( _i ) = _eo.gene( _j ); - _eo.gene( _j ) = tmp; - } catch ( exception& _e ) { - string msg = _e.what(); - msg += "Caught exception at eoTranspose"; - throw runtime_error( msg.c_str() ); - } - } - + }; #endif diff --git a/eo/src/eoUniform.h b/eo/src/obsolete/eoUniform.h similarity index 100% rename from eo/src/eoUniform.h rename to eo/src/obsolete/eoUniform.h diff --git a/eo/src/eoUniformXOver.h b/eo/src/obsolete/eoUniformXOver.h similarity index 100% rename from eo/src/eoUniformXOver.h rename to eo/src/obsolete/eoUniformXOver.h diff --git a/eo/src/eoVector.h b/eo/src/obsolete/eoVector.h similarity index 100% rename from eo/src/eoVector.h rename to eo/src/obsolete/eoVector.h diff --git a/eo/src/eoXOver2.h b/eo/src/obsolete/eoXOver2.h similarity index 100% rename from eo/src/eoXOver2.h rename to eo/src/obsolete/eoXOver2.h diff --git a/eo/src/other/eoExternalEO.h b/eo/src/other/eoExternalEO.h index 5094a7ecf..37e1036af 100644 --- a/eo/src/other/eoExternalEO.h +++ b/eo/src/other/eoExternalEO.h @@ -40,8 +40,6 @@ class eoExternalEO : public EO, virtual public External { public : - typedef External Type; - eoExternalEO(void) : EO(), External() {} /** diff --git a/eo/src/other/eoExternalOpFunctions.h b/eo/src/other/eoExternalOpFunctions.h index b27dd93b1..73620b412 100644 --- a/eo/src/other/eoExternalOpFunctions.h +++ b/eo/src/other/eoExternalOpFunctions.h @@ -30,7 +30,7 @@ #include #include -#include +#include #include /** @@ -41,18 +41,20 @@ Where External is the user defined struct or class */ -template -class eoExternalInit : public eoRnd > +template > +class eoExternalInit : public eoInit { public : - - typedef eoExternalEO ExternalEO; eoExternalInit(External (*_init)(void)) : init(_init) {} - ExternalEO operator()(void) { return (*init)(); } + void operator()(ExternalEO& _eo) + { + _eo = (*init)(); + _eo.invalidate(); + } private : @@ -67,18 +69,17 @@ private : Where External is the user defined struct or class and Fit the fitness type */ -template -class eoExternalEvalFunc : public eoEvalFunc > +template > +class eoExternalEvalFunc : public eoEvalFunc { public : - typedef eoExternalEO ExternalEO; - eoExternalEvalFunc(F (*_eval)(const External&)) : eval(_eval) {} - void operator()(ExternalEO& eo) const + void operator()(ExternalEO& eo) { - eo.fitness( (*eval)(eo) ); + if (eo.invalid()) + eo.fitness( (*eval)(eo) ); } private : @@ -90,88 +91,86 @@ class eoExternalEvalFunc : public eoEvalFunc > Mutation of external struct, ctor expects a function of the following signature: - void func(External&); + bool func(External&); - Where External is the user defined struct or class + + Where External is the user defined struct or class. + The function should return true when it changed something, false otherwise */ -template -class eoExternalMonOp : public eoMonOp > +template > +class eoExternalMonOp : public eoMonOp { public : - typedef eoExternalEO ExternalEO; + eoExternalMonOp(bool (*_mutate)(External&)) : mutate(_mutate) {} - eoExternalMonOp(void (*_mutate)(External&)) : mutate(_mutate) {} - - void operator()(ExternalEO& eo) const + void operator()(ExternalEO& eo) { - (*mutate)(eo); - eo.invalidate(); + if ((*mutate)(eo)) + eo.invalidate(); } private : - void (*mutate)(External&); + bool (*mutate)(External&); }; /** Crossover of external struct, ctor expects a function of the following signature: - void func(External&, const External&); + bool func(External&, const External&); Where External is the user defined struct or class + The function should return true when it changed something, false otherwise */ -template -class eoExternalBinOp : public eoBinOp > +template > +class eoExternalBinOp : public eoBinOp { public : - typedef eoExternalEO ExternalEO; + eoExternalBinOp(bool (*_binop)(External&, const External&)) : binop(_binop) {} - eoExternalBinOp(void (*_binop)(External&, const External&)) : binop(_binop) {} - - void operator()(ExternalEO& eo1, const ExternalEO& eo2) const + void operator()(ExternalEO& eo1, const ExternalEO& eo2) { - (*binop)(eo1, eo2); - eo1.invalidate(); + if ((*binop)(eo1, eo2)) + eo1.invalidate(); } private : - void (*binop)(External&, const External&); + bool (*binop)(External&, const External&); }; /** Crossover of external struct, ctor expects a function of the following signature: - void func(External&, External&); + bool func(External&, External&); Where External is the user defined struct or class + The function should return true when it changed something, false otherwise */ -template -class eoExternalQuadraticOp : public eoQuadraticOp > +template > +class eoExternalQuadraticOp : public eoQuadraticOp { public : - typedef eoExternalEO ExternalEO; + eoExternalQuadraticOp(bool (*_quadop)(External&, External&)) : quadop(_quadop) {} - eoExternalQuadraticOp(void (*_quadop)(External&, External&)) : quadop(_quadop) {} - - void operator()(ExternalEO& eo1, ExternalEO& eo2) const + void operator()(ExternalEO& eo1, ExternalEO& eo2) { - (*quadop)(eo1, eo2); - eo1.invalidate(); - eo2.invalidate(); + if ((*quadop)(eo1, eo2)) + { + eo1.invalidate(); + eo2.invalidate(); + } } private : - void (*quadop)(External&, External&); + bool (*quadop)(External&, External&); }; - - #endif diff --git a/eo/src/other/eoString.h b/eo/src/other/eoString.h index d1ba55b44..88e6d4636 100644 --- a/eo/src/other/eoString.h +++ b/eo/src/other/eoString.h @@ -31,105 +31,23 @@ using namespace std; -// EO headers -#include - //----------------------------------------------------------------------------- // eoString //----------------------------------------------------------------------------- /** Adaptor that turns an STL string into an EO */ template -class eoString: public eo1d, public string { +class eoString: public EO, public string +{ public: + typedef char Type; + /// Canonical part of the objects: several ctors, copy ctor, dtor and assignment operator //@{ /// ctor eoString( const string& _str ="" ) - : eo1d(), string( _str ) {}; - - - /** Ctor using a random number generator - @param _size Lineal length of the object - @param _rnd a random number generator, which returns a random value each time it´s called - */ - eoString( unsigned _size, eoRnd& _rnd ) - : eo1d(), string(){ - for ( unsigned i = 0; i < _size; i ++ ) { - *this += _rnd(); - } - }; - - /** Ctor from a stream - @param _s input stream - */ - eoString( istream & _s ) - : eo1d(){ - _s >> *this; - }; - - /// copy ctor - eoString( const eoString& _eoStr ) - :eo1d( static_cast & > ( _eoStr ) ), - string( _eoStr ){}; - - /// Assignment operator - const eoString& operator =( const eoString& _eoStr ) { - if ( this != & _eoStr ) { - eo1d::operator = ( _eoStr ); - string::operator = ( _eoStr ); - } - return *this; - } - - /// dtor - virtual ~eoString() {}; -//@} - - - /** methods that implement the eo1d protocol - @exception out_of_range if _i is larger than EO´s size - */ - virtual char getGene( unsigned _i ) const { - if ( _i >= length() ) - throw out_of_range( "out_of_range when reading gene"); - return (*this)[_i]; - }; - - /** methods that implement the eo1d protocol - @exception out_of_range if _i is larger than EO´s size - */ - virtual void setGene( unsigned _i, const char& _value ) { - if ( _i >= size() ) - throw out_of_range( "out_of_range when writing a gene"); - (*this)[_i] = _value; - }; - - /** Inserts a value after _i, displacing anything to the right - @exception out_of_range if _i is larger than EO´s size - */ - virtual void insertGene( unsigned _i, char _val ) { - if (_i <= this->size() ) { - string::iterator i = this->begin()+_i; - this->insert( i, _val ); - } else - throw out_of_range( "out_of_range when inserting gene"); - }; - - /** Eliminates the gene at position _i - @exception out_of_range if _i is larger than EO´s size - */ - virtual void deleteGene( unsigned _i ) { - if (_i < this->size() ) { - string::iterator i = this->begin()+_i; - this->erase( i ); - } else - throw out_of_range( "out_of_range when deleting gene"); - }; - - /// methods that implement the EO protocol - virtual unsigned length() const { return this->size(); }; + : string( _str ) {}; /** @name Methods from eoObject readFrom and printOn are directly inherited from eo1d diff --git a/eo/src/utils/Makefile.am b/eo/src/utils/Makefile.am index 455e723ba..77beb7501 100644 --- a/eo/src/utils/Makefile.am +++ b/eo/src/utils/Makefile.am @@ -7,7 +7,9 @@ INCLUDES = -I$(top_builddir)/src lib_LIBRARIES = libeoutils.a -libeoutils_a_SOURCES = eoParser.cpp eoRNG.cpp eoState.cpp eoUpdater.cpp eoFileMonitor.cpp +libeoutils_a_SOURCES = eoParser.cpp eoRNG.cpp eoState.cpp eoUpdater.cpp eoFileMonitor.cpp eoStdoutMonitor.cpp libeoincdir = $(includedir)/eo/utils -libeoinc_HEADERS = compatibility.h eoParam.h eoRNG.h rnd_generators.h eoData.h eoParser.h eoState.h selectors.h eoStat.h eoMonitor.h eoFileMonitor.h eoUpdater.h checkpointing eoCheckPoint.h +libeoinc_HEADERS = compatibility.h eoParam.h eoRNG.h rnd_generators.h eoData.h eoParser.h eoState.h selectors.h eoStat.h eoMonitor.h eoFileMonitor.h eoUpdater.h checkpointing eoCheckPoint.h eoStdoutMonitor.h + + diff --git a/eo/src/utils/checkpointing b/eo/src/utils/checkpointing index f13ac85a7..dba79bcef 100644 --- a/eo/src/utils/checkpointing +++ b/eo/src/utils/checkpointing @@ -2,5 +2,6 @@ #include #include #include +#include #include #include \ No newline at end of file diff --git a/eo/src/utils/eoCheckPoint.h b/eo/src/utils/eoCheckPoint.h index 537b60cda..c7abcef7b 100644 --- a/eo/src/utils/eoCheckPoint.h +++ b/eo/src/utils/eoCheckPoint.h @@ -27,30 +27,30 @@ #ifndef _eoCheckPoint_h #define _eoCheckPoint_h -#include +#include template class eoStatBase; class eoMonitor; class eoUpdater; template -class eoCheckPoint : public eoTerm +class eoCheckPoint : public eoContinue { public : - eoCheckPoint(eoTerm& _term) : term(_term) {} + eoCheckPoint(eoContinue& _cont) : cont(_cont) {} bool operator()(const eoPop& _pop); void add(eoStatBase& _stat) { stats.push_back(&_stat); } - void add(eoMonitor& _mon) { monitors.push_back(&_mon); } - void add(eoUpdater& _upd) { updaters.push_back(&_upd); } + void add(eoMonitor& _mon) { monitors.push_back(&_mon); } + void add(eoUpdater& _upd) { updaters.push_back(&_upd); } std::string className(void) const { return "eoCheckPoint"; } private : - eoTerm& term; + eoContinue& cont; std::vector*> stats; std::vector monitors; std::vector updaters; @@ -69,7 +69,7 @@ bool eoCheckPoint::operator()(const eoPop& _pop) for (i = 0; i < monitors.size(); ++i) (*monitors[i])(); - return term(_pop); + return cont(_pop); } #endif \ No newline at end of file diff --git a/eo/src/utils/eoFileMonitor.cpp b/eo/src/utils/eoFileMonitor.cpp index 43dbeb607..241f715ff 100644 --- a/eo/src/utils/eoFileMonitor.cpp +++ b/eo/src/utils/eoFileMonitor.cpp @@ -23,13 +23,13 @@ eoMonitor& eoFileMonitor::operator()(void) throw runtime_error(str); } - iterator it = begin(); + iterator it = vec.begin(); os << (*it)->longName(); ++it; - for (; it != end(); ++it) + for (; it != vec.end(); ++it) { os << ',' << (*it)->longName(); } @@ -44,11 +44,11 @@ eoMonitor& eoFileMonitor::operator()(void) throw runtime_error(str); } - iterator it = begin(); + iterator it = vec.begin(); os << '\n' << (*it)->getValue(); - for(++it; it != end(); ++it) + for(++it; it != vec.end(); ++it) { os << ',' << (*it)->getValue(); } diff --git a/eo/src/utils/eoMonitor.h b/eo/src/utils/eoMonitor.h index d79d8245e..e4e44e3fa 100644 --- a/eo/src/utils/eoMonitor.h +++ b/eo/src/utils/eoMonitor.h @@ -20,7 +20,7 @@ Contact: todos@geneura.ugr.es, http://geneura.ugr.es Marc.Schoenauer@polytechnique.fr - mkeijzer@dhi.dk + mak@dhi.dk */ //----------------------------------------------------------------------------- @@ -30,6 +30,8 @@ #include +#include + class eoParam; /** @@ -39,16 +41,16 @@ class eoParam; will stream or pipe the current values of the parameters to wherever you want it streamed or piped to. */ -class eoMonitor : public std::vector +class eoMonitor : public eoProcedure { public : - virtual ~eoMonitor() {} + void add(const eoParam& _param) { vec.push_back(&_param); } - /** Just do it! */ - virtual eoMonitor& operator()(void) = 0; - void add(const eoParam& _param) { push_back(&_param); } +protected : + typedef std::vector::iterator iterator; + std::vector vec; }; #endif \ No newline at end of file diff --git a/eo/src/utils/eoParam.h b/eo/src/utils/eoParam.h index 4dba2c3ba..dfd6b3fa4 100644 --- a/eo/src/utils/eoParam.h +++ b/eo/src/utils/eoParam.h @@ -187,8 +187,10 @@ void eoValueParam::setValue(std::string _value) /// Because MSVC does not support partial specialization, the pair is a double, not a T template <> std::string eoValueParam >::getValue(void) const -{ - std::ostrstream os; +{ + // use own buffer as MSVC's buffer leaks! + char buff[1024]; + std::ostrstream os(buff, 1024); os << repValue.first << ' ' << repValue.second << std::ends; return os.str(); } diff --git a/eo/src/utils/eoRNG.cpp b/eo/src/utils/eoRNG.cpp index a3950638f..fadc1aa23 100644 --- a/eo/src/utils/eoRNG.cpp +++ b/eo/src/utils/eoRNG.cpp @@ -1,5 +1,7 @@ #include #include "eoRNG.h" +/// The global object, should probably be initialized with an xor +/// between time and process_id. eoRng rng((uint32) time(0)); diff --git a/eo/src/utils/eoRNG.h b/eo/src/utils/eoRNG.h index 1dcd0a616..235847465 100644 --- a/eo/src/utils/eoRNG.h +++ b/eo/src/utils/eoRNG.h @@ -176,7 +176,15 @@ public : { return mean + normal(stdev); } - + + /** + Generates random numbers using a negative exponential distribution + */ + double negexp(double mean) + { + return ( -mean*log((double)rand() / rand_max())); + } + /** rand() returns a random number in the range [0, rand_max) */ @@ -273,55 +281,6 @@ private : */ extern eoRng rng; -/** - The class uniform_generator can be used in the STL generate function - to easily generate random floats and doubles between [0, _max). _max - defaults to 1.0 -*/ -template class uniform_generator -{ - public : - uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {} - - virtual T operator()(void) { return (T) uniform.uniform(maxim); } - private : - T maxim; - eoRng& uniform; -}; - -/** - The class random_generator can be used in the STL generate function - to easily generate random ints between [0, _max). -*/ -template class random_generator -{ - public : - random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {} - - virtual T operator()(void) { return (T) random.random(max); } - - private : - T maxim; - eoRng& random; -}; - -/** - The class normal_generator can be used in the STL generate function - to easily generate gaussian distributed floats and doubles. The user - can supply a standard deviation which defaults to 1. -*/ -template class normal_generator -{ - public : - normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {} - - virtual T operator()(void) { return (T) normal.normal(stdev); } - - private : - T stdev; - eoRng& normal; -}; - // Implementation of some eoRng members.... Don't mind the mess, it does work. diff --git a/eo/src/utils/eoStat.h b/eo/src/utils/eoStat.h index 78b1778c6..a7d3c72f1 100644 --- a/eo/src/utils/eoStat.h +++ b/eo/src/utils/eoStat.h @@ -27,11 +27,12 @@ #ifndef _eoStat_h #define _eoStat_h +#include #include #include template -class eoStatBase +class eoStatBase : public eoUnaryFunctor&> { public : virtual ~eoStatBase(){} @@ -98,7 +99,7 @@ public : double n = _pop.size(); value().first = result.first / n; // average - value().second = sqrt( (result.second - value().first) / (n - 1.0)); // stdev + value().second = sqrt( (result.second - n * value().first * value().first) / (n - 1.0)); // stdev } }; diff --git a/eo/src/utils/eoStdoutMonitor.cpp b/eo/src/utils/eoStdoutMonitor.cpp new file mode 100644 index 000000000..23ec63bbe --- /dev/null +++ b/eo/src/utils/eoStdoutMonitor.cpp @@ -0,0 +1,37 @@ +#include +#include +#include + +#include +#include +#include + +using namespace std; + +eoMonitor& eoStdoutMonitor::operator()(void) +{ + if (firsttime) + { + cout << "First Generation" << endl; + + firsttime = false; + + } + // ok, now the real saving. write out + + if (!cout) + { + string str = "eoStdoutMonitor: Could not write to cout"; + throw runtime_error(str); + } + + for(iterator it = vec.begin(); it != vec.end(); ++it) + { + cout << (*it)->longName() << ": " << (*it)->getValue() << '\n'; + } + + cout << "\n****** End of Generation ******\n\n"; + + return *this; +} + diff --git a/eo/src/utils/eoStdoutMonitor.h b/eo/src/utils/eoStdoutMonitor.h new file mode 100644 index 000000000..b9667e6f4 --- /dev/null +++ b/eo/src/utils/eoStdoutMonitor.h @@ -0,0 +1,49 @@ +// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- + +//----------------------------------------------------------------------------- +// eoFileMonitor.h +// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 +/* + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + Contact: todos@geneura.ugr.es, http://geneura.ugr.es + Marc.Schoenauer@polytechnique.fr + mkeijzer@dhi.dk + */ +//----------------------------------------------------------------------------- + +#ifndef _eoStdoutMonitor_h +#define _eoStdoutMonitor_h + +#include + +#include +#include + +/** + Prints statistics to stdout +*/ +class eoStdoutMonitor : public eoMonitor +{ +public : + eoStdoutMonitor(std::string _delim = "\t") : delim(_delim), firsttime(true) {} + eoMonitor& operator()(void); + +private : + std::string delim; + bool firsttime; +}; + +#endif diff --git a/eo/src/utils/eoUpdater.h b/eo/src/utils/eoUpdater.h index f877bf113..db096749c 100644 --- a/eo/src/utils/eoUpdater.h +++ b/eo/src/utils/eoUpdater.h @@ -27,21 +27,15 @@ #ifndef _eoUpdater_h #define _eoUpdater_h +#include +#include + /** eoUpdater is a generic procudere for updating whatever you want. - It is about as abstract as you can get. + Yet again an empty name */ -class eoUpdater -{ -public : - /// virtual classes have virtual dtors - virtual ~eoUpdater(void) {} - - /** - does the work, what it is is quite undefined - */ - virtual void operator()(void) = 0; -}; +class eoUpdater : public eoProcedure +{}; /** */ diff --git a/eo/src/utils/rnd_generators.h b/eo/src/utils/rnd_generators.h index 5074af013..a8c6ceb1c 100644 --- a/eo/src/utils/rnd_generators.h +++ b/eo/src/utils/rnd_generators.h @@ -43,12 +43,27 @@ template class uniform_generator public : uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : maxim(_max), uniform(_rng) {} - virtual T operator()(void) { return (T) uniform.uniform(maxim); } + T operator()(void) { return (T) uniform.uniform(maxim); } private : T maxim; eoRng& uniform; }; +/** + The class boolean_generator can be used in the STL generate function + to easily generate random booleans with a specified bias +*/ +class boolean_generator +{ + public : + boolean_generator(float _bias = 0.5, eoRng& _rng = rng) : bias(_bias), gen(_rng) {} + + bool operator()(void) { return gen.flip(0.5); } + private : + float bias; + eoRng& gen; +}; + /** The class random_generator can be used in the STL generate function to easily generate random ints between [0, _max). @@ -56,15 +71,23 @@ template class uniform_generator template class random_generator { public : - random_generator(int _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {} + random_generator(T _max, eoRng& _rng = rng) : maxim(_max), random(_rng) {} - virtual T operator()(void) { return (T) random.random(max); } + T operator()(void) { return (T) random.random(max); } private : T maxim; eoRng& random; }; +/// Specialization for bool +template <> +bool random_generator::operator()(void) +{ + return random.flip(0.5); +} + + /** The class normal_generator can be used in the STL generate function to easily generate gaussian distributed floats and doubles. The user @@ -75,11 +98,28 @@ template class normal_generator public : normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {} - virtual T operator()(void) { return (T) normal.normal(stdev); } + T operator()(void) { return (T) normal.normal(stdev); } private : T stdev; eoRng& normal; }; +/** + The class negexp_generator can be used in the STL generate function + to easily generate negative exponential distributed floats and doubles. The user + can supply a mean. +*/ +template class negexp_generator +{ + public : + negexp_generator(T _mean = 1.0, eoRng& _rng = rng) : mean(_mean), negexp(_rng) {} + + T operator()(void) { return (T) negexp.negexp(mean); } + + private : + T mean; + eoRng& negexp; +}; + #endif diff --git a/eo/test/Makefile.am b/eo/test/Makefile.am index 022798ca0..1b40b10c9 100644 --- a/eo/test/Makefile.am +++ b/eo/test/Makefile.am @@ -13,46 +13,7 @@ LDADDS = $(top_builddir)/src/libeo.a $(top_builddir)/src/obsolete/libeoobsolete. ############################################################################### -noinst_PROGRAMS = t-eobreeder t-eoinclusion t-eoinsertion t-eo t-eofitness \ - t-eoproblem t-eobin t-eolottery t-eo2dVector t-eogeneration t-eoEasyEA\ - t-eoNonUniform t-eoUniform t-eoRandom t-eoStateAndParser \ - t-eoAtomOps t-selectOne t-eoGOpSel \ - t-eoVector t-eoCheckpointing t-eoExternalEO t-eoESFull - -############################################################################### - -t_eoVector_SOURCES = t-eoVector.cpp -t_eoVector_DEPENDENCIES = $(DEPS) -t_eoVector_LDFLAGS = -lm -t_eoVector_LDADD = $(LDADDS) - -############################################################################### - -t_eoGOpSel_SOURCES = t-eoGOpSel.cpp -t_eoGOpSel_DEPENDENCIES = $(DEPS) -t_eoGOpSel_LDFLAGS = -lm -t_eoGOpSel_LDADD = $(LDADDS) - -############################################################################### - -t_selectOne_SOURCES = t-selectOne.cpp -t_selectOne_DEPENDENCIES = $(DEPS) -t_selectOne_LDFLAGS = -lm -t_selectOne_LDADD = $(LDADDS) - -############################################################################### - -t_eoAtomOps_SOURCES = t-eoAtomOps.cpp -t_eoAtomOps_DEPENDENCIES = $(DEPS) -t_eoAtomOps_LDFLAGS = -lm -t_eoAtomOps_LDADD = $(LDADDS) - -############################################################################### -#disabled -#t_eoESOps_SOURCES = t-eoESOps.cpp -#t_eoESOps_DEPENDENCIES = $(DEPS) -#t_eoESOps_LDFLAGS = -lm -#t_eoESOps_LDADD = $(LDADDS) +noinst_PROGRAMS = t-eofitness t-eobin t-eoStateAndParser t-eoCheckpointing t-eoExternalEO t-eoESFull ############################################################################### @@ -63,99 +24,18 @@ t_eoESFull_LDADD = $(LDADDS) ############################################################################### -t_eoNonUniform_SOURCES = t-eoNonUniform.cpp -t_eoNonUniform_DEPENDENCIES = $(DEPS) -t_eoNonUniform_LDFLAGS = -lm -t_eoNonUniform_LDADD = $(LDADDS) - -############################################################################### - -t_eoUniform_SOURCES = t-eoUniform.cpp -t_eoUniform_DEPENDENCIES = $(DEPS) -t_eoUniform_LDFLAGS = -lm -t_eoUniform_LDADD = $(LDADDS) - -############################################################################### - -t_eoRandom_SOURCES = t-eoRandom.cpp -t_eoRandom_DEPENDENCIES = $(DEPS) -t_eoRandom_LDFLAGS = -lm -t_eoRandom_LDADD = $(LDADDS) - -############################################################################### - -t_eogeneration_SOURCES = t-eogeneration.cpp -t_eogeneration_DEPENDENCIES = $(DEPS) -t_eogeneration_LDFLAGS = -lm -t_eogeneration_LDADD = $(LDADDS) - -############################################################################### - -t_eoEasyEA_SOURCES = t-eoEasyEA.cpp binary_value.h -t_eoEasyEA_DEPENDENCIES = $(DEPS) -t_eoEasyEA_LDFLAGS = -lm -t_eoEasyEA_LDADD = $(LDADDS) - -############################################################################### - -t_eobreeder_SOURCES = t-eobreeder.cpp binary_value.h -t_eobreeder_DEPENDENCIES = $(DEPS) -t_eobreeder_LDFLAGS = -lm -t_eobreeder_LDADD = $(LDADDS) - -############################################################################### - -t_eoinclusion_SOURCES = t-eoinclusion.cpp -t_eoinclusion_DEPENDENCIES = $(DEPS) -t_eoinclusion_LDFLAGS = -lm -t_eoinclusion_LDADD = $(LDADDS) - -############################################################################### - -t_eoinsertion_SOURCES = t-eoinsertion.cpp -t_eoinsertion_DEPENDENCIES = $(DEPS) -t_eoinsertion_LDFLAGS = -lm -t_eoinsertion_LDADD = $(LDADDS) - -############################################################################### - -t_eo_SOURCES = t-eo.cpp -t_eo_DEPENDENCIES = $(DEPS) -t_eo_LDADD = $(LDADDS) - -############################################################################### - t_eofitness_SOURCES = t-eofitness.cpp t_eofitness_DEPENDENCIES = $(DEPS) t_eofitness_LDADD = $(LDADDS) ############################################################################### -t_eoproblem_SOURCES = t-eoproblem.cpp -t_eoproblem_LDFLAGS = -lm - -############################################################################### - t_eobin_SOURCES = t-eobin.cpp t_eobin_DEPENDENCIES = $(DEPS) t_eobin_LDADD = $(LDADDS) ############################################################################### -t_eolottery_SOURCES = t-eolottery.cpp -t_eolottery_DEPENDENCIES = $(DEPS) -t_eolottery_LDFLAGS = -lm -t_eolottery_LDADD = $(LDADDS) - -############################################################################### - -t_eo2dVector_SOURCES = t-eo2dVector.cc -t_eo2dVector_DEPENDENCIES = $(DEPS) -t_eo2dVector_LDFLAGS = -lm -t_eo2dVector_LDADD = $(LDADDS) - -############################################################################### - t_eoStateAndParser_SOURCES = t-eoStateAndParser.cpp t_eoStateAndParser_DEPENDENCIES = $(DEPS) t_eoStateAndParser_LDFLAGS = -lm diff --git a/eo/test/real_value.h b/eo/test/real_value.h index c6b30b6c1..b176edfdb 100644 --- a/eo/test/real_value.h +++ b/eo/test/real_value.h @@ -1,4 +1,4 @@ -#include +#include //----------------------------------------------------------------------------- @@ -7,7 +7,7 @@ @param _ind A floatingpoint vector */ -double real_value(const eoFixedLength& _ind) +double real_value(const std::vector& _ind) { double sum = 0; /* compute in double format, even if return a float */ for (unsigned i = 0; i < _ind.size(); i++) diff --git a/eo/test/t-eoBaseFunctions.cpp b/eo/test/t-eoBaseFunctions.cpp new file mode 100644 index 000000000..052c1f4f4 --- /dev/null +++ b/eo/test/t-eoBaseFunctions.cpp @@ -0,0 +1,26 @@ + +#include + +#include + +using namespace std; + +struct eo1 : public eoProcedure +{ + void operator()(void) {} +}; + +struct eo2 : public eoProcedure +{ + int operator()(void) { return 1; } +}; + +int main() +{ + eo1 _1; _1(); + eo2 _2; + int i = _2(); + + cout << i << '\n'; + return i; +} \ No newline at end of file diff --git a/eo/test/t-eoCheckpointing.cpp b/eo/test/t-eoCheckpointing.cpp index 612890475..282bbb0b5 100644 --- a/eo/test/t-eoCheckpointing.cpp +++ b/eo/test/t-eoCheckpointing.cpp @@ -18,12 +18,11 @@ #include #include #include - +#include //----------------------------------------------------------------------------- // include package checkpointing #include -#include struct Dummy : public EO { @@ -74,7 +73,7 @@ int the_main(int argc, char **argv) eoDummyPop pop; - eoGenTerm genTerm(5); // run for 5 generations + eoGenContinue genTerm(5); // run for 5 generations eoCheckPoint checkpoint(genTerm); // The algorithm will now quit after five generations diff --git a/eo/test/t-eoESFull.cpp b/eo/test/t-eoESFull.cpp index 08e17b7cd..2333bb27a 100644 --- a/eo/test/t-eoESFull.cpp +++ b/eo/test/t-eoESFull.cpp @@ -9,20 +9,11 @@ #include #include #include +#include using namespace std; -#include -#include - -#include -#include - -// population -#include - -// evaluation specific -#include +#include // representation specific #include @@ -31,7 +22,7 @@ using namespace std; // Now the main /////////////// -typedef double FitT; +typedef eoMinimizingFitness FitT; template void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoEsObjectiveBounds& _bounds); @@ -45,9 +36,9 @@ main(int argc, char *argv[]) eoValueParam& seed = parser.createParam(static_cast(time(0)), "seed", "Random number seed"); eoValueParam& load_name = parser.createParam(string(), "Load","Load a state file",'L'); eoValueParam& save_name = parser.createParam(string(), "Save","Saves a state file",'S'); - eoValueParam& stdevs = parser.createParam(true, "Stdev", "Use adaptive mutation rates", 's'); - eoValueParam& corr = parser.createParam(true, "Correl", "Use correlated mutations", 'c'); - eoValueParam& chromSize = parser.createParam(unsigned(1), "ChromSize", "Number of chromosomes", 'n'); + eoValueParam& stdevs = parser.createParam(false, "Stdev", "Use adaptive mutation rates", 's'); + eoValueParam& corr = parser.createParam(false, "Correl", "Use correlated mutations", 'c'); + eoValueParam& chromSize = parser.createParam(unsigned(50), "ChromSize", "Number of chromosomes", 'n'); eoValueParam& minimum = parser.createParam(-1.e5, "Min", "Minimum for Objective Variables", 'l'); eoValueParam& maximum = parser.createParam(1.e5, "Max", "Maximum for Objective Variables", 'h'); @@ -57,7 +48,9 @@ main(int argc, char *argv[]) if (!load_name.value().empty()) { // load the parser. This is only neccessary when the user wants to - // be able to change the parameters in the state file by hand. + // be able to change the parameters in the state file by hand + // Note that only parameters inserted in the parser at this point + // will be loaded!. state.load(load_name.value()); // load the parser } @@ -94,15 +87,15 @@ template void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoEsObjectiveBounds& _bounds) { // evaluation - eoEvalFuncPtr > eval( real_value ); + eoEvalFuncPtr&> eval( real_value ); // population parameters, unfortunately these can not be altered in the state file eoValueParam mu = _parser.createParam(unsigned(50), "mu","Size of the population"); - eoValueParamlambda = _parser.createParam(unsigned(250), "lambda", "No. of children to produce"); + eoValueParamlambda_rate = _parser.createParam(float(7.0), "lambda_rate", "Factor of children to produce"); - if (mu.value() > lambda.value()) + if (lambda_rate.value() < 1.0f) { - throw logic_error("Mu must be smaller than lambda in a comma strategy"); + throw logic_error("lambda_rate must be larger than 1 in a comma strategy"); } // Initialization @@ -112,7 +105,7 @@ void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoEsObjectiveBounds& _state.registerObject(pop); // evaluate initial population - eval.range(pop.begin(), pop.end()); + apply(eval, pop); // Ok, time to set up the algorithm // Proxy for the mutation parameters @@ -122,29 +115,20 @@ void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoEsObjectiveBounds& // monitoring, statistics etc. eoAverageStat average; - eoFileMonitor monitor("test.csv"); + eoStdoutMonitor monitor; monitor.add(average); - // Okok, I'm lazy, here's the algorithm defined inline + eoGenContinue cnt(2000); + eoCheckPoint checkpoint(cnt); + checkpoint.add(monitor); + checkpoint.add(average); - for (unsigned i = 0; i < 20; ++i) - { - pop.resize(pop.size() + lambda.value()); - for (unsigned j = mu.value(); j < pop.size(); ++j) - { - pop[j] = pop[rng.random(mu.value())]; - mutate(pop[j]); - eval(pop[j]); - } + eoProportionalGOpSel opSel; + opSel.addOp(mutate, 1.0); - // comma strategy - std::sort(pop.begin() + mu.value(), pop.end()); - copy(pop.begin() + mu.value(), pop.begin() + 2 * mu.value(), pop.begin()); - pop.resize(mu.value()); - - average(pop); - monitor(); - } + eoEvolutionStrategy es(checkpoint, eval, opSel, lambda_rate.value(), eoEvolutionStrategy::comma_strategy()); + + es(pop); } diff --git a/eo/test/t-eoExternalEO.cpp b/eo/test/t-eoExternalEO.cpp index debcb1c49..c880ba215 100644 --- a/eo/test/t-eoExternalEO.cpp +++ b/eo/test/t-eoExternalEO.cpp @@ -55,7 +55,7 @@ UserDefStruct RandomStruct() // reading and writing -void UserDefMutate(UserDefStruct& a) +bool UserDefMutate(UserDefStruct& a) { cout << "UserDefMutate\n"; a = RandomStruct(); // just for testing @@ -64,9 +64,10 @@ void UserDefMutate(UserDefStruct& a) a.d = UserDefStruct::test; else a.d = UserDefStruct::another; + return true; } -void UserDefBinCrossover(UserDefStruct& a, const UserDefStruct& b) +bool UserDefBinCrossover(UserDefStruct& a, const UserDefStruct& b) { cout << "UserDefBinCrossover\n"; @@ -78,9 +79,10 @@ void UserDefBinCrossover(UserDefStruct& a, const UserDefStruct& b) a.c = b.c; if (rng.flip(0.5)) a.d = b.d; + return true; } -void UserDefQuadCrossover(UserDefStruct& a, UserDefStruct& b) +bool UserDefQuadCrossover(UserDefStruct& a, UserDefStruct& b) { cout << "UserDefQuadCrossover\n"; if (rng.flip(0.5)) @@ -91,6 +93,8 @@ void UserDefQuadCrossover(UserDefStruct& a, UserDefStruct& b) swap(a.c, b.c); if (rng.flip(0.5)) swap(a.d, b.d); + + return true; } float UserDefEvalFunc(const UserDefStruct& a) @@ -112,8 +116,10 @@ int main() // eoExternalEvalFunc eval(UserDefEvalFunc); - EoType eo1 = init(); - EoType eo2 = init(); + EoType eo1; + init(eo1); + EoType eo2; + init(eo2); cout << "before mutation " << eo1 << '\n'; mutate(eo1); diff --git a/eo/test/t-eoFunctor.cpp b/eo/test/t-eoFunctor.cpp new file mode 100644 index 000000000..ab46f8e3c --- /dev/null +++ b/eo/test/t-eoFunctor.cpp @@ -0,0 +1,53 @@ + +#include +#include + +void f(eoInit& func) +{ + int i; + func(i); +} + +class Tester : public eoInit +{ +public : + void operator()(int& i) + { + i=1; + } +}; + +#include +#include +#include +#include + +using namespace std; + +int main(void) +{ + Tester test; + + eoFunctorStore store; + + /// make a counter and store it in 'store' + eoInit& cntr = make_counter(functor_category(test), test, store); + + eoUnaryFunctorCounter > cntr2(test); + + f(cntr); + f(cntr2); + f(cntr2); + f(test); + + typedef eoVariableLength EoType; + EoType eo; + + eo.push_back(1); + eo.push_back(2); + + eoTranspose transpose; + transpose(eo); + + return 1; +} \ No newline at end of file diff --git a/eo/test/t-eoStateAndParser.cpp b/eo/test/t-eoStateAndParser.cpp index fad70b243..f1548dfce 100644 --- a/eo/test/t-eoStateAndParser.cpp +++ b/eo/test/t-eoStateAndParser.cpp @@ -23,7 +23,6 @@ // include package checkpointing #include -#include struct Dummy : public EO { diff --git a/eo/test/t-eobin.cpp b/eo/test/t-eobin.cpp index 93cc9da0c..0d91e002c 100644 --- a/eo/test/t-eobin.cpp +++ b/eo/test/t-eobin.cpp @@ -27,13 +27,15 @@ #include // ostrstream, istrstream #include // eoBin +#include "binary_value.h" + //----------------------------------------------------------------------------- typedef eoBin Chrom; //----------------------------------------------------------------------------- -main() +void main_function() { const unsigned SIZE = 8; unsigned i, j; @@ -52,19 +54,22 @@ main() cout << "chrom: " << chrom << endl << "chrom2: " << chrom2 << endl; - ostrstream os; + char buff[1024]; + ostrstream os(buff, 1024); os << chrom; istrstream is(os.str()); is >> chrom2; - cout << "chrom: " << chrom << endl - << "chrom2: " << chrom2 << endl; + cout << "\nTesting reading, writing\n"; + cout << "chrom: " << chrom << "\nchrom2: " << chrom2 << '\n'; fill(chrom.begin(), chrom.end(), false); cout << "--------------------------------------------------" << endl << "eoMonOp's aplied to .......... " << chrom << endl; - eoBinRandom random; + eoInitFixedLength + random(chrom.size(), boolean_generator()); + random(chrom); cout << "after eoBinRandom ............ " << chrom << endl; @@ -120,16 +125,41 @@ main() cout << "eoBinGxOver(" << i << ", " << j << ") ..... " << chrom << " " << chrom2 << endl; } - - for (double r = 0.1; r < 1.0; r += 0.1) - { - eoUniformXOver uxover(r); - fill(chrom.begin(), chrom.end(), false); - fill(chrom2.begin(), chrom2.end(), true); - uxover(chrom, chrom2); - cout << "eoBinUxOver(" << r << ") ...... " - << chrom << " " << chrom2 << endl; - } + + // test SGA algorithm + eoGenContinue continuator1(50); + eoFitContinue continuator2(65535.f); + + eoCombinedContinue continuator(continuator1, continuator2); + + eoCheckPoint checkpoint(continuator); + + eoStdoutMonitor monitor; + + checkpoint.add(monitor); + + eoSecondMomentStats stats; + + monitor.add(stats); + checkpoint.add(stats); + + eoProportional select; + eoEvalFuncPtr eval(binary_value); + + eoSGA sga(checkpoint, bitflip, 0.1f, xover, 0.8f, select, eval); + + eoInitFixedLength + init(16, boolean_generator()); + eoPop pop(100, init); + + apply(eval, pop); + //for_each(pop.begin(), pop.end(), eval); + + sga(pop); + + pop.sort(); + + cout << "\nBest: " << pop[0].fitness() << '\n'; /* @@ -149,8 +179,31 @@ main() mbOp( chrom, chrom2 ); cout << "after multiBinOp .............. " << chrom << " " << chrom2 < +#endif + +int main() +{ +#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(); + } + catch(exception& e) + { + cout << "Exception: " << e.what() << '\n'; + } + + return 1; +} \ No newline at end of file diff --git a/eo/test/t-eobreeder.cpp b/eo/test/t-eobreeder.cpp index 9672acc9d..80560a4d3 100644 --- a/eo/test/t-eobreeder.cpp +++ b/eo/test/t-eobreeder.cpp @@ -75,7 +75,7 @@ main() breeder(pop); // reevaluation of fitness - for_each(pop.begin(), pop.end(), eval); + for_each(pop.begin(), pop.end(), BinaryValue()); cout << "new population:" << endl; for (i = 0; i < pop.size(); ++i) diff --git a/eo/test/t-eofitness.cpp b/eo/test/t-eofitness.cpp index 9973444a3..041a69077 100644 --- a/eo/test/t-eofitness.cpp +++ b/eo/test/t-eofitness.cpp @@ -1,175 +1,91 @@ //----------------------------------------------------------------------------- - // t-eofitness.cpp - // (c) GeNeura Team 1998 - //----------------------------------------------------------------------------- - - #include // time - #include // srand, rand - #include // cout -#include // eoFitness - +#include +using namespace std; //----------------------------------------------------------------------------- - - -class eoFloat: public eoFitness - +template +int test_fitness(Fitness a, Fitness b) { +// srand(time(0)); -public: - - eoFloat(const float x) { fitness = x; } - - eoFloat(const int x) { fitness = static_cast(x); } - - - - bool operator<(const eoFitness& other) const - - { - - const eoFloat& x = (const eoFloat&) other; - - return fitness < x.fitness; - - } - - - - operator float() const - - { - - return fitness; - - } - - - - void printOn(ostream& os) const - - { - - os << fitness; - - } - - - - void readFrom(istream& is) - - { - - is >> fitness; - - } - - - -private: - - float fitness; - -}; - - - -//----------------------------------------------------------------------------- - - - -int main() - -{ - - srand(time(0)); - - - - eoFloat a = static_cast(rand()) / RAND_MAX, - - b = static_cast(rand()) / RAND_MAX; - - +// Fitness a = aval; //static_cast(rand()) / RAND_MAX; +// Fitness b = bval; //static_cast(rand()) / RAND_MAX; cout.precision(2); - - unsigned repeat = 2; - while (repeat--) - { - cout << "------------------------------------------------------" << endl; - cout << "testing < "; - if (a < b) - cout << a << " < " << b << " is true" << endl; - else - cout << a << " < " << b << " is false" < "; - if (a > b) - cout << a << " > " << b << " is true" << endl; - else - cout << a << " > " << b << " is false" < ############################################################################### +Project: "t_eoFunctor"=.\t_eoFunctor.dsp - Package Owner=<4> + +Package=<5> +{{{ +}}} + +Package=<4> +{{{ + Begin Project Dependency + Project_Dep_Name eo + End Project Dependency +}}} + +############################################################################### + Project: "t_eoGOpSel"=.\t_eoGOpSel.dsp - Package Owner=<4> Package=<5> diff --git a/eo/win/esfull.dsp b/eo/win/esfull.dsp index ffa566ab9..791ddeb06 100644 --- a/eo/win/esfull.dsp +++ b/eo/win/esfull.dsp @@ -96,10 +96,6 @@ SOURCE="..\test\t-eoESFull.cpp" # PROP Default_Filter "h;hpp;hxx;hm;inl" # Begin Source File -SOURCE=..\src\es\eoEsBase.h -# End Source File -# Begin Source File - SOURCE=..\src\es\eoEsChromInit.h # End Source File # Begin Source File @@ -126,6 +122,14 @@ SOURCE=..\src\es\eoEsSimple.h SOURCE=..\src\es\eoEsStdev.h # End Source File +# Begin Source File + +SOURCE=..\src\eoFixedLength.h +# End Source File +# Begin Source File + +SOURCE=..\test\real_value.h +# End Source File # End Group # Begin Group "Resource Files" diff --git a/eo/win/t_eoFunctor.dsp b/eo/win/t_eoFunctor.dsp new file mode 100644 index 000000000..35bd33611 --- /dev/null +++ b/eo/win/t_eoFunctor.dsp @@ -0,0 +1,104 @@ +# Microsoft Developer Studio Project File - Name="t_eoFunctor" - Package Owner=<4> +# Microsoft Developer Studio Generated Build File, Format Version 6.00 +# ** DO NOT EDIT ** + +# TARGTYPE "Win32 (x86) Console Application" 0x0103 + +CFG=t_eoFunctor - Win32 Debug +!MESSAGE This is not a valid makefile. To build this project using NMAKE, +!MESSAGE use the Export Makefile command and run +!MESSAGE +!MESSAGE NMAKE /f "t_eoFunctor.mak". +!MESSAGE +!MESSAGE You can specify a configuration when running NMAKE +!MESSAGE by defining the macro CFG on the command line. For example: +!MESSAGE +!MESSAGE NMAKE /f "t_eoFunctor.mak" CFG="t_eoFunctor - Win32 Debug" +!MESSAGE +!MESSAGE Possible choices for configuration are: +!MESSAGE +!MESSAGE "t_eoFunctor - Win32 Release" (based on "Win32 (x86) Console Application") +!MESSAGE "t_eoFunctor - Win32 Debug" (based on "Win32 (x86) Console Application") +!MESSAGE + +# Begin Project +# PROP AllowPerConfigDependencies 0 +# PROP Scc_ProjName "" +# PROP Scc_LocalPath "" +CPP=cl.exe +RSC=rc.exe + +!IF "$(CFG)" == "t_eoFunctor - Win32 Release" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 0 +# PROP BASE Output_Dir "t_eoFunctor___Win32_Release" +# PROP BASE Intermediate_Dir "t_eoFunctor___Win32_Release" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 0 +# PROP Output_Dir "t_eoFunctor___Win32_Release" +# PROP Intermediate_Dir "t_eoFunctor___Win32_Release" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c +# ADD BASE RSC /l 0x409 /d "NDEBUG" +# ADD RSC /l 0x409 /d "NDEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 + +!ELSEIF "$(CFG)" == "t_eoFunctor - Win32 Debug" + +# PROP BASE Use_MFC 0 +# PROP BASE Use_Debug_Libraries 1 +# PROP BASE Output_Dir "t_eoFunctor___Win32_Debug" +# PROP BASE Intermediate_Dir "t_eoFunctor___Win32_Debug" +# PROP BASE Target_Dir "" +# PROP Use_MFC 0 +# PROP Use_Debug_Libraries 1 +# PROP Output_Dir "t_eoFunctor___Win32_Debug" +# PROP Intermediate_Dir "t_eoFunctor___Win32_Debug" +# PROP Target_Dir "" +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /I "../src" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c +# ADD BASE RSC /l 0x409 /d "_DEBUG" +# ADD RSC /l 0x409 /d "_DEBUG" +BSC32=bscmake.exe +# ADD BASE BSC32 /nologo +# ADD BSC32 /nologo +LINK32=link.exe +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept + +!ENDIF + +# Begin Target + +# Name "t_eoFunctor - Win32 Release" +# Name "t_eoFunctor - Win32 Debug" +# Begin Group "Source Files" + +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" +# Begin Source File + +SOURCE=..\src\eoFunctorStore.cpp +# End Source File +# Begin Source File + +SOURCE="..\test\t-eoFunctor.cpp" +# End Source File +# End Group +# Begin Group "Header Files" + +# PROP Default_Filter "h;hpp;hxx;hm;inl" +# End Group +# Begin Group "Resource Files" + +# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" +# End Group +# End Target +# End Project diff --git a/eo/win/t_eobin.dsp b/eo/win/t_eobin.dsp index ba1079bdf..40d036423 100644 --- a/eo/win/t_eobin.dsp +++ b/eo/win/t_eobin.dsp @@ -75,7 +75,7 @@ BSC32=bscmake.exe # ADD BSC32 /nologo LINK32=link.exe # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 eo.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept +# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept !ENDIF