Paradiseo-eo sources added
git-svn-id: svn://scm.gforge.inria.fr/svnroot/paradiseo@40 331e1502-861f-0410-8da2-ba01fb791d7f
This commit is contained in:
parent
bc1f453978
commit
c3aec878e5
3609 changed files with 342772 additions and 0 deletions
6
trunk/paradiseo-eo/src/.cvsignore
Normal file
6
trunk/paradiseo-eo/src/.cvsignore
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
*.lo
|
||||
*.la
|
||||
.deps
|
||||
.libs
|
||||
Makefile
|
||||
Makefile.in
|
||||
108
trunk/paradiseo-eo/src/CVS/Entries
Normal file
108
trunk/paradiseo-eo/src/CVS/Entries
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
/.cvsignore/1.1.1.1/Fri Jan 29 12:23:53 1999//
|
||||
/EO.h/1.26/Thu Feb 27 19:26:10 2003//
|
||||
/Makefile.am/1.59/Thu Mar 23 10:15:17 2006//
|
||||
/apply.h/1.4/Thu Feb 27 19:26:11 2003//
|
||||
/eo/1.57/Tue Feb 28 14:40:37 2006//
|
||||
/eoAlgo.h/1.5/Thu Dec 23 17:26:38 2004//
|
||||
/eoBreed.h/1.4/Wed Oct 5 22:08:29 2005//
|
||||
/eoCellularEasyEA.h/1.1/Thu Apr 25 14:06:43 2002//
|
||||
/eoCloneOps.h/1.2/Thu Feb 27 19:26:09 2003//
|
||||
/eoCombinedContinue.h/1.6/Tue Jun 15 07:28:54 2004//
|
||||
/eoCombinedInit.h/1.2/Sat Aug 28 14:03:34 2004//
|
||||
/eoContinue.h/1.4/Fri Dec 9 17:45:56 2005//
|
||||
/eoCounter.h/1.4/Wed Feb 14 10:35:25 2001//
|
||||
/eoCtrlCContinue.cpp/1.4/Fri Feb 28 16:49:13 2003//
|
||||
/eoCtrlCContinue.h/1.6/Tue Jun 15 07:28:54 2004//
|
||||
/eoDetSelect.h/1.5/Sun Mar 2 11:29:01 2003//
|
||||
/eoDetTournamentSelect.h/1.7/Thu Feb 27 19:26:01 2003//
|
||||
/eoDistribUpdater.h/1.2/Sat Nov 10 09:02:17 2001//
|
||||
/eoDistribution.h/1.1/Thu Nov 8 07:40:27 2001//
|
||||
/eoDominanceMap.h/1.10/Thu Dec 23 15:40:44 2004//
|
||||
/eoEDA.h/1.1/Mon Jun 9 06:17:26 2003//
|
||||
/eoEasyEA.h/1.23/Wed Oct 5 22:08:29 2005//
|
||||
/eoEvalContinue.h/1.3/Tue Jun 15 07:28:54 2004//
|
||||
/eoEvalFunc.h/1.16/Mon Jul 12 09:16:41 2004//
|
||||
/eoEvalFuncCounter.h/1.1/Tue Apr 24 04:56:12 2001//
|
||||
/eoEvalFuncPtr.h/1.7/Sat Nov 17 07:22:31 2001//
|
||||
/eoFactory.h/1.4/Thu Feb 27 19:25:59 2003//
|
||||
/eoFitContinue.h/1.4/Tue Jun 15 07:28:54 2004//
|
||||
/eoFitnessScalingSelect.h/1.2/Fri Feb 16 08:21:25 2001//
|
||||
/eoFlOrBinOp.h/1.1/Sat Aug 2 06:42:33 2003//
|
||||
/eoFlOrMonOp.h/1.2/Mon Mar 14 21:00:00 2005//
|
||||
/eoFlOrQuadOp.h/1.1/Sat Aug 2 06:42:33 2003//
|
||||
/eoFunctor.h/1.7/Wed Dec 1 09:22:48 2004//
|
||||
/eoFunctorStore.cpp/1.5/Wed Dec 7 15:51:32 2005//
|
||||
/eoFunctorStore.h/1.7/Wed Dec 7 15:40:23 2005//
|
||||
/eoG3Replacement.h/1.2/Thu Feb 27 19:25:59 2003//
|
||||
/eoGenContinue.h/1.10/Fri Dec 9 17:49:43 2005//
|
||||
/eoGenOp.h/1.11/Tue Aug 10 17:19:46 2004//
|
||||
/eoGeneralBreeder.h/1.7/Thu Feb 27 19:25:59 2003//
|
||||
/eoInit.h/1.16/Wed Dec 1 09:19:47 2004//
|
||||
/eoInvalidateOps.h/1.3/Thu Feb 15 04:47:18 2001//
|
||||
/eoLinearFitScaling.h/1.7/Mon Mar 27 18:55:19 2006//
|
||||
/eoMGGReplacement.h/1.4/Sun Mar 2 11:26:45 2003//
|
||||
/eoMerge.h/1.12/Thu Feb 27 19:25:58 2003//
|
||||
/eoMergeReduce.h/1.2/Fri Jan 5 05:42:08 2001//
|
||||
/eoNDSorting.h/1.20/Mon Mar 27 18:55:19 2006//
|
||||
/eoObject.h/1.15/Thu Feb 27 19:25:58 2003//
|
||||
/eoOneToOneBreeder.h/1.3/Thu Feb 27 19:25:57 2003//
|
||||
/eoOp.h/1.29/Tue Aug 10 17:19:46 2004//
|
||||
/eoOpContainer.h/1.10/Mon Mar 27 18:55:19 2006//
|
||||
/eoOpSelMason.h/1.5/Thu Feb 27 19:25:55 2003//
|
||||
/eoParetoConstraintFitness.h/1.3/Fri Apr 18 13:32:39 2003//
|
||||
/eoParetoFitness.cpp/1.2/Mon Feb 4 13:16:50 2002//
|
||||
/eoParetoFitness.h/1.10/Thu Feb 27 19:25:54 2003//
|
||||
/eoParetoRanking.h/1.5/Mon Mar 27 18:55:19 2006//
|
||||
/eoPerf2Worth.h/1.10/Mon Mar 27 18:55:19 2006//
|
||||
/eoPeriodicContinue.h/1.1/Tue Feb 28 14:39:45 2006//
|
||||
/eoPersistent.cpp/1.9/Thu Feb 27 19:25:53 2003//
|
||||
/eoPersistent.h/1.8/Thu Feb 27 19:25:53 2003//
|
||||
/eoPop.h/1.40/Thu Dec 23 10:14:42 2004//
|
||||
/eoPopAlgo.h/1.1/Wed Mar 27 17:28:04 2002//
|
||||
/eoPopEvalFunc.h/1.2/Tue Sep 4 06:50:42 2001//
|
||||
/eoPopulator.h/1.9/Mon Sep 5 16:47:53 2005//
|
||||
/eoPrintable.cpp/1.3/Thu Feb 27 19:25:52 2003//
|
||||
/eoPrintable.h/1.6/Thu Feb 27 19:25:52 2003//
|
||||
/eoPropGAGenOp.h/1.1/Sat May 7 15:43:29 2005//
|
||||
/eoProportionalCombinedOp.h/1.8/Tue Aug 10 17:19:46 2004//
|
||||
/eoProportionalSelect.h/1.4/Wed Jun 4 09:33:27 2003//
|
||||
/eoRandomSelect.h/1.12/Mon Jun 17 09:18:37 2002//
|
||||
/eoRanking.h/1.9/Mon Mar 27 18:55:19 2006//
|
||||
/eoRankingSelect.h/1.4/Thu Feb 27 19:25:52 2003//
|
||||
/eoReduce.h/1.11/Thu Feb 27 19:25:52 2003//
|
||||
/eoReduceMerge.h/1.1/Tue Dec 19 18:41:19 2000//
|
||||
/eoReduceMergeReduce.h/1.3/Thu Feb 27 19:25:52 2003//
|
||||
/eoReduceSplit.h/1.4/Mon Jan 2 14:09:22 2006//
|
||||
/eoReplacement.h/1.5/Tue Aug 10 17:19:46 2004//
|
||||
/eoSGA.h/1.11/Thu Dec 23 17:26:38 2004//
|
||||
/eoSGAGenOp.h/1.3/Thu Feb 27 19:25:51 2003//
|
||||
/eoSGATransform.h/1.8/Tue Aug 10 17:19:46 2004//
|
||||
/eoSTLFunctor.h/1.2/Wed Mar 21 12:10:13 2001//
|
||||
/eoScalarFitness.h/1.7/Sat Feb 17 10:51:31 2001//
|
||||
/eoScalarFitnessAssembled.cpp/1.1/Wed Apr 2 21:08:13 2003//
|
||||
/eoScalarFitnessAssembled.h/1.11/Thu Dec 23 15:29:06 2004//
|
||||
/eoSelect.h/1.2/Mon Oct 9 16:13:19 2000//
|
||||
/eoSelectFactory.h/1.4/Thu Feb 27 19:25:52 2003//
|
||||
/eoSelectFromWorth.h/1.9/Thu Dec 23 15:29:06 2004//
|
||||
/eoSelectMany.h/1.2/Mon May 7 07:13:36 2001//
|
||||
/eoSelectNumber.h/1.1/Tue Dec 19 18:41:19 2000//
|
||||
/eoSelectOne.h/1.4/Sat Nov 10 09:02:17 2001//
|
||||
/eoSelectPerc.h/1.3/Fri Dec 1 15:46:07 2000//
|
||||
/eoSequentialSelect.h/1.4/Mon Oct 3 12:54:45 2005//
|
||||
/eoSharing.h/1.6/Mon Mar 27 18:55:19 2006//
|
||||
/eoSharingSelect.h/1.2/Sat Aug 28 16:26:03 2004//
|
||||
/eoSimpleEDA.h/1.1/Mon Jun 9 06:17:26 2003//
|
||||
/eoSteadyFitContinue.h/1.5/Tue Aug 10 17:19:46 2004//
|
||||
/eoStochTournamentSelect.h/1.5/Thu Feb 27 19:25:48 2003//
|
||||
/eoStochasticUniversalSelect.h/1.3/Thu Dec 23 17:22:52 2004//
|
||||
/eoSurviveAndDie.h/1.3/Thu Dec 23 15:29:06 2004//
|
||||
/eoTransform.h/1.2/Mon Oct 9 16:13:19 2000//
|
||||
/eoTruncSelect.h/1.2/Sun Jan 5 16:31:47 2003//
|
||||
/eoTruncatedSelectMany.h/1.2/Thu Feb 27 19:25:48 2003//
|
||||
/eoTruncatedSelectOne.h/1.2/Mon Jun 17 09:19:17 2002//
|
||||
/eoVariableLengthCrossover.h/1.14/Fri Oct 7 08:27:59 2005//
|
||||
/eoVariableLengthMutation.h/1.10/Wed Sep 28 21:49:26 2005//
|
||||
/eoVector.h/1.17/Thu Oct 6 17:22:40 2005//
|
||||
/es.h/1.8/Tue Jul 29 05:33:58 2003//
|
||||
/ga.h/1.3/Sat Sep 8 05:58:13 2001//
|
||||
D
|
||||
10
trunk/paradiseo-eo/src/CVS/Entries.Log
Normal file
10
trunk/paradiseo-eo/src/CVS/Entries.Log
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
A D/MGE////
|
||||
A D/do////
|
||||
A D/es////
|
||||
A D/ga////
|
||||
A D/gp////
|
||||
A D/obsolete////
|
||||
A D/other////
|
||||
A D/paradisEO////
|
||||
A D/pyeo////
|
||||
A D/utils////
|
||||
1
trunk/paradiseo-eo/src/CVS/Repository
Normal file
1
trunk/paradiseo-eo/src/CVS/Repository
Normal file
|
|
@ -0,0 +1 @@
|
|||
eo/src
|
||||
1
trunk/paradiseo-eo/src/CVS/Root
Normal file
1
trunk/paradiseo-eo/src/CVS/Root
Normal file
|
|
@ -0,0 +1 @@
|
|||
:ext:evomarc@eodev.cvs.sourceforge.net:/cvsroot/eodev
|
||||
152
trunk/paradiseo-eo/src/EO.h
Normal file
152
trunk/paradiseo-eo/src/EO.h
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// EO.h
|
||||
// (c) GeNeura Team 1998
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EO_H
|
||||
#define EO_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <stdexcept> // std::runtime_error
|
||||
#include <eoObject.h> // eoObject
|
||||
#include <eoPersistent.h> // eoPersistent
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
/** EO is a base class for evolvable objects, that is, the subjects of
|
||||
evolution. EOs have only got a fitness, which at the same time needs to be
|
||||
only an object with the operation less than (<) defined. Fitness says how
|
||||
good is the object; evolution or change of these objects is left to the
|
||||
genetic operators. A fitness less than another means a worse fitness, in
|
||||
whatever the context; thus, fitness is always maximized; although it can
|
||||
be minimized with a proper definition of the < operator. The fitness
|
||||
object must have, besides an void ctor, a copy ctor.
|
||||
*/
|
||||
template<class F> class EO: public eoObject, public eoPersistent
|
||||
{
|
||||
public:
|
||||
typedef F Fitness;
|
||||
|
||||
/** Default constructor.
|
||||
Fitness must have a ctor which takes 0 as a value; we can not use void
|
||||
ctors here since default types like float have no void initializer.
|
||||
VC++ allows it, but gcc does not
|
||||
*/
|
||||
EO(): repFitness(Fitness()), invalidFitness(true) {}
|
||||
|
||||
/// Virtual dtor
|
||||
virtual ~EO() {};
|
||||
|
||||
/// Return fitness value.
|
||||
Fitness fitness() const {
|
||||
if (invalid())
|
||||
throw std::runtime_error("invalid fitness");
|
||||
return repFitness;
|
||||
}
|
||||
|
||||
// Set fitness as invalid.
|
||||
void invalidate() { invalidFitness = true; }
|
||||
|
||||
/** Set fitness. At the same time, validates it.
|
||||
* @param _fitness New fitness value.
|
||||
*/
|
||||
void fitness(const Fitness& _fitness)
|
||||
{
|
||||
repFitness = _fitness;
|
||||
invalidFitness = false;
|
||||
}
|
||||
|
||||
/** Return true If fitness value is invalid, false otherwise.
|
||||
* @return true If fitness is invalid.
|
||||
*/
|
||||
bool invalid() const { return invalidFitness; }
|
||||
|
||||
/** Returns true if
|
||||
@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
|
||||
//@{
|
||||
|
||||
/** Return the class id.
|
||||
* @return the class name as a std::string
|
||||
*/
|
||||
virtual std::string className() const { return "EO"; }
|
||||
|
||||
/**
|
||||
* Read object.\\
|
||||
* Calls base class, just in case that one had something to do.
|
||||
* The read and print methods should be compatible and have the same format.
|
||||
* In principle, format is "plain": they just print a number
|
||||
* @param _is a std::istream.
|
||||
* @throw runtime_std::exception If a valid object can't be read.
|
||||
*/
|
||||
virtual void readFrom(std::istream& _is) {
|
||||
|
||||
// the new version of the reafFrom function.
|
||||
// It can distinguish between valid and invalid fitness values.
|
||||
std::string fitness_str;
|
||||
int pos = _is.tellg();
|
||||
_is >> fitness_str;
|
||||
|
||||
if (fitness_str == "INVALID")
|
||||
{
|
||||
invalidFitness = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
invalidFitness = false;
|
||||
_is.seekg(pos); // rewind
|
||||
_is >> repFitness;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write object. Called printOn since it prints the object _on_ a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const {
|
||||
|
||||
|
||||
// the latest version of the code. Very similar to the old code
|
||||
if (invalid()) {
|
||||
_os << "INVALID ";
|
||||
}
|
||||
else
|
||||
{
|
||||
_os << repFitness << ' ';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//@}
|
||||
|
||||
private:
|
||||
Fitness repFitness; // value of fitness for this chromosome
|
||||
bool invalidFitness; // true if the value of fitness is invalid
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif
|
||||
1
trunk/paradiseo-eo/src/MGE/CVS/Entries
Normal file
1
trunk/paradiseo-eo/src/MGE/CVS/Entries
Normal file
|
|
@ -0,0 +1 @@
|
|||
D
|
||||
1
trunk/paradiseo-eo/src/MGE/CVS/Repository
Normal file
1
trunk/paradiseo-eo/src/MGE/CVS/Repository
Normal file
|
|
@ -0,0 +1 @@
|
|||
eo/src/MGE
|
||||
1
trunk/paradiseo-eo/src/MGE/CVS/Root
Normal file
1
trunk/paradiseo-eo/src/MGE/CVS/Root
Normal file
|
|
@ -0,0 +1 @@
|
|||
:ext:evomarc@eodev.cvs.sourceforge.net:/cvsroot/eodev
|
||||
116
trunk/paradiseo-eo/src/Makefile.am
Normal file
116
trunk/paradiseo-eo/src/Makefile.am
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
# Makefile.am for eo/src
|
||||
|
||||
SUBDIRS = es ga gp do utils other
|
||||
|
||||
lib_LIBRARIES = libeo.a
|
||||
|
||||
libeo_a_SOURCES = eoFunctorStore.cpp \
|
||||
eoPersistent.cpp \
|
||||
eoPrintable.cpp \
|
||||
eoCtrlCContinue.cpp \
|
||||
eoParetoFitness.cpp \
|
||||
eoScalarFitnessAssembled.cpp
|
||||
|
||||
|
||||
pkginclude_HEADERS = eo \
|
||||
EO.h \
|
||||
apply.h \
|
||||
eoAlgo.h \
|
||||
eoBreed.h \
|
||||
eoCellularEasyEA.h \
|
||||
eoCloneOps.h \
|
||||
eoCombinedContinue.h \
|
||||
eoCombinedInit.h \
|
||||
eoContinue.h \
|
||||
eoCounter.h \
|
||||
eoCtrlCContinue.h \
|
||||
eoDetSelect.h \
|
||||
eoDetTournamentSelect.h \
|
||||
eoDistribUpdater.h \
|
||||
eoDistribution.h \
|
||||
eoDominanceMap.h \
|
||||
eoEDA.h \
|
||||
eoEasyEA.h \
|
||||
eoEvalContinue.h \
|
||||
eoEvalFunc.h \
|
||||
eoEvalFuncCounter.h \
|
||||
eoEvalFuncPtr.h \
|
||||
eoFactory.h \
|
||||
eoFitContinue.h \
|
||||
eoFitnessScalingSelect.h \
|
||||
eoFlOrBinOp.h \
|
||||
eoFlOrMonOp.h \
|
||||
eoFlOrQuadOp.h \
|
||||
eoFunctor.h \
|
||||
eoFunctorStore.h \
|
||||
eoG3Replacement.h \
|
||||
eoGenContinue.h \
|
||||
eoGenOp.h \
|
||||
eoGeneralBreeder.h \
|
||||
eoInit.h \
|
||||
eoInvalidateOps.h \
|
||||
eoLinearFitScaling.h \
|
||||
eoMGGReplacement.h \
|
||||
eoMerge.h \
|
||||
eoMergeReduce.h \
|
||||
eoNDSorting.h \
|
||||
eoObject.h \
|
||||
eoOneToOneBreeder.h \
|
||||
eoOp.h \
|
||||
eoOpContainer.h \
|
||||
eoOpSelMason.h \
|
||||
eoParetoConstraintFitness.h \
|
||||
eoParetoFitness.h \
|
||||
eoParetoRanking.h \
|
||||
eoPerf2Worth.h \
|
||||
eoPeriodicContinue.h \
|
||||
eoPersistent.h \
|
||||
eoPop.h \
|
||||
eoPopAlgo.h \
|
||||
eoPopEvalFunc.h \
|
||||
eoPopulator.h \
|
||||
eoPrintable.h \
|
||||
eoPropGAGenOp.h \
|
||||
eoProportionalCombinedOp.h \
|
||||
eoProportionalSelect.h \
|
||||
eoRandomSelect.h \
|
||||
eoRanking.h \
|
||||
eoRankingSelect.h \
|
||||
eoReduce.h \
|
||||
eoReduceMerge.h \
|
||||
eoReduceMergeReduce.h \
|
||||
eoReduceSplit.h \
|
||||
eoReplacement.h \
|
||||
eoSGA.h \
|
||||
eoSGAGenOp.h \
|
||||
eoSGATransform.h \
|
||||
eoSTLFunctor.h \
|
||||
eoScalarFitness.h \
|
||||
eoScalarFitnessAssembled.cpp \
|
||||
eoScalarFitnessAssembled.h \
|
||||
eoSelect.h \
|
||||
eoSelectFactory.h \
|
||||
eoSelectFromWorth.h \
|
||||
eoSelectMany.h \
|
||||
eoSelectNumber.h \
|
||||
eoSelectOne.h \
|
||||
eoSelectPerc.h \
|
||||
eoSequentialSelect.h \
|
||||
eoSharing.h \
|
||||
eoSharingSelect.h \
|
||||
eoSimpleEDA.h \
|
||||
eoSteadyFitContinue.h \
|
||||
eoStochTournamentSelect.h \
|
||||
eoStochasticUniversalSelect.h \
|
||||
eoSurviveAndDie.h \
|
||||
eoTransform.h \
|
||||
eoTruncSelect.h \
|
||||
eoTruncatedSelectMany.h \
|
||||
eoTruncatedSelectOne.h \
|
||||
eoVariableLengthCrossover.h \
|
||||
eoVariableLengthMutation.h \
|
||||
eoVector.h \
|
||||
es.h \
|
||||
ga.h
|
||||
|
||||
AM_CXXFLAGS = -I$(top_srcdir)/src
|
||||
44
trunk/paradiseo-eo/src/apply.h
Normal file
44
trunk/paradiseo-eo/src/apply.h
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// -*- 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>
|
||||
|
||||
/**
|
||||
Applies a unary function to a std::vector of things.
|
||||
*/
|
||||
template <class EOT>
|
||||
void apply(eoUF<EOT&, void>& _proc, std::vector<EOT>& _pop)
|
||||
{
|
||||
for (unsigned i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
_proc(_pop[i]);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
1
trunk/paradiseo-eo/src/do/.cvsignore
Normal file
1
trunk/paradiseo-eo/src/do/.cvsignore
Normal file
|
|
@ -0,0 +1 @@
|
|||
Makefile.in
|
||||
16
trunk/paradiseo-eo/src/do/CVS/Entries
Normal file
16
trunk/paradiseo-eo/src/do/CVS/Entries
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
/.cvsignore/1.1/Fri Sep 17 17:00:04 2004//
|
||||
/Makefile.am/1.3/Wed Sep 22 18:18:30 2004//
|
||||
/Readme/1.2/Tue Sep 4 06:35:58 2001//
|
||||
/make_algo_easea.h/1.2/Thu Feb 27 19:25:26 2003//
|
||||
/make_algo_pareto.h/1.3/Mon Apr 4 20:41:05 2005//
|
||||
/make_algo_scalar.h/1.15/Tue Sep 28 17:13:34 2004//
|
||||
/make_checkpoint.h/1.13/Wed Oct 5 21:34:19 2005//
|
||||
/make_checkpoint_FDC.h/1.3/Thu Feb 27 19:25:25 2003//
|
||||
/make_checkpoint_assembled.h/1.4/Wed Oct 5 21:34:19 2005//
|
||||
/make_checkpoint_pareto.h/1.10/Mon Oct 10 13:34:21 2005//
|
||||
/make_continue.h/1.8/Mon Sep 12 17:53:25 2005//
|
||||
/make_continue_pareto.h/1.2/Thu Feb 27 19:25:25 2003//
|
||||
/make_general_replacement.h/1.4/Sun Apr 27 06:08:11 2003//
|
||||
/make_pop.h/1.8/Mon Sep 26 10:18:15 2005//
|
||||
/make_run.h/1.1/Tue Apr 24 04:52:04 2001//
|
||||
D
|
||||
1
trunk/paradiseo-eo/src/do/CVS/Repository
Normal file
1
trunk/paradiseo-eo/src/do/CVS/Repository
Normal file
|
|
@ -0,0 +1 @@
|
|||
eo/src/do
|
||||
1
trunk/paradiseo-eo/src/do/CVS/Root
Normal file
1
trunk/paradiseo-eo/src/do/CVS/Root
Normal file
|
|
@ -0,0 +1 @@
|
|||
:ext:evomarc@eodev.cvs.sourceforge.net:/cvsroot/eodev
|
||||
15
trunk/paradiseo-eo/src/do/Makefile.am
Normal file
15
trunk/paradiseo-eo/src/do/Makefile.am
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
pkginclude_HEADERS = make_algo_easea.h \
|
||||
make_algo_pareto.h \
|
||||
make_algo_scalar.h \
|
||||
make_checkpoint.h \
|
||||
make_checkpoint_FDC.h \
|
||||
make_checkpoint_assembled.h \
|
||||
make_checkpoint_pareto.h \
|
||||
make_continue.h \
|
||||
make_continue_pareto.h \
|
||||
make_general_replacement.h \
|
||||
make_pop.h \
|
||||
make_run.h
|
||||
|
||||
|
||||
EXTRA_DIST = Readme
|
||||
36
trunk/paradiseo-eo/src/do/Readme
Normal file
36
trunk/paradiseo-eo/src/do/Readme
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
This directory contains templatized code that is supposed to be
|
||||
instanciated and compiled in an actual library for every type of EOT
|
||||
|
||||
The user can then modify and recompile only the part he/she wishes to
|
||||
change (as in any library!).
|
||||
|
||||
See in EO src/ga dir the corresponding .cpp files, that simply instanciate
|
||||
the functions here for eoBit<double> AND eoBit<eoMinimizingFitness>
|
||||
and in EO test dir the t-eoGA.cpp file that is a sample program that uses
|
||||
the whole facility.
|
||||
|
||||
All make_XXX.h file define some parser-based constructions of basic
|
||||
Evolutionary Algorithms components, using state-based memory management
|
||||
(see in src/utils dir, or read the tutorial).
|
||||
|
||||
In this src/do dir, the following ***representation indedendent*** code
|
||||
is defined
|
||||
|
||||
make_algo_scalar.h The selection/replacement for scalar fitnesses
|
||||
make_checkpoint.h The output facilities
|
||||
make_continue.h The stpping criteria
|
||||
make_pop.h Init of the population (from an EOT initializer)
|
||||
make_run.h Run the algorithm
|
||||
|
||||
See also (NOW MOVED TO util DIR, as it was useful everywhere)
|
||||
make_help.cpp Help on demand (+ status file)
|
||||
|
||||
Note:
|
||||
-----
|
||||
two additional make_XXX.h files need to be defined for each representation
|
||||
|
||||
make_genotype.h Builds an initializer for the corresponding EOType
|
||||
make_op.h Builds a general Operator to be used in the algo
|
||||
|
||||
MS, April 23, 2001
|
||||
July 23, 2001
|
||||
368
trunk/paradiseo-eo/src/do/make_algo_easea.h
Normal file
368
trunk/paradiseo-eo/src/do/make_algo_easea.h
Normal file
|
|
@ -0,0 +1,368 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// make_algo_easea.h
|
||||
// (c) Marc Schoenauer and Pierre Collet, 2002
|
||||
/*
|
||||
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: Pierre.Collet@polytechnique.fr
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _make_algo_easea_h
|
||||
#define _make_algo_easea_h
|
||||
|
||||
#include <utils/eoData.h> // for eo_is_a_rate
|
||||
// everything tha's needed for the algorithms - SCALAR fitness
|
||||
|
||||
// Selection
|
||||
// the eoSelectOne's
|
||||
#include <eoRandomSelect.h>
|
||||
#include <eoSequentialSelect.h>
|
||||
#include <eoDetTournamentSelect.h>
|
||||
#include <eoProportionalSelect.h>
|
||||
#include <eoFitnessScalingSelect.h>
|
||||
#include <eoRankingSelect.h>
|
||||
#include <eoStochTournamentSelect.h>
|
||||
// #include <eoSelect.h> included in all others
|
||||
|
||||
// Breeders
|
||||
#include <eoGeneralBreeder.h>
|
||||
|
||||
// Replacement
|
||||
#include "make_general_replacement.h"
|
||||
#include "eoMGGReplacement.h"
|
||||
#include "eoG3Replacement.h"
|
||||
|
||||
|
||||
// Algorithm (only this one needed)
|
||||
#include <eoEasyEA.h>
|
||||
|
||||
// also need the parser and param includes
|
||||
#include <utils/eoParser.h>
|
||||
#include <utils/eoState.h>
|
||||
|
||||
|
||||
/*
|
||||
* This function builds the algorithm (i.e. selection and replacement)
|
||||
* from existing continue (or checkpoint) and operators
|
||||
*
|
||||
* It uses a parser (to get user parameters) and a state (to store the memory)
|
||||
* the last argument is an individual, needed for 2 reasons
|
||||
* it disambiguates the call after instanciations
|
||||
* some operator might need some private information about the indis
|
||||
*
|
||||
* This is why the template is the complete EOT even though only the fitness
|
||||
* is actually templatized here
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc<EOT>& _eval, eoContinue<EOT>& _continue, eoGenOp<EOT>& _op)
|
||||
{
|
||||
// the selection
|
||||
eoValueParam<eoParamParamType>& selectionParam = _parser.createParam(eoParamParamType("DetTour(2)"), "selection", "Selection: Roulette, Ranking(p,e), DetTour(T), StochTour(t), Sequential(ordered/unordered) or EliteSequentialSelect", 'S', "Evolution Engine");
|
||||
|
||||
eoParamParamType & ppSelect = selectionParam.value(); // std::pair<std::string,std::vector<std::string> >
|
||||
|
||||
eoSelectOne<EOT>* select ;
|
||||
if (ppSelect.first == std::string("DetTour"))
|
||||
{
|
||||
unsigned detSize;
|
||||
|
||||
if (!ppSelect.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl;
|
||||
detSize = 2;
|
||||
// put back 2 in parameter for consistency (and status file)
|
||||
ppSelect.second.push_back(std::string("2"));
|
||||
}
|
||||
else // parameter passed by user as DetTour(T)
|
||||
detSize = atoi(ppSelect.second[0].c_str());
|
||||
select = new eoDetTournamentSelect<EOT>(detSize);
|
||||
}
|
||||
else if (ppSelect.first == std::string("StochTour"))
|
||||
{
|
||||
double p;
|
||||
if (!ppSelect.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl;
|
||||
p = 1;
|
||||
// put back p in parameter for consistency (and status file)
|
||||
ppSelect.second.push_back(std::string("1"));
|
||||
}
|
||||
else // parameter passed by user as DetTour(T)
|
||||
p = atof(ppSelect.second[0].c_str());
|
||||
|
||||
select = new eoStochTournamentSelect<EOT>(p);
|
||||
}
|
||||
else if (ppSelect.first == std::string("Ranking"))
|
||||
{
|
||||
double p,e;
|
||||
if (ppSelect.second.size()==2) // 2 parameters: pressure and exponent
|
||||
{
|
||||
p = atof(ppSelect.second[0].c_str());
|
||||
e = atof(ppSelect.second[1].c_str());
|
||||
}
|
||||
else if (ppSelect.second.size()==1) // 1 parameter: pressure
|
||||
{
|
||||
std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl;
|
||||
e = 1;
|
||||
ppSelect.second.push_back(std::string("1"));
|
||||
p = atof(ppSelect.second[0].c_str());
|
||||
}
|
||||
else // no parameters ... or garbage
|
||||
{
|
||||
std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl;
|
||||
p=2;
|
||||
e=1;
|
||||
// put back in parameter for consistency (and status file)
|
||||
ppSelect.second.resize(2); // just in case
|
||||
ppSelect.second[0] = (std::string("2"));
|
||||
ppSelect.second[1] = (std::string("1"));
|
||||
}
|
||||
// check for authorized values
|
||||
// pressure in (0,1]
|
||||
if ( (p<=1) || (p>2) )
|
||||
{
|
||||
std::cerr << "WARNING, selective pressure must be in (1,2] in Ranking, using 2\n";
|
||||
p=2;
|
||||
ppSelect.second[0] = (std::string("2"));
|
||||
}
|
||||
// exponent >0
|
||||
if (e<=0)
|
||||
{
|
||||
std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n";
|
||||
e=1;
|
||||
ppSelect.second[1] = (std::string("1"));
|
||||
}
|
||||
// now we're OK
|
||||
eoPerf2Worth<EOT> & p2w = _state.storeFunctor( new eoRanking<EOT>(p,e) );
|
||||
select = new eoRouletteWorthSelect<EOT>(p2w);
|
||||
}
|
||||
else if (ppSelect.first == std::string("Sequential")) // one after the other
|
||||
{
|
||||
bool b;
|
||||
if (ppSelect.second.size() == 0) // no argument -> default = ordered
|
||||
{
|
||||
b=true;
|
||||
// put back in parameter for consistency (and status file)
|
||||
ppSelect.second.push_back(std::string("ordered"));
|
||||
}
|
||||
else
|
||||
b = !(ppSelect.second[0] == std::string("unordered"));
|
||||
select = new eoSequentialSelect<EOT>(b);
|
||||
}
|
||||
else if (ppSelect.first == std::string("EliteSequential")) // Best first, one after the other in random order afterwards
|
||||
{
|
||||
select = new eoEliteSequentialSelect<EOT>;
|
||||
}
|
||||
else if (ppSelect.first == std::string("Roulette")) // no argument (yet)
|
||||
{
|
||||
select = new eoProportionalSelect<EOT>;
|
||||
}
|
||||
else if (ppSelect.first == std::string("Random")) // no argument
|
||||
{
|
||||
select = new eoRandomSelect<EOT>;
|
||||
}
|
||||
else
|
||||
{
|
||||
std::string stmp = std::string("Invalid selection: ") + ppSelect.first;
|
||||
throw std::runtime_error(stmp.c_str());
|
||||
}
|
||||
|
||||
_state.storeFunctor(select);
|
||||
|
||||
// the number of offspring
|
||||
eoValueParam<eoHowMany>& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine");
|
||||
|
||||
/////////////////////////////////////////////////////
|
||||
// the replacement
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
/** Replacement type - high level: predefined replacements
|
||||
* ESComma :
|
||||
* elite = 0
|
||||
* surviveParents=0 (no reduce)
|
||||
* surviveOffspring=100% (no reduce)
|
||||
* reduceFinal = Deterministic
|
||||
*
|
||||
* ESPlus : idem, except for
|
||||
* surviveParents = 100%
|
||||
*
|
||||
* GGA : generational GA - idem ESComma except for
|
||||
* offspringRate = 100%
|
||||
* all reducers are unused
|
||||
*
|
||||
* SSGA(T/t) : Steady-State GA
|
||||
* surviveParents = 1.0 - offspringRate
|
||||
* reduceFinal = DetTour(T>1) ou StochTour(0.5<t<1)
|
||||
*
|
||||
* EP(T) : Evolutionary Programming
|
||||
* offspringRate=100%
|
||||
* surviveParents = 100%
|
||||
* surviveOffspring = 100%
|
||||
* reduceFinal = EP(T)
|
||||
*
|
||||
* G3 and MGG are excetions at the moment, treated on their own
|
||||
*
|
||||
*/
|
||||
|
||||
eoParamParamType & replacementParam = _parser.createParam(eoParamParamType("General"), "replacement", "Type of replacement: General, or Generational, ESComma, ESPlus, SSGA(T), EP(T), G3, MGG(T)", '\0', "Evolution Engine").value();
|
||||
// the pointer
|
||||
eoReplacement<EOT> * ptReplace;
|
||||
|
||||
// first, separate G3 and MGG
|
||||
// maybe one day we have a common class - but is it really necessary???
|
||||
if (replacementParam.first == std::string("G3"))
|
||||
{
|
||||
// reduce the parents: by default, survive parents = -2 === 2 parents die
|
||||
eoHowMany surviveParents = _parser.createParam(eoHowMany(-2,false), "surviveParents", "Nb of surviving parents (percentage or absolute)", '\0', "Evolution Engine / Replacement").value();
|
||||
// at the moment, this is the only argument
|
||||
ptReplace = new eoG3Replacement<EOT>(-surviveParents); // must receive nb of eliminated parets!
|
||||
_state.storeFunctor(ptReplace);
|
||||
}
|
||||
else if (replacementParam.first == std::string("MGG"))
|
||||
{
|
||||
float t;
|
||||
unsigned tSize;
|
||||
// reduce the parents: by default, survive parents = -2 === 2 parents die
|
||||
eoHowMany surviveParents = _parser.createParam(eoHowMany(-2,false), "surviveParents", "Nb of surviving parents (percentage or absolute)", '\0', "Evolution Engine / Replacement").value();
|
||||
// the tournament size
|
||||
if (!replacementParam.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to MGG replacement, using 2" << std::endl;
|
||||
tSize = 2;
|
||||
// put back 2 in parameter for consistency (and status file)
|
||||
replacementParam.second.push_back(std::string("2"));
|
||||
}
|
||||
else
|
||||
{
|
||||
t = atof(replacementParam.second[0].c_str());
|
||||
if (t>=2)
|
||||
{ // build the appropriate deafult value
|
||||
tSize = unsigned(t);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw std::runtime_error("Sorry, only deterministic tournament available at the moment");
|
||||
}
|
||||
}
|
||||
ptReplace = new eoMGGReplacement<EOT>(-surviveParents, tSize);
|
||||
_state.storeFunctor(ptReplace);
|
||||
}
|
||||
else { // until the end of what was the only loop/switch
|
||||
|
||||
// the default deafult values
|
||||
eoHowMany elite (0.0);
|
||||
bool strongElitism (false);
|
||||
eoHowMany surviveParents (0.0);
|
||||
eoParamParamType reduceParentType ("Deterministic");
|
||||
eoHowMany surviveOffspring (1.0);
|
||||
eoParamParamType reduceOffspringType ("Deterministic");
|
||||
eoParamParamType reduceFinalType ("Deterministic");
|
||||
|
||||
// depending on the value entered by the user, change some of the above
|
||||
double t;
|
||||
|
||||
// ---------- General
|
||||
if (replacementParam.first == std::string("General"))
|
||||
{
|
||||
; // defaults OK
|
||||
}
|
||||
// ---------- ESComma
|
||||
else if (replacementParam.first == std::string("ESComma"))
|
||||
{
|
||||
; // OK too
|
||||
}
|
||||
// ---------- ESPlus
|
||||
else if (replacementParam.first == std::string("ESPlus"))
|
||||
{
|
||||
surviveParents = eoHowMany(1.0);
|
||||
}
|
||||
// ---------- Generational
|
||||
else if (replacementParam.first == std::string("Generational"))
|
||||
{
|
||||
; // OK too (we should check nb of offspring)
|
||||
}
|
||||
// ---------- EP
|
||||
else if (replacementParam.first == std::string("EP"))
|
||||
{
|
||||
if (!replacementParam.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to EP replacement, using 6" << std::endl;
|
||||
// put back 6 in parameter for consistency (and status file)
|
||||
replacementParam.second.push_back(std::string("6"));
|
||||
}
|
||||
// by coincidence, the syntax for the EP reducer is the same than here:
|
||||
reduceFinalType = replacementParam;
|
||||
surviveParents = eoHowMany(1.0);
|
||||
}
|
||||
// ---------- SSGA
|
||||
else if (replacementParam.first == std::string("SSGA"))
|
||||
{
|
||||
if (!replacementParam.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to SSGA replacement, using 2" << std::endl;
|
||||
// put back 2 in parameter for consistency (and status file)
|
||||
replacementParam.second.push_back(std::string("2"));
|
||||
reduceParentType = eoParamParamType(std::string("DetTour(2)"));
|
||||
}
|
||||
else
|
||||
{
|
||||
t = atof(replacementParam.second[0].c_str());
|
||||
if (t>=2)
|
||||
{ // build the appropriate deafult value
|
||||
reduceParentType = eoParamParamType(std::string("DetTour(") + replacementParam.second[0].c_str() + ")");
|
||||
}
|
||||
else // check for [0.5,1] will be made in make_general_replacement
|
||||
{ // build the appropriate deafult value
|
||||
reduceParentType = eoParamParamType(std::string("StochTour(") + replacementParam.second[0].c_str() + ")");
|
||||
}
|
||||
}
|
||||
//
|
||||
surviveParents = eoHowMany(-1);
|
||||
surviveOffspring = eoHowMany(1);
|
||||
}
|
||||
else // no replacement recognized
|
||||
{
|
||||
throw std::runtime_error("Invalid replacement type " + replacementParam.first);
|
||||
}
|
||||
|
||||
ptReplace = & make_general_replacement<EOT>(
|
||||
_parser, _state, elite, strongElitism, surviveParents, reduceParentType, surviveOffspring, reduceOffspringType, reduceFinalType);
|
||||
|
||||
} // end of the ugly construct due to G3 and MGG - totaly heterogeneous at the moment
|
||||
|
||||
|
||||
///////////////////////////////
|
||||
// the general breeder
|
||||
///////////////////////////////
|
||||
eoGeneralBreeder<EOT> *breed =
|
||||
new eoGeneralBreeder<EOT>(*select, _op, offspringRateParam.value());
|
||||
_state.storeFunctor(breed);
|
||||
|
||||
///////////////////////////////
|
||||
// now the eoEasyEA
|
||||
///////////////////////////////
|
||||
eoAlgo<EOT> *algo = new eoEasyEA<EOT>(_continue, _eval, *breed, *ptReplace);
|
||||
_state.storeFunctor(algo);
|
||||
// that's it!
|
||||
return *algo;
|
||||
}
|
||||
|
||||
#endif
|
||||
203
trunk/paradiseo-eo/src/do/make_algo_pareto.h
Normal file
203
trunk/paradiseo-eo/src/do/make_algo_pareto.h
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// make_algo_pareto.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2002
|
||||
/*
|
||||
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@inria.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _make_algo_pareto_h
|
||||
#define _make_algo_pareto_h
|
||||
|
||||
#include "utils/eoData.h" // for eo_is_a_rate
|
||||
// everything tha's needed for the algorithms - SCALAR fitness
|
||||
|
||||
// Selection
|
||||
// the eoSelectOne's
|
||||
#include "eoSelectFromWorth.h"
|
||||
#include "eoNDSorting.h"
|
||||
|
||||
// Breeders
|
||||
#include "eoGeneralBreeder.h"
|
||||
|
||||
// Replacement - at the moment limited to eoNDPlusReplacement, locally defined
|
||||
#include "eoReplacement.h"
|
||||
|
||||
template <class EOT, class WorthT = double>
|
||||
class eoNDPlusReplacement : public eoReplacement<EOT>
|
||||
{
|
||||
public:
|
||||
eoNDPlusReplacement(eoPerf2Worth<EOT, WorthT>& _perf2worth) : perf2worth(_perf2worth) {}
|
||||
|
||||
struct WorthPair : public std::pair<WorthT, const EOT*>
|
||||
{
|
||||
bool operator<(const WorthPair& other) const { return other.first < this->first; }
|
||||
};
|
||||
|
||||
void operator()(eoPop<EOT>& _parents, eoPop<EOT>& _offspring)
|
||||
{
|
||||
unsigned sz = _parents.size();
|
||||
_parents.reserve(_parents.size() + _offspring.size());
|
||||
copy(_offspring.begin(), _offspring.end(), back_inserter(_parents));
|
||||
|
||||
// calculate worths
|
||||
perf2worth(_parents);
|
||||
perf2worth.sort_pop(_parents);
|
||||
perf2worth.resize(_parents, sz);
|
||||
|
||||
_offspring.clear();
|
||||
}
|
||||
|
||||
private :
|
||||
eoPerf2Worth<EOT, WorthT>& perf2worth;
|
||||
};
|
||||
|
||||
|
||||
// Algorithm (only this one needed)
|
||||
#include "eoEasyEA.h"
|
||||
|
||||
// also need the parser and param includes
|
||||
#include "utils/eoParser.h"
|
||||
#include "utils/eoState.h"
|
||||
|
||||
|
||||
/*
|
||||
* This function builds the algorithm (i.e. selection and replacement)
|
||||
* from existing continue (or checkpoint) and operators
|
||||
*
|
||||
* It uses a parser (to get user parameters) and a state (to store the memory)
|
||||
* the last argument is an individual, needed for 2 reasons
|
||||
* it disambiguates the call after instanciations
|
||||
* some operator might need some private information about the indis
|
||||
*
|
||||
* This is why the template is the complete EOT even though only the fitness
|
||||
* is actually templatized here
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
eoAlgo<EOT> & do_make_algo_pareto(eoParser& _parser, eoState& _state, eoEvalFunc<EOT>& _eval, eoContinue<EOT>& _continue, eoGenOp<EOT>& _op)
|
||||
{
|
||||
// the selection
|
||||
std::string & selStr = _parser.createParam(std::string("NSGA-II"), "selCrit", "Pareto Selection Criterion: NSGA, NSGA-II, ParetoRanking", 'S', "Evolution Engine").value();
|
||||
double nicheSize = _parser.createParam(1.0, "nicheSize", "Size of niche for NSGA-I", '\0', "Evolution Engine").value();
|
||||
eoPerf2Worth<EOT, double> *p2w;
|
||||
if ( (selStr == std::string("NSGA")) || (selStr == std::string("NSGA-I") ) )
|
||||
p2w = new eoNDSorting_I<EOT>(nicheSize);
|
||||
else if (selStr == std::string("NSGA-II"))
|
||||
p2w = new eoNDSorting_II<EOT>();
|
||||
else if (selStr == std::string("ParetoRanking"))
|
||||
{
|
||||
eoDominanceMap<EOT>& dominance = _state.storeFunctor(new eoDominanceMap<EOT>);
|
||||
p2w = new eoParetoRanking<EOT>(dominance);
|
||||
}
|
||||
|
||||
_state.storeFunctor(p2w);
|
||||
|
||||
// now the selector (from p2w) - cut-and-pasted from make_algo_scalar!
|
||||
// only all classes are now ...FromWorth ...
|
||||
// only the ranking is not re-implemented (yet?)
|
||||
eoValueParam<eoParamParamType>& selectionParam = _parser.createParam(eoParamParamType("DetTour(2)"), "selection", "Selection: Roulette, DetTour(T), StochTour(t) or Random", 'S', "Evolution Engine");
|
||||
|
||||
eoParamParamType & ppSelect = selectionParam.value(); // std::pair<std::string,std::vector<std::string> >
|
||||
|
||||
eoSelectOne<EOT>* select ;
|
||||
if (ppSelect.first == std::string("DetTour"))
|
||||
{
|
||||
unsigned detSize;
|
||||
|
||||
if (!ppSelect.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl;
|
||||
detSize = 2;
|
||||
// put back 2 in parameter for consistency (and status file)
|
||||
ppSelect.second.push_back(std::string("2"));
|
||||
}
|
||||
else // parameter passed by user as DetTour(T)
|
||||
detSize = atoi(ppSelect.second[0].c_str());
|
||||
select = new eoDetTournamentWorthSelect<EOT>(*p2w, detSize);
|
||||
}
|
||||
else if (ppSelect.first == std::string("StochTour"))
|
||||
{
|
||||
double p;
|
||||
if (!ppSelect.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl;
|
||||
p = 1;
|
||||
// put back p in parameter for consistency (and status file)
|
||||
ppSelect.second.push_back(std::string("1"));
|
||||
}
|
||||
else // parameter passed by user as DetTour(T)
|
||||
p = atof(ppSelect.second[0].c_str());
|
||||
|
||||
select = new eoStochTournamentWorthSelect<EOT>(*p2w, p);
|
||||
}
|
||||
// else if (ppSelect.first == std::string("Sequential")) // one after the other
|
||||
// {
|
||||
// bool b;
|
||||
// if (ppSelect.second.size() == 0) // no argument -> default = ordered
|
||||
// {
|
||||
// b=true;
|
||||
// // put back in parameter for consistency (and status file)
|
||||
// ppSelect.second.push_back(std::string("ordered"));
|
||||
// }
|
||||
// else
|
||||
// b = !(ppSelect.second[0] == std::string("unordered"));
|
||||
// select = new eoSequentialWorthSelect<EOT>(b);
|
||||
// }
|
||||
else if (ppSelect.first == std::string("Roulette")) // no argument (yet)
|
||||
{
|
||||
select = new eoRouletteWorthSelect<EOT>(*p2w);
|
||||
}
|
||||
else if (ppSelect.first == std::string("Random")) // no argument, no perf2Worth
|
||||
{
|
||||
select = new eoRandomSelect<EOT>;
|
||||
}
|
||||
else
|
||||
{
|
||||
std::string stmp = std::string("Invalid selection: ") + ppSelect.first;
|
||||
throw std::runtime_error(stmp.c_str());
|
||||
}
|
||||
|
||||
_state.storeFunctor(select);
|
||||
|
||||
|
||||
// the number of offspring
|
||||
eoValueParam<eoHowMany>& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine");
|
||||
|
||||
// the replacement
|
||||
// actually limited to eoNDPlusReplacement
|
||||
eoReplacement<EOT> & replace = _state.storeFunctor(
|
||||
new eoNDPlusReplacement<EOT, double>(*p2w)
|
||||
);
|
||||
|
||||
// the general breeder
|
||||
eoGeneralBreeder<EOT> *breed =
|
||||
new eoGeneralBreeder<EOT>(*select, _op, offspringRateParam.value());
|
||||
_state.storeFunctor(breed);
|
||||
|
||||
// now the eoEasyEA
|
||||
eoAlgo<EOT> *algo = new eoEasyEA<EOT>(_continue, _eval, *breed, replace);
|
||||
_state.storeFunctor(algo);
|
||||
// that's it!
|
||||
return *algo;
|
||||
}
|
||||
|
||||
#endif
|
||||
311
trunk/paradiseo-eo/src/do/make_algo_scalar.h
Normal file
311
trunk/paradiseo-eo/src/do/make_algo_scalar.h
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// make_algo_scalar.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _make_algo_scalar_h
|
||||
#define _make_algo_scalar_h
|
||||
|
||||
#include <utils/eoData.h> // for eo_is_a_rate
|
||||
// everything tha's needed for the algorithms - SCALAR fitness
|
||||
|
||||
// Selection
|
||||
// the eoSelectOne's
|
||||
#include <eoRandomSelect.h>
|
||||
#include <eoSequentialSelect.h>
|
||||
#include <eoDetTournamentSelect.h>
|
||||
#include <eoProportionalSelect.h>
|
||||
#include <eoFitnessScalingSelect.h>
|
||||
#include <eoRankingSelect.h>
|
||||
#include <eoStochTournamentSelect.h>
|
||||
#include <eoSharingSelect.h>
|
||||
#include <utils/eoDistance.h>
|
||||
|
||||
// Breeders
|
||||
#include <eoGeneralBreeder.h>
|
||||
|
||||
// Replacement
|
||||
// #include <eoReplacement.h>
|
||||
#include <eoMergeReduce.h>
|
||||
#include <eoReduceMerge.h>
|
||||
#include <eoSurviveAndDie.h>
|
||||
|
||||
// distance
|
||||
#include <utils/eoDistance.h>
|
||||
|
||||
// Algorithm (only this one needed)
|
||||
#include <eoEasyEA.h>
|
||||
|
||||
// also need the parser and param includes
|
||||
#include <utils/eoParser.h>
|
||||
#include <utils/eoState.h>
|
||||
|
||||
|
||||
/*
|
||||
* This function builds the algorithm (i.e. selection and replacement)
|
||||
* from existing continue (or checkpoint) and operators
|
||||
*
|
||||
* It uses a parser (to get user parameters) and a state (to store the memory)
|
||||
* the last argument is an individual, needed for 2 reasons
|
||||
* it disambiguates the call after instanciations
|
||||
* some operator might need some private information about the indis
|
||||
*
|
||||
* This is why the template is the complete EOT even though only the fitness
|
||||
* is actually templatized here
|
||||
*/
|
||||
|
||||
|
||||
template <class EOT>
|
||||
eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc<EOT>& _eval, eoContinue<EOT>& _continue, eoGenOp<EOT>& _op, eoDistance<EOT> * _dist = NULL)
|
||||
{
|
||||
// the selection : help and comment depend on whether or not a distance is passed
|
||||
std::string comment;
|
||||
if (_dist == NULL)
|
||||
comment = "Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e) or Sequential(ordered/unordered)";
|
||||
else
|
||||
comment = "Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e), Sharing(sigma_share) or Sequential(ordered/unordered)";
|
||||
|
||||
eoValueParam<eoParamParamType>& selectionParam = _parser.createParam(eoParamParamType("DetTour(2)"), "selection", comment, 'S', "Evolution Engine");
|
||||
|
||||
eoParamParamType & ppSelect = selectionParam.value(); // std::pair<std::string,std::vector<std::string> >
|
||||
|
||||
eoSelectOne<EOT>* select ;
|
||||
if (ppSelect.first == std::string("DetTour"))
|
||||
{
|
||||
unsigned detSize;
|
||||
|
||||
if (!ppSelect.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl;
|
||||
detSize = 2;
|
||||
// put back 2 in parameter for consistency (and status file)
|
||||
ppSelect.second.push_back(std::string("2"));
|
||||
}
|
||||
else // parameter passed by user as DetTour(T)
|
||||
detSize = atoi(ppSelect.second[0].c_str());
|
||||
select = new eoDetTournamentSelect<EOT>(detSize);
|
||||
}
|
||||
else if (ppSelect.first == std::string("Sharing"))
|
||||
{
|
||||
double nicheSize;
|
||||
|
||||
if (!ppSelect.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to Sharing, using 0.5" << std::endl;
|
||||
nicheSize = 0.5;
|
||||
// put back 2 in parameter for consistency (and status file)
|
||||
ppSelect.second.push_back(std::string("0.5"));
|
||||
}
|
||||
else // parameter passed by user as DetTour(T)
|
||||
nicheSize = atof(ppSelect.second[0].c_str());
|
||||
if (_dist == NULL) // no distance
|
||||
throw std::runtime_error("You didn't specify a distance when calling make_algo_scalar and using sharing");
|
||||
select = new eoSharingSelect<EOT>(nicheSize, *_dist);
|
||||
}
|
||||
else if (ppSelect.first == std::string("StochTour"))
|
||||
{
|
||||
double p;
|
||||
if (!ppSelect.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl;
|
||||
p = 1;
|
||||
// put back p in parameter for consistency (and status file)
|
||||
ppSelect.second.push_back(std::string("1"));
|
||||
}
|
||||
else // parameter passed by user as DetTour(T)
|
||||
p = atof(ppSelect.second[0].c_str());
|
||||
|
||||
select = new eoStochTournamentSelect<EOT>(p);
|
||||
}
|
||||
else if (ppSelect.first == std::string("Ranking"))
|
||||
{
|
||||
double p,e;
|
||||
if (ppSelect.second.size()==2) // 2 parameters: pressure and exponent
|
||||
{
|
||||
p = atof(ppSelect.second[0].c_str());
|
||||
e = atof(ppSelect.second[1].c_str());
|
||||
}
|
||||
else if (ppSelect.second.size()==1) // 1 parameter: pressure
|
||||
{
|
||||
std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl;
|
||||
e = 1;
|
||||
ppSelect.second.push_back(std::string("1"));
|
||||
p = atof(ppSelect.second[0].c_str());
|
||||
}
|
||||
else // no parameters ... or garbage
|
||||
{
|
||||
std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl;
|
||||
p=2;
|
||||
e=1;
|
||||
// put back in parameter for consistency (and status file)
|
||||
ppSelect.second.resize(2); // just in case
|
||||
ppSelect.second[0] = (std::string("2"));
|
||||
ppSelect.second[1] = (std::string("1"));
|
||||
}
|
||||
// check for authorized values
|
||||
// pressure in (0,1]
|
||||
if ( (p<=1) || (p>2) )
|
||||
{
|
||||
std::cerr << "WARNING, selective pressure must be in (0,1] in Ranking, using 2\n";
|
||||
p=2;
|
||||
ppSelect.second[0] = (std::string("2"));
|
||||
}
|
||||
// exponent >0
|
||||
if (e<=0)
|
||||
{
|
||||
std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n";
|
||||
e=1;
|
||||
ppSelect.second[1] = (std::string("1"));
|
||||
}
|
||||
// now we're OK
|
||||
eoPerf2Worth<EOT> & p2w = _state.storeFunctor( new eoRanking<EOT>(p,e) );
|
||||
select = new eoRouletteWorthSelect<EOT>(p2w);
|
||||
}
|
||||
else if (ppSelect.first == std::string("Sequential")) // one after the other
|
||||
{
|
||||
bool b;
|
||||
if (ppSelect.second.size() == 0) // no argument -> default = ordered
|
||||
{
|
||||
b=true;
|
||||
// put back in parameter for consistency (and status file)
|
||||
ppSelect.second.push_back(std::string("ordered"));
|
||||
}
|
||||
else
|
||||
b = !(ppSelect.second[0] == std::string("unordered"));
|
||||
select = new eoSequentialSelect<EOT>(b);
|
||||
}
|
||||
else if (ppSelect.first == std::string("Roulette")) // no argument (yet)
|
||||
{
|
||||
select = new eoProportionalSelect<EOT>;
|
||||
}
|
||||
else if (ppSelect.first == std::string("Random")) // no argument
|
||||
{
|
||||
select = new eoRandomSelect<EOT>;
|
||||
}
|
||||
else
|
||||
{
|
||||
std::string stmp = std::string("Invalid selection: ") + ppSelect.first;
|
||||
throw std::runtime_error(stmp.c_str());
|
||||
}
|
||||
|
||||
_state.storeFunctor(select);
|
||||
|
||||
// the number of offspring
|
||||
eoValueParam<eoHowMany>& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine");
|
||||
|
||||
// the replacement
|
||||
eoValueParam<eoParamParamType>& replacementParam = _parser.createParam(eoParamParamType("Comma"), "replacement", "Replacement: Comma, Plus or EPTour(T), SSGAWorst, SSGADet(T), SSGAStoch(t)", 'R', "Evolution Engine");
|
||||
|
||||
eoParamParamType & ppReplace = replacementParam.value(); // std::pair<std::string,std::vector<std::string> >
|
||||
|
||||
eoReplacement<EOT>* replace ;
|
||||
if (ppReplace.first == std::string("Comma")) // Comma == generational
|
||||
{
|
||||
replace = new eoCommaReplacement<EOT>;
|
||||
}
|
||||
else if (ppReplace.first == std::string("Plus"))
|
||||
{
|
||||
replace = new eoPlusReplacement<EOT>;
|
||||
}
|
||||
else if (ppReplace.first == std::string("EPTour"))
|
||||
{
|
||||
unsigned detSize;
|
||||
|
||||
if (!ppReplace.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to EPTour, using 6" << std::endl;
|
||||
detSize = 6;
|
||||
// put back in parameter for consistency (and status file)
|
||||
ppReplace.second.push_back(std::string("6"));
|
||||
}
|
||||
else // parameter passed by user as EPTour(T)
|
||||
detSize = atoi(ppSelect.second[0].c_str());
|
||||
|
||||
replace = new eoEPReplacement<EOT>(detSize);
|
||||
}
|
||||
else if (ppReplace.first == std::string("SSGAWorst"))
|
||||
{
|
||||
replace = new eoSSGAWorseReplacement<EOT>;
|
||||
}
|
||||
else if (ppReplace.first == std::string("SSGADet"))
|
||||
{
|
||||
unsigned detSize;
|
||||
|
||||
if (!ppReplace.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to SSGADet, using 2" << std::endl;
|
||||
detSize = 2;
|
||||
// put back in parameter for consistency (and status file)
|
||||
ppReplace.second.push_back(std::string("2"));
|
||||
}
|
||||
else // parameter passed by user as SSGADet(T)
|
||||
detSize = atoi(ppSelect.second[0].c_str());
|
||||
|
||||
replace = new eoSSGADetTournamentReplacement<EOT>(detSize);
|
||||
}
|
||||
else if (ppReplace.first == std::string("SSGAStoch"))
|
||||
{
|
||||
double p;
|
||||
if (!ppReplace.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to SSGAStoch, using 1" << std::endl;
|
||||
p = 1;
|
||||
// put back in parameter for consistency (and status file)
|
||||
ppReplace.second.push_back(std::string("1"));
|
||||
}
|
||||
else // parameter passed by user as SSGADet(T)
|
||||
p = atof(ppSelect.second[0].c_str());
|
||||
|
||||
replace = new eoSSGAStochTournamentReplacement<EOT>(p);
|
||||
}
|
||||
else
|
||||
{
|
||||
std::string stmp = std::string("Invalid replacement: ") + ppReplace.first;
|
||||
throw std::runtime_error(stmp.c_str());
|
||||
}
|
||||
|
||||
_state.storeFunctor(replace);
|
||||
|
||||
// adding weak elitism
|
||||
eoValueParam<bool>& weakElitismParam = _parser.createParam(false, "weakElitism", "Old best parent replaces new worst offspring *if necessary*", 'w', "Evolution Engine");
|
||||
if (weakElitismParam.value())
|
||||
{
|
||||
eoReplacement<EOT> *replaceTmp = replace;
|
||||
replace = new eoWeakElitistReplacement<EOT>(*replaceTmp);
|
||||
_state.storeFunctor(replace);
|
||||
}
|
||||
|
||||
// the general breeder
|
||||
eoGeneralBreeder<EOT> *breed =
|
||||
new eoGeneralBreeder<EOT>(*select, _op, offspringRateParam.value());
|
||||
_state.storeFunctor(breed);
|
||||
|
||||
// now the eoEasyEA
|
||||
eoAlgo<EOT> *algo = new eoEasyEA<EOT>(_continue, _eval, *breed, *replace);
|
||||
_state.storeFunctor(algo);
|
||||
// that's it!
|
||||
return *algo;
|
||||
}
|
||||
|
||||
#endif
|
||||
291
trunk/paradiseo-eo/src/do/make_checkpoint.h
Normal file
291
trunk/paradiseo-eo/src/do/make_checkpoint.h
Normal file
|
|
@ -0,0 +1,291 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// make_checkpoint.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _make_checkpoint_h
|
||||
#define _make_checkpoint_h
|
||||
|
||||
#include <eoScalarFitness.h>
|
||||
#include <utils/selectors.h> // for minimizing_fitness()
|
||||
#include <EO.h>
|
||||
#include <eoEvalFuncCounter.h>
|
||||
#include <utils/checkpointing>
|
||||
|
||||
// at the moment, in utils/make_help.cpp
|
||||
// this should become some eoUtils.cpp with corresponding eoUtils.h
|
||||
bool testDirRes(std::string _dirName, bool _erase);
|
||||
/////////////////// The checkpoint and other I/O //////////////
|
||||
|
||||
|
||||
template <class EOT>
|
||||
eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter<EOT>& _eval, eoContinue<EOT>& _continue)
|
||||
{
|
||||
// first, create a checkpoint from the eoContinue
|
||||
eoCheckPoint<EOT> *checkpoint = new eoCheckPoint<EOT>(_continue);
|
||||
_state.storeFunctor(checkpoint);
|
||||
|
||||
///////////////////
|
||||
// Counters
|
||||
//////////////////
|
||||
// is nb Eval to be used as counter?
|
||||
eoValueParam<bool>& useEvalParam = _parser.createParam(true, "useEval", "Use nb of eval. as counter (vs nb of gen.)", '\0', "Output");
|
||||
eoValueParam<bool>& useTimeParam = _parser.createParam(true, "useTime", "Display time (s) every generation", '\0', "Output");
|
||||
|
||||
// if we want the time, we need an eoTimeCounter
|
||||
eoTimeCounter * tCounter = NULL;
|
||||
|
||||
// Create anyway a generation-counter
|
||||
// Recent change (03/2002): it is now an eoIncrementorParam, both
|
||||
// a parameter AND updater so you can store it into the eoState
|
||||
eoIncrementorParam<unsigned> *generationCounter = new eoIncrementorParam<unsigned>("Gen.");
|
||||
// store it in the state
|
||||
_state.storeFunctor(generationCounter);
|
||||
// And add it to the checkpoint,
|
||||
checkpoint->add(*generationCounter);
|
||||
|
||||
// dir for DISK output
|
||||
eoValueParam<std::string>& dirNameParam = _parser.createParam(std::string("Res"), "resDir", "Directory to store DISK outputs", '\0', "Output - Disk");
|
||||
// shoudl we empty it if exists
|
||||
eoValueParam<bool>& eraseParam = _parser.createParam(true, "eraseDir", "erase files in dirName if any", '\0', "Output - Disk");
|
||||
bool dirOK = false; // not tested yet
|
||||
|
||||
/////////////////////////////////////////
|
||||
// now some statistics on the population:
|
||||
/////////////////////////////////////////
|
||||
/**
|
||||
* existing stats as of today, April 10. 2001
|
||||
*
|
||||
* eoBestFitnessStat : best value in pop - type EOT::Fitness
|
||||
* eoAverageStat : average value in pop - type EOT::Fitness
|
||||
* eoSecondMomentStat: average + stdev - type std::pair<double, double>
|
||||
* eoSortedPopStat : whole population - type std::string (!!)
|
||||
* eoScalarFitnessStat: the fitnesses - type std::vector<double>
|
||||
*/
|
||||
|
||||
// Best fitness in population
|
||||
//---------------------------
|
||||
eoValueParam<bool>& printBestParam = _parser.createParam(true, "printBestStat", "Print Best/avg/stdev every gen.", '\0', "Output");
|
||||
eoValueParam<bool>& plotBestParam = _parser.createParam(false, "plotBestStat", "Plot Best/avg Stat", '\0', "Output - Graphical");
|
||||
eoValueParam<bool>& fileBestParam = _parser.createParam(false, "fileBestStat", "Output bes/avg/std to file", '\0', "Output - Disk");
|
||||
|
||||
eoBestFitnessStat<EOT> *bestStat = NULL;
|
||||
if ( printBestParam.value() || plotBestParam.value() || fileBestParam.value() )
|
||||
// we need the bestStat for at least one of the 3 above
|
||||
{
|
||||
bestStat = new eoBestFitnessStat<EOT>;
|
||||
// store it
|
||||
_state.storeFunctor(bestStat);
|
||||
// add it to the checkpoint
|
||||
checkpoint->add(*bestStat);
|
||||
}
|
||||
|
||||
// Average fitness alone
|
||||
//----------------------
|
||||
eoAverageStat<EOT> *averageStat = NULL; // do we need averageStat?
|
||||
if ( plotBestParam.value() ) // we need it for gnuplot output
|
||||
{
|
||||
averageStat = new eoAverageStat<EOT>;
|
||||
// store it
|
||||
_state.storeFunctor(averageStat);
|
||||
// add it to the checkpoint
|
||||
checkpoint->add(*averageStat);
|
||||
}
|
||||
|
||||
// Second moment stats: average and stdev
|
||||
//---------------------------------------
|
||||
eoSecondMomentStats<EOT> *secondStat = NULL;
|
||||
if ( printBestParam.value() ) // we need it for sreen output
|
||||
{
|
||||
secondStat = new eoSecondMomentStats<EOT>;
|
||||
// store it
|
||||
_state.storeFunctor(secondStat);
|
||||
// add it to the checkpoint
|
||||
checkpoint->add(*secondStat);
|
||||
}
|
||||
|
||||
|
||||
// Dump of the whole population
|
||||
//-----------------------------
|
||||
eoSortedPopStat<EOT> *popStat = NULL;
|
||||
eoValueParam<bool>& printPopParam = _parser.createParam(false, "printPop", "Print sorted pop. every gen.", '\0', "Output");
|
||||
if ( printPopParam.value() ) // we do want pop dump
|
||||
{
|
||||
popStat = new eoSortedPopStat<EOT>;
|
||||
// store it
|
||||
_state.storeFunctor(popStat);
|
||||
// add it to the checkpoint
|
||||
checkpoint->add(*popStat);
|
||||
}
|
||||
|
||||
|
||||
// do we wnat some histogram of fitnesses snpashots?
|
||||
eoValueParam<bool> plotHistogramParam = _parser.createParam(false, "plotHisto", "Plot histogram of fitnesses", '\0', "Output - Graphical");
|
||||
|
||||
///////////////
|
||||
// The monitors
|
||||
///////////////
|
||||
// do we want an eoStdoutMonitor?
|
||||
bool needStdoutMonitor = printBestParam.value()
|
||||
|| printPopParam.value() ;
|
||||
|
||||
// The Stdout monitor will print parameters to the screen ...
|
||||
if ( needStdoutMonitor )
|
||||
{
|
||||
eoStdoutMonitor *monitor = new eoStdoutMonitor(false);
|
||||
_state.storeFunctor(monitor);
|
||||
|
||||
// when called by the checkpoint (i.e. at every generation)
|
||||
checkpoint->add(*monitor);
|
||||
|
||||
// the monitor will output a series of parameters: add them
|
||||
monitor->add(*generationCounter);
|
||||
if (useEvalParam.value()) // we want nb of evaluations
|
||||
monitor->add(_eval);
|
||||
if (useTimeParam.value()) // we want time
|
||||
{
|
||||
tCounter = new eoTimeCounter;
|
||||
_state.storeFunctor(tCounter);
|
||||
checkpoint->add(*tCounter);
|
||||
monitor->add(*tCounter);
|
||||
}
|
||||
if (printBestParam.value())
|
||||
{
|
||||
monitor->add(*bestStat);
|
||||
monitor->add(*secondStat);
|
||||
}
|
||||
if ( printPopParam.value())
|
||||
monitor->add(*popStat);
|
||||
}
|
||||
|
||||
// first handle the dir test - if we need at least one file
|
||||
if ( ( fileBestParam.value() || plotBestParam.value() ||
|
||||
plotHistogramParam.value() )
|
||||
&& !dirOK ) // just in case we add something before
|
||||
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
|
||||
|
||||
if (fileBestParam.value()) // A file monitor for best & secondMoment
|
||||
{
|
||||
#ifdef _MSVC
|
||||
std::string stmp = dirNameParam.value() + "\best.xg";
|
||||
#else
|
||||
std::string stmp = dirNameParam.value() + "/best.xg";
|
||||
#endif
|
||||
eoFileMonitor *fileMonitor = new eoFileMonitor(stmp);
|
||||
// save and give to checkpoint
|
||||
_state.storeFunctor(fileMonitor);
|
||||
checkpoint->add(*fileMonitor);
|
||||
// and feed with some statistics
|
||||
fileMonitor->add(*generationCounter);
|
||||
fileMonitor->add(_eval);
|
||||
if (tCounter) // we want the time as well
|
||||
{
|
||||
// std::cout << "On met timecounter\n";
|
||||
fileMonitor->add(*tCounter);
|
||||
}
|
||||
fileMonitor->add(*bestStat);
|
||||
fileMonitor->add(*secondStat);
|
||||
}
|
||||
|
||||
if (plotBestParam.value()) // an eoGnuplot1DMonitor for best & average
|
||||
{
|
||||
std::string stmp = dirNameParam.value() + "/gnu_best.xg";
|
||||
eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness<EOT>());
|
||||
// save and give to checkpoint
|
||||
_state.storeFunctor(gnuMonitor);
|
||||
checkpoint->add(*gnuMonitor);
|
||||
// and feed with some statistics
|
||||
if (useEvalParam.value()) // do we want eval as X coordinate
|
||||
gnuMonitor->add(_eval);
|
||||
else if (tCounter) // or time?
|
||||
gnuMonitor->add(*tCounter);
|
||||
else // default: generation
|
||||
gnuMonitor->add(*generationCounter);
|
||||
gnuMonitor->add(*bestStat);
|
||||
gnuMonitor->add(*averageStat);
|
||||
}
|
||||
|
||||
// historgram?
|
||||
if (plotHistogramParam.value()) // want to see how the fitness is spread?
|
||||
{
|
||||
eoScalarFitnessStat<EOT> *fitStat = new eoScalarFitnessStat<EOT>;
|
||||
_state.storeFunctor(fitStat);
|
||||
checkpoint->add(*fitStat);
|
||||
// a gnuplot-based monitor for snapshots: needs a dir name
|
||||
eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value());
|
||||
_state.storeFunctor(fitSnapshot);
|
||||
// add any stat that is a std::vector<double> to it
|
||||
fitSnapshot->add(*fitStat);
|
||||
// and of course add it to the checkpoint
|
||||
checkpoint->add(*fitSnapshot);
|
||||
}
|
||||
|
||||
//////////////////////////////////
|
||||
// State savers
|
||||
//////////////////////////////
|
||||
|
||||
// feed the state to state savers
|
||||
// save state every N generation
|
||||
eoValueParam<unsigned>& saveFrequencyParam = _parser.createParam(unsigned(0), "saveFrequency", "Save every F generation (0 = only final state, absent = never)", '\0', "Persistence" );
|
||||
|
||||
if (_parser.isItThere(saveFrequencyParam))
|
||||
{
|
||||
// first make sure dirName is OK
|
||||
if (! dirOK )
|
||||
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
|
||||
|
||||
unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX );
|
||||
#ifdef _MSVC
|
||||
std::string stmp = dirNameParam.value() + "\generations";
|
||||
#else
|
||||
std::string stmp = dirNameParam.value() + "/generations";
|
||||
#endif
|
||||
eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp);
|
||||
_state.storeFunctor(stateSaver1);
|
||||
checkpoint->add(*stateSaver1);
|
||||
}
|
||||
|
||||
// save state every T seconds
|
||||
eoValueParam<unsigned>& saveTimeIntervalParam = _parser.createParam(unsigned(0), "saveTimeInterval", "Save every T seconds (0 or absent = never)", '\0',"Persistence" );
|
||||
if (_parser.isItThere(saveTimeIntervalParam) && saveTimeIntervalParam.value()>0)
|
||||
{
|
||||
// first make sure dirName is OK
|
||||
if (! dirOK )
|
||||
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
|
||||
|
||||
#ifdef _MSVC
|
||||
std::string stmp = dirNameParam.value() + "\time";
|
||||
#else
|
||||
std::string stmp = dirNameParam.value() + "/time";
|
||||
#endif
|
||||
eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp);
|
||||
_state.storeFunctor(stateSaver2);
|
||||
checkpoint->add(*stateSaver2);
|
||||
}
|
||||
|
||||
// and that's it for the (control and) output
|
||||
return *checkpoint;
|
||||
}
|
||||
|
||||
#endif
|
||||
298
trunk/paradiseo-eo/src/do/make_checkpoint_FDC.h
Normal file
298
trunk/paradiseo-eo/src/do/make_checkpoint_FDC.h
Normal file
|
|
@ -0,0 +1,298 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// make_checkpoint.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _make_checkpoint_h
|
||||
#define _make_checkpoint_h
|
||||
|
||||
#include <eoScalarFitness.h>
|
||||
#include <utils/selectors.h> // for minimizing_fitness()
|
||||
#include <EO.h>
|
||||
#include <eoEvalFuncCounter.h>
|
||||
#include <utils/checkpointing>
|
||||
|
||||
// at the moment, in utils/make_help.cpp
|
||||
// this should become some eoUtils.cpp with corresponding eoUtils.h
|
||||
bool testDirRes(std::string _dirName, bool _erase);
|
||||
/////////////////// The checkpoint and other I/O //////////////
|
||||
|
||||
|
||||
template <class EOT>
|
||||
eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter<EOT>& _eval, eoContinue<EOT>& _continue)
|
||||
{
|
||||
// first, create a checkpoint from the eoContinue
|
||||
eoCheckPoint<EOT> *checkpoint = new eoCheckPoint<EOT>(_continue);
|
||||
_state.storeFunctor(checkpoint);
|
||||
|
||||
///////////////////
|
||||
// Counters
|
||||
//////////////////
|
||||
// is nb Eval to be used as counter?
|
||||
eoValueParam<bool>& useEvalParam = _parser.createParam(true, "useEval", "Use nb of eval. as counter (vs nb of gen.)", '\0', "Output");
|
||||
|
||||
// Create anyway a generation-counter parameter
|
||||
eoValueParam<unsigned> *generationCounter = new eoValueParam<unsigned>(0, "Gen.");
|
||||
// Create an incrementor (sub-class of eoUpdater).
|
||||
eoIncrementor<unsigned>* increment = new eoIncrementor<unsigned>(generationCounter->value());
|
||||
// Add it to the checkpoint,
|
||||
checkpoint->add(*increment);
|
||||
// and store it in the state
|
||||
_state.storeFunctor(increment);
|
||||
|
||||
// dir for DISK output
|
||||
eoValueParam<std::string>& dirNameParam = _parser.createParam(std::string("Res"), "resDir", "Directory to store DISK outputs", '\0', "Output - Disk");
|
||||
// shoudl we empty it if exists
|
||||
eoValueParam<bool>& eraseParam = _parser.createParam(false, "eraseDir", "erase files in dirName if any", '\0', "Output - Disk");
|
||||
bool dirOK = false; // not tested yet
|
||||
|
||||
/////////////////////////////////////////
|
||||
// now some statistics on the population:
|
||||
/////////////////////////////////////////
|
||||
/**
|
||||
* existing stats as of today, April 10. 2001
|
||||
*
|
||||
* eoBestFitnessStat : best value in pop - type EOT::Fitness
|
||||
* eoAverageStat : average value in pop - type EOT::Fitness
|
||||
* eoSecondMomentStat: average + stdev - type std::pair<double, double>
|
||||
* eoSortedPopStat : whole population - type std::string (!!)
|
||||
* eoScalarFitnessStat: the fitnesses - type std::vector<double>
|
||||
* eoDFCSTat : FDC wrt best in pop or absolute best - type double
|
||||
* requires an eoDistance. See eoFDCStat.h
|
||||
* also computes all elements for the FDC scatter plot
|
||||
*/
|
||||
|
||||
// Best fitness in population
|
||||
//---------------------------
|
||||
eoValueParam<bool>& printBestParam = _parser.createParam(true, "printBestStat", "Print Best/avg/stdev every gen.", '\0', "Output");
|
||||
eoValueParam<bool>& plotBestParam = _parser.createParam(false, "plotBestStat", "Plot Best/avg Stat", '\0', "Output - Graphical");
|
||||
eoValueParam<bool>& fileBestParam = _parser.createParam(false, "fileBestStat", "Output bes/avg/std to file", '\0', "Output - Disk");
|
||||
|
||||
eoBestFitnessStat<EOT> *bestStat = NULL;
|
||||
if ( printBestParam.value() || plotBestParam.value() || fileBestParam.value() )
|
||||
// we need the bestStat for at least one of the 3 above
|
||||
{
|
||||
bestStat = new eoBestFitnessStat<EOT>;
|
||||
// store it
|
||||
_state.storeFunctor(bestStat);
|
||||
// add it to the checkpoint
|
||||
checkpoint->add(*bestStat);
|
||||
}
|
||||
|
||||
// Average fitness alone
|
||||
//----------------------
|
||||
eoAverageStat<EOT> *averageStat = NULL; // do we need averageStat?
|
||||
if ( plotBestParam.value() ) // we need it for gnuplot output
|
||||
{
|
||||
averageStat = new eoAverageStat<EOT>;
|
||||
// store it
|
||||
_state.storeFunctor(averageStat);
|
||||
// add it to the checkpoint
|
||||
checkpoint->add(*averageStat);
|
||||
}
|
||||
|
||||
// Second moment stats: average and stdev
|
||||
//---------------------------------------
|
||||
eoSecondMomentStats<EOT> *secondStat = NULL;
|
||||
if ( printBestParam.value() ) // we need it for sreen output
|
||||
{
|
||||
secondStat = new eoSecondMomentStats<EOT>;
|
||||
// store it
|
||||
_state.storeFunctor(secondStat);
|
||||
// add it to the checkpoint
|
||||
checkpoint->add(*secondStat);
|
||||
}
|
||||
|
||||
|
||||
// Dump of the whole population
|
||||
//-----------------------------
|
||||
eoSortedPopStat<EOT> *popStat = NULL;
|
||||
eoValueParam<bool>& printPopParam = _parser.createParam(false, "printPop", "Print sorted pop. every gen.", '\0', "Output");
|
||||
if ( printPopParam.value() ) // we do want pop dump
|
||||
{
|
||||
popStat = new eoSortedPopStat<EOT>("Dump of whole population");
|
||||
// store it
|
||||
_state.storeFunctor(popStat);
|
||||
// add it to the checkpoint
|
||||
checkpoint->add(*popStat);
|
||||
}
|
||||
|
||||
|
||||
// the Fitness Distance Correlation
|
||||
//---------------------------------
|
||||
eoValueParam<bool>& printFDCParam = _parser.createParam(true, "printFDC", "Print FDC coeff. every gen.", '\0', "Output");
|
||||
eoValueParam<bool>& plotFDCParam = _parser.createParam(false, "plotFDCStat", "Plot FDC scatter plot", '\0', "Output - Graphical");
|
||||
|
||||
eoFDCStat<EOT> *fdcStat = NULL;
|
||||
if ( printFDCParam.value() || plotFDCParam.value() ) // we need FDCStat
|
||||
{
|
||||
// need first an object to compute the distances - here Hamming dist.
|
||||
eoQuadDistance<EOT> *dist = new eoQuadDistance<EOT>;
|
||||
_state.storeFunctor(dist);
|
||||
fdcStat = new eoFDCStat<EOT>(*dist);
|
||||
// storeFunctor it
|
||||
_state.storeFunctor(fdcStat);
|
||||
// add it to the checkpoint
|
||||
checkpoint->add(*fdcStat);
|
||||
}
|
||||
|
||||
// do we wnat some histogram of fitnesses snpashots?
|
||||
eoValueParam<bool> plotHistogramParam = _parser.createParam(false, "plotHisto", "Plot histogram of fitnesses", '\0', "Output - Graphical");
|
||||
|
||||
///////////////
|
||||
// The monitors
|
||||
///////////////
|
||||
// do we want an eoStdoutMonitor?
|
||||
bool needStdoutMonitor = printBestParam.value() || printFDCParam.value()
|
||||
|| printPopParam.value() ;
|
||||
|
||||
// The Stdout monitor will print parameters to the screen ...
|
||||
if ( needStdoutMonitor )
|
||||
{
|
||||
eoStdoutMonitor *monitor = new eoStdoutMonitor(false);
|
||||
_state.storeFunctor(monitor);
|
||||
|
||||
// when called by the checkpoint (i.e. at every generation)
|
||||
checkpoint->add(*monitor);
|
||||
|
||||
// the monitor will output a series of parameters: add them
|
||||
monitor->add(*generationCounter);
|
||||
if (useEvalParam.value()) // we want nb of evaluations
|
||||
monitor->add(_eval);
|
||||
if (printBestParam.value())
|
||||
{
|
||||
monitor->add(*bestStat);
|
||||
monitor->add(*secondStat);
|
||||
}
|
||||
if (printFDCParam.value())
|
||||
monitor->add(*fdcStat);
|
||||
if ( printPopParam.value())
|
||||
monitor->add(*popStat);
|
||||
}
|
||||
|
||||
// first handle the dir test - if we need at least one file
|
||||
if ( ( fileBestParam.value() || plotBestParam.value() ||
|
||||
plotFDCParam.value() || plotHistogramParam.value() )
|
||||
&& !dirOK ) // just in case we add something before
|
||||
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
|
||||
|
||||
if (fileBestParam.value()) // A file monitor for best & secondMoment
|
||||
{
|
||||
std::string stmp = dirNameParam.value() + "/best.xg";
|
||||
eoFileMonitor *fileMonitor = new eoFileMonitor(stmp);
|
||||
// save and give to checkpoint
|
||||
_state.storeFunctor(fileMonitor);
|
||||
checkpoint->add(*fileMonitor);
|
||||
// and feed with some statistics
|
||||
fileMonitor->add(*generationCounter);
|
||||
fileMonitor->add(_eval);
|
||||
fileMonitor->add(*bestStat);
|
||||
fileMonitor->add(*secondStat);
|
||||
}
|
||||
|
||||
if (plotBestParam.value()) // an eoGnuplot1DMonitor for best & average
|
||||
{
|
||||
std::string stmp = dirNameParam.value() + "_gnu_best.xg";
|
||||
eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness<EOT>());
|
||||
// save and give to checkpoint
|
||||
_state.storeFunctor(gnuMonitor);
|
||||
checkpoint->add(*gnuMonitor);
|
||||
// and feed with some statistics
|
||||
if (useEvalParam.value())
|
||||
gnuMonitor->add(_eval);
|
||||
else
|
||||
gnuMonitor->add(*generationCounter);
|
||||
gnuMonitor->add(*bestStat);
|
||||
gnuMonitor->add(*averageStat);
|
||||
}
|
||||
|
||||
if (plotFDCParam.value()) // a specific plot monitor for FDC
|
||||
{
|
||||
// first into a file (it adds everything ti itself
|
||||
eoFDCFileSnapshot<EOT> *fdcFileSnapshot = new eoFDCFileSnapshot<EOT>(*fdcStat, dirNameParam.value());
|
||||
_state.storeFunctor(fdcFileSnapshot);
|
||||
// then to a Gnuplot monitor
|
||||
eoGnuplot1DSnapshot *fdcGnuplot = new eoGnuplot1DSnapshot(*fdcFileSnapshot);
|
||||
_state.storeFunctor(fdcGnuplot);
|
||||
|
||||
// and of course add them to the checkPoint
|
||||
checkpoint->add(*fdcFileSnapshot);
|
||||
checkpoint->add(*fdcGnuplot);
|
||||
}
|
||||
|
||||
// historgram?
|
||||
if (plotHistogramParam.value()) // want to see how the fitness is spread?
|
||||
{
|
||||
eoScalarFitnessStat<EOT> *fitStat = new eoScalarFitnessStat<EOT>;
|
||||
_state.storeFunctor(fitStat);
|
||||
checkpoint->add(*fitStat);
|
||||
// a gnuplot-based monitor for snapshots: needs a dir name
|
||||
eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value());
|
||||
_state.storeFunctor(fitSnapshot);
|
||||
// add any stat that is a std::vector<double> to it
|
||||
fitSnapshot->add(*fitStat);
|
||||
// and of course add it to the checkpoint
|
||||
checkpoint->add(*fitSnapshot);
|
||||
}
|
||||
|
||||
//////////////////////////////////
|
||||
// State savers
|
||||
//////////////////////////////
|
||||
|
||||
// feed the state to state savers
|
||||
// save state every N generation
|
||||
eoValueParam<unsigned>& saveFrequencyParam = _parser.createParam(unsigned(0), "saveFrequency", "Save every F generation (0 = only final state, absent = never)", '\0', "Persistence" );
|
||||
|
||||
if (_parser.isItThere(saveFrequencyParam))
|
||||
{
|
||||
// first make sure dirName is OK
|
||||
if (! dirOK )
|
||||
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
|
||||
|
||||
unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX );
|
||||
std::string stmp = dirNameParam.value() + "/generations";
|
||||
eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp);
|
||||
_state.storeFunctor(stateSaver1);
|
||||
checkpoint->add(*stateSaver1);
|
||||
}
|
||||
|
||||
// save state every T seconds
|
||||
eoValueParam<unsigned>& saveTimeIntervalParam = _parser.createParam(unsigned(0), "saveTimeInterval", "Save every T seconds (0 or absent = never)", '\0',"Persistence" );
|
||||
if (_parser.isItThere(saveTimeIntervalParam) && saveTimeIntervalParam.value()>0)
|
||||
{
|
||||
// first make sure dirName is OK
|
||||
if (! dirOK )
|
||||
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
|
||||
|
||||
std::string stmp = dirNameParam.value() + "/time";
|
||||
eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp);
|
||||
_state.storeFunctor(stateSaver2);
|
||||
checkpoint->add(*stateSaver2);
|
||||
}
|
||||
|
||||
// and that's it for the (control and) output
|
||||
return *checkpoint;
|
||||
}
|
||||
|
||||
#endif
|
||||
202
trunk/paradiseo-eo/src/do/make_checkpoint_assembled.h
Normal file
202
trunk/paradiseo-eo/src/do/make_checkpoint_assembled.h
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
/* -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- */
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// make_checkpoint_assembled.h
|
||||
// Marc Wintermantel & Oliver Koenig
|
||||
// IMES-ST@ETHZ.CH
|
||||
// March 2003
|
||||
|
||||
/*
|
||||
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@inria.fr
|
||||
mak@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _make_checkpoint_assembled_h
|
||||
#define _make_checkpoint_assembled_h
|
||||
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
#include <eoScalarFitnessAssembled.h>
|
||||
#include <utils/selectors.h>
|
||||
#include <EO.h>
|
||||
#include <eoEvalFuncCounter.h>
|
||||
#include <utils/checkpointing>
|
||||
|
||||
// at the moment, in utils/make_help.cpp
|
||||
// this should become some eoUtils.cpp with corresponding eoUtils.h
|
||||
bool testDirRes(std::string _dirName, bool _erase);
|
||||
/////////////////// The checkpoint and other I/O //////////////
|
||||
|
||||
/** Of course, Fitness needs to be an eoScalarFitnessAssembled!!! */
|
||||
template <class EOT>
|
||||
eoCheckPoint<EOT>& do_make_checkpoint_assembled(eoParser& _parser, eoState& _state, eoEvalFuncCounter<EOT>& _eval, eoContinue<EOT>& _continue)
|
||||
{
|
||||
|
||||
// SOME PARSER PARAMETERS
|
||||
// ----------------------
|
||||
std::string dirName = _parser.getORcreateParam(std::string("Res"), "resDir",
|
||||
"Directory to store DISK outputs",
|
||||
'\0', "Output").value();
|
||||
bool erase = _parser.getORcreateParam(true, "eraseDir",
|
||||
"Erase files in dirName if any",
|
||||
'\0', "Output").value();
|
||||
bool gnuplots = _parser.getORcreateParam(true, "plots",
|
||||
"Plot stuff using GnuPlot",
|
||||
'\0', "Output").value();
|
||||
bool printFile = _parser.getORcreateParam(true, "printFile",
|
||||
"Print statistics file",
|
||||
'\0', "Output").value();
|
||||
|
||||
eoValueParam<unsigned>& saveFrequencyParam
|
||||
= _parser.getORcreateParam(unsigned(0), "saveFrequency",
|
||||
"Save every F generation (0 = only final state, absent = never)",
|
||||
'\0', "Persistence" );
|
||||
|
||||
testDirRes(dirName, erase); // TRUE
|
||||
|
||||
// CREATE CHECKPOINT FROM eoContinue
|
||||
// ---------------------------------
|
||||
eoCheckPoint<EOT> *checkpoint = new eoCheckPoint<EOT>(_continue);
|
||||
_state.storeFunctor(checkpoint);
|
||||
|
||||
// GENERATIONS
|
||||
// -----------
|
||||
eoIncrementorParam<unsigned> *generationCounter = new eoIncrementorParam<unsigned>("Gen.");
|
||||
_state.storeFunctor(generationCounter);
|
||||
checkpoint->add(*generationCounter);
|
||||
|
||||
// TIME
|
||||
// ----
|
||||
eoTimeCounter * tCounter = NULL;
|
||||
tCounter = new eoTimeCounter;
|
||||
_state.storeFunctor(tCounter);
|
||||
checkpoint->add(*tCounter);
|
||||
|
||||
// ACCESS DESCRIPTIONS OF TERMS OF FITNESS CLASS
|
||||
// ---------------------------------------------
|
||||
// define a temporary fitness instance
|
||||
typedef typename EOT::Fitness Fit;
|
||||
Fit fit;
|
||||
std::vector<std::string> fitness_descriptions = fit.getDescriptionVector();
|
||||
unsigned nTerms = fitness_descriptions.size();
|
||||
|
||||
// STAT VALUES OF A POPULATION
|
||||
// ---------------------------
|
||||
|
||||
// average vals
|
||||
std::vector<eoAssembledFitnessAverageStat<EOT>* > avgvals( nTerms );
|
||||
for (unsigned i=0; i < nTerms; ++i){
|
||||
std::string descr = "Avg. of " + fitness_descriptions[i];
|
||||
avgvals[i] = new eoAssembledFitnessAverageStat<EOT>(i, descr);
|
||||
_state.storeFunctor( avgvals[i] );
|
||||
checkpoint->add( *avgvals[i] );
|
||||
}
|
||||
|
||||
// best vals
|
||||
std::vector<eoAssembledFitnessBestStat<EOT>* > bestvals( nTerms );
|
||||
for (unsigned j=0; j < nTerms; ++j){
|
||||
std::string descr = fitness_descriptions[j] + " of best ind.";
|
||||
bestvals[j] = new eoAssembledFitnessBestStat<EOT>(j, descr);
|
||||
_state.storeFunctor( bestvals[j] );
|
||||
checkpoint->add( *bestvals[j] );
|
||||
}
|
||||
|
||||
// STDOUT
|
||||
// ------
|
||||
eoStdoutMonitor *monitor = new eoStdoutMonitor(false);
|
||||
_state.storeFunctor(monitor);
|
||||
checkpoint->add(*monitor);
|
||||
monitor->add(*generationCounter);
|
||||
monitor->add(_eval);
|
||||
monitor->add(*tCounter);
|
||||
|
||||
// Add best fitness
|
||||
monitor->add( *bestvals[0] );
|
||||
|
||||
// Add all average vals
|
||||
for (unsigned l=0; l < nTerms; ++l)
|
||||
monitor->add( *avgvals[l] );
|
||||
|
||||
// GNUPLOT
|
||||
// -------
|
||||
if (gnuplots ){
|
||||
std::string stmp;
|
||||
|
||||
// Histogramm of the different fitness vals
|
||||
eoScalarFitnessStat<EOT> *fitStat = new eoScalarFitnessStat<EOT>;
|
||||
_state.storeFunctor(fitStat);
|
||||
checkpoint->add(*fitStat);
|
||||
// a gnuplot-based monitor for snapshots: needs a dir name
|
||||
eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirName);
|
||||
_state.storeFunctor(fitSnapshot);
|
||||
// add any stat that is a vector<double> to it
|
||||
fitSnapshot->add(*fitStat);
|
||||
// and of course add it to the checkpoint
|
||||
checkpoint->add(*fitSnapshot);
|
||||
|
||||
std::vector<eoGnuplot1DMonitor*> gnumonitors(nTerms, NULL );
|
||||
for (unsigned k=0; k < nTerms; ++k){
|
||||
stmp = dirName + "/gnuplot_" + fitness_descriptions[k] + ".xg";
|
||||
gnumonitors[k] = new eoGnuplot1DMonitor(stmp,true);
|
||||
_state.storeFunctor(gnumonitors[k]);
|
||||
checkpoint->add(*gnumonitors[k]);
|
||||
gnumonitors[k]->add(*generationCounter);
|
||||
gnumonitors[k]->add(*bestvals[k]);
|
||||
gnumonitors[k]->add(*avgvals[k]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// WRITE STUFF TO FILE
|
||||
// -------------------
|
||||
if( printFile ){
|
||||
std::string stmp2 = dirName + "/eoStatistics.sav";
|
||||
eoFileMonitor *fileMonitor = new eoFileMonitor(stmp2);
|
||||
_state.storeFunctor(fileMonitor);
|
||||
checkpoint->add(*fileMonitor);
|
||||
fileMonitor->add(*generationCounter);
|
||||
fileMonitor->add(_eval);
|
||||
fileMonitor->add(*tCounter);
|
||||
|
||||
for (unsigned i=0; i < nTerms; ++i){
|
||||
fileMonitor->add(*bestvals[i]);
|
||||
fileMonitor->add(*avgvals[i]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// STATE SAVER
|
||||
// -----------
|
||||
// feed the state to state savers
|
||||
|
||||
if (_parser.isItThere(saveFrequencyParam)) {
|
||||
|
||||
unsigned freq = (saveFrequencyParam.value() > 0 ? saveFrequencyParam.value() : UINT_MAX );
|
||||
std::string stmp = dirName + "/generations";
|
||||
eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp);
|
||||
_state.storeFunctor(stateSaver1);
|
||||
checkpoint->add(*stateSaver1);
|
||||
}
|
||||
|
||||
// and that's it for the (control and) output
|
||||
return *checkpoint;
|
||||
}
|
||||
|
||||
#endif
|
||||
247
trunk/paradiseo-eo/src/do/make_checkpoint_pareto.h
Normal file
247
trunk/paradiseo-eo/src/do/make_checkpoint_pareto.h
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// make_checkpoint_pareto.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@inria.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _make_checkpoint_pareto_h
|
||||
#define _make_checkpoint_pareto_h
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <sstream>
|
||||
|
||||
#include "EO.h"
|
||||
#include "eoParetoFitness.h"
|
||||
#include "eoEvalFuncCounter.h"
|
||||
#include "utils/checkpointing"
|
||||
#include "utils/selectors.h"
|
||||
|
||||
// at the moment, in utils/make_help.cpp
|
||||
// this should become some eoUtils.cpp with corresponding eoUtils.h
|
||||
bool testDirRes(std::string _dirName, bool _erase);
|
||||
/////////////////// The checkpoint and other I/O //////////////
|
||||
|
||||
/** Of course, Fitness needs to be an eoParetoFitness!!!
|
||||
*/
|
||||
template <class EOT>
|
||||
eoCheckPoint<EOT>& do_make_checkpoint_pareto(eoParser& _parser, eoState& _state,
|
||||
eoEvalFuncCounter<EOT>& _eval, eoContinue<EOT>& _continue)
|
||||
{
|
||||
// first, create a checkpoint from the eoContinue - and store in _state
|
||||
eoCheckPoint<EOT> & checkpoint = _state.storeFunctor(new eoCheckPoint<EOT>(_continue));
|
||||
|
||||
/////// get number of obectives from Fitness - not very elegant
|
||||
typedef typename EOT::Fitness Fit;
|
||||
Fit fit;
|
||||
unsigned nObj = fit.size();
|
||||
|
||||
///////////////////
|
||||
// Counters
|
||||
//////////////////
|
||||
// is nb Eval to be used as counter?
|
||||
bool useEval = _parser.getORcreateParam(true, "useEval",
|
||||
"Use nb of eval. as counter (vs nb of gen.)",
|
||||
'\0', "Output").value();
|
||||
|
||||
// Create anyway a generation-counter parameter WARNING: not stored anywhere!!!
|
||||
eoValueParam<unsigned> *generationCounter = new eoValueParam<unsigned>(0, "Gen.");
|
||||
// Create an incrementor (sub-class of eoUpdater).
|
||||
eoIncrementor<unsigned> & increment =
|
||||
_state.storeFunctor(new eoIncrementor<unsigned>(generationCounter->value()) );
|
||||
// Add it to the checkpoint,
|
||||
checkpoint.add(increment);
|
||||
|
||||
// dir for DISK output
|
||||
std::string & dirName = _parser.getORcreateParam(std::string("Res"), "resDir",
|
||||
"Directory to store DISK outputs",
|
||||
'\0', "Output - Disk").value();
|
||||
// shoudl we empty it if exists
|
||||
eoValueParam<bool>& eraseParam = _parser.getORcreateParam(true, "eraseDir",
|
||||
"erase files in dirName if any",
|
||||
'\0', "Output - Disk");
|
||||
bool dirOK = false; // not tested yet
|
||||
|
||||
/////////////////////////////////////////
|
||||
// now some statistics on the population:
|
||||
/////////////////////////////////////////
|
||||
/**
|
||||
* existing stats for Pareto as of today, Jan. 31. 2002
|
||||
*
|
||||
* eoSortedPopStat : whole population - type std::string (!!)
|
||||
*/
|
||||
|
||||
eoValueParam<eoParamParamType>& fPlotParam
|
||||
= _parser.getORcreateParam(eoParamParamType("1(0,1)"), "frontFileFrequency",
|
||||
"File save frequency in objective spaces (std::pairs of comma-separated objectives " \
|
||||
"in 1 single parentheses std::pair)",
|
||||
'\0', "Output - Disk");
|
||||
|
||||
bool boolGnuplot = _parser.getORcreateParam(false, "plotFront",
|
||||
"Objective plots (requires corresponding files " \
|
||||
"- see frontFileFrequency",
|
||||
'\0', "Output - Graphical").value();
|
||||
|
||||
eoParamParamType & fPlot = fPlotParam.value(); // std::pair<std::string,std::vector<std::string> >
|
||||
unsigned frequency = atoi(fPlot.first.c_str());
|
||||
if (frequency) // something to plot
|
||||
{
|
||||
unsigned nbPlot = fPlot.second.size();
|
||||
if ( nbPlot % 2 ) // odd!
|
||||
throw std::runtime_error("Odd number of front description in make_checkpoint_pareto");
|
||||
|
||||
// only create the necessary stats
|
||||
std::vector<bool> bStat(nObj, false); // track of who's already there
|
||||
std::vector<eoMOFitnessStat<EOT>* > theStats(nObj);
|
||||
|
||||
// first create the stats
|
||||
for (unsigned i=0; i<nbPlot; i+=2)
|
||||
{
|
||||
unsigned obj1 = atoi(fPlot.second[i].c_str());
|
||||
unsigned obj2 = atoi(fPlot.second[i+1].c_str());
|
||||
eoMOFitnessStat<EOT>* fStat;
|
||||
if (!bStat[obj1]) { // not already there: create it
|
||||
std::ostringstream os;
|
||||
os << "Obj. " << obj1 << std::ends;
|
||||
fStat = new eoMOFitnessStat<EOT>(obj1, os.str().c_str());
|
||||
_state.storeFunctor(fStat);
|
||||
bStat[obj1]=true;
|
||||
theStats[obj1]=fStat;
|
||||
checkpoint.add(*fStat);
|
||||
}
|
||||
if (!bStat[obj2]) { // not already there: create it
|
||||
std::ostringstream os;
|
||||
os << "Obj. " << obj2 << std::ends;
|
||||
fStat = new eoMOFitnessStat<EOT>(obj2, os.str().c_str());
|
||||
_state.storeFunctor(fStat);
|
||||
bStat[obj2]=true;
|
||||
theStats[obj2]=fStat;
|
||||
checkpoint.add(*fStat);
|
||||
}
|
||||
|
||||
// then the fileSnapshots
|
||||
std::ostringstream os;
|
||||
os << "Front." << obj1 << "." << obj2 << "." << std::ends;
|
||||
eoFileSnapshot& snapshot = _state.storeFunctor(
|
||||
new eoFileSnapshot(dirName, frequency, os.str().c_str()));
|
||||
checkpoint.add(snapshot);
|
||||
|
||||
snapshot.add(*theStats[obj1]);
|
||||
snapshot.add(*theStats[obj2]);
|
||||
|
||||
// and create the gnuplotter from the fileSnapshot
|
||||
if(boolGnuplot)
|
||||
{
|
||||
eoGnuplot1DSnapshot & plotSnapshot = _state.storeFunctor(new
|
||||
eoGnuplot1DSnapshot(snapshot));
|
||||
plotSnapshot.setPointSize(3);
|
||||
checkpoint.add(plotSnapshot);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Dump of the whole population
|
||||
//-----------------------------
|
||||
bool printPop = _parser.getORcreateParam(false, "printPop",
|
||||
"Print sorted pop. every gen.",
|
||||
'\0', "Output").value();
|
||||
eoSortedPopStat<EOT> * popStat;
|
||||
if ( printPop ) // we do want pop dump
|
||||
{
|
||||
std::cout << "On cree printpop\n";
|
||||
popStat = & _state.storeFunctor(new eoSortedPopStat<EOT>);
|
||||
// add it to the checkpoint
|
||||
checkpoint.add(*popStat);
|
||||
}
|
||||
|
||||
///////////////
|
||||
// The monitors
|
||||
///////////////
|
||||
// do we want an eoStdoutMonitor?
|
||||
bool needStdoutMonitor = printPop ; // only this one at the moment
|
||||
|
||||
// The Stdout monitor will print parameters to the screen ...
|
||||
if ( needStdoutMonitor )
|
||||
{
|
||||
eoStdoutMonitor & monitor = _state.storeFunctor(new eoStdoutMonitor(false));
|
||||
|
||||
// when called by the checkpoint (i.e. at every generation)
|
||||
checkpoint.add(monitor);
|
||||
|
||||
// the monitor will output a series of parameters: add them
|
||||
monitor.add(*generationCounter);
|
||||
if (useEval) // we want nb of evaluations
|
||||
monitor.add(_eval);
|
||||
if ( printPop)
|
||||
monitor.add(*popStat);
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////
|
||||
// State savers
|
||||
//////////////////////////////
|
||||
|
||||
// feed the state to state savers
|
||||
// save state every N generation
|
||||
eoValueParam<unsigned>& saveFrequencyParam = _parser.createParam(unsigned(0), "saveFrequency", "Save every F generation (0 = only final state, absent = never)", '\0', "Persistence" );
|
||||
|
||||
if (_parser.isItThere(saveFrequencyParam))
|
||||
{
|
||||
// first make sure dirName is OK
|
||||
if (! dirOK )
|
||||
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
|
||||
|
||||
unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX );
|
||||
#ifdef _MSVC
|
||||
std::string stmp = dirName + "\generations";
|
||||
#else
|
||||
std::string stmp = dirName + "/generations";
|
||||
#endif
|
||||
eoCountedStateSaver *stateSaver1 = new eoCountedStateSaver(freq, _state, stmp);
|
||||
_state.storeFunctor(stateSaver1);
|
||||
checkpoint.add(*stateSaver1);
|
||||
}
|
||||
|
||||
// save state every T seconds
|
||||
eoValueParam<unsigned>& saveTimeIntervalParam
|
||||
= _parser.getORcreateParam(unsigned(0), "saveTimeInterval",
|
||||
"Save every T seconds (0 or absent = never)", '\0',"Persistence" );
|
||||
if (_parser.isItThere(saveTimeIntervalParam) && saveTimeIntervalParam.value()>0)
|
||||
{
|
||||
// first make sure dirName is OK
|
||||
if (! dirOK )
|
||||
dirOK = testDirRes(dirName, eraseParam.value()); // TRUE
|
||||
|
||||
#ifdef _MSVC
|
||||
std::string stmp = dirName + "\time";
|
||||
#else
|
||||
std::string stmp = dirName + "/time";
|
||||
#endif
|
||||
eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp);
|
||||
_state.storeFunctor(stateSaver2);
|
||||
checkpoint.add(*stateSaver2);
|
||||
}
|
||||
|
||||
// and that's it for the (control and) output
|
||||
return checkpoint;
|
||||
}
|
||||
|
||||
#endif
|
||||
160
trunk/paradiseo-eo/src/do/make_continue.h
Normal file
160
trunk/paradiseo-eo/src/do/make_continue.h
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// make_continue.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _make_continue_h
|
||||
#define _make_continue_h
|
||||
|
||||
/*
|
||||
Contains the templatized version of parser-based choice of stopping criterion
|
||||
It can then be instantiated, and compiled on its own for a given EOType
|
||||
(see e.g. in dir ga, ga.cpp)
|
||||
*/
|
||||
|
||||
// Continuators - all include eoContinue.h
|
||||
#include <eoCombinedContinue.h>
|
||||
#include <eoGenContinue.h>
|
||||
#include <eoSteadyFitContinue.h>
|
||||
#include <eoEvalContinue.h>
|
||||
#include <eoFitContinue.h>
|
||||
#ifndef _MSC_VER
|
||||
#include <eoCtrlCContinue.h> // CtrlC handling (using 2 global variables!)
|
||||
#endif
|
||||
|
||||
// also need the parser and param includes
|
||||
#include <utils/eoParser.h>
|
||||
#include <utils/eoState.h>
|
||||
|
||||
|
||||
/////////////////// the stopping criterion ////////////////
|
||||
template <class Indi>
|
||||
eoCombinedContinue<Indi> * make_combinedContinue(eoCombinedContinue<Indi> *_combined, eoContinue<Indi> *_cont)
|
||||
{
|
||||
if (_combined) // already exists
|
||||
_combined->add(*_cont);
|
||||
else
|
||||
_combined = new eoCombinedContinue<Indi>(*_cont);
|
||||
return _combined;
|
||||
}
|
||||
|
||||
template <class Indi>
|
||||
eoContinue<Indi> & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFuncCounter<Indi> & _eval)
|
||||
{
|
||||
//////////// Stopping criterion ///////////////////
|
||||
// the combined continue - to be filled
|
||||
eoCombinedContinue<Indi> *continuator = NULL;
|
||||
|
||||
// for each possible criterion, check if wanted, otherwise do nothing
|
||||
|
||||
// First the eoGenContinue - need a default value so you can run blind
|
||||
// but we also need to be able to avoid it <--> 0
|
||||
eoValueParam<unsigned>& maxGenParam = _parser.getORcreateParam(unsigned(100), "maxGen", "Maximum number of generations () = none)",'G',"Stopping criterion");
|
||||
|
||||
if (maxGenParam.value()) // positive: -> define and store
|
||||
{
|
||||
eoGenContinue<Indi> *genCont = new eoGenContinue<Indi>(maxGenParam.value());
|
||||
_state.storeFunctor(genCont);
|
||||
// and "add" to combined
|
||||
continuator = make_combinedContinue<Indi>(continuator, genCont);
|
||||
}
|
||||
|
||||
// the steadyGen continue - only if user imput
|
||||
eoValueParam<unsigned>& steadyGenParam = _parser.createParam(unsigned(100), "steadyGen", "Number of generations with no improvement",'s', "Stopping criterion");
|
||||
eoValueParam<unsigned>& minGenParam = _parser.createParam(unsigned(0), "minGen", "Minimum number of generations",'g', "Stopping criterion");
|
||||
if (_parser.isItThere(steadyGenParam))
|
||||
{
|
||||
eoSteadyFitContinue<Indi> *steadyCont = new eoSteadyFitContinue<Indi>
|
||||
(minGenParam.value(), steadyGenParam.value());
|
||||
// store
|
||||
_state.storeFunctor(steadyCont);
|
||||
// add to combinedContinue
|
||||
continuator = make_combinedContinue<Indi>(continuator, steadyCont);
|
||||
}
|
||||
|
||||
// Same thing with Eval - but here default value is 0
|
||||
eoValueParam<unsigned long>& maxEvalParam
|
||||
= _parser.getORcreateParam((unsigned long)0, "maxEval",
|
||||
"Maximum number of evaluations (0 = none)",
|
||||
'E', "Stopping criterion");
|
||||
|
||||
if (maxEvalParam.value()) // positive: -> define and store
|
||||
{
|
||||
eoEvalContinue<Indi> *evalCont = new eoEvalContinue<Indi>(_eval, maxEvalParam.value());
|
||||
_state.storeFunctor(evalCont);
|
||||
// and "add" to combined
|
||||
continuator = make_combinedContinue<Indi>(continuator, evalCont);
|
||||
}
|
||||
/*
|
||||
// the steadyEval continue - only if user imput
|
||||
eoValueParam<unsigned>& steadyGenParam = _parser.createParam(unsigned(100), "steadyGen", "Number of generations with no improvement",'s', "Stopping criterion");
|
||||
eoValueParam<unsigned>& minGenParam = _parser.createParam(unsigned(0), "minGen", "Minimum number of generations",'g', "Stopping criterion");
|
||||
if (_parser.isItThere(steadyGenParam))
|
||||
{
|
||||
eoSteadyGenContinue<Indi> *steadyCont = new eoSteadyFitContinue<Indi>
|
||||
(minGenParam.value(), steadyGenParam.value());
|
||||
// store
|
||||
_state.storeFunctor(steadyCont);
|
||||
// add to combinedContinue
|
||||
continuator = make_combinedContinue<Indi>(continuator, steadyCont);
|
||||
}
|
||||
*/
|
||||
// the target fitness
|
||||
eoFitContinue<Indi> *fitCont;
|
||||
eoValueParam<double>& targetFitnessParam = _parser.createParam(double(0.0), "targetFitness", "Stop when fitness reaches",'T', "Stopping criterion");
|
||||
if (_parser.isItThere(targetFitnessParam))
|
||||
{
|
||||
fitCont = new eoFitContinue<Indi>
|
||||
(targetFitnessParam.value());
|
||||
// store
|
||||
_state.storeFunctor(fitCont);
|
||||
// add to combinedContinue
|
||||
continuator = make_combinedContinue<Indi>(continuator, fitCont);
|
||||
}
|
||||
|
||||
#ifndef _MSC_VER
|
||||
// the CtrlC interception (Linux only I'm afraid)
|
||||
eoCtrlCContinue<Indi> *ctrlCCont;
|
||||
eoValueParam<bool>& ctrlCParam = _parser.createParam(false, "CtrlC", "Terminate current generation upon Ctrl C",'C', "Stopping criterion");
|
||||
if (ctrlCParam.value())
|
||||
{
|
||||
ctrlCCont = new eoCtrlCContinue<Indi>;
|
||||
// store
|
||||
_state.storeFunctor(ctrlCCont);
|
||||
// add to combinedContinue
|
||||
continuator = make_combinedContinue<Indi>(continuator, ctrlCCont);
|
||||
}
|
||||
#endif
|
||||
|
||||
// now check that there is at least one!
|
||||
if (!continuator)
|
||||
throw std::runtime_error("You MUST provide a stopping criterion");
|
||||
// OK, it's there: store in the eoState
|
||||
_state.storeFunctor(continuator);
|
||||
|
||||
// and return
|
||||
return *continuator;
|
||||
}
|
||||
|
||||
#endif
|
||||
108
trunk/paradiseo-eo/src/do/make_continue_pareto.h
Normal file
108
trunk/paradiseo-eo/src/do/make_continue_pareto.h
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// make_continue_pareto.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@inria.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _make_continue_pareto_h
|
||||
#define _make_continue_pareto_h
|
||||
|
||||
/*
|
||||
Contains the templatized version of parser-based choice of stopping criterion
|
||||
for Pareto optimization (e.g. no "... without improvement" criterion
|
||||
It can then be instantiated, and compiled on its own for a given EOType
|
||||
(see e.g. in dir ga, ga.cpp)
|
||||
*/
|
||||
|
||||
// Continuators - all include eoContinue.h
|
||||
#include <eoCombinedContinue.h>
|
||||
#include <eoGenContinue.h>
|
||||
#include <eoEvalContinue.h>
|
||||
#include <eoFitContinue.h>
|
||||
#ifndef _MSC_VER
|
||||
#include <eoCtrlCContinue.h> // CtrlC handling (using 2 global variables!)
|
||||
#endif
|
||||
|
||||
// also need the parser and param includes
|
||||
#include <utils/eoParser.h>
|
||||
#include <utils/eoState.h>
|
||||
|
||||
|
||||
/////////////////// helper function ////////////////
|
||||
template <class Indi>
|
||||
eoCombinedContinue<Indi> * make_combinedContinue(eoCombinedContinue<Indi> *_combined, eoContinue<Indi> *_cont)
|
||||
{
|
||||
if (_combined) // already exists
|
||||
_combined->add(*_cont);
|
||||
else
|
||||
_combined = new eoCombinedContinue<Indi>(*_cont);
|
||||
return _combined;
|
||||
}
|
||||
|
||||
///////////// The make_continue function
|
||||
template <class Indi>
|
||||
eoContinue<Indi> & do_make_continue_pareto(eoParser& _parser, eoState& _state, eoEvalFuncCounter<Indi> & _eval)
|
||||
{
|
||||
//////////// Stopping criterion ///////////////////
|
||||
// the combined continue - to be filled
|
||||
eoCombinedContinue<Indi> *continuator = NULL;
|
||||
|
||||
// for each possible criterion, check if wanted, otherwise do nothing
|
||||
|
||||
// First the eoGenContinue - need a default value so you can run blind
|
||||
// but we also need to be able to avoid it <--> 0
|
||||
eoValueParam<unsigned>& maxGenParam = _parser.createParam(unsigned(100), "maxGen", "Maximum number of generations () = none)",'G',"Stopping criterion");
|
||||
|
||||
if (maxGenParam.value()) // positive: -> define and store
|
||||
{
|
||||
eoGenContinue<Indi> *genCont = new eoGenContinue<Indi>(maxGenParam.value());
|
||||
_state.storeFunctor(genCont);
|
||||
// and "add" to combined
|
||||
continuator = make_combinedContinue<Indi>(continuator, genCont);
|
||||
}
|
||||
|
||||
#ifndef _MSC_VER
|
||||
// the CtrlC interception (Linux only I'm afraid)
|
||||
eoCtrlCContinue<Indi> *ctrlCCont;
|
||||
eoValueParam<bool>& ctrlCParam = _parser.createParam(true, "CtrlC", "Terminate current generation upon Ctrl C",'C', "Stopping criterion");
|
||||
if (_parser.isItThere(ctrlCParam))
|
||||
{
|
||||
ctrlCCont = new eoCtrlCContinue<Indi>;
|
||||
// store
|
||||
_state.storeFunctor(ctrlCCont);
|
||||
// add to combinedContinue
|
||||
continuator = make_combinedContinue<Indi>(continuator, ctrlCCont);
|
||||
}
|
||||
#endif
|
||||
|
||||
// now check that there is at least one!
|
||||
if (!continuator)
|
||||
throw std::runtime_error("You MUST provide a stopping criterion");
|
||||
// OK, it's there: store in the eoState
|
||||
_state.storeFunctor(continuator);
|
||||
|
||||
// and return
|
||||
return *continuator;
|
||||
}
|
||||
|
||||
#endif
|
||||
181
trunk/paradiseo-eo/src/do/make_general_replacement.h
Normal file
181
trunk/paradiseo-eo/src/do/make_general_replacement.h
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// make_general_replacement.h
|
||||
// (c) Marc Schoenauer and Pierre Collet, 2002
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _make_general_replacement_h
|
||||
#define _make_general_replacement_h
|
||||
|
||||
#include <utils/eoData.h> // for eo_is_a_rate
|
||||
|
||||
// Replacement
|
||||
#include <eoReduceMergeReduce.h>
|
||||
|
||||
// also need the parser and param includes
|
||||
#include <utils/eoParser.h>
|
||||
#include <utils/eoState.h>
|
||||
|
||||
|
||||
/** a helper function that decodes a parameter read by the parser into an
|
||||
* eoReduce<EOT> & (allocates the pointer and stores it into an eoState)
|
||||
*/
|
||||
template <class EOT>
|
||||
eoReduce<EOT> & decode_reduce(eoParamParamType & _ppReduce, eoState & _state)
|
||||
{
|
||||
unsigned int detSize;
|
||||
eoReduce<EOT> * ptReduce;
|
||||
|
||||
// ---------- Deterministic
|
||||
if ( (_ppReduce.first == std::string("Deterministic")) ||
|
||||
(_ppReduce.first == std::string("Sequential"))
|
||||
)
|
||||
{
|
||||
ptReduce = new eoTruncate<EOT>;
|
||||
}
|
||||
// ---------- EP
|
||||
else if (_ppReduce.first == std::string("EP"))
|
||||
{
|
||||
if (!_ppReduce.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to EP, using 6" << std::endl;
|
||||
detSize = 6;
|
||||
// put back 6 in parameter for consistency (and status file)
|
||||
_ppReduce.second.push_back(std::string("6"));
|
||||
}
|
||||
else // parameter passed by user as EP(T)
|
||||
detSize = atoi(_ppReduce.second[0].c_str());
|
||||
ptReduce = new eoEPReduce<EOT>(detSize);
|
||||
}
|
||||
// ---------- DetTour
|
||||
else if (_ppReduce.first == std::string("DetTour"))
|
||||
{
|
||||
if (!_ppReduce.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl;
|
||||
detSize = 2;
|
||||
// put back 2 in parameter for consistency (and status file)
|
||||
_ppReduce.second.push_back(std::string("2"));
|
||||
}
|
||||
else // parameter passed by user as DetTour(T)
|
||||
detSize = atoi(_ppReduce.second[0].c_str());
|
||||
ptReduce = new eoDetTournamentTruncate<EOT>(detSize);
|
||||
}
|
||||
else if (_ppReduce.first == std::string("StochTour"))
|
||||
{
|
||||
double p;
|
||||
if (!_ppReduce.second.size()) // no parameter added
|
||||
{
|
||||
std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl;
|
||||
p = 1;
|
||||
// put back p in parameter for consistency (and status file)
|
||||
_ppReduce.second.push_back(std::string("1"));
|
||||
}
|
||||
else // parameter passed by user as DetTour(T)
|
||||
{
|
||||
p = atof(_ppReduce.second[0].c_str());
|
||||
if ( (p<=0.5) || (p>1) )
|
||||
throw std::runtime_error("Stochastic tournament size should be in [0.5,1]");
|
||||
}
|
||||
|
||||
ptReduce = new eoStochTournamentTruncate<EOT>(p);
|
||||
}
|
||||
else if ( (_ppReduce.first == std::string("Uniform")) ||
|
||||
(_ppReduce.first == std::string("Random"))
|
||||
)
|
||||
{
|
||||
ptReduce = new eoRandomReduce<EOT>;
|
||||
}
|
||||
else // no known reduction entered
|
||||
{
|
||||
throw std::runtime_error("Unknown reducer: " + _ppReduce.first);
|
||||
}
|
||||
// all done, stores and return a reference
|
||||
_state.storeFunctor(ptReduce);
|
||||
return (*ptReduce);
|
||||
}
|
||||
|
||||
/** Helper function that creates a replacement from the class
|
||||
* eoReduceMergeReduce using 6 parameters
|
||||
* (after the usual eoState and eoParser)
|
||||
*
|
||||
* eoHowMany _elite the number of elite parents (0 = no elitism)
|
||||
* see below
|
||||
* bool _strongElitism if elite > 0, std::string elitism or weak elitism
|
||||
* strong = elite parents survive, whatever the offspring
|
||||
* weak - elite patents compete AFTER replacement with best offspring
|
||||
* eoHowMany _surviveParents number of parents after parents recuction
|
||||
* eoParamParamType & _reduceParentType how the parents are reduced
|
||||
* eoHowMany _surviveOffspring number of offspring after offspring recuction
|
||||
* eoParamParamType & _reduceOffspringType how the offspring are reduced
|
||||
* eoParamParamType & _reduceFinalType how the final population is reduced to initial population size
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
eoReplacement<EOT> & make_general_replacement(
|
||||
eoParser& _parser, eoState& _state,
|
||||
eoHowMany _elite = eoHowMany(0),
|
||||
bool _strongElitism = false,
|
||||
eoHowMany _surviveParents = eoHowMany(0.0),
|
||||
eoParamParamType & _reduceParentType = eoParamParamType("Deterministic"),
|
||||
eoHowMany _surviveOffspring = eoHowMany(1.0),
|
||||
eoParamParamType & _reduceOffspringType = eoParamParamType("Deterministic"),
|
||||
eoParamParamType & _reduceFinalType = eoParamParamType("Deterministic")
|
||||
)
|
||||
{
|
||||
/////////////////////////////////////////////////////
|
||||
// the replacement
|
||||
/////////////////////////////////////////////////////
|
||||
|
||||
// Elitism
|
||||
eoHowMany elite = _parser.createParam(_elite, "elite", "Nb of elite parents (percentage or absolute)", '\0', "Evolution Engine / Replacement").value();
|
||||
|
||||
bool strongElitism = _parser.createParam(_strongElitism,"eliteType", "Strong (true) or weak (false) elitism (set elite to 0 for none)", '\0', "Evolution Engine / Replacement").value();
|
||||
|
||||
// reduce the parents
|
||||
eoHowMany surviveParents = _parser.createParam(_surviveParents, "surviveParents", "Nb of surviving parents (percentage or absolute)", '\0', "Evolution Engine / Replacement").value();
|
||||
|
||||
eoParamParamType & reduceParentType = _parser.createParam(_reduceParentType, "reduceParents", "Parents reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform", '\0', "Evolution Engine / Replacement").value();
|
||||
|
||||
eoReduce<EOT> & reduceParent = decode_reduce<EOT>(reduceParentType, _state);
|
||||
|
||||
// reduce the offspring
|
||||
eoHowMany surviveOffspring = _parser.createParam(_surviveOffspring, "surviveOffspring", "Nb of surviving offspring (percentage or absolute)", '\0', "Evolution Engine / Replacement").value();
|
||||
|
||||
eoParamParamType & reduceOffspringType = _parser.createParam(_reduceOffspringType, "reduceOffspring", "Offspring reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform", '\0', "Evolution Engine / Replacement").value();
|
||||
|
||||
eoReduce<EOT> & reduceOffspring = decode_reduce<EOT>(reduceOffspringType, _state);
|
||||
|
||||
eoParamParamType & reduceFinalType = _parser.createParam(_reduceFinalType, "reduceFinal", "Final reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform", '\0', "Evolution Engine / Replacement").value();
|
||||
|
||||
eoReduce<EOT> & reduceFinal = decode_reduce<EOT>(reduceFinalType, _state);
|
||||
|
||||
// now the replacement itself
|
||||
eoReduceMergeReduce<EOT> *ptReplace = new eoReduceMergeReduce<EOT>(elite, strongElitism, surviveParents, reduceParent, surviveOffspring, reduceOffspring, reduceFinal);
|
||||
_state.storeFunctor(ptReplace);
|
||||
|
||||
// that's it!
|
||||
return *ptReplace;
|
||||
}
|
||||
|
||||
#endif
|
||||
108
trunk/paradiseo-eo/src/do/make_pop.h
Normal file
108
trunk/paradiseo-eo/src/do/make_pop.h
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// make_pop.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _make_pop_h
|
||||
#define _make_pop_h
|
||||
|
||||
#include <ctime> // for time(0) for random seeding
|
||||
#include <eoPop.h>
|
||||
#include <eoInit.h>
|
||||
#include <utils/eoRNG.h>
|
||||
#include <utils/eoParser.h>
|
||||
#include <utils/eoState.h>
|
||||
|
||||
|
||||
///////////////////////////////// INIT POP ///////////////////////////////
|
||||
/**
|
||||
* Templatized version of parser-based construct of the population
|
||||
* + other initializations that are NOT representation-dependent.
|
||||
*
|
||||
* It must then be instantiated, and compiled on its own for a given EOType
|
||||
* (see e.g. ga.h and ga.pp in dir ga)
|
||||
*/
|
||||
|
||||
|
||||
template <class EOT>
|
||||
eoPop<EOT>& do_make_pop(eoParser & _parser, eoState& _state, eoInit<EOT> & _init)
|
||||
{
|
||||
// random seed
|
||||
eoValueParam<uint32_t>& seedParam = _parser.createParam(uint32_t(0), "seed", "Random number seed", 'S');
|
||||
if (seedParam.value() == 0)
|
||||
seedParam.value() = time(0);
|
||||
eoValueParam<unsigned>& popSize = _parser.createParam(unsigned(20), "popSize", "Population Size", 'P', "Evolution Engine");
|
||||
|
||||
// Either load or initialize
|
||||
// create an empty pop and let the state handle the memory
|
||||
eoPop<EOT>& pop = _state.takeOwnership(eoPop<EOT>());
|
||||
|
||||
eoValueParam<std::string>& loadNameParam = _parser.createParam(std::string(""), "Load","A save file to restart from",'L', "Persistence" );
|
||||
eoValueParam<bool> & recomputeFitnessParam = _parser.createParam(false, "recomputeFitness", "Recompute the fitness after re-loading the pop.?", 'r', "Persistence" );
|
||||
|
||||
if (loadNameParam.value() != "") // something to load
|
||||
{
|
||||
// create another state for reading
|
||||
eoState inState; // a state for loading - WITHOUT the parser
|
||||
// register the rng and the pop in the state, so they can be loaded,
|
||||
// and the present run will be the exact continuation of the saved run
|
||||
// eventually with different parameters
|
||||
inState.registerObject(pop);
|
||||
inState.registerObject(rng);
|
||||
inState.load(loadNameParam.value()); // load the pop and the rng
|
||||
// the fitness is read in the file:
|
||||
// do only evaluate the pop if the fitness has changed
|
||||
if (recomputeFitnessParam.value())
|
||||
{
|
||||
for (unsigned i=0; i<pop.size(); i++)
|
||||
pop[i].invalidate();
|
||||
}
|
||||
if (pop.size() < popSize.value())
|
||||
std::cerr << "WARNING, only " << pop.size() << " individuals read in file " << loadNameParam.value() << "\nThe remaining " << popSize.value() - pop.size() << " will be randomly drawn" << std::endl;
|
||||
if (pop.size() > popSize.value())
|
||||
{
|
||||
std::cerr << "WARNING, Load file contained too many individuals. Only the best will be retained" << std::endl;
|
||||
pop.resize(popSize.value());
|
||||
}
|
||||
}
|
||||
else // nothing loaded from a file
|
||||
{
|
||||
rng.reseed(seedParam.value());
|
||||
}
|
||||
|
||||
if (pop.size() < popSize.value()) // missing some guys
|
||||
{
|
||||
// Init pop from the randomizer: need to use the append function
|
||||
pop.append(popSize.value(), _init);
|
||||
}
|
||||
|
||||
// for future stateSave, register the algorithm into the state
|
||||
_state.registerObject(_parser);
|
||||
_state.registerObject(pop);
|
||||
_state.registerObject(rng);
|
||||
|
||||
return pop;
|
||||
}
|
||||
|
||||
#endif
|
||||
45
trunk/paradiseo-eo/src/do/make_run.h
Normal file
45
trunk/paradiseo-eo/src/do/make_run.h
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// make_run.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _make_run_h
|
||||
#define _make_run_h
|
||||
|
||||
// Algorithm (only this one needed)
|
||||
#include <eoAlgo.h>
|
||||
|
||||
/*
|
||||
* A trivial function - only here to allow instanciation with a give EOType
|
||||
* and separate compilation - see in ga dir, make_run_ga
|
||||
*
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
void do_run(eoAlgo<EOT>& _algo, eoPop<EOT>& _pop)
|
||||
{
|
||||
_algo(_pop);
|
||||
}
|
||||
|
||||
#endif
|
||||
154
trunk/paradiseo-eo/src/eo
Normal file
154
trunk/paradiseo-eo/src/eo
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// eo
|
||||
// (c) GeNeura Team 1998 - 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
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#ifndef _eo_
|
||||
#define _eo_
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
// general purpose
|
||||
#include <utils/eoData.h>
|
||||
#include <eoObject.h>
|
||||
#include <eoPrintable.h>
|
||||
#include <eoPersistent.h>
|
||||
#include <eoScalarFitness.h>
|
||||
#include <EO.h>
|
||||
|
||||
#include <utils/rnd_generators.h>
|
||||
#include <eoFunctor.h>
|
||||
#include <apply.h>
|
||||
|
||||
// eo's
|
||||
#include <eoVector.h>
|
||||
|
||||
#include <other/eoString.h>
|
||||
|
||||
#include <utils/eoRndGenerators.h>
|
||||
#include <eoInit.h>
|
||||
#include <utils/eoUniformInit.h>
|
||||
|
||||
// the variation operators
|
||||
#include <eoOp.h>
|
||||
#include <eoGenOp.h>
|
||||
#include <eoCloneOps.h>
|
||||
#include <eoOpContainer.h>
|
||||
// combinations of simple eoOps (eoMonOp and eoQuadOp)
|
||||
#include <eoProportionalCombinedOp.h>
|
||||
// didactic (mimics SGA-like variation into an eoGenOp)
|
||||
// calls crossover and mutation sequentially,
|
||||
// with their respective mutation rates
|
||||
#include <eoSGAGenOp.h>
|
||||
// its dual: crossover, mutation (and copy) - proportional choice
|
||||
// w.r.t. given relative weights
|
||||
#include <eoPropGAGenOp.h>
|
||||
|
||||
// population
|
||||
#include <eoPop.h>
|
||||
|
||||
// Evaluation functions (all include eoEvalFunc.h)
|
||||
#include <eoPopEvalFunc.h>
|
||||
#include <eoEvalFuncPtr.h>
|
||||
|
||||
// Continuators - all include eoContinue.h
|
||||
#include <eoCombinedContinue.h>
|
||||
#include <eoGenContinue.h>
|
||||
#include <eoSteadyFitContinue.h>
|
||||
#include <eoEvalContinue.h>
|
||||
#include <eoFitContinue.h>
|
||||
#include <eoPeriodicContinue.h>
|
||||
#ifndef _MSC_VER
|
||||
#include <eoCtrlCContinue.h> // CtrlC handling (using 2 global variables!)
|
||||
#endif
|
||||
// Selection
|
||||
// the eoSelectOne's
|
||||
#include <eoRandomSelect.h>
|
||||
#include <eoSequentialSelect.h>
|
||||
#include <eoDetTournamentSelect.h>
|
||||
#include <eoProportionalSelect.h>
|
||||
#include <eoFitnessScalingSelect.h> // also contains eoLinearFitScaling.h
|
||||
#include <eoRankingSelect.h>
|
||||
#include <eoStochTournamentSelect.h>
|
||||
#include <eoSharingSelect.h>
|
||||
// Embedding truncation selection
|
||||
#include <eoTruncatedSelectOne.h>
|
||||
|
||||
// the batch selection - from an eoSelectOne
|
||||
#include <eoSelectPerc.h>
|
||||
#include <eoSelectNumber.h>
|
||||
#include <eoSelectMany.h>
|
||||
#include <eoTruncatedSelectMany.h>
|
||||
|
||||
// other batch selections
|
||||
// DetSelect can also be obtained as eoSequentialSelect, an eoSelectOne
|
||||
// (using setup and an index)
|
||||
#include <eoDetSelect.h>
|
||||
|
||||
// Breeders
|
||||
#include <eoGeneralBreeder.h> // applies one eoGenOp, stop on offspring count
|
||||
// #include <eoOneToOneBreeder.h> // parent + SINGLE offspring compete (e.g. DE) - not ready yet...
|
||||
|
||||
// Replacement
|
||||
// #include <eoReplacement.h>
|
||||
#include <eoMergeReduce.h>
|
||||
#include <eoReduceMerge.h>
|
||||
#include <eoSurviveAndDie.h>
|
||||
|
||||
// a simple transformer
|
||||
#include <eoSGATransform.h>
|
||||
|
||||
// Perf2Worth stuff - includes eoSelectFromWorth.h
|
||||
#include <eoParetoRanking.h>
|
||||
#include <eoNDSorting.h>
|
||||
|
||||
// Algorithms
|
||||
#include <eoEasyEA.h>
|
||||
#include <eoSGA.h>
|
||||
// #include <eoEvolutionStrategy.h> removed for a while - until eoGenOp is done
|
||||
|
||||
// Utils
|
||||
#include <utils/checkpointing>
|
||||
#include <utils/eoRealVectorBounds.h> // includes eoRealBounds.h
|
||||
#include <utils/eoIntBounds.h> // no eoIntVectorBounds
|
||||
|
||||
// aliens
|
||||
#include <other/external_eo>
|
||||
#include <eoCounter.h>
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// to be continued ...
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif
|
||||
|
||||
// Local Variables:
|
||||
// mode: C++
|
||||
// End:
|
||||
43
trunk/paradiseo-eo/src/eoAlgo.h
Normal file
43
trunk/paradiseo-eo/src/eoAlgo.h
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoAlgo.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 _EOALGO_H
|
||||
#define _EOALGO_H
|
||||
|
||||
#include <eoPop.h> // for population
|
||||
#include <eoFunctor.h>
|
||||
|
||||
/**
|
||||
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.
|
||||
*/
|
||||
template< class EOT >
|
||||
class eoAlgo : public eoUF<eoPop<EOT>&, void>
|
||||
{};
|
||||
|
||||
|
||||
#endif
|
||||
75
trunk/paradiseo-eo/src/eoBreed.h
Normal file
75
trunk/paradiseo-eo/src/eoBreed.h
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
/** -*- 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>
|
||||
#include <eoSelect.h>
|
||||
#include <eoTransform.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** Breeding: combination of selecting and transforming a population
|
||||
|
||||
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 eoBF<const eoPop<EOT>&, eoPop<EOT>&, void>
|
||||
{};
|
||||
|
||||
|
||||
|
||||
/** Embedded select, followed by an embedded transform
|
||||
|
||||
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
|
||||
161
trunk/paradiseo-eo/src/eoCellularEasyEA.h
Normal file
161
trunk/paradiseo-eo/src/eoCellularEasyEA.h
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
// "eoCellularEasyEA.h"
|
||||
|
||||
// (c) OPAC Team, LIFL, 2002
|
||||
|
||||
/* 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: cahon@lifl.fr
|
||||
*/
|
||||
|
||||
#ifndef eoCellularEasyEA_h
|
||||
#define eoCellularEasyEA_h
|
||||
|
||||
#include <eoContinue.h>
|
||||
#include <eoEvalFunc.h>
|
||||
#include <eoSelectOne.h>
|
||||
#include <eoPopEvalFunc.h>
|
||||
#include <eoAlgo.h>
|
||||
#include <eoOp.h>
|
||||
|
||||
/**
|
||||
The abstract cellular easy algorithm.
|
||||
*/
|
||||
|
||||
template <class EOT> class eoCellularEasyEA : public eoAlgo <EOT> {
|
||||
|
||||
public :
|
||||
|
||||
/**
|
||||
Two constructors
|
||||
*/
|
||||
|
||||
eoCellularEasyEA (eoContinue <EOT> & _cont, // Stop. criterion
|
||||
eoEvalFunc <EOT> & _eval, // Evaluation function
|
||||
eoSelectOne <EOT> & _sel_neigh, // To choose a partner
|
||||
eoBinOp <EOT> & _cross, // Cross-over operator
|
||||
eoMonOp <EOT> & _mut, // Mutation operator
|
||||
eoSelectOne <EOT> & _sel_repl /* Which to keep between the new
|
||||
child and the old individual ? */
|
||||
) :
|
||||
cont (_cont),
|
||||
eval (_eval),
|
||||
popEval (_eval),
|
||||
sel_neigh (_sel_neigh),
|
||||
cross (_cross),
|
||||
mut (_mut),
|
||||
sel_child (eoSelectFirstOne ()),
|
||||
sel_repl (_sel_repl) {
|
||||
|
||||
}
|
||||
|
||||
eoCellularEasyEA (eoContinue <EOT> & _cont,
|
||||
eoEvalFunc <EOT> & _eval,
|
||||
eoSelectOne <EOT> & _sel_neigh,
|
||||
eoQuadOp <EOT> & _cross,
|
||||
eoMonOp <EOT> & _mut,
|
||||
eoSelectOne <EOT> & _sel_child, /* To choose one from
|
||||
the both children */
|
||||
eoSelectOne <EOT> & _sel_repl
|
||||
) :
|
||||
cont (_cont),
|
||||
eval (_eval),
|
||||
popEval (_eval),
|
||||
sel_neigh (_sel_neigh),
|
||||
cross (_cross),
|
||||
mut (_mut),
|
||||
sel_child (_sel_child),
|
||||
sel_repl (_sel_repl) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
For a given population.
|
||||
*/
|
||||
|
||||
void operator () (eoPop <EOT> & pop) {
|
||||
|
||||
do {
|
||||
|
||||
for (unsigned i = 0 ; i < pop.size () ; i ++) {
|
||||
|
||||
// Who are neighbouring to the current individual ?
|
||||
eoPop <EOT> neigh = neighbours (pop, i) ;
|
||||
|
||||
// To select a partner
|
||||
EOT part, old_sol = pop [i] ;
|
||||
part = sel_neigh (neigh) ;
|
||||
|
||||
// To perform cross-over
|
||||
cross (pop [i], part) ;
|
||||
|
||||
// To perform mutation
|
||||
mut (pop [i]) ;
|
||||
mut (part) ;
|
||||
|
||||
pop [i].invalidate () ;
|
||||
part.invalidate () ;
|
||||
eval (pop [i]) ;
|
||||
eval (part) ;
|
||||
|
||||
// To choose one of the two children ...
|
||||
eoPop <EOT> pop_loc ;
|
||||
pop_loc.push_back (pop [i]) ;
|
||||
pop_loc.push_back (part) ;
|
||||
|
||||
pop [i] = sel_child (pop_loc) ;
|
||||
|
||||
// To choose only one between the new made child and the old individual
|
||||
pop_loc.clear () ;
|
||||
pop_loc.push_back (pop [i]) ;
|
||||
|
||||
pop_loc.push_back (old_sol) ;
|
||||
|
||||
pop [i] = sel_repl (pop_loc) ;
|
||||
}
|
||||
|
||||
} while (cont (pop)) ;
|
||||
}
|
||||
|
||||
protected :
|
||||
|
||||
virtual eoPop <EOT> neighbours (const eoPop <EOT> & pop, int rank) = 0 ;
|
||||
|
||||
private :
|
||||
|
||||
eoContinue <EOT> & cont ;
|
||||
eoEvalFunc <EOT> & eval ;
|
||||
eoPopLoopEval <EOT> popEval ;
|
||||
eoSelectOne <EOT> & sel_neigh ;
|
||||
eoBF <EOT &, EOT &, bool> & cross ;
|
||||
eoMonOp <EOT> & mut ;
|
||||
eoSelectOne <EOT> & sel_child ;
|
||||
eoSelectOne <EOT> & sel_repl ;
|
||||
|
||||
class eoSelectFirstOne : public eoSelectOne <EOT> {
|
||||
|
||||
public :
|
||||
|
||||
const EOT & operator () (const eoPop <EOT> & pop) {
|
||||
|
||||
return pop [0] ;
|
||||
}
|
||||
|
||||
} ;
|
||||
|
||||
} ;
|
||||
|
||||
#endif
|
||||
79
trunk/paradiseo-eo/src/eoCloneOps.h
Normal file
79
trunk/paradiseo-eo/src/eoCloneOps.h
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoCloneOps.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
|
||||
CVS Info: $Date: 2003/02/27 19:26:09 $ $Header: /cvsroot/eodev/eo/src/eoCloneOps.h,v 1.2 2003/02/27 19:26:09 okoenig Exp $ $Author: okoenig $
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoCloneOps_H
|
||||
#define _eoCloneOps_H
|
||||
|
||||
#include <eoOp.h>
|
||||
|
||||
/**
|
||||
* The different null-variation operators (i.e. they do nothing)
|
||||
*
|
||||
* eoQuadCloneOp at least is useful to emulate the standard
|
||||
* crossover(pCross) + mutation(pMut)
|
||||
* within the eoGenOp framework
|
||||
* eoMonCloneOp will probably be useful as the copy operator
|
||||
* eoBinCloneOp will certainly never been used - but let's be complete :-)
|
||||
*/
|
||||
|
||||
/**
|
||||
Mon clone: one argument
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoMonCloneOp: public eoMonOp<EOT>
|
||||
{
|
||||
public:
|
||||
/// Ctor
|
||||
eoMonCloneOp() : eoMonOp<EOT>() {}
|
||||
virtual std::string className() const {return "eoMonCloneOp";}
|
||||
virtual bool operator()(EOT&){return false;}
|
||||
};
|
||||
|
||||
|
||||
/** Binary clone: two operands, only the first could be modified
|
||||
*/
|
||||
template<class EOT>
|
||||
class eoBinCloneOp: public eoBinOp<EOT>
|
||||
{
|
||||
public:
|
||||
/// Ctor
|
||||
eoBinCloneOp() : eoBinOp<EOT>() {}
|
||||
virtual std::string className() const {return "eoBinCloneOp";}
|
||||
virtual bool operator()(EOT&, const EOT&){return false;}
|
||||
};
|
||||
|
||||
/** Quad clone: two operands, both could be modified - but are not!
|
||||
*/
|
||||
template<class EOT>
|
||||
class eoQuadCloneOp: public eoQuadOp<EOT>
|
||||
{
|
||||
public:
|
||||
/// Ctor
|
||||
eoQuadCloneOp():eoQuadOp<EOT>() {}
|
||||
virtual std::string className() const {return "eoQuadCloneOp";}
|
||||
virtual bool operator()(EOT& , EOT& ) {return false;}
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
92
trunk/paradiseo-eo/src/eoCombinedContinue.h
Normal file
92
trunk/paradiseo-eo/src/eoCombinedContinue.h
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
// -*- 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>
|
||||
|
||||
/**
|
||||
Combined continuators - logical AND:
|
||||
Continues until one of the embedded continuators says halt!
|
||||
|
||||
20/11/00 MS: Changed the 2-continuator construct to a std::vector<eoContinue<EOT> >
|
||||
to be consistent with other Combined constructs
|
||||
and allow to easily handle more than 2 continuators
|
||||
|
||||
02/2003 Ramón Casero Cañas - added the removeLast() method
|
||||
*/
|
||||
|
||||
template< class EOT>
|
||||
class eoCombinedContinue: public eoContinue<EOT> {
|
||||
public:
|
||||
|
||||
/// Define Fitness
|
||||
typedef typename EOT::Fitness FitnessType;
|
||||
|
||||
/// Ctor, make sure that at least on continuator is present
|
||||
eoCombinedContinue( eoContinue<EOT>& _cont)
|
||||
: eoContinue<EOT> ()
|
||||
{
|
||||
continuators.push_back(&_cont);
|
||||
}
|
||||
|
||||
/// Ctor - for historical reasons ... should disspear some day
|
||||
eoCombinedContinue( eoContinue<EOT>& _cont1, eoContinue<EOT>& _cont2)
|
||||
: eoContinue<EOT> ()
|
||||
{
|
||||
continuators.push_back(&_cont1);
|
||||
continuators.push_back(&_cont2);
|
||||
}
|
||||
|
||||
void add(eoContinue<EOT> & _cont)
|
||||
{
|
||||
continuators.push_back(&_cont);
|
||||
}
|
||||
|
||||
///////////// RAMON'S CODE ///////////////
|
||||
void removeLast(void)
|
||||
{
|
||||
continuators.pop_back();
|
||||
}
|
||||
///////////// RAMON'S CODE (end) ///////////////
|
||||
|
||||
|
||||
/** Returns false when one of the embedded continuators say so (logical and)
|
||||
*/
|
||||
virtual bool operator() ( const eoPop<EOT>& _pop )
|
||||
{
|
||||
for (unsigned i = 0; i < continuators.size(); ++i)
|
||||
if ( !(*continuators[i])(_pop) ) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoCombinedContinue"; }
|
||||
|
||||
private:
|
||||
std::vector<eoContinue<EOT>*> continuators;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
89
trunk/paradiseo-eo/src/eoCombinedInit.h
Normal file
89
trunk/paradiseo-eo/src/eoCombinedInit.h
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoCombinedInit.h
|
||||
// (c) Maarten Keijzer, GeNeura Team, Marc Schoenauer 2004
|
||||
/*
|
||||
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: Marc.Schoenauer@inria.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoCombinedInit_h
|
||||
#define _eoCombinedInit_h
|
||||
|
||||
#include <eoInit.h>
|
||||
|
||||
/**
|
||||
Combined INIT: a proportional recombination of eoInit objects
|
||||
*/
|
||||
|
||||
template< class EOT>
|
||||
class eoCombinedInit: public eoInit<EOT> {
|
||||
public:
|
||||
|
||||
/** Ctor, make sure that at least one eoInit is present */
|
||||
eoCombinedInit( eoInit<EOT>& _init, double _rate)
|
||||
: eoInit<EOT> ()
|
||||
{
|
||||
initializers.push_back(&_init);
|
||||
rates.push_back(_rate);
|
||||
}
|
||||
|
||||
/** The usual method to add objects to the combination
|
||||
* note the _verbose parameter, that allows to print what's
|
||||
* inside the combination with scaled rates
|
||||
*/
|
||||
void add(eoInit<EOT> & _init, double _rate, bool _verbose=false)
|
||||
{
|
||||
initializers.push_back(&_init);
|
||||
rates.push_back(_rate);
|
||||
// compute the relative rates in percent - to warn the user!
|
||||
if (_verbose)
|
||||
printOn(std::cout);
|
||||
}
|
||||
|
||||
/** outputs the operators and percentages */
|
||||
virtual void printOn(std::ostream & _os)
|
||||
{
|
||||
double total = 0;
|
||||
unsigned i;
|
||||
for (i=0; i<initializers.size(); i++)
|
||||
total += rates[i];
|
||||
_os << "In " << className() << "\n" ;
|
||||
for (i=0; i<initializers.size(); i++)
|
||||
_os << initializers[i]->className() << " with rate " << 100*rates[i]/total << " %\n";
|
||||
}
|
||||
|
||||
/** Performs the init: chooses among all initializers
|
||||
* using roulette wheel on the rates
|
||||
*/
|
||||
virtual void operator() ( EOT & _eo )
|
||||
{
|
||||
unsigned what = rng.roulette_wheel(rates); // choose one op
|
||||
(*initializers[what])(_eo); // apply it
|
||||
return;
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoCombinedInit"; }
|
||||
|
||||
private:
|
||||
std::vector<eoInit<EOT>*> initializers;
|
||||
std::vector<double> rates;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
54
trunk/paradiseo-eo/src/eoContinue.h
Normal file
54
trunk/paradiseo-eo/src/eoContinue.h
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// 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
|
||||
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 _eoContinue_h
|
||||
#define _eoContinue_h
|
||||
|
||||
#include <eoFunctor.h>
|
||||
#include <eoPop.h>
|
||||
#include <eoPersistent.h>
|
||||
|
||||
/** Termination condition for the genetic algorithm
|
||||
* Takes the population as input, returns true for continue,
|
||||
* false for termination
|
||||
*/
|
||||
template< class EOT>
|
||||
class eoContinue : public eoUF<const eoPop<EOT>&, bool>, public eoPersistent
|
||||
{
|
||||
public:
|
||||
virtual std::string className(void) const { return "eoContinue"; }
|
||||
|
||||
void readFrom (std :: istream & __is) {
|
||||
|
||||
/* It should be implemented by subclasses ! */
|
||||
}
|
||||
|
||||
void printOn (std :: ostream & __os) const {
|
||||
|
||||
/* It should be implemented by subclasses ! */
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
219
trunk/paradiseo-eo/src/eoCounter.h
Normal file
219
trunk/paradiseo-eo/src/eoCounter.h
Normal 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")
|
||||
: eoValueParam<unsigned long>(0, _name), proc(_proc) {}
|
||||
|
||||
/** 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")
|
||||
: eoValueParam<unsigned long>(0, _name), func(_func) {}
|
||||
|
||||
/** 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")
|
||||
: eoValueParam<unsigned long>(0, _name), func(_func) {}
|
||||
|
||||
/** 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.storeFunctor(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.storeFunctor(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.storeFunctor(result);
|
||||
return *result;
|
||||
}
|
||||
|
||||
#endif
|
||||
50
trunk/paradiseo-eo/src/eoCtrlCContinue.cpp
Normal file
50
trunk/paradiseo-eo/src/eoCtrlCContinue.cpp
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoCtrlCContinue.cpp
|
||||
// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
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
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <signal.h>
|
||||
#include <iostream>
|
||||
|
||||
// --- Global variables - but don't know what else to do - MS ---
|
||||
bool arret_demande = false;
|
||||
bool existCtrlCContinue = false;
|
||||
|
||||
//
|
||||
// The signal handler - installed in the eoCtrlCContinue Ctor
|
||||
//
|
||||
void signal_handler( int sig )
|
||||
// ---------------------------
|
||||
{
|
||||
// --- On veut la paix, jusqu'a la fin ---
|
||||
signal( SIGINT, SIG_IGN );
|
||||
signal( SIGQUIT, SIG_IGN );
|
||||
std::cerr << "Ctrl C entered ... closing down" << std::endl ;
|
||||
arret_demande = true;
|
||||
}
|
||||
|
||||
76
trunk/paradiseo-eo/src/eoCtrlCContinue.h
Normal file
76
trunk/paradiseo-eo/src/eoCtrlCContinue.h
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoCtrlCContinue.h
|
||||
// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
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
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
// the same thing can probably be done in MS environement, but I hoave no way
|
||||
// to test it so at the moment it is commented out when in MSVC
|
||||
#ifndef _MSC_VER
|
||||
|
||||
#ifndef eoCtrlCContinue_h
|
||||
#define eoCtrlCContinue_h
|
||||
|
||||
#include <signal.h>
|
||||
#include <eoContinue.h>
|
||||
|
||||
extern bool arret_demande, existCtrlCContinue;
|
||||
|
||||
extern void signal_handler( int sig );
|
||||
|
||||
|
||||
/**
|
||||
Ctrl C handling: this eoContinue tells whether the user pressed Ctrl C
|
||||
*/
|
||||
template< class EOT>
|
||||
class eoCtrlCContinue: public eoContinue<EOT>
|
||||
{
|
||||
public:
|
||||
|
||||
/// Ctor : installs the signal handler
|
||||
eoCtrlCContinue()
|
||||
{
|
||||
// First checks that no other eoCtrlCContinue does exist
|
||||
if (existCtrlCContinue)
|
||||
throw std::runtime_error("A signal handler for Ctrl C is already defined!\n");
|
||||
signal( SIGINT, signal_handler );
|
||||
signal( SIGQUIT, signal_handler );
|
||||
existCtrlCContinue = true;
|
||||
}
|
||||
|
||||
/** Returns false when Ctrl C has been typed in
|
||||
* reached */
|
||||
virtual bool operator() ( const eoPop<EOT>& _vEO )
|
||||
{
|
||||
if (arret_demande)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoCtrlCContinue"; }
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
#endif
|
||||
// of MSVC comment-out
|
||||
83
trunk/paradiseo-eo/src/eoDetSelect.h
Normal file
83
trunk/paradiseo-eo/src/eoDetSelect.h
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoDetSelect.h
|
||||
(c) Marc Schoenauer, 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
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoDetSelect_h
|
||||
#define _eoDetSelect_h
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoSelect.h>
|
||||
#include <utils/eoHowMany.h>
|
||||
#include <math.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** eoDetSelect selects many individuals determinisctically
|
||||
*/
|
||||
template<class EOT>
|
||||
class eoDetSelect : public eoSelect<EOT>
|
||||
{
|
||||
public:
|
||||
/// init
|
||||
eoDetSelect(double _rate = 1.0, bool _interpret_as_rate = true)
|
||||
: howMany(_rate, _interpret_as_rate) {}
|
||||
|
||||
/**
|
||||
@param _source the source population
|
||||
@param _dest the resulting population (size of this population is
|
||||
given by the HowMany data
|
||||
It empties the destination and adds the selection into it)
|
||||
*/
|
||||
virtual void operator()(const eoPop<EOT>& _source, eoPop<EOT>& _dest)
|
||||
{
|
||||
unsigned int pSize = _source.size();
|
||||
size_t target = howMany(pSize);
|
||||
|
||||
_dest.resize(target);
|
||||
|
||||
unsigned remain = target % pSize;
|
||||
unsigned entireCopy = target / pSize;
|
||||
typename eoPop<EOT>::iterator it = _dest.begin();
|
||||
|
||||
if (target >= pSize)
|
||||
{
|
||||
for (unsigned i=0; i<entireCopy; i++)
|
||||
{
|
||||
std::copy(_source.begin(), _source.end(), it);
|
||||
it += pSize;
|
||||
}
|
||||
}
|
||||
// the last ones
|
||||
if (remain)
|
||||
{
|
||||
std::copy(_source.begin(), _source.begin()+remain, it);
|
||||
}
|
||||
}
|
||||
|
||||
private :
|
||||
eoHowMany howMany;
|
||||
};
|
||||
|
||||
#endif
|
||||
73
trunk/paradiseo-eo/src/eoDetTournamentSelect.h
Executable file
73
trunk/paradiseo-eo/src/eoDetTournamentSelect.h
Executable file
|
|
@ -0,0 +1,73 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoDetTournament.h
|
||||
// (c) GeNeura Team, 1998 - EEAAX 1999
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoDetTournament_h
|
||||
#define eoDetTournament_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <functional> //
|
||||
#include <numeric> // accumulate
|
||||
|
||||
#include <eoFunctor.h>
|
||||
#include <eoPop.h>
|
||||
#include <utils/selectors.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
/** eoDetTournamentSelect: a selection method that selects ONE individual by
|
||||
deterministic tournament
|
||||
-MS- 24/10/99 */
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
template <class EOT> class eoDetTournamentSelect: public eoSelectOne<EOT>
|
||||
{
|
||||
public:
|
||||
/* (Default) Constructor -
|
||||
@param _tSize tournament size
|
||||
*/
|
||||
eoDetTournamentSelect(unsigned _tSize = 2 ):eoSelectOne<EOT>(), tSize(_tSize) {
|
||||
// consistency check
|
||||
if (tSize < 2) {
|
||||
std::cout << "Warning, Tournament size should be >= 2\nAdjusted to 2\n";
|
||||
tSize = 2;
|
||||
}
|
||||
}
|
||||
|
||||
/* Perform deterministic tournament calling the appropriate fn
|
||||
see selectors.h
|
||||
*/
|
||||
virtual const EOT& operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
return deterministic_tournament(_pop, tSize);
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned tSize;
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif
|
||||
|
||||
50
trunk/paradiseo-eo/src/eoDistribUpdater.h
Normal file
50
trunk/paradiseo-eo/src/eoDistribUpdater.h
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoDistribUpdater.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoDistribUpdater_H
|
||||
#define _eoDistribUpdater_H
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <eoDistribution.h>
|
||||
#include <eoPop.h>
|
||||
|
||||
/**
|
||||
* Base class for Distribution Evolution Algorithms within EO:
|
||||
* the update rule of distribution
|
||||
*
|
||||
* It takes one distribution and updates it according to one population
|
||||
*
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoDistribUpdater :
|
||||
public eoBF<eoDistribution<EOT> &, eoPop<EOT> &, void>
|
||||
{
|
||||
public:
|
||||
virtual void operator()(eoDistribution<EOT> &, eoPop<EOT> &)=0;
|
||||
};
|
||||
|
||||
#endif
|
||||
52
trunk/paradiseo-eo/src/eoDistribution.h
Normal file
52
trunk/paradiseo-eo/src/eoDistribution.h
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoDistribution.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoDistribution_H
|
||||
#define _eoDistribution_H
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <eoInit.h>
|
||||
#include <eoPop.h>
|
||||
|
||||
/**
|
||||
* Abstract class for Distribution Evolution Algorithms within EO:
|
||||
* the distribution itself
|
||||
*
|
||||
* It basically IS AN eoInit - operator()(EOT &) generates new indis
|
||||
*
|
||||
* The instances will probably be eoValueParam of some kind
|
||||
* see eoPBILDistrib.h
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoDistribution : public eoInit<EOT>,
|
||||
public eoPersistent, public eoObject
|
||||
{
|
||||
public:
|
||||
virtual void operator()(EOT &) = 0; // DO NOT FORGET TO INVALIDATE the EOT
|
||||
};
|
||||
|
||||
#endif
|
||||
162
trunk/paradiseo-eo/src/eoDominanceMap.h
Normal file
162
trunk/paradiseo-eo/src/eoDominanceMap.h
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoDominanceMap.h
|
||||
(c) Maarten Keijzer, Marc Schoenauer, 2001
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoDominanceMap_h
|
||||
#define eoDominanceMap_h
|
||||
|
||||
#include <eoFunctor.h>
|
||||
#include <eoPop.h>
|
||||
|
||||
/**
|
||||
eoDominanceMap, utility class to calculate and maintain a map (std::vector<std::vector<bool> >) of pareto dominance statistics.
|
||||
|
||||
It is set up such that
|
||||
|
||||
if map[i][j] == true
|
||||
then i dominates j
|
||||
|
||||
The dominance map can be used to perform pareto ranking (eoParetoRanking) or non dominated sorting.
|
||||
For the latter, the remove() member function might come in handy.
|
||||
|
||||
\todo make it an eoStat?
|
||||
*/
|
||||
template <class EoType>
|
||||
class eoDominanceMap : public eoUF<const eoPop<EoType>&, void>, public std::vector<std::vector<bool> >
|
||||
{
|
||||
public:
|
||||
|
||||
/** Clears the map */
|
||||
void clear() {
|
||||
std::vector<std::vector<bool> >::clear();
|
||||
fitness.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
Update or create the dominance map
|
||||
*/
|
||||
void operator()(const eoPop<EoType>& _pop)
|
||||
{
|
||||
setup(_pop);
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
Removes the domination info for a given individual, thus nothing dominates it and it dominates nothing.
|
||||
*/
|
||||
void remove(unsigned i)
|
||||
{
|
||||
for (unsigned j = 0; j < size(); ++j)
|
||||
{
|
||||
operator[](i)[j] = false; // clear row
|
||||
operator[](j)[i] = false; // clear col
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Create domination matrix from scratch. Complexity O(N^2)
|
||||
*/
|
||||
void setup(const eoPop<EoType>& _pop)
|
||||
{
|
||||
fitness.resize(_pop.size());
|
||||
resize(_pop.size());
|
||||
|
||||
for (unsigned i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
fitness[i] = _pop[i].fitness();
|
||||
operator[](i).resize(_pop.size(), false);
|
||||
|
||||
for (unsigned j = 0; j < i; ++j)
|
||||
{
|
||||
if (_pop[i].fitness().dominates(_pop[j].fitness()))
|
||||
{
|
||||
operator[](i)[j] = true;
|
||||
operator[](j)[i] = false;
|
||||
}
|
||||
else if (_pop[j].fitness().dominates(_pop[i].fitness()))
|
||||
{
|
||||
operator[](i)[j] = false;
|
||||
operator[](j)[i] = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
operator[](i)[j] = false;
|
||||
operator[](j)[i] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
For all elements, returns the no. of elements that dominate the element
|
||||
Thus: lower is better (and 0 is the front).
|
||||
It returns a std::vector<double> cuz that
|
||||
makes subsequent manipulation that much easier
|
||||
*/
|
||||
std::vector<double> sum_dominators() const
|
||||
{
|
||||
std::vector<double> result(size(), 0.0);
|
||||
|
||||
for (unsigned i = 0; i < size(); ++i)
|
||||
{
|
||||
for (unsigned j = 0; j < size(); ++j)
|
||||
{
|
||||
if (operator[](i)[j]) // i dominates j
|
||||
result[j]++;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
For all elements, returns the number of elements that the element dominates
|
||||
Thus: higher is better
|
||||
It returns a std::vector<double> cuz that
|
||||
makes subsequent manipulation that much easier
|
||||
*/
|
||||
std::vector<double> sum_dominants() const
|
||||
{
|
||||
std::vector<double> result(size(), 0.0);
|
||||
|
||||
for (unsigned i = 0; i < size(); ++i)
|
||||
{
|
||||
for (unsigned j = 0; j < size(); ++j)
|
||||
{
|
||||
if (operator[](i)[j]) // i dominates j
|
||||
result[i]++;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private :
|
||||
|
||||
|
||||
std::vector<typename EoType::Fitness> fitness;
|
||||
};
|
||||
|
||||
#endif
|
||||
46
trunk/paradiseo-eo/src/eoEDA.h
Normal file
46
trunk/paradiseo-eo/src/eoEDA.h
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoEDA.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoEDA_h
|
||||
#define _eoEDA_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <eoDistribution.h>
|
||||
|
||||
/** eoEDA: Estimation of Distribution Algorithm within EO
|
||||
*
|
||||
* The abstract class for algorithms that evolve a probability distribution
|
||||
* on the spaces of populations rather than a population
|
||||
*
|
||||
* It IS NOT an eoAlgo, as it evolves a distribution, not a population
|
||||
*/
|
||||
|
||||
template<class EOT> class eoEDA: public eoUF<eoDistribution<EOT>&, void>
|
||||
{
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
243
trunk/paradiseo-eo/src/eoEasyEA.h
Normal file
243
trunk/paradiseo-eo/src/eoEasyEA.h
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoEasyEA.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 _eoEasyEA_h
|
||||
#define _eoEasyEA_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <apply.h>
|
||||
#include <eoAlgo.h>
|
||||
#include <eoPopAlgo.h>
|
||||
#include <eoPopEvalFunc.h>
|
||||
#include <eoContinue.h>
|
||||
#include <eoSelect.h>
|
||||
#include <eoTransform.h>
|
||||
#include <eoBreed.h>
|
||||
#include <eoMergeReduce.h>
|
||||
#include <eoReplacement.h>
|
||||
|
||||
|
||||
|
||||
template <class EOT> class eoIslandsEasyEA ;
|
||||
|
||||
template <class EOT> class eoDistEvalEasyEA ;
|
||||
|
||||
/** 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
|
||||
|
||||
Change (MS, July 3. 2001):
|
||||
Replaced the eoEvalFunc by an eoPopEvalFunc: this immediately
|
||||
allows many useful constructs, such as co-evolution (e.g. game players),
|
||||
parisian approach (the solution to the problem is the whole population)
|
||||
or simple distribution of evaluations on a cluster.
|
||||
In case an eoEvalFunc is passed, it is embedded on an eoPopLoopEval
|
||||
This makes things a little uglier (required an additional "dummy" member
|
||||
|
||||
Note: it looks ugly only because we wanted to authorize many different
|
||||
constructors. Please only look at the operator() and there shall be light
|
||||
*/
|
||||
template<class EOT> class eoEasyEA: public eoAlgo<EOT> {
|
||||
public:
|
||||
|
||||
/** Ctor taking a breed and merge */
|
||||
eoEasyEA(
|
||||
eoContinue<EOT>& _continuator,
|
||||
eoEvalFunc<EOT>& _eval,
|
||||
eoBreed<EOT>& _breed,
|
||||
eoReplacement<EOT>& _replace
|
||||
) : continuator(_continuator),
|
||||
eval (_eval),
|
||||
loopEval(_eval),
|
||||
popEval(loopEval),
|
||||
selectTransform(dummySelect, dummyTransform),
|
||||
breed(_breed),
|
||||
mergeReduce(dummyMerge, dummyReduce),
|
||||
replace(_replace)
|
||||
{}
|
||||
|
||||
/*
|
||||
eoEasyEA(eoContinue <EOT> & _continuator,
|
||||
eoPopEvalFunc <EOT> & _pop_eval,
|
||||
eoBreed <EOT> & _breed,
|
||||
eoReplacement <EOT> & _replace
|
||||
) :
|
||||
continuator (_continuator),
|
||||
eval (dummyEval),
|
||||
loopEval(dummyEval),
|
||||
popEval (_pop_eval),
|
||||
selectTransform (dummySelect, dummyTransform),
|
||||
breed (_breed),
|
||||
mergeReduce (dummyMerge, dummyReduce),
|
||||
replace (_replace) {
|
||||
|
||||
}
|
||||
*/
|
||||
|
||||
/** NEW Ctor taking a breed and merge and an eoPopEval */
|
||||
eoEasyEA(
|
||||
eoContinue<EOT>& _continuator,
|
||||
eoPopEvalFunc<EOT>& _eval,
|
||||
eoBreed<EOT>& _breed,
|
||||
eoReplacement<EOT>& _replace
|
||||
) : continuator(_continuator),
|
||||
eval (dummyEval),
|
||||
loopEval(dummyEval),
|
||||
popEval(_eval),
|
||||
selectTransform(dummySelect, dummyTransform),
|
||||
breed(_breed),
|
||||
mergeReduce(dummyMerge, dummyReduce),
|
||||
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),
|
||||
loopEval(_eval),
|
||||
popEval(loopEval),
|
||||
selectTransform(dummySelect, dummyTransform),
|
||||
breed(_breed),
|
||||
mergeReduce(_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),
|
||||
loopEval(_eval),
|
||||
popEval(loopEval),
|
||||
selectTransform(_select, _transform),
|
||||
breed(selectTransform),
|
||||
mergeReduce(dummyMerge, dummyReduce),
|
||||
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),
|
||||
loopEval(_eval),
|
||||
popEval(loopEval),
|
||||
selectTransform(_select, _transform),
|
||||
breed(selectTransform),
|
||||
mergeReduce(_merge, _reduce),
|
||||
replace(mergeReduce)
|
||||
{}
|
||||
|
||||
|
||||
|
||||
|
||||
/// Apply a few generation of evolution to the population.
|
||||
virtual void operator()(eoPop<EOT>& _pop)
|
||||
{
|
||||
eoPop<EOT> offspring, empty_pop;
|
||||
popEval(empty_pop, _pop); // A first eval of pop.
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
unsigned pSize = _pop.size();
|
||||
offspring.clear(); // new offspring
|
||||
|
||||
breed(_pop, offspring);
|
||||
|
||||
popEval(_pop, offspring); // eval of parents + offspring if necessary
|
||||
|
||||
replace(_pop, offspring); // after replace, the new pop. is in _pop
|
||||
|
||||
if (pSize > _pop.size())
|
||||
throw std::runtime_error("Population shrinking!");
|
||||
else if (pSize < _pop.size())
|
||||
throw std::runtime_error("Population growing!");
|
||||
|
||||
}
|
||||
catch (std::exception& e)
|
||||
{
|
||||
std::string s = e.what();
|
||||
s.append( " in eoEasyEA");
|
||||
throw std::runtime_error( s );
|
||||
}
|
||||
} while ( continuator( _pop ) );
|
||||
}
|
||||
|
||||
protected :
|
||||
|
||||
// If selectTransform needs not be used, dummySelect and dummyTransform are used
|
||||
// to instantiate it.
|
||||
class eoDummySelect : public eoSelect<EOT>
|
||||
{ public : void operator()(const eoPop<EOT>&, eoPop<EOT>&) {} } dummySelect;
|
||||
|
||||
class eoDummyTransform : public eoTransform<EOT>
|
||||
{ public : void operator()(eoPop<EOT>&) {} } dummyTransform;
|
||||
|
||||
class eoDummyEval : public eoEvalFunc<EOT>
|
||||
{public: void operator()(EOT &) {} } dummyEval;
|
||||
|
||||
eoContinue<EOT>& continuator;
|
||||
|
||||
eoEvalFunc <EOT> & eval ;
|
||||
eoPopLoopEval<EOT> loopEval;
|
||||
|
||||
eoPopEvalFunc<EOT>& popEval;
|
||||
|
||||
eoSelectTransform<EOT> selectTransform;
|
||||
eoBreed<EOT>& breed;
|
||||
|
||||
// If mergeReduce needs not be used, dummyMerge and dummyReduce are used
|
||||
// to instantiate it.
|
||||
eoNoElitism<EOT> dummyMerge;
|
||||
eoTruncate<EOT> dummyReduce;
|
||||
|
||||
eoMergeReduce<EOT> mergeReduce;
|
||||
eoReplacement<EOT>& replace;
|
||||
|
||||
// Friend classes
|
||||
friend class eoIslandsEasyEA <EOT> ;
|
||||
friend class eoDistEvalEasyEA <EOT> ;
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif
|
||||
|
||||
68
trunk/paradiseo-eo/src/eoEvalContinue.h
Normal file
68
trunk/paradiseo-eo/src/eoEvalContinue.h
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoEvalContinue.h
|
||||
// (c) GeNeura Team, 1999, Marc Schoenauer 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoEvalContinue_h
|
||||
#define _eoEvalContinue_h
|
||||
|
||||
#include <eoContinue.h>
|
||||
#include <eoEvalFuncCounter.h>
|
||||
|
||||
/**
|
||||
* Continues until a number of evaluations has been made
|
||||
*/
|
||||
template< class EOT>
|
||||
class eoEvalContinue: public eoContinue<EOT>
|
||||
{
|
||||
public:
|
||||
/// Ctor
|
||||
eoEvalContinue( eoEvalFuncCounter<EOT> & _eval, unsigned long _totalEval)
|
||||
: eval(_eval), repTotalEvaluations( _totalEval ) {
|
||||
std::cout << "Ctor de eoEvalFuncCounter avec total = " << repTotalEvaluations << std::endl;
|
||||
};
|
||||
|
||||
/** Returns false when a certain number of evaluations has been done
|
||||
*/
|
||||
virtual bool operator() ( const eoPop<EOT>& _vEO ) {
|
||||
if (eval.value() >= repTotalEvaluations)
|
||||
{
|
||||
std::cout << "STOP in eoEvalContinue: Reached maximum number of evaluations [" << repTotalEvaluations << "]\n";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Returns the number of generations to reach*/
|
||||
virtual unsigned long totalEvaluations( )
|
||||
{
|
||||
return repTotalEvaluations;
|
||||
};
|
||||
|
||||
virtual std::string className(void) const { return "eoEvalContinue"; }
|
||||
private:
|
||||
eoEvalFuncCounter<EOT> & eval;
|
||||
unsigned long repTotalEvaluations;
|
||||
};
|
||||
|
||||
#endif
|
||||
49
trunk/paradiseo-eo/src/eoEvalFunc.h
Normal file
49
trunk/paradiseo-eo/src/eoEvalFunc.h
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoEvalFunc.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 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.\\
|
||||
|
||||
The requirements on the types with which this class is to be
|
||||
instantiated with are null, or else, they depend on the particular
|
||||
class it's going to be applied to; EO does not impose any requirement
|
||||
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> class eoEvalFunc : public eoUF<EOT&, void>
|
||||
{
|
||||
public :
|
||||
typedef EOT EOType;
|
||||
|
||||
typedef typename EOT::Fitness EOFitT;
|
||||
};
|
||||
|
||||
#endif
|
||||
56
trunk/paradiseo-eo/src/eoEvalFuncCounter.h
Normal file
56
trunk/paradiseo-eo/src/eoEvalFuncCounter.h
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoEvalFuncCounter.h
|
||||
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoEvalFuncCounter_H
|
||||
#define eoEvalFuncCounter_H
|
||||
|
||||
#include <eoEvalFunc.h>
|
||||
#include <utils/eoParam.h>
|
||||
|
||||
/**
|
||||
Counts the number of evaluations actually performed, thus checks first
|
||||
if it has to evaluate.. etc.
|
||||
*/
|
||||
template<class EOT> class eoEvalFuncCounter : public eoEvalFunc<EOT>, public eoValueParam<unsigned long>
|
||||
{
|
||||
public :
|
||||
eoEvalFuncCounter(eoEvalFunc<EOT>& _func, std::string _name = "Eval. ")
|
||||
: eoValueParam<unsigned long>(0, _name), func(_func) {}
|
||||
|
||||
virtual void operator()(EOT& _eo)
|
||||
{
|
||||
if (_eo.invalid())
|
||||
{
|
||||
value()++;
|
||||
func(_eo);
|
||||
}
|
||||
}
|
||||
|
||||
private :
|
||||
eoEvalFunc<EOT>& func;
|
||||
};
|
||||
|
||||
#endif
|
||||
66
trunk/paradiseo-eo/src/eoEvalFuncPtr.h
Normal file
66
trunk/paradiseo-eo/src/eoEvalFuncPtr.h
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoEvalFuncPtr.h
|
||||
Converts a classical C fitness evaluation function into a fitness
|
||||
evaluation object
|
||||
|
||||
(c) 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 EOEVALFUNCPTR_H
|
||||
#define EOEVALFUNCPTR_H
|
||||
|
||||
#include <eoEvalFunc.h>
|
||||
|
||||
/** EOEvalFuncPtr: This class
|
||||
* takes an existing function pointer and converts it into a evaluation
|
||||
* function class. That way, old style C or C++ functions can be adapted to EO
|
||||
* function classes.
|
||||
*/
|
||||
#ifdef _MSC_VER
|
||||
template< class EOT, class FitT = EOT::Fitness, class FunctionArg = const EOT& >
|
||||
#else
|
||||
template< class EOT, class FitT = typename EOT::Fitness, class FunctionArg = const EOT& >
|
||||
#endif
|
||||
struct eoEvalFuncPtr: public eoEvalFunc<EOT> {
|
||||
|
||||
/** Applies the function to the chromosome and sets the fitness of the
|
||||
Chrom. Thus, the evaluation function need not be worried about that.
|
||||
@param _eval pointer to the evaluation function, takes a EOT as an
|
||||
argument and returns the fitness
|
||||
@return the evaluated fitness for that object.
|
||||
*/
|
||||
eoEvalFuncPtr( FitT (* _eval)( FunctionArg ) )
|
||||
: eoEvalFunc<EOT>(), evalFunc( _eval ) {};
|
||||
|
||||
/// Effectively applies the evaluation function to an EO
|
||||
virtual void operator() ( EOT & _eo )
|
||||
{
|
||||
if (_eo.invalid())
|
||||
_eo.fitness((*evalFunc)( _eo ));
|
||||
};
|
||||
|
||||
private:
|
||||
FitT (* evalFunc )( FunctionArg );
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
72
trunk/paradiseo-eo/src/eoFactory.h
Normal file
72
trunk/paradiseo-eo/src/eoFactory.h
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoFactory.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 _EOFACTORY_H
|
||||
#define _EOFACTORY_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoObject.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** EO Factory. A factory is used to create other objects. In particular,
|
||||
it can be used so that objects of that kind can´t be created in any other
|
||||
way. It should be instantiated with anything that needs a factory, like selectors
|
||||
or whatever; but the instance class should be the parent class from which all the
|
||||
object that are going to be created descend. This class basically defines an interface,
|
||||
as usual. The base factory class for each hierarchy should be redefined every time a new
|
||||
object is added to the hierarchy, which is not too good, but in any case, some code would
|
||||
have to be modified*/
|
||||
template<class EOClass>
|
||||
class eoFactory: public eoObject {
|
||||
|
||||
public:
|
||||
|
||||
/// @name ctors and dtors
|
||||
//{@
|
||||
/// constructor
|
||||
eoFactory( ) {}
|
||||
|
||||
/// destructor
|
||||
virtual ~eoFactory() {}
|
||||
//@}
|
||||
|
||||
/** Another factory methods: creates an object from an std::istream, reading from
|
||||
it whatever is needed to create the object. Usually, the format for the std::istream will be\\
|
||||
objectType parameter1 parameter2 ... parametern\\
|
||||
*/
|
||||
virtual EOClass* make(std::istream& _is) = 0;
|
||||
|
||||
///@name eoObject methods
|
||||
//@{
|
||||
/** Return the class id */
|
||||
virtual std::string className() const { return "eoFactory"; }
|
||||
|
||||
/** Read and print are left without implementation */
|
||||
//@}
|
||||
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
66
trunk/paradiseo-eo/src/eoFitContinue.h
Normal file
66
trunk/paradiseo-eo/src/eoFitContinue.h
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
// -*- 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 )
|
||||
{
|
||||
FitnessType bestCurrentFitness = _pop.nth_element_fitness(0);
|
||||
if (bestCurrentFitness >= maximum)
|
||||
{
|
||||
std::cout << "STOP in eoFitContinue: Best fitness has reached " <<
|
||||
bestCurrentFitness << "\n";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoFitContinue"; }
|
||||
private:
|
||||
FitnessType maximum;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
54
trunk/paradiseo-eo/src/eoFitnessScalingSelect.h
Normal file
54
trunk/paradiseo-eo/src/eoFitnessScalingSelect.h
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoFitnessScalingSelect.h
|
||||
// (c) GeNeura Team, 1998, Maarten Keijzer 2000, Marc Schoenauer 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mak@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoFitnessScalingSelect_h
|
||||
#define eoFitnessScalingSelect_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <eoSelectFromWorth.h>
|
||||
#include <eoLinearFitScaling.h>
|
||||
|
||||
/** eoFitnessScalingSelect: select an individual proportional to the
|
||||
* linearly scaled fitness that is computed by the private
|
||||
* eoLinearFitScaling object
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoFitnessScalingSelect: public eoRouletteWorthSelect<EOT, double>
|
||||
{
|
||||
public:
|
||||
/** Ctor:
|
||||
* @param _p the selective pressure, should be in [1,2] (2 is the default)
|
||||
*/
|
||||
eoFitnessScalingSelect(double _p = 2.0):
|
||||
eoRouletteWorthSelect<EOT, double>(scaling), scaling(_p) {}
|
||||
|
||||
private :
|
||||
eoLinearFitScaling<EOT> scaling; // derived from eoPerf2Worth
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
219
trunk/paradiseo-eo/src/eoFlOrBinOp.h
Normal file
219
trunk/paradiseo-eo/src/eoFlOrBinOp.h
Normal file
|
|
@ -0,0 +1,219 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoFlOrBinOp.h
|
||||
// (c) Marc Schoenauer - Maarten Keijzer 2000-2003
|
||||
/*
|
||||
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: Marc.Schoenauer@inria.fr
|
||||
mkeijzer@cs.vu.nl
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoFlOrBinOp_h
|
||||
#define _eoFlOrBinOp_h
|
||||
|
||||
#include <eoFunctor.h>
|
||||
#include <eoOp.h>
|
||||
|
||||
/** Generic eoBinOps on fixed length genotypes.
|
||||
* Contains exchange crossovers (1pt and uniform)
|
||||
* and crossovers that applies an Atom crossover
|
||||
* to all components with given rate, or
|
||||
* to a fixed prescribed nb of components
|
||||
*
|
||||
* Example: the standard bitstring 1-point and uniform crossovers
|
||||
* could be implemented as resp. eoFlOr1ptBinOp and eoFlOrUniformBinOp
|
||||
*/
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// eoFlOrAllAtomBinOp
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
/** Bin Crossover using an Atom Crossover
|
||||
* that is applied to a ALL components with given rate
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoFlOrAllAtomBinOp : public eoBinOp<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
/** default ctor: requires an Atom BinOp */
|
||||
eoFlOrAllAtomBinOp( eoBinOp<AtomType>& _op, float _rate = 1.0):
|
||||
op(_op), rate( _rate ) {}
|
||||
|
||||
/** applies Atom crossover to ALL components with given rate */
|
||||
bool operator()(EOT & _eo1, const EOT & _eo2)
|
||||
{
|
||||
if (_eo1.size() != _eo2.size())
|
||||
{
|
||||
string s = "Operand size don't match in " + className();
|
||||
throw runtime_error(s);
|
||||
}
|
||||
bool changed = false;
|
||||
for ( unsigned i = 0; i < _eo1.size(); i++ ) {
|
||||
if ( rng.flip( rate ) ) {
|
||||
bool changedHere = op( _eo1[i], _eo2[i] );
|
||||
changed |= changedHere;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** inherited className()*/
|
||||
virtual string className() const { return "eoFlOrAllAtomBinOp"; }
|
||||
|
||||
private:
|
||||
double rate;
|
||||
eoBinOp<AtomType> & op;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// eoFlOrKAtomBinOp
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
/** Bin Crossover using an Atom Crossover
|
||||
* that is applied to a FIXED NB of components
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoFlOrKAtomBinOp : public eoBinOp<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
/** default ctor: requires an Atom BinOp and an unsigned */
|
||||
eoFlOrAtomBinOp( eoBinOp<AtomType>& _op, unsigned _k = 1):
|
||||
op(_op), k( _k ) {}
|
||||
|
||||
/** applies the Atom BinOp to some components */
|
||||
bool operator()(EOT & _eo1, const EOT & _eo2)
|
||||
{
|
||||
if (_eo1.size() != _eo2.size())
|
||||
{
|
||||
string s = "Operand size don't match in " + className();
|
||||
throw runtime_error(s);
|
||||
}
|
||||
|
||||
bool changed = false;
|
||||
for ( unsigned i = 0; i < k; i++ ) // TODO: check that we don't do twice the same
|
||||
{
|
||||
unsigned where = eo::rng.random(_eo1.size());
|
||||
bool changedHere = op( _eo1[where], _eo2[where] );
|
||||
changed |= changedHere;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** inherited className()*/
|
||||
virtual string className() const { return "eoFlOrKAtomBinOp"; }
|
||||
|
||||
private:
|
||||
unsigned k;
|
||||
eoBinOp<AtomType> & op;
|
||||
};
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// eoFlOrUniformBinOp
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
/** The uniform crossover - exchanges atoms uniformly ! */
|
||||
template <class EOT>
|
||||
class eoFlOrUniformBinOp : public eoBinOp<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
/** default ctor: requires a rate - 0.5 by default */
|
||||
eoFlOrUniformBinOp(double _rate=0.5) : eoBinOp<EOT>(_size),
|
||||
rate(_rate) {}
|
||||
|
||||
/** excahnges atoms at given rate */
|
||||
bool operator()(EOT & _eo1, const EOT & _eo2)
|
||||
{
|
||||
unsigned i;
|
||||
Atom tmp;
|
||||
if (_eo1.size() != _eo2.size())
|
||||
{
|
||||
string s = "Operand size don't match in " + className();
|
||||
throw runtime_error(s);
|
||||
}
|
||||
bool hasChanged = false;
|
||||
for (unsigned i=0; i<_eo1.size(); i++)
|
||||
{
|
||||
if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) )
|
||||
{
|
||||
_eo1[i] = _eo2[i];
|
||||
hasChanged = true;
|
||||
}
|
||||
}
|
||||
return hasChanged;
|
||||
}
|
||||
|
||||
/** inherited className()*/
|
||||
virtual string className() const { return "eoFlOrUniformBinOp"; }
|
||||
|
||||
private:
|
||||
double rate;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// eoFlOr1ptBinOp
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
/** The 1pt crossover (just in case someone wants it some day!) */
|
||||
template <class EOT>
|
||||
class eoFlOr1ptBinOp : public eoBinOp<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
/** default ctor: no argument */
|
||||
eoVlUniformBinOp() {}
|
||||
|
||||
/** exchanges first and second parts of the vectors of Atoms */
|
||||
bool operator()(EOT & _eo1, EOT & _eo2)
|
||||
{
|
||||
unsigned i;
|
||||
Atom tmp;
|
||||
if (_eo1.size() != _eo2.size())
|
||||
{
|
||||
string s = "Operand size don't match in " + className();
|
||||
throw runtime_error(s);
|
||||
}
|
||||
bool hasChanged = false;
|
||||
unsigned where = eo::rng.random(_eo1.size()-1);
|
||||
for (unsigned i=where+1; i<_eo1.size(); i++)
|
||||
{
|
||||
if ( (_eo1[i]!=_eo2[i]) )
|
||||
{
|
||||
_eo1[i] = _eo2[i];
|
||||
hasChanged = true;
|
||||
}
|
||||
}
|
||||
return hasChanged;
|
||||
}
|
||||
|
||||
/** inherited className()*/
|
||||
virtual string className() const { return "eoFlOr1ptBinOp"; }
|
||||
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
118
trunk/paradiseo-eo/src/eoFlOrMonOp.h
Normal file
118
trunk/paradiseo-eo/src/eoFlOrMonOp.h
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoFlOrMonOp.h
|
||||
// (c) Marc Schoenauer - Maarten Keijzer 2000-2003
|
||||
/*
|
||||
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: Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@cs.vu.nl
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoFlOrMonOp_h
|
||||
#define _eoFlOrMonOp_h
|
||||
|
||||
#include <eoFunctor.h>
|
||||
#include <eoOp.h>
|
||||
#include <eoInit.h>
|
||||
|
||||
/** Base classes for generic mutations on fixed length chromosomes.
|
||||
* COntains 2 classes that both use an atomic mutation
|
||||
* eoFlOrAllMutation applies the atom mutation to all components with given rate
|
||||
* eoFlOrKMutation applies the atom mutation to a fixed nb of components
|
||||
*
|
||||
* Remark: the standard bit-flip mutation is an eoFlOrAllMutation
|
||||
* with atom mutation == bitflipping
|
||||
*/
|
||||
|
||||
/** applies an atomic mutation to all the components with a given rate
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoFlOrAllMutation : public eoMonOp<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
/** default ctor: requires an Atom mutation and a rate */
|
||||
eoFlOrAllMutation(eoMonOp<AtomType> & _atomMutation, double _rate=1.0) :
|
||||
atomMutation(_atomMutation), rate(_rate) {}
|
||||
|
||||
/** applies the atom mutation to all components with given rate */
|
||||
bool operator()(EOT & _eo)
|
||||
{
|
||||
bool modified=false;
|
||||
for (unsigned i=0; i<_eo.size(); i++)
|
||||
if (eo::rng.flip(rate))
|
||||
if (atomMutation(_eo[i]))
|
||||
modified = true;
|
||||
|
||||
return modified;
|
||||
}
|
||||
|
||||
/** inherited className() */
|
||||
virtual std::string className() const
|
||||
{
|
||||
return "eoFlOrAllMutation(" + atomMutation.className() + ")";
|
||||
}
|
||||
|
||||
private:
|
||||
eoMonOp<AtomType> & atomMutation; // the atom mutation
|
||||
double rate; // the mutation rate PER ATOM
|
||||
};
|
||||
|
||||
/** Applies an atomic mutation to a fixed
|
||||
number of components (1 by default)
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoFlOrKMutation : public eoMonOp<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
/** default ctor: requires an Atom mutation */
|
||||
eoFlOrKMutation(eoMonOp<AtomType> & _atomMutation, unsigned _nb=1) :
|
||||
nb(_nb), atomMutation(_atomMutation) {}
|
||||
|
||||
|
||||
/** applies the atom mutation to K randomly selected components */
|
||||
bool operator()(EOT & _eo)
|
||||
{
|
||||
bool modified=false;
|
||||
for (unsigned k=0; k<nb; k++)
|
||||
{
|
||||
unsigned i = rng.random(_eo.size()); // we don't test for duplicates...
|
||||
if (atomMutation(_eo[i]))
|
||||
modified = true;
|
||||
}
|
||||
return modified;
|
||||
}
|
||||
|
||||
/** inherited className() */
|
||||
virtual std::string className() const
|
||||
{
|
||||
return "eoFlOrKMutation(" + atomMutation.className() + ")";
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned nb; // the number of atoms to mutate
|
||||
eoMonOp<AtomType> & atomMutation; // the atom mutation
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
213
trunk/paradiseo-eo/src/eoFlOrQuadOp.h
Normal file
213
trunk/paradiseo-eo/src/eoFlOrQuadOp.h
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoFlOrQuadOp.h
|
||||
// (c) Marc Schoenauer - Maarten Keijzer 2000-2003
|
||||
/*
|
||||
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: Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@cs.vu.nl
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoFlOrQuadOp_h
|
||||
#define _eoFlOrQuadOp_h
|
||||
|
||||
#include <eoFunctor.h>
|
||||
#include <eoOp.h>
|
||||
|
||||
/** Generic eoQuadOps on fixed length genotypes.
|
||||
* Contains exchange crossovers (1pt and uniform)
|
||||
* and crossovers that applies an Atom crossover
|
||||
* to all components with given rate, or
|
||||
* to a fixed prescribed nb of components
|
||||
*/
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// eoFlOrAllAtomQuadOp
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
/** Quad Crossover using an Atom Crossover
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoFlOrAllAtomQuadOp : public eoQuadOp<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
/** default ctor: requires an Atom QuadOp */
|
||||
eoFlOrAllAtomQuadOp( eoQuadOp<AtomType>& _op, double _rate = 1):
|
||||
op(_op), rate( _rate ) {}
|
||||
|
||||
/** applies Atom crossover to ALL components with given rate */
|
||||
bool operator()(EOT & _eo1, EOT & _eo2)
|
||||
{
|
||||
bool changed = false;
|
||||
for ( unsigned i = 0; i < _eo1.size(); i++ ) {
|
||||
if ( rng.flip( rate ) ) {
|
||||
bool changedHere = op( _eo1[i], _eo2[i] );
|
||||
changed |= changedHere;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** inherited className()*/
|
||||
virtual string className() const { return "eoFlOrAllAtomQuadOp"; }
|
||||
|
||||
private:
|
||||
double rate;
|
||||
eoQuadOp<AtomType> & op;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// eoFlOrKAtomQuadOp
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
/** Quad Crossover using an Atom Crossover
|
||||
* that is applied to a FIXED NB of components
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoFlOrKAtomQuadOp : public eoQuadOp<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
/** default ctor: requires an Atom QuadOp and an unsigned */
|
||||
eoFlOrAtomQuadOp( eoQuadOp<AtomType>& _op, unsigned _k = 1):
|
||||
op(_op), k( _k ) {}
|
||||
|
||||
/** applies the Atom QuadOp to some components */
|
||||
bool operator()(EOT & _eo1, const EOT & _eo2)
|
||||
{
|
||||
if (_eo1.size() != _eo2.size())
|
||||
{
|
||||
string s = "Operand size don't match in " + className();
|
||||
throw runtime_error(s);
|
||||
}
|
||||
|
||||
bool changed = false;
|
||||
for ( unsigned i = 0; i < k; i++ ) // TODO: check that we don't do twice the same
|
||||
{
|
||||
unsigned where = eo::rng.random(_eo1.size());
|
||||
bool changedHere = op( _eo1[where], _eo2[where] );
|
||||
changed |= changedHere;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
/** inherited className()*/
|
||||
virtual string className() const { return "eoFlOrKAtomQuadOp"; }
|
||||
|
||||
private:
|
||||
unsigned k;
|
||||
eoQuadOp<AtomType> & op;
|
||||
};
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// eoFlOrUniformQuadOp
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
/** The uniform crossover - exchanges atoms uniformly ! */
|
||||
template <class EOT>
|
||||
class eoFlOrUniformQuadOp : public eoQuadOp<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
/** default ctor: requires a rate - 0.5 by default */
|
||||
eoVlUniformQuadOp(double _rate=0.5) : eoQuadOp<EOT>(_size),
|
||||
rate(_rate) {}
|
||||
|
||||
/** excahnges atoms at given rate */
|
||||
bool operator()(EOT & _eo1, EOT & _eo2)
|
||||
{
|
||||
unsigned i;
|
||||
Atom tmp;
|
||||
if (_eo1.size() != _eo2.size())
|
||||
{
|
||||
string s = "Operand size don't match in " + className();
|
||||
throw runtime_error(s);
|
||||
}
|
||||
bool hasChanged = false;
|
||||
for (unsigned i=0; i<_eo1.size(); i++)
|
||||
{
|
||||
if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) )
|
||||
{
|
||||
tmp = _eo1[i];
|
||||
_eo1[i] = _eo2[i];
|
||||
_eo2[i] = tmp;
|
||||
hasChanged = true;
|
||||
}
|
||||
}
|
||||
return hasChanged;
|
||||
}
|
||||
|
||||
/** inherited className()*/
|
||||
virtual string className() const { return "eoFlOrUniformQuadOp"; }
|
||||
|
||||
private:
|
||||
double rate;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// eoFlOr1ptQuadOp
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
/** The 1pt crossover (just in case someone wants it some day!) */
|
||||
template <class EOT>
|
||||
class eoFlOr1ptQuadOp : public eoQuadOp<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
/** default ctor: no argument */
|
||||
eoVlUniformQuadOp() {}
|
||||
|
||||
/** exchanges first and second parts of the vectors of Atoms */
|
||||
bool operator()(EOT & _eo1, EOT & _eo2)
|
||||
{
|
||||
unsigned i;
|
||||
Atom tmp;
|
||||
if (_eo1.size() != _eo2.size())
|
||||
{
|
||||
string s = "Operand size don't match in " + className();
|
||||
throw runtime_error(s);
|
||||
}
|
||||
bool hasChanged = false;
|
||||
unsigned where = eo::rng.random(_eo1.size()-1);
|
||||
for (unsigned i=where+1; i<_eo1.size(); i++)
|
||||
{
|
||||
if ( (_eo1[i]!=_eo2[i]) )
|
||||
{
|
||||
tmp = _eo1[i];
|
||||
_eo1[i] = _eo2[i];
|
||||
_eo2[i] = tmp;
|
||||
hasChanged = true;
|
||||
}
|
||||
}
|
||||
return hasChanged;
|
||||
}
|
||||
|
||||
/** inherited className()*/
|
||||
virtual string className() const { return "eoFlOr1ptQuadOp"; }
|
||||
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
177
trunk/paradiseo-eo/src/eoFunctor.h
Normal file
177
trunk/paradiseo-eo/src/eoFunctor.h
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
// -*- 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
|
||||
CVS Info: $Date: 2004/12/01 09:22:48 $ $Header: /cvsroot/eodev/eo/src/eoFunctor.h,v 1.7 2004/12/01 09:22:48 evomarc Exp $ $Author: evomarc $
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoFunctor_h
|
||||
#define _eoFunctor_h
|
||||
|
||||
#include <functional>
|
||||
|
||||
/** Base class for functors to get a nice hierarchy diagram
|
||||
|
||||
That's actually quite an understatement as it does quite a bit more than
|
||||
just that. By having all functors derive from the same base class, we can
|
||||
do some memory management that would otherwise be very hard.
|
||||
|
||||
The memory management base class is called eoFunctorStore, and it supports
|
||||
a member add() to add a pointer to a functor. When the functorStore is
|
||||
destroyed, it will delete all those pointers. So beware: do not delete
|
||||
the functorStore before you are done with anything that might have been allocated.
|
||||
|
||||
@see eoFunctorStore
|
||||
|
||||
*/
|
||||
class eoFunctorBase
|
||||
{
|
||||
public :
|
||||
/// virtual dtor here so there is no need to define it in derived classes
|
||||
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 Function. 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 eoF : public eoFunctorBase
|
||||
{
|
||||
public :
|
||||
|
||||
/// virtual dtor here so there is no need to define it in derived classes
|
||||
virtual ~eoF() {}
|
||||
|
||||
/// the return type - probably useless ....
|
||||
typedef R result_type;
|
||||
|
||||
/// The pure virtual function that needs to be implemented by the subclass
|
||||
virtual R operator()() = 0;
|
||||
|
||||
/// tag to identify a procedure in compile time function selection @see functor_category
|
||||
static eoFunctorBase::procedure_tag functor_category()
|
||||
{
|
||||
return eoFunctorBase::procedure_tag();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
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 eoF<R>&)
|
||||
{
|
||||
return eoFunctorBase::procedure_tag();
|
||||
}
|
||||
|
||||
/**
|
||||
Basic Unary Functor. Derive from this class when defining
|
||||
any unary function. First template argument is the first_argument_type,
|
||||
second result_type.
|
||||
Argument and result types can be any type including void for
|
||||
result_type
|
||||
**/
|
||||
template <class A1, class R>
|
||||
class eoUF : public eoFunctorBase, public std::unary_function<A1, R>
|
||||
{
|
||||
public :
|
||||
|
||||
/// virtual dtor here so there is no need to define it in derived classes
|
||||
virtual ~eoUF() {}
|
||||
|
||||
/// The pure virtual function that needs to be implemented by the subclass
|
||||
virtual R operator()(A1) = 0;
|
||||
|
||||
/// tag to identify a procedure in compile time function selection @see functor_category
|
||||
static eoFunctorBase::unary_function_tag functor_category()
|
||||
{
|
||||
return eoFunctorBase::unary_function_tag();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
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 eoUF<A1, R>&)
|
||||
{
|
||||
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 A1, class A2, class R>
|
||||
class eoBF : public eoFunctorBase, public std::binary_function<A1, A2, R>
|
||||
{
|
||||
public :
|
||||
/// virtual dtor here so there is no need to define it in derived classes
|
||||
virtual ~eoBF() {}
|
||||
|
||||
//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;
|
||||
|
||||
/// tag to identify a procedure in compile time function selection @see functor_category
|
||||
static eoFunctorBase::binary_function_tag functor_category()
|
||||
{
|
||||
return eoFunctorBase::binary_function_tag();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
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 eoBF<A1, A2, R>&)
|
||||
{
|
||||
return eoFunctorBase::binary_function_tag();
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
16
trunk/paradiseo-eo/src/eoFunctorStore.cpp
Normal file
16
trunk/paradiseo-eo/src/eoFunctorStore.cpp
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <eoFunctorStore.h>
|
||||
#include <eoFunctor.h>
|
||||
|
||||
|
||||
/// clears the memory
|
||||
eoFunctorStore::~eoFunctorStore()
|
||||
{
|
||||
for(size_t i = 0; i < vec.size(); ++i) {
|
||||
delete vec[i];
|
||||
}
|
||||
}
|
||||
70
trunk/paradiseo-eo/src/eoFunctorStore.h
Normal file
70
trunk/paradiseo-eo/src/eoFunctorStore.h
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
// -*- 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:
|
||||
|
||||
/// Default Ctor
|
||||
eoFunctorStore() {}
|
||||
|
||||
// virtual destructor so we don't need to define it in derived classes
|
||||
virtual ~eoFunctorStore();
|
||||
|
||||
/// Add an eoFunctorBase to the store
|
||||
template <class Functor>
|
||||
Functor& storeFunctor(Functor* r)
|
||||
{
|
||||
// If the compiler complains about the following line,
|
||||
// check if you really are giving it a pointer to an
|
||||
// eoFunctorBase derived object
|
||||
vec.push_back(r);
|
||||
return *r;
|
||||
}
|
||||
|
||||
private :
|
||||
|
||||
/// no copying allowed
|
||||
eoFunctorStore(const eoFunctorStore&);
|
||||
|
||||
/// no copying allowed
|
||||
eoFunctorStore operator=(const eoFunctorStore&);
|
||||
std::vector<eoFunctorBase*> vec;
|
||||
};
|
||||
|
||||
#endif
|
||||
86
trunk/paradiseo-eo/src/eoG3Replacement.h
Normal file
86
trunk/paradiseo-eo/src/eoG3Replacement.h
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoG3Replacement.h
|
||||
(c) Maarten Keijzer, Marc Schoenauer, 2002
|
||||
|
||||
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: Marc.Schoenauer@inria.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoG3Replacement_h
|
||||
#define _eoG3Replacement_h
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoPop.h>
|
||||
#include <eoFunctor.h>
|
||||
#include <eoMerge.h>
|
||||
#include <eoReduce.h>
|
||||
#include <utils/eoHowMany.h>
|
||||
#include <eoReduceSplit.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
eoG3Replacement is an eoReplacement:
|
||||
- no strong elitism (is suppposed to be within a steady-state engine)
|
||||
- choose N (2) parents RANDOMLY - remove them from the parent population
|
||||
- merge offspring and the N removed parents
|
||||
- select best N of this merged population
|
||||
- put them back into parent population
|
||||
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoG3Replacement : public eoReplacement<EOT>
|
||||
{
|
||||
public:
|
||||
eoG3Replacement(eoHowMany _howManyEliminatedParents = eoHowMany(2, false)) :
|
||||
// split truncates the parents and returns eliminated parents
|
||||
split(_howManyEliminatedParents, true),
|
||||
// reduce truncates the offpsring and does not return eliminated guys
|
||||
reduce(-_howManyEliminatedParents, false)
|
||||
{}
|
||||
|
||||
void operator()(eoPop<EOT> & _parents, eoPop<EOT> & _offspring)
|
||||
{
|
||||
eoPop<EOT> temp;
|
||||
split(_parents, temp);
|
||||
unsigned toKeep = temp.size(); // how many to keep from merged populations
|
||||
// merge temp into offspring
|
||||
plus(temp, _offspring); // add temp to _offspring (a little inconsistent!)
|
||||
|
||||
// reduce merged
|
||||
reduce(_offspring, temp); // temp dummy arg. will not be modified
|
||||
// minimla check:
|
||||
if (_offspring.size() != toKeep)
|
||||
{
|
||||
std::cerr << "Les tailles " << _offspring.size() << " " << toKeep << std::endl;
|
||||
throw std::runtime_error("eoG3Replacement: wrong number of remaining offspring");
|
||||
}
|
||||
// and put back into _parents
|
||||
plus(_offspring, _parents);
|
||||
}
|
||||
|
||||
private:
|
||||
eoLinearTruncateSplit<EOT> split; // few parents to truncate -> linear
|
||||
eoTruncateSplit<EOT> reduce; // supposedly many offspring to truncate
|
||||
eoPlus<EOT> plus;
|
||||
};
|
||||
|
||||
#endif
|
||||
103
trunk/paradiseo-eo/src/eoGenContinue.h
Normal file
103
trunk/paradiseo-eo/src/eoGenContinue.h
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
// -*- 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>
|
||||
#include <utils/eoParam.h>
|
||||
/**
|
||||
Generational continuator: continues until a number of generations is reached
|
||||
*/
|
||||
template< class EOT>
|
||||
class eoGenContinue: public eoContinue<EOT>, public eoValueParam<unsigned>
|
||||
{
|
||||
public:
|
||||
|
||||
/// Ctor for setting a
|
||||
eoGenContinue( unsigned long _totalGens)
|
||||
: eoValueParam<unsigned>(0, "Generations", "Generations"),
|
||||
repTotalGenerations( _totalGens ),
|
||||
thisGenerationPlaceHolder(0),
|
||||
thisGeneration(thisGenerationPlaceHolder), verbose(true) {};
|
||||
|
||||
/// Ctor for enabling the save/load the no. of generations counted
|
||||
eoGenContinue( unsigned long _totalGens, unsigned long& _currentGen)
|
||||
: eoValueParam<unsigned>(0, "Generations", "Generations"),
|
||||
repTotalGenerations( _totalGens ),
|
||||
thisGenerationPlaceHolder(0),
|
||||
thisGeneration(_currentGen), verbose(true){};
|
||||
|
||||
/** Returns false when a certain number of generations is
|
||||
* reached */
|
||||
virtual bool operator() ( const eoPop<EOT>& _vEO ) {
|
||||
thisGeneration++;
|
||||
value() = thisGeneration;
|
||||
// std::cout << " [" << thisGeneration << "] ";
|
||||
if (thisGeneration >= repTotalGenerations)
|
||||
{
|
||||
if (verbose)
|
||||
std::cout << "STOP in eoGenContinue: Reached maximum number of generations [" << thisGeneration << "/" << repTotalGenerations << "]\n";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Sets the number of generations to reach
|
||||
and sets the current generation to 0 (the begin)*/
|
||||
virtual void totalGenerations( unsigned long _tg ) {
|
||||
repTotalGenerations = _tg;
|
||||
thisGeneration = 0;
|
||||
};
|
||||
|
||||
/** Returns the number of generations to reach*/
|
||||
virtual unsigned long totalGenerations( )
|
||||
{
|
||||
return repTotalGenerations;
|
||||
};
|
||||
|
||||
|
||||
virtual std::string className(void) const { return "eoGenContinue"; }
|
||||
|
||||
void readFrom (std :: istream & __is) {
|
||||
|
||||
__is >> thisGeneration; /* Loading the number of generations counted */
|
||||
}
|
||||
|
||||
void printOn (std :: ostream & __os) const {
|
||||
|
||||
__os << thisGeneration << std :: endl; /* Saving the number of generations counted */
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned long repTotalGenerations;
|
||||
unsigned long thisGenerationPlaceHolder;
|
||||
unsigned long& thisGeneration;
|
||||
|
||||
public:
|
||||
bool verbose; // allows to turn off annoying message to cout
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
224
trunk/paradiseo-eo/src/eoGenOp.h
Normal file
224
trunk/paradiseo-eo/src/eoGenOp.h
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoGenOp.h
|
||||
// (c) Maarten Keijzer and Marc Schoenauer, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: mak@dhi.dk
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoGenOp_H
|
||||
#define _eoGenOp_H
|
||||
|
||||
#include <eoOp.h>
|
||||
#include <eoPopulator.h>
|
||||
#include <eoFunctorStore.h>
|
||||
#include <assert.h>
|
||||
|
||||
/** @name General variation operators
|
||||
|
||||
a class that allows to use i->j operators for any i and j
|
||||
thanks to the friend class eoPopulator
|
||||
|
||||
@author Maarten Keijzer
|
||||
@version 0.0
|
||||
*/
|
||||
|
||||
//@{
|
||||
|
||||
/** The base class for General Operators
|
||||
Subclass this operator is you want to define an operator that falls
|
||||
outside of the eoMonOp, eoBinOp, eoQuadOp classification. The argument
|
||||
the operator will receive is an eoPopulator, which is a wrapper around
|
||||
the original population, is an instantiation of the next population and
|
||||
has often a selection function embedded in it to select new individuals.
|
||||
|
||||
Note that the actual work is performed in the apply function.
|
||||
AND that the apply function is responsible for invalidating
|
||||
the object if necessary
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoGenOp : public eoOp<EOT>, public eoUF<eoPopulator<EOT> &, void>
|
||||
{
|
||||
public :
|
||||
/// Ctor that honors its superclass
|
||||
eoGenOp(): eoOp<EOT>( eoOp<EOT>::general ) {}
|
||||
|
||||
/** Max production is used to reserve space for all elements that are used by the operator,
|
||||
not setting it properly can result in a crash
|
||||
*/
|
||||
virtual unsigned max_production(void) = 0;
|
||||
|
||||
virtual std::string className() const = 0;
|
||||
void operator()(eoPopulator<EOT>& _pop)
|
||||
{
|
||||
_pop.reserve(max_production());
|
||||
apply(_pop);
|
||||
}
|
||||
|
||||
|
||||
protected :
|
||||
/** the function that will do the work
|
||||
*/
|
||||
virtual void apply(eoPopulator<EOT>& _pop) = 0;
|
||||
};
|
||||
|
||||
|
||||
/** Wrapper for eoMonOp */
|
||||
template <class EOT>
|
||||
class eoMonGenOp : public eoGenOp<EOT>
|
||||
{
|
||||
public:
|
||||
eoMonGenOp(eoMonOp<EOT>& _op) : op(_op) {}
|
||||
|
||||
unsigned max_production(void) { return 1; }
|
||||
|
||||
void apply(eoPopulator<EOT>& _it)
|
||||
{
|
||||
if (op(*_it))
|
||||
(*_it).invalidate(); // look how simple
|
||||
|
||||
}
|
||||
virtual std::string className() const {return op.className();}
|
||||
private :
|
||||
eoMonOp<EOT>& op;
|
||||
};
|
||||
|
||||
/** Wrapper for binop: here we use select method of eoPopulator
|
||||
* but we could also have an embedded selector to select the second parent
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoBinGenOp : public eoGenOp<EOT>
|
||||
{
|
||||
public:
|
||||
eoBinGenOp(eoBinOp<EOT>& _op) : op(_op) {}
|
||||
|
||||
unsigned max_production(void) { return 1; }
|
||||
|
||||
/** do the work: get 2 individuals from the population, modifies
|
||||
only one (it's a eoBinOp)
|
||||
*/
|
||||
void apply(eoPopulator<EOT>& _pop)
|
||||
{
|
||||
EOT& a = *_pop;
|
||||
const EOT& b = _pop.select();
|
||||
|
||||
if (op(a, b))
|
||||
a.invalidate();
|
||||
}
|
||||
virtual std::string className() const {return op.className();}
|
||||
|
||||
private :
|
||||
eoBinOp<EOT>& op;
|
||||
};
|
||||
|
||||
/** wrapper for eoBinOp with a selector */
|
||||
template <class EOT>
|
||||
class eoSelBinGenOp : public eoGenOp<EOT>
|
||||
{
|
||||
public:
|
||||
eoSelBinGenOp(eoBinOp<EOT>& _op, eoSelectOne<EOT>& _sel) :
|
||||
op(_op), sel(_sel) {}
|
||||
|
||||
unsigned max_production(void) { return 1; }
|
||||
|
||||
void apply(eoPopulator<EOT>& _pop)
|
||||
{ // _pop.source() gets the original population, an eoVecOp can make use of this as well
|
||||
if (op(*_pop, sel(_pop.source())))
|
||||
(*_pop).invalidate();
|
||||
}
|
||||
virtual std::string className() const {return op.className();}
|
||||
|
||||
private :
|
||||
eoBinOp<EOT>& op;
|
||||
eoSelectOne<EOT>& sel;
|
||||
};
|
||||
|
||||
|
||||
/** Wrapper for quadop: easy as pie
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoQuadGenOp : public eoGenOp<EOT>
|
||||
{
|
||||
public:
|
||||
eoQuadGenOp(eoQuadOp<EOT>& _op) : op(_op) {}
|
||||
|
||||
unsigned max_production(void) { return 2; }
|
||||
|
||||
void apply(eoPopulator<EOT>& _pop)
|
||||
{
|
||||
EOT& a = *_pop;
|
||||
EOT& b = *++_pop;
|
||||
|
||||
|
||||
if(op(a, b))
|
||||
{
|
||||
a.invalidate();
|
||||
b.invalidate();
|
||||
}
|
||||
|
||||
}
|
||||
virtual std::string className() const {return op.className();}
|
||||
|
||||
private :
|
||||
eoQuadOp<EOT>& op;
|
||||
};
|
||||
|
||||
/**
|
||||
Factory function for automagically creating references to an
|
||||
eoGenOp object. Useful when you are too lazy to figure out
|
||||
which wrapper belongs to which operator. The memory allocated
|
||||
in the wrapper will be stored in a eoFunctorStore (eoState derives from this).
|
||||
Therefore the memory will only be freed when the eoFunctorStore is deleted.
|
||||
Make very sure that you are not using these wrappers after this happens.
|
||||
|
||||
You can use this function 'wrap_op' in the following way. Suppose you've
|
||||
created an eoQuadOp<EOT> called my_quad, and you want to feed it to an eoTransform
|
||||
derived class that expects an eoGenOp<EOT>. If you have an eoState lying around
|
||||
(which is generally a good idea) you can say:
|
||||
|
||||
eoDerivedTransform<EOT> trans(eoGenOp<EOT>::wrap_op(my_quad, state), ...);
|
||||
|
||||
And as long as your state is not destroyed (by going out of scope for example,
|
||||
your 'trans' functor will be usefull.
|
||||
|
||||
As a final note, you can also enter an eoGenOp as the argument. It will
|
||||
not allocate memory then. This to make it even easier to use the wrap_op function.
|
||||
For an example of how this is used, check the eoOpContainer class.
|
||||
|
||||
@see eoOpContainer
|
||||
*/
|
||||
template <class EOT>
|
||||
eoGenOp<EOT>& wrap_op(eoOp<EOT>& _op, eoFunctorStore& _store)
|
||||
{
|
||||
switch(_op.getType())
|
||||
{
|
||||
case eoOp<EOT>::unary : return _store.storeFunctor(new eoMonGenOp<EOT>(static_cast<eoMonOp<EOT>&>(_op)));
|
||||
case eoOp<EOT>::binary : return _store.storeFunctor(new eoBinGenOp<EOT>(static_cast<eoBinOp<EOT>&>(_op)));
|
||||
case eoOp<EOT>::quadratic : return _store.storeFunctor(new eoQuadGenOp<EOT>(static_cast<eoQuadOp<EOT>&>(_op)));
|
||||
case eoOp<EOT>::general : return static_cast<eoGenOp<EOT>&>(_op);
|
||||
}
|
||||
|
||||
assert(false);
|
||||
return static_cast<eoGenOp<EOT>&>(_op);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
//@}
|
||||
106
trunk/paradiseo-eo/src/eoGeneralBreeder.h
Normal file
106
trunk/paradiseo-eo/src/eoGeneralBreeder.h
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoGeneralBreeder.h
|
||||
// (c) Maarten Keijzer and Marc Schoenauer, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: mkeijzer@dhi.dk
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoGeneralBreeder_h
|
||||
#define eoGeneralBreeder_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/*****************************************************************************
|
||||
* eoGeneralBreeder: transforms a population using the generalOp construct.
|
||||
*****************************************************************************/
|
||||
|
||||
#include <eoOp.h>
|
||||
#include <eoGenOp.h>
|
||||
#include <eoPopulator.h>
|
||||
#include <eoSelectOne.h>
|
||||
#include <eoBreed.h>
|
||||
#include <utils/eoHowMany.h>
|
||||
|
||||
/**
|
||||
Base class for breeders using generalized operators.
|
||||
*/
|
||||
template<class EOT>
|
||||
class eoGeneralBreeder: public eoBreed<EOT>
|
||||
{
|
||||
public:
|
||||
/** Ctor:
|
||||
*
|
||||
* @param _select a selectoOne, to be used for all selections
|
||||
* @param _op a general operator (will generally be an eoOpContainer)
|
||||
* @param _rate pour howMany, le nbre d'enfants a generer
|
||||
* @param _interpret_as_rate <a href="../../tutorial/html/eoEngine.html#howmany">explanation</a>
|
||||
*/
|
||||
eoGeneralBreeder(
|
||||
eoSelectOne<EOT>& _select,
|
||||
eoGenOp<EOT>& _op,
|
||||
double _rate=1.0,
|
||||
bool _interpret_as_rate = true) :
|
||||
select( _select ), op(_op), howMany(_rate, _interpret_as_rate) {}
|
||||
|
||||
/** Ctor:
|
||||
*
|
||||
* @param _select a selectoOne, to be used for all selections
|
||||
* @param _op a general operator (will generally be an eoOpContainer)
|
||||
* @param _howMany an eoHowMany <a href="../../tutorial/html/eoEngine.html#howmany">explanation</a>
|
||||
*/
|
||||
eoGeneralBreeder(
|
||||
eoSelectOne<EOT>& _select,
|
||||
eoGenOp<EOT>& _op,
|
||||
eoHowMany _howMany ) :
|
||||
select( _select ), op(_op), howMany(_howMany) {}
|
||||
|
||||
/** The breeder: simply calls the genOp on a selective populator!
|
||||
*
|
||||
* @param _parents the initial population
|
||||
* @param _offspring the resulting population (content -if any- is lost)
|
||||
*/
|
||||
void operator()(const eoPop<EOT>& _parents, eoPop<EOT>& _offspring)
|
||||
{
|
||||
unsigned target = howMany(_parents.size());
|
||||
|
||||
_offspring.clear();
|
||||
eoSelectivePopulator<EOT> it(_parents, _offspring, select);
|
||||
|
||||
while (_offspring.size() < target)
|
||||
{
|
||||
op(it);
|
||||
++it;
|
||||
}
|
||||
|
||||
_offspring.resize(target); // you might have generated a few more
|
||||
}
|
||||
|
||||
/// The class name.
|
||||
virtual std::string className() const { return "eoGeneralBreeder"; }
|
||||
|
||||
private:
|
||||
eoSelectOne<EOT>& select;
|
||||
eoGenOp<EOT>& op;
|
||||
eoHowMany howMany;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
172
trunk/paradiseo-eo/src/eoInit.h
Normal file
172
trunk/paradiseo-eo/src/eoInit.h
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoInit.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 _eoInit_H
|
||||
#define _eoInit_H
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include <eoOp.h>
|
||||
#include <eoSTLFunctor.h>
|
||||
#include <utils/eoRndGenerators.h>
|
||||
|
||||
/**
|
||||
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 : public eoUF<EOT&, void>
|
||||
{
|
||||
public:
|
||||
|
||||
/** className: Mandatory because of eoCombinedInit.
|
||||
SHould be pure virtual, but then we should go over the whole
|
||||
* code to write the method for all derived classes ... MS 16/7/04 */
|
||||
virtual std::string className(void) const { return "eoInit"; }
|
||||
};
|
||||
|
||||
/** turning an eoInit into a generator
|
||||
* probably we should only use genrators - and suppress eoInit ???
|
||||
* MS - July 2001
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoInitGenerator : public eoF<EOT>
|
||||
{
|
||||
public:
|
||||
|
||||
/** Ctor from a plain eoInit */
|
||||
eoInitGenerator(eoInit<EOT> & _init):init(_init) {}
|
||||
|
||||
virtual EOT operator()()
|
||||
{
|
||||
EOT p;
|
||||
init(p);
|
||||
return (p);
|
||||
}
|
||||
private:
|
||||
eoInit<EOT> & init;
|
||||
};
|
||||
|
||||
/**
|
||||
Initializer for fixed length representations with a single type
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoInitFixedLength: public eoInit<EOT>
|
||||
{
|
||||
public:
|
||||
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
eoInitFixedLength(unsigned _combien, eoRndGenerator<AtomType>& _generator)
|
||||
: combien(_combien), generator(_generator) {}
|
||||
|
||||
virtual void operator()(EOT& chrom)
|
||||
{
|
||||
chrom.resize(combien);
|
||||
std::generate(chrom.begin(), chrom.end(), generator);
|
||||
chrom.invalidate();
|
||||
}
|
||||
|
||||
private :
|
||||
unsigned combien;
|
||||
/// generic wrapper for eoFunctor (s), to make them have the function-pointer style copy semantics
|
||||
eoSTLF<AtomType> generator;
|
||||
};
|
||||
|
||||
/**
|
||||
Initializer for variable length representations with a single type
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoInitVariableLength: public eoInit<EOT>
|
||||
{
|
||||
public:
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
// /** Ctor from a generator */
|
||||
// eoInitVariableLength(unsigned _minSize, unsigned _maxSize, eoF<typename EOT::AtomType> & _generator = Gen())
|
||||
// : offset(_minSize), extent(_maxSize - _minSize),
|
||||
// repGenerator( eoInitGenerator<typename EOT::AtomType>(*(new eoInit<EOT>)) ),
|
||||
// generator(_generator)
|
||||
// {
|
||||
// if (_minSize >= _maxSize)
|
||||
// throw std::logic_error("eoInitVariableLength: minSize larger or equal to maxSize");
|
||||
// }
|
||||
|
||||
/** Ctor from an eoInit */
|
||||
eoInitVariableLength(unsigned _minSize, unsigned _maxSize, eoInit<AtomType> & _init)
|
||||
: offset(_minSize), extent(_maxSize - _minSize), init(_init)
|
||||
{
|
||||
if (_minSize >= _maxSize)
|
||||
throw std::logic_error("eoInitVariableLength: minSize larger or equal to maxSize");
|
||||
}
|
||||
|
||||
|
||||
virtual void operator()(EOT& _chrom)
|
||||
{
|
||||
_chrom.resize(offset + rng.random(extent));
|
||||
typename std::vector<AtomType>::iterator it;
|
||||
for (it=_chrom.begin(); it<_chrom.end(); it++)
|
||||
init(*it);
|
||||
_chrom.invalidate();
|
||||
}
|
||||
|
||||
// accessor to the atom initializer (needed by operator constructs sometimes)
|
||||
eoInit<AtomType> & atomInit() {return init;}
|
||||
|
||||
private :
|
||||
unsigned offset;
|
||||
unsigned extent;
|
||||
eoInit<AtomType> & init;
|
||||
};
|
||||
|
||||
/**
|
||||
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) {}
|
||||
|
||||
bool operator()(EOT& _eot)
|
||||
{
|
||||
init(_eot);
|
||||
return true;
|
||||
}
|
||||
private :
|
||||
|
||||
eoInit<EOT>& init;
|
||||
};
|
||||
|
||||
#endif
|
||||
134
trunk/paradiseo-eo/src/eoInvalidateOps.h
Normal file
134
trunk/paradiseo-eo/src/eoInvalidateOps.h
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoInvalidateOps.h
|
||||
// (c) Maarten Keijzer 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mak@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoInvalidateOps_h
|
||||
#define _eoInvalidateOps_h
|
||||
|
||||
#include <eoOp.h>
|
||||
|
||||
/**
|
||||
One of the invalidator operators. Use this one as a 'hat' on an operator
|
||||
that is defined to work on a generic datatype. This functor will then check
|
||||
the return type of the operator and invalidate the fitness of the individual.
|
||||
|
||||
This functor is used in algorithms that work with straight eoMonOp, eoBinOp
|
||||
or eoQuadOp operators, for instance eoSGA. Note that eoGenOp derived operators
|
||||
generally do invalidate the fitness of the objects they have changed.
|
||||
|
||||
Return value means "Has_Changed" and not "Needs_To_Be_Invalidated"
|
||||
as successive invalidation are not really a problem
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoInvalidateMonOp : public eoMonOp<EOT>
|
||||
{
|
||||
public:
|
||||
eoInvalidateMonOp(eoMonOp<EOT>& _op) : op(_op) {}
|
||||
|
||||
bool operator()(EOT& _eo)
|
||||
{
|
||||
if (op(_eo))
|
||||
{
|
||||
_eo.invalidate();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
eoMonOp<EOT>& op;
|
||||
};
|
||||
|
||||
/**
|
||||
One of the invalidator operators. Use this one as a 'hat' on an operator
|
||||
that is defined to work on a generic datatype. This functor will then check
|
||||
the return type of the operator and invalidate the fitness of the individual.
|
||||
|
||||
This functor is used in algorithms that work with straight eoMonOp, eoBinOp
|
||||
or eoQuadOp operators, for instance eoSGA. Note that eoGenOp derived operators
|
||||
generally do invalidate the fitness of the objects they have changed.
|
||||
|
||||
Return value means "Has_Changed" and not "Needs_To_Be_Invalidated"
|
||||
as successive invalidation are not really a problem
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoInvalidateBinOp : public eoBinOp<EOT>
|
||||
{
|
||||
public:
|
||||
eoInvalidateBinOp(eoBinOp<EOT>& _op) : op(_op) {}
|
||||
|
||||
bool operator()(EOT& _eo, const EOT& _eo2)
|
||||
{
|
||||
if (op(_eo, _eo2))
|
||||
{
|
||||
_eo.invalidate();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
eoBinOp<EOT>& op;
|
||||
};
|
||||
|
||||
/**
|
||||
One of the invalidator operators. Use this one as a 'hat' on an operator
|
||||
that is defined to work on a generic datatype. This functor will then check
|
||||
the return type of the operator and invalidate the fitness of the individual.
|
||||
|
||||
This functor is used in algorithms that work with straight eoMonOp, eoBinOp
|
||||
or eoQuadOp operators, for instance eoSGA. Note that eoGenOp derived operators
|
||||
generally do invalidate the fitness of the objects they have changed.
|
||||
|
||||
Return value means "Has_Changed" and not "Needs_To_Be_Invalidated"
|
||||
as successive invalidation are not really a problem
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoInvalidateQuadOp : public eoQuadOp<EOT>
|
||||
{
|
||||
public:
|
||||
eoInvalidateQuadOp(eoQuadOp<EOT>& _op) : op(_op) {}
|
||||
|
||||
bool operator()(EOT& _eo1, EOT& _eo2)
|
||||
{
|
||||
if (op(_eo1, _eo2))
|
||||
{
|
||||
_eo1.invalidate();
|
||||
_eo2.invalidate();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
eoQuadOp<EOT>& op;
|
||||
};
|
||||
|
||||
#endif
|
||||
92
trunk/paradiseo-eo/src/eoLinearFitScaling.h
Normal file
92
trunk/paradiseo-eo/src/eoLinearFitScaling.h
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoLinearFitScaling.h
|
||||
(c) GeNeura Team, 1998, Maarten Keijzer, Marc Schoenauer, 2001
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoLinearFitScaling_h
|
||||
#define eoLinearFitScaling_h
|
||||
|
||||
#include <eoSelectFromWorth.h>
|
||||
#include <eoPerf2Worth.h>
|
||||
|
||||
/** An instance of eoPerf2Worth
|
||||
* COmputes the linearly scaled fitnesses
|
||||
* with given selective pressure
|
||||
* Pselect(Best) == pressure/sizePop
|
||||
* Pselect(average) == 1.0/sizePop
|
||||
* truncate negative values to 0 -
|
||||
*
|
||||
* to be used within an eoSelectFromWorth object
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoLinearFitScaling : public eoPerf2Worth<EOT> // false: do not cache fitness
|
||||
{
|
||||
public:
|
||||
|
||||
using eoPerf2Worth<EOT>::value;
|
||||
|
||||
/* Ctor:
|
||||
@param _p selective pressure (in (1,2])
|
||||
@param _e exponent (1 == linear)
|
||||
*/
|
||||
eoLinearFitScaling(double _p=2.0)
|
||||
: pressure(_p) {}
|
||||
|
||||
/* COmputes the ranked fitness: fitnesses range in [m,M]
|
||||
with m=2-pressure/popSize and M=pressure/popSize.
|
||||
in between, the progression depends on exponent (linear if 1).
|
||||
*/
|
||||
virtual void operator()(const eoPop<EOT>& _pop) {
|
||||
unsigned pSize =_pop.size();
|
||||
// value() refers to the vector of worthes (we're in an eoParamvalue)
|
||||
value().resize(pSize);
|
||||
|
||||
// best and worse fitnesses
|
||||
double bestFitness = static_cast<double> (_pop.best_element().fitness());
|
||||
// double worstFitness = static_cast<double> (_pop.worse_element().fitness());
|
||||
|
||||
// average fitness
|
||||
double sum=0.0;
|
||||
unsigned i;
|
||||
for (i=0; i<pSize; i++)
|
||||
sum += static_cast<double>(_pop[i].fitness());
|
||||
double averageFitness = sum/pSize;
|
||||
|
||||
// the coefficients for linear scaling
|
||||
double denom = pSize*(bestFitness - averageFitness);
|
||||
double alpha = (pressure-1)/denom;
|
||||
double beta = (bestFitness - pressure*averageFitness)/denom;
|
||||
|
||||
for (i=0; i<pSize; i++) { // truncate to 0
|
||||
value()[i] = std::max(alpha*_pop[i].fitness()+beta, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
double pressure; // selective pressure
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
103
trunk/paradiseo-eo/src/eoMGGReplacement.h
Normal file
103
trunk/paradiseo-eo/src/eoMGGReplacement.h
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoMGGReplacement.h
|
||||
(c) Maarten Keijzer, Marc Schoenauer, 2002
|
||||
|
||||
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: Marc.Schoenauer@inria.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoMGGReplacement_h
|
||||
#define _eoMGGReplacement_h
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoPop.h>
|
||||
#include <eoFunctor.h>
|
||||
#include <eoMerge.h>
|
||||
#include <eoReduce.h>
|
||||
#include <utils/eoHowMany.h>
|
||||
#include <eoReduceSplit.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
eoMGGReplacement is an eoReplacement:
|
||||
- choose N (2) parents RANDOMLY - remove them from the parent population
|
||||
- select best offspring, add to parents
|
||||
- merge (other?) offspring and the N removed parents
|
||||
- select best N-1 of this merged population (detTournament only at the moment)
|
||||
- put them back into parent population
|
||||
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoMGGReplacement : public eoReplacement<EOT>
|
||||
{
|
||||
public:
|
||||
eoMGGReplacement(eoHowMany _howManyEliminatedParents = eoHowMany(2, false),
|
||||
unsigned _tSize=2) :
|
||||
// split truncates the parents and returns eliminated parents
|
||||
split(_howManyEliminatedParents, true),
|
||||
tSize(_tSize)
|
||||
{
|
||||
if (tSize < 2)
|
||||
{
|
||||
std::cout << "Warning, Size for eoDetTournamentTruncateSplit adjusted to 2\n";
|
||||
tSize = 2;
|
||||
}
|
||||
}
|
||||
|
||||
void operator()(eoPop<EOT> & _parents, eoPop<EOT> & _offspring)
|
||||
{
|
||||
eoPop<EOT> temp;
|
||||
split(_parents, temp);
|
||||
unsigned toKeep = temp.size(); // how many to keep from merged populations
|
||||
// minimal check
|
||||
if (toKeep < 2)
|
||||
throw std::runtime_error("Not enough parents killed in eoMGGReplacement");
|
||||
|
||||
// select best offspring
|
||||
typename eoPop<EOT>::iterator it = _offspring.it_best_element();
|
||||
// add to parents
|
||||
_parents.push_back(*it);
|
||||
// remove from offspring
|
||||
_offspring.erase(it);
|
||||
|
||||
// merge temp into offspring
|
||||
plus(temp, _offspring);
|
||||
|
||||
// repeatedly add selected offspring to parents
|
||||
for (unsigned i=0; i<toKeep-1; i++)
|
||||
{
|
||||
// select
|
||||
it = deterministic_tournament(_offspring.begin(), _offspring.end(), tSize);
|
||||
// add to parents
|
||||
_parents.push_back(*it);
|
||||
// remove from offspring
|
||||
_offspring.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
eoLinearTruncateSplit<EOT> split; // few parents to truncate -> linear
|
||||
eoPlus<EOT> plus;
|
||||
unsigned int tSize;
|
||||
};
|
||||
|
||||
#endif
|
||||
134
trunk/paradiseo-eo/src/eoMerge.h
Normal file
134
trunk/paradiseo-eo/src/eoMerge.h
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoMerge.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 eoMerge_h
|
||||
#define eoMerge_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
// EO includes
|
||||
#include <eoPop.h> // eoPop
|
||||
#include <eoFunctor.h> // eoMerge
|
||||
|
||||
/**
|
||||
* 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 eoBF<const eoPop<Chrom>&, eoPop<Chrom>&, void>
|
||||
{};
|
||||
|
||||
/**
|
||||
Straightforward elitism class, specify the number of individuals to copy
|
||||
into new geneneration or the rate w.r.t. pop size
|
||||
*/
|
||||
template <class EOT> class eoElitism : public eoMerge<EOT>
|
||||
{
|
||||
public :
|
||||
eoElitism(double _rate, bool _interpret_as_rate = true):
|
||||
rate(0), combien(0)
|
||||
{
|
||||
if (_interpret_as_rate)
|
||||
{
|
||||
if ( (_rate<0) || (_rate>1) )
|
||||
throw std::logic_error("eoElitism: rate shoud be in [0,1]");
|
||||
rate = _rate;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_rate<0)
|
||||
throw std::logic_error("Negative number of offspring in eoElitism!");
|
||||
combien = (unsigned int)_rate;
|
||||
if (combien != _rate)
|
||||
std::cout << "Warning: Number of guys to merge in eoElitism was rounded";
|
||||
}
|
||||
}
|
||||
|
||||
void operator()(const eoPop<EOT>& _pop, eoPop<EOT>& _offspring)
|
||||
{
|
||||
if ((combien == 0) && (rate == 0.0))
|
||||
return;
|
||||
unsigned combienLocal;
|
||||
if (combien == 0) // rate is specified
|
||||
combienLocal = (unsigned int) (rate * _pop.size());
|
||||
else
|
||||
combienLocal = combien;
|
||||
|
||||
if (combienLocal > _pop.size())
|
||||
throw std::logic_error("Elite larger than population");
|
||||
|
||||
std::vector<const EOT*> result;
|
||||
_pop.nth_element(combienLocal, result);
|
||||
|
||||
for (size_t i = 0; i < result.size(); ++i)
|
||||
{
|
||||
_offspring.push_back(*result[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private :
|
||||
double rate;
|
||||
unsigned combien;
|
||||
};
|
||||
|
||||
/**
|
||||
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 (size_t i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
_offspring.push_back(_pop[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private :
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif
|
||||
115
trunk/paradiseo-eo/src/eoMergeReduce.h
Normal file
115
trunk/paradiseo-eo/src/eoMergeReduce.h
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoMergeReduce.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 _eoMergeReduce_h
|
||||
#define _eoMergeReduce_h
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoPop.h>
|
||||
#include <eoFunctor.h>
|
||||
#include <eoMerge.h>
|
||||
#include <eoReduce.h>
|
||||
#include <eoReplacement.h>
|
||||
#include <utils/eoHowMany.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
/**
|
||||
Replacement strategies that combine en eoMerge and an eoReduce.
|
||||
|
||||
@classes: eoMergeReduce, the base (pure abstract) class
|
||||
eoPlusReplacement the ES plus strategy
|
||||
eoCommaReplacement the ES comma strategy
|
||||
*/
|
||||
|
||||
/**
|
||||
eoMergeReduce: abstract 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()(eoPop<EOT>& _parents, eoPop<EOT>& _offspring)
|
||||
{
|
||||
merge(_parents, _offspring); // parents untouched, result in offspring
|
||||
reduce(_offspring, _parents.size());
|
||||
_parents.swap(_offspring);
|
||||
}
|
||||
|
||||
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;
|
||||
};
|
||||
|
||||
/**
|
||||
EP type of replacement strategy: first add parents to population,
|
||||
then truncate using EP tournament
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoEPReplacement : public eoMergeReduce<EOT>
|
||||
{
|
||||
public :
|
||||
eoEPReplacement(int _tSize) : eoMergeReduce<EOT>(plus, truncate), truncate(_tSize)
|
||||
// {truncate.setSize(_tSize);}
|
||||
{}
|
||||
private :
|
||||
eoPlus<EOT> plus;
|
||||
eoEPReduce<EOT> truncate;
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
496
trunk/paradiseo-eo/src/eoNDSorting.h
Normal file
496
trunk/paradiseo-eo/src/eoNDSorting.h
Normal file
|
|
@ -0,0 +1,496 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoNDSorting.h
|
||||
(c) Maarten Keijzer, Marc Schoenauer, 2001
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoNDSorting_h
|
||||
#define eoNDSorting_h
|
||||
|
||||
#include <EO.h>
|
||||
#include <algorithm>
|
||||
#include <eoPop.h>
|
||||
#include <eoPerf2Worth.h>
|
||||
#include <cassert>
|
||||
|
||||
/**
|
||||
Non dominated sorting, it *is a* std::vector of doubles, the integer part is the rank (to which front it belongs),
|
||||
the fractional part the niching penalty or distance penalty or whatever penalty you want to squeeze into
|
||||
the bits.
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoNDSorting : public eoPerf2WorthCached<EOT, double>
|
||||
{
|
||||
public :
|
||||
|
||||
using eoPerf2WorthCached<EOT, double>::value;
|
||||
eoNDSorting(bool nasty_flag_ = false)
|
||||
: nasty_declone_flag_that_only_is_implemented_for_two_objectives(nasty_flag_)
|
||||
{}
|
||||
|
||||
|
||||
eoNDSorting()
|
||||
: nasty_declone_flag_that_only_is_implemented_for_two_objectives(false)
|
||||
{}
|
||||
|
||||
/** Pure virtual function that calculates the 'distance' for each element in the current front
|
||||
Implement to create your own nondominated sorting algorithm. The size of the returned std::vector
|
||||
should be equal to the size of the current_front.
|
||||
*/
|
||||
virtual std::vector<double> niche_penalty(const std::vector<unsigned>& current_front, const eoPop<EOT>& _pop) = 0;
|
||||
|
||||
void calculate_worths(const eoPop<EOT>& _pop)
|
||||
{
|
||||
// resize the worths beforehand
|
||||
value().resize(_pop.size());
|
||||
|
||||
typedef typename EOT::Fitness::fitness_traits traits;
|
||||
|
||||
switch (traits::nObjectives())
|
||||
{
|
||||
case 1:
|
||||
{
|
||||
one_objective(_pop);
|
||||
return;
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
two_objectives(_pop);
|
||||
return;
|
||||
}
|
||||
default :
|
||||
{
|
||||
m_objectives(_pop);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private :
|
||||
|
||||
/** used in fast nondominated sorting
|
||||
DummyEO is just a storage place for fitnesses and
|
||||
to store the original index
|
||||
*/
|
||||
class DummyEO : public EO<typename EOT::Fitness>
|
||||
{
|
||||
public: unsigned index;
|
||||
};
|
||||
|
||||
void one_objective(const eoPop<EOT>& _pop)
|
||||
{
|
||||
unsigned i;
|
||||
std::vector<DummyEO> tmp_pop;
|
||||
tmp_pop.resize(_pop.size());
|
||||
|
||||
// copy pop to dummy population (only need the fitnesses)
|
||||
for (i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
tmp_pop[i].fitness(_pop[i].fitness());
|
||||
tmp_pop[i].index = i;
|
||||
}
|
||||
|
||||
std::sort(tmp_pop.begin(), tmp_pop.end(), std::greater<DummyEO>());
|
||||
|
||||
for (i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
value()[tmp_pop[i].index] = _pop.size() - i; // set rank
|
||||
}
|
||||
|
||||
// no point in calculcating niche penalty, as every distinct fitness value has a distinct rank
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimization for two objectives. Makes the algorithm run in
|
||||
* complexity O(n log n) where n is the population size
|
||||
*
|
||||
* This is the same complexity as for a single objective
|
||||
* or truncation selection or sorting.
|
||||
*
|
||||
* It will perform a sort on the two objectives seperately,
|
||||
* and from the information on the ranks of the individuals on
|
||||
* these two objectives, the non-dominated sorting rank is determined.
|
||||
* There are then three nlogn operations in place: one sort per objective,
|
||||
* plus a binary search procedure to combine the information about the
|
||||
* ranks.
|
||||
*
|
||||
* After that it is a simple exercise to calculate the distance
|
||||
* penalty
|
||||
*/
|
||||
|
||||
void two_objectives(const eoPop<EOT>& _pop)
|
||||
{
|
||||
unsigned i;
|
||||
typedef typename EOT::Fitness::fitness_traits traits;
|
||||
assert(traits::nObjectives() == 2);
|
||||
|
||||
std::vector<unsigned> sort1(_pop.size()); // index into population sorted on first objective
|
||||
|
||||
for (i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
sort1[i] = i;
|
||||
}
|
||||
|
||||
std::sort(sort1.begin(), sort1.end(), Sorter(_pop));
|
||||
|
||||
// Ok, now the meat of the algorithm
|
||||
|
||||
unsigned last_front = 0;
|
||||
|
||||
double max1 = -1e+20;
|
||||
for (i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
max1 = std::max(max1, _pop[i].fitness()[1]);
|
||||
}
|
||||
|
||||
max1 = max1 + 1.0; // add a bit to it so that it is a real upperbound
|
||||
|
||||
unsigned prev_front = 0;
|
||||
std::vector<double> d;
|
||||
d.resize(_pop.size(), max1); // initialize with the value max1 everywhere
|
||||
|
||||
std::vector<std::vector<unsigned> > fronts(_pop.size()); // to store indices into the front
|
||||
|
||||
for (i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
unsigned index = sort1[i];
|
||||
|
||||
// check for clones and delete them
|
||||
if (0 && i > 0)
|
||||
{
|
||||
unsigned prev = sort1[i-1];
|
||||
if ( _pop[index].fitness() == _pop[prev].fitness())
|
||||
{ // it's a clone, give it the worst rank!
|
||||
|
||||
if (nasty_declone_flag_that_only_is_implemented_for_two_objectives)
|
||||
//declone
|
||||
fronts.back().push_back(index);
|
||||
else // assign it the rank of the previous
|
||||
fronts[prev_front].push_back(index);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
double value2 = _pop[index].fitness()[1];
|
||||
|
||||
if (traits::maximizing(1))
|
||||
value2 = max1 - value2;
|
||||
|
||||
// perform binary search using std::upper_bound, a log n operation for each member
|
||||
std::vector<double>::iterator it =
|
||||
std::upper_bound(d.begin(), d.begin() + last_front, value2);
|
||||
|
||||
unsigned front = unsigned(it - d.begin());
|
||||
if (front == last_front) ++last_front;
|
||||
|
||||
assert(it != d.end());
|
||||
|
||||
*it = value2; //update d
|
||||
fronts[front].push_back(index); // add it to the front
|
||||
|
||||
prev_front = front;
|
||||
}
|
||||
|
||||
// ok, and finally the niche penalty
|
||||
|
||||
for (i = 0; i < fronts.size(); ++i)
|
||||
{
|
||||
if (fronts[i].size() == 0) continue;
|
||||
|
||||
// Now we have the indices to the current front in current_front, do the niching
|
||||
std::vector<double> niche_count = niche_penalty(fronts[i], _pop);
|
||||
|
||||
// Check whether the derived class was nice
|
||||
if (niche_count.size() != fronts[i].size())
|
||||
{
|
||||
throw std::logic_error("eoNDSorting: niche and front should have the same size");
|
||||
}
|
||||
|
||||
double max_niche = *std::max_element(niche_count.begin(), niche_count.end());
|
||||
|
||||
for (unsigned j = 0; j < fronts[i].size(); ++j)
|
||||
{
|
||||
value()[fronts[i][j]] = i + niche_count[j] / (max_niche + 1.); // divide by max_niche + 1 to ensure that this front does not overlap with the next
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// invert ranks to obtain a 'bigger is better' score
|
||||
rank_to_worth();
|
||||
}
|
||||
|
||||
class Sorter
|
||||
{
|
||||
public:
|
||||
Sorter(const eoPop<EOT>& _pop) : pop(_pop) {}
|
||||
|
||||
bool operator()(unsigned i, unsigned j) const
|
||||
{
|
||||
typedef typename EOT::Fitness::fitness_traits traits;
|
||||
|
||||
double diff = pop[i].fitness()[0] - pop[j].fitness()[0];
|
||||
|
||||
if (fabs(diff) < traits::tol())
|
||||
{
|
||||
diff = pop[i].fitness()[1] - pop[j].fitness()[1];
|
||||
|
||||
if (fabs(diff) < traits::tol())
|
||||
return false;
|
||||
|
||||
if (traits::maximizing(1))
|
||||
return diff > 0.;
|
||||
return diff < 0.;
|
||||
}
|
||||
|
||||
if (traits::maximizing(0))
|
||||
return diff > 0.;
|
||||
return diff < 0.;
|
||||
}
|
||||
|
||||
const eoPop<EOT>& pop;
|
||||
};
|
||||
|
||||
void m_objectives(const eoPop<EOT>& _pop)
|
||||
{
|
||||
unsigned i;
|
||||
|
||||
typedef typename EOT::Fitness::fitness_traits traits;
|
||||
|
||||
std::vector<std::vector<unsigned> > S(_pop.size()); // which individuals does guy i dominate
|
||||
std::vector<unsigned> n(_pop.size(), 0); // how many individuals dominate guy i
|
||||
|
||||
unsigned j;
|
||||
for (i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
for (j = 0; j < _pop.size(); ++j)
|
||||
{
|
||||
if (_pop[i].fitness().dominates(_pop[j].fitness()))
|
||||
{ // i dominates j
|
||||
S[i].push_back(j); // add j to i's domination std::list
|
||||
|
||||
//n[j]++; // as i dominates j
|
||||
}
|
||||
else if (_pop[j].fitness().dominates(_pop[i].fitness()))
|
||||
{ // j dominates i, increment count for i, add i to the domination std::list of j
|
||||
n[i]++;
|
||||
|
||||
//S[j].push_back(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<unsigned> current_front;
|
||||
current_front.reserve(_pop.size());
|
||||
|
||||
// get the first front out
|
||||
for (i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
if (n[i] == 0)
|
||||
{
|
||||
current_front.push_back(i);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<unsigned> next_front;
|
||||
next_front.reserve(_pop.size());
|
||||
|
||||
unsigned front_index = 0; // which front are we processing
|
||||
while (!current_front.empty())
|
||||
{
|
||||
// Now we have the indices to the current front in current_front, do the niching
|
||||
std::vector<double> niche_count = niche_penalty(current_front, _pop);
|
||||
|
||||
// Check whether the derived class was nice
|
||||
if (niche_count.size() != current_front.size())
|
||||
{
|
||||
throw std::logic_error("eoNDSorting: niche and front should have the same size");
|
||||
}
|
||||
|
||||
double max_niche = *std::max_element(niche_count.begin(), niche_count.end());
|
||||
|
||||
for (i = 0; i < current_front.size(); ++i)
|
||||
{
|
||||
value()[current_front[i]] = front_index + niche_count[i] / (max_niche + 1.); // divide by max_niche + 1 to ensure that this front does not overlap with the next
|
||||
}
|
||||
|
||||
// Calculate which individuals are in the next front;
|
||||
|
||||
for (i = 0; i < current_front.size(); ++i)
|
||||
{
|
||||
for (j = 0; j < S[current_front[i]].size(); ++j)
|
||||
{
|
||||
unsigned dominated_individual = S[current_front[i]][j];
|
||||
n[dominated_individual]--; // As we remove individual i -- being part of the current front -- it no longer dominates j
|
||||
|
||||
if (n[dominated_individual] == 0) // it should be in the current front
|
||||
{
|
||||
next_front.push_back(dominated_individual);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
front_index++; // go to the next front
|
||||
swap(current_front, next_front); // make the next front current
|
||||
next_front.clear(); // clear it for the next iteration
|
||||
}
|
||||
|
||||
rank_to_worth();
|
||||
}
|
||||
|
||||
void rank_to_worth()
|
||||
{
|
||||
// now all that's left to do is to transform lower rank into higher worth
|
||||
double max_fitness = *std::max_element(value().begin(), value().end());
|
||||
|
||||
// but make sure it's an integer upper bound, so that all ranks inside the highest integer are the front
|
||||
max_fitness = ceil(max_fitness);
|
||||
|
||||
for (unsigned i = 0; i < value().size(); ++i)
|
||||
{
|
||||
value()[i] = max_fitness - value()[i];
|
||||
}
|
||||
|
||||
}
|
||||
public : bool nasty_declone_flag_that_only_is_implemented_for_two_objectives;
|
||||
};
|
||||
|
||||
/**
|
||||
The original Non Dominated Sorting algorithm from Srinivas and Deb
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoNDSorting_I : public eoNDSorting<EOT>
|
||||
{
|
||||
public :
|
||||
eoNDSorting_I(double _nicheSize, bool nasty_flag_ = false) : eoNDSorting<EOT>(nasty_flag_), nicheSize(_nicheSize) {}
|
||||
|
||||
std::vector<double> niche_penalty(const std::vector<unsigned>& current_front, const eoPop<EOT>& _pop)
|
||||
{
|
||||
std::vector<double> niche_count(current_front.size(), 0.);
|
||||
|
||||
for (unsigned i = 0; i < current_front.size(); ++i)
|
||||
{ // calculate whether the other points lie within the nice
|
||||
for (unsigned j = 0; j < current_front.size(); ++j)
|
||||
{
|
||||
if (i == j)
|
||||
continue;
|
||||
|
||||
double dist = 0.0;
|
||||
|
||||
for (unsigned k = 0; k < _pop[current_front[j]].fitness().size(); ++k)
|
||||
{
|
||||
double d = _pop[current_front[i]].fitness()[k] - _pop[current_front[j]].fitness()[k];
|
||||
dist += d*d;
|
||||
}
|
||||
|
||||
if (dist < nicheSize)
|
||||
{
|
||||
niche_count[i] += 1.0 - pow(dist / nicheSize,2.);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return niche_count;
|
||||
}
|
||||
|
||||
private :
|
||||
|
||||
double nicheSize;
|
||||
};
|
||||
|
||||
/** @brief Fast Elitist Non-Dominant Sorting Genetic Algorithm
|
||||
|
||||
Adapted from Deb, Agrawal, Pratab and Meyarivan: A Fast Elitist
|
||||
Non-Dominant Sorting Genetic Algorithm for MultiObjective
|
||||
Optimization: NSGA-II KanGAL Report No. 200001
|
||||
|
||||
Note that this class does not do the sorting per se, but the sorting
|
||||
of it worth_std::vector will give the right order
|
||||
|
||||
The crowding distance is calculated as the sum of the distances to
|
||||
the nearest neighbours. As we need to return the penalty value, we
|
||||
have to invert that and invert it again in the base class, but such
|
||||
is life, sigh
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoNDSorting_II : public eoNDSorting<EOT>
|
||||
{
|
||||
public:
|
||||
|
||||
eoNDSorting_II(bool nasty_flag_ = false) : eoNDSorting<EOT>(nasty_flag_) {}
|
||||
|
||||
typedef std::pair<double, unsigned> double_index_pair;
|
||||
|
||||
class compare_nodes
|
||||
{
|
||||
public :
|
||||
bool operator()(const double_index_pair& a, const double_index_pair& b) const
|
||||
{
|
||||
return a.first < b.first;
|
||||
}
|
||||
};
|
||||
|
||||
/// _cf points into the elements that consist of the current front
|
||||
std::vector<double> niche_penalty(const std::vector<unsigned>& _cf, const eoPop<EOT>& _pop)
|
||||
{
|
||||
typedef typename EOT::Fitness::fitness_traits traits;
|
||||
unsigned i;
|
||||
std::vector<double> niche_count(_cf.size(), 0.);
|
||||
|
||||
|
||||
unsigned nObjectives = traits::nObjectives(); //_pop[_cf[0]].fitness().size();
|
||||
|
||||
for (unsigned o = 0; o < nObjectives; ++o)
|
||||
{
|
||||
|
||||
std::vector<std::pair<double, unsigned> > performance(_cf.size());
|
||||
for (i =0; i < _cf.size(); ++i)
|
||||
{
|
||||
performance[i].first = _pop[_cf[i]].fitness()[o];
|
||||
performance[i].second = i;
|
||||
}
|
||||
|
||||
std::sort(performance.begin(), performance.end(), compare_nodes()); // a lambda operator would've been nice here
|
||||
|
||||
std::vector<double> nc(niche_count.size(), 0.0);
|
||||
|
||||
for (i = 1; i < _cf.size()-1; ++i)
|
||||
{ // and yet another level of indirection
|
||||
nc[performance[i].second] = performance[i+1].first - performance[i-1].first;
|
||||
}
|
||||
|
||||
double max_dist = *std::max_element(nc.begin(), nc.end());
|
||||
|
||||
// set boundary at max_dist + 1 (so it will get chosen over all the others
|
||||
nc[performance[0].second] = max_dist + 1;
|
||||
nc[performance.back().second] = max_dist + 1;
|
||||
|
||||
for (i = 0; i < nc.size(); ++i)
|
||||
{
|
||||
niche_count[i] = (max_dist + 1 - nc[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return niche_count;
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
75
trunk/paradiseo-eo/src/eoObject.h
Normal file
75
trunk/paradiseo-eo/src/eoObject.h
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoObject.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 EOOBJECT_H
|
||||
#define EOOBJECT_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <utils/eoData.h> // For limits definition
|
||||
#include <iostream> // std::istream, std::ostream
|
||||
#include <string> // std::string
|
||||
|
||||
#include <utils/compatibility.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoObject
|
||||
//-----------------------------------------------------------------------------
|
||||
/**
|
||||
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.
|
||||
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, eoState
|
||||
|
||||
*/
|
||||
class eoObject
|
||||
{
|
||||
public:
|
||||
/// Virtual dtor. They are needed in virtual class hierarchies.
|
||||
virtual ~eoObject() {}
|
||||
|
||||
/** Return the class id. This should be redefined in each class.
|
||||
Only "leaf" classes can be non-virtual.
|
||||
|
||||
Maarten: removed the default implementation as this proved to
|
||||
be too error-prone: I found several classes that had a typo in
|
||||
className (like classname), which would print eoObject instead of
|
||||
their own. Having it pure will force the implementor to provide a
|
||||
name.
|
||||
*/
|
||||
virtual std::string className() const = 0;
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
123
trunk/paradiseo-eo/src/eoOneToOneBreeder.h
Normal file
123
trunk/paradiseo-eo/src/eoOneToOneBreeder.h
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoOneToOneBreeder.h
|
||||
// (c) Maarten Keijzer and Marc Schoenauer, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: mkeijzer@dhi.dk
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoOneToOneBreeder_h
|
||||
#define eoOneToOneBreeder_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <eoOp.h>
|
||||
#include <eoGenOp.h>
|
||||
#include <eoPopulator.h>
|
||||
#include <eoSelectOne.h>
|
||||
#include <eoSequentialSelect.h>
|
||||
#include <eoBreed.h>
|
||||
#include <eoEvalFunc.h>
|
||||
#include <eoPopulator.h>
|
||||
#include <utils/eoHowMany.h>
|
||||
|
||||
/*****************************************************************************
|
||||
* eoOneToOneBreeder: transforms a population using
|
||||
* - an operator that MODIFIES only one parent from the populator
|
||||
* (though it can use any number aside) and thus generates ONE offspring)
|
||||
* - a local replacement between the parent and its offspring
|
||||
*
|
||||
* Typically, Differential Evolution (Storn and Price 94) and Deb et al's
|
||||
* G3 can be built on this
|
||||
****************************************************************************
|
||||
*/
|
||||
template<class EOT>
|
||||
class eoOneToOneBreeder: public eoBreed<EOT>
|
||||
{
|
||||
public:
|
||||
/** Ctor:
|
||||
* @param _op a general operator (must MODIFY only ONE parent)
|
||||
* @param _eval an eoEvalFunc to evaluate the offspring
|
||||
* @param _select a selectoOne, to be used for all selections [sequential]
|
||||
* @param _pReplace probability that the best of parent/offspring wins [1]
|
||||
* @param _howMany eoHowMany offpsring to generate [100%]
|
||||
*/
|
||||
eoOneToOneBreeder(
|
||||
eoGenOp<EOT>& _op,
|
||||
eoEvalFunc<EOT> & _eval,
|
||||
double _pReplace = 1.0,
|
||||
eoHowMany _howMany = eoHowMany(1.0) ) :
|
||||
op(_op), eval(_eval), select( false ),
|
||||
pReplace(_pReplace), howMany(_howMany) {}
|
||||
|
||||
|
||||
/** The breeder: iteratively calls the genOp ONCE on a selective populator
|
||||
* after having recorded the parent
|
||||
* Then does the replacement
|
||||
*
|
||||
* @param _parents the initial population
|
||||
* @param _offspring the resulting population (content -if any- is lost)
|
||||
*/
|
||||
void operator()(const eoPop<EOT>& _parents, eoPop<EOT>& _offspring)
|
||||
{
|
||||
unsigned target = howMany(_parents.size());
|
||||
|
||||
_offspring.clear();
|
||||
eoSelectivePopulator<EOT> popit(_parents, _offspring, select);
|
||||
|
||||
for (unsigned iParent=0; iParent<target; iParent++)
|
||||
{
|
||||
unsigned pos = popit.tellp(); // remember current position
|
||||
EOT theParent = *popit; // remember the parent itself
|
||||
|
||||
// now apply operator - will modify the parent
|
||||
op(popit);
|
||||
|
||||
// replacement
|
||||
EOT & leOffspring = *popit;
|
||||
|
||||
// check: only one offspring?
|
||||
unsigned posEnd = popit.tellp();
|
||||
if (posEnd != pos)
|
||||
throw std::runtime_error("Operator can only generate a SINGLE offspring in eoOneToOneBreeder");
|
||||
|
||||
// do the tournament between parent and offspring
|
||||
eval(leOffspring); // first need to evaluate the offspring
|
||||
if (theParent > leOffspring) // old parent better than offspring
|
||||
if (rng.uniform() < pReplace) // if probability
|
||||
leOffspring = theParent; // replace
|
||||
// finally, go to next guy to handle
|
||||
++popit;
|
||||
}
|
||||
}
|
||||
|
||||
/// The class name.
|
||||
virtual std::string className() const { return "eoOneToOneBreeder"; }
|
||||
|
||||
private:
|
||||
eoGenOp<EOT>& op;
|
||||
eoEvalFunc<EOT> & eval;
|
||||
eoSequentialSelect<EOT> select;
|
||||
double pReplace;
|
||||
eoHowMany howMany;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
170
trunk/paradiseo-eo/src/eoOp.h
Normal file
170
trunk/paradiseo-eo/src/eoOp.h
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoOp.h
|
||||
// (c) GeNeura Team, 1998
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
CVS Info: $Date: 2004/08/10 17:19:46 $ $Header: /cvsroot/eodev/eo/src/eoOp.h,v 1.29 2004/08/10 17:19:46 jmerelo Exp $ $Author: jmerelo $
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoOp_H
|
||||
#define _eoOp_H
|
||||
|
||||
#include <eoObject.h>
|
||||
#include <eoPrintable.h>
|
||||
#include <eoFunctor.h>
|
||||
#include <utils/eoRNG.h>
|
||||
/**
|
||||
\defgroup Operators
|
||||
Genetic Operators are used for various purposes
|
||||
*/
|
||||
|
||||
/** @name Genetic operators
|
||||
|
||||
What is a genetic algorithm without genetic operators?
|
||||
There is a genetic operator hierarchy, with eoOp as father and
|
||||
eoMonOp (monary or unary operator), eoBinOp and eoQuadOp (binary operators)
|
||||
and eoGenOp (any number of inputs and outputs, see eoGenOp.h)
|
||||
as subclasses.
|
||||
Nobody should subclass eoOp, you should subclass eoGenOp, eoBinOp, eoQuadOp
|
||||
or eoMonOp, those are the ones actually used here.
|
||||
|
||||
#eoOp#s are only printable objects, so if you want to build them
|
||||
from a file, it has to be done in another class, namely factories.
|
||||
Each hierarchy of #eoOp#s should have its own factory, which know
|
||||
how to build them from a description in a file.
|
||||
|
||||
@author GeNeura Team, Marten Keijzer and Marc Schoenauer
|
||||
@version 0.9
|
||||
@see eoGenOp.h eoOpFactory
|
||||
*/
|
||||
|
||||
//@{
|
||||
|
||||
/** Abstract data types for EO operators.
|
||||
Genetic operators act on chromosomes, changing them.
|
||||
The type to use them on is problem specific. If your genotype
|
||||
is a std::vector<bool>, there are operators that work specifically
|
||||
on std::vector<bool>, but you might also find that generic operators
|
||||
working on std::vector<T> are what you need.
|
||||
|
||||
*/
|
||||
template<class EOType>
|
||||
class eoOp
|
||||
{
|
||||
public:
|
||||
//@{
|
||||
enum OpType { unary = 0, binary = 1, quadratic = 2, general = 3};
|
||||
///
|
||||
|
||||
/// Ctor
|
||||
eoOp(OpType _type)
|
||||
:opType( _type ) {};
|
||||
|
||||
/// Copy Ctor
|
||||
eoOp( const eoOp& _eop )
|
||||
:opType( _eop.opType ) {};
|
||||
|
||||
/// Needed virtual destructor
|
||||
virtual ~eoOp(){};
|
||||
|
||||
/// getType: number of operands it takes and individuals it produces
|
||||
OpType getType() const {return opType;};
|
||||
|
||||
private:
|
||||
|
||||
/// OpType is the type of the operator: how many operands it takes and how many it produces
|
||||
OpType opType;
|
||||
};
|
||||
|
||||
/**
|
||||
eoMonOp is the monary operator: genetic operator that takes only one EO.
|
||||
When defining your own, make sure that you return a boolean value
|
||||
indicating that you have changed the content.
|
||||
*/
|
||||
template <class EOType>
|
||||
class eoMonOp: public eoOp<EOType>, public eoUF<EOType&, bool>
|
||||
{
|
||||
public:
|
||||
/// Ctor
|
||||
eoMonOp()
|
||||
: eoOp<EOType>( eoOp<EOType>::unary ) {};
|
||||
virtual std::string className() const {return "eoMonOp";};
|
||||
};
|
||||
|
||||
|
||||
/** Binary genetic operator: subclasses eoOp, and defines basically the
|
||||
* operator() with two operands, only the first one can be modified
|
||||
When defining your own, make sure that you return a boolean value
|
||||
indicating that you have changed the content.
|
||||
*/
|
||||
template<class EOType>
|
||||
class eoBinOp: public eoOp<EOType>, public eoBF<EOType&, const EOType&, bool>
|
||||
{
|
||||
public:
|
||||
/// Ctor
|
||||
eoBinOp()
|
||||
:eoOp<EOType>( eoOp<EOType>::binary ) {};
|
||||
virtual std::string className() const {return "eoBinOp";};
|
||||
};
|
||||
|
||||
/** Quad genetic operator: subclasses eoOp, and defines basically the
|
||||
operator() with two operands, both can be modified.
|
||||
When defining your own, make sure that you return a boolean value
|
||||
indicating that you have changed the content.
|
||||
*/
|
||||
template<class EOType>
|
||||
class eoQuadOp: public eoOp<EOType>, public eoBF<EOType&, EOType&, bool> {
|
||||
public:
|
||||
/// Ctor
|
||||
eoQuadOp()
|
||||
:eoOp<EOType>( eoOp<EOType>::quadratic ) {};
|
||||
virtual std::string className() const {return "eoQuadOp";};
|
||||
};
|
||||
|
||||
/** Turning an eoQuadOp into an eoBinOp: simply don't touch the second arg!
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoQuad2BinOp: public eoBinOp<EOT>
|
||||
{
|
||||
public:
|
||||
/** Ctor
|
||||
* @param _quadOp the eoQuadOp to be transformed
|
||||
*/
|
||||
eoQuad2BinOp(eoQuadOp<EOT> & _quadOp) : quadOp(_quadOp) {}
|
||||
|
||||
/** Operator() simply calls embedded quadOp operator() with dummy second arg
|
||||
*/
|
||||
bool operator()(EOT & _eo1, const EOT & _eo2)
|
||||
{
|
||||
EOT eoTmp = _eo2; // a copy that can be modified
|
||||
// if the embedded eoQuadOp is not symmetrical,
|
||||
// the result might be biased - hence the flip ...
|
||||
if (eo::rng.flip(0.5))
|
||||
return quadOp(_eo1, eoTmp); // both are modified - that's all
|
||||
else
|
||||
return quadOp(eoTmp, _eo1); // both are modified - that's all
|
||||
}
|
||||
|
||||
private:
|
||||
eoQuadOp<EOT> & quadOp;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
//@}
|
||||
159
trunk/paradiseo-eo/src/eoOpContainer.h
Normal file
159
trunk/paradiseo-eo/src/eoOpContainer.h
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoOpContainer.h
|
||||
// (c) Maarten Keijzer and Marc Schoenauer, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: mkeijzer@dhi.dk
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoOpContainer_H
|
||||
#define _eoOpContainer_H
|
||||
|
||||
#include <eoGenOp.h>
|
||||
|
||||
/** eoOpContainer is a base class for the sequential and proportional selectors
|
||||
* It takes care of wrapping the other operators,
|
||||
* and deleting stuff that it has allocated
|
||||
*
|
||||
* Warning: all operators are added together with a rate (double)
|
||||
* However, the meaning of this rate will be different in
|
||||
* the differnet instances of eoOpContainer:
|
||||
* an ***absolute*** probability in the sequential version, and
|
||||
* a ***relative*** weight in the proportional version
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoOpContainer : public eoGenOp<EOT>
|
||||
{
|
||||
public :
|
||||
/** Ctor: nothing much to do */
|
||||
eoOpContainer() : max_to_produce(0) {}
|
||||
|
||||
/** Dtor: delete all the GenOps created when wrapping simple ops
|
||||
*/
|
||||
virtual ~eoOpContainer(void) {}
|
||||
|
||||
/** for memory management (doesn't have to be very precise */
|
||||
virtual unsigned max_production(void)
|
||||
{
|
||||
return max_to_produce;
|
||||
}
|
||||
|
||||
/**
|
||||
Add an operator to the container, also give it a rate
|
||||
|
||||
(sidenote, it's much less hairy since I added the wrap_op is used)
|
||||
*/
|
||||
void add(eoOp<EOT>& _op, double _rate)
|
||||
{
|
||||
ops.push_back(&wrap_op<EOT>(_op, store));
|
||||
rates.push_back(_rate);
|
||||
max_to_produce = std::max(max_to_produce,ops.back()->max_production());
|
||||
}
|
||||
|
||||
virtual std::string className() const = 0;
|
||||
|
||||
protected :
|
||||
|
||||
std::vector<double> rates;
|
||||
std::vector<eoGenOp<EOT>*> ops;
|
||||
|
||||
private :
|
||||
eoFunctorStore store;
|
||||
unsigned max_to_produce;
|
||||
};
|
||||
|
||||
/** Sequential selection:
|
||||
* note the mark, rewind, unmark cycle
|
||||
* here operators are repeatedly applied on the same individual(s)
|
||||
* not all too elegant, but it sort of works...
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoSequentialOp : public eoOpContainer<EOT>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoOpContainer<EOT>::ops;
|
||||
using eoOpContainer<EOT>::rates;
|
||||
|
||||
typedef unsigned position_type;
|
||||
|
||||
|
||||
void apply(eoPopulator<EOT>& _pop) {
|
||||
position_type pos = _pop.tellp();
|
||||
for (size_t i = 0; i < rates.size(); ++i) {
|
||||
_pop.seekp(pos);
|
||||
do {
|
||||
if (eo::rng.flip(rates[i])) {
|
||||
// try
|
||||
// {
|
||||
// apply it to all the guys in the todo std::list
|
||||
(*ops[i])(_pop);
|
||||
// }
|
||||
// check for out of individuals and do nothing with that...
|
||||
// catch(eoPopulator<EOT>::OutOfIndividuals&)
|
||||
// {
|
||||
// std::cout << "Warning: not enough individuals to handle\n";
|
||||
// return ;
|
||||
// }
|
||||
}
|
||||
|
||||
if (!_pop.exhausted())
|
||||
++_pop;
|
||||
}
|
||||
while (!_pop.exhausted());
|
||||
}
|
||||
}
|
||||
virtual std::string className() const {return "SequentialOp";}
|
||||
|
||||
private:
|
||||
|
||||
std::vector<size_t> to_apply;
|
||||
std::vector<size_t> production;
|
||||
};
|
||||
|
||||
|
||||
|
||||
/** The proportional versions: easy! */
|
||||
template <class EOT>
|
||||
class eoProportionalOp : public eoOpContainer<EOT>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoOpContainer< EOT >::ops;
|
||||
using eoOpContainer< EOT >::rates;
|
||||
|
||||
void apply(eoPopulator<EOT>& _pop)
|
||||
{
|
||||
unsigned i = eo::rng.roulette_wheel(rates);
|
||||
|
||||
try
|
||||
{
|
||||
(*ops[i])(_pop);
|
||||
++_pop;
|
||||
}
|
||||
catch( typename eoPopulator<EOT>::OutOfIndividuals&)
|
||||
{}
|
||||
}
|
||||
virtual std::string className() const {return "ProportionalOp";}
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
109
trunk/paradiseo-eo/src/eoOpSelMason.h
Normal file
109
trunk/paradiseo-eo/src/eoOpSelMason.h
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoOpSelMason.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 _EOOPSELMASON_H
|
||||
#define _EOOPSELMASON_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoProportionalOpSel.h>
|
||||
#include <eoOpFactory.h> // for eoFactory and eoOpFactory
|
||||
|
||||
#include <map>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** EO Mason, or builder, for operator selectors. A builder must allocate memory
|
||||
to the objects it builds, and then deallocate it when it gets out of scope*/
|
||||
template<class eoClass>
|
||||
class eoOpSelMason: public eoFactory<eoOpSelector<eoClass> > {
|
||||
|
||||
public:
|
||||
typedef std::vector<eoOp<eoClass>* > vOpP;
|
||||
typedef map<eoOpSelector<eoClass>*, vOpP > MEV;
|
||||
|
||||
/// @name ctors and dtors
|
||||
//{@
|
||||
/// constructor
|
||||
eoOpSelMason( eoOpFactory<eoClass>& _opFact): operatorFactory( _opFact ) {};
|
||||
|
||||
/// destructor
|
||||
virtual ~eoOpSelMason() {};
|
||||
//@}
|
||||
|
||||
/** Factory methods: creates an object from an std::istream, reading from
|
||||
it whatever is needed to create the object. The format is
|
||||
opSelClassName\\
|
||||
rate 1 operator1\\
|
||||
rate 2 operator2\\
|
||||
...\\
|
||||
Stores all operators built in a database (#allocMap#), so that somebody
|
||||
can destroy them later. The Mason is in charge or destroying the operators,
|
||||
since the built object can´t do it itself. The objects built must be destroyed
|
||||
from outside, using the #destroy# method
|
||||
*/
|
||||
virtual eoOpSelector<eoClass>* make(std::istream& _is) {
|
||||
|
||||
std::string opSelName;
|
||||
_is >> opSelName;
|
||||
eoOpSelector<eoClass>* opSelectorP;
|
||||
// Build the operator selector
|
||||
if ( opSelName == "eoProportionalOpSel" ) {
|
||||
opSelectorP = new eoProportionalOpSel<eoClass>();
|
||||
}
|
||||
|
||||
// Temp std::vector for storing pointers
|
||||
vOpP tmpPVec;
|
||||
// read operator rate and name
|
||||
while ( _is ) {
|
||||
float rate;
|
||||
_is >> rate;
|
||||
if ( _is ) {
|
||||
eoOp<eoClass>* op = operatorFactory.make( _is ); // This reads the rest of the line
|
||||
// Add the operators to the selector, don´t pay attention to the IDs
|
||||
opSelectorP->addOp( *op, rate );
|
||||
// Keep it in the store, to destroy later
|
||||
tmpPVec.push_back( op );
|
||||
} // if
|
||||
} // while
|
||||
|
||||
// Put it in the map
|
||||
allocMap.insert( MEV::value_type( opSelectorP, tmpPVec ) );
|
||||
|
||||
return opSelectorP;
|
||||
};
|
||||
|
||||
///@name eoObject methods
|
||||
//@{
|
||||
/** Return the class id */
|
||||
virtual std::string className() const { return "eoOpSelMason"; }
|
||||
|
||||
//@}
|
||||
|
||||
private:
|
||||
map<eoOpSelector<eoClass>*,std::vector<eoOp<eoClass>* > > allocMap;
|
||||
eoOpFactory<eoClass>& operatorFactory;
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
229
trunk/paradiseo-eo/src/eoParetoConstraintFitness.h
Normal file
229
trunk/paradiseo-eo/src/eoParetoConstraintFitness.h
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoParetoConstraintFitness.h
|
||||
// (c) Maarten Keijzer and Marc Schoenauer, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: mkeijzer@cs.vu.nl
|
||||
Marc.Schoenauer@inria.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoParetoConstraintFitness_h
|
||||
#define _eoParetoConstraintFitness_h
|
||||
|
||||
#include <math.h>
|
||||
#include <vector>
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
|
||||
#include <eoParetoFitness.h>
|
||||
|
||||
/**
|
||||
eoParetoOneConstraintFitness class:
|
||||
std::vector of doubles + constraint value
|
||||
|
||||
Comparison (dominance) is done
|
||||
on pareto dominance for 2 feasible individuals,
|
||||
one feasible individual always wins over an infeasible
|
||||
on constraint violations for 2 infeasible individuals
|
||||
|
||||
The template argument FitnessTraits defaults to
|
||||
eoParetoFitnessTraits, which can be replaces at will by any other
|
||||
class that implements the static functions defined therein.
|
||||
|
||||
Note that the domninance defines a partial order, so that
|
||||
!dominates(a,b) && !domaintes(b,a) does not neccessarily imply that (a==b)
|
||||
The other way around does hold.
|
||||
|
||||
However, be careful that the comparison operators do define a total order
|
||||
based on considering first objective, then in case of tie, second objective, etc
|
||||
|
||||
NOTE: in a hurry, I did not want to make it derive from eoParetoFitness
|
||||
(used cut-and-paste instead!) : I know it might be a good idea, but I'm
|
||||
not sure I see why at the moment (any hint someone?)
|
||||
*/
|
||||
template <class FitnessTraits = eoParetoFitnessTraits>
|
||||
class eoParetoOneConstraintFitness : public std::vector<double>
|
||||
{
|
||||
private:
|
||||
// this class implements only 1 inequality constraint
|
||||
// (must ponder a bit for generality without huge overload)
|
||||
double constraintValue; // inequality cstr - must be negative
|
||||
|
||||
public :
|
||||
typedef FitnessTraits fitness_traits;
|
||||
|
||||
eoParetoOneConstraintFitness(void) : std::vector<double>(FitnessTraits::nObjectives(),0.0) {}
|
||||
|
||||
// Ctr from a std::vector<double> (size nObjectives+1)
|
||||
eoParetoOneConstraintFitness(std::vector<double> & _v) :
|
||||
std::vector<double>(_v)
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
if (_v.size() != fitness_traits::nObjectives()+1)
|
||||
throw std::runtime_error("Size error in Ctor of eoParetoOneConstraintFitness from std::vector");
|
||||
#endif
|
||||
constraintValue = _v[fitness_traits::nObjectives()];
|
||||
resize(fitness_traits::nObjectives());
|
||||
}
|
||||
|
||||
// Ctr from a std::vector<double> and a value
|
||||
eoParetoOneConstraintFitness(std::vector<double> & _v, double _c) :
|
||||
std::vector<double>(_v), constraintValue(_c)
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
if (_v.size() != fitness_traits::nObjectives())
|
||||
throw std::runtime_error("Size error in Ctor of eoParetoOneConstraintFitness from std::vector and value");
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
/** access to the traits characteristics (so you don't have to write
|
||||
* a lot of typedef's around
|
||||
*/
|
||||
static void setUp(unsigned _n, std::vector<bool> & _b) {FitnessTraits::setUp(_n, _b);}
|
||||
static bool maximizing(unsigned _i) { return FitnessTraits::maximizing(_i);}
|
||||
|
||||
bool feasible() const { return constraintValue<=0;}
|
||||
double violation() const { return (feasible()?0.0:constraintValue);}
|
||||
double ConstraintValue() const {return constraintValue;}
|
||||
void ConstraintValue(double _c) {constraintValue=_c;}
|
||||
|
||||
/// Partial order based on Pareto-dominance
|
||||
//bool operator<(const eoParetoFitness<FitnessTraits>& _other) const
|
||||
bool dominates(const eoParetoOneConstraintFitness<FitnessTraits>& _other) const
|
||||
{
|
||||
bool dom = false;
|
||||
|
||||
double tol = FitnessTraits::tol();
|
||||
const std::vector<double>& performance = *this;
|
||||
const std::vector<double>& otherperformance = _other;
|
||||
|
||||
if (feasible() && _other.feasible())
|
||||
// here both are feasible: do the "standard" domination
|
||||
for (unsigned i = 0; i < FitnessTraits::nObjectives(); ++i)
|
||||
{
|
||||
bool maxim = FitnessTraits::maximizing(i);
|
||||
double aval = maxim? performance[i] : -performance[i];
|
||||
double bval = maxim? otherperformance[i] : -otherperformance[i];
|
||||
|
||||
if (fabs(aval - bval) > tol)
|
||||
{
|
||||
if (aval < bval)
|
||||
{
|
||||
return false; // cannot dominate
|
||||
}
|
||||
// else aval < bval
|
||||
dom = true; // for the moment: goto next objective
|
||||
}
|
||||
//else they're equal in this objective, goto next
|
||||
}
|
||||
else
|
||||
{ // one at least is not feasible
|
||||
if (feasible())
|
||||
return true; // feasible wins
|
||||
else if (_other.feasible())
|
||||
return false; // feasible wins
|
||||
return (violation()<_other.violation()); // smallest violation wins
|
||||
}
|
||||
|
||||
return dom;
|
||||
}
|
||||
|
||||
/// compare *not* on dominance, but on the first, then the second, etc
|
||||
bool operator<(const eoParetoOneConstraintFitness<FitnessTraits>& _other) const
|
||||
{
|
||||
double tol = FitnessTraits::tol();
|
||||
const std::vector<double>& performance = *this;
|
||||
const std::vector<double>& otherperformance = _other;
|
||||
for (unsigned i = 0; i < FitnessTraits::nObjectives(); ++i)
|
||||
{
|
||||
bool maxim = FitnessTraits::maximizing(i);
|
||||
double aval = maxim? performance[i] : -performance[i];
|
||||
double bval = maxim? otherperformance[i] : -otherperformance[i];
|
||||
|
||||
if (fabs(aval-bval) > tol)
|
||||
{
|
||||
if (aval < bval)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool operator>(const eoParetoOneConstraintFitness<FitnessTraits>& _other) const
|
||||
{
|
||||
return _other < *this;
|
||||
}
|
||||
|
||||
bool operator<=(const eoParetoOneConstraintFitness<FitnessTraits>& _other) const
|
||||
{
|
||||
return operator==(_other) || operator<(_other);
|
||||
}
|
||||
|
||||
bool operator>=(const eoParetoOneConstraintFitness<FitnessTraits>& _other) const
|
||||
{
|
||||
return _other <= *this;
|
||||
}
|
||||
|
||||
bool operator==(const eoParetoOneConstraintFitness<FitnessTraits>& _other) const
|
||||
{ // check if they're all within tolerance
|
||||
for (unsigned i = 0; i < size(); ++i)
|
||||
{
|
||||
if (fabs(operator[](i) - _other[i]) > FitnessTraits::tol())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool operator!=(const eoParetoOneConstraintFitness<FitnessTraits>& _other) const
|
||||
{ return ! operator==(_other); }
|
||||
|
||||
};
|
||||
|
||||
template <class FitnessTraits>
|
||||
std::ostream& operator<<(std::ostream& os, const eoParetoOneConstraintFitness<FitnessTraits>& fitness)
|
||||
{
|
||||
for (unsigned i = 0; i < fitness.size(); ++i)
|
||||
{
|
||||
os << fitness[i] << ' ';
|
||||
}
|
||||
os << fitness.ConstraintValue() << " " ;
|
||||
return os;
|
||||
}
|
||||
|
||||
template <class FitnessTraits>
|
||||
std::istream& operator>>(std::istream& is, eoParetoOneConstraintFitness<FitnessTraits>& fitness)
|
||||
{
|
||||
fitness = eoParetoOneConstraintFitness<FitnessTraits>();
|
||||
for (unsigned i = 0; i < fitness.size(); ++i)
|
||||
{
|
||||
is >> fitness[i];
|
||||
}
|
||||
double r;
|
||||
is >> r;
|
||||
fitness.ConstraintValue(r);
|
||||
return is;
|
||||
}
|
||||
|
||||
#endif
|
||||
38
trunk/paradiseo-eo/src/eoParetoFitness.cpp
Normal file
38
trunk/paradiseo-eo/src/eoParetoFitness.cpp
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoPareto.cpp
|
||||
// (c) EEAAX,1996-GeNeura Team,1998-Maarten Keijzer,2000-Marc Schoenauer 2002
|
||||
/*
|
||||
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@inria.fr
|
||||
mak@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include "eoParetoFitness.h"
|
||||
|
||||
|
||||
// need to allocate the static variables of class eoVariableParetoTraits
|
||||
unsigned eoVariableParetoTraits::nObj;
|
||||
std::vector<bool> eoVariableParetoTraits::bObj;
|
||||
|
||||
|
||||
234
trunk/paradiseo-eo/src/eoParetoFitness.h
Normal file
234
trunk/paradiseo-eo/src/eoParetoFitness.h
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoParetoFitness.h
|
||||
// (c) Maarten Keijzer and Marc Schoenauer, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: mak@dhi.dk
|
||||
Marc.Schoenauer@inria.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoParetoFitness_h
|
||||
#define _eoParetoFitness_h
|
||||
|
||||
#include <math.h>
|
||||
#include <vector>
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
|
||||
|
||||
/**
|
||||
* eoFitnessTraits: a traits class to specify
|
||||
* the number of objectives and which one are maximizing or not
|
||||
* See test/t-eoParetoFitness for its use.
|
||||
*
|
||||
* If you define your own, make sure you make the functions static!
|
||||
*/
|
||||
class eoParetoFitnessTraits
|
||||
{
|
||||
public :
|
||||
|
||||
static unsigned nObjectives() { return 2; }
|
||||
static double tol() { return 1e-6; }
|
||||
static bool maximizing(int which) { return true; } // by default: all are maximizing
|
||||
};
|
||||
|
||||
/**
|
||||
* eoVariableParetoTraits : an eoParetoFitnessTraits whose characteristics
|
||||
* can be set at run-time (nb objectives and min/max's)
|
||||
* Why bother? For didactical purposes (and EASEA implementation :-)
|
||||
*/
|
||||
class eoVariableParetoTraits : public eoParetoFitnessTraits
|
||||
{
|
||||
public :
|
||||
/** setting the static stuff */
|
||||
static void setUp(unsigned _n, std::vector<bool> & _b)
|
||||
{
|
||||
// possible problems
|
||||
if ( nObj && (nObj != _n) ) // was already set to a different value
|
||||
{
|
||||
std::cout << "WARNING\n";
|
||||
std::cout << "WARNING : you are changing the number of objectives\n";
|
||||
std::cout << "WARNING : Make sure all existing objects are destroyed\n";
|
||||
std::cout << "WARNING\n";
|
||||
}
|
||||
nObj=_n;
|
||||
bObj=_b;
|
||||
if (nObj != bObj.size())
|
||||
throw std::runtime_error("Number of objectives and min/max size don't match in VariableParetoTraits::setup");
|
||||
}
|
||||
|
||||
/** the accessors */
|
||||
static unsigned nObjectives()
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
if (!nObj)
|
||||
throw std::runtime_error("Number of objectives not assigned in VariableParetoTraits");
|
||||
#endif
|
||||
return nObj;
|
||||
}
|
||||
static bool maximizing(unsigned _i)
|
||||
{
|
||||
#ifndef NDEBUG
|
||||
if (_i >= bObj.size())
|
||||
throw std::runtime_error("Wrong index in VariableParetoTraits");
|
||||
#endif
|
||||
return bObj[_i];
|
||||
}
|
||||
private:
|
||||
static unsigned nObj;
|
||||
static std::vector<bool> bObj;
|
||||
};
|
||||
|
||||
/**
|
||||
eoParetoFitness class: std::vector of doubles with overloaded comparison operators. Comparison is done
|
||||
on pareto dominance. The template argument FitnessTraits defaults to eoParetoFitnessTraits, which
|
||||
can be replaces at will by any other class that implements the static functions defined therein.
|
||||
|
||||
Note that the comparison defines a partial order, so that
|
||||
!(a < b) && !(b <a) does not neccessarily imply that (a==b)
|
||||
The other way around does hold.
|
||||
*/
|
||||
template <class FitnessTraits = eoParetoFitnessTraits>
|
||||
class eoParetoFitness : public std::vector<double>
|
||||
{
|
||||
public :
|
||||
|
||||
typedef FitnessTraits fitness_traits;
|
||||
|
||||
eoParetoFitness(void) : std::vector<double>(FitnessTraits::nObjectives(),0.0) {}
|
||||
|
||||
// Ctr from a std::vector<double>
|
||||
eoParetoFitness(std::vector<double> & _v) : std::vector<double>(_v) {}
|
||||
|
||||
|
||||
/** access to the traits characteristics (so you don't have to write
|
||||
* a lot of typedef's around
|
||||
*/
|
||||
static void setUp(unsigned _n, std::vector<bool> & _b) {FitnessTraits::setUp(_n, _b);}
|
||||
static bool maximizing(unsigned _i) { return FitnessTraits::maximizing(_i);}
|
||||
|
||||
/// Partial order based on Pareto-dominance
|
||||
//bool operator<(const eoParetoFitness<FitnessTraits>& _other) const
|
||||
bool dominates(const eoParetoFitness<FitnessTraits>& _other) const
|
||||
{
|
||||
bool dom = false;
|
||||
|
||||
double tol = FitnessTraits::tol();
|
||||
const std::vector<double>& performance = *this;
|
||||
const std::vector<double>& otherperformance = _other;
|
||||
|
||||
for (unsigned i = 0; i < FitnessTraits::nObjectives(); ++i)
|
||||
{
|
||||
bool maxim = FitnessTraits::maximizing(i);
|
||||
double aval = maxim? performance[i] : -performance[i];
|
||||
double bval = maxim? otherperformance[i] : -otherperformance[i];
|
||||
|
||||
if (fabs(aval - bval) > tol)
|
||||
{
|
||||
if (aval < bval)
|
||||
{
|
||||
return false; // cannot dominate
|
||||
}
|
||||
// else aval < bval
|
||||
dom = true; // for the moment: goto next objective
|
||||
}
|
||||
//else they're equal in this objective, goto next
|
||||
}
|
||||
|
||||
return dom;
|
||||
}
|
||||
|
||||
/// compare *not* on dominance, but on the first, then the second, etc
|
||||
bool operator<(const eoParetoFitness<FitnessTraits>& _other) const
|
||||
{
|
||||
double tol = FitnessTraits::tol();
|
||||
const std::vector<double>& performance = *this;
|
||||
const std::vector<double>& otherperformance = _other;
|
||||
for (unsigned i = 0; i < FitnessTraits::nObjectives(); ++i)
|
||||
{
|
||||
bool maxim = FitnessTraits::maximizing(i);
|
||||
double aval = maxim? performance[i] : -performance[i];
|
||||
double bval = maxim? otherperformance[i] : -otherperformance[i];
|
||||
|
||||
if (fabs(aval-bval) > tol)
|
||||
{
|
||||
if (aval < bval)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool operator>(const eoParetoFitness<FitnessTraits>& _other) const
|
||||
{
|
||||
return _other < *this;
|
||||
}
|
||||
|
||||
bool operator<=(const eoParetoFitness<FitnessTraits>& _other) const
|
||||
{
|
||||
return operator==(_other) || operator<(_other);
|
||||
}
|
||||
|
||||
bool operator>=(const eoParetoFitness<FitnessTraits>& _other) const
|
||||
{
|
||||
return _other <= *this;
|
||||
}
|
||||
|
||||
bool operator==(const eoParetoFitness<FitnessTraits>& _other) const
|
||||
{ // check if they're all within tolerance
|
||||
for (unsigned i = 0; i < size(); ++i)
|
||||
{
|
||||
if (fabs(operator[](i) - _other[i]) > FitnessTraits::tol())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool operator!=(const eoParetoFitness<FitnessTraits>& _other) const
|
||||
{ return ! operator==(_other); }
|
||||
|
||||
};
|
||||
|
||||
template <class FitnessTraits>
|
||||
std::ostream& operator<<(std::ostream& os, const eoParetoFitness<FitnessTraits>& fitness)
|
||||
{
|
||||
for (unsigned i = 0; i < fitness.size(); ++i)
|
||||
{
|
||||
os << fitness[i] << ' ';
|
||||
}
|
||||
return os;
|
||||
}
|
||||
|
||||
template <class FitnessTraits>
|
||||
std::istream& operator>>(std::istream& is, eoParetoFitness<FitnessTraits>& fitness)
|
||||
{
|
||||
fitness = eoParetoFitness<FitnessTraits>();
|
||||
for (unsigned i = 0; i < fitness.size(); ++i)
|
||||
{
|
||||
is >> fitness[i];
|
||||
}
|
||||
return is;
|
||||
}
|
||||
|
||||
#endif
|
||||
71
trunk/paradiseo-eo/src/eoParetoRanking.h
Normal file
71
trunk/paradiseo-eo/src/eoParetoRanking.h
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoParetoRanking.h
|
||||
(c) Maarten Keijzer, Marc Schoenauer, 2001
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoParetoRanking_h
|
||||
#define eoParetoRanking_h
|
||||
|
||||
#include <eoPerf2Worth.h>
|
||||
#include <eoDominanceMap.h>
|
||||
|
||||
/**
|
||||
Straightforward pareto ranking. Every individual gets a rank according to the number
|
||||
of elements it dominates. Note that without niching, this technique will usually not
|
||||
find the whole front of non-dominated solutions, but will quite likely converge
|
||||
on a single spot on the front.
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoParetoRanking : public eoPerf2WorthCached<EOT, double>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoPerf2WorthCached<EOT, double>::value;
|
||||
|
||||
eoParetoRanking(eoDominanceMap<EOT>& _dominanceMap)
|
||||
: eoPerf2WorthCached<EOT, double>(), dominanceMap(_dominanceMap)
|
||||
{}
|
||||
|
||||
void calculate_worths(const eoPop<EOT>& _pop)
|
||||
{
|
||||
dominanceMap(_pop);
|
||||
value() = dominanceMap.sum_dominators(); // get rank: 0 means part of current front
|
||||
|
||||
// calculate maximum
|
||||
double maxim = *std::max_element(value().begin(), value().end());
|
||||
|
||||
// higher is better, so invert the value
|
||||
for (unsigned i = 0; i < value().size(); ++i)
|
||||
{
|
||||
value()[i] = maxim - value()[i];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private :
|
||||
|
||||
eoDominanceMap<EOT>& dominanceMap;
|
||||
};
|
||||
|
||||
#endif
|
||||
247
trunk/paradiseo-eo/src/eoPerf2Worth.h
Normal file
247
trunk/paradiseo-eo/src/eoPerf2Worth.h
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoPerf2Worth.h
|
||||
(c) Maarten Keijzer, Marc Schoenauer, 2001
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoPerf2Worth_h
|
||||
#define eoPerf2Worth_h
|
||||
|
||||
#include <utils/eoParam.h>
|
||||
#include <eoPop.h>
|
||||
#include <eoFunctor.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
/** @brief Base class to transform raw fitnesses into fitness for selection
|
||||
|
||||
@see eoSelectFromWorth
|
||||
*/
|
||||
template <class EOT, class WorthT = double>
|
||||
class eoPerf2Worth : public eoUF<const eoPop<EOT>&, void>, public eoValueParam<std::vector<WorthT> >
|
||||
{
|
||||
public:
|
||||
|
||||
using eoValueParam<std::vector<WorthT> >::value;
|
||||
|
||||
/** @brief default constructor */
|
||||
eoPerf2Worth(std::string _description = "Worths")
|
||||
: eoValueParam<std::vector<WorthT> >(std::vector<WorthT>(0), _description)
|
||||
{}
|
||||
|
||||
/** Sort population according to worth, will keep the worths and
|
||||
fitness_cache in sync with the population. */
|
||||
virtual void sort_pop(eoPop<EOT>& _pop)
|
||||
{ // start with a std::vector of indices
|
||||
std::vector<unsigned> indices(_pop.size());
|
||||
|
||||
unsigned i;
|
||||
for (i = 0; i < _pop.size();++i)
|
||||
{ // could use generate, but who cares
|
||||
indices[i] = i;
|
||||
}
|
||||
|
||||
std::sort(indices.begin(), indices.end(), compare_worth(value()));
|
||||
|
||||
eoPop<EOT> tmp_pop;
|
||||
tmp_pop.resize(_pop.size());
|
||||
std::vector<WorthT> tmp_worths(value().size());
|
||||
|
||||
for (i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
tmp_pop[i] = _pop[indices[i]];
|
||||
tmp_worths[i] = value()[indices[i]];
|
||||
}
|
||||
|
||||
std::swap(_pop, tmp_pop);
|
||||
std::swap(value(), tmp_worths);
|
||||
}
|
||||
|
||||
/** helper class used to sort indices into populations/worths */
|
||||
class compare_worth
|
||||
{
|
||||
public:
|
||||
|
||||
compare_worth(const std::vector<WorthT>& _worths) : worths(_worths) {}
|
||||
|
||||
bool operator()(unsigned a, unsigned b) const {
|
||||
return worths[b] < worths[a]; // sort in descending (!) order
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
const std::vector<WorthT>& worths;
|
||||
};
|
||||
|
||||
|
||||
|
||||
virtual void resize(eoPop<EOT>& _pop, unsigned sz) {
|
||||
_pop.resize(sz);
|
||||
value().resize(sz);
|
||||
};
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
Perf2Worth with fitness cache
|
||||
*/
|
||||
template <class EOT, class WorthT = typename EOT::Fitness>
|
||||
class eoPerf2WorthCached : public eoPerf2Worth<EOT, WorthT>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoPerf2Worth<EOT, WorthT>::value;
|
||||
|
||||
eoPerf2WorthCached(std::string _description = "Worths") : eoPerf2Worth<EOT, WorthT>(_description) {}
|
||||
|
||||
|
||||
/**
|
||||
Implementation of the operator(), updating a cache of fitnesses. Calls the virtual function
|
||||
calculate_worths when one of the fitnesses has changed. It is not virtual, but derived classes
|
||||
can remove the fitness caching trough the third template element
|
||||
*/
|
||||
void operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
unsigned i;
|
||||
if (fitness_cache.size() == _pop.size())
|
||||
{
|
||||
bool in_sync = true;
|
||||
for (i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
if (fitness_cache[i] != _pop[i].fitness())
|
||||
{
|
||||
in_sync = false;
|
||||
fitness_cache[i] = _pop[i].fitness();
|
||||
}
|
||||
}
|
||||
|
||||
if (in_sync)
|
||||
{ // worths are up to date
|
||||
return;
|
||||
}
|
||||
}
|
||||
else // just cache the fitness
|
||||
{
|
||||
fitness_cache.resize(_pop.size());
|
||||
for (i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
fitness_cache[i] = _pop[i].fitness();
|
||||
}
|
||||
}
|
||||
|
||||
// call derived implementation of perf2worth mapping
|
||||
calculate_worths(_pop);
|
||||
}
|
||||
|
||||
/** The actual virtual function the derived classes should implement*/
|
||||
virtual void calculate_worths(const eoPop<EOT>& _pop) = 0;
|
||||
|
||||
/**
|
||||
Sort population according to worth, will keep the worths and fitness_cache in sync with the population.
|
||||
*/
|
||||
virtual void sort_pop(eoPop<EOT>& _pop)
|
||||
{ // start with a std::vector of indices
|
||||
std::vector<unsigned> indices(_pop.size());
|
||||
|
||||
unsigned i;
|
||||
for (i = 0; i < _pop.size();++i)
|
||||
{ // could use generate, but who cares
|
||||
indices[i] = i;
|
||||
}
|
||||
|
||||
std::sort(indices.begin(), indices.end(), compare_worth(value()));
|
||||
|
||||
eoPop<EOT> tmp_pop;
|
||||
tmp_pop.resize(_pop.size());
|
||||
std::vector<WorthT> tmp_worths(value().size());
|
||||
|
||||
#ifdef _MSC_VER
|
||||
std::vector<EOT::Fitness> tmp_cache(_pop.size());
|
||||
#else
|
||||
std::vector<typename EOT::Fitness> tmp_cache(_pop.size());
|
||||
#endif
|
||||
for (i = 0; i < _pop.size(); ++i)
|
||||
{
|
||||
tmp_pop[i] = _pop[indices[i]];
|
||||
tmp_worths[i] = value()[indices[i]];
|
||||
|
||||
tmp_cache[i] = fitness_cache[indices[i]];
|
||||
}
|
||||
|
||||
std::swap(_pop, tmp_pop);
|
||||
std::swap(value(), tmp_worths);
|
||||
std::swap(fitness_cache, tmp_cache);
|
||||
}
|
||||
|
||||
/** helper class used to sort indices into populations/worths
|
||||
*/
|
||||
class compare_worth
|
||||
{
|
||||
public :
|
||||
compare_worth(const std::vector<WorthT>& _worths) : worths(_worths) {}
|
||||
|
||||
bool operator()(unsigned a, unsigned b) const
|
||||
{
|
||||
return worths[b] < worths[a]; // sort in descending (!) order
|
||||
}
|
||||
|
||||
private :
|
||||
|
||||
const std::vector<WorthT>& worths;
|
||||
};
|
||||
|
||||
virtual void resize(eoPop<EOT>& _pop, unsigned sz)
|
||||
{
|
||||
_pop.resize(sz);
|
||||
value().resize(sz);
|
||||
fitness_cache.resize(sz);
|
||||
}
|
||||
|
||||
private :
|
||||
std::vector <typename EOT::Fitness> fitness_cache;
|
||||
};
|
||||
|
||||
|
||||
|
||||
/** A dummy perf2worth, just in case you need it */
|
||||
template <class EOT>
|
||||
class eoNoPerf2Worth : public eoPerf2Worth<EOT, typename EOT::Fitness>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoValueParam< EOT >::value;
|
||||
|
||||
// default behaviour, just copy fitnesses
|
||||
void operator()(const eoPop<EOT>& _pop) {
|
||||
unsigned i;
|
||||
value().resize(_pop.size());
|
||||
for (i = 0; i < _pop.size(); ++i)
|
||||
value()[i]=_pop[i];
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
63
trunk/paradiseo-eo/src/eoPeriodicContinue.h
Normal file
63
trunk/paradiseo-eo/src/eoPeriodicContinue.h
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
// "eoFreqContinue.h"
|
||||
|
||||
// (c) OPAC Team, LIFL, Feb. 2006
|
||||
|
||||
/* 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: cahon@lifl.fr
|
||||
*/
|
||||
|
||||
#ifndef __eoPeriodicContinue_h
|
||||
#define __eoPeriodicContinue_h
|
||||
|
||||
#include <eoContinue.h>
|
||||
#include <eoPop.h>
|
||||
|
||||
template <class EOT> class eoPeriodicContinue: public eoContinue <EOT> {
|
||||
|
||||
public:
|
||||
|
||||
/** Constructor. The period is given in parameter. */
|
||||
eoPeriodicContinue (unsigned __period, unsigned __init_counter = 0);
|
||||
|
||||
/** It returns 'true' only if the current number of generations modulo
|
||||
the period doen't equal to zero. */
|
||||
bool operator () (const eoPop <EOT> & pop);
|
||||
|
||||
private:
|
||||
|
||||
unsigned period;
|
||||
|
||||
unsigned counter;
|
||||
|
||||
};
|
||||
|
||||
template <class EOT>
|
||||
eoPeriodicContinue <EOT> :: eoPeriodicContinue (unsigned __period, unsigned __init_counter
|
||||
) : period (__period),
|
||||
counter (__init_counter) {
|
||||
|
||||
}
|
||||
|
||||
template <class EOT>
|
||||
bool eoPeriodicContinue <EOT> :: operator () (const eoPop <EOT> & __pop) {
|
||||
|
||||
return ((++ counter) % period) != 0 ;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
15
trunk/paradiseo-eo/src/eoPersistent.cpp
Normal file
15
trunk/paradiseo-eo/src/eoPersistent.cpp
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <eoPersistent.h>
|
||||
|
||||
//Implementation of these objects
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
std::istream & operator >> ( std::istream& _is, eoPersistent& _o ) {
|
||||
_o.readFrom(_is);
|
||||
return _is;
|
||||
};
|
||||
72
trunk/paradiseo-eo/src/eoPersistent.h
Normal file
72
trunk/paradiseo-eo/src/eoPersistent.h
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
// eoPersistent.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 EOPERSISTENT_H
|
||||
#define EOPERSISTENT_H
|
||||
|
||||
/// @name variables Some definitions of variables used throughout the program
|
||||
//@{
|
||||
/// max length to store stuff read
|
||||
const unsigned MAXLINELENGTH=1024;
|
||||
//@}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <iostream> // std::istream, std::ostream
|
||||
#include <string> // para std::string
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include "eoPrintable.h"
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoPersistent
|
||||
//-----------------------------------------------------------------------------
|
||||
/**
|
||||
An persistent object that knows how to write (through functions inherited from
|
||||
#eoPrintable#) and read itself
|
||||
*/
|
||||
class eoPersistent: public eoPrintable
|
||||
{
|
||||
public:
|
||||
/// Virtual dtor. They are needed in virtual class hierarchies.
|
||||
virtual ~eoPersistent() {}
|
||||
|
||||
/**
|
||||
* Read object.
|
||||
* @param _is A std::istream.
|
||||
* @throw runtime_std::exception If a valid object can't be read.
|
||||
*/
|
||||
virtual void readFrom(std::istream& _is) = 0;
|
||||
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
///Standard input for all objects in the EO hierarchy
|
||||
std::istream & operator >> ( std::istream& _is, eoPersistent& _o );
|
||||
|
||||
#endif
|
||||
|
||||
304
trunk/paradiseo-eo/src/eoPop.h
Normal file
304
trunk/paradiseo-eo/src/eoPop.h
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoPop.h
|
||||
// (c) GeNeura Team, 1998
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _EOPOP_H
|
||||
#define _EOPOP_H
|
||||
|
||||
#include <algorithm>
|
||||
#include <iostream>
|
||||
#include <iterator> // needed for GCC 3.2
|
||||
#include <vector>
|
||||
|
||||
// EO includes
|
||||
#include <eoOp.h> // for eoInit
|
||||
#include <eoPersistent.h>
|
||||
#include <eoInit.h>
|
||||
#include <utils/rnd_generators.h> // for shuffle method
|
||||
|
||||
/** A std::vector of EO object, to be used in all algorithms
|
||||
* (selectors, operators, replacements, ...).
|
||||
*
|
||||
* We have no idea if a population can be
|
||||
* some other thing that a std::vector, but if somebody thinks of it, this concrete
|
||||
* implementation can be moved to "generic" and an abstract Population
|
||||
* interface be provided.
|
||||
*
|
||||
* The template can be instantiated with anything that accepts a "size"
|
||||
* and eoInit derived object. in the ctor.
|
||||
* EOT must also have a copy ctor, since temporaries are created and then
|
||||
* passed to the eoInit object
|
||||
*/
|
||||
|
||||
template<class EOT>
|
||||
class eoPop: public std::vector<EOT>, public eoObject, public eoPersistent
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
using std::vector<EOT>::size;
|
||||
using std::vector<EOT>::resize;
|
||||
using std::vector<EOT>::operator[];
|
||||
using std::vector<EOT>::begin;
|
||||
using std::vector<EOT>::end;
|
||||
|
||||
typedef typename EOT::Fitness Fitness;
|
||||
/** Default ctor. Creates empty pop
|
||||
*/
|
||||
eoPop() : std::vector<EOT>(), eoObject(), eoPersistent() {};
|
||||
|
||||
/** Ctor for the initialization of chromosomes
|
||||
|
||||
@param _popSize total population size
|
||||
@param _chromInit Initialization routine, produces EO's, needs to be an eoInit
|
||||
*/
|
||||
eoPop( unsigned _popSize, eoInit<EOT>& _chromInit )
|
||||
:std::vector<EOT>()
|
||||
{
|
||||
resize(_popSize);
|
||||
for ( unsigned i = 0; i < _popSize; i++ )
|
||||
{
|
||||
_chromInit(operator[](i));
|
||||
}
|
||||
};
|
||||
|
||||
/** appstd::ends random guys at end of pop.
|
||||
Can be used to initialize it pop is empty
|
||||
|
||||
@param _popSize total population size
|
||||
@param _chromInit Initialization routine, produces EO's, needs to be an eoInit
|
||||
*/
|
||||
void append( unsigned _newPopSize, eoInit<EOT>& _chromInit )
|
||||
{
|
||||
unsigned oldSize = size();
|
||||
if (_newPopSize < oldSize)
|
||||
{
|
||||
throw std::runtime_error("New size smaller than old size in pop.append");
|
||||
return;
|
||||
}
|
||||
if (_newPopSize == oldSize)
|
||||
return;
|
||||
resize(_newPopSize); // adjust the size
|
||||
for ( unsigned i = oldSize; i < _newPopSize; i++ )
|
||||
{
|
||||
_chromInit(operator[](i));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** Ctor from an std::istream; reads the population from a stream,
|
||||
each element should be in different lines
|
||||
@param _is the stream
|
||||
*/
|
||||
eoPop( std::istream& _is ) :std::vector<EOT>() {
|
||||
readFrom( _is );
|
||||
}
|
||||
|
||||
/** Empty Dtor */
|
||||
virtual ~eoPop() {};
|
||||
|
||||
|
||||
/// helper struct for getting a pointer
|
||||
struct Ref { const EOT* operator()(const EOT& eot) { return &eot;}};
|
||||
/// helper struct for comparing on pointers
|
||||
struct Cmp {
|
||||
bool operator()(const EOT* a, const EOT* b) const
|
||||
{ return b->operator<(*a); }
|
||||
};
|
||||
|
||||
/**
|
||||
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(), std::greater<EOT>());
|
||||
}
|
||||
|
||||
/** creates a std::vector<EOT*> pointing to the individuals in descending order */
|
||||
void sort(std::vector<const EOT*>& result) const
|
||||
{
|
||||
result.resize(size());
|
||||
|
||||
std::transform(begin(), end(), result.begin(), Ref());
|
||||
|
||||
std::sort(result.begin(), result.end(), Cmp());
|
||||
}
|
||||
|
||||
/**
|
||||
shuffle the population. Use this member to put the population
|
||||
in random order
|
||||
*/
|
||||
void shuffle(void)
|
||||
{
|
||||
UF_random_generator<unsigned int> gen;
|
||||
std::random_shuffle(begin(), end(), gen);
|
||||
}
|
||||
|
||||
/** creates a std::vector<EOT*> pointing to the individuals in random order */
|
||||
void shuffle(std::vector<const EOT*>& result) const
|
||||
{
|
||||
result.resize(size());
|
||||
|
||||
std::transform(begin(), end(), result.begin(), Ref());
|
||||
|
||||
UF_random_generator<unsigned int> gen;
|
||||
std::random_shuffle(result.begin(), result.end(), gen);
|
||||
}
|
||||
|
||||
/** returns an iterator to the best individual DOES NOT MOVE ANYBODY */
|
||||
typename eoPop<EOT>::iterator it_best_element()
|
||||
{
|
||||
typename eoPop<EOT>::iterator it = std::max_element(begin(), end());
|
||||
return it;
|
||||
}
|
||||
|
||||
/** returns an iterator to the best individual DOES NOT MOVE ANYBODY */
|
||||
const EOT & best_element() const
|
||||
{
|
||||
typename eoPop<EOT>::const_iterator it = std::max_element(begin(), end());
|
||||
return (*it);
|
||||
}
|
||||
|
||||
/** returns a const reference to the worse individual DOES NOT MOVE ANYBODY */
|
||||
const EOT & worse_element() const
|
||||
{
|
||||
typename eoPop<EOT>::const_iterator it = std::min_element(begin(), end());
|
||||
return (*it);
|
||||
}
|
||||
|
||||
/** returns an iterator to the worse individual DOES NOT MOVE ANYBODY */
|
||||
typename eoPop<EOT>::iterator it_worse_element()
|
||||
{
|
||||
typename eoPop<EOT>::iterator it = std::min_element(begin(), end());
|
||||
return it;
|
||||
}
|
||||
|
||||
/**
|
||||
slightly faster algorithm than sort to find all individuals that are better
|
||||
than the nth individual. INDIVIDUALS ARE MOVED AROUND in the pop.
|
||||
*/
|
||||
typename eoPop<EOT>::iterator nth_element(int nth)
|
||||
{
|
||||
typename eoPop<EOT>::iterator it = begin() + nth;
|
||||
std::nth_element(begin(), it, end(), std::greater<EOT>());
|
||||
return it;
|
||||
}
|
||||
|
||||
struct GetFitness { Fitness operator()(const EOT& _eo) const { return _eo.fitness(); } };
|
||||
|
||||
/** returns the fitness of the nth element */
|
||||
Fitness nth_element_fitness(int which) const
|
||||
{ // probably not the fastest way to do this, but what the heck
|
||||
|
||||
std::vector<Fitness> fitness(size());
|
||||
std::transform(begin(), end(), fitness.begin(), GetFitness());
|
||||
|
||||
typename std::vector<Fitness>::iterator it = fitness.begin() + which;
|
||||
std::nth_element(fitness.begin(), it, fitness.end(), std::greater<Fitness>());
|
||||
return *it;
|
||||
}
|
||||
|
||||
/** const nth_element function, returns pointers to sorted individuals
|
||||
* up the the nth
|
||||
*/
|
||||
void nth_element(int which, std::vector<const EOT*>& result) const
|
||||
{
|
||||
|
||||
result.resize(size());
|
||||
std::transform(begin(), end(), result.begin(), Ref());
|
||||
|
||||
typename std::vector<const EOT*>::iterator it = result.begin() + which;
|
||||
|
||||
std::nth_element(result.begin(), it, result.end(), Cmp());
|
||||
}
|
||||
|
||||
/** does STL swap with other pop */
|
||||
void swap(eoPop<EOT>& other)
|
||||
{
|
||||
std::swap(static_cast<std::vector<EOT>& >(*this), static_cast<std::vector<EOT>& >(other));
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints sorted pop but does NOT modify it!
|
||||
*
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void sortedPrintOn(std::ostream& _os) const
|
||||
{
|
||||
std::vector<const EOT*> result;
|
||||
sort(result);
|
||||
_os << size() << '\n';
|
||||
for (unsigned i = 0; i < size(); ++i)
|
||||
{
|
||||
_os << *result[i] << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write object. It's called printOn since it prints the object _on_ a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const
|
||||
{
|
||||
_os << size() << '\n';
|
||||
std::copy( begin(), end(), std::ostream_iterator<EOT>( _os, "\n") );
|
||||
}
|
||||
|
||||
/** @name Methods from eoObject */
|
||||
//@{
|
||||
/**
|
||||
* Read object. The EOT class must have a ctor from a stream;
|
||||
* @param _is A std::istream.
|
||||
*/
|
||||
virtual void readFrom(std::istream& _is)
|
||||
{
|
||||
size_t sz;
|
||||
_is >> sz;
|
||||
|
||||
resize(sz);
|
||||
|
||||
for (size_t i = 0; i < sz; ++i) {
|
||||
operator[](i).readFrom( _is );
|
||||
}
|
||||
}
|
||||
|
||||
/** Inherited from eoObject. Returns the class name.
|
||||
@see eoObject
|
||||
*/
|
||||
virtual std::string className() const {return "eoPop";};
|
||||
//@}
|
||||
|
||||
virtual void invalidate()
|
||||
{
|
||||
for (unsigned i=0; i<size(); i++)
|
||||
this->operator[](i).invalidate();
|
||||
}
|
||||
|
||||
|
||||
protected:
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
17
trunk/paradiseo-eo/src/eoPopAlgo.h
Normal file
17
trunk/paradiseo-eo/src/eoPopAlgo.h
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
#ifndef eoPopAlgo_h
|
||||
#define eoPopAlgo_h
|
||||
|
||||
#include <eoPop.h>
|
||||
#include <eoFunctor.h>
|
||||
|
||||
/**
|
||||
For all "population transforming" algos ...
|
||||
*/
|
||||
|
||||
template <class EOT> class eoPopAlgo : public eoUF <eoPop <EOT> &, void> {
|
||||
|
||||
} ;
|
||||
|
||||
#endif
|
||||
101
trunk/paradiseo-eo/src/eoPopEvalFunc.h
Normal file
101
trunk/paradiseo-eo/src/eoPopEvalFunc.h
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoPopEvalFunc.h
|
||||
Abstract class for global evaluation of the population
|
||||
|
||||
(c) 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 eoPopEvalFunc_H
|
||||
#define eoPopEvalFunc_H
|
||||
|
||||
#include <eoEvalFunc.h>
|
||||
#include <apply.h>
|
||||
|
||||
/** eoPopEvalFunc: This abstract class is for GLOBAL evaluators
|
||||
* of a population after variation.
|
||||
* It takes 2 populations (typically the parents and the offspring)
|
||||
* and is suppposed to evaluate them alltogether
|
||||
*
|
||||
* Basic use: apply an embedded eoEvalFunc to the offspring
|
||||
*
|
||||
* Time-varying fitness: apply the embedded eoEvalFunc to both
|
||||
* offspring and parents
|
||||
*
|
||||
* Advanced uses: Co-evolution or "parisian" approach, or ...
|
||||
*
|
||||
* Basic parallelization (synchronous standard evolution engine):
|
||||
* call the slaves and wait for the results
|
||||
*/
|
||||
template<class EOT>
|
||||
class eoPopEvalFunc : public eoBF<eoPop<EOT> & , eoPop<EOT> &, void>
|
||||
{};
|
||||
|
||||
/////////////////////////////////////////////////////////////
|
||||
// eoPopLoopEval
|
||||
/////////////////////////////////////////////////////////////
|
||||
|
||||
/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies
|
||||
* a private eoEvalFunc to all offspring
|
||||
*/
|
||||
template<class EOT>
|
||||
class eoPopLoopEval : public eoPopEvalFunc<EOT> {
|
||||
public:
|
||||
/** Ctor: set value of embedded eoEvalFunc */
|
||||
eoPopLoopEval(eoEvalFunc<EOT> & _eval) : eval(_eval) {}
|
||||
|
||||
/** Do the job: simple loop over the offspring */
|
||||
void operator()(eoPop<EOT> & _parents, eoPop<EOT> & _offspring)
|
||||
{
|
||||
apply<EOT>(eval, _offspring);
|
||||
}
|
||||
|
||||
private:
|
||||
eoEvalFunc<EOT> & eval;
|
||||
};
|
||||
|
||||
/////////////////////////////////////////////////////////////
|
||||
// eoTimeVaryingLoopEval
|
||||
/////////////////////////////////////////////////////////////
|
||||
|
||||
/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies
|
||||
* a private eoEvalFunc to all offspring AND ALL PARENTS
|
||||
* as the fitness is supposed here to vary
|
||||
*/
|
||||
template<class EOT>
|
||||
class eoTimeVaryingLoopEval : public eoPopEvalFunc<EOT> {
|
||||
public:
|
||||
/** Ctor: set value of embedded eoEvalFunc */
|
||||
eoTimeVaryingLoopEval(eoEvalFunc<EOT> & _eval) : eval(_eval) {}
|
||||
|
||||
/** Do the job: simple loop over the offspring */
|
||||
void operator()(eoPop<EOT> & _parents, eoPop<EOT> & _offspring)
|
||||
{
|
||||
apply<EOT>(eval, _parents);
|
||||
apply<EOT>(eval, _offspring);
|
||||
}
|
||||
|
||||
private:
|
||||
eoEvalFunc<EOT> & eval;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
208
trunk/paradiseo-eo/src/eoPopulator.h
Normal file
208
trunk/paradiseo-eo/src/eoPopulator.h
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoPopulator.h
|
||||
// (c) Maarten Keijzer and Marc Schoenauer, 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: mkeijzer@dhi.dk
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoPopulator_H
|
||||
#define _eoPopulator_H
|
||||
|
||||
#include <eoPop.h>
|
||||
#include <eoSelectOne.h>
|
||||
|
||||
/** eoPopulator is a helper class for general operators eoGenOp
|
||||
It is an eoPop but also behaves like an eoPop::iterator
|
||||
as far as operator* and operator++ are concerned
|
||||
|
||||
See eoGenOp and eoOpContainer
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoPopulator
|
||||
{
|
||||
public :
|
||||
|
||||
eoPopulator(const eoPop<EOT>& _src, eoPop<EOT>& _dest) : dest(_dest), current(dest.end()), src(_src)
|
||||
{
|
||||
dest.reserve(src.size()); // we don't know this, but wth.
|
||||
current = dest.end();
|
||||
}
|
||||
|
||||
/** @brief Virtual Constructor */
|
||||
virtual ~eoPopulator() {};
|
||||
|
||||
struct OutOfIndividuals {};
|
||||
|
||||
/** a populator behaves like an iterator. Hence the operator*
|
||||
* it returns the current individual -- eventually getting
|
||||
* a new one through the operator++ if at the end
|
||||
*/
|
||||
EOT& operator*(void)
|
||||
{
|
||||
if (current == dest.end())
|
||||
get_next(); // get a new individual
|
||||
|
||||
return *current;
|
||||
}
|
||||
|
||||
/** only prefix increment defined
|
||||
Does not add a new element when at the end, use operator* for that
|
||||
If not on the end, increment the pointer to the next individual
|
||||
*/
|
||||
eoPopulator& operator++()
|
||||
{
|
||||
if (current == dest.end())
|
||||
{ // keep the pointer there
|
||||
return *this;
|
||||
}
|
||||
// else
|
||||
++current;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** mandatory for operators that generate more offspring than parents
|
||||
* if such a thing exists ?
|
||||
*/
|
||||
void insert(const EOT& _eo)
|
||||
{ /* not really efficient, but its nice to have */
|
||||
current = dest.insert(current, _eo);
|
||||
}
|
||||
|
||||
/** just to make memory mangement more efficient
|
||||
*/
|
||||
void reserve(int how_many)
|
||||
{
|
||||
size_t sz = current - dest.begin();
|
||||
if (dest.capacity() < dest.size() + how_many)
|
||||
{
|
||||
dest.reserve(dest.size() + how_many);
|
||||
}
|
||||
|
||||
current = dest.begin() + sz;
|
||||
}
|
||||
|
||||
/** can be useful for operators with embedded selectors
|
||||
* e.g. your brain and my beauty -type
|
||||
*/
|
||||
const eoPop<EOT>& source(void) { return src; }
|
||||
|
||||
/** Get the offspring population.
|
||||
Can be useful when you want to do some online niching kind of thing
|
||||
*/
|
||||
eoPop<EOT>& offspring(void) { return dest; }
|
||||
|
||||
typedef unsigned position_type;
|
||||
|
||||
/** this is a direct access container: tell position */
|
||||
position_type tellp() { return current - dest.begin(); }
|
||||
/** this is a direct access container: go to position */
|
||||
void seekp(position_type pos) { current = dest.begin() + pos; }
|
||||
/** no more individuals */
|
||||
bool exhausted(void) { return current == dest.end(); }
|
||||
|
||||
/** the pure virtual selection method - will be instanciated in
|
||||
* eoSeqPopulator and eoSelectivePopulator
|
||||
*/
|
||||
virtual const EOT& select() = 0;
|
||||
|
||||
protected:
|
||||
eoPop<EOT>& dest;
|
||||
typename eoPop<EOT>::iterator current;
|
||||
const eoPop<EOT>& src;
|
||||
|
||||
private:
|
||||
|
||||
void get_next() {
|
||||
if(current == dest.end())
|
||||
{ // get new individual from derived class select()
|
||||
dest.push_back(select());
|
||||
current = dest.end();
|
||||
--current;
|
||||
return;
|
||||
}
|
||||
// else
|
||||
++current;
|
||||
return;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
/** SeqPopulator: an eoPopulator that sequentially goes through the
|
||||
population is supposed to be used after a batch select of a whole
|
||||
bunch or genitors
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoSeqPopulator : public eoPopulator<EOT>
|
||||
{
|
||||
public:
|
||||
|
||||
using eoPopulator< EOT >::src;
|
||||
|
||||
eoSeqPopulator(const eoPop<EOT>& _pop, eoPop<EOT>& _dest) :
|
||||
eoPopulator<EOT>(_pop, _dest), current(0) {}
|
||||
|
||||
/** the select method simply returns next individual in the src pop */
|
||||
const EOT& select(void) {
|
||||
if(current >= eoPopulator< EOT >::src.size()) {
|
||||
throw OutOfIndividuals();
|
||||
}
|
||||
|
||||
const EOT& res = src[current++];
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
|
||||
struct OutOfIndividuals {};
|
||||
|
||||
unsigned current;
|
||||
};
|
||||
|
||||
|
||||
/** SelectivePopulator an eoPoplator that uses an eoSelectOne to select guys.
|
||||
Supposedly, it is passed the initial population.
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoSelectivePopulator : public eoPopulator<EOT>
|
||||
{
|
||||
public :
|
||||
|
||||
using eoPopulator< EOT >::src;
|
||||
|
||||
eoSelectivePopulator(const eoPop<EOT>& _pop, eoPop<EOT>& _dest, eoSelectOne<EOT>& _sel)
|
||||
: eoPopulator<EOT>(_pop, _dest), sel(_sel)
|
||||
{ sel.setup(_pop); };
|
||||
|
||||
/** the select method actually selects one guy from the src pop */
|
||||
const EOT& select() {
|
||||
return sel(src);
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
|
||||
eoSelectOne<EOT>& sel;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
22
trunk/paradiseo-eo/src/eoPrintable.cpp
Normal file
22
trunk/paradiseo-eo/src/eoPrintable.cpp
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoPrintable.cpp
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <eoPrintable.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
//Implementation of these objects
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
std::ostream & operator << ( std::ostream& _os, const eoPrintable& _o ) {
|
||||
_o.printOn(_os);
|
||||
return _os;
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
61
trunk/paradiseo-eo/src/eoPrintable.h
Normal file
61
trunk/paradiseo-eo/src/eoPrintable.h
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoPrintable.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 EOPRINTABLE_H
|
||||
#define EOPRINTABLE_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <iostream> // std::istream, std::ostream
|
||||
#include <string> // para std::string
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoPrintable
|
||||
//-----------------------------------------------------------------------------
|
||||
/**
|
||||
Base class for objects that can print themselves
|
||||
(#printOn#). Besides, this file defines the standard output for all the objects;
|
||||
if the objects define printOn there's no need to define #operator <<#.\\
|
||||
This functionality was separated from eoObject, since it makes no sense to print
|
||||
some objects (for instance, a #eoFactory# or a random number generator.
|
||||
*/
|
||||
class eoPrintable
|
||||
{
|
||||
public:
|
||||
/// Virtual dtor. They are needed in virtual class hierarchies.
|
||||
virtual ~eoPrintable() {}
|
||||
|
||||
/**
|
||||
* Write object. It's called printOn since it prints the object on a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const = 0;
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
///Standard output for all objects in the EO hierarchy
|
||||
std::ostream & operator << ( std::ostream& _os, const eoPrintable& _o );
|
||||
|
||||
#endif
|
||||
|
||||
87
trunk/paradiseo-eo/src/eoPropGAGenOp.h
Normal file
87
trunk/paradiseo-eo/src/eoPropGAGenOp.h
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoPropGAGenOp.h
|
||||
// (c) Marc.Schoenauer 2005
|
||||
/*
|
||||
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@inria.fr
|
||||
mak@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoPropGAGenOp_h
|
||||
#define _eoPropGAGenOp_h
|
||||
|
||||
#include "eoGenOp.h"
|
||||
#include "eoInvalidateOps.h"
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// class eoSGAGenOp
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/** ***************************************************************************
|
||||
* eoPropGAGenOp (for Simple GA, but Proportional)
|
||||
* choice between Crossover, mutation or cloining
|
||||
* with respect to given relatve weights
|
||||
*****************************************************************************/
|
||||
template<class EOT>
|
||||
class eoPropGAGenOp : public eoGenOp<EOT>
|
||||
{
|
||||
public:
|
||||
|
||||
/** Ctor from
|
||||
* * weight of clone
|
||||
* * crossover (with weight)
|
||||
* * mutation (with weight)
|
||||
*/
|
||||
eoPropGAGenOp(double _wClone, eoQuadOp<EOT>& _cross, double _wCross,
|
||||
eoMonOp<EOT>& _mut, double _wMut)
|
||||
: wClone(_wClone),
|
||||
cross(_cross),
|
||||
wCross(_wCross),
|
||||
mut(_mut),
|
||||
wMut(_wMut)
|
||||
{
|
||||
propOp.add(cross, wCross); // the crossover - with weight wCross
|
||||
propOp.add(mut, wMut); // mutation with weight wMut
|
||||
propOp.add(monClone, wClone);
|
||||
}
|
||||
|
||||
/** do the job: delegate to op */
|
||||
virtual void apply(eoPopulator<EOT>& _pop)
|
||||
{
|
||||
propOp.apply(_pop);
|
||||
}
|
||||
|
||||
/** inherited from eoGenOp */
|
||||
virtual unsigned max_production(void) {return 2;}
|
||||
|
||||
virtual std::string className() const {return "eoPropGAGenOp";}
|
||||
|
||||
|
||||
private:
|
||||
double wClone;
|
||||
eoQuadOp<EOT> ✗ // eoInvalidateXXX take the boolean output
|
||||
double wCross;
|
||||
eoMonOp<EOT> & mut; // of the XXX op and invalidate the EOT
|
||||
double wMut;
|
||||
eoProportionalOp<EOT> propOp;
|
||||
eoMonCloneOp<EOT> monClone;
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
210
trunk/paradiseo-eo/src/eoProportionalCombinedOp.h
Normal file
210
trunk/paradiseo-eo/src/eoProportionalCombinedOp.h
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoCombinedOp.h
|
||||
// (c) GeNeura Team, 1998, Marc Schoenauer, 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 _eoCombinedOp_H
|
||||
#define _eoCombinedOp_H
|
||||
|
||||
#include <eoObject.h>
|
||||
#include <eoPrintable.h>
|
||||
#include <eoFunctor.h>
|
||||
#include <eoOp.h>
|
||||
#include <utils/eoRNG.h>
|
||||
/**
|
||||
\defgroup PropCombinedOperators
|
||||
Combination of same-type Genetic Operators - Proportional choice
|
||||
*/
|
||||
|
||||
/** @name PropCombined Genetic operators
|
||||
|
||||
This files contains the classes eoPropCombinedXXXOp (XXX in {Mon, Bin, Quad})
|
||||
that allow to use more than a single operator of a specific class
|
||||
into an algorithm, chosing by a roulette wheel based on user-defined rates
|
||||
|
||||
@author Marc Schoenauer
|
||||
@version 0.1
|
||||
*/
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
//// combined MonOp
|
||||
//////////////////////////////////////////////////////
|
||||
|
||||
/** eoMonOp is the monary operator: genetic operator that takes only one EO
|
||||
|
||||
* now accepts generic operators
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoPropCombinedMonOp: public eoMonOp<EOT>
|
||||
{
|
||||
public:
|
||||
/// Ctor from a "true" operator
|
||||
eoPropCombinedMonOp(eoMonOp<EOT> & _first, const double _rate)
|
||||
{
|
||||
ops.push_back(&_first);
|
||||
rates.push_back(_rate);
|
||||
}
|
||||
|
||||
virtual std::string className() const { return "eoPropCombinedMonOp"; }
|
||||
|
||||
virtual void add(eoMonOp<EOT> & _op, const double _rate, bool _verbose=false)
|
||||
{
|
||||
ops.push_back(&_op);
|
||||
rates.push_back(_rate);
|
||||
// compute the relative rates in percent - to warn the user!
|
||||
if (_verbose)
|
||||
printOn(std::cout);
|
||||
}
|
||||
|
||||
// outputs the operators and percentages
|
||||
virtual void printOn(std::ostream & _os)
|
||||
{
|
||||
double total = 0;
|
||||
unsigned i;
|
||||
for (i=0; i<ops.size(); i++)
|
||||
total += rates[i];
|
||||
_os << "In " << className() << "\n" ;
|
||||
for (i=0; i<ops.size(); i++)
|
||||
_os << ops[i]->className() << " with rate " << 100*rates[i]/total << " %\n";
|
||||
}
|
||||
|
||||
virtual bool operator()(EOT & _indi)
|
||||
{
|
||||
unsigned what = rng.roulette_wheel(rates); // choose one op
|
||||
return (*ops[what])(_indi); // apply it
|
||||
}
|
||||
protected:
|
||||
std::vector<eoMonOp<EOT>*> ops;
|
||||
std::vector<double> rates;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
//// combined BinOp
|
||||
//////////////////////////////////////////////////////
|
||||
|
||||
/** COmbined Binary genetic operator:
|
||||
* operator() has two operands, only the first one can be modified
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoPropCombinedBinOp: public eoBinOp<EOT>
|
||||
{
|
||||
public:
|
||||
/// Ctor
|
||||
eoPropCombinedBinOp(eoBinOp<EOT> & _first, const double _rate)
|
||||
{
|
||||
ops.push_back(&_first);
|
||||
rates.push_back(_rate);
|
||||
}
|
||||
|
||||
virtual std::string className() const { return "eoPropCombinedBinOp"; }
|
||||
|
||||
virtual void add(eoBinOp<EOT> & _op, const double _rate, bool _verbose=false)
|
||||
{
|
||||
ops.push_back(&_op);
|
||||
rates.push_back(_rate);
|
||||
// compute the relative rates in percent - to warn the user!
|
||||
if (_verbose)
|
||||
{
|
||||
double total = 0;
|
||||
unsigned i;
|
||||
for (i=0; i<ops.size(); i++)
|
||||
total += rates[i];
|
||||
std::cout << "In " << className() << "\n" ;
|
||||
for (i=0; i<ops.size(); i++)
|
||||
std::cout << ops[i]->className() << " with rate " << 100*rates[i]/total << " %\n";
|
||||
}
|
||||
}
|
||||
|
||||
virtual void operator()(EOT & _indi1, const EOT & _indi2)
|
||||
{
|
||||
unsigned what = rng.roulette_wheel(rates); // choose one op index
|
||||
return (*ops[what])(_indi1, _indi2); // apply it
|
||||
}
|
||||
private:
|
||||
std::vector<eoBinOp<EOT>*> ops;
|
||||
std::vector<double> rates;
|
||||
};
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////
|
||||
//// combined QuadOp
|
||||
//////////////////////////////////////////////////////
|
||||
|
||||
/** Quad genetic operator: subclasses eoOp, and defines basically the
|
||||
operator() with two operands, both can be modified.
|
||||
*/
|
||||
/** Combined quad genetic operator:
|
||||
* operator() has two operands, both can be modified
|
||||
|
||||
* generic operators are now allowed: there are imbedded into
|
||||
* the corresponding "true" operator
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoPropCombinedQuadOp: public eoQuadOp<EOT>
|
||||
{
|
||||
public:
|
||||
/// Ctor from a true operator
|
||||
eoPropCombinedQuadOp(eoQuadOp<EOT> & _first, const double _rate)
|
||||
{
|
||||
ops.push_back(&_first);
|
||||
rates.push_back(_rate);
|
||||
}
|
||||
|
||||
virtual std::string className() const { return "eoPropCombinedQuadOp"; }
|
||||
|
||||
// addition of a true operator
|
||||
virtual void add(eoQuadOp<EOT> & _op, const double _rate, bool _verbose=false)
|
||||
{
|
||||
ops.push_back(&_op);
|
||||
rates.push_back(_rate);
|
||||
// compute the relative rates in percent - to warn the user!
|
||||
if (_verbose)
|
||||
printOn(std::cout);
|
||||
}
|
||||
|
||||
// outputs the operators and percentages
|
||||
virtual void printOn(std::ostream & _os)
|
||||
{
|
||||
double total = 0;
|
||||
unsigned i;
|
||||
for (i=0; i<ops.size(); i++)
|
||||
total += rates[i];
|
||||
_os << "In " << className() << "\n" ;
|
||||
for (i=0; i<ops.size(); i++)
|
||||
_os << ops[i]->className() << " with rate " << 100*rates[i]/total << " %\n";
|
||||
}
|
||||
|
||||
virtual bool operator()(EOT & _indi1, EOT & _indi2)
|
||||
{
|
||||
unsigned what = rng.roulette_wheel(rates); // choose one op index
|
||||
return (*ops[what])(_indi1, _indi2); // apply it
|
||||
}
|
||||
private:
|
||||
std::vector<eoQuadOp<EOT>*> ops;
|
||||
std::vector<double> rates;
|
||||
};
|
||||
|
||||
|
||||
// for General Ops, it's another story - see eoOpCOntainer
|
||||
#endif
|
||||
|
||||
85
trunk/paradiseo-eo/src/eoProportionalSelect.h
Executable file
85
trunk/paradiseo-eo/src/eoProportionalSelect.h
Executable file
|
|
@ -0,0 +1,85 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoProportionalSelect.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 eoProportionalSelect_h
|
||||
#define eoProportionalSelect_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <utils/eoRNG.h>
|
||||
#include <utils/selectors.h>
|
||||
#include <eoSelectOne.h>
|
||||
#include <eoPop.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
/** eoProportionalSelect: select an individual proportional to her stored fitness
|
||||
value
|
||||
|
||||
Changed the algorithm to make use of a cumulative array of fitness scores,
|
||||
This changes the algorithm from O(n) per call to O(log n) per call. (MK)
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
template <class EOT> class eoProportionalSelect: public eoSelectOne<EOT>
|
||||
{
|
||||
public:
|
||||
/// Sanity check
|
||||
eoProportionalSelect(const eoPop<EOT>& pop = eoPop<EOT>())
|
||||
{
|
||||
if (minimizing_fitness<EOT>())
|
||||
throw std::logic_error("eoProportionalSelect: minimizing fitness");
|
||||
}
|
||||
|
||||
void setup(const eoPop<EOT>& _pop)
|
||||
{
|
||||
if (_pop.size() == 0) return;
|
||||
|
||||
cumulative.resize(_pop.size());
|
||||
cumulative[0] = _pop[0].fitness();
|
||||
|
||||
for (unsigned i = 1; i < _pop.size(); ++i)
|
||||
{
|
||||
cumulative[i] = _pop[i].fitness() + cumulative[i-1];
|
||||
}
|
||||
}
|
||||
|
||||
/** do the selection,
|
||||
*/
|
||||
const EOT& operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
if (cumulative.size() == 0) setup(_pop);
|
||||
|
||||
double fortune = rng.uniform() * cumulative.back();
|
||||
typename FitVec::iterator result = std::upper_bound(cumulative.begin(), cumulative.end(), fortune);
|
||||
return _pop[result - cumulative.begin()];
|
||||
}
|
||||
|
||||
private :
|
||||
|
||||
typedef std::vector<typename EOT::Fitness> FitVec;
|
||||
FitVec cumulative;
|
||||
};
|
||||
|
||||
#endif
|
||||
98
trunk/paradiseo-eo/src/eoRandomSelect.h
Normal file
98
trunk/paradiseo-eo/src/eoRandomSelect.h
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoRandomSelect.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 eoRandomSelect_h
|
||||
#define eoRandomSelect_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
/** This file contains straightforward selectors:
|
||||
* eoRandomSelect returns an individual uniformly selected
|
||||
* eoBestSelect always return the best individual
|
||||
* eoSequentialSelect returns all individuals in turn
|
||||
*/
|
||||
|
||||
#include <utils/eoRNG.h>
|
||||
#include <eoSelectOne.h>
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
/** eoRandomSelect: a selection method that selects ONE individual randomly */
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
template <class EOT> class eoRandomSelect: public eoSelectOne<EOT>
|
||||
{
|
||||
public:
|
||||
|
||||
/// not a big deal!!!
|
||||
virtual const EOT& operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
return _pop[eo::rng.random(_pop.size())] ;
|
||||
}
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
/** eoBestSelect: a selection method that always return the best
|
||||
* (mainly for testing purposes) */
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
template <class EOT> class eoBestSelect: public eoSelectOne<EOT>
|
||||
{
|
||||
public:
|
||||
|
||||
/// not a big deal!!!
|
||||
virtual const EOT& operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
return _pop.best_element() ;
|
||||
}
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
/** eoNoSelect: returns all individual in order WITHOUT USING FITNESS!!!
|
||||
* looping back to the beginning when exhasuted
|
||||
*
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
template <class EOT> class eoNoSelect: public eoSelectOne<EOT>
|
||||
{
|
||||
public:
|
||||
/** Ctor
|
||||
*/
|
||||
eoNoSelect(): current(0) {}
|
||||
|
||||
virtual const EOT& operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
if (current >= _pop.size())
|
||||
current=0;
|
||||
|
||||
current++;
|
||||
return _pop[current-1] ;
|
||||
}
|
||||
private:
|
||||
unsigned current;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
110
trunk/paradiseo-eo/src/eoRanking.h
Normal file
110
trunk/paradiseo-eo/src/eoRanking.h
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoRanking.h
|
||||
(c) Maarten Keijzer, Marc Schoenauer, 2001
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoRanking_h
|
||||
#define eoRanking_h
|
||||
|
||||
#include <eoPerf2Worth.h>
|
||||
|
||||
/** An instance of eoPerfFromWorth
|
||||
* COmputes the ranked fitness: fitnesses range in [m,M]
|
||||
* with m=2-pressure/popSize and M=pressure/popSize.
|
||||
* in between, the progression depstd::ends on exponent (linear if 1).
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoRanking : public eoPerf2Worth<EOT> // false: do not cache fitness
|
||||
{
|
||||
public:
|
||||
|
||||
using eoPerf2Worth<EOT>::value;
|
||||
|
||||
/* Ctor:
|
||||
@param _p selective pressure (in (1,2]
|
||||
@param _e exponent (1 == linear)
|
||||
*/
|
||||
eoRanking(double _p=2.0, double _e=1.0):
|
||||
pressure(_p), exponent(_e) {}
|
||||
|
||||
/* helper function: finds index in _pop of _eo, an EOT * */
|
||||
int lookfor(const EOT *_eo, const eoPop<EOT>& _pop)
|
||||
{
|
||||
typename eoPop<EOT>::const_iterator it;
|
||||
for (it=_pop.begin(); it<_pop.end(); it++)
|
||||
{
|
||||
if (_eo == &(*it))
|
||||
return it-_pop.begin();
|
||||
}
|
||||
throw std::runtime_error("Not found in eoLinearRanking");
|
||||
}
|
||||
|
||||
/* COmputes the ranked fitness: fitnesses range in [m,M]
|
||||
with m=2-pressure/popSize and M=pressure/popSize.
|
||||
in between, the progression depstd::ends on exponent (linear if 1).
|
||||
*/
|
||||
virtual void operator()(const eoPop<EOT>& _pop)
|
||||
{
|
||||
std::vector<const EOT *> rank;
|
||||
_pop.sort(rank);
|
||||
unsigned pSize =_pop.size();
|
||||
unsigned int pSizeMinusOne = pSize-1;
|
||||
|
||||
if (pSize <= 1)
|
||||
throw std::runtime_error("Cannot do ranking with population of size <= 1");
|
||||
|
||||
// value() refers to the std::vector of worthes (we're in an eoParamvalue)
|
||||
value().resize(pSize);
|
||||
|
||||
double beta = (2-pressure)/pSize;
|
||||
if (exponent == 1.0) // no need for exponetial then
|
||||
{
|
||||
double alpha = (2*pressure-2)/(pSize*pSizeMinusOne);
|
||||
for (unsigned i=0; i<pSize; i++)
|
||||
{
|
||||
int which = lookfor(rank[i], _pop);
|
||||
value()[which] = alpha*(pSize-i)+beta; // worst -> 1/[P(P-1)/2]
|
||||
}
|
||||
}
|
||||
else // exponent != 1
|
||||
{
|
||||
double gamma = (2*pressure-2)/pSize;
|
||||
for (unsigned i=0; i<pSize; i++)
|
||||
{
|
||||
int which = lookfor(rank[i], _pop);
|
||||
// value in in [0,1]
|
||||
double tmp = ((double)(pSize-i))/pSize;
|
||||
// to the exponent, and back to [m,M]
|
||||
value()[which] = gamma*pow(tmp, exponent)+beta;
|
||||
}
|
||||
}
|
||||
}
|
||||
private:
|
||||
double pressure; // selective pressure
|
||||
double exponent;
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
55
trunk/paradiseo-eo/src/eoRankingSelect.h
Normal file
55
trunk/paradiseo-eo/src/eoRankingSelect.h
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoRankingSelect.h
|
||||
// (c) GeNeura Team, 1998, Maarten Keijzer 2000, Marc Schoenauer 2001
|
||||
/*
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: Marc.Schoenauer@polytechnique.fr
|
||||
mak@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoRankingSelect_h
|
||||
#define eoRankingSelect_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <eoSelectFromWorth.h>
|
||||
#include <eoRanking.h>
|
||||
|
||||
/** eoRankingSelect: select an individual by roulette wheel on its rank
|
||||
* is an eoRouletteWorthSelect, i.e. a selector using a std::vector of worthes
|
||||
* rather than the raw fitness (see eoSelectFromWorth.h)
|
||||
* uses an internal eoRanking object which is an eoPerf2Worth<EOT, double>
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoRankingSelect: public eoRouletteWorthSelect<EOT, double>
|
||||
{
|
||||
public:
|
||||
/** Ctor:
|
||||
* @param _p the selective pressure, should be in [1,2] (2 is the default)
|
||||
* @param _e exponent (1 == linear)
|
||||
*/
|
||||
eoRankingSelect(double _p = 2.0, double _e=1.0):
|
||||
eoRouletteWorthSelect<EOT, double>(ranking), ranking(_p, _e) {}
|
||||
|
||||
private :
|
||||
eoRanking<EOT> ranking; // derived from eoPerf2Worth
|
||||
};
|
||||
|
||||
#endif
|
||||
288
trunk/paradiseo-eo/src/eoReduce.h
Normal file
288
trunk/paradiseo-eo/src/eoReduce.h
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
// -*- 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
|
||||
#include <utils/selectors.h>
|
||||
|
||||
/**
|
||||
* eoReduce: .reduce the new generation to the specified size
|
||||
At the moment, limited to truncation - with 2 different methods,
|
||||
one that sorts the whole population, and one that repeatidely kills
|
||||
the worst. Ideally, we should be able to choose at run-time!!!
|
||||
*/
|
||||
|
||||
template<class EOT> class eoReduce: public eoBF<eoPop<EOT>&, unsigned, void>
|
||||
{};
|
||||
|
||||
/** truncation method using sort */
|
||||
template <class EOT> class eoTruncate : public eoReduce<EOT>
|
||||
{
|
||||
void operator()(eoPop<EOT>& _newgen, unsigned _newsize)
|
||||
{
|
||||
if (_newgen.size() == _newsize)
|
||||
return;
|
||||
if (_newgen.size() < _newsize)
|
||||
throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n");
|
||||
|
||||
_newgen.nth_element(_newsize);
|
||||
_newgen.resize(_newsize);
|
||||
}
|
||||
};
|
||||
|
||||
/** random truncation */
|
||||
template <class EOT> class eoRandomReduce : public eoReduce<EOT>
|
||||
{
|
||||
void operator()(eoPop<EOT>& _newgen, unsigned _newsize)
|
||||
{
|
||||
if (_newgen.size() == _newsize)
|
||||
return;
|
||||
if (_newgen.size() < _newsize)
|
||||
throw std::logic_error("eoRandomReduce: Cannot truncate to a larger size!\n");
|
||||
|
||||
// shuffle the population, then trucate
|
||||
_newgen.shuffle();
|
||||
_newgen.resize(_newsize);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
EP truncation method (some global stochastic tournament + sort)
|
||||
Softer selective pressure than pure truncate
|
||||
*/
|
||||
template <class EOT> class eoEPReduce : public eoReduce<EOT>
|
||||
{
|
||||
public:
|
||||
typedef typename EOT::Fitness Fitness;
|
||||
|
||||
eoEPReduce(unsigned _t_size ):
|
||||
t_size(_t_size)
|
||||
{
|
||||
if (t_size < 2)
|
||||
{
|
||||
std::cout << "Warning: EP tournament size should be >= 2. Adjusted" << std::endl;
|
||||
t_size = 2;
|
||||
}
|
||||
}
|
||||
|
||||
/// helper struct for comparing on std::pairs
|
||||
// compares the scores
|
||||
// uses the fitness if scores are equals ????
|
||||
typedef std::pair<float, typename eoPop<EOT>::iterator> EPpair;
|
||||
struct Cmp {
|
||||
bool operator()(const EPpair a, const EPpair b) const
|
||||
{
|
||||
if (b.first == a.first)
|
||||
return (*b.second < *a.second);
|
||||
return b.first < a.first;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
void operator()(eoPop<EOT>& _newgen, unsigned _newsize)
|
||||
{
|
||||
unsigned int presentSize = _newgen.size();
|
||||
|
||||
if (presentSize == _newsize)
|
||||
return;
|
||||
if (presentSize < _newsize)
|
||||
throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n");
|
||||
std::vector<EPpair> scores(presentSize);
|
||||
for (unsigned i=0; i<presentSize; i++)
|
||||
{
|
||||
scores[i].second = _newgen.begin()+i;
|
||||
Fitness fit = _newgen[i].fitness();
|
||||
for (unsigned itourn = 0; itourn < t_size; ++itourn)
|
||||
{
|
||||
const EOT & competitor = _newgen[rng.random(presentSize)];
|
||||
if (fit > competitor.fitness())
|
||||
scores[i].first += 1;
|
||||
else if (fit == competitor.fitness())
|
||||
scores[i].first += 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
// now we have the scores
|
||||
typename std::vector<EPpair>::iterator it = scores.begin() + _newsize;
|
||||
std::nth_element(scores.begin(), it, scores.end(), Cmp());
|
||||
// sort(scores.begin(), scores.end(), Cmp());
|
||||
unsigned j;
|
||||
// std::cout << "Les scores apres tri\n";
|
||||
// for (j=0; j<scores.size(); j++)
|
||||
// {
|
||||
// std::cout << scores[j].first << " " << *scores[j].second << std::endl;
|
||||
// }
|
||||
eoPop<EOT> tmPop;
|
||||
for (j=0; j<_newsize; j++)
|
||||
{
|
||||
tmPop.push_back(*scores[j].second);
|
||||
}
|
||||
_newgen.swap(tmPop);
|
||||
// erase does not work, but I'm sure there is a way in STL to mark
|
||||
// and later delete all inside a std::vector ??????
|
||||
// this would avoid all copies here
|
||||
|
||||
// it = scores.begin() + _newsize;
|
||||
// while (it < scores.end())
|
||||
// _newgen.erase(it->second);
|
||||
}
|
||||
private:
|
||||
unsigned t_size;
|
||||
};
|
||||
|
||||
/** a truncate class that does not sort, but repeatidely kills the worse.
|
||||
To be used in SSGA-like replacements (e.g. see eoSSGAWorseReplacement)
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoLinearTruncate : public eoReduce<EOT>
|
||||
{
|
||||
void operator()(eoPop<EOT>& _newgen, unsigned _newsize)
|
||||
{
|
||||
unsigned oldSize = _newgen.size();
|
||||
if (oldSize == _newsize)
|
||||
return;
|
||||
if (oldSize < _newsize)
|
||||
throw std::logic_error("eoLinearTruncate: Cannot truncate to a larger size!\n");
|
||||
for (unsigned i=0; i<oldSize - _newsize; i++)
|
||||
{
|
||||
typename eoPop<EOT>::iterator it = _newgen.it_worse_element();
|
||||
_newgen.erase(it);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** a truncate class based on a repeated deterministic (reverse!) tournament
|
||||
To be used in SSGA-like replacements (e.g. see eoSSGADetTournamentReplacement)
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoDetTournamentTruncate : public eoReduce<EOT>
|
||||
{
|
||||
public:
|
||||
eoDetTournamentTruncate(unsigned _t_size):
|
||||
t_size(_t_size)
|
||||
{
|
||||
if (t_size < 2)
|
||||
{
|
||||
std::cout << "Warning, Size for eoDetTournamentTruncate adjusted to 2\n";
|
||||
t_size = 2;
|
||||
}
|
||||
}
|
||||
|
||||
void operator()(eoPop<EOT>& _newgen, unsigned _newsize)
|
||||
{
|
||||
unsigned oldSize = _newgen.size();
|
||||
if (_newsize == 0)
|
||||
{
|
||||
_newgen.resize(0);
|
||||
return;
|
||||
}
|
||||
if (oldSize == _newsize)
|
||||
return;
|
||||
if (oldSize < _newsize)
|
||||
throw std::logic_error("eoDetTournamentTruncate: Cannot truncate to a larger size!\n");
|
||||
|
||||
// Now OK to erase some losers
|
||||
for (unsigned i=0; i<oldSize - _newsize; i++)
|
||||
{
|
||||
//OLDCODE EOT & eo = inverse_deterministic_tournament<EOT>(_newgen, t_size);
|
||||
//OLDCODE _newgen.erase(&eo);
|
||||
|
||||
// Jeroen Eggermont stdc++v3 patch
|
||||
// in the new code from stdc++v3 an iterator from a container<T> is no longer an pointer to T
|
||||
// Because eo already contained a fuction using eoPop<EOT>::iterator's we will use the following
|
||||
|
||||
_newgen.erase( inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size) );
|
||||
|
||||
}
|
||||
}
|
||||
private:
|
||||
unsigned t_size;
|
||||
};
|
||||
|
||||
/** a truncate class based on a repeated deterministic (reverse!) tournament
|
||||
To be used in SSGA-like replacements (e.g. see eoSSGAStochTournamentReplacement)
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoStochTournamentTruncate : public eoReduce<EOT>
|
||||
{
|
||||
public:
|
||||
eoStochTournamentTruncate(double _t_rate):
|
||||
t_rate(_t_rate)
|
||||
{
|
||||
if (t_rate <= 0.5)
|
||||
{
|
||||
std::cout << "Warning, Rate for eoStochTournamentTruncate adjusted to 0.51\n";
|
||||
t_rate = 0.51;
|
||||
}
|
||||
if (t_rate > 1)
|
||||
{
|
||||
std::cout << "Warning, Rate for eoStochTournamentTruncate adjusted to 1\n";
|
||||
t_rate = 1;
|
||||
}
|
||||
}
|
||||
|
||||
void operator()(eoPop<EOT>& _newgen, unsigned _newsize)
|
||||
{
|
||||
unsigned oldSize = _newgen.size();
|
||||
if (_newsize == 0)
|
||||
{
|
||||
_newgen.resize(0);
|
||||
return;
|
||||
}
|
||||
if (oldSize == _newsize)
|
||||
return;
|
||||
if (oldSize < _newsize)
|
||||
throw std::logic_error("eoStochTournamentTruncate: Cannot truncate to a larger size!\n");
|
||||
// Now OK to erase some losers
|
||||
for (unsigned i=0; i<oldSize - _newsize; i++)
|
||||
{
|
||||
//OLDCODE EOT & eo = inverse_stochastic_tournament<EOT>(_newgen, t_rate);
|
||||
//OLDCODE _newgen.erase(&eo);
|
||||
|
||||
// Jeroen Eggermont stdc++v3 patch
|
||||
// in the new code from stdc++v3 an iterator from a container<T> is no longer an pointer to T
|
||||
// Because eo already contained a fuction using eoPop<EOT>::iterator's we will use the following
|
||||
|
||||
_newgen.erase( inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate) );
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
double t_rate;
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif
|
||||
119
trunk/paradiseo-eo/src/eoReduceMerge.h
Normal file
119
trunk/paradiseo-eo/src/eoReduceMerge.h
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoReduceMerge.h
|
||||
(c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
Marc.Schoenauer@polytechnique.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoReduceMerge_h
|
||||
#define _eoReduceMerge_h
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoPop.h>
|
||||
#include <eoFunctor.h>
|
||||
#include <eoMerge.h>
|
||||
#include <eoReduce.h>
|
||||
#include <eoReplacement.h>
|
||||
#include <utils/eoHowMany.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
/**
|
||||
eoReduceMerge: Replacement strategies that start by reducing the parents,
|
||||
then merge with the offspring
|
||||
|
||||
This is the way to do SSGA: the offspring gets inserted in the population
|
||||
even if it is worse than anybody else.
|
||||
|
||||
@classes: eoReduceMerge, eoSSGAWorseReplacement,
|
||||
eoSSGADetTournamentReplacement, eoSSGAStochTournamentReplacement
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoReduceMerge : public eoReplacement<EOT>
|
||||
{
|
||||
public:
|
||||
eoReduceMerge(eoReduce<EOT>& _reduce, eoMerge<EOT>& _merge) :
|
||||
reduce(_reduce), merge(_merge)
|
||||
{}
|
||||
|
||||
void operator()(eoPop<EOT>& _parents, eoPop<EOT>& _offspring)
|
||||
{
|
||||
if (_parents.size() < _offspring.size())
|
||||
throw std::logic_error("eoReduceMerge: More offspring than parents!\n");
|
||||
reduce(_parents, _parents.size() - _offspring.size());
|
||||
merge(_offspring, _parents);
|
||||
}
|
||||
|
||||
private :
|
||||
eoReduce<EOT>& reduce;
|
||||
eoMerge<EOT>& merge;
|
||||
};
|
||||
|
||||
/**
|
||||
SSGA replace worst. Is an eoReduceMerge.
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoSSGAWorseReplacement : public eoReduceMerge<EOT>
|
||||
{
|
||||
public :
|
||||
eoSSGAWorseReplacement() : eoReduceMerge<EOT>(truncate, plus) {}
|
||||
|
||||
private :
|
||||
eoLinearTruncate<EOT> truncate;
|
||||
eoPlus<EOT> plus;
|
||||
};
|
||||
|
||||
/**
|
||||
SSGA deterministic tournament replacement. Is an eoReduceMerge.
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoSSGADetTournamentReplacement : public eoReduceMerge<EOT>
|
||||
{
|
||||
public :
|
||||
eoSSGADetTournamentReplacement(unsigned _t_size) :
|
||||
eoReduceMerge<EOT>(truncate, plus), truncate(_t_size) {}
|
||||
|
||||
private :
|
||||
eoDetTournamentTruncate<EOT> truncate;
|
||||
eoPlus<EOT> plus;
|
||||
};
|
||||
|
||||
/** SSGA stochastic tournament replacement. Is an eoReduceMerge.
|
||||
It much cleaner to insert directly the offspring in the parent population,
|
||||
but it is NOT equivalent in case of more than 1 offspring as already
|
||||
replaced could be removed , which is not possible in the eoReduceMerge
|
||||
So what the heck ! */
|
||||
template <class EOT>
|
||||
class eoSSGAStochTournamentReplacement : public eoReduceMerge<EOT>
|
||||
{
|
||||
public :
|
||||
eoSSGAStochTournamentReplacement(double _t_rate) :
|
||||
eoReduceMerge<EOT>(truncate, plus), truncate(_t_rate) {}
|
||||
|
||||
private :
|
||||
eoStochTournamentTruncate<EOT> truncate;
|
||||
eoPlus<EOT> plus;
|
||||
};
|
||||
|
||||
#endif
|
||||
143
trunk/paradiseo-eo/src/eoReduceMergeReduce.h
Normal file
143
trunk/paradiseo-eo/src/eoReduceMergeReduce.h
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
-----------------------------------------------------------------------------
|
||||
eoReduceMergeReduce.h
|
||||
(c) Maarten Keijzer, Marc Schoenauer, 2002
|
||||
|
||||
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: Marc.Schoenauer@inria.fr
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoReduceMergeReduce_h
|
||||
#define _eoReduceMergeReduce_h
|
||||
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoPop.h>
|
||||
#include <eoFunctor.h>
|
||||
#include <eoMerge.h>
|
||||
#include <eoReduce.h>
|
||||
#include <utils/eoHowMany.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
eoReduceMergeReduce is an eoReplacement:
|
||||
- saves possible elite parents
|
||||
- reduces rest of parents
|
||||
- reduces offspring
|
||||
- merges reduced populations
|
||||
- reduces resulting merged pop if necessary
|
||||
|
||||
*/
|
||||
|
||||
template <class EOT>
|
||||
class eoReduceMergeReduce : public eoReplacement<EOT>
|
||||
{
|
||||
public:
|
||||
eoReduceMergeReduce(eoHowMany _howManyElite,
|
||||
bool _strongElitism,
|
||||
eoHowMany _howManyReducedParents,
|
||||
eoReduce<EOT> & _reduceParents,
|
||||
eoHowMany _howManyReducedOffspring,
|
||||
eoReduce<EOT> & _reduceOffspring,
|
||||
eoReduce<EOT> & _reduceFinal) :
|
||||
howManyElite(_howManyElite),
|
||||
strongElitism(_strongElitism),
|
||||
howManyReducedParents(_howManyReducedParents),
|
||||
howManyReducedOffspring (_howManyReducedOffspring),
|
||||
reduceParents(_reduceParents),
|
||||
reduceOffspring(_reduceOffspring),
|
||||
reduceFinal(_reduceFinal)
|
||||
{}
|
||||
|
||||
void operator()(eoPop<EOT> & _parents, eoPop<EOT> & _offspring)
|
||||
{
|
||||
eoPop<EOT> temp;
|
||||
unsigned int finalPopSize = _parents.size();
|
||||
unsigned int offSize = _offspring.size();
|
||||
|
||||
unsigned int elite = howManyElite(finalPopSize);
|
||||
if (elite) // some parents MUST be saved somewhere
|
||||
{
|
||||
temp.resize(elite);
|
||||
_parents.nth_element(elite);
|
||||
std::copy(_parents.begin(), _parents.begin()+elite, temp.begin());
|
||||
_parents.erase(_parents.begin(), _parents.begin()+elite);
|
||||
}
|
||||
|
||||
// the reduce steps. First the parents
|
||||
unsigned reducedParentSize = howManyReducedParents(_parents.size());
|
||||
if (!reducedParentSize)
|
||||
_parents.clear();
|
||||
else if (reducedParentSize != _parents.size())
|
||||
reduceParents(_parents, reducedParentSize);
|
||||
|
||||
// then the offspring
|
||||
unsigned reducedOffspringSize = howManyReducedOffspring(offSize);
|
||||
if (!reducedOffspringSize)
|
||||
throw std::runtime_error("No offspring left after reduction!");
|
||||
if (reducedOffspringSize != offSize) // need reduction
|
||||
reduceOffspring(_offspring, reducedOffspringSize);
|
||||
|
||||
// now merge reduced populations
|
||||
_parents.resize(reducedParentSize + _offspring.size());
|
||||
std::copy(_offspring.begin(), _offspring.end(),
|
||||
_parents.begin()+reducedParentSize);
|
||||
|
||||
// reduce the resulting population
|
||||
// size depstd::ends on elitism
|
||||
if (elite && strongElitism)
|
||||
{
|
||||
if (_parents.size() != finalPopSize-elite)
|
||||
reduceFinal(_parents, finalPopSize-elite);
|
||||
// and put back the elite
|
||||
unsigned oldPSize = _parents.size();
|
||||
_parents.resize(_parents.size()+elite);
|
||||
std::copy(temp.begin(), temp.end(), _parents.begin()+oldPSize);
|
||||
}
|
||||
else
|
||||
{ // only reduce final pop to right size
|
||||
if (_parents.size() != finalPopSize)
|
||||
reduceFinal(_parents, finalPopSize);
|
||||
if (elite) // then treat weak elitism
|
||||
{
|
||||
unsigned toSave = 0;
|
||||
_parents.sort();
|
||||
EOT & eoLimit = _parents[elite-1];
|
||||
unsigned index=0;
|
||||
while ( (temp[index++] > eoLimit) && (index < temp.size()) )
|
||||
toSave++;
|
||||
if (toSave)
|
||||
for (unsigned i=0; i<toSave; i++)
|
||||
_parents[finalPopSize-1-i] = temp[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
eoHowMany howManyElite; // if 0, no elitism at all
|
||||
bool strongElitism; // if false -> weak estd::listism
|
||||
eoHowMany howManyReducedParents; // if 0, no parent in final replacement
|
||||
eoHowMany howManyReducedOffspring; // if 0, std::runtime_error
|
||||
// the reducers
|
||||
eoReduce<EOT> & reduceParents;
|
||||
eoReduce<EOT> & reduceOffspring;
|
||||
eoReduce<EOT> & reduceFinal;
|
||||
};
|
||||
|
||||
#endif
|
||||
323
trunk/paradiseo-eo/src/eoReduceSplit.h
Normal file
323
trunk/paradiseo-eo/src/eoReduceSplit.h
Normal file
|
|
@ -0,0 +1,323 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoReduceSplit.h
|
||||
// Base class for population-reducing classes - retaining the poor losers
|
||||
// (c) GeNeura Team, 1998, Marc Schoenauer, 2002
|
||||
/*
|
||||
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: Marc.Schoenauer@inria.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoReduceSplit_h
|
||||
#define eoReduceSplit_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <iostream>
|
||||
|
||||
// EO includes
|
||||
#include <eoPop.h> // eoPop
|
||||
#include <eoFunctor.h> // eoReduce
|
||||
#include <utils/selectors.h>
|
||||
|
||||
/**
|
||||
* eoReduceSplit: reduce the pop to the specified size
|
||||
* AND eventually returns the eliminated guys
|
||||
*/
|
||||
template<class EOT> class eoReduceSplit: public eoBF<eoPop<EOT>&, eoPop<EOT> &, void >
|
||||
{};
|
||||
|
||||
/** deterministic truncation method using sort */
|
||||
template <class EOT>
|
||||
class eoTruncateSplit : public eoReduceSplit<EOT>
|
||||
{
|
||||
public:
|
||||
/** Ctor: must provide amount of reduction,
|
||||
and whether or not you need to return the eliminated guys
|
||||
*/
|
||||
eoTruncateSplit(eoHowMany _howMany, bool _returnEliminated = false):
|
||||
howMany(_howMany), returnEliminated(_returnEliminated) {}
|
||||
|
||||
/** do the jonb */
|
||||
void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated)
|
||||
{
|
||||
unsigned popSize = _newgen.size();
|
||||
unsigned eliminated = howMany(popSize);
|
||||
if (!eliminated) // nothing to do
|
||||
return ;
|
||||
unsigned newsize = popSize - eliminated;
|
||||
if (newsize < 0)
|
||||
throw std::logic_error("eoTruncateSplit: Cannot truncate to a larger size!\n");
|
||||
|
||||
_newgen.nth_element(newsize);
|
||||
|
||||
// save poor losers if necessary
|
||||
if (returnEliminated)
|
||||
for (unsigned i=0; i<eliminated; i++)
|
||||
_eliminated.push_back(_newgen[newsize+i]);
|
||||
// truncate
|
||||
_newgen.resize(newsize);
|
||||
return ;
|
||||
}
|
||||
|
||||
private:
|
||||
eoHowMany howMany;
|
||||
bool returnEliminated;
|
||||
};
|
||||
|
||||
/** a ReduceSplit class that does not sort, but repeatidely kills the worse.
|
||||
To be used in SSGA-like replacements (e.g. see eoSSGAWorseReplacement)
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoLinearTruncateSplit : public eoReduceSplit<EOT>
|
||||
{
|
||||
public:
|
||||
/** Ctor: must provide amount of reduction,
|
||||
and whether or not you need to return the eliminated guys
|
||||
*/
|
||||
eoLinearTruncateSplit(eoHowMany _howMany, bool _returnEliminated = false):
|
||||
howMany(_howMany), returnEliminated(_returnEliminated) {}
|
||||
|
||||
/** do the job */
|
||||
void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated)
|
||||
{
|
||||
unsigned popSize = _newgen.size();
|
||||
unsigned eliminated = howMany(popSize);
|
||||
if (!eliminated) // nothing to do
|
||||
return ;
|
||||
unsigned newsize = popSize - eliminated;
|
||||
if (newsize < 0)
|
||||
throw std::logic_error("eoLinearTruncateSplit: Cannot truncate to a larger size!\n");
|
||||
|
||||
_eliminated.reserve(_eliminated.size()+eliminated); //in case not empty?
|
||||
for (unsigned i=0; i<eliminated; i++)
|
||||
{
|
||||
typename eoPop<EOT>::iterator it = _newgen.it_worse_element();
|
||||
if (returnEliminated)
|
||||
_eliminated.push_back(*it);
|
||||
_newgen.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
eoHowMany howMany;
|
||||
bool returnEliminated;
|
||||
};
|
||||
|
||||
/** random truncation - batch version */
|
||||
template <class EOT>
|
||||
class eoRandomSplit : public eoReduceSplit<EOT>
|
||||
{
|
||||
public:
|
||||
/** Ctor: must provide amount of reduction,
|
||||
and whether or not you need to return the eliminated guys
|
||||
*/
|
||||
eoRandomSplit(eoHowMany _howMany, bool _returnEliminated = false):
|
||||
howMany(_howMany), returnEliminated(_returnEliminated) {}
|
||||
|
||||
/** do the job */
|
||||
void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated)
|
||||
{
|
||||
unsigned popSize = _newgen.size();
|
||||
unsigned eliminated = howMany(popSize);
|
||||
if (!eliminated) // nothing to do
|
||||
return ;
|
||||
unsigned newsize = popSize - eliminated;
|
||||
if (newsize < 0)
|
||||
throw std::logic_error("eoRandomSplit: Cannot truncate to a larger size!\n");
|
||||
|
||||
_newgen.shuffle();
|
||||
|
||||
// save poor losers if necessary
|
||||
if (returnEliminated)
|
||||
for (unsigned i=0; i<eliminated; i++)
|
||||
_eliminated.push_back(_newgen[newsize+i]);
|
||||
// truncate
|
||||
_newgen.resize(newsize);
|
||||
return ;
|
||||
}
|
||||
|
||||
private:
|
||||
eoHowMany howMany;
|
||||
bool returnEliminated;
|
||||
};
|
||||
|
||||
|
||||
/** random truncation - linear version */
|
||||
template <class EOT>
|
||||
class eoLinearRandomSplit : public eoReduceSplit<EOT>
|
||||
{
|
||||
public:
|
||||
/** Ctor: must provide amount of reduction,
|
||||
and whether or not you need to return the eliminated guys
|
||||
*/
|
||||
eoLinearRandomSplit(eoHowMany _howMany, bool _returnEliminated = false):
|
||||
howMany(_howMany), returnEliminated(_returnEliminated) {}
|
||||
|
||||
/** do the job */
|
||||
void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated)
|
||||
{
|
||||
unsigned popSize = _newgen.size();
|
||||
unsigned eliminated = howMany(popSize);
|
||||
if (!eliminated) // nothing to do
|
||||
return ;
|
||||
unsigned newsize = popSize - eliminated;
|
||||
if (newsize < 0)
|
||||
throw std::logic_error("eoLinearRandomSplit: Cannot truncate to a larger size!\n");
|
||||
|
||||
_eliminated.reserve(_eliminated.size()+eliminated); //in case not empty?
|
||||
for (unsigned i=0; i<eliminated; i++)
|
||||
{
|
||||
unsigned loser=random(_newgen.size());
|
||||
typename eoPop<EOT>::iterator it = _newgen.begin()+loser;
|
||||
if (returnEliminated)
|
||||
_eliminated.push_back(*it);
|
||||
_newgen.erase(it);
|
||||
}
|
||||
return ;
|
||||
}
|
||||
|
||||
private:
|
||||
eoHowMany howMany;
|
||||
bool returnEliminated;
|
||||
};
|
||||
|
||||
|
||||
/** a ReduceSplit class based on a repeated deterministic (reverse!) tournament
|
||||
To be used in SSGA-like replacements (e.g. see eoSSGADetTournamentReplacement)
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoDetTournamentTruncateSplit : public eoReduceSplit<EOT>
|
||||
{
|
||||
public:
|
||||
/** Ctor: must provide amount of reduction,
|
||||
and whether or not you need to return the eliminated guys
|
||||
*/
|
||||
eoDetTournamentTruncateSplit(unsigned _t_size, eoHowMany _howMany,
|
||||
bool _returnEliminated = false):
|
||||
t_size(_t_size), howMany(_howMany),
|
||||
returnEliminated(_returnEliminated)
|
||||
{
|
||||
if (t_size < 2)
|
||||
{
|
||||
std::cout << "Warning, Size for eoDetTournamentTruncateSplit adjusted to 2\n";
|
||||
t_size = 2;
|
||||
}
|
||||
}
|
||||
|
||||
/** Performs repeated inverse_deterministic_tournament on the pop */
|
||||
void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated)
|
||||
// BUG??? void operator()(eoPop<EOT>& _newgen, unsigned _newsize)
|
||||
{
|
||||
unsigned popSize = _newgen.size();
|
||||
unsigned eliminated = howMany(popSize);
|
||||
if (!eliminated) // nothing to do
|
||||
return ;
|
||||
unsigned newsize = popSize - eliminated;
|
||||
if (newsize < 0)
|
||||
throw std::logic_error("eoDetTournamentTruncateSplit: Cannot truncate to a larger size!\n");
|
||||
|
||||
|
||||
_eliminated.reserve(_eliminated.size()+eliminated); //in case not empty?
|
||||
for (unsigned i=0; i<eliminated; i++)
|
||||
{
|
||||
typename eoPop<EOT>::iterator it = inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size);
|
||||
if (returnEliminated)
|
||||
_eliminated.push_back(*it);
|
||||
_newgen.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned t_size;
|
||||
eoHowMany howMany;
|
||||
bool returnEliminated;
|
||||
};
|
||||
|
||||
/** a ReduceSplit class based on a repeated deterministic (reverse!) tournament
|
||||
To be used in SSGA-like replacements (e.g. see eoSSGAStochTournamentReplacement)
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoStochTournamentTruncateSplit : public eoReduce<EOT>
|
||||
{
|
||||
public:
|
||||
/** Ctor: must provide amount of reduction,
|
||||
and whether or not you need to return the eliminated guys
|
||||
*/
|
||||
eoStochTournamentTruncateSplit(double _t_rate, eoHowMany _howMany,
|
||||
bool _returnEliminated = false):
|
||||
t_rate(_t_rate), howMany(_howMany),
|
||||
returnEliminated(_returnEliminated)
|
||||
{
|
||||
if (t_rate <= 0.5)
|
||||
{
|
||||
std::cout << "Warning, Rate for eoStochTournamentTruncateSplit adjusted to 0.51\n";
|
||||
t_rate = 0.51;
|
||||
}
|
||||
if (t_rate > 1)
|
||||
{
|
||||
std::cout << "Warning, Rate for eoStochTournamentTruncateSplit adjusted to 1\n";
|
||||
t_rate = 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** Performs repeated inverse_stochastic_tournament on the pop */
|
||||
void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated)
|
||||
//BUG??? void operator()(eoPop<EOT>& _newgen, unsigned _newsize)
|
||||
{
|
||||
/* old version
|
||||
if (!_eliminated.size()) // nothing to do
|
||||
return;
|
||||
unsigned oldSize = _newgen.size();
|
||||
unsigned newSize = oldSize - _eliminated.size();
|
||||
unsigned eliminated = howMany(popSize);
|
||||
if (newSize < 0)
|
||||
throw std::logic_error("eoStochTournamentTruncateSplit: Cannot truncate to a larger size!\n");
|
||||
|
||||
end of old version */
|
||||
|
||||
unsigned popSize = _newgen.size();
|
||||
unsigned eliminated = howMany(popSize);
|
||||
if (!eliminated) // nothing to do
|
||||
return ;
|
||||
unsigned newsize = popSize - eliminated;
|
||||
if (newsize < 0)
|
||||
throw std::logic_error("eoDetTournamentTruncateSplit: Cannot truncate to a larger size!\n");
|
||||
|
||||
|
||||
|
||||
_eliminated.reserve(_eliminated.size()+eliminated); //in case not empty?
|
||||
for (unsigned i=0; i<_eliminated.size(); i++)
|
||||
{
|
||||
typename eoPop<EOT>::iterator it = inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate);
|
||||
if (returnEliminated)
|
||||
_eliminated.push_back(*it);
|
||||
_newgen.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
double t_rate;
|
||||
eoHowMany howMany;
|
||||
bool returnEliminated;
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue