Extreme cleanup, see src/obsolete for details

This commit is contained in:
mac 2000-08-10 14:18:34 +00:00
commit 6d8e3a6504
141 changed files with 3937 additions and 1815 deletions

View file

@ -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

View file

@ -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

View file

@ -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
//@{

View file

@ -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

41
eo/src/apply.h Normal file
View file

@ -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 <eoFunctor.h>
#include <vector>
template <class EOT>
void apply(eoUnaryFunctor<void, EOT&>& _proc, std::vector<EOT>& _pop)
{
for (unsigned i = 0; i < _pop.size(); ++i)
{
_proc(_pop[i]);
}
}
#endif

View file

@ -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 <eoObject.h>
#include <eoPrintable.h>
#include <eoPersistent.h>
#include <eoFitness.h>
#include <eoScalarFitness.h>
#include <EO.h>
#include <eoID.h>
#include <utils/rnd_generators.h>
#include <eoFunctor.h>
#include <apply.h>
#include <eoVector.h>
#include <eo1d.h>
// eo's
#include <eoVariableLength.h>
#include <eoFixedLength.h>
//#include <eoID.h>
//#include <eoVector.h>
//#include <eo1d.h>
#include <other/eoString.h>
#include <ga/eoBin.h>
#include <eoRnd.h>
#include <eoUniform.h>
#include <eoNormal.h>
#include <eoNegExp.h>
#include <eoInit.h>
//#include <eoUniform.h>
//#include <eoNormal.h>
//#include <eoNegExp.h>
#include <eoOp.h>
#include <eoDup.h>
#include <eoKill.h>
#include <eoTranspose.h>
#include <eoXOver2.h>
#include <eoUniformXOver.h>
#include <eoMutation.h>
//#include <eoDup.h>
//#include <eoKill.h>
//#include <eoTranspose.h>
//#include <eoXOver2.h>
//#include <eoUniformXOver.h>
//#include <eoMutation.h>
#include <eoPop.h>
#include <eoPopOps.h>
#include <eoMerge.h>
#include <ga/eoBitOp.h>
// Evaluation functions
#include <eoEvalFunc.h>
#include <eoEvalFuncPtr.h>
// Terminators
#include <eoTerm.h>
#include <eoGenTerm.h>
#include <eoFitTerm.h>
// Continuators
#include <eoContinue.h>
#include <eoCombinedContinue.h>
#include <eoGenContinue.h>
#include <eoFitContinue.h>
// Selection and reproduction stuff
#include <eoUniformSelect.h>
#include <eoSelectOne.h>
#include <eoSelectRandom.h>
#include <eoDetTournament.h>
#include <eoProportional.h>
#include <eoStochTournament.h>
#include <eoLottery.h>
#include <eoBreeder.h>
#include <eoInsertion.h>
#include <eoInclusion.h>
#include <eoGeneration.h>
#include <eoProportionalOpSel.h>
#include <eoProportionalGOpSel.h>
#include <eoSequentialGOpSel.h>
//#include <eoLottery.h>
//#include <eoBreeder.h>
//#include <eoInsertion.h>
//#include <eoInclusion.h>
//#include <eoGeneration.h>
//#include <eoProportionalOpSel.h>
// Algorithms
#include <eoEasyEA.h>
#include <eoSGA.h>
#include <eoSteadyStateEA.h>
#include <eoEvolutionStrategy.h>
// Utils
#include <utils/checkpointing>
// aliens
#include <eoNonUniform.h>
//#include <eoNonUniform.h>
//-----------------------------------------------------------------------------
// to be continued ...
//-----------------------------------------------------------------------------
/*
#include <eoFitness.h>
#include <eoProblem.h>
//#include <eoFitness.h>
//#include <eoProblem.h>
*/
//-----------------------------------------------------------------------------

View file

@ -26,30 +26,18 @@
#define _EOALGO_H
#include <eoPop.h> // for population
#include <eoFunctor.h>
/** 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<void, eoPop<EOT>&>
{};
/// 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<EOT>& _pop ) = 0;
};
#endif

69
eo/src/eoBreed.h Normal file
View file

@ -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 <eoPop.h>
#include <eoFunctor.h>
//-----------------------------------------------------------------------------
/**
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 EOT>
class eoBreed : public eoBinaryFunctor<void, const eoPop<EOT>&, eoPop<EOT>&>
{};
/**
eoSelectTransform: special breeder that is just an application of an embedded select,
followed by an embedded transform
*/
template <class EOT>
class eoSelectTransform : public eoBreed<EOT>
{
public:
eoSelectTransform(eoSelect<EOT>& _select, eoTransform<EOT>& _transform) :
select(_select), transform(_transform)
{}
void operator()(const eoPop<EOT>& _parents, eoPop<EOT>& _offspring)
{
select(_parents, _offspring);
transform(_offspring);
}
private :
eoSelect<EOT>& select;
eoTransform<EOT>& transform;
};
#endif

View file

@ -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 <eoContinue.h>
/**
Fitness continuation:
Continues until one of the embedded continuators says halt!
*/
template< class EOT>
class eoCombinedContinue: public eoContinue<EOT> {
public:
/// Define Fitness
typedef typename EOT::Fitness FitnessType;
/// Ctor
eoCombinedContinue( eoContinue<EOT>& _arg1, eoContinue<EOT>& _arg2)
: eoContinue<EOT> (), arg1(_arg1), arg2(_arg2) {};
/** Returns false when one of the embedded continuators say so (logical and)
*/
virtual bool operator() ( const eoPop<EOT>& _pop )
{
return arg1(_pop) && arg2(_pop);
}
private:
eoContinue<EOT>& arg1;
eoContinue<EOT>& arg2;
};
#endif

View file

@ -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 <eoExternalEO.h>
#include <eoOp.h>
#include <utils/eoRNG.h>
#include <eoFunctor.h>
#include <eoPop.h>
template <class F, class External>
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<bool, const eoPop<EOT>&> {};
#endif

110
eo/src/eoCopyElite.h Normal file
View file

@ -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.h> // eoPop
#include <eoFunctor.h> // 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 Chrom> class eoCopyElite: public eoBinaryFunctor<void, const eoPop<Chrom>&, eoPop<Chrom>&>
{};
/**
Straightforward elitism class, specify the number of individuals to copy
into new geneneration
*/
template <class EOT> class eoElitism : public eoCopyElite<EOT>
{
public :
eoElitism(unsigned _howmany) : howmany(_howmany) {}
void operator()(const eoPop<EOT>& _pop, eoPop<EOT>& offspring)
{
if (howmany == 0)
return;
if (howmany > _pop.size())
throw logical_error("Elite larger than population");
vector<const EOT*> 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 EOT> class eoNoElitism : public eoElitism<EOT>
{
public :
eoNoElitism() : eoElitism(0) {}
}
/**
Very elitist class, copies entire population into next gen
*/
template <class EOT> class eoPlus : public eoCopyElite<EOT>
{
public :
void operator()(const eoPop<EOT>& _pop, eoPop<EOT>& offspring)
{
offspring.reserve(offspring.size() + _pop.size());
for (int i = 0; i < _pop.size(); ++i)
{
offspring.push_back(*result[i]);
}
}
private :
unsigned howmany;
};
//-----------------------------------------------------------------------------
#endif

219
eo/src/eoCounter.h Normal file
View file

@ -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 <eoFunctor.h>
#include <eoFunctorStore.h>
#include <utils/eoParam.h>
/**
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 Procedure>
class eoProcedureCounter : public Procedure, public eoValueParam<unsigned long>
{
public:
eoProcedureCounter(Procedure& _proc, std::string _name = "proc_counter")
: proc(_proc), eoValueParam<unsigned long>(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<void, EoType> evalCounter(myeval);
and use evalCounter now instead of myeval.
*/
template <class UnaryFunctor>
class eoUnaryFunctorCounter : public UnaryFunctor, public eoValueParam<unsigned long>
{
public:
eoUnaryFunctorCounter(UnaryFunctor& _func, std::string _name = "uf_counter")
: func(_func), eoValueParam<unsigned long>(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 BinaryFunctor>
class eoBinaryFunctorCounter : public BinaryFunctor, public eoValueParam<unsigned long>
{
public:
eoBinaryFunctorCounter(BinaryFunctor& _func, std::string _name = "proc_counter")
: func(_func), eoValueParam<unsigned long>(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<EOT>), by
simply stating:
eoEval<EOT>& myCounted = make_counter(functor_category(myEval), myEval, store)
@see eoFunctorBase, functor_category, eoFunctorStore
*/
template <class Procedure>
eoProcedureCounter<Procedure>& make_counter(eoFunctorBase::procedure_tag, Procedure& _proc, eoFunctorStore& store, std::string _name = "proc_counter")
{
eoProcedureCounter<Procedure>* result = new eoProcedureCounter<Procedure>(_proc, _name);
store.add(result);
return *result;
}
template <class UnaryFunctor>
eoUnaryFunctorCounter<UnaryFunctor>& make_counter(eoFunctorBase::unary_function_tag, UnaryFunctor& _proc, eoFunctorStore& store, std::string _name = "uf_counter")
{
eoUnaryFunctorCounter<UnaryFunctor>* result = new eoUnaryFunctorCounter<UnaryFunctor>(_proc, _name);
store.add(result);
return *result;
}
template <class BinaryFunctor>
eoBinaryFunctorCounter<BinaryFunctor>& make_counter(eoFunctorBase::binary_function_tag, BinaryFunctor& _proc, eoFunctorStore& store, std::string _name = "uf_counter")
{
eoBinaryFunctorCounter<BinaryFunctor>* result = new eoBinaryFunctorCounter<BinaryFunctor>(_proc, _name);
store.add(result);
return *result;
}
#endif

View file

@ -30,8 +30,10 @@
#include <functional> //
#include <numeric> // accumulate
#include "eoPopOps.h" // eoPop eoSelect MINFLOAT
#include "utils/selectors.h"
#include <eoFunctor.h>
#include <eoPop.h>
#include <utils/selectors.h>
//-----------------------------------------------------------------------------
/** eoDetTournament: a selection method that selects ONE individual by
@ -51,15 +53,11 @@ template <class EOT> class eoDetTournament: public eoSelectOne<EOT>
}
}
/// Perform deterministic tournament
virtual const EOT& operator()(const eoPop<EOT>& pop)
{
return deterministic_tournament(pop, Tsize);
}
/** Inherited from eoObject
@see eoObject
*/
string className() const {return "eoDetTournament";};
private:
unsigned Tsize;

View file

@ -57,7 +57,6 @@ public :
EOT& eo = inverse_deterministic_tournament<EOT>(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;
}

View file

@ -27,59 +27,139 @@
//-----------------------------------------------------------------------------
#include <eoGeneration.h> // eoPop
#include <eoTerm.h>
#include <eoAlgo.h>
#include <eoContinue.h>
#include <eoSelect.h>
#include <eoTransform.h>
#include <eoBreed.h>
#include <eoMerge.h>
#include <eoReduce.h>
#include <eoReplacement.h>
/** 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 Chrom> class eoEasyEA: public eoAlgo<Chrom>
template<class EOT> class eoEasyEA: public eoAlgo<EOT>
{
public:
/// Constructor.
eoEasyEA(eoBinPopOp<Chrom>& _select,
eoMonPopOp<Chrom>& _transform,
eoBinPopOp<Chrom>& _replace,
eoEvalFunc<Chrom>& _evaluator,
eoTerm<Chrom>& _terminator)
:step(_select, _transform, _replace, _evaluator),
terminator( _terminator){};
/// Constructor from an already created generation
eoEasyEA(eoGeneration<Chrom>& _gen,
eoTerm<Chrom>& _terminator):
step(_gen),
terminator( _terminator){};
/// Apply one generation of evolution to the population.
virtual void operator()(eoPop<Chrom>& pop) {
while ( terminator( pop ) ) {
/// Ctor taking a breed and merge.
eoEasyEA(
eoContinue<EOT>& _continuator,
eoEvalFunc<EOT>& _eval,
eoBreed<EOT>& _breed,
eoReplacement<EOT>& _replace
) : continuator(_continuator),
eval(_eval),
selectTransform(0),
breed(_breed),
mergeReduce(0),
replace(_replace)
{}
/// Ctor eoBreed, eoMerge and eoReduce.
eoEasyEA(
eoContinue<EOT>& _continuator,
eoEvalFunc<EOT>& _eval,
eoBreed<EOT>& _breed,
eoMerge<EOT>& _merge,
eoReduce<EOT>& _reduce
) : continuator(_continuator),
eval(_eval),
selectTransform(0),
breed(_breed),
mergeReduce(new eoMergeReduce<EOT>(_merge, _reduce)),
replace(mergeReduce)
{}
/// Ctor eoSelect, eoTransform, and eoReplacement
eoEasyEA(
eoContinue<EOT>& _continuator,
eoEvalFunc<EOT>& _eval,
eoSelect<EOT>& _select,
eoTransform<EOT>& _transform,
eoReplacement<EOT>& _replace
) : continuator(_continuator),
eval(_eval),
selectTransform(new eoSelectTransform<EOT>(_select, _transform)),
breed(selectTransform),
mergeReduce(0),
replace(_replace)
{}
/// Ctor eoSelect, eoTransform, eoMerge and eoReduce.
eoEasyEA(
eoContinue<EOT>& _continuator,
eoEvalFunc<EOT>& _eval,
eoSelect<EOT>& _select,
eoTransform<EOT>& _transform,
eoMerge<EOT>& _merge,
eoReduce<EOT>& _reduce
) : continuator(_continuator),
eval(_eval),
selectTransform(new eoSelectTransform<EOT>(_select, _transform)),
breed(*selectTransform),
mergeReduce(new eoMergeReduce<EOT>(_merge, _reduce)),
replace(*mergeReduce)
{}
~eoEasyEA() { delete selectTransform; delete mergeReduce; }
/// Apply a few generation of evolution to the population.
virtual void operator()(eoPop<EOT>& _pop)
{
eoPop<EOT> offspring;
while ( continuator( _pop ) )
{
try
{
step(pop);
}
{
breed(_pop, offspring);
apply<EOT>(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<Chrom> step;
eoTerm<Chrom>& terminator;
/// dissallow copying cuz of pointer stuff
eoEasyEA(const eoEasyEA&);
/// dissallow copying cuz of pointer stuff
const eoEasyEA& operator=(const eoEasyEA&);
eoContinue<EOT>& continuator;
eoEvalFunc<EOT>& eval;
eoSelectTransform<EOT>* selectTransform;
eoBreed<EOT>& breed;
eoMergeReduce<EOT>* mergeReduce;
eoReplacement<EOT>& replace;
};
//-----------------------------------------------------------------------------
#endif eoEasyEA_h
#endif eoSelectTransformReduce_h

View file

@ -25,6 +25,8 @@
#ifndef eoEvalFunc_H
#define eoEvalFunc_H
#include <eoFunctor.h>
/** 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<class EOT> struct eoEvalFunc {
#ifdef _MSC_VER
typedef EOT::Fitness EOFitT;
#else
template<class EOT> class eoEvalFunc : public eoUnaryFunctor<void, EOT&>
{
public :
typedef typename EOT::Fitness EOFitT;
#endif
/// Effectively applies the evaluation function to an EO
virtual void operator() ( EOT & _eo ) const = 0;
template <class It>
void range(It begin, It end) const
{
for (;begin != end; ++begin)
{
operator()(*begin);
}
}
};
#endif
#endif

View file

@ -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<EOT> {
/** Applies the function to the chromosome and sets the fitness of the
@ -44,16 +44,18 @@ struct eoEvalFuncPtr: public eoEvalFunc<EOT> {
argument and returns the fitness
@return the evaluated fitness for that object.
*/
eoEvalFuncPtr( EOFitT (* _eval)( const EOT& ) )
eoEvalFuncPtr( FitT (* _eval)( FunctionArg ) )
: eoEvalFunc<EOT>(), 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

View file

@ -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 <eoEasyEA.h>
#include <eoInplaceTransform.h>
/** eoEvolutionStrategy:
*/
template<class EOT>
class eoEvolutionStrategy: public eoAlgo<EOT>
{
public:
struct plus_strategy{};
struct comma_strategy{};
eoEvolutionStrategy(
eoContinue<EOT>& _continuator,
eoEvalFunc<EOT>& _eval,
eoGOpSelector<EOT>& _opSel,
float _lambdaRate,
comma_strategy)
: selectPerc(randomSelect, _lambdaRate),
transform(_opSel),
easyEA(_continuator, _eval, selectPerc, transform, noElitism, truncate)
{}
eoEvolutionStrategy(
eoContinue<EOT>& _continuator,
eoEvalFunc<EOT>& _eval,
eoGOpSelector<EOT>& _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<EOT>& _pop)
{
easyEA(_pop);
}
private:
eoPlus<EOT> plus;
eoNoElitism<EOT> noElitism;
eoTruncate<EOT> truncate;
eoSelectRandom<EOT> randomSelect;
eoSelectPerc<EOT> selectPerc;
eoInplaceTransform2<EOT> transform;
/// easyEA is contained rather than a base because of member initialization order!
eoEasyEA<EOT> easyEA;
};
//-----------------------------------------------------------------------------
#endif eoSelectTransformReduce_h

58
eo/src/eoFitContinue.h Normal file
View file

@ -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 <eoContinue.h>
/**
Fitness continuation:
Continues until the maximum fitness level is reached.
*/
template< class EOT>
class eoFitContinue: public eoContinue<EOT> {
public:
/// Define Fitness
typedef typename EOT::Fitness FitnessType;
/// Ctor
eoFitContinue( const FitnessType _maximum)
: eoContinue<EOT> (), maximum( _maximum ) {};
/** Returns false when a fitness criterium is
* reached. Assumes pop is not sorted! */
virtual bool operator() ( const eoPop<EOT>& _pop )
{
return (_pop.nth_element_fitness(0) < maximum);
}
private:
FitnessType maximum;
};
#endif

View file

@ -28,7 +28,7 @@
#define _eoFixedLength_h
#include <vector>
#include <EO.h>
/**
Base class for fixed length chromosomes, just derives from EO and vector and
@ -40,7 +40,11 @@ class eoFixedLength : public EO<FitT>, public std::vector<GeneType>
{
public :
typedef GeneType Type;
typedef GeneType AtomType;
typedef std::vector<GeneType> ContainerType;
eoFixedLength(unsigned size = 0, GeneType value = GeneType()) : EO<FitT>(), std::vector<GeneType>(size, value)
{}
/// to avoid conflicts between EO::operator< and vector<double>::operator<
bool operator<(const eoFixedLength<FitT, GeneType>& _eo) const
@ -71,7 +75,11 @@ class eoFixedLength : public EO<FitT>, public std::vector<GeneType>
unsigned i;
for (i = 0; i < sz; ++i)
is >> operator[](i);
{
AtomType atom;
is >> atom;
operator[](i) = atom;
}
}
};

144
eo/src/eoFunctor.h Normal file
View file

@ -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 R>
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<class R>
eoFunctorBase::procedure_tag functor_category(const eoProcedure<R>&)
{
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 R, class A1>
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<class R, class A1>
eoFunctorBase::unary_function_tag functor_category(const eoUnaryFunctor<R, A1>&)
{
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 R, class A1, class A2>
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<class R, class A1, class A2>
eoFunctorBase::binary_function_tag functor_category(const eoBinaryFunctor<R, A1, A2>&)
{
return eoFunctorBase::binary_function_tag();
}
#endif

11
eo/src/eoFunctorStore.cpp Normal file
View file

@ -0,0 +1,11 @@
#include <eoFunctorStore.h>
#include <eoFunctor.h>
/// clears the memory
eoFunctorStore::~eoFunctorStore()
{
for (int i = 0; i < vec.size(); ++i)
{
delete vec[i];
}
}

60
eo/src/eoFunctorStore.h Normal file
View file

@ -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 <vector>
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<eoFunctorBase*> vec;
};
#endif

View file

@ -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 <eoFunctor.h>
#include <eoPop.h>
#include <eoGOpSelector.h>
#include <eoIndiSelector.h>
#include <eoBackInserter.h>
template<class EOT>
class eoGOpBreeder: public eoMonPopOp<EOT>
class eoGOpBreeder: public eoUnaryFunctor<void, eoPop<EOT>&>
{
public:
/// Default constructor.
@ -27,9 +28,6 @@ class eoGOpBreeder: public eoMonPopOp<EOT>
: opSel( _opSel ), selector(_selector)
{}
/// Destructor.
virtual ~eoGOpBreeder() {}
/**
* Enlarges the population.
* @param pop The population to be transformed.

View file

@ -124,7 +124,7 @@ inline eoOpSelector<EOT>::ID eoGOpSelector<EOT>::addOp( eoOp<EOT>& _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<EOT>::unary :
op= new eoWrappedMonOp<EOT>(static_cast<eoMonOp<EOT>&>(_op));

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

@ -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 <eoContinue.h>
/**
Generational continuator: continues until a number of generations is reached
*/
template< class EOT>
class eoGenContinue: public eoContinue<EOT>
{
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<EOT>& _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

View file

@ -30,11 +30,18 @@
#ifndef eoIndiSelector_h
#define eoIndiSelector_h
#include <eoFunctor.h>
/**
* 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 EOT>
class eoIndiSelector
class eoIndiSelector : public eoProcedure<const EOT&>
{
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<const EOT*> select(size_t _how_many)
{ vector<const EOT*> result(_how_many);
for (unsigned i = 0; i < _how_many; ++i)
{
result[i] = &operator()();
}
return result;
}
};
#include <eoSelectOne.h>
/**
* 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 EOT>
class eoPopIndiSelector : public eoIndiSelector<EOT>
class eoSelectOneIndiSelector : public eoIndiSelector<EOT>
{
public :
eoPopIndiSelector(void) : eoIndiSelector<EOT>(), pop(0), last(0), firstChoice(-1), secondChoice(-1) {}
virtual ~eoPopIndiSelector(void) {}
eoSelectOneIndiSelector(eoSelectOne<EOT>& _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<EOT>& _pop, int _end = -1)
eoSelectOneIndiSelector& bind(const eoPop<EOT>& _pop, int _end = -1)
{
pop = &_pop;
last = _end;
@ -101,6 +97,8 @@ class eoPopIndiSelector : public eoIndiSelector<EOT>
{
last = pop->size();
}
select.setup(*pop);
return *this;
}
@ -108,7 +106,7 @@ class eoPopIndiSelector : public eoIndiSelector<EOT>
/** 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<EOT>
eoPop<EOT>::const_iterator begin(void) const { valid(); return pop->begin(); }
eoPop<EOT>::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<EOT>
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<EOT>
int last;
int firstChoice;
int secondChoice;
eoSelectOne<EOT>& select;
};
#endif

View file

@ -27,17 +27,91 @@
#ifndef _eoInit_H
#define _eoInit_H
#include <eoOp.h>
/**
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 EOT>
class eoInit
class eoInit : public eoUnaryFunctor<void, EOT&>
{};
/**
Initializor for fixed length representations with a single type
*/
template <class EOT, class Gen>
class eoInitFixedLength: public eoInit<EOT>
{
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 EOT, class Gen>
class eoInitVariableLength: public eoInit<EOT>
{
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 EOT>
class eoInitAdaptor : public eoMonOp<EOT>
{
public :
eoInitAdaptor(eoInit<EOT>& _init) : init(_init) {}
void operator()(EOT& _eot)
{
init(_eot);
}
private :
eoInit<EOT>& init;
};
#endif

193
eo/src/eoInplaceTransform.h Normal file
View file

@ -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> // vector
#include <utils/eoRNG.h>
#include <eoOp.h> // eoOp, eoMonOp, eoBinOp
#include <eoPop.h> // eoPop
#include <eoOpSelector.h> // eoOpSelector
#include <eoFunctor.h>
#include <eoIndiSelector.h>
#include <eoBackInserter.h>
/*****************************************************************************
* eoInplaceTransform1: transforms a population using genetic operators. *
* It does it in an SGA like manner
*****************************************************************************/
template<class Chrom> class eoInplaceTransform1 : public eoTransform<Chrom>
{
public:
/// Default constructor.
eoInplaceTransform1( eoOpSelector<Chrom>& _opSel): opSel( _opSel ), select(defaultSelect) {}
eoInplaceTransform1( eoOpSelector<Chrom>& _opSel, eoSelectOne<Chrom>& _select)
: opSel(_opSel), select(_select) {}
/**
* Transforms a population.
* @param pop The population to be transformed.
*/
void operator()(eoPop<Chrom>& pop)
{
// copy the guys in a newpop
// because otherwise eoSelectRandom might select freshly created individuals
eoPop<Chrom> newpop;
newpop.reserve(pop.size());
// Set up general op helper classes
eoSelectOneIndiSelector<Chrom> inplace(select);
eoBackInserter<Chrom> inserter;
// set up selection routine
select.setup(pop);
for (unsigned i = 0; i < pop.size(); i++)
{
eoOp<Chrom>* op = opSel.Op();
switch (op->getType())
{
case eoOp<Chrom>::unary:
{
eoMonOp<Chrom>* monop = static_cast<eoMonOp<Chrom>* >(op);
newpop.push_back(pop[i]);
(*monop)( newpop.back() );
break;
}
case eoOp<Chrom>::binary:
{
eoBinOp<Chrom>* binop = static_cast<eoBinOp<Chrom>* >(op);
newpop.push_back(pop[i]);
(*binop)(newpop[i], select(pop));
break;
}
case eoOp<Chrom>::quadratic:
{
eoQuadraticOp<Chrom>* Qop = static_cast<eoQuadraticOp<Chrom>* >(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<Chrom>::general :
{
eoGeneralOp<Chrom>* Gop = static_cast<eoGeneralOp<Chrom>* >(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<Chrom>& opSel;
eoSelectRandom<Chrom> defaultSelect;
eoSelectOne<Chrom>& select;
};
#include <eoGOpSelector.h>
/*****************************************************************************
* eoInplaceTransform2: transforms a population using general genetic operators. *
* It does it in an SGA like manner
*****************************************************************************/
template<class Chrom> class eoInplaceTransform2 : public eoTransform<Chrom>
{
public:
/// Default constructor.
eoInplaceTransform2( eoGOpSelector<Chrom>& _opSel): opSel( _opSel ), select(defaultSelect) {}
eoInplaceTransform2( eoGOpSelector<Chrom>& _opSel, eoSelectOne<Chrom>& _select)
: opSel(_opSel), select(_select) {}
/**
* Transforms a population.
* @param pop The population to be transformed.
*/
void operator()(eoPop<Chrom>& pop)
{
// copy the guys in a newpop
// because otherwise eoSelectRandom might select freshly created individuals
eoPop<Chrom> newpop;
newpop.reserve(pop.size());
// Set up general op helper classes
eoSelectOneIndiSelector<Chrom> inplace(select);
eoBackInserter<Chrom> inserter;
// set up selection routine
select.setup(pop);
for (unsigned i = 0; i < pop.size(); i++)
{
eoGeneralOp<Chrom>& 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<Chrom>& opSel;
eoSelectRandom<Chrom> defaultSelect;
eoSelectOne<Chrom>& select;
};
//-----------------------------------------------------------------------------
#endif eoBreeder_h

View file

@ -30,23 +30,20 @@
#ifndef eoInserter_h
#define eoInserter_h
#include "eoPop.h"
/**
#include <eoFunctor.h>
#include <eoPop.h>
/**
* 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 EOT>
class eoInserter
class eoInserter : public eoUnaryFunctor<eoInserter<EOT>&, const EOT&>
{
public :
virtual ~eoInserter() {}
struct eoInserterException{};
/**
insert argument somewhere (quite likely a population)
*/
virtual eoInserter<EOT>& operator()(const EOT&) = 0; // can throw an eoInserterException
};
/**

View file

@ -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 <iostream>
#include <stdexcept>
// EO includes
#include <eoPop.h> // eoPop
#include <eoPopOps.h> // eoMerge
#include <eoFunctor.h> // 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 Chrom> class eoMerge: public eoBinPopOp<Chrom>
template<class Chrom> class eoMerge: public eoBinaryFunctor<void, const eoPop<Chrom>&, eoPop<Chrom>&>
{};
/**
Straightforward elitism class, specify the number of individuals to copy
into new geneneration
*/
template <class EOT> class eoElitism : public eoMerge<EOT>
{
public:
/// (Default) Constructor.
eoMerge(const float& _rate = 1.0): eoBinPopOp<Chrom>(), repRate( _rate ) {}
public :
eoElitism(unsigned _howmany) : howmany(_howmany) {}
/// Ctor from istream
eoMerge( istream& _is): eoBinPopOp<Chrom>() { readFrom( _is ); };
/**
* Creates a new population based on breeders and original populations.
* @param breeders The population of breeders. Should be sorted to work correctly
* @param pop The original population.
*/
void operator()( eoPop<Chrom>& _breeders, eoPop<Chrom>& _pop)
{
unsigned target = static_cast<unsigned>(_pop.size() * rate());
_pop.swap(_breeders);
if (target < _pop.size())
{
partial_sort(_pop.begin(), _pop.begin() + target, _pop.end(),
greater<Chrom>());
_pop.erase(_pop.begin() + target, _pop.end());
}
else
{
target = min(target - _pop.size(), _breeders.size());
partial_sort(_breeders.begin(), _breeders.begin() + target,
_breeders.end(), greater<Chrom>());
copy(_breeders.begin(), _breeders.begin() + target,
back_insert_iterator<eoPop<Chrom> >(_pop));
}
};
void operator()(const eoPop<EOT>& _pop, eoPop<EOT>& 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<const EOT*> 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 EOT> class eoNoElitism : public eoElitism<EOT>
{
public :
eoNoElitism() : eoElitism<EOT>(0) {}
};
/**
Very elitist class, copies entire population into next gen
*/
template <class EOT> class eoPlus : public eoMerge<EOT>
{
public :
void operator()(const eoPop<EOT>& _pop, eoPop<EOT>& 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

View file

@ -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

View file

@ -26,6 +26,7 @@
#include <eoObject.h>
#include <eoPrintable.h>
#include <eoFunctor.h>
/**
\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 EOType>
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 EOType>
class eoBinOp: public eoOp<EOType> {
/** eoMonOp is the monary operator: genetic operator that takes only one EO */
template <class EOType>
class eoMonOp: public eoOp<EOType>, public eoUnaryFunctor<void, EOType&>
{
public:
/// Ctor
eoBinOp()
:eoOp<EOType>( binary ) {};
/// Copy Ctor
eoBinOp( const eoBinOp& _ebop )
: eoOp<EOType>( _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<EOType>( eoOp<EOType>::unary ) {};
};
/** Binary genetic operator: subclasses eoOp, and defines basically the
* operator() with two operands, only the first one can be modified
*/
template<class EOType>
class eoBinOp: public eoOp<EOType>, public eoBinaryFunctor<void, EOType&, const EOType&>
{
public:
/// Ctor
eoBinOp()
:eoOp<EOType>( eoOp<EOType>::binary ) {};
};
/** Quadratic genetic operator: subclasses eoOp, and defines basically the
operator() with two operands
operator() with two operands, both can be modified.
*/
template<class EOType>
class eoQuadraticOp: public eoOp<EOType> {
class eoQuadraticOp: public eoOp<EOType>, public eoBinaryFunctor<void, EOType&, EOType&> {
public:
/// Ctor
eoQuadraticOp()
:eoOp<EOType>( eoOp<EOType>::quadratic ) {};
/// Copy Ctor
eoQuadraticOp( const eoQuadraticOp& _ebop )
: eoOp<EOType>( _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 EOType>
class eoMonOp: public eoOp<EOType> {
public:
/// Ctor
eoMonOp( )
: eoOp<EOType>( eoOp<EOType>::unary ) {};
/// Copy Ctor
eoMonOp( const eoMonOp& _emop )
: eoOp<EOType>( _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<class EOT>
@ -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 EOT>
class eoGeneralOp: public eoOp<EOT>
{
public:
/// Ctor that honors its superclass
eoGeneralOp(): eoOp<EOT>( eoOp<EOT>::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<EOT>& _in,
eoInserter<EOT>& _out) const = 0;
template<class EOT>
virtual string className() const {return "eoGeneralOp";}
class eoGeneralOp: public eoOp<EOT>, public eoBinaryFunctor<void, eoIndiSelector<EOT>&, eoInserter<EOT>&>
{
public:
/// Ctor that honors its superclass
eoGeneralOp(): eoOp<EOT>( eoOp<EOT>::general ) {}
};
#endif

View file

@ -29,9 +29,9 @@
#include <strstream>
// EO includes
#include <eoRnd.h>
#include <eoInit.h>
#include <eoOp.h> // for eoInit
#include <eoPersistent.h>
#include <eoInit.h>
/** 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 EOT>
class eoPop: public vector<EOT>, 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<EOT>, 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<EOT>() {};
eoPop() : vector<EOT>(), 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<Type> & _geneRnd )
:vector<EOT>() {
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<unsigned> & _sizeRnd, eoRnd<Type> & _geneRnd )
:vector<EOT>() {
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<EOT> & _chromRnd )
eoPop( unsigned _popSize, eoInit<EOT>& _chromInit )
:vector<EOT>()
{
resize(_popSize);
for ( unsigned i = 0; i < _popSize; i++ )
{
push_back( _chromRnd() );
_chromInit(operator[](i));
}
};
@ -133,6 +107,60 @@ class eoPop: public vector<EOT>, 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<EO<Fitness> >());
}
/**
slightly faster algorithm than sort to find all individuals that are better
than the nth individual
*/
eoPop<EOT>::iterator nth_element(int nth)
{
iterator it = begin() + nth;
std::nth_element(begin(), it, end(), greater<EO<Fitness> >());
return it;
}
struct GetFitness { Fitness operator()(const EOT& _eo) const { return _eo.fitness(); } };
Fitness nth_element_fitness(int which) const
{
vector<Fitness> fitness(size());
std::transform(begin(), end(), fitness.begin(), GetFitness());
vector<Fitness>::iterator it = fitness.begin();
std::nth_element(fitness.begin(), it, fitness.end(), greater<Fitness>());
return *it;
}
struct Ref { const EOT* operator()(const EOT& eot) { return &eot;}};
struct Cmp {
bool operator()(const EO<Fitness>* a, const EO<Fitness>* b) const
{ return b->operator<(*a); }
};
/// const nth_element function, returns pointers to sorted individuals
void nth_element(int which, vector<const EOT*>& result) const
{
result.resize(size());
std::transform(begin(), end(), result.begin(), Ref());
vector<const EOT*>::iterator it = result.begin() + which;
std::nth_element(result.begin(), it, result.end(), Cmp());
}
void swap(eoPop<EOT>& other)
{
std::swap(static_cast<vector<EOT>& >(*this), static_cast<vector<EOT>& >(other));
}
/**
* Write object. It's called printOn since it prints the object _on_ a stream.
@ -151,5 +179,79 @@ class eoPop: public vector<EOT>, 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 EOT>
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<EOT>& _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<EOT>& _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

73
eo/src/eoProportional.h Normal file
View file

@ -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 <utils/eoRNG.h>
#include <utils/selectors.h>
#include <eoSelectOne.h>
//-----------------------------------------------------------------------------
/** eoProportional: select an individual proportional to her stored fitness
value
*/
//-----------------------------------------------------------------------------
template <class EOT> class eoProportional: public eoSelectOne<EOT>
{
public:
/// Sanity check
eoProportional(void) : total(-1.0)
{
if (minimizing_fitness<EOT>())
{
throw logic_error("eoProportional: minimizing fitness");
}
}
void setup(const eoPop<EOT>& _pop)
{
total = sum_fitness(_pop);
}
/** do the selection, call roulette_wheel.
*/
const EOT& operator()(const eoPop<EOT>& _pop)
{
return roulette_wheel(_pop, total) ;
}
private :
typename EOT::Fitness total;
};
#endif

58
eo/src/eoReduce.h Normal file
View file

@ -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 <iostream>
// EO includes
#include <eoPop.h> // eoPop
#include <eoFunctor.h> // eoReduce
/**
* eoReduce: .reduce the new generation to the specified size
*/
template<class Chrom> class eoReduce: public eoBinaryFunctor<void, eoPop<Chrom>&, unsigned>
{};
template <class EOT> class eoTruncate : public eoReduce<EOT>
{
void operator()(eoPop<EOT>& _newgen, unsigned _newsize)
{
if (_newgen.size() == _newsize)
return;
_newgen.nth_element(_newsize);
_newgen.resize(_newsize);
}
};
//-----------------------------------------------------------------------------
#endif //eoInsertion_h

111
eo/src/eoReplacement.h Normal file
View file

@ -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 <eoPop.h>
#include <eoFunctor.h>
#include <eoMerge.h>
#include <eoReduce.h>
//-----------------------------------------------------------------------------
/**
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 EOT>
class eoReplacement : public eoBinaryFunctor<void, const eoPop<EOT>&, eoPop<EOT>&>
{};
/**
no replacement
*/
template <class EOT>
class eoNoReplacement : public eoReplacement<EOT>
{
public :
/// do nothing
void operator()(const eoPop<EOT>&, eoPop<EOT>&)
{}
};
/**
eoMergeReduce: special replacement strategy that is just an application of an embedded merge,
followed by an embedded reduce
*/
template <class EOT>
class eoMergeReduce : public eoReplacement<EOT>
{
public:
eoMergeReduce(eoMerge<EOT>& _merge, eoReduce<EOT>& _reduce) :
merge(_merge), reduce(_reduce)
{}
void operator()(const eoPop<EOT>& _parents, eoPop<EOT>& _offspring)
{
merge(_parents, _offspring);
reduce(_offspring, _parents.size());
}
private :
eoMerge<EOT>& merge;
eoReduce<EOT>& reduce;
};
/**
ES type of replacement strategy: first add parents to population, then truncate
*/
template <class EOT>
class eoPlusReplacement : public eoMergeReduce<EOT>
{
public :
eoPlusReplacement() : eoMergeReduce<EOT>(plus, truncate) {}
private :
eoPlus<EOT> plus;
eoTruncate<EOT> truncate;
};
/**
ES type of replacement strategy: ignore parents, truncate offspring
*/
template <class EOT>
class eoCommaReplacement : public eoMergeReduce<EOT>
{
public :
eoCommaReplacement() : eoMergeReduce<EOT>(no_elite, truncate) {}
private :
eoNoElitism<EOT> no_elite;
eoTruncate<EOT> truncate;
};
#endif

101
eo/src/eoSGA.h Normal file
View file

@ -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 <eoOp.h>
#include <eoContinue.h>
#include <eoPop.h>
#include <eoSelectOne.h>
#include <eoSelectPerc.h>
#include <eoEvalFunc.h>
#include <eoAlgo.h>
template <class EOT>
class eoSGA : public eoAlgo<EOT>
{
public :
eoSGA(
eoContinue<EOT>& _cont,
eoMonOp<EOT>& _mutate, float _mrate,
eoQuadraticOp<EOT>& _cross, float _crate,
eoSelectOne<EOT>& _select,
eoEvalFunc<EOT>& _eval)
: cont(_cont),
mutate(_mutate),
mutationRate(_mrate),
cross(_cross),
crossoverRate(_crate),
select(_select),
eval(_eval) {}
void operator()(eoPop<EOT>& _pop)
{
eoPop<EOT> 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<EOT>& cont;
eoMonOp<EOT>& mutate;
float mutationRate;
eoQuadraticOp<EOT>& cross;
float crossoverRate;
eoSelectPerc<EOT> select;
eoEvalFunc<EOT>& eval;
};
#endif

View file

@ -26,18 +26,23 @@
#ifndef eoScalarFitness_h
#define eoScalarFitness_h
#include <functional>
#include <iostream>
/**
* eoScalarFitness<ScalarType, Compare = less<ScalarType> >:
* Wraps a scalar fitness values such as a double or int, with the option of
* maximizing (using less<ScalarType>) or miniziming (using greater<ScalarType>)
* this quantity in EO.
* maximizing (using less<ScalarType>) or minimizing (using greater<ScalarType>)
*
*
*
*
* 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 <class ScalarType, class Compare = less<ScalarType> >
template <class ScalarType, class Compare >
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<ScalarType, Compare>& y ) const { return y < *this; }
// implementation of the other operators
bool operator<=( const eoScalarFitness<ScalarType, Compare>& y ) const { return !(*this > y); }
// implementation of the other operators
bool operator>=(const eoScalarFitness<ScalarType, Compare>& y ) const { return !(*this < y); }
private :
ScalarType value;
};
/**
Typedefs for fitness comparison,
*/
typedef eoScalarFitness<double, std::greater<double> > eoMaximizingFitness;
typedef eoScalarFitness<double, std::less<double> > eoMinimizingFitness;
template <class F, class Cmp>
std::ostream& operator<<(std::ostream& os, const eoScalarFitness<F, Cmp>& f)
{
@ -69,7 +88,7 @@ std::ostream& operator<<(std::ostream& os, const eoScalarFitness<F, Cmp>& f)
}
template <class F, class Cmp>
std::istream& operator>>(istream& is, eoScalarFitness<F, Cmp>& f)
std::istream& operator>>(std::istream& is, eoScalarFitness<F, Cmp>& f)
{
F value;
is >> value;

43
eo/src/eoSelect.h Normal file
View file

@ -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 <eoPop.h>
//-----------------------------------------------------------------------------
/**
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 EOT>
class eoSelect : public eoBinaryFunctor<void, const eoPop<EOT>&, eoPop<EOT>&>
{};
#endif

49
eo/src/eoSelectOne.h Normal file
View file

@ -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 <eoPop.h>
#include <eoFunctor.h>
//-----------------------------------------------------------------------------
/** 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 EOT>
class eoSelectOne : public eoUnaryFunctor<const EOT&, const eoPop<EOT>&>
{
public :
/// virtual function to setup some population stats (for instance eoProportional can benefit greatly from this)
virtual void setup(const eoPop<EOT>&) {}
};
#endif

72
eo/src/eoSelectPerc.h Normal file
View file

@ -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 <eoSelect.h>
#include <eoSelectOne.h>
#include <math.h>
//-----------------------------------------------------------------------------
/** 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 EOT>
class eoSelectPerc : public eoSelect<EOT>
{
public:
/// init
eoSelectPerc(eoSelectOne<EOT>& _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<EOT>& _source, eoPop<EOT>& _dest)
{
size_t target = static_cast<size_t>(floor(rate * _source.size()));
_dest.resize(target);
select.setup(_source);
for (int i = 0; i < _dest.size(); ++i)
_dest[i] = select(_source);
}
private :
eoSelectOne<EOT>& select;
float rate;
};
#endif

View file

@ -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 <functional> //
#include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include <utils/eoRNG.h>
#include <eoSelectOne.h>
//-----------------------------------------------------------------------------
/** eoUniformSelect: a selection method that selects ONE individual randomly
/** eoSelectRandom: a selection method that selects ONE individual randomly
-MS- 22/10/99 */
//-----------------------------------------------------------------------------
template <class EOT> class eoUniformSelect: public eoSelectOne<EOT>
template <class EOT> class eoSelectRandom: public eoSelectOne<EOT>
{
public:
/// (Default) Constructor.
eoUniformSelect():eoSelectOne<EOT>() {}
/// not a big deal!!!
virtual const EOT& operator()(const eoPop<EOT>& pop) {
virtual const EOT& operator()(const eoPop<EOT>& pop)
{
return pop[rng.random(pop.size())] ;
}
/// Methods inherited from eoObject
//@{
/** Return the class id.
* @return the class name as a string
*/
virtual string className() const { return "eoUniformSelect"; };
private:
};
#endif eoUniformSelect_h
#endif eoSelectRandom_h

View file

@ -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 <eoGOpSelector.h>
/** 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 EOT>
class eoSequentialGOpSel : public eoGOpSelector<EOT>
{
public :
virtual ~eoSequentialGOpSel(void) {}
eoSequentialGOpSel(void) : combined(*this, getRates()) {}
virtual eoGeneralOp<EOT>& 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;
}

View file

@ -27,8 +27,8 @@
//-----------------------------------------------------------------------------
#include "eoSteadyStateGeneration.h" // eoPop
#include <eoTerm.h>
#include <eoAlgo.h>
#include <eoSteadyStateTransform.h>
/** EOSteadyStateEA:
An easy-to-use evolutionary algorithm, just supply
@ -42,19 +42,19 @@ template<class EOT> class eoSteadyStateEA: public eoAlgo<EOT>
/// Constructor.
eoSteadyStateEA(
eoGOpSelector<EOT>& _opSelector,
eoPopIndiSelector<EOT>& _selector,
eoSelectOne<EOT>& _selector,
eoSteadyStateInserter<EOT>& _inserter,
eoTerm<EOT>& _terminator,
eoContinue<EOT>& _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<EOT>& _gen,
eoTerm<EOT>& _terminator):
eoSteadyStateEA(eoSteadyStateTransform<EOT>& _gen,
eoContinue<EOT>& _continuator):
step(_gen),
terminator( _terminator){};
continuator( _continuator){};
/// Apply one generation of evolution to the population.
virtual void operator()(eoPop<EOT>& pop) {
@ -69,16 +69,13 @@ template<class EOT> class eoSteadyStateEA: public eoAlgo<EOT>
s.append( " in eoSteadyStateEA ");
throw runtime_error( s );
}
} while ( terminator( pop ) );
} while ( continuator( pop ) );
}
/// Class name.
string className() const { return "eoSteadyStateEA"; }
private:
eoSteadyStateGeneration<EOT> step;
eoTerm<EOT>& terminator;
eoSteadyStateTransform<EOT> step;
eoContinue<EOT>& continuator;
};
//-----------------------------------------------------------------------------

View file

@ -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 EOT>
class eoSteadyStateInserter : public eoPopInserter<EOT>
{
public :
eoSteadyStateInserter(eoEvalFunc<EOT>& _eval):
eoSteadyStateInserter(eoEvalFunc<EOT>& _eval):
eoPopInserter<EOT>(),
eval(_eval) {}
protected :
eoEvalFunc<EOT>& eval;
eoEvalFunc<EOT>& eval;
};

View file

@ -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 <eoAlgo.h> // eoPop
#include <eoEvalFunc.h>
#include <eoPopOps.h> // eoSelect, eoTranform, eoMerge
#include "eoGOpSelector.h"
#include "eoIndiSelector.h"
#include "eoSteadyStateInserter.h"
#include <eoGOpSelector.h>
#include <eoIndiSelector.h>
#include <eoSteadyStateInserter.h>
//-----------------------------------------------------------------------------
/** 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 EOT> class eoSteadyStateGeneration: public eoAlgo<EOT>
template<class EOT> class eoSteadyStateTransform: public eoTransform<EOT>
{
public:
/// Constructor.
eoSteadyStateGeneration(
eoSteadyStateTransform(
eoGOpSelector<EOT>& _opSelector,
eoPopIndiSelector<EOT>& _selector,
eoSelectOne<EOT>& _selector,
eoSteadyStateInserter<EOT>& _inserter,
unsigned _steps = 0) :
opSelector(_opSelector),
@ -66,19 +65,19 @@ template<class EOT> class eoSteadyStateGeneration: public eoAlgo<EOT>
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<EOT>& opSelector;
eoPopIndiSelector<EOT>& selector;
eoSelectOneIndiSelector<EOT>& selector;
eoSteadyStateInserter<EOT>& inserter;
unsigned steps;
};

View file

@ -30,7 +30,6 @@
#include <functional> //
#include <numeric> // accumulate
#include <eoPopOps.h> // eoPop eoSelect MINFLOAT
#include <utils/eoRNG.h>
//-----------------------------------------------------------------------------
@ -44,7 +43,8 @@ template <class EOT> class eoStochTournament: public eoSelectOne<EOT>
public:
///
eoStochTournament(float _Trate = 1.0 ):eoSelectOne<EOT>(), Trate(_Trate) {
eoStochTournament(float _Trate = 1.0 ) : eoSelectOne<EOT>(), 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 EOT> class eoStochTournament: public eoSelectOne<EOT>
}
}
/** 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<EOT>& pop)
{
return stochastic_tournament(pop, Trate);

View file

@ -63,7 +63,6 @@ public :
eo = _eot; // overwrite loser of tournament
eo.invalidate();
eval(eo); // Evaluate after insert
return *this;
}

41
eo/src/eoTransform.h Normal file
View file

@ -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 <eoPop.h>
//-----------------------------------------------------------------------------
/**
eoTransform transforms a population by applying genetic operators on
it.
*/
template<class EOT>
class eoTransform : public eoUnaryFunctor<void, eoPop<EOT>&>
{};
#endif

View file

@ -30,8 +30,9 @@
#include <list>
/**
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 <class FitT, class GeneType>
@ -39,8 +40,39 @@ class eoVariableLength : public EO<FitT>, public std::list<GeneType>
{
public :
typedef typename GeneType Type;
typedef GeneType AtomType;
typedef std::list<GeneType> ContainerType;
/// printing...
void printOn(ostream& os) const
{
EO<FitT>::printOn(os);
os << ' ';
os << size() << ' ';
std::copy(begin(), end(), ostream_iterator<double>(os));
}
/// reading...
void readFrom(istream& is)
{
EO<FitT>::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<double>::operator<
bool operator<(const eoVariableLength<FitT, GeneType>& _eo) const
{

View file

@ -42,25 +42,22 @@ class eoWrappedMonOp : public eoGeneralOp<EOT>
{
public :
///
eoWrappedMonOp(const eoMonOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {};
eoWrappedMonOp(eoMonOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {};
///
virtual ~eoWrappedMonOp() {}
/// Instantiates the abstract method
void operator()( eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const {
eoInserter<EOT>& _out)
{
EOT result = _in();
op( result );
_out(result);
}
///
virtual string className() const {return "eoWrappedMonOp";};
private :
const eoMonOp<EOT>& op;
eoMonOp<EOT>& op;
};
@ -70,25 +67,23 @@ class eoWrappedBinOp : public eoGeneralOp<EOT>
{
public :
///
eoWrappedBinOp(const eoBinOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {}
eoWrappedBinOp(eoBinOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {}
///
virtual ~eoWrappedBinOp() {}
/// Instantiates the abstract method. EOT should have copy ctor.
void operator()(eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const {
eoInserter<EOT>& _out)
{
EOT out1 = _in();
const EOT& out2 = _in();
op(out1, out2);
_out(out1);
}
///
virtual string className() const {return "eoWrappedBinOp";};
private :
const eoBinOp<EOT>& op;
eoBinOp<EOT>& op;
};
/// Wraps Quadratic operators
@ -97,125 +92,105 @@ class eoWrappedQuadraticOp : public eoGeneralOp<EOT>
{
public :
///
eoWrappedQuadraticOp(const eoQuadraticOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {}
eoWrappedQuadraticOp(eoQuadraticOp<EOT>& _op) : eoGeneralOp<EOT>(), op(_op) {}
///
virtual ~eoWrappedQuadraticOp() {}
/// Instantiates the abstract method. EOT should have copy ctor.
void operator()(eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out) const {
eoInserter<EOT>& _out)
{
EOT out1 = _in();
EOT out2 = _in();
op(out1, out2);
_out(out1)(out2);
}
///
virtual string className() const {return "eoWrappedQuadraticOp";};
private :
const eoQuadraticOp<EOT>& op;
eoQuadraticOp<EOT>& op;
};
/// Combines several ops
template <class EOT>
#include <eoBackInserter.h>
template <class EOT>
class eoCombinedOp : public eoGeneralOp<EOT>
{
public :
///
eoCombinedOp() : eoGeneralOp<EOT>() {}
public :
eoCombinedOp(const std::vector<eoGeneralOp<EOT>*>& _ops, const std::vector<float>& rates)
: ops(_ops), rates(_rates) {}
///
virtual ~eoCombinedOp() {}
/// Adds a new operator to the combined Op
void addOp(eoGeneralOp<EOT>* _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<EOT>, public eoInserter<EOT>
{
public :
eoIndiSelectorInserter(eoIndiSelector<EOT>& _in)
: eoIndiSelector<EOT>(), eoInserter<EOT>(), 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<EOT>::iterator it = *results.begin();
results.pop_front();
return *it;
}
eoInserter<EOT>& operator()(const EOT& _eot)
{
intermediate.push_front(_eot);
results.push_front(intermediate.begin());
return *this;
}
void fill(eoInserter<EOT>& _out)
{
typedef list<list<EOT>::iterator>::iterator Iterator;
for (Iterator it = results.begin(); it != results.end(); ++it)
{
_out(**it);
}
results.clear();
intermediate.clear(); // reclaim memory
}
private :
eoIndiSelector<EOT>& 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<list<EOT>::iterator> results;
list<EOT> intermediate;
};
/// Applies all ops in the combined op
void operator()( eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out ) const {
eoIndiSelectorInserter in_out(_in);
for (size_t i = 0; i < ops.size(); ++i)
class eoDelayedSelector : public eoIndiSelector<EOT>
{
(*ops[i])(in_out, in_out);
}
public :
eoDelayedSelector(eoIndiSelector<EOT>& _select, const eoPop<EOT>& _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<EOT>::const_iterator get_it(void) const { return it; }
private :
eoIndiSelector<EOT>& select;
const eoPop<EOT>& pop;
eoPop<EOT>::const_iterator it;
};
/** Applies all ops in the combined op
It works in the following way
*/
void operator()( eoIndiSelector<EOT>& _in,
eoInserter<EOT>& _out )
{
eoPop<EOT> intermediate;
eoPop<EOT> 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<eoGeneralOp<EOT>* > ops;
private :
const std::vector<eoGeneralOp<EOT>*>& ops;
const std::vector<float> rates;
eoBackInserter<EOT> inserter;
};
#endif eoGeneral_h
#endif

View file

@ -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
libeoinc_HEADERS = evolution_strategies eoEsChromInit.h eoEsFull.h eoEsMutate.h eoEsMutationInit.h eoEsObjectiveBounds.h eoEsSimple.h eoEsStdev.h

View file

@ -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 <utils/eoParser.h>
#include <utils/eoRNG.h>
#include <cmath> // for exp
#include <es/eoESFullChrom.h>
#include <eoOp.h>
#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 fitT>
class eoESMutate: public eoMonOp< eoESFullChrom<fitT> > {
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<fitT> >( ), TauLcl(_TauLcl), TauGlb(_TauGlb),
TauBeta(_TauBeta) {};
/* The parser constructor
*/
eoESMutate(Parser & parser, unsigned _stdDevLength, unsigned _size, bool _correlated ):
eoMonOp< eoESFullChrom<fitT> >( ) {
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<fitT> & _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<fitT> & _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<fitT> & _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<double> 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

View file

@ -33,7 +33,7 @@
#include <es/eoEsFull.h>
#include <utils/eoRNG.h>
#include <eoInit.h>
#include <eoInit.h>
#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 :

View file

@ -30,7 +30,7 @@
#define _EOESMUTATE_H
#include <utils/eoRNG.h>
#include <eoRnd.h>
#include <eoInit.h>
#include <cmath> // for exp
#include <es/eoEsMutationInit.h>
@ -89,7 +89,7 @@ public:
/**
Mutate eoEsSimple
*/
virtual void operator()( eoEsSimple<FitT>& _eo) const
virtual void operator()( eoEsSimple<FitT>& _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<FitT>& _eo ) const
virtual void operator()( eoEsStdev<FitT>& _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<FitT> & _eo ) const
virtual void operator()( eoEsFull<FitT> & _eo )
{
/*
@ -216,6 +220,8 @@ public:
_eo[i] += VarStp[i];
keepInBounds(_eo);
_eo.invalidate();
}
void keepInBounds(eoFixedLength<FitT, double>& _eo) const

View file

@ -27,7 +27,8 @@
#include <iostream> // ostream, istream
#include <functional> // bind2nd
#include <string> // string
#include <eoVector.h> // EO
#include <eoFixedLength.h>
/**
\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<bool>).
* based on STL's vector<bool> specialization.
*/
template <class F> class eoBin: public eoVector<bool, F>
template <class F> class eoBin: public eoFixedLength<F, bool>
{
public:
@ -49,21 +50,8 @@ template <class F> class eoBin: public eoVector<bool, F>
* @param size Size of the binary string.
*/
eoBin(unsigned size = 0, bool value = false):
eoVector<bool,F>(size, value) {}
/**
* Constructor.
* @param size Size of the binary string.
*/
eoBin(unsigned size, const eoRnd<bool>& rnd): eoVector<bool,F>(size)
{
generate(begin(), end(), rnd);
}
/** Constructor from istream.
@param is The istream to read from.*/
eoBin(istream& _is):eoVector<bool,F>(_is){};
eoFixedLength<F, bool>(size, value) {}
/// My class name.
string className() const
{
@ -76,6 +64,7 @@ template <class F> class eoBin: public eoVector<bool, F>
*/
void printOn(ostream& os) const
{
os << size() << ' ';
copy(begin(), end(), ostream_iterator<bool>(os));
}
@ -98,4 +87,4 @@ template <class F> class eoBin: public eoVector<bool, F>
//-----------------------------------------------------------------------------
#endif eoBin_h
#endif //eoBin_h

View file

@ -9,45 +9,8 @@
#include <algorithm> // swap_ranges
#include <utils/eoRNG.h>
#include <ga/eoBin.h> // eoBin
#include <eoOp.h> // 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 Chrom> class eoBinRandom: public eoMonOp<Chrom>
{
public:
/// The class name.
string className() const { return "eoBinRandom"; }
/**
* Randomizes a cromosome.
* @param chrom The cromosome to be randomize.
*/
void operator()(Chrom& chrom) const
{
for (unsigned i = 0; i < chrom.size(); i++)
chrom[i] = rng.flip(0.5) ? false : true;
}
};
#include <eoInit.h> // eoMonOp
#include <ga/eoBin.h>
/** eoBinBitFlip --> changes a bit
\class eoBinBitFlip eoBitOp.h ga/eoBitOp.h
@ -64,8 +27,9 @@ template<class Chrom> class eoBinBitFlip: public eoMonOp<Chrom>
* 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 Chrom> class eoBinMutation: public eoMonOp<Chrom>
* 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 Chrom> class eoBinInversion: public eoMonOp<Chrom>
* 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 Chrom> class eoBinInversion: public eoMonOp<Chrom>
unsigned r1 = min(u1, u2), r2 = max(u1, u2);
reverse(chrom.begin() + r1, chrom.begin() + r2);
chrom.invalidate();
}
};
@ -147,7 +119,7 @@ template<class Chrom> class eoBinNext: public eoMonOp<Chrom>
* 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 Chrom> class eoBinNext: public eoMonOp<Chrom>
chrom[i] = 1;
break;
}
chrom.invalidate();
}
};
@ -179,7 +153,7 @@ template<class Chrom> class eoBinPrev: public eoMonOp<Chrom>
* 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 Chrom> class eoBinPrev: public eoMonOp<Chrom>
chrom[i] = 1;
continue;
}
chrom.invalidate();
}
};
@ -212,10 +188,19 @@ template<class Chrom> class eoBinCrossover: public eoQuadraticOp<Chrom>
* @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 Chrom> class eoBinNxOver: public eoQuadraticOp<Chrom>
* @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 Chrom> class eoBinNxOver: public eoQuadraticOp<Chrom>
if (change)
swap(chrom1[bit], chrom2[bit]);
}
chrom1.invalidate();
chrom2.invalidate();
}
private:
@ -305,7 +293,7 @@ template<class Chrom> class eoBinGxOver: public eoQuadraticOp<Chrom>
* @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 Chrom> class eoBinGxOver: public eoQuadraticOp<Chrom>
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;

View file

@ -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<EOT> {
class eoBitOpFactory: public eoOpFactory<EOT>
{
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<EOT>* make(istream& _is) {
virtual eoOp<EOT>* make(istream& _is)
{
eoOp<EOT> * opPtr = NULL;
try {
opPtr = eoOpFactory<EOT>::make( _is );

View file

@ -3,12 +3,12 @@
#include <list>
#include "EO.h"
#include "eoOp.h"
#include "eoInserter.h"
#include "eoIndiSelector.h"
#include "parse_tree.h"
#include "eoRnd.h"
#include <EO.h>
#include <eoOp.h>
#include <eoInserter.h>
#include <eoIndiSelector.h>
#include <gp/parse_tree.h>
#include <eoInit.h>
using namespace gp_parse_tree;
using namespace std;
@ -90,7 +90,7 @@ std::istream& operator>>(std::istream& is, eoParseTree<FType, Node>& eot)
template <class FType, class Node>
class eoGpDepthInitializer : public eoRnd< eoParseTree<FType, Node>::Type >
class eoGpDepthInitializer : public eoInit< eoParseTree<FType, Node> >
{
public :
@ -109,15 +109,13 @@ class eoGpDepthInitializer : public eoRnd< eoParseTree<FType, Node>::Type >
virtual string className() const { return "eoDepthInitializer"; };
EoType::Type operator()(void)
void operator()(EoType& _tree)
{
list<Node> sequence;
generate(sequence, max_depth);
parse_tree<Node> tree(sequence.begin(), sequence.end());
return tree.root();
_tree = parse_tree<Node>(sequence.begin(), sequence.end());
}
void generate(list<Node>& sequence, int the_max, int last_terminal = -1)

View file

@ -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

View file

@ -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.

View file

@ -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 T>
class eoAtomBitFlip: public eoAtomMutator<bool> {
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 T>
class eoAtomBitFlip: public eoAtomMutator<bool> {
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

View file

@ -24,38 +24,16 @@
#ifndef _EOATOMMUTATOR_H
#define _EOATOMMUTATOR_H
#include <eoFunctor.h>
/** 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 T>
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<void, T&> {};
#endif

View file

@ -36,14 +36,14 @@ class eoAtomRandom: public eoAtomMutator<T> {
public:
///
eoAtomRandom( eoRnd<T>& _rng): rng( _rng ) {};
eoAtomRandom( eoRnd<T>& _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<T>& rng;
eoRnd<T>& rnd;
};

89
eo/src/obsolete/eoBin.h Normal file
View file

@ -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 <iostream> // ostream, istream
#include <functional> // bind2nd
#include <string> // string
#include <eoFixedLength.h>
/**
\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<bool>).
*/
template <class F> class eoBin: public eoFixedLength<F, bool>
{
public:
/**
* (Default) Constructor.
* @param size Size of the binary string.
*/
eoBin(unsigned size = 0, bool value = false):
eoVector<bool,F>(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<bool>(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<char>(), '1'));
}
}
};
//-----------------------------------------------------------------------------
#endif eoBin_h

View file

@ -32,9 +32,10 @@
#include <utils/eoRNG.h>
#include <eoOp.h> // eoOp, eoMonOp, eoBinOp
#include <eoPop.h> // eoPop
#include <eoPopOps.h> // eoTransform
#include <eoOpSelector.h> // eoOpSelector
#include <eoFunctor.h>
#include <eoRandomIndiSelector.h>
#include <eoBackInserter.h>
@ -45,7 +46,8 @@ using namespace std;
* For every operator there is a rated to be applyed. *
*****************************************************************************/
template<class Chrom> class eoBreeder: public eoMonPopOp<Chrom>
template<class Chrom> class eoBreeder: public eoTransform<EOT>
//eoUnaryFunctor<void, eoPop<Chrom>&>
{
public:
/// Default constructor.
@ -62,9 +64,11 @@ template<class Chrom> class eoBreeder: public eoMonPopOp<Chrom>
{
size_t orgsize = pop.size();
for (unsigned i = 0; i < pop.size(); i++) {
eoOp<Chrom>* op = opSel.Op();
switch (op->getType()) {
for (unsigned i = 0; i < pop.size(); i++)
{
eoOp<Chrom>* op = opSel.Op();
switch (op->getType())
{
case eoOp<Chrom>::unary:
{
eoMonOp<Chrom>* monop = static_cast<eoMonOp<Chrom>* >(op);

View file

@ -31,8 +31,8 @@
#include <eoOp.h>
/// Dup or duplicate: duplicates a gene in a chromosome
template <class EOT>
class eoDup: public eoMonOp<EOT> {
template <class FitT, class Atomic>
class eoDup: public eoMonOp<eoVariableLength<FitT, Atomic> > {
public:
///
eoDup( )
@ -42,11 +42,17 @@ public:
virtual ~eoDup() {};
///
virtual void operator()( EOT& _eo ) const
virtual void operator()(eoVariableLength<FitT, Atomic>& _eo ) const
{
unsigned pos = rng.random(_eo.length());
_eo.insertGene( pos, _eo.gene(pos) );
}
unsigned pos = rng.random(_eo.size());
eoVariableLength<FitT, Atomic>::iterator it = begin();
while (pos--) {++it;}
_eo.insert(it, 1, *it);
_eo.invalidate();
}
/** @name Methods from eoObject

164
eo/src/obsolete/eoES.h Normal file
View file

@ -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 <vector> // For vector<>
#include <stdexcept>
#include <strstream>
#include <iostream> // for ostream
// EO includes
#include <eoVector.h>
/**@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 <class T>
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 <class T>
struct eoESGene : public eoESValue<T>
{
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 <typename fitT = float >
class eoESChrom: public eoVector<eoESGene, fitT> {
public:
/// Basic ctor
eoESChrom( ):eoVector<eoESGene, fitT>() {};
/** 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<double>& _rnd, eoRnd<double>& _rndS )
: eoVector<eoESGene, fitT>( _size ){
for ( iterator i = begin(); i != end(); i ++ ) {
i->val = _rnd();
i->sigma = _rndS();
}
};
/// Copy ctor
eoESChrom( const eoESChrom& _eoes): eoVector<eoESGene, fitT>( _eoes ) {};
/// Assignment operator
const eoESChrom& operator =( const eoESChrom & _eoes ) {
if ( this != &_eoes ){
eoVector<eoESGene, fitT>::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

View file

@ -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 <class T>
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 <class T>
struct eoESGene : public eoESValue<T>
{
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

View file

@ -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<double, fitT> {
verbose( _verbose ),
ObjMin( _ObjMin ),
ObjMax(_ObjMax ),
StdDevInit( _StdDevInit ) {}
StdDevInit( _StdDevInit )
{ // check consistency
}
/// copy constructor
eoESFullChrom( const eoESFullChrom& _eo ):
eoVector<double, fitT> ( _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

View file

@ -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 <utils/eoParser.h>
#include <utils/eoRNG.h>
#include <cmath> // for exp
#include <es/eoESFullChrom.h>
#include <es/eoESInit.h>
#include <eoOp.h>
#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 EOT>
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<EOT>::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<EOT>::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<FitT>& _eo) const
{
_eo.stdev *= exp(TauLcl * rng.normal());
if (_eo.stdev < eoEsInfo<EOT>::stdev_eps)
_eo.stdev = eoEsInfo<EOT>::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<FitT>& _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<EOT>::stdev_eps)
stdev = eoEsInfo<EOT>::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<fitT> & _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<EOT>::stdev_eps)
stdev = eoEsInfo<EOT>::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<double> 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

View file

@ -25,42 +25,34 @@
#ifndef _EOFITTERM_H
#define _EOFITTERM_H
#include <eoTerm.h>
#include <eoContinue.h>
/** 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|<epsilon
/**
Fitness continuation:
Continues until the maximum fitness level is reached.
*/
template< class EOT>
class eoFitTerm: public eoTerm<EOT> {
class eoFitContinue: public eoContinue<EOT> {
public:
/// Ctors/dtors
eoFitTerm( const float _maximum, const float _epsilon )
: eoTerm<EOT> (), maximum( _maximum ), epsilon(_epsilon){};
/// Define Fitness
typedef typename EOT::Fitness FitnessType;
/// Copy ctor
eoFitTerm( const eoFitTerm& _t )
: eoTerm<EOT> ( _t ), maximum( _t.maximum ),
epsilon(_t.epsilon){};
///
virtual ~eoFitTerm() {};
/// Ctor
eoFitContinue( const FitnessType _maximum)
: eoContinuator<EOT> (), maximum( _maximum ) {};
/** Returns false when a fitness criterium is
* reached */
virtual bool operator() ( const eoPop<EOT>& _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<EOT>& _vEO )
{
return (bestFitness < maximum);
}
std::string className(void) const { return "eoFitTerm"; }
private:
float maximum, epsilon;
FitnessType maximum;
};
#endif

View file

@ -25,36 +25,19 @@
#ifndef _EOGENTERM_H
#define _EOGENTERM_H
#include <eoTerm.h>
#include <eoContinue.h>
/** 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<EOT> {
class eoGenContinue: public eoContinue<EOT> {
public:
/// Ctors/dtors
eoGenTerm( unsigned _totalGens)
: eoTerm<EOT> (), repTotalGenerations( _totalGens ),
eoGenContinue( unsigned _totalGens)
: repTotalGenerations( _totalGens ),
thisGeneration(0){};
/// Copy Ctor
eoGenTerm( const eoGenTerm& _t)
: eoTerm<EOT> ( _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<EOT>& _vEO ) {

View file

@ -26,7 +26,6 @@
#define eoGeneration_h
//-----------------------------------------------------------------------------
#include <strstream>
#include <eoAlgo.h> // eoPop
#include <eoEvalFunc.h>
#include <eoPopOps.h> // eoSelect, eoTranform, eoMerge
@ -41,8 +40,8 @@ template<class Chrom> class eoGeneration: public eoAlgo<Chrom>
{
public:
/// Constructor.
eoGeneration(eoBinPopOp<Chrom>& _select,
eoMonPopOp<Chrom>& _transform,
eoGeneration(eoSelect<Chrom>& _select,
eoBreeder<Chrom>& _breeder,
eoBinPopOp<Chrom>& _replace,
eoEvalFunc<Chrom>& _evaluator):
select(_select), transform(_transform),

View file

@ -40,7 +40,7 @@
* from the original population.
*****************************************************************************/
template<class Chrom> class eoInsertion: public eoMerge<Chrom>
template<class Chrom> class eoInsertion: public eoBinaryFunctor<eoPop<Chrom>&, const eoPop<Chrom>&>
{
public:
/// (Default) Constructor.
@ -57,7 +57,7 @@ template<class Chrom> class eoInsertion: public eoMerge<Chrom>
* @param breeders The population of breeders. Should be sorted to work correctly
* @param pop The original population.
*/
void operator()( eoPop<Chrom>& _breeders, eoPop<Chrom>& _pop)
void operator()( eoPop<Chrom>& _breeders, const eoPop<Chrom>& _pop)
{
unsigned target = static_cast<unsigned>((_pop.size() * rate()));

View file

@ -30,6 +30,7 @@
#include <stdexcept> // logic_error
#include <utils/selectors.h> // sum_fitness
#include <eoFunctor.h>
// #include <functional> //
// #include <numeric> // accumulate
@ -44,7 +45,7 @@
*/
//-----------------------------------------------------------------------------
template<class EOT> class eoLottery: public eoBinPopOp<EOT>
template<class EOT> class eoLottery: public eoBinaryFunctor<void, const eoPop<EOT>&, eoPop<EOT>& >
{
public:
/// (Default) Constructor.
@ -61,7 +62,7 @@ template<class EOT> class eoLottery: public eoBinPopOp<EOT>
* BUT what happens if breeders is already too big?
* Too big for what?
*/
void operator()( eoPop<EOT>& pop, eoPop<EOT>& breeders)
void operator()(const eoPop<EOT>& pop, eoPop<EOT>& breeders)
{
size_t target = static_cast<size_t>(rate_ * pop.size());

View file

@ -48,21 +48,14 @@
*/
template<class EOT>
class eoRank: public eoSelect<EOT>{
class eoRank: public eoSelect<EOT>, public eoObject, public eoPrintable
{
public:
/// Ctor
eoRank( unsigned _newPopSize, eoOpSelector<EOT>& _opSelector)
:eoSelect<EOT>(), opSelector( _opSelector ), repNewPopSize( _newPopSize ) {};
/** Copy ctor
* Needs a copy ctor for the EO operators */
eoRank( const eoRank& _rankBreeder)
:eoSelect<EOT>( _rankBreeder),
opSelector( _rankBreeder.opSelector ), repNewPopSize( _rankBreeder.repNewPopSize ) {};
/// Dtor
virtual ~eoRank() {};
@ -79,12 +72,10 @@ class eoRank: public eoSelect<EOT>{
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<EOT>{
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;
};

Some files were not shown because too many files have changed in this diff Show more