Merge from rc2.0
git-svn-id: svn://scm.gforge.inria.fr/svnroot/paradiseo@2713 331e1502-861f-0410-8da2-ba01fb791d7f
This commit is contained in:
parent
71864c2a6e
commit
409a1b21b8
1731 changed files with 104909 additions and 64375 deletions
54
trunk/eo/src/CMakeLists.txt
Normal file
54
trunk/eo/src/CMakeLists.txt
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
######################################################################################
|
||||
### 1) Include the sources
|
||||
######################################################################################
|
||||
|
||||
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
######################################################################################
|
||||
### 2) Define the eo target
|
||||
######################################################################################
|
||||
|
||||
SET(EO_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib)
|
||||
SET(LIBRARY_OUTPUT_PATH ${EO_LIB_OUTPUT_PATH})
|
||||
|
||||
SET(EO_SOURCES
|
||||
eoFunctorStore.cpp
|
||||
eoPersistent.cpp
|
||||
eoPrintable.cpp
|
||||
eoCtrlCContinue.cpp
|
||||
eoScalarFitnessAssembled.cpp
|
||||
eoSIGContinue.cpp
|
||||
)
|
||||
|
||||
ADD_LIBRARY(eo STATIC ${EO_SOURCES})
|
||||
INSTALL(TARGETS eo ARCHIVE DESTINATION ${LIB} COMPONENT libraries)
|
||||
|
||||
FILE(GLOB HDRS *.h eo)
|
||||
INSTALL(FILES ${HDRS} DESTINATION include${INSTALL_SUB_DIR}/eo COMPONENT headers)
|
||||
|
||||
INSTALL(DIRECTORY do es ga gp other utils
|
||||
DESTINATION include${INSTALL_SUB_DIR}/eo
|
||||
COMPONENT headers
|
||||
FILES_MATCHING PATTERN "*.h" PATTERN "checkpointing" PATTERN external_eo
|
||||
)
|
||||
|
||||
######################################################################################
|
||||
### 3) Optionnal: define your target(s)'s version: no effect for windows
|
||||
######################################################################################
|
||||
|
||||
SET(EO_VERSION ${GLOBAL_VERSION})
|
||||
SET_TARGET_PROPERTIES(eo PROPERTIES VERSION "${EO_VERSION}")
|
||||
|
||||
######################################################################################
|
||||
### 4) Where must cmake go now ?
|
||||
######################################################################################
|
||||
|
||||
ADD_SUBDIRECTORY(es)
|
||||
ADD_SUBDIRECTORY(ga)
|
||||
ADD_SUBDIRECTORY(utils)
|
||||
|
||||
IF(ENABLE_PYEO)
|
||||
ADD_SUBDIRECTORY(pyeo)
|
||||
ENDIF(ENABLE_PYEO)
|
||||
|
||||
######################################################################################
|
||||
173
trunk/eo/src/EO.h
Normal file
173
trunk/eo/src/EO.h
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
// -*- 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
|
||||
|
||||
/**
|
||||
@defgroup Core Core components
|
||||
|
||||
This are the base classes from which useful objects inherits.
|
||||
|
||||
@{
|
||||
*/
|
||||
|
||||
/** EO is the base class for objects with a fitness.
|
||||
|
||||
Those evolvable objects are 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.
|
||||
|
||||
A fitness can be invalid if undefined, trying to read an invalid fitness will raise an error.
|
||||
@ref Operators that effectively modify EO objects must invalidate them.
|
||||
|
||||
The fitness object must have, besides an void ctor, a copy ctor.
|
||||
|
||||
@example t-eo.cpp
|
||||
*/
|
||||
template<class F = double> class EO: public eoObject, public eoPersistent
|
||||
{
|
||||
public:
|
||||
typedef F Fitness;
|
||||
|
||||
/** Default constructor.
|
||||
*/
|
||||
EO(): repFitness(Fitness()), invalidFitness(true) { }
|
||||
|
||||
/// Virtual dtor
|
||||
virtual ~EO() {};
|
||||
|
||||
/// Return fitness value.
|
||||
const Fitness& fitness() const {
|
||||
if (invalid())
|
||||
throw std::runtime_error("invalid fitness");
|
||||
return repFitness;
|
||||
}
|
||||
|
||||
/// Get fitness as reference, useful when fitness is set in a multi-stage way, e.g., MOFitness gets performance information, is subsequently ranked
|
||||
Fitness& fitnessReference() {
|
||||
if (invalid()) throw std::runtime_error("invalid fitness");
|
||||
return repFitness;
|
||||
}
|
||||
|
||||
// Set fitness as invalid.
|
||||
void invalidate() { invalidFitness = true; repFitness = Fitness(); }
|
||||
|
||||
/** 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
|
||||
|
||||
/** @} */
|
||||
191
trunk/eo/src/PO.h
Normal file
191
trunk/eo/src/PO.h
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// PO.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef PO_H
|
||||
#define PO_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <stdexcept>
|
||||
#include <EO.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** PO inheriting from EO is specially designed for particle swarm optimization particle.POs have got a fitness,
|
||||
which at the same time needs to be only an object with the operation less than (<)
|
||||
defined. A best fitness also belongs to the particle.Fitness says how
|
||||
good is the particle for a current iteration whereas the best fitness can be saved for
|
||||
many iterations.
|
||||
|
||||
@ingroup Core
|
||||
*/
|
||||
template < class F > class PO:public EO < F >
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
#if defined(__CUDACC__)
|
||||
typedef typename EO < F >::Fitness Fitness;
|
||||
#else
|
||||
typedef typename PO<F>::Fitness Fitness;
|
||||
#endif
|
||||
|
||||
/** Default constructor.
|
||||
Fitness must have a ctor which takes 0 as a value. Best fitness mush also have the same constructor.
|
||||
*/
|
||||
PO ():repFitness (Fitness ()), invalidFitness (true),
|
||||
bestFitness (Fitness()){}
|
||||
|
||||
|
||||
/// Return fitness value.
|
||||
Fitness fitness () const
|
||||
{
|
||||
if (invalid ())
|
||||
throw std::runtime_error ("invalid fitness in PO.h");
|
||||
return repFitness;
|
||||
}
|
||||
|
||||
|
||||
/** Set fitness. At the same time, validates it.
|
||||
* @param _fitness New fitness value.
|
||||
*/
|
||||
void fitness (const Fitness & _fitness)
|
||||
{
|
||||
repFitness = _fitness;
|
||||
invalidFitness = false;
|
||||
}
|
||||
|
||||
/** Return the best fitness.
|
||||
* @return bestFitness
|
||||
*/
|
||||
Fitness best () const
|
||||
{
|
||||
if (invalid ())
|
||||
throw std::runtime_error ("invalid best fitness in PO.h");
|
||||
return bestFitness;
|
||||
}
|
||||
|
||||
|
||||
/** Set the best fitness.
|
||||
* @param _bestFitness New best fitness found for the particle.
|
||||
*/
|
||||
void best (const Fitness & _bestFitness)
|
||||
{
|
||||
bestFitness = _bestFitness;
|
||||
invalidBestFitness = false;
|
||||
}
|
||||
|
||||
|
||||
/** Return true If fitness value is invalid, false otherwise.
|
||||
* @return true If fitness is invalid.
|
||||
*/
|
||||
bool invalid () const
|
||||
{
|
||||
return invalidFitness;
|
||||
}
|
||||
|
||||
/** Invalidate the fitness.
|
||||
* @return
|
||||
*/
|
||||
void invalidate ()
|
||||
{
|
||||
invalidFitness = true;
|
||||
}
|
||||
|
||||
/** Return true If the best fitness value is invalid, false otherwise.
|
||||
* @return true If the bestfitness is invalid.
|
||||
*/
|
||||
bool invalidBest () const
|
||||
{
|
||||
return invalidBestFitness;
|
||||
}
|
||||
|
||||
/** Invalidate the best fitness.
|
||||
* @return
|
||||
*/
|
||||
void invalidateBest ()
|
||||
{
|
||||
invalidBestFitness = true;
|
||||
}
|
||||
|
||||
/** Return the class id.
|
||||
* @return the class name as a std::string
|
||||
*/
|
||||
virtual std::string className () const
|
||||
{
|
||||
return "PO";
|
||||
}
|
||||
|
||||
/** Returns true if
|
||||
@return true if the fitness is higher
|
||||
*/
|
||||
bool operator< (const PO & _po2) const { return fitness () < _po2.fitness ();}
|
||||
bool operator> (const PO & _po2) const { return !(fitness () <= _po2.fitness ());}
|
||||
|
||||
|
||||
/**
|
||||
* Write object. Called printOn since it prints the object _on_ a stream.
|
||||
* @param _os A std::ostream.
|
||||
*/
|
||||
virtual void printOn(std::ostream& _os) const { _os << bestFitness << ' ' ;}
|
||||
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
Fitness repFitness; // value of fitness for this particle
|
||||
bool invalidFitness; // true if the value of the fitness is invalid
|
||||
|
||||
Fitness bestFitness; // value of the best fitness found for the particle
|
||||
bool invalidBestFitness; // true if the value of the best fitness is invalid
|
||||
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif /*PO_H */
|
||||
119
trunk/eo/src/apply.h
Normal file
119
trunk/eo/src/apply.h
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
// -*- 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 <utils/eoParallel.h>
|
||||
#include <utils/eoParser.h>
|
||||
#include <utils/eoLogger.h>
|
||||
#include <eoFunctor.h>
|
||||
#include <vector>
|
||||
#include <omp.h>
|
||||
|
||||
/**
|
||||
Applies a unary function to a std::vector of things.
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
template <class EOT>
|
||||
void apply(eoUF<EOT&, void>& _proc, std::vector<EOT>& _pop)
|
||||
{
|
||||
size_t size = _pop.size();
|
||||
|
||||
#ifdef _OPENMP
|
||||
|
||||
double t1 = 0;
|
||||
|
||||
if ( eo::parallel.enableResults() )
|
||||
{
|
||||
t1 = omp_get_wtime();
|
||||
}
|
||||
|
||||
if (!eo::parallel.isDynamic())
|
||||
{
|
||||
#pragma omp parallel for if(eo::parallel.isEnabled()) //default(none) shared(_proc, _pop, size)
|
||||
for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); }
|
||||
}
|
||||
else
|
||||
{
|
||||
#pragma omp parallel for schedule(dynamic) if(eo::parallel.isEnabled())
|
||||
//doesnot work with gcc 4.1.2
|
||||
//default(none) shared(_proc, _pop, size)
|
||||
for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); }
|
||||
}
|
||||
|
||||
if ( eo::parallel.enableResults() )
|
||||
{
|
||||
double t2 = omp_get_wtime();
|
||||
eoLogger log;
|
||||
log << eo::file(eo::parallel.prefix()) << t2 - t1 << ' ';
|
||||
}
|
||||
|
||||
#else // _OPENMP
|
||||
|
||||
for (size_t i = 0; i < size; ++i) { _proc(_pop[i]); }
|
||||
|
||||
#endif // !_OPENMP
|
||||
}
|
||||
|
||||
/**
|
||||
This is a variant of apply<EOT> which is called in parallel
|
||||
thanks to OpenMP.
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
// template <class EOT>
|
||||
// void omp_apply(eoUF<EOT&, void>& _proc, std::vector<EOT>& _pop)
|
||||
// {
|
||||
// size_t size = _pop.size();
|
||||
// #pragma omp parallel for if(eo::parallel.isEnabled())
|
||||
// //doesnot work with gcc 4.1.2
|
||||
// //default(none) shared(_proc, _pop, size)
|
||||
// for (size_t i = 0; i < size; ++i)
|
||||
// {
|
||||
// _proc(_pop[i]);
|
||||
// }
|
||||
// }
|
||||
|
||||
/**
|
||||
And now we are using the dynamic scheduling.
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
// template <class EOT>
|
||||
// void omp_dynamic_apply(eoUF<EOT&, void>& _proc, std::vector<EOT>& _pop)
|
||||
// {
|
||||
// size_t size = _pop.size();
|
||||
// #pragma omp parallel for if(eo::parallel.isEnabled()) schedule(dynamic)
|
||||
// //doesnot work with gcc 4.1.2
|
||||
// //default(none) shared(_proc, _pop, size)
|
||||
// for (size_t i = 0; i < size; ++i)
|
||||
// {
|
||||
// _proc(_pop[i]);
|
||||
// }
|
||||
// }
|
||||
|
||||
#endif
|
||||
36
trunk/eo/src/do/Readme
Normal file
36
trunk/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
|
||||
389
trunk/eo/src/do/make_algo_easea.h
Normal file
389
trunk/eo/src/do/make_algo_easea.h
Normal file
|
|
@ -0,0 +1,389 @@
|
|||
// -*- 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
|
||||
*
|
||||
*
|
||||
* @ingroup Builders
|
||||
*/
|
||||
template <class EOT>
|
||||
eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalFunc<EOT>& _popeval, 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, _popeval, *breed, *ptReplace);
|
||||
_state.storeFunctor(algo);
|
||||
// that's it!
|
||||
return *algo;
|
||||
}
|
||||
|
||||
/*
|
||||
* 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)
|
||||
{
|
||||
do_make_algo_scalar( _parser, _state, *(new eoPopLoopEval<EOT>(_eval)), _continue, _op);
|
||||
}
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
313
trunk/eo/src/do/make_algo_scalar.h
Normal file
313
trunk/eo/src/do/make_algo_scalar.h
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
// -*- 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
|
||||
*
|
||||
* @ingroup Builders
|
||||
*/
|
||||
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;
|
||||
}
|
||||
/** @example t-eoGA.cpp
|
||||
*/
|
||||
|
||||
#endif
|
||||
353
trunk/eo/src/do/make_checkpoint.h
Normal file
353
trunk/eo/src/do/make_checkpoint.h
Normal file
|
|
@ -0,0 +1,353 @@
|
|||
// -*- 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
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#include <climits>
|
||||
|
||||
#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 //////////////
|
||||
|
||||
/**
|
||||
*
|
||||
* CHANGE (March 2008): now receiving an eoValueParam instead of an eoEvalFuncCounter. This function is just interested
|
||||
* in the value of the parameter calculated on the evaluation function, not in the actual function itself!!
|
||||
*
|
||||
* @ingroup Builders
|
||||
*/
|
||||
template <class EOT>
|
||||
eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValueParam<unsigned long>& _eval, eoContinue<EOT>& _continue)
|
||||
{
|
||||
// first, create a checkpoint from the eoContinue
|
||||
eoCheckPoint<EOT> *checkpoint = new eoCheckPoint<EOT>(_continue);
|
||||
|
||||
_state.storeFunctor(checkpoint);
|
||||
|
||||
////////////////////
|
||||
// Signal monitoring
|
||||
////////////////////
|
||||
|
||||
#ifndef _MSC_VER
|
||||
// the CtrlC monitoring interception
|
||||
eoSignal<EOT> *mon_ctrlCCont;
|
||||
eoValueParam<bool>& mon_ctrlCParam = _parser.createParam(false, "monitor-with-CtrlC", "Monitor current generation upon Ctrl C",0, "Stopping criterion");
|
||||
if (mon_ctrlCParam.value())
|
||||
{
|
||||
mon_ctrlCCont = new eoSignal<EOT>;
|
||||
// store
|
||||
_state.storeFunctor(mon_ctrlCCont);
|
||||
// add to checkpoint
|
||||
checkpoint->add(*mon_ctrlCCont);
|
||||
}
|
||||
#endif
|
||||
|
||||
///////////////////
|
||||
// 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);
|
||||
// check if monitoring with signal
|
||||
if ( mon_ctrlCParam.value() )
|
||||
mon_ctrlCCont->add(*bestStat);
|
||||
}
|
||||
|
||||
// Average fitness alone
|
||||
//----------------------
|
||||
eoAverageStat<EOT> *averageStat = NULL; // do we need averageStat?
|
||||
if ( printBestParam.value() || plotBestParam.value() || fileBestParam.value() ) // we need it for gnuplot output
|
||||
{
|
||||
averageStat = new eoAverageStat<EOT>;
|
||||
// store it
|
||||
_state.storeFunctor(averageStat);
|
||||
// add it to the checkpoint
|
||||
checkpoint->add(*averageStat);
|
||||
// check if monitoring with signal
|
||||
if ( mon_ctrlCParam.value() )
|
||||
mon_ctrlCCont->add(*averageStat);
|
||||
}
|
||||
|
||||
// Second moment stats: average and stdev
|
||||
//---------------------------------------
|
||||
eoSecondMomentStats<EOT> *secondStat = NULL;
|
||||
if ( printBestParam.value() || fileBestParam.value() ) // we need it for screen output or file output
|
||||
{
|
||||
secondStat = new eoSecondMomentStats<EOT>;
|
||||
// store it
|
||||
_state.storeFunctor(secondStat);
|
||||
// add it to the checkpoint
|
||||
checkpoint->add(*secondStat);
|
||||
// check if monitoring with signal
|
||||
if ( mon_ctrlCParam.value() )
|
||||
mon_ctrlCCont->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);
|
||||
// check if monitoring with signal
|
||||
if ( mon_ctrlCParam.value() )
|
||||
mon_ctrlCCont->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)
|
||||
// check if monitoring with signal
|
||||
if ( ! mon_ctrlCParam.value() )
|
||||
checkpoint->add(*monitor);
|
||||
else
|
||||
mon_ctrlCCont->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);
|
||||
// check if monitoring with signal
|
||||
if ( ! mon_ctrlCParam.value() )
|
||||
checkpoint->add(*tCounter);
|
||||
else
|
||||
mon_ctrlCCont->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 defined(HAVE_GNUPLOT)
|
||||
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);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
//////////////////////////////////
|
||||
// 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
|
||||
303
trunk/eo/src/do/make_checkpoint_FDC.h
Normal file
303
trunk/eo/src/do/make_checkpoint_FDC.h
Normal file
|
|
@ -0,0 +1,303 @@
|
|||
// -*- 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 <climits>
|
||||
|
||||
#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 //////////////
|
||||
|
||||
|
||||
/**
|
||||
* @ingroup Builders
|
||||
*/
|
||||
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
|
||||
212
trunk/eo/src/do/make_checkpoint_assembled.h
Normal file
212
trunk/eo/src/do/make_checkpoint_assembled.h
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
/* -*- 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
|
||||
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#include <climits>
|
||||
#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!!!
|
||||
*
|
||||
*
|
||||
* @ingroup Builders
|
||||
* */
|
||||
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);
|
||||
#ifdef HAVE_GNUPLOT
|
||||
// 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]);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// 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
|
||||
167
trunk/eo/src/do/make_continue.h
Normal file
167
trunk/eo/src/do/make_continue.h
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
// -*- 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 ////////////////
|
||||
/**
|
||||
* @ingroup Builders
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @ingroup Builders
|
||||
*/
|
||||
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
|
||||
184
trunk/eo/src/do/make_general_replacement.h
Normal file
184
trunk/eo/src/do/make_general_replacement.h
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
// -*- 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)
|
||||
*
|
||||
* @ingroup Builders
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @ingroup Builders
|
||||
*/
|
||||
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
|
||||
116
trunk/eo/src/do/make_pop.h
Normal file
116
trunk/eo/src/do/make_pop.h
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
// -*- 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>
|
||||
|
||||
/** @defgroup Builders Automatic builders
|
||||
*
|
||||
* Automatic builders are functions that automagically builds most commons instances for you.
|
||||
*
|
||||
* All the options you needs are set in the command-line parser.
|
||||
* Those functions all start with the "do_make_" prefix.
|
||||
*
|
||||
* @ingroup Utilities
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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)
|
||||
*
|
||||
* @ingroup Builders
|
||||
*/
|
||||
template <class EOT>
|
||||
eoPop<EOT>& do_make_pop(eoParser & _parser, eoState& _state, eoInit<EOT> & _init)
|
||||
{
|
||||
// random seed
|
||||
eoValueParam<uint32_t>& seedParam = _parser.getORcreateParam(uint32_t(0), "seed", "Random number seed", 'S');
|
||||
if (seedParam.value() == 0)
|
||||
seedParam.value() = time(0);
|
||||
eoValueParam<unsigned>& popSize = _parser.getORcreateParam(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.getORcreateParam(std::string(""), "Load","A save file to restart from",'L', "Persistence" );
|
||||
eoValueParam<bool> & recomputeFitnessParam = _parser.getORcreateParam(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
|
||||
46
trunk/eo/src/do/make_run.h
Normal file
46
trunk/eo/src/do/make_run.h
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
// -*- 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
|
||||
*
|
||||
*
|
||||
* @ingroup Builders
|
||||
*/
|
||||
template <class EOT>
|
||||
void do_run(eoAlgo<EOT>& _algo, eoPop<EOT>& _pop)
|
||||
{
|
||||
_algo(_pop);
|
||||
}
|
||||
|
||||
#endif
|
||||
209
trunk/eo/src/eo
Normal file
209
trunk/eo/src/eo
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
//-----------------------------------------------------------------------------
|
||||
// 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 <eoDualFitness.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>
|
||||
#include <eoEvalCounterThrowException.h>
|
||||
#include <eoEvalTimeThrowException.h>
|
||||
#include <eoEvalUserTimeThrowException.h>
|
||||
|
||||
// Continuators - all include eoContinue.h
|
||||
#include <eoCombinedContinue.h>
|
||||
#include <eoGenContinue.h>
|
||||
#include <eoSteadyFitContinue.h>
|
||||
#include <eoEvalContinue.h>
|
||||
#include <eoFitContinue.h>
|
||||
#include <eoPeriodicContinue.h>
|
||||
#include <eoTimeContinue.h> // added th T.Legrand
|
||||
#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 <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 ...
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/*** Particle Swarm Optimization stuff ***/
|
||||
|
||||
// basic particle definitions
|
||||
#include <PO.h>
|
||||
#include <eoVectorParticle.h>
|
||||
#include <eoBitParticle.h>
|
||||
#include <eoRealParticle.h>
|
||||
|
||||
// initialization
|
||||
#include <eoParticleBestInit.h>
|
||||
#include <eoInitializer.h>
|
||||
|
||||
// velocities
|
||||
#include <eoVelocity.h>
|
||||
#include <eoStandardVelocity.h>
|
||||
#include <eoExtendedVelocity.h>
|
||||
#include <eoIntegerVelocity.h>
|
||||
#include <eoConstrictedVelocity.h>
|
||||
#include <eoFixedInertiaWeightedVelocity.h>
|
||||
#include <eoVariableInertiaWeightedVelocity.h>
|
||||
#include <eoConstrictedVariableWeightVelocity.h>
|
||||
|
||||
// flights
|
||||
#include <eoFlight.h>
|
||||
#include <eoStandardFlight.h>
|
||||
#include <eoVelocityInit.h>
|
||||
#include <eoBinaryFlight.h>
|
||||
#include <eoSigBinaryFlight.h>
|
||||
|
||||
// topologies
|
||||
#include <eoTopology.h>
|
||||
#include <eoStarTopology.h>
|
||||
#include <eoLinearTopology.h>
|
||||
#include <eoRingTopology.h>
|
||||
#include <eoNeighborhood.h>
|
||||
#include <eoSocialNeighborhood.h>
|
||||
|
||||
// PS algorithms
|
||||
#include <eoPSO.h>
|
||||
#include <eoEasyPSO.h>
|
||||
#include <eoSyncEasyPSO.h>
|
||||
|
||||
// utils
|
||||
#include <eoRealBoundModifier.h>
|
||||
#include <eoRandomRealWeightUp.h>
|
||||
#include <eoWeightUpdater.h>
|
||||
#include <eoLinearDecreasingWeightUp.h>
|
||||
#include <eoGaussRealWeightUp.h>
|
||||
|
||||
#include <utils/eoLogger.h>
|
||||
#include <utils/eoParallel.h>
|
||||
|
||||
#endif
|
||||
|
||||
// Local Variables:
|
||||
// mode: C++
|
||||
// End:
|
||||
56
trunk/eo/src/eoAlgo.h
Normal file
56
trunk/eo/src/eoAlgo.h
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
// -*- 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>
|
||||
|
||||
/**
|
||||
@defgroup Algorithms Algorithms
|
||||
|
||||
In EO, an algorithm is a functor that takes one or several solutions to an optimization
|
||||
problem as arguments, and iteratively modify them with the help of operators.
|
||||
|
||||
Generally, an EO object is built by assembling together @ref Operators in an algorithm instance,
|
||||
and then calling the algorithm's operator() on an initial population (an eoPop). The algorithm will then
|
||||
manipulate the solutions within the population to search for the problem's optimum.
|
||||
*/
|
||||
|
||||
/**
|
||||
This is the base 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.
|
||||
|
||||
@ingroup Algorithms
|
||||
*/
|
||||
template< class EOT >
|
||||
class eoAlgo : public eoUF<eoPop<EOT>&, void>
|
||||
{};
|
||||
|
||||
|
||||
#endif
|
||||
44
trunk/eo/src/eoBinaryFlight.h
Normal file
44
trunk/eo/src/eoBinaryFlight.h
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoBinaryFlight.h
|
||||
// (c) OPAC Team, 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EOBINARYFLIGHT_H
|
||||
#define EOBINARYFLIGHT_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoFlight.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
/** Abstract class for binary flight of particle swarms. Positions are updated but are expected to be binary.
|
||||
* A function must be used to decide, according to continuous velocities, of the
|
||||
* new positions (0,1 ... ?)
|
||||
*
|
||||
* @ingroup Core
|
||||
*/
|
||||
template < class POT > class eoBinaryFlight:public eoFlight < POT >{};
|
||||
|
||||
|
||||
|
||||
#endif /*EOBINARYFLIGHT_H */
|
||||
50
trunk/eo/src/eoBitParticle.h
Normal file
50
trunk/eo/src/eoBitParticle.h
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoBitParticle.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _EOBITPARTICLE_H
|
||||
#define _EOBITPARTICLE_H
|
||||
|
||||
|
||||
#include <eoVectorParticle.h>
|
||||
|
||||
|
||||
/** eoBitParticle: Implementation of a bit-coded particle (swarm optimization).
|
||||
* Positions and best positions are 0 or 1 but the velocity is a vector of double.
|
||||
*
|
||||
* @ingroup Bitstring
|
||||
*/
|
||||
template < class FitT> class eoBitParticle: public eoVectorParticle<FitT,bool,double>
|
||||
|
||||
{
|
||||
public:
|
||||
|
||||
eoBitParticle(unsigned size = 0, bool positions = 0,double velocities = 0.0,bool bestPositions = 0): eoVectorParticle<FitT, bool,double> (size, positions,velocities,bestPositions) {}
|
||||
|
||||
virtual std::string className() const
|
||||
{
|
||||
return "eoBitParticle";
|
||||
}
|
||||
};
|
||||
|
||||
#endif /*_EOBITPARTICLE_H*/
|
||||
79
trunk/eo/src/eoBreed.h
Normal file
79
trunk/eo/src/eoBreed.h
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
/** -*- 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
|
||||
|
||||
@ingroup Combination
|
||||
*/
|
||||
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
|
||||
|
||||
@ingroup Combination
|
||||
*/
|
||||
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
|
||||
162
trunk/eo/src/eoCellularEasyEA.h
Normal file
162
trunk/eo/src/eoCellularEasyEA.h
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
// -*- 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.
|
||||
|
||||
@ingroup Algorithms
|
||||
*/
|
||||
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
|
||||
82
trunk/eo/src/eoCloneOps.h
Normal file
82
trunk/eo/src/eoCloneOps.h
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
// -*- 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: /home/nojhan/dev/eodev/eodev_cvs/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 :-)
|
||||
*
|
||||
* @addtogroup Core
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
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
|
||||
/** @} */
|
||||
102
trunk/eo/src/eoCombinedContinue.h
Normal file
102
trunk/eo/src/eoCombinedContinue.h
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
// -*- 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
|
||||
Authors :
|
||||
todos@geneura.ugr.es
|
||||
Marc Schoenauer
|
||||
Ramón Casero Cañas
|
||||
Johann Dréo
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#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
|
||||
|
||||
@ingroup Combination
|
||||
*/
|
||||
template< class EOT>
|
||||
class eoCombinedContinue: public eoContinue<EOT>, public std::vector<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>(), std::vector<eoContinue<EOT>* >(1, &_cont)
|
||||
{
|
||||
}
|
||||
|
||||
/// Ctor - for historical reasons ... should disspear some day
|
||||
eoCombinedContinue( eoContinue<EOT>& _cont1, eoContinue<EOT>& _cont2)
|
||||
: eoContinue<EOT>(), std::vector<eoContinue<EOT>* >()
|
||||
{
|
||||
#ifndef DEPRECATED_MESSAGES
|
||||
#pragma message "The double continuators constructor of eocombinedContinue is deprecated and will be removed in the next release."
|
||||
#endif // !DEPRECATED_MESSAGES
|
||||
|
||||
this->push_back(&_cont1);
|
||||
this->push_back(&_cont2);
|
||||
}
|
||||
|
||||
void add(eoContinue<EOT> & _cont)
|
||||
{
|
||||
this->push_back(&_cont);
|
||||
}
|
||||
|
||||
void removeLast(void)
|
||||
{
|
||||
#ifndef DEPRECATED_MESSAGES
|
||||
#pragma message "The removeLast method of eocombinedContinue is deprecated and will be removed in the next release, use pop_back instead."
|
||||
#endif // !DEPRECATED_MESSAGES
|
||||
|
||||
this->pop_back();
|
||||
}
|
||||
|
||||
|
||||
/** Returns false when one of the embedded continuators say so (logical and)
|
||||
*/
|
||||
virtual bool operator() ( const eoPop<EOT>& _pop )
|
||||
{
|
||||
for (unsigned i = 0; i < this->size(); ++i)
|
||||
if ( ! (*this->at(i))(_pop) ) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoCombinedContinue"; }
|
||||
|
||||
//private:
|
||||
// std::vector<eoContinue<EOT>*> continuators;
|
||||
};
|
||||
|
||||
#endif
|
||||
92
trunk/eo/src/eoCombinedInit.h
Normal file
92
trunk/eo/src/eoCombinedInit.h
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
// -*- 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
|
||||
|
||||
@ingroup Initializators
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
void add(eoInit<EOT> & _init, double _rate, bool _verbose)
|
||||
{
|
||||
eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoCombinedInit::add is deprecated and will be removed in the next release." << std::endl;
|
||||
add( _init, _rate );
|
||||
}
|
||||
|
||||
/** The usual method to add objects to the combination
|
||||
*/
|
||||
void add(eoInit<EOT> & _init, double _rate)
|
||||
{
|
||||
initializers.push_back(&_init);
|
||||
rates.push_back(_rate);
|
||||
// compute the relative rates in percent - to warn the user!
|
||||
printOn( eo::log << eo::logging );
|
||||
}
|
||||
|
||||
/** 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
|
||||
209
trunk/eo/src/eoConstrictedVariableWeightVelocity.h
Normal file
209
trunk/eo/src/eoConstrictedVariableWeightVelocity.h
Normal file
|
|
@ -0,0 +1,209 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoConstrictedVariableWeightVelocity.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EOCONSTRICTEDVARIABLEWEIGHTVELOCITY_H
|
||||
#define EOCONSTRICTEDVARIABLEWEIGHTVELOCITY_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoVelocity.h>
|
||||
#include <eoTopology.h>
|
||||
#include <eoWeightUpdater.h>
|
||||
#include <utils/eoRealVectorBounds.h>
|
||||
#include <eoRealBoundModifier.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
/** Inertia variable + constriction velocity for particle swarm optimization. Derivated from abstract eoVelocity,
|
||||
* At step t: v(t+1)= K * ( w*v(t) + c1*r1* (xbest(t)-x(t)) + c2*r2* (gbest(t) - x(t)))
|
||||
* w is updated each time the velocity performer is called and K is fixed
|
||||
* (ci given and Ri chosen at random in [0;1]).
|
||||
*
|
||||
* @ingroup Variators
|
||||
*/
|
||||
template < class POT > class eoConstrictedVariableWeightVelocity:public eoVelocity < POT >
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
/*
|
||||
* Each element for the velocity evaluation is expected to be of type VelocityType.
|
||||
*/
|
||||
typedef typename POT::ParticleVelocityType VelocityType;
|
||||
|
||||
/** Full constructor: Bounds and bound modifier required
|
||||
* @param _topology - The topology to get the global/local/other best
|
||||
* @param _coeff - The constriction coefficient
|
||||
* @param _weightUpdater - An eoWeightUpdater used to update the inertia weight
|
||||
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
|
||||
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
|
||||
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
|
||||
* @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _coeff,
|
||||
eoWeightUpdater<VelocityType> & _weightUpdater,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2 ,
|
||||
eoRealVectorBounds & _bounds,
|
||||
eoRealBoundModifier & _bndsModifier,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
coeff(_coeff),
|
||||
weightUpdater(_weightUpdater),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
bounds(_bounds),
|
||||
bndsModifier(_bndsModifier),
|
||||
gen(_gen){}
|
||||
|
||||
|
||||
/** Constructor: No bound updater required <-> fixed bounds
|
||||
* @param _topology - The topology to get the global/local/other best
|
||||
* @param _coeff - The constriction coefficient
|
||||
* @param _weightUpdater - An eoWeightUpdater used to update the inertia weight
|
||||
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
|
||||
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
|
||||
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _coeff,
|
||||
eoWeightUpdater<VelocityType> & _weightUpdater,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2,
|
||||
eoRealVectorBounds & _bounds,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
coeff(_coeff),
|
||||
weightUpdater(_weightUpdater),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
bounds(_bounds),
|
||||
bndsModifier(dummyModifier),
|
||||
gen(_gen){}
|
||||
|
||||
|
||||
/** Constructor: Neither bounds nor bound updater required <-> free velocity
|
||||
* @param _topology - The topology to get the global/local/other best*
|
||||
* @param _coeff - The constriction coefficient
|
||||
* @param _weightUpdater - An eoWeightUpdater used to update the inertia weight
|
||||
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _coeff,
|
||||
eoWeightUpdater<VelocityType> & _weightUpdater,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
coeff(_coeff),
|
||||
weightUpdater(_weightUpdater),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
bounds(*(new eoRealVectorNoBounds(0))),
|
||||
bndsModifier(dummyModifier),
|
||||
gen(_gen)
|
||||
{}
|
||||
|
||||
/**
|
||||
* Evaluate the new velocities of the given particle. Need an indice to identify the particle
|
||||
* into the topology. Steps are :
|
||||
* - evaluate r1 and r2, the customed learning factors
|
||||
* - adjust the size of the bounds (even if dummy)
|
||||
* - update the weight with the weightUpdater (use the dummy updater if there's no updater provided)
|
||||
* - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided)
|
||||
* @param _po - A particle
|
||||
* @param _indice - The indice (into the topology) of the given particle
|
||||
*/
|
||||
void operator () (POT & _po,unsigned _indice)
|
||||
{
|
||||
VelocityType r1;
|
||||
VelocityType r2;
|
||||
|
||||
VelocityType newVelocity;
|
||||
|
||||
// cast the learning factors to VelocityType
|
||||
r1 = (VelocityType) rng.uniform (1) * c1;
|
||||
r2 = (VelocityType) rng.uniform (1) * c2;
|
||||
|
||||
// need to resize the bounds even if there are dummy because of "isBounded" call
|
||||
bounds.adjust_size(_po.size());
|
||||
|
||||
// update the inertia weight
|
||||
weightUpdater(weight);
|
||||
|
||||
// assign the new velocities
|
||||
for (unsigned j = 0; j < _po.size (); j++)
|
||||
{
|
||||
newVelocity= coeff * (weight * _po.velocities[j] + r1 * (_po.bestPositions[j] - _po[j]) + r2 * (topology.best (_indice)[j] - _po[j]));
|
||||
|
||||
/* modify the bounds */
|
||||
bndsModifier(bounds,j);
|
||||
|
||||
/* check bounds */
|
||||
if (bounds.isMinBounded(j))
|
||||
newVelocity=(VelocityType)std::max(newVelocity,bounds.minimum(j));
|
||||
if (bounds.isMaxBounded(j))
|
||||
newVelocity=(VelocityType)std::min(newVelocity,bounds.maximum(j));
|
||||
|
||||
_po.velocities[j]=newVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the neighborhood.
|
||||
*/
|
||||
void updateNeighborhood(POT & _po,unsigned _indice)
|
||||
{
|
||||
topology.updateNeighborhood(_po,_indice);
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected:
|
||||
eoTopology < POT > & topology;
|
||||
|
||||
const VelocityType & coeff; // the fixed constriction coefficient
|
||||
eoWeightUpdater<VelocityType> & weightUpdater; // the updater used to make the weight evoluate
|
||||
|
||||
const VelocityType & c1; // learning factor 1
|
||||
const VelocityType & c2; // learning factor 2
|
||||
|
||||
eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type.
|
||||
eoRealBoundModifier & bndsModifier;
|
||||
|
||||
VelocityType weight;
|
||||
eoRng & gen; // the random generator
|
||||
|
||||
// If the bound modifier doesn't need to be used, use the dummy instance
|
||||
eoDummyRealBoundModifier dummyModifier;
|
||||
};
|
||||
|
||||
#endif /*EOCONSTRICTEDVARIABLEWEIGHTVELOCITY_H*/
|
||||
199
trunk/eo/src/eoConstrictedVelocity.h
Normal file
199
trunk/eo/src/eoConstrictedVelocity.h
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoConstrictedVelocity.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
clive.canape@inria.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EOCONSTRICTEDVELOCITY_H
|
||||
#define EOCONSTRICTEDVELOCITY_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoFunctor.h>
|
||||
#include <utils/eoRNG.h>
|
||||
#include <eoPop.h>
|
||||
#include <utils/eoRealVectorBounds.h>
|
||||
#include <eoTopology.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
/** Constricted velocity performer for particle swarm optimization. Derivated from abstract eoVelocity,
|
||||
* At step t+1 : v(t+1)= C * [ v(t) + c1*r1 * (xbest(t)-x(t)) + c2*r2 * (gbest(t) - x(t)) ]
|
||||
* C is fixed for all the particles and all the generations.
|
||||
* Default C = 2 * k / abs(2 - P - sqrt (P*(P-4)))
|
||||
* (ci and C given;P=c1*r1 + c2*r2 ; Ri chosen at random * in [0;1])
|
||||
*
|
||||
* @ingroup Variators
|
||||
*/
|
||||
template < class POT > class eoConstrictedVelocity:public eoVelocity < POT >
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
/*
|
||||
* Each element for the velocity evaluation is expected to be of type VelocityType.
|
||||
*/
|
||||
typedef typename POT::ParticleVelocityType VelocityType;
|
||||
|
||||
/** Full constructor: Bounds and bound modifier required
|
||||
* @param _topology - The topology to get the global/local/other best
|
||||
* @param _coeff - The constriction coefficient
|
||||
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
|
||||
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
|
||||
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
|
||||
* @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoConstrictedVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _coeff,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2 ,
|
||||
eoRealVectorBounds & _bounds,
|
||||
eoRealBoundModifier & _bndsModifier,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
coeff(_coeff),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
bounds(_bounds),
|
||||
bndsModifier(_bndsModifier),
|
||||
gen(_gen){}
|
||||
|
||||
|
||||
/** Constructor: No bound updater required <-> fixed bounds
|
||||
* @param _topology - The topology to get the global/local/other best
|
||||
* @param _coeff - The constriction coefficient
|
||||
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
|
||||
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
|
||||
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoConstrictedVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _coeff,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2,
|
||||
eoRealVectorBounds & _bounds,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
coeff(_coeff),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
bounds(_bounds),
|
||||
bndsModifier(dummyModifier),
|
||||
gen(_gen){}
|
||||
|
||||
|
||||
/** Constructor: Neither bounds nor bound updater required <-> free velocity
|
||||
* @param _topology - The topology to get the global/local/other best
|
||||
* @param _coeff - The constriction coefficient
|
||||
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoConstrictedVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _coeff,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
coeff(_coeff),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
bounds(*(new eoRealVectorNoBounds(0))),
|
||||
bndsModifier(dummyModifier),
|
||||
gen(_gen){}
|
||||
|
||||
|
||||
/**
|
||||
* Evaluate the new velocities of the given particle. Need an indice to identify the particle
|
||||
* into the topology. Steps are :
|
||||
* - evaluate r1 and r2, the customed learning factors
|
||||
* - adjust the size of the bounds (even if dummy)
|
||||
* - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided)
|
||||
* @param _po - A particle
|
||||
* @param _indice - The indice (into the topology) of the given particle
|
||||
*/
|
||||
void operator () (POT & _po,unsigned _indice)
|
||||
{
|
||||
VelocityType r1;
|
||||
VelocityType r2;
|
||||
|
||||
VelocityType newVelocity;
|
||||
|
||||
// cast the learning factors to VelocityType
|
||||
r1 = (VelocityType) rng.uniform (1) * c1;
|
||||
r2 = (VelocityType) rng.uniform (1) * c2;
|
||||
|
||||
// need to resize the bounds even if there are dummy because of "isBounded" call
|
||||
bounds.adjust_size(_po.size());
|
||||
|
||||
// assign the new velocities
|
||||
for (unsigned j = 0; j < _po.size (); j++)
|
||||
{
|
||||
newVelocity= coeff * (_po.velocities[j] + r1 * (_po.bestPositions[j] - _po[j]) + r2 * (topology.best (_indice)[j] - _po[j]));
|
||||
|
||||
/* modify the bounds */
|
||||
bndsModifier(bounds,j);
|
||||
|
||||
/* check bounds */
|
||||
if (bounds.isMinBounded(j))
|
||||
newVelocity=(VelocityType)std::max(newVelocity,bounds.minimum(j));
|
||||
if (bounds.isMaxBounded(j))
|
||||
newVelocity=(VelocityType)std::min(newVelocity,bounds.maximum(j));
|
||||
|
||||
_po.velocities[j]=newVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the neighborhood of a particle.
|
||||
*/
|
||||
void updateNeighborhood(POT & _po,unsigned _indice)
|
||||
{
|
||||
topology.updateNeighborhood(_po,_indice);
|
||||
}
|
||||
|
||||
//! eoTopology<POT> getTopology
|
||||
//! @return topology
|
||||
|
||||
eoTopology<POT> & getTopology ()
|
||||
{
|
||||
return topology;
|
||||
}
|
||||
|
||||
protected:
|
||||
eoTopology < POT > & topology;
|
||||
const VelocityType & c1; // learning factor 1
|
||||
const VelocityType & c2; // learning factor 2
|
||||
const VelocityType & coeff; // the fixed constriction coefficient
|
||||
eoRng & gen; // the random generator
|
||||
|
||||
eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type.
|
||||
eoRealBoundModifier & bndsModifier;
|
||||
|
||||
// If the bound modifier doesn't need to be used, use the dummy instance
|
||||
eoDummyRealBoundModifier dummyModifier;
|
||||
};
|
||||
|
||||
|
||||
#endif /*EOCONSTRICTEDVELOCITY_H */
|
||||
70
trunk/eo/src/eoContinue.h
Normal file
70
trunk/eo/src/eoContinue.h
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
// -*- 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>
|
||||
|
||||
/** @defgroup Continuators Stopping criteria
|
||||
*
|
||||
* A stopping criterion is called a "continue". This is a functor that is called at each generation end
|
||||
* and that return true if one should stop the search.
|
||||
*
|
||||
* @ingroup Utilities
|
||||
*/
|
||||
|
||||
/** Termination condition for the genetic algorithm
|
||||
* Takes the population as input, returns true for continue,
|
||||
* false for termination
|
||||
*
|
||||
* @ingroup Continuators
|
||||
* @ingroup Core
|
||||
*/
|
||||
template< class EOT>
|
||||
class eoContinue : public eoUF<const eoPop<EOT>&, bool>, public eoPersistent
|
||||
{
|
||||
public:
|
||||
virtual std::string className(void) const { return "eoContinue"; }
|
||||
|
||||
/** Read from a stream
|
||||
* @param __is istream to read from
|
||||
*/
|
||||
void readFrom (std :: istream & __is) {
|
||||
(void)__is;
|
||||
/* It should be implemented by subclasses ! */
|
||||
}
|
||||
|
||||
/** Print on a stream
|
||||
* @param __os ostream to print on
|
||||
*/
|
||||
void printOn (std :: ostream & __os) const {
|
||||
(void)__os;
|
||||
/* It should be implemented by subclasses ! */
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
221
trunk/eo/src/eoCounter.h
Normal file
221
trunk/eo/src/eoCounter.h
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
// -*- 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.
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
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
|
||||
62
trunk/eo/src/eoCtrlCContinue.cpp
Normal file
62
trunk/eo/src/eoCtrlCContinue.cpp
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
// -*- 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 <utils/eoLogger.h>
|
||||
|
||||
#include <signal.h>
|
||||
#include <iostream>
|
||||
|
||||
/**
|
||||
* @addtogroup Continuators
|
||||
* @{
|
||||
*/
|
||||
|
||||
// --- Global variables - but don't know what else to do - MS ---
|
||||
bool ask_for_stop = 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 ---
|
||||
#ifndef _WINDOWS
|
||||
#ifdef SIGQUIT
|
||||
signal( SIGINT, SIG_IGN );
|
||||
signal( SIGQUIT, SIG_IGN );
|
||||
eo::log << eo::logging << "Ctrl C entered ... closing down" << std::endl ;
|
||||
ask_for_stop = true;
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
/** @} */
|
||||
86
trunk/eo/src/eoCtrlCContinue.h
Normal file
86
trunk/eo/src/eoCtrlCContinue.h
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
// -*- 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 eoCtrlCContinue_h
|
||||
#define eoCtrlCContinue_h
|
||||
|
||||
#include <csignal>
|
||||
#include <eoContinue.h>
|
||||
|
||||
/**
|
||||
* @addtogroup Continuators
|
||||
* @{
|
||||
*/
|
||||
|
||||
extern bool ask_for_stop, 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");
|
||||
|
||||
#ifndef _WINDOWS
|
||||
#ifdef SIGQUIT
|
||||
signal( SIGINT, signal_handler );
|
||||
signal( SIGQUIT, signal_handler );
|
||||
existCtrlCContinue = true;
|
||||
#endif
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
/** Returns false when Ctrl C has been typed in
|
||||
* reached */
|
||||
virtual bool operator() ( const eoPop<EOT>& _vEO )
|
||||
{
|
||||
(void)_vEO;
|
||||
if (ask_for_stop)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoCtrlCContinue"; }
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
/** @} */
|
||||
91
trunk/eo/src/eoDetSelect.h
Normal file
91
trunk/eo/src/eoDetSelect.h
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
/** -*- 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
|
||||
*
|
||||
* @ingroup Selectors
|
||||
*/
|
||||
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);
|
||||
|
||||
if ( target == 0 )
|
||||
{
|
||||
eo::log << eo::warnings << "Call to a eoHowMany instance returns 0 (target=" << target << ") it will be replaced by 1 to continue." << std::endl;
|
||||
target = 1;
|
||||
}
|
||||
|
||||
_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/eo/src/eoDetTournamentSelect.h
Normal file
73
trunk/eo/src/eoDetTournamentSelect.h
Normal 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/eoLogger.h>
|
||||
#include <utils/selectors.h>
|
||||
|
||||
/** eoDetTournamentSelect: a selection method that selects ONE individual by
|
||||
deterministic tournament
|
||||
-MS- 24/10/99
|
||||
|
||||
@ingroup Selectors
|
||||
*/
|
||||
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) {
|
||||
eo::log << eo::warnings << "Tournament size should be >= 2, adjusted to 2" << std::endl;
|
||||
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/eo/src/eoDistribUpdater.h
Normal file
50
trunk/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
|
||||
*
|
||||
* @ingroup Core
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoDistribUpdater :
|
||||
public eoBF<eoDistribution<EOT> &, eoPop<EOT> &, void>
|
||||
{
|
||||
public:
|
||||
virtual void operator()(eoDistribution<EOT> &, eoPop<EOT> &)=0;
|
||||
};
|
||||
|
||||
#endif
|
||||
54
trunk/eo/src/eoDistribution.h
Normal file
54
trunk/eo/src/eoDistribution.h
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
// -*- 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
|
||||
*
|
||||
* @ingroup Core
|
||||
*/
|
||||
|
||||
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
|
||||
328
trunk/eo/src/eoDualFitness.h
Normal file
328
trunk/eo/src/eoDualFitness.h
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
/*
|
||||
|
||||
(c) 2010 Thales group
|
||||
|
||||
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; version 2
|
||||
of the License.
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
|
||||
*/
|
||||
|
||||
#ifndef _eoDualFitness_h_
|
||||
#define _eoDualFitness_h_
|
||||
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
#include <utility> // for std::pair
|
||||
#include <string>
|
||||
|
||||
#include <utils/eoStat.h>
|
||||
#include <utils/eoLogger.h>
|
||||
|
||||
/** @addtogroup Evaluation
|
||||
* @{
|
||||
*/
|
||||
|
||||
//! A fitness class that permits to compare feasible and unfeasible individuals and guaranties that a feasible individual will always be better than an unfeasible one.
|
||||
/**
|
||||
* Use this class as fitness if you have some kind of individuals
|
||||
* that must be always considered as better than others while having the same fitness type.
|
||||
*
|
||||
* Wraps a scalar fitness _values such as a double or int, with the option of
|
||||
* maximizing (using less<BaseType>, @see eoMaximizingDualFitness)
|
||||
* or minimizing (using greater<BaseType>, @see eoMinimizingDualFitness).
|
||||
*
|
||||
* Suitable constructors, assignments and casts are defined to work
|
||||
* with those quantities as if they were a pair of: a BaseType and a boolean.
|
||||
*
|
||||
* When changing the fitness, you can use:
|
||||
* individual.fitness( std::make_pair<BaseType,bool>( fitness, feasibility ) );
|
||||
*
|
||||
* Be aware that, when printing or reading an eDualFitness instance on a iostream,
|
||||
* friend IO classes use a space separator.
|
||||
*
|
||||
* This class overrides operator<() to use the Compare template argument and handle feasibility.
|
||||
* Over operators are coded using this sole function.
|
||||
*
|
||||
* Standard arithmetic operators are provided to add or substract dual fitnesses.
|
||||
* They behave as expected for the fitness value and gives priority to unfeasible fitness
|
||||
* (i.e. when adding or substracting dual fitness, the only case when the result will be
|
||||
* a feasible fitness is when both are feasible, else the result is an unfeasibe fitness)
|
||||
*/
|
||||
template <class BaseType, class Compare >
|
||||
class eoDualFitness
|
||||
{
|
||||
protected:
|
||||
//! Scalar type of the fitness (generally a double)
|
||||
BaseType _value;
|
||||
|
||||
//! Flag that marks if the individual is feasible
|
||||
bool _is_feasible;
|
||||
|
||||
public:
|
||||
|
||||
//! Empty initialization
|
||||
/*!
|
||||
* Unfeasible by default
|
||||
*/
|
||||
eoDualFitness() :
|
||||
_value(),
|
||||
_is_feasible(false)
|
||||
{}
|
||||
|
||||
//! Copy constructor
|
||||
eoDualFitness(const eoDualFitness& other) :
|
||||
_value(other._value),
|
||||
_is_feasible(other._is_feasible)
|
||||
{}
|
||||
|
||||
//! Constructor from explicit value/feasibility
|
||||
eoDualFitness(const BaseType& v, const bool& is_feasible) :
|
||||
_value(v),
|
||||
_is_feasible(is_feasible)
|
||||
{}
|
||||
|
||||
//! From a std::pair (first element is the value, second is the feasibility)
|
||||
eoDualFitness(const std::pair<BaseType,bool>& dual) :
|
||||
_value(dual.first),
|
||||
_is_feasible(dual.second)
|
||||
{}
|
||||
|
||||
// FIXME is it a good idea to include implicit conversion here?
|
||||
/** Conversion operator: it permits to use a fitness instance as its scalar
|
||||
* type, if needed. For example, this is possible:
|
||||
* eoDualFitness<double,std::less<double> > fit;
|
||||
* double val = 1.0;
|
||||
* fit = val;
|
||||
* val = fit;
|
||||
*/
|
||||
operator BaseType(void) const { return _value; }
|
||||
|
||||
|
||||
inline bool is_feasible() const
|
||||
{
|
||||
return _is_feasible;
|
||||
}
|
||||
|
||||
inline BaseType value() const
|
||||
{
|
||||
return _value;
|
||||
}
|
||||
|
||||
//! Copy operator from a std::pair
|
||||
eoDualFitness& operator=(const std::pair<BaseType,bool>& v)
|
||||
{
|
||||
_value = v.first;
|
||||
_is_feasible = v.second;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Copy operator from another eoDualFitness
|
||||
template <class F, class Cmp>
|
||||
eoDualFitness<F,Cmp> & operator=(const eoDualFitness<BaseType, Compare>& other )
|
||||
{
|
||||
if (this != &other) {
|
||||
this->_value = other._value;
|
||||
this->_is_feasible = other._is_feasible;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Comparison that separate feasible individuals from unfeasible ones. Feasible are always better
|
||||
/*!
|
||||
* Use less as a default comparison operator
|
||||
* (see the "Compare" template of the class to change this behaviour,
|
||||
* @see eoMinimizingDualFitness for an example).
|
||||
*/
|
||||
bool operator<(const eoDualFitness& other) const
|
||||
{
|
||||
// am I better (less, by default) than the other ?
|
||||
|
||||
// if I'm feasible and the other is not
|
||||
if( this->_is_feasible && !other._is_feasible ) {
|
||||
// no, the other has a better fitness
|
||||
return false;
|
||||
|
||||
} else if( !this->_is_feasible && other._is_feasible ) {
|
||||
// yes, a feasible fitness is always better than an unfeasible one
|
||||
return true;
|
||||
|
||||
} else {
|
||||
// the two fitness are of the same type
|
||||
// lets rely on the comparator
|
||||
return Compare()(_value, other._value);
|
||||
}
|
||||
}
|
||||
|
||||
//! Greater: if the other is lesser than me
|
||||
bool operator>( const eoDualFitness& other ) const { return other < *this; }
|
||||
|
||||
//! Less or equal: if the other is not lesser than me
|
||||
bool operator<=( const eoDualFitness& other ) const { return !(other < *this); }
|
||||
|
||||
//! Greater or equal: if the other is not greater than me
|
||||
bool operator>=(const eoDualFitness& other ) const { return !(*this < other); }
|
||||
|
||||
//! Equal: if the other is equal to me
|
||||
bool operator==(const eoDualFitness& other) const { return ( _is_feasible == other._is_feasible ) && ( _value == other._value ); }
|
||||
|
||||
public:
|
||||
|
||||
//! Add a given fitness to the current one
|
||||
template <class F, class Cmp>
|
||||
friend
|
||||
eoDualFitness<F,Cmp> & operator+=( eoDualFitness<F,Cmp> & from, const eoDualFitness<F,Cmp> & that )
|
||||
{
|
||||
from._value += that._value;
|
||||
|
||||
// true only if the two are feasible, else false
|
||||
from._is_feasible = from._is_feasible && that._is_feasible;
|
||||
|
||||
return from;
|
||||
}
|
||||
|
||||
//! Substract a given fitness to the current one
|
||||
template <class F, class Cmp>
|
||||
friend
|
||||
eoDualFitness<F,Cmp> & operator-=( eoDualFitness<F,Cmp> & from, const eoDualFitness<F,Cmp> & that )
|
||||
{
|
||||
from._value -= that._value;
|
||||
|
||||
// true only if the two are feasible, else false
|
||||
from._is_feasible = from._is_feasible && that._is_feasible;
|
||||
|
||||
return from;
|
||||
}
|
||||
|
||||
// Add this fitness's value to that other, and return a _new_ instance with the result.
|
||||
template <class F, class Cmp>
|
||||
eoDualFitness<F,Cmp> operator+(const eoDualFitness<F,Cmp> & that)
|
||||
{
|
||||
eoDualFitness<F,Cmp> from( *this );
|
||||
return from += that;
|
||||
}
|
||||
|
||||
// Add this fitness's value to that other, and return a _new_ instance with the result.
|
||||
template <class F, class Cmp>
|
||||
eoDualFitness<F,Cmp> operator-(const eoDualFitness<F,Cmp> & that)
|
||||
{
|
||||
eoDualFitness<F,Cmp> from( *this );
|
||||
return from -= that;
|
||||
}
|
||||
|
||||
//! Print an eoDualFitness instance as a pair of numbers, separated by a space
|
||||
template <class F, class Cmp>
|
||||
friend
|
||||
std::ostream& operator<<(std::ostream& os, const eoDualFitness<F, Cmp>& f)
|
||||
{
|
||||
os << f._value << " " << f._is_feasible;
|
||||
return os;
|
||||
}
|
||||
|
||||
//! Read an eoDualFitness instance as a pair of numbers, separated by a space
|
||||
template <class F, class Cmp>
|
||||
friend
|
||||
std::istream& operator>>(std::istream& is, eoDualFitness<F, Cmp>& f)
|
||||
{
|
||||
F value;
|
||||
is >> value;
|
||||
|
||||
bool feasible;
|
||||
is >> feasible;
|
||||
|
||||
f = std::make_pair<F,bool>( value, feasible );
|
||||
return is;
|
||||
}
|
||||
};
|
||||
|
||||
//! Compare dual fitnesses as if we were maximizing
|
||||
typedef eoDualFitness<double, std::less<double> > eoMaximizingDualFitness;
|
||||
|
||||
//! Compare dual fitnesses as if we were minimizing
|
||||
typedef eoDualFitness<double, std::greater<double> > eoMinimizingDualFitness;
|
||||
|
||||
//! A predicate that returns the feasibility of a given dual fitness
|
||||
/** Use this in STL algorithm that use binary predicates (e.g. count_if, find_if, etc.)
|
||||
*/
|
||||
template< class EOT>
|
||||
bool eoIsFeasible ( const EOT & sol ) { return sol.fitness().is_feasible(); }
|
||||
|
||||
|
||||
/** Embed two eoStat and call the first one on the feasible individuals and
|
||||
* the second one on the unfeasible ones, merge the two resulting value in
|
||||
* a string, separated by a given marker.
|
||||
*/
|
||||
//template<class EOT, class T>
|
||||
template<class EOT, class EOSTAT>
|
||||
class eoDualStatSwitch : public eoStat< EOT, std::string >
|
||||
{
|
||||
public:
|
||||
using eoStat<EOT,std::string>::value;
|
||||
|
||||
// eoDualStatSwitch( eoStat<EOT,T> & stat_feasible, eoStat<EOT,T> & stat_unfeasible, std::string sep=" " ) :
|
||||
eoDualStatSwitch( EOSTAT & stat_feasible, EOSTAT & stat_unfeasible, std::string sep=" " ) :
|
||||
eoStat<EOT,std::string>(
|
||||
"?"+sep+"?",
|
||||
stat_feasible.longName()+sep+stat_unfeasible.longName()
|
||||
),
|
||||
_stat_feasible(stat_feasible),
|
||||
_stat_unfeasible(stat_unfeasible),
|
||||
_sep(sep)
|
||||
{ }
|
||||
|
||||
virtual void operator()( const eoPop<EOT> & pop )
|
||||
{
|
||||
eoPop<EOT> pop_feasible;
|
||||
pop_feasible.reserve(pop.size());
|
||||
|
||||
eoPop<EOT> pop_unfeasible;
|
||||
pop_unfeasible.reserve(pop.size());
|
||||
|
||||
for( typename eoPop<EOT>::const_iterator ieot=pop.begin(), iend=pop.end(); ieot!=iend; ++ieot ) {
|
||||
/*
|
||||
if( ieot->invalid() ) {
|
||||
eo::log << eo::errors << "ERROR: trying to access to an invalid fitness" << std::endl;
|
||||
}
|
||||
*/
|
||||
if( ieot->fitness().is_feasible() ) {
|
||||
pop_feasible.push_back( *ieot );
|
||||
} else {
|
||||
pop_unfeasible.push_back( *ieot );
|
||||
}
|
||||
}
|
||||
|
||||
_stat_feasible( pop_feasible );
|
||||
_stat_unfeasible( pop_unfeasible );
|
||||
|
||||
std::ostringstream out;
|
||||
out << _stat_feasible.value() << _sep << _stat_unfeasible.value();
|
||||
|
||||
value() = out.str();
|
||||
}
|
||||
|
||||
protected:
|
||||
// eoStat<EOT,T> & _stat_feasible;
|
||||
// eoStat<EOT,T> & _stat_unfeasible;
|
||||
EOSTAT & _stat_feasible;
|
||||
EOSTAT & _stat_unfeasible;
|
||||
|
||||
std::string _sep;
|
||||
};
|
||||
|
||||
/** @} */
|
||||
#endif // _eoDualFitness_h_
|
||||
46
trunk/eo/src/eoEDA.h
Normal file
46
trunk/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>
|
||||
|
||||
/** The abstract class for estimation of disribution algorithms.
|
||||
* This design 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.
|
||||
*
|
||||
* @ingroup Algorithms
|
||||
*/
|
||||
|
||||
template<class EOT> class eoEDA: public eoUF<eoDistribution<EOT>&, void>
|
||||
{
|
||||
};
|
||||
|
||||
#endif
|
||||
322
trunk/eo/src/eoEasyEA.h
Normal file
322
trunk/eo/src/eoEasyEA.h
Normal file
|
|
@ -0,0 +1,322 @@
|
|||
// -*- 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 <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
|
||||
|
||||
@ingroup Algorithms
|
||||
*/
|
||||
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),
|
||||
isFirstCall(true)
|
||||
{}
|
||||
|
||||
/** Ctor taking a breed and merge, an overload of ctor to define an offspring size */
|
||||
eoEasyEA(
|
||||
eoContinue<EOT>& _continuator,
|
||||
eoEvalFunc<EOT>& _eval,
|
||||
eoBreed<EOT>& _breed,
|
||||
eoReplacement<EOT>& _replace,
|
||||
unsigned _offspringSize
|
||||
) : continuator(_continuator),
|
||||
eval (_eval),
|
||||
loopEval(_eval),
|
||||
popEval(loopEval),
|
||||
selectTransform(dummySelect, dummyTransform),
|
||||
breed(_breed),
|
||||
mergeReduce(dummyMerge, dummyReduce),
|
||||
replace(_replace),
|
||||
isFirstCall(true)
|
||||
{
|
||||
offspring.reserve(_offspringSize); // This line avoids an incremental resize of offsprings.
|
||||
}
|
||||
|
||||
/*
|
||||
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),
|
||||
isFirstCall(true)
|
||||
{
|
||||
|
||||
}
|
||||
*/
|
||||
|
||||
/** 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),
|
||||
isFirstCall(true)
|
||||
{}
|
||||
|
||||
|
||||
/// Ctor eoSelect, eoTransform, eoReplacement and an eoPopEval
|
||||
eoEasyEA(
|
||||
eoContinue<EOT>& _continuator,
|
||||
eoPopEvalFunc<EOT>& _eval,
|
||||
eoSelect<EOT>& _select,
|
||||
eoTransform<EOT>& _transform,
|
||||
eoReplacement<EOT>& _replace
|
||||
) : continuator(_continuator),
|
||||
eval (dummyEval),
|
||||
loopEval(dummyEval),
|
||||
popEval(_eval),
|
||||
selectTransform(_select, _transform),
|
||||
breed(selectTransform),
|
||||
mergeReduce(dummyMerge, dummyReduce),
|
||||
replace(_replace),
|
||||
isFirstCall(true)
|
||||
{}
|
||||
|
||||
/// 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),
|
||||
isFirstCall(true)
|
||||
{}
|
||||
|
||||
/// 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),
|
||||
isFirstCall(true)
|
||||
{}
|
||||
|
||||
/// 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),
|
||||
isFirstCall(true)
|
||||
{}
|
||||
|
||||
|
||||
|
||||
|
||||
/// Apply a few generation of evolution to the population.
|
||||
virtual void operator()(eoPop<EOT>& _pop)
|
||||
{
|
||||
if (isFirstCall)
|
||||
{
|
||||
size_t total_capacity = _pop.capacity() + offspring.capacity();
|
||||
_pop.reserve(total_capacity);
|
||||
offspring.reserve(total_capacity);
|
||||
isFirstCall = false;
|
||||
}
|
||||
|
||||
eoPop<EOT> 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;
|
||||
|
||||
eoPop<EOT> offspring;
|
||||
|
||||
bool isFirstCall;
|
||||
|
||||
// Friend classes
|
||||
friend class eoIslandsEasyEA <EOT> ;
|
||||
friend class eoDistEvalEasyEA <EOT> ;
|
||||
};
|
||||
/**
|
||||
@example t-eoEasyEA.cpp
|
||||
Example of a test program building an EA algorithm.
|
||||
*/
|
||||
|
||||
#endif
|
||||
196
trunk/eo/src/eoEasyPSO.h
Normal file
196
trunk/eo/src/eoEasyPSO.h
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoEasyPSO.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _EOEASYPSO_H
|
||||
#define _EOEASYPSO_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoContinue.h>
|
||||
#include <eoPSO.h>
|
||||
#include <eoVelocity.h>
|
||||
#include <eoFlight.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** An easy-to-use particle swarm algorithm.
|
||||
* Use any particle, any flight, any topology...
|
||||
*
|
||||
* The main steps are :
|
||||
* (The population is expected to be already evaluated)
|
||||
* - for each generation and each particle pi
|
||||
* - evaluate the velocities
|
||||
* -- perform the fligth of pi
|
||||
* -- evaluate pi
|
||||
* -- update the neighborhoods
|
||||
*
|
||||
* @ingroup Algorithms
|
||||
*/
|
||||
template < class POT > class eoEasyPSO:public eoPSO < POT >
|
||||
{
|
||||
public:
|
||||
|
||||
/** Full constructor
|
||||
* @param _init - An eoInitializerBase that initializes the topology, velocity, best particle(s)
|
||||
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
|
||||
* @param _eval - An eoEvalFunc: the evaluation performer
|
||||
* @param _velocity - An eoVelocity that defines how to compute the velocities
|
||||
* @param _flight - An eoFlight that defines how to make the particle flying: that means how
|
||||
* to modify the positions according to the velocities
|
||||
*/
|
||||
eoEasyPSO (
|
||||
eoInitializerBase <POT> &_init,
|
||||
eoContinue < POT > &_continuator,
|
||||
eoEvalFunc < POT > &_eval,
|
||||
eoVelocity < POT > &_velocity,
|
||||
eoFlight < POT > &_flight):
|
||||
init(_init),
|
||||
continuator (_continuator),
|
||||
eval (_eval),
|
||||
velocity (_velocity),
|
||||
flight (_flight)
|
||||
{}
|
||||
|
||||
|
||||
/** Constructor without eoFlight. For special cases when the flight is performed withing the velocity.
|
||||
* @param _init - An eoInitializerBase that initializes the topology, velocity, best particle(s)
|
||||
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
|
||||
* @param _eval - An eoEvalFunc: the evaluation performer
|
||||
* @param _velocity - An eoVelocity that defines how to compute the velocities
|
||||
*/
|
||||
eoEasyPSO (
|
||||
eoInitializerBase <POT> &_init,
|
||||
eoContinue < POT > &_continuator,
|
||||
eoEvalFunc < POT > &_eval,
|
||||
eoVelocity < POT > &_velocity):
|
||||
init(_init),
|
||||
continuator (_continuator),
|
||||
eval (_eval),
|
||||
velocity (_velocity),
|
||||
flight (dummyFlight)
|
||||
{}
|
||||
|
||||
|
||||
/* Constructor without eoInitializerBase. Assume the initialization is done before running the algorithm
|
||||
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
|
||||
* @param _eval - An eoEvalFunc: the evaluation performer
|
||||
* @param _velocity - An eoVelocity that defines how to compute the velocities
|
||||
* @param _flight - An eoFlight that defines how to make the particle flying: that means how
|
||||
* to modify the positions according to the velocities
|
||||
*/
|
||||
eoEasyPSO (
|
||||
eoContinue < POT > &_continuator,
|
||||
eoEvalFunc < POT > &_eval,
|
||||
eoVelocity < POT > &_velocity,
|
||||
eoFlight < POT > &_flight):
|
||||
init(dummyInit),
|
||||
continuator (_continuator),
|
||||
eval (_eval),
|
||||
velocity (_velocity),
|
||||
flight (_flight)
|
||||
{}
|
||||
|
||||
|
||||
/** Constructor without eoFlight nor eoInitializerBase. For special cases when the flight is performed withing the velocity.
|
||||
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
|
||||
* @param _eval - An eoEvalFunc: the evaluation performer
|
||||
* @param _velocity - An eoVelocity that defines how to compute the velocities
|
||||
*/
|
||||
eoEasyPSO (
|
||||
eoContinue < POT > &_continuator,
|
||||
eoEvalFunc < POT > &_eval,
|
||||
eoVelocity < POT > &_velocity):
|
||||
init(dummyInit),
|
||||
continuator (_continuator),
|
||||
eval (_eval),
|
||||
velocity (_velocity),
|
||||
flight (dummyFlight)
|
||||
{}
|
||||
|
||||
/// Apply a few iteration of flight to the population (=swarm).
|
||||
virtual void operator () (eoPop < POT > &_pop)
|
||||
{
|
||||
try
|
||||
{
|
||||
// initializes the topology, velocity, best particle(s)
|
||||
init();
|
||||
do
|
||||
{
|
||||
// loop over all the particles for the current iteration
|
||||
for (unsigned idx = 0; idx < _pop.size (); idx++)
|
||||
{
|
||||
// perform velocity evaluation
|
||||
velocity (_pop[idx],idx);
|
||||
|
||||
// apply the flight
|
||||
flight (_pop[idx]);
|
||||
|
||||
// evaluate the position
|
||||
eval (_pop[idx]);
|
||||
|
||||
// update the topology (particle and local/global best(s))
|
||||
velocity.updateNeighborhood(_pop[idx],idx);
|
||||
}
|
||||
|
||||
}
|
||||
while (continuator (_pop));
|
||||
|
||||
}
|
||||
catch (std::exception & e)
|
||||
{
|
||||
std::string s = e.what ();
|
||||
s.append (" in eoEasyPSO");
|
||||
throw std::runtime_error (s);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected:
|
||||
eoInitializerBase <POT> &init;
|
||||
eoContinue < POT > &continuator;
|
||||
eoEvalFunc < POT > &eval;
|
||||
eoVelocity < POT > &velocity;
|
||||
eoFlight < POT > &flight;
|
||||
|
||||
// if the flight does not need to be used, use the dummy flight instance
|
||||
class eoDummyFlight:public eoFlight < POT >
|
||||
{
|
||||
public:
|
||||
eoDummyFlight () {}
|
||||
void operator () (POT & _po) {}
|
||||
}dummyFlight;
|
||||
|
||||
// if the initializer does not need to be used, use the dummy one instead
|
||||
class eoDummyInitializer:public eoInitializerBase < POT >
|
||||
{
|
||||
public:
|
||||
eoDummyInitializer () {}
|
||||
void operator () (POT & _po) {}
|
||||
}dummyInit;
|
||||
|
||||
};
|
||||
/**
|
||||
* @example t-eoEasyPSO.cpp
|
||||
* Example of a test program building a PSO algorithm.
|
||||
*/
|
||||
|
||||
#endif /*_EOEASYPSO_H*/
|
||||
69
trunk/eo/src/eoEvalContinue.h
Normal file
69
trunk/eo/src/eoEvalContinue.h
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
// -*- 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
|
||||
*
|
||||
* @ingroup Continuators
|
||||
*/
|
||||
template< class EOT>
|
||||
class eoEvalContinue: public eoContinue<EOT>
|
||||
{
|
||||
public:
|
||||
/// Ctor
|
||||
eoEvalContinue( eoEvalFuncCounter<EOT> & _eval, unsigned long _totalEval)
|
||||
: eval(_eval), repTotalEvaluations( _totalEval ) {};
|
||||
|
||||
/** Returns false when a certain number of evaluations has been done
|
||||
*/
|
||||
virtual bool operator() ( const eoPop<EOT>& _vEO ) {
|
||||
(void)_vEO;
|
||||
if (eval.value() >= repTotalEvaluations)
|
||||
{
|
||||
eo::log << eo::progress << "STOP in eoEvalContinue: Reached maximum number of evaluations [" << repTotalEvaluations << "]" << std::endl;
|
||||
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
|
||||
86
trunk/eo/src/eoEvalCounterThrowException.h
Normal file
86
trunk/eo/src/eoEvalCounterThrowException.h
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
/*
|
||||
(c) Thales group, 2010
|
||||
|
||||
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;
|
||||
version 2 of the License.
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
Caner Candan <caner.candan@thalesgroup.com>
|
||||
|
||||
*/
|
||||
|
||||
#ifndef __eoEvalCounterThrowException_h__
|
||||
#define __eoEvalCounterThrowException_h__
|
||||
|
||||
#include <eoEvalFuncCounter.h>
|
||||
#include <utils/eoParam.h>
|
||||
#include <eoExceptions.h>
|
||||
|
||||
/*!
|
||||
Wrap an evaluation function so that an exception may be thrown when the
|
||||
algorithm have reached a maximum number of evaluations.
|
||||
|
||||
This may be useful if you want to check this kind of stopping criterion
|
||||
at each _evaluation_, instead of using continuators at each _iteration_.
|
||||
|
||||
The class first call the evaluation function, then check the number of
|
||||
times it has been called. If the maximum number of evaluation has been
|
||||
reached, it throw an eoMaxEvalException. You can catch this exception
|
||||
from your main function, so as to stop everything properly.
|
||||
|
||||
@ingroup Evaluation
|
||||
*/
|
||||
template < typename EOT >
|
||||
class eoEvalCounterThrowException : public eoEvalFuncCounter< EOT >
|
||||
{
|
||||
public :
|
||||
eoEvalCounterThrowException( eoEvalFunc<EOT>& func, unsigned long max_evals, std::string name = "Eval. ")
|
||||
: eoEvalFuncCounter< EOT >( func, name ), _threshold( max_evals )
|
||||
{}
|
||||
|
||||
using eoEvalFuncCounter< EOT >::value;
|
||||
|
||||
//! Evaluate the individual, then throw an exception if it exceed the max number of evals.
|
||||
virtual void operator()(EOT& eo)
|
||||
{
|
||||
// bypass already evaluated individuals
|
||||
if (eo.invalid()) {
|
||||
|
||||
// increment the value of the self parameter
|
||||
// (eoEvalFuncCounter inherits from @see eoValueParam)
|
||||
value()++;
|
||||
|
||||
// if we have reached the maximum
|
||||
if ( value() >= _threshold ) {
|
||||
|
||||
// go back through the stack until catched
|
||||
throw eoMaxEvalException(_threshold);
|
||||
}
|
||||
|
||||
// evaluate
|
||||
func(eo);
|
||||
|
||||
} // if invalid
|
||||
}
|
||||
|
||||
virtual std::string className() const {return "eoEvalCounterThrowException";}
|
||||
|
||||
private :
|
||||
unsigned long _threshold;
|
||||
};
|
||||
|
||||
#endif // __eoEvalCounterThrowException_h__
|
||||
55
trunk/eo/src/eoEvalFunc.h
Normal file
55
trunk/eo/src/eoEvalFunc.h
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
// -*- 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>
|
||||
|
||||
/** @defgroup Evaluation Evaluation
|
||||
* @ingroup Operators
|
||||
*/
|
||||
|
||||
/** 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.
|
||||
|
||||
@ingroup Evaluation
|
||||
@ingroup Core
|
||||
*/
|
||||
template<class EOT> class eoEvalFunc : public eoUF<EOT&, void>
|
||||
{
|
||||
public :
|
||||
typedef EOT EOType;
|
||||
|
||||
typedef typename EOT::Fitness EOFitT;
|
||||
};
|
||||
|
||||
#endif
|
||||
57
trunk/eo/src/eoEvalFuncCounter.h
Normal file
57
trunk/eo/src/eoEvalFuncCounter.h
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
// -*- 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.
|
||||
|
||||
@ingroup Evaluation
|
||||
*/
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
protected :
|
||||
eoEvalFunc<EOT>& func;
|
||||
};
|
||||
|
||||
#endif
|
||||
67
trunk/eo/src/eoEvalFuncCounterBounder.h
Normal file
67
trunk/eo/src/eoEvalFuncCounterBounder.h
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
#ifndef eoEvalFuncCounterBounder_H
|
||||
#define eoEvalFuncCounterBounder_H
|
||||
|
||||
#include <eoEvalFunc.h>
|
||||
#include <utils/eoParam.h>
|
||||
|
||||
/** @addtogroup Evaluation
|
||||
* @{
|
||||
*/
|
||||
|
||||
/** The exception raised by eoEvalFuncCounterBounder
|
||||
* when the maximum number of allowed evaluations is reached.
|
||||
*/
|
||||
class eoEvalFuncCounterBounderException : public std::exception
|
||||
{
|
||||
public:
|
||||
eoEvalFuncCounterBounderException(unsigned long threshold) : _threshold(threshold){}
|
||||
|
||||
const char* what() const throw()
|
||||
{
|
||||
std::ostringstream ss;
|
||||
ss << "STOP in eoEvalFuncCounterBounderException: the maximum number of evaluation has been reached (" << _threshold << ").";
|
||||
return ss.str().c_str();
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned long _threshold;
|
||||
};
|
||||
|
||||
/** Counts the number of evaluations actually performed and throw an eoEvalFuncCounterBounderException
|
||||
* when the maximum number of allowed evaluations is reached.
|
||||
*
|
||||
* This eval counter permits to stop a search during a generation, without waiting for a continue to be
|
||||
* checked at the end of the loop. Useful if you have 10 individuals and 10 generations,
|
||||
* but want to stop after 95 evaluations.
|
||||
*/
|
||||
template < typename EOT >
|
||||
class eoEvalFuncCounterBounder : public eoEvalFuncCounter< EOT >
|
||||
{
|
||||
public :
|
||||
eoEvalFuncCounterBounder(eoEvalFunc<EOT>& func, unsigned long threshold, std::string name = "Eval. ")
|
||||
: eoEvalFuncCounter< EOT >( func, name ), _threshold( threshold )
|
||||
{}
|
||||
|
||||
using eoEvalFuncCounter< EOT >::value;
|
||||
|
||||
virtual void operator()(EOT& eo)
|
||||
{
|
||||
if (eo.invalid())
|
||||
{
|
||||
value()++;
|
||||
|
||||
if (_threshold > 0 && value() >= _threshold)
|
||||
{
|
||||
throw eoEvalFuncCounterBounderException(_threshold);
|
||||
}
|
||||
|
||||
func(eo);
|
||||
}
|
||||
}
|
||||
|
||||
private :
|
||||
unsigned long _threshold;
|
||||
};
|
||||
|
||||
/** @} */
|
||||
#endif
|
||||
67
trunk/eo/src/eoEvalFuncPtr.h
Normal file
67
trunk/eo/src/eoEvalFuncPtr.h
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
/** -*- 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.
|
||||
*
|
||||
* @ingroup Evaluation
|
||||
*/
|
||||
#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
|
||||
59
trunk/eo/src/eoEvalTimeThrowException.h
Normal file
59
trunk/eo/src/eoEvalTimeThrowException.h
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
/*
|
||||
(c) Thales group, 2010
|
||||
|
||||
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;
|
||||
version 2 of the License.
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#include <ctime>
|
||||
|
||||
#include <eoExceptions.h>
|
||||
|
||||
/** Check at each evaluation if a given tie contract has been reached.
|
||||
*
|
||||
* Throw an eoMaxTimeException if the given max time has been reached.
|
||||
* Usefull if you want to end the search independently of generations.
|
||||
*
|
||||
* @ingroup Evaluation
|
||||
*/
|
||||
template< class EOT >
|
||||
class eoEvalTimeThrowException : public eoEvalFuncCounter< EOT >
|
||||
{
|
||||
public:
|
||||
eoEvalTimeThrowException( eoEvalFunc<EOT> & func, time_t max ) : _max(max), _start( std::time(NULL) ), eoEvalFuncCounter<EOT>( func, "Eval.") {}
|
||||
|
||||
virtual void operator() ( EOT & eo )
|
||||
{
|
||||
if( eo.invalid() ) {
|
||||
|
||||
time_t elapsed = static_cast<time_t>( std::difftime( std::time(NULL) , _start ) );
|
||||
|
||||
if( elapsed >= _max ) {
|
||||
throw eoMaxTimeException(elapsed);
|
||||
} else {
|
||||
func(eo);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
time_t _max;
|
||||
|
||||
time_t _start;
|
||||
};
|
||||
73
trunk/eo/src/eoEvalUserTimeThrowException.h
Normal file
73
trunk/eo/src/eoEvalUserTimeThrowException.h
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
/*
|
||||
(c) Thales group, 2010
|
||||
|
||||
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;
|
||||
version 2 of the License.
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
*/
|
||||
|
||||
|
||||
#ifndef __unix__
|
||||
/*#warning "Warning: class 'eoEvalUserTimeThrowException' is only available under UNIX systems (defining 'rusage' in 'sys/resource.h'), contributions for other systems are welcomed."*/
|
||||
#else
|
||||
|
||||
#ifndef __EOEVALUSERTIMETHROWEXCEPTION_H__
|
||||
#define __EOEVALUSERTIMETHROWEXCEPTION_H__
|
||||
|
||||
#include <sys/time.h>
|
||||
#include <sys/resource.h>
|
||||
|
||||
#include <eoExceptions.h>
|
||||
|
||||
/** Check at each evaluation if a given CPU user time contract has been reached.
|
||||
*
|
||||
* Throw an eoMaxTimeException if the given max time has been reached.
|
||||
* Usefull if you want to end the search independently of generations.
|
||||
* This class uses (almost-)POSIX headers.
|
||||
* It uses a computation of the user time used on the CPU. For a wallclock time measure, see eoEvalTimeThrowException
|
||||
*
|
||||
* @ingroup Evaluation
|
||||
*/
|
||||
template< class EOT >
|
||||
class eoEvalUserTimeThrowException : public eoEvalFuncCounter< EOT >
|
||||
{
|
||||
public:
|
||||
eoEvalUserTimeThrowException( eoEvalFunc<EOT> & func, const long max ) : eoEvalFuncCounter<EOT>( func, "CPU-user"), _max(max) {}
|
||||
|
||||
virtual void operator() ( EOT & eo )
|
||||
{
|
||||
if( eo.invalid() ) {
|
||||
|
||||
getrusage(RUSAGE_SELF,&_usage);
|
||||
|
||||
long current = _usage.ru_utime.tv_sec;
|
||||
if( current >= _max ) {
|
||||
throw eoMaxTimeException( current );
|
||||
} else {
|
||||
func(eo);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
const long _max;
|
||||
struct rusage _usage;
|
||||
};
|
||||
|
||||
#endif // __EOEVALUSERTIMETHROWEXCEPTION_H__
|
||||
#endif // __UNIX__
|
||||
132
trunk/eo/src/eoExceptions.h
Normal file
132
trunk/eo/src/eoExceptions.h
Normal file
|
|
@ -0,0 +1,132 @@
|
|||
/*
|
||||
(c) Thales group, 2010
|
||||
|
||||
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;
|
||||
version 2 of the License.
|
||||
|
||||
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: http://eodev.sourceforge.net
|
||||
|
||||
Authors:
|
||||
Johann Dréo <johann.dreo@thalesgroup.com>
|
||||
*/
|
||||
|
||||
#ifndef __eoExceptions_h__
|
||||
#define __eoExceptions_h__
|
||||
|
||||
#include <ctime>
|
||||
#include <stdexcept>
|
||||
|
||||
class eoMaxException : public std::exception {};
|
||||
|
||||
|
||||
|
||||
/*!
|
||||
An error that signals that a maximum elapsed time has been reached.
|
||||
|
||||
Thrown by @see eoEvalTimeThrowException
|
||||
|
||||
@ingroup Evaluation
|
||||
*/
|
||||
class eoMaxTimeException : public eoMaxException
|
||||
{
|
||||
public:
|
||||
eoMaxTimeException( time_t elapsed) : _elapsed(elapsed) {}
|
||||
|
||||
virtual const char* what() const throw()
|
||||
{
|
||||
std::ostringstream ss;
|
||||
ss << "STOP in eoMaxTimeException: the maximum number of allowed seconds has been reached (" << _elapsed << ").";
|
||||
return ss.str().c_str();
|
||||
}
|
||||
|
||||
private:
|
||||
time_t _elapsed;
|
||||
};
|
||||
|
||||
|
||||
/*!
|
||||
An error that signals that a maximum number of evaluations has been reached.
|
||||
|
||||
Thrown by @see eoEvalEvalThrowException
|
||||
|
||||
@ingroup Evaluation
|
||||
*/
|
||||
class eoMaxEvalException : public eoMaxException
|
||||
{
|
||||
public:
|
||||
eoMaxEvalException(unsigned long threshold) : _threshold(threshold){}
|
||||
|
||||
virtual const char* what() const throw()
|
||||
{
|
||||
std::ostringstream ss;
|
||||
ss << "STOP in eoMaxEvalException: the maximum number of evaluation has been reached (" << _threshold << ").";
|
||||
return ss.str().c_str();
|
||||
}
|
||||
|
||||
private:
|
||||
unsigned long _threshold;
|
||||
};
|
||||
|
||||
|
||||
/*!
|
||||
* An error that signals a missing parameter
|
||||
*
|
||||
* Thrown by eoParser::getParam
|
||||
*
|
||||
* @ingroup Parameters
|
||||
*/
|
||||
class eoMissingParamException : public std::exception
|
||||
{
|
||||
public:
|
||||
eoMissingParamException(std::string name) : _name(name){}
|
||||
|
||||
virtual const char* what() const throw()
|
||||
{
|
||||
std::ostringstream ss;
|
||||
ss << "The command parameter " << _name << " has not been declared";
|
||||
return ss.str().c_str();
|
||||
}
|
||||
|
||||
~eoMissingParamException() throw() {}
|
||||
|
||||
private:
|
||||
std::string _name;
|
||||
};
|
||||
|
||||
/*!
|
||||
* An error that signals a bad parameter type
|
||||
*
|
||||
* Thrown by eoParser::valueOf
|
||||
*
|
||||
* @ingroup Parameters
|
||||
*/
|
||||
class eoWrongParamTypeException : public std::exception
|
||||
{
|
||||
public:
|
||||
eoWrongParamTypeException(std::string name) : _name(name){}
|
||||
|
||||
virtual const char* what() const throw()
|
||||
{
|
||||
std::ostringstream ss;
|
||||
ss << "You asked for the parameter " << _name << " but it has not been declared under this type";
|
||||
return ss.str().c_str();
|
||||
}
|
||||
|
||||
~eoWrongParamTypeException() throw() {}
|
||||
|
||||
private:
|
||||
std::string _name;
|
||||
};
|
||||
|
||||
#endif // __eoExceptions_h__
|
||||
213
trunk/eo/src/eoExtendedVelocity.h
Normal file
213
trunk/eo/src/eoExtendedVelocity.h
Normal file
|
|
@ -0,0 +1,213 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoExtendedVelocity.h
|
||||
// (c) INRIA Dolphin 2008
|
||||
/*
|
||||
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: thomas.legrand@inria.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoExtendedVelocity_H
|
||||
#define eoExtendedVelocity_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoFunctor.h>
|
||||
#include <utils/eoRNG.h>
|
||||
#include <eoPop.h>
|
||||
#include <utils/eoRealVectorBounds.h>
|
||||
#include <eoRealBoundModifier.h>
|
||||
#include <eoTopology.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
/** Extended velocity performer for particle swarm optimization.
|
||||
*
|
||||
* Derivated from abstract eoVelocity,
|
||||
* At step t: v(t+1)= w * v(t) + c1 * r1 * ( xbest(t)-x(t) ) + c2 * r2 * ( lbest(t) - x(t) ) + c3 * r3 * ( gbest(t) - x(t) )
|
||||
* It includes both a "topology" best and a global best in the social knowledge. Each topology
|
||||
* provides a method to retrieve the global best <=> the best of all the neighborhood the topology contains.
|
||||
*
|
||||
* @ingroup Variators
|
||||
*/
|
||||
template < class POT > class eoExtendedVelocity:public eoVelocity < POT >
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
/*
|
||||
* Each element for the velocity evaluation is expected to be of type VelocityType.
|
||||
*/
|
||||
typedef typename POT::ParticleVelocityType VelocityType;
|
||||
|
||||
/** Full constructor: Bounds and bound modifier required
|
||||
* @param _topology - The topology
|
||||
* @param _w - The weight factor.
|
||||
* @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - Learning factor used for the local best
|
||||
* @param _c3 - Learning factor used for the global best
|
||||
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
|
||||
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
|
||||
* @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoExtendedVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _w,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2,
|
||||
const VelocityType & _c3,
|
||||
eoRealVectorBounds & _bounds,
|
||||
eoRealBoundModifier & _bndsModifier,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
omega (_w),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
c3 (_c3),
|
||||
bounds(_bounds),
|
||||
bndsModifier(_bndsModifier),
|
||||
gen(_gen){}
|
||||
|
||||
|
||||
/** Constructor: No bound updater required <-> fixed bounds
|
||||
* @param _topology - The topology
|
||||
* @param _w - The weight factor.
|
||||
* @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType
|
||||
* @param _c3 - Learning factor used for the global best
|
||||
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
|
||||
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoExtendedVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _w,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2,
|
||||
const VelocityType & _c3,
|
||||
eoRealVectorBounds & _bounds,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
omega (_w),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
c3 (_c3),
|
||||
bounds(_bounds),
|
||||
bndsModifier(dummyModifier),
|
||||
gen(_gen){}
|
||||
|
||||
|
||||
/** Constructor: Neither bounds nor bound updater required <-> free velocity
|
||||
* @param _topology - The topology
|
||||
* @param _w - The weight factor.
|
||||
* @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType
|
||||
* @param _c3 - Learning factor used for the global best
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoExtendedVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _w,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2,
|
||||
const VelocityType & _c3,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
omega (_w),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
c3 (_c3),
|
||||
bounds(*(new eoRealVectorNoBounds(0))),
|
||||
bndsModifier(dummyModifier),
|
||||
gen(_gen)
|
||||
{}
|
||||
|
||||
|
||||
/**
|
||||
* Evaluate the new velocities of the given particle. Need an indice to identify the particle
|
||||
* into the topology.
|
||||
* @param _po - A particle
|
||||
* @param _indice - The indice (into the topology) of the given particle
|
||||
*/
|
||||
void operator () (POT & _po,unsigned _indice)
|
||||
{
|
||||
VelocityType r1;
|
||||
VelocityType r2;
|
||||
VelocityType r3;
|
||||
|
||||
VelocityType newVelocity;
|
||||
|
||||
// cast the learning factors to VelocityType
|
||||
r1 = (VelocityType) rng.uniform (1) * c1;
|
||||
r2 = (VelocityType) rng.uniform (1) * c2;
|
||||
r3 = (VelocityType) rng.uniform (1) * c3;
|
||||
|
||||
// need to resize the bounds even if there are dummy because of "isBounded" call
|
||||
bounds.adjust_size(_po.size());
|
||||
|
||||
// assign the new velocities
|
||||
for (unsigned j = 0; j < _po.size (); j++)
|
||||
{
|
||||
newVelocity= omega * _po.velocities[j]
|
||||
+ r1 * (_po.bestPositions[j] - _po[j])
|
||||
+ r2 * (topology.best (_indice)[j] - _po[j])
|
||||
+ r3 * (topology.globalBest()[j] - _po[j]);
|
||||
|
||||
/* check bounds */
|
||||
if (bounds.isMinBounded(j))
|
||||
newVelocity=std::max(newVelocity,bounds.minimum(j));
|
||||
if (bounds.isMaxBounded(j))
|
||||
newVelocity=std::min(newVelocity,bounds.maximum(j));
|
||||
|
||||
_po.velocities[j]=newVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the neighborhood.
|
||||
*/
|
||||
void updateNeighborhood(POT & _po,unsigned _indice)
|
||||
{
|
||||
topology.updateNeighborhood(_po,_indice);
|
||||
}
|
||||
|
||||
//! eoTopology<POT> getTopology
|
||||
//! @return topology
|
||||
|
||||
eoTopology<POT> & getTopology ()
|
||||
{
|
||||
return topology;
|
||||
}
|
||||
|
||||
protected:
|
||||
eoTopology < POT > & topology;
|
||||
const VelocityType & omega; // social/cognitive coefficient
|
||||
const VelocityType & c1;
|
||||
const VelocityType & c2; // social/cognitive coefficient
|
||||
const VelocityType & c3; // social/cognitive coefficient
|
||||
|
||||
eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type.
|
||||
eoRealBoundModifier & bndsModifier;
|
||||
|
||||
eoRng & gen; // the random generator
|
||||
|
||||
// If the bound modifier doesn't need to be used, use the dummy instance
|
||||
eoDummyRealBoundModifier dummyModifier;
|
||||
};
|
||||
/** @todo this example does not appear in the doc for an unknown reason
|
||||
* @example t-eoExtendedVelocity.cpp
|
||||
* Example of a test program using this class:
|
||||
*/
|
||||
#endif /*eoExtendedVelocity_H */
|
||||
75
trunk/eo/src/eoFactory.h
Normal file
75
trunk/eo/src/eoFactory.h
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
// -*- 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
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
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
|
||||
69
trunk/eo/src/eoFitContinue.h
Normal file
69
trunk/eo/src/eoFitContinue.h
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
// -*- 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>
|
||||
#include <utils/eoLogger.h>
|
||||
|
||||
/**
|
||||
Continues until the optimum fitness level is reached.
|
||||
|
||||
All types which derive from eoScalarFitness is able to compare well via the operator override ( <, >, <=, ...)
|
||||
|
||||
@ingroup Continuators
|
||||
*/
|
||||
template< class EOT>
|
||||
class eoFitContinue: public eoContinue<EOT> {
|
||||
public:
|
||||
|
||||
/// Define Fitness
|
||||
typedef typename EOT::Fitness FitnessType;
|
||||
|
||||
/// Ctor
|
||||
eoFitContinue( const FitnessType _optimum)
|
||||
: eoContinue<EOT> (), optimum( _optimum ) {};
|
||||
|
||||
/** 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);
|
||||
FitnessType bestCurrentFitness = _pop.best_element().fitness();
|
||||
if (bestCurrentFitness >= optimum)
|
||||
{
|
||||
eo::log << eo::logging << "STOP in eoFitContinue: Best fitness has reached " <<
|
||||
bestCurrentFitness << "\n";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual std::string className(void) const { return "eoFitContinue"; }
|
||||
|
||||
private:
|
||||
FitnessType optimum;
|
||||
};
|
||||
|
||||
#endif
|
||||
55
trunk/eo/src/eoFitnessScalingSelect.h
Normal file
55
trunk/eo/src/eoFitnessScalingSelect.h
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
// -*- 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
|
||||
*
|
||||
* @ingroup Selectors
|
||||
*/
|
||||
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
|
||||
191
trunk/eo/src/eoFixedInertiaWeightedVelocity.h
Normal file
191
trunk/eo/src/eoFixedInertiaWeightedVelocity.h
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoFixedInertiaWeightedVelocity.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EOFIXEDINERTIAWEIGHTEDVELOCITY_H
|
||||
#define EOFIXEDINERTIAWEIGHTEDVELOCITY_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoFunctor.h>
|
||||
#include <utils/eoRNG.h>
|
||||
#include <eoPop.h>
|
||||
#include <utils/eoRealVectorBounds.h>
|
||||
#include <eoTopology.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
/** Inertia weight based velocity performer. Derivated from abstract eoVelocity,
|
||||
* At step t+1 : v(t+1)= w * v(t) + c1*r1 * (xbest(t)-x(t)) + c2*r2 * (gbest(t) - x(t))
|
||||
* w is fixed for all the particles and all the generations.
|
||||
* (ci and w given; Ri chosen at random * in [0;1])
|
||||
*
|
||||
* @ingroup Variators
|
||||
*/
|
||||
template < class POT > class eoFixedInertiaWeightedVelocity:public eoVelocity < POT >
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
/*
|
||||
* Each element for the velocity evaluation is expected to be of type VelocityType.
|
||||
*/
|
||||
typedef typename POT::ParticleVelocityType VelocityType;
|
||||
|
||||
/** Full constructor: Bounds and bound modifier required
|
||||
* @param _topology - The topology to get the global/local/other best
|
||||
* @param _weight - The weight with type VelocityType
|
||||
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
|
||||
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
|
||||
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
|
||||
* @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _weight,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2 ,
|
||||
eoRealVectorBounds & _bounds,
|
||||
eoRealBoundModifier & _bndsModifier,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
weight(_weight),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
bounds(_bounds),
|
||||
bndsModifier(_bndsModifier),
|
||||
gen(_gen){}
|
||||
|
||||
|
||||
/** Constructor: No bound updater required <-> fixed bounds
|
||||
* @param _topology - The topology to get the global/local/other best
|
||||
* @param _weight - The weight with type VelocityType
|
||||
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
|
||||
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
|
||||
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _weight,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2,
|
||||
eoRealVectorBounds & _bounds,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
weight(_weight),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
bounds(_bounds),
|
||||
bndsModifier(dummyModifier),
|
||||
gen(_gen){}
|
||||
|
||||
|
||||
/** Constructor: Neither bounds nor bound updater required <-> free velocity
|
||||
* @param _topology - The topology to get the global/local/other best
|
||||
* @param _weight - The weight with type VelocityType
|
||||
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _weight,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
weight(_weight),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
bounds(*(new eoRealVectorNoBounds(0))),
|
||||
bndsModifier(dummyModifier),
|
||||
gen(_gen)
|
||||
{}
|
||||
|
||||
/**
|
||||
* Evaluate the new velocities of the given particle. Need an indice to identify the particle
|
||||
* into the topology. Steps are :
|
||||
* - evaluate r1 and r2, the customed learning factors
|
||||
* - adjust the size of the bounds (even if dummy)
|
||||
* - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided)
|
||||
* @param _po - A particle
|
||||
* @param _indice - The indice (into the topology) of the given particle
|
||||
*/
|
||||
void operator () (POT & _po,unsigned _indice)
|
||||
{
|
||||
VelocityType r1;
|
||||
VelocityType r2;
|
||||
|
||||
VelocityType newVelocity;
|
||||
|
||||
// cast the learning factors to VelocityType
|
||||
r1 = (VelocityType) rng.uniform (1) * c1;
|
||||
r2 = (VelocityType) rng.uniform (1) * c2;
|
||||
|
||||
// need to resize the bounds even if there are dummy because of "isBounded" call
|
||||
bounds.adjust_size(_po.size());
|
||||
|
||||
// assign the new velocities
|
||||
for (unsigned j = 0; j < _po.size (); j++)
|
||||
{
|
||||
newVelocity= weight * _po.velocities[j] + r1 * (_po.bestPositions[j] - _po[j]) + r2 * (topology.best (_indice)[j] - _po[j]);
|
||||
|
||||
/* modify the bounds */
|
||||
bndsModifier(bounds,j);
|
||||
|
||||
/* check bounds */
|
||||
if (bounds.isMinBounded(j))
|
||||
newVelocity=(VelocityType)std::max(newVelocity,bounds.minimum(j));
|
||||
if (bounds.isMaxBounded(j))
|
||||
newVelocity=(VelocityType)std::min(newVelocity,bounds.maximum(j));
|
||||
|
||||
_po.velocities[j]=newVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the neighborhood.
|
||||
*/
|
||||
void updateNeighborhood(POT & _po,unsigned _indice)
|
||||
{
|
||||
topology.updateNeighborhood(_po,_indice);
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected:
|
||||
eoTopology < POT > & topology;
|
||||
const VelocityType & c1; // learning factor 1
|
||||
const VelocityType & c2; // learning factor 2
|
||||
const VelocityType & weight; // the fixed weight
|
||||
eoRng & gen; // the random generator
|
||||
|
||||
eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type.
|
||||
eoRealBoundModifier & bndsModifier;
|
||||
|
||||
// If the bound modifier doesn't need to be used, use the dummy instance
|
||||
eoDummyRealBoundModifier dummyModifier;
|
||||
};
|
||||
|
||||
|
||||
#endif /*EOFIXEDINERTIAWEIGHTEDVELOCITY_H */
|
||||
224
trunk/eo/src/eoFlOrBinOp.h
Normal file
224
trunk/eo/src/eoFlOrBinOp.h
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
// -*- 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>
|
||||
|
||||
/** @addtogroup Variators
|
||||
* @{
|
||||
*/
|
||||
|
||||
/** 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
|
||||
123
trunk/eo/src/eoFlOrMonOp.h
Normal file
123
trunk/eo/src/eoFlOrMonOp.h
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
// -*- 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>
|
||||
|
||||
/** @addtogroup Variators
|
||||
* @{
|
||||
*/
|
||||
|
||||
/** 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
|
||||
218
trunk/eo/src/eoFlOrQuadOp.h
Normal file
218
trunk/eo/src/eoFlOrQuadOp.h
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
// -*- 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>
|
||||
|
||||
/** @addtogroup Variators
|
||||
* @{
|
||||
*/
|
||||
|
||||
/** 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
|
||||
55
trunk/eo/src/eoFlight.h
Normal file
55
trunk/eo/src/eoFlight.h
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoFlight.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EOFLIGHT_H
|
||||
#define EOFLIGHT_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoFunctor.h>
|
||||
#include <utils/eoRealVectorBounds.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/** Abstract class for particle swarm optimization flight.
|
||||
* All the flights must derivated from eoFlight.
|
||||
*
|
||||
* @ingroup Variators
|
||||
*/
|
||||
template < class POT > class eoFlight:public eoUF < POT &, void >
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* Apply the flight to a whole population.
|
||||
*/
|
||||
virtual void apply (eoPop < POT > &_pop)
|
||||
{
|
||||
for (unsigned i = 0; i < _pop.size (); i++)
|
||||
{
|
||||
this->operator ()(_pop[i]);
|
||||
}
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
#endif /*EOFLIGHT_H */
|
||||
184
trunk/eo/src/eoFunctor.h
Normal file
184
trunk/eo/src/eoFunctor.h
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
// -*- 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: /home/nojhan/dev/eodev/eodev_cvs/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>
|
||||
|
||||
/** @addtogroup Core
|
||||
* @{
|
||||
*/
|
||||
|
||||
/** 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 {};
|
||||
};
|
||||
/** @example t-eoFunctor.cpp
|
||||
*/
|
||||
|
||||
/**
|
||||
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
|
||||
18
trunk/eo/src/eoFunctorStore.cpp
Normal file
18
trunk/eo/src/eoFunctorStore.cpp
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
#ifdef _MSC_VER
|
||||
// to avoid long name warnings
|
||||
#pragma warning(disable:4786)
|
||||
#endif
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
#include <eoFunctorStore.h>
|
||||
#include <eoFunctor.h>
|
||||
|
||||
|
||||
/// clears the memory
|
||||
eoFunctorStore::~eoFunctorStore()
|
||||
{
|
||||
for( std::size_t i = 0; i < vec.size(); ++i) {
|
||||
delete vec[i];
|
||||
}
|
||||
}
|
||||
73
trunk/eo/src/eoFunctorStore.h
Normal file
73
trunk/eo/src/eoFunctorStore.h
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
// -*- 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.
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
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 assignment allowed */
|
||||
eoFunctorStore operator=(const eoFunctorStore&);
|
||||
|
||||
std::vector<eoFunctorBase*> vec;
|
||||
};
|
||||
|
||||
#endif
|
||||
86
trunk/eo/src/eoG3Replacement.h
Normal file
86
trunk/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
|
||||
|
||||
@ingroup Replacors
|
||||
*/
|
||||
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
|
||||
71
trunk/eo/src/eoGaussRealWeightUp.h
Normal file
71
trunk/eo/src/eoGaussRealWeightUp.h
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoGaussRealWeightUp.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EOGAUSSREALWEIGHTUP_H
|
||||
#define EOGAUSSREALWEIGHTUP_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoWeightUpdater.h>
|
||||
#include <utils/eoRNG.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
/**
|
||||
* Update an inertia weight by assigning it a Gaussian randomized value
|
||||
* (used for the velocity in particle swarm optimization).
|
||||
*
|
||||
* @ingroup Variators
|
||||
*/
|
||||
class eoGaussRealWeightUp:public eoWeightUpdater<double>
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* Default constructor
|
||||
* @param _mean - Mean for Gaussian distribution
|
||||
* @param _stdev - Standard deviation for Gaussian distribution
|
||||
*/
|
||||
eoGaussRealWeightUp(
|
||||
double _mean=0,
|
||||
double _stdev=1.0
|
||||
):mean(_mean),stdev(_stdev){}
|
||||
|
||||
/**
|
||||
* Assign Gaussian deviation to _weight
|
||||
* @param _weight - The modified weight as a double
|
||||
*/
|
||||
void operator() (double & _weight)
|
||||
{
|
||||
_weight=rng.normal(mean,stdev);
|
||||
}
|
||||
|
||||
|
||||
protected:
|
||||
double mean,stdev;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif/*EOGAUSSREALWEIGHTUP_H*/
|
||||
114
trunk/eo/src/eoGenContinue.h
Normal file
114
trunk/eo/src/eoGenContinue.h
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
// -*- 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>
|
||||
#include <utils/eoLogger.h>
|
||||
|
||||
/**
|
||||
Generational continuator: continues until a number of generations is reached
|
||||
|
||||
@ingroup Continuators
|
||||
*/
|
||||
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)
|
||||
{};
|
||||
|
||||
/// 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)
|
||||
{};
|
||||
|
||||
/** Returns false when a certain number of generations is
|
||||
* reached */
|
||||
virtual bool operator() ( const eoPop<EOT>& _vEO ) {
|
||||
(void)_vEO;
|
||||
thisGeneration++;
|
||||
value() = thisGeneration;
|
||||
|
||||
if (thisGeneration >= repTotalGenerations)
|
||||
{
|
||||
eo::log << eo::logging << "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)
|
||||
|
||||
@todo replace this by an "init" method
|
||||
*/
|
||||
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"; }
|
||||
|
||||
/** Read from a stream
|
||||
* @param __is the istream to read from
|
||||
*/
|
||||
void readFrom (std :: istream & __is) {
|
||||
|
||||
__is >> thisGeneration; /* Loading the number of generations counted */
|
||||
}
|
||||
|
||||
/** Print on a stream
|
||||
* @param __os the ostream to print on
|
||||
*/
|
||||
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;
|
||||
};
|
||||
|
||||
#endif
|
||||
229
trunk/eo/src/eoGenOp.h
Normal file
229
trunk/eo/src/eoGenOp.h
Normal file
|
|
@ -0,0 +1,229 @@
|
|||
// -*- 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
|
||||
|
||||
@ingroup Core
|
||||
@ingroup Variators
|
||||
*/
|
||||
|
||||
//@{
|
||||
|
||||
/** 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;
|
||||
};
|
||||
/** @example t-eoGenOp.cpp
|
||||
*/
|
||||
|
||||
|
||||
/** 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
|
||||
|
||||
//@}
|
||||
107
trunk/eo/src/eoGeneralBreeder.h
Normal file
107
trunk/eo/src/eoGeneralBreeder.h
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
// -*- 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.
|
||||
|
||||
@ingroup Combination
|
||||
*/
|
||||
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
|
||||
214
trunk/eo/src/eoInit.h
Normal file
214
trunk/eo/src/eoInit.h
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
// -*- 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>
|
||||
#include <utils/rnd_generators.h> // for shuffle method
|
||||
|
||||
|
||||
/**
|
||||
@defgroup Initializators Initialization operators
|
||||
@ingroup Operators
|
||||
|
||||
Initializators are operators that creates initial individuals and populations.
|
||||
*/
|
||||
/** @{*/
|
||||
/**
|
||||
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;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
Initializer for permutation (integer-based) representations.
|
||||
*/
|
||||
template <class EOT>
|
||||
class eoInitPermutation: public eoInit<EOT>
|
||||
{
|
||||
public:
|
||||
|
||||
typedef typename EOT::AtomType AtomType;
|
||||
|
||||
eoInitPermutation(unsigned _chromSize, unsigned _startFrom=0)
|
||||
: chromSize(_chromSize), startFrom(_startFrom){}
|
||||
|
||||
virtual void operator()(EOT& chrom)
|
||||
{
|
||||
chrom.resize(chromSize);
|
||||
for(unsigned idx=0;idx <chrom.size();idx++)
|
||||
chrom[idx]=idx+startFrom;
|
||||
|
||||
std::random_shuffle(chrom.begin(), chrom.end(),gen);
|
||||
chrom.invalidate();
|
||||
}
|
||||
|
||||
private :
|
||||
unsigned chromSize;
|
||||
unsigned startFrom;
|
||||
UF_random_generator<unsigned int> gen;
|
||||
};
|
||||
/** @example t-eoInitPermutation.cpp
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
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
|
||||
/** @}*/
|
||||
147
trunk/eo/src/eoInitializer.h
Normal file
147
trunk/eo/src/eoInitializer.h
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoInitializer.h
|
||||
// (c) OPAC Team, INRIA, 2007
|
||||
/*
|
||||
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: clive.canape@inria.fr
|
||||
|
||||
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoInitializer_H
|
||||
#define _eoInitializer_H
|
||||
|
||||
#include <utils/eoRealVectorBounds.h>
|
||||
#include <eoVelocityInit.h>
|
||||
#include <eoPop.h>
|
||||
#include <eoParticleBestInit.h>
|
||||
#include <eoTopology.h>
|
||||
|
||||
/**
|
||||
@addtogroup Initializators
|
||||
@{
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Abstract class for initialization of algorithm PSO
|
||||
*/
|
||||
template <class POT> class eoInitializerBase : public eoFunctorBase
|
||||
{
|
||||
public :
|
||||
|
||||
virtual ~eoInitializerBase()
|
||||
{}
|
||||
|
||||
virtual void operator()()
|
||||
{};
|
||||
};
|
||||
|
||||
/**
|
||||
Base (name) class for Initialization of algorithm PSO
|
||||
|
||||
@see eoInitializerBase eoUF apply
|
||||
*/
|
||||
template <class POT> class eoInitializer : public eoInitializerBase <POT>
|
||||
{
|
||||
public:
|
||||
|
||||
//! Constructor
|
||||
//! @param _proc Evaluation function
|
||||
//! @param _initVelo Initialization of the velocity
|
||||
//! @param _initBest Initialization of the best
|
||||
//! @param _topology the topology to use
|
||||
//! @param _pop Population
|
||||
eoInitializer(
|
||||
eoUF<POT&, void>& _proc,
|
||||
eoVelocityInit < POT > &_initVelo,
|
||||
eoParticleBestInit <POT> &_initBest,
|
||||
eoTopology <POT> &_topology,
|
||||
eoPop < POT > &_pop
|
||||
) : proc(_proc), initVelo(_initVelo), procPara(dummyEval), initBest(_initBest), topology(_topology), pop(_pop)
|
||||
{}
|
||||
|
||||
//! Constructor for parallel evaluation
|
||||
//! @param _proc Evaluation function
|
||||
//! @param _initVelo Initialization of the velocity
|
||||
//! @param _initBest Initialization of the best
|
||||
//! @param _topology the topology to use
|
||||
//! @param _pop Population
|
||||
eoInitializer(
|
||||
eoPopEvalFunc <POT>& _proc,
|
||||
eoVelocityInit < POT > &_initVelo,
|
||||
eoParticleBestInit <POT> &_initBest,
|
||||
eoTopology <POT> &_topology,
|
||||
eoPop < POT > &_pop
|
||||
) : proc(dummy), initVelo(_initVelo), procPara(_proc), initBest(_initBest), topology(_topology), pop(_pop)
|
||||
{}
|
||||
|
||||
|
||||
//! Give the name of the class
|
||||
//! @return The name of the class
|
||||
virtual std::string className (void) const
|
||||
{
|
||||
return "eoInitializer";
|
||||
}
|
||||
|
||||
|
||||
|
||||
virtual void operator() ()
|
||||
{
|
||||
eoPop<POT> empty_pop;
|
||||
apply(proc, pop);
|
||||
procPara(empty_pop, pop);
|
||||
apply < POT > (initVelo, pop);
|
||||
apply < POT > (initBest, pop);
|
||||
topology.setup(pop);
|
||||
}
|
||||
|
||||
private :
|
||||
|
||||
/*
|
||||
@param proc First evaluation
|
||||
@param initVelo Initialization of the velocity
|
||||
@param initBest Initialization of the best
|
||||
*/
|
||||
eoUF<POT&, void>& proc;
|
||||
eoVelocityInit < POT > & initVelo;
|
||||
eoPopEvalFunc <POT>& procPara;
|
||||
eoParticleBestInit <POT> & initBest;
|
||||
eoTopology <POT> & topology;
|
||||
eoPop < POT > & pop;
|
||||
|
||||
class eoDummyEval : public eoPopEvalFunc<POT>
|
||||
{
|
||||
public:
|
||||
void operator()(eoPop<POT> &,eoPop<POT> &/*_pop*/)
|
||||
{}
|
||||
}
|
||||
dummyEval;
|
||||
class eoDummy : public eoUF<POT&, void>
|
||||
{
|
||||
public:
|
||||
void operator()(POT &)
|
||||
{}
|
||||
|
||||
}
|
||||
dummy;
|
||||
};
|
||||
#endif
|
||||
|
||||
/** @} */
|
||||
63
trunk/eo/src/eoInt.h
Normal file
63
trunk/eo/src/eoInt.h
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
/*
|
||||
eoInt.h
|
||||
// (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2 of the License, or (at your option) any later version.
|
||||
|
||||
This library is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
Contact: thomas.legrand@lifl.fr
|
||||
todos@geneura.ugr.es, http://geneura.ugr.es
|
||||
mkeijzer@dhi.dk
|
||||
*/
|
||||
|
||||
#ifndef eoInt_h
|
||||
#define eoInt_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <iostream> // std::ostream, std::istream
|
||||
#include <string> // std::string
|
||||
|
||||
#include <eoVector.h>
|
||||
|
||||
/** eoInt: implementation of simple integer-valued chromosome.
|
||||
* based on eoVector class
|
||||
*
|
||||
* @ingroup Representations
|
||||
*/
|
||||
template <class FitT> class eoInt: public eoVector<FitT, int>
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* (Default) Constructor.
|
||||
* @param size Size of the std::vector
|
||||
* @param value fill the vector with this value
|
||||
*/
|
||||
eoInt(unsigned size = 0, int value = 0):
|
||||
eoVector<FitT, int>(size, value) {}
|
||||
|
||||
/// My class name.
|
||||
virtual std::string className() const
|
||||
{
|
||||
return "eoInt";
|
||||
}
|
||||
|
||||
};
|
||||
/** @example t-eoInt.cpp
|
||||
*/
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#endif
|
||||
195
trunk/eo/src/eoIntegerVelocity.h
Normal file
195
trunk/eo/src/eoIntegerVelocity.h
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoIntegerVelocity.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
clive.canape@inria.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EOINTEGERVELOCITY_H
|
||||
#define EOINTEGERVELOCITY_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoFunctor.h>
|
||||
#include <utils/eoRNG.h>
|
||||
#include <eoPop.h>
|
||||
#include <utils/eoRealVectorBounds.h>
|
||||
#include <eoRealBoundModifier.h>
|
||||
#include <eoTopology.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
/** Integer velocity performer for particle swarm optimization. Derivated from abstract eoVelocity,
|
||||
* At step t: v(t+1)= c1 * v(t) + c2 * r2 * ( xbest(t)-x(t) ) + c3 * r3 * ( gbest(t) - x(t) )
|
||||
* v(t) is an INT for any time step
|
||||
* (ci given and Ri chosen at random in [0;1]).
|
||||
*
|
||||
* @ingroup Variators
|
||||
*/
|
||||
template < class POT > class eoIntegerVelocity:public eoVelocity < POT >
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
/*
|
||||
* Each element for the velocity evaluation is expected to be of type VelocityType.
|
||||
*/
|
||||
typedef typename POT::ParticleVelocityType VelocityType;
|
||||
|
||||
/** Full constructor: Bounds and bound modifier required
|
||||
* @param _topology - The topology to get the global/local/other best
|
||||
* @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
|
||||
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
|
||||
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
|
||||
* @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoIntegerVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2,
|
||||
const VelocityType & _c3,
|
||||
eoRealVectorBounds & _bounds,
|
||||
eoRealBoundModifier & _bndsModifier,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
c3 (_c3),
|
||||
bounds(_bounds),
|
||||
bndsModifier(_bndsModifier),
|
||||
gen(_gen){}
|
||||
|
||||
|
||||
/** Constructor: No bound updater required <-> fixed bounds
|
||||
* @param _topology - The topology to get the global/local/other best
|
||||
* @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
|
||||
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
|
||||
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoIntegerVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2,
|
||||
const VelocityType & _c3,
|
||||
eoRealVectorBounds & _bounds,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
c3 (_c3),
|
||||
bounds(_bounds),
|
||||
bndsModifier(dummyModifier),
|
||||
gen(_gen){}
|
||||
|
||||
|
||||
/** Constructor: Neither bounds nor bound updater required <-> free velocity
|
||||
* @param _topology the topology to use
|
||||
* @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType
|
||||
* @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType
|
||||
* @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
|
||||
* @param _gen - The eo random generator, default=rng
|
||||
*/
|
||||
eoIntegerVelocity (eoTopology < POT > & _topology,
|
||||
const VelocityType & _c1,
|
||||
const VelocityType & _c2,
|
||||
const VelocityType & _c3,
|
||||
eoRng & _gen = rng):
|
||||
topology(_topology),
|
||||
c1 (_c1),
|
||||
c2 (_c2),
|
||||
c3 (_c3),
|
||||
bounds(*(new eoRealVectorNoBounds(0))),
|
||||
bndsModifier(dummyModifier),
|
||||
gen(_gen)
|
||||
{}
|
||||
|
||||
|
||||
/**
|
||||
* Evaluate the new velocities of the given particle. Need an indice to identify the particle
|
||||
* into the topology.
|
||||
* @param _po - A particle
|
||||
* @param _indice - The indice (into the topology) of the given particle
|
||||
*/
|
||||
void operator () (POT & _po,unsigned _indice)
|
||||
{
|
||||
VelocityType r2;
|
||||
VelocityType r3;
|
||||
|
||||
VelocityType newVelocity;
|
||||
|
||||
// cast the learning factors to VelocityType
|
||||
r2 = (VelocityType) rng.uniform (1) * c2;
|
||||
r3 = (VelocityType) rng.uniform (1) * c3;
|
||||
|
||||
// need to resize the bounds even if there are dummy because of "isBounded" call
|
||||
bounds.adjust_size(_po.size());
|
||||
|
||||
// assign the new velocities
|
||||
for (unsigned j = 0; j < _po.size (); j++)
|
||||
{
|
||||
newVelocity= round (c1 * _po.velocities[j] + r2 * (_po.bestPositions[j] - _po[j]) + r3 * (topology.best (_indice)[j] - _po[j]));
|
||||
|
||||
/* check bounds */
|
||||
if (bounds.isMinBounded(j))
|
||||
newVelocity=std::max(newVelocity,bounds.minimum(j));
|
||||
if (bounds.isMaxBounded(j))
|
||||
newVelocity=std::min(newVelocity,bounds.maximum(j));
|
||||
|
||||
_po.velocities[j]=newVelocity;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the neighborhood.
|
||||
*/
|
||||
void updateNeighborhood(POT & _po,unsigned _indice)
|
||||
{
|
||||
topology.updateNeighborhood(_po,_indice);
|
||||
}
|
||||
|
||||
//! eoTopology<POT> getTopology
|
||||
//! @return topology
|
||||
|
||||
eoTopology<POT> & getTopology ()
|
||||
{
|
||||
return topology;
|
||||
}
|
||||
|
||||
protected:
|
||||
eoTopology < POT > & topology;
|
||||
const VelocityType & c1; // social/cognitive coefficient
|
||||
const VelocityType & c2; // social/cognitive coefficient
|
||||
const VelocityType & c3; // social/cognitive coefficient
|
||||
|
||||
eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type.
|
||||
eoRealBoundModifier & bndsModifier;
|
||||
|
||||
eoRng & gen; // the random generator
|
||||
|
||||
// If the bound modifier doesn't need to be used, use the dummy instance
|
||||
eoDummyRealBoundModifier dummyModifier;
|
||||
};
|
||||
|
||||
|
||||
#endif /*EOINTEGERVELOCITY_H */
|
||||
135
trunk/eo/src/eoInvalidateOps.h
Normal file
135
trunk/eo/src/eoInvalidateOps.h
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
// -*- 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>
|
||||
|
||||
/** @addtogroup Utilities
|
||||
|
||||
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
|
||||
77
trunk/eo/src/eoLinearDecreasingWeightUp.h
Normal file
77
trunk/eo/src/eoLinearDecreasingWeightUp.h
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoLinearDecreasingWeightUp.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EOLINEARDECREASINGWEIGHTUP_H
|
||||
#define EOLINEARDECREASINGWEIGHTUP_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoWeightUpdater.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
/**
|
||||
* Linear (inertia) weight updater for particle swarm optimization. Update a weight according to:
|
||||
* w(t)=(w(0)-w(Nt))*(Nt -t)/Nt + w(Nt) where
|
||||
* t is the current generation/event
|
||||
* Nt is the total number of generations/event
|
||||
* w(0) is the initial weight
|
||||
* w(Nt) is the last inertia weight
|
||||
*
|
||||
* @ingroup Variators
|
||||
*/
|
||||
template <class WeightType, class StopCriteriaType> class eoLinearDecreasingWeightUp:public eoWeightUpdater<WeightType>
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* Ctor
|
||||
*/
|
||||
eoLinearDecreasingWeightUp(
|
||||
const StopCriteriaType & _stop,
|
||||
const WeightType & _initialValue,
|
||||
const WeightType & _finalValue,
|
||||
eoValueParam<StopCriteriaType> & _counter):
|
||||
stop(_stop),
|
||||
initialValue(_initialValue),
|
||||
finalValue(_finalValue),
|
||||
counter(_counter){}
|
||||
|
||||
/**
|
||||
* Update the given weight
|
||||
*/
|
||||
void operator() (WeightType & _weight)
|
||||
{
|
||||
_weight=(initialValue-finalValue)* (WeightType)(stop-counter.value())/(WeightType)stop + finalValue;
|
||||
|
||||
}
|
||||
|
||||
protected:
|
||||
const StopCriteriaType & stop;
|
||||
const WeightType & initialValue,finalValue;
|
||||
eoValueParam<StopCriteriaType> & counter; // a counter of the number of past events (should say "generations")
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif/*EOLINEARDECREASINGWEIGHTUP_H*/
|
||||
94
trunk/eo/src/eoLinearFitScaling.h
Normal file
94
trunk/eo/src/eoLinearFitScaling.h
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
/** -*- 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
|
||||
*
|
||||
* @ingroup Selectors
|
||||
*/
|
||||
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
|
||||
217
trunk/eo/src/eoLinearTopology.h
Normal file
217
trunk/eo/src/eoLinearTopology.h
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoLinearTopology.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
clive.canape@inria.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EOLINEARTOPOLOGY_H_
|
||||
#define EOLINEARTOPOLOGY_H_
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoPop.h>
|
||||
#include <eoTopology.h>
|
||||
#include <eoSocialNeighborhood.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
|
||||
/**
|
||||
* One of the local best strategies for particle swarm optimization. Each particle has a fixed number of neighbours, ans
|
||||
* the neighborhood is social.
|
||||
* The topology is never modified during the flight.
|
||||
*
|
||||
* @ingroup Selectors
|
||||
*/
|
||||
template < class POT > class eoLinearTopology:public eoTopology <
|
||||
POT >
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
/**
|
||||
* Build the topology made of _neighborhoodSize neighborhoods.
|
||||
* @param _neighborhoodSize - The size of each neighborhood.
|
||||
*/
|
||||
eoLinearTopology (unsigned _neighborhoodSize):neighborhoodSize (_neighborhoodSize),isSetup(false){}
|
||||
|
||||
|
||||
/**
|
||||
* Build the neighborhoods contained in the topology.
|
||||
* @param _pop - The population used to build the neighborhoods.
|
||||
* If it remains several particle (because _pop.size()%neighborhoodSize !=0), there are inserted
|
||||
* in the last neighborhood. So it may be possible to have a bigger neighborhood.
|
||||
*/
|
||||
void setup(const eoPop<POT> & _pop)
|
||||
{
|
||||
if (!isSetup)
|
||||
{
|
||||
// consitency check
|
||||
if (neighborhoodSize >= _pop.size()){
|
||||
std::string s;
|
||||
s.append (" Invalid neighborhood size in eoLinearTopology ");
|
||||
throw std::runtime_error (s);
|
||||
}
|
||||
|
||||
unsigned howManyNeighborhood=_pop.size()/ neighborhoodSize;
|
||||
|
||||
// build all the neighborhoods
|
||||
for (unsigned i=0;i< howManyNeighborhood;i++)
|
||||
{
|
||||
eoSocialNeighborhood<POT> currentNghd;
|
||||
|
||||
currentNghd.best(_pop[i*neighborhoodSize]);
|
||||
for (unsigned k=i*neighborhoodSize;k < neighborhoodSize*(i+1);k++)
|
||||
{
|
||||
currentNghd.put(k);
|
||||
if (_pop[k].fitness() > currentNghd.best().fitness())
|
||||
currentNghd.best(_pop[k]);
|
||||
}
|
||||
neighborhoods.push_back(currentNghd);
|
||||
}
|
||||
|
||||
// assign the last neighborhood to the remaining particles
|
||||
if (_pop.size()%neighborhoodSize !=0)
|
||||
{
|
||||
for (unsigned z=_pop.size()-1;z >= (_pop.size()-_pop.size()%neighborhoodSize);z--){
|
||||
neighborhoods.back().put(z);
|
||||
|
||||
if (_pop[z].fitness() > neighborhoods.back().best().fitness())
|
||||
neighborhoods.back().best(_pop[z]);
|
||||
}
|
||||
}
|
||||
|
||||
isSetup=true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Should activate this part ?
|
||||
/*
|
||||
std::string s;
|
||||
s.append (" Linear topology already setup in eoLinearTopology");
|
||||
throw std::runtime_error (s);
|
||||
*/
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Retrieve the neighboorhood of a particle.
|
||||
* @return _indice - The particle indice (in the population)
|
||||
*/
|
||||
unsigned retrieveNeighborhoodByIndice(unsigned _indice)
|
||||
{
|
||||
unsigned i=0;
|
||||
for (i=0;i< neighborhoods.size();i++)
|
||||
{
|
||||
if (neighborhoods[i].contains(_indice))
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the neighborhood: update the particle's best fitness and the best particle
|
||||
* of the corresponding neighborhood.
|
||||
*/
|
||||
void updateNeighborhood(POT & _po,unsigned _indice)
|
||||
{
|
||||
// update the best fitness of the particle
|
||||
if (_po.fitness() > _po.best())
|
||||
{
|
||||
_po.best(_po.fitness());
|
||||
for(unsigned i=0;i<_po.size();i++)
|
||||
_po.bestPositions[i]=_po[i];
|
||||
}
|
||||
|
||||
// update the best in its neighborhood
|
||||
unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice);
|
||||
if (_po.fitness() > neighborhoods[theGoodNhbd].best().fitness())
|
||||
{
|
||||
neighborhoods[theGoodNhbd].best(_po);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the best informative of a particle. Could be itself.
|
||||
* @param _indice - The indice of a particle in the population
|
||||
* @return POT & - The best particle in the neighborhood of the particle whose indice is _indice
|
||||
*/
|
||||
POT & best (unsigned _indice)
|
||||
{
|
||||
unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice);
|
||||
|
||||
return (neighborhoods[theGoodNhbd].best());
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Return the global best of the topology
|
||||
*/
|
||||
virtual POT & globalBest()
|
||||
{
|
||||
POT gBest,tmp;
|
||||
unsigned indGlobalBest=0;
|
||||
if(neighborhoods.size()==1)
|
||||
return neighborhoods[0].best();
|
||||
|
||||
gBest=neighborhoods[0].best();
|
||||
for(unsigned i=1;i<neighborhoods.size();i++)
|
||||
{
|
||||
tmp=neighborhoods[i].best();
|
||||
if(gBest.best() < tmp.best())
|
||||
{
|
||||
gBest=tmp;
|
||||
indGlobalBest=i;
|
||||
}
|
||||
|
||||
}
|
||||
return neighborhoods[indGlobalBest].best();
|
||||
}
|
||||
|
||||
/**
|
||||
* Print the structure of the topology on the standrad output.
|
||||
*/
|
||||
void printOn()
|
||||
{
|
||||
for (unsigned i=0;i< neighborhoods.size();i++)
|
||||
{
|
||||
std::cout << "{ " ;
|
||||
for (unsigned j=0;j< neighborhoods[i].size();j++)
|
||||
{
|
||||
std::cout << neighborhoods[i].get(j) << " ";
|
||||
}
|
||||
std::cout << "}" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected:
|
||||
std::vector<eoSocialNeighborhood<POT> > neighborhoods;
|
||||
unsigned neighborhoodSize; // the size of each neighborhood
|
||||
|
||||
bool isSetup;
|
||||
|
||||
};
|
||||
|
||||
#endif /*EOLINEARTOPOLOGY_H_ */
|
||||
104
trunk/eo/src/eoMGGReplacement.h
Normal file
104
trunk/eo/src/eoMGGReplacement.h
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
/** -*- 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
|
||||
|
||||
@ingroup Replacors
|
||||
*/
|
||||
|
||||
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)
|
||||
{
|
||||
eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncateSplit adjusted to 2" << std::endl;
|
||||
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
|
||||
142
trunk/eo/src/eoMerge.h
Normal file
142
trunk/eo/src/eoMerge.h
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
// -*- 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
|
||||
#include <utils/eoLogger.h>
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @ingroup Core
|
||||
* @ingroup Replacors
|
||||
*/
|
||||
|
||||
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
|
||||
|
||||
@ingroup Replacors
|
||||
*/
|
||||
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)
|
||||
eo::log << eo::warnings << "Warning: Number of guys to merge in eoElitism was rounded" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
@ingroup Replacors
|
||||
*/
|
||||
template <class EOT> class eoNoElitism : public eoElitism<EOT>
|
||||
{
|
||||
public :
|
||||
eoNoElitism() : eoElitism<EOT>(0) {}
|
||||
};
|
||||
|
||||
/**
|
||||
Very elitist class, copies entire population into next gen
|
||||
@ingroup Replacors
|
||||
*/
|
||||
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
|
||||
119
trunk/eo/src/eoMergeReduce.h
Normal file
119
trunk/eo/src/eoMergeReduce.h
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
/** -*- 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.
|
||||
|
||||
@class eoMergeReduce, the base (pure abstract) class
|
||||
@class eoPlusReplacement the ES plus strategy
|
||||
@class eoCommaReplacement the ES comma strategy
|
||||
*/
|
||||
|
||||
/**
|
||||
eoMergeReduce: abstract replacement strategy that is just an application of
|
||||
an embedded merge, followed by an embedded reduce
|
||||
@ingroup Replacors
|
||||
*/
|
||||
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
|
||||
@ingroup Replacors
|
||||
*/
|
||||
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
|
||||
@ingroup Replacors
|
||||
*/
|
||||
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
|
||||
@ingroup Replacors
|
||||
*/
|
||||
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/eo/src/eoNDSorting.h
Normal file
496
trunk/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 (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)
|
||||
{ // calculate distance
|
||||
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
|
||||
57
trunk/eo/src/eoNeighborhood.h
Normal file
57
trunk/eo/src/eoNeighborhood.h
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoNeighborhood.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EONEIGHBORHOOD_H_
|
||||
#define EONEIGHBORHOOD_H_
|
||||
|
||||
|
||||
/**
|
||||
* Abstract class for neighborboods. Used for particle swarm optimization
|
||||
* topology strategies. Can be social or physical.
|
||||
*
|
||||
* @ingroup Selectors
|
||||
*/
|
||||
template < class POT > class eoNeighborhood
|
||||
{
|
||||
public:
|
||||
|
||||
virtual void put(unsigned _oneIndice)=0;
|
||||
|
||||
virtual bool contains(unsigned _oneIndice)=0;
|
||||
|
||||
virtual unsigned size()=0;
|
||||
|
||||
virtual unsigned get(unsigned _index)=0;
|
||||
|
||||
virtual POT & best()=0;
|
||||
|
||||
virtual void best(POT _particle)=0;
|
||||
|
||||
/// Virtual dtor
|
||||
virtual ~eoNeighborhood() {};
|
||||
|
||||
};
|
||||
|
||||
|
||||
#endif /* EONEIGHBORHOOD_H_ */
|
||||
75
trunk/eo/src/eoObject.h
Normal file
75
trunk/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 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.
|
||||
*/
|
||||
|
||||
/** Defines a name (#className#), used when loading or saving a state.
|
||||
|
||||
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
|
||||
|
||||
@ingroup Core
|
||||
*/
|
||||
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
|
||||
121
trunk/eo/src/eoOneToOneBreeder.h
Normal file
121
trunk/eo/src/eoOneToOneBreeder.h
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
// -*- 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
|
||||
*
|
||||
* @ingroup Combination
|
||||
*/
|
||||
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 _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
|
||||
189
trunk/eo/src/eoOp.h
Normal file
189
trunk/eo/src/eoOp.h
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
// -*- 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: /home/nojhan/dev/eodev/eodev_cvs/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 Evolutionary Operators
|
||||
|
||||
in EO, an operator is any functors that modifies objects and inherits from an eoOp.
|
||||
|
||||
Typically, a mutation is an operator that modifies an individual, and an algorithm is an operator that modifies a population.
|
||||
|
||||
In EO, 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
|
||||
*/
|
||||
//@{
|
||||
|
||||
/**
|
||||
@defgroup Variators Variation operators
|
||||
Variators are operators that modify individuals.
|
||||
|
||||
@defgroup Selectors Selection operators
|
||||
|
||||
Selectors are operators that select a subset of a population.
|
||||
|
||||
Example:
|
||||
@include t-eoSelect.cpp
|
||||
|
||||
|
||||
@defgroup Replacors Replacement operators
|
||||
|
||||
Replacors are operators that replace a subset of a population by another set of individuals.
|
||||
|
||||
Here is an example with several replacement operators:
|
||||
@include t-eoReplacement.cpp
|
||||
*/
|
||||
|
||||
/** 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
|
||||
|
||||
//@}
|
||||
168
trunk/eo/src/eoOpContainer.h
Normal file
168
trunk/eo/src/eoOpContainer.h
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
// -*- 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
|
||||
*
|
||||
* @ingroup Combination
|
||||
*/
|
||||
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...
|
||||
*
|
||||
* @ingroup Combination
|
||||
*/
|
||||
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) {
|
||||
_pop.reserve( this->max_production() );
|
||||
|
||||
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);
|
||||
|
||||
ops[i]->apply(_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
|
||||
108
trunk/eo/src/eoOpSelMason.h
Normal file
108
trunk/eo/src/eoOpSelMason.h
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
// -*- 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 <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
|
||||
|
||||
@ingroup Utilities
|
||||
*/
|
||||
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
|
||||
92
trunk/eo/src/eoOrderXover.h
Normal file
92
trunk/eo/src/eoOrderXover.h
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoOrderXover.h
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef eoOrderXover_h
|
||||
#define eoOrderXover_h
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#include <algorithm>
|
||||
#include <utils/eoRNG.h>
|
||||
#include <eoInit.h>
|
||||
|
||||
/**
|
||||
* apply orderXover on two chromosomes.
|
||||
* Example:
|
||||
* With 2 parents p1= [1,2,4,3,6,5], p2= [4,5,3,1,6,2]
|
||||
* It applies a random cut between ("|") two indices. Example: the second element and the fourth:
|
||||
* p1 : [1|2,4,3|6,5] and p2 : [4|5,3,1|6,2] generate two children:
|
||||
* c1 = [2,4,3,6,5,1] 2,4,3 taken from p1 and 6,5,1 from p2
|
||||
* c2 = [5,3,1,6,2,4] 5,3,1 taken from p2 and 6,2,4 from p1
|
||||
*
|
||||
* @ingroup Variators
|
||||
*/
|
||||
template<class Chrom> class eoOrderXover: public eoQuadOp<Chrom>
|
||||
{
|
||||
public:
|
||||
/// The class name.
|
||||
virtual std::string className() const { return "eoOrderXover"; }
|
||||
|
||||
/**
|
||||
* @return true if the chromosome has changed
|
||||
* @param _chrom1 The first chromosome which will be crossed with chrom2.
|
||||
* @param _chrom2 The second chromosome which will be crossed with chrom1.
|
||||
*/
|
||||
bool operator()(Chrom& _chrom1, Chrom& _chrom2){
|
||||
|
||||
char direction=eo::rng.flip()? 1 : -1;
|
||||
unsigned cut2= 1 + eo::rng.random(_chrom1.size());
|
||||
unsigned cut1= eo::rng.random(cut2);
|
||||
Chrom tmp1= _chrom1;
|
||||
Chrom tmp2= _chrom2;
|
||||
|
||||
cross(tmp1, tmp2, _chrom1, direction, cut1, cut2);
|
||||
cross(tmp2, tmp1, _chrom2, direction, cut1, cut2);
|
||||
|
||||
_chrom1.invalidate();
|
||||
_chrom2.invalidate();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
/**
|
||||
* @param _chrom1 The first parent chromosome.
|
||||
* @param _chrom2 The second parent chromosome.
|
||||
* @param _child The result chromosome.
|
||||
* @param _direction The direction of the OrderXover (left: -1 or right: 1)
|
||||
* @param _cut1 index of the first cut
|
||||
* @param _cut2 index of the second cut
|
||||
*/
|
||||
void cross(Chrom& _chrom1, Chrom& _chrom2, Chrom& _child, char _direction, unsigned _cut1, unsigned _cut2){
|
||||
|
||||
unsigned size, id=0, from=0;
|
||||
size= _chrom1.size();
|
||||
|
||||
std::vector<bool> verif(size, false);
|
||||
|
||||
for(unsigned i= _cut1; i<_cut2; i++){
|
||||
_child[id++]= _chrom1[i];
|
||||
verif[_chrom1[i] % size] = true;
|
||||
}
|
||||
|
||||
while(_chrom2[from] != _child[_cut2 - 1])
|
||||
from++;
|
||||
|
||||
for(unsigned i=0; i<size; i++){
|
||||
unsigned j= (_direction*i + from + size) % size;
|
||||
if(!verif[_chrom2[j] % size]){
|
||||
_child[id++]=_chrom2[j];
|
||||
verif[_chrom2[j]%size]=true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
/** @example t-eoOrderXover.cpp
|
||||
*/
|
||||
|
||||
#endif
|
||||
42
trunk/eo/src/eoPSO.h
Normal file
42
trunk/eo/src/eoPSO.h
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoPSO.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _EOPSO_H
|
||||
#define _EOPSO_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoAlgo.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
This is a generic class for particle swarm 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. Only used for mono-objective cases.
|
||||
|
||||
@ingroup Algorithms
|
||||
*/
|
||||
template < class POT > class eoPSO:public eoAlgo < POT >{};
|
||||
|
||||
#endif /*_EOPSO_H*/
|
||||
82
trunk/eo/src/eoParticleBestInit.h
Normal file
82
trunk/eo/src/eoParticleBestInit.h
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoParticleBestInit.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _EOPARTICLEBESTINIT_H
|
||||
#define _EOPARTICLEBESTINIT_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoFunctor.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
@addtogroup Initializators
|
||||
@{
|
||||
*/
|
||||
|
||||
/**
|
||||
* Abstract class for particle best position initialization.
|
||||
*/
|
||||
template < class POT > class eoParticleBestInit:public eoUF < POT &, void >
|
||||
{
|
||||
public:
|
||||
|
||||
/** Apply the initialization to a whole given population */
|
||||
virtual void apply (eoPop < POT > &_pop)
|
||||
{
|
||||
for (unsigned i = 0; i < _pop.size (); i++)
|
||||
{
|
||||
this->operator ()(_pop[i]);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Initializes the best positions of a particle as its current positions and set the
|
||||
* particle best fitness.
|
||||
*/
|
||||
template < class POT > class eoFirstIsBestInit:public eoParticleBestInit <POT>
|
||||
{
|
||||
|
||||
public:
|
||||
|
||||
/** Default CTor */
|
||||
eoFirstIsBestInit (){}
|
||||
|
||||
void operator () (POT & _po1)
|
||||
{
|
||||
//Set the bestPositions
|
||||
_po1.bestPositions = _po1 ;
|
||||
|
||||
|
||||
// set the fitness
|
||||
_po1.best(_po1.fitness());
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
#endif /*_EOPARTICLEBESTINIT_H */
|
||||
|
||||
/** @} */
|
||||
155
trunk/eo/src/eoParticleFullInitializer.h
Normal file
155
trunk/eo/src/eoParticleFullInitializer.h
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoParticleFullInitializer.h
|
||||
// (c) OPAC Team, INRIA, 2007
|
||||
/*
|
||||
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: clive.canape@inria.fr
|
||||
|
||||
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef _eoParticleFullInitializer_H
|
||||
#define _eoParticleFullInitializer_H
|
||||
|
||||
#include <utils/eoRealVectorBounds.h>
|
||||
#include <eoVelocityInit.h>
|
||||
#include <eoPop.h>
|
||||
#include <eoParticleBestInit.h>
|
||||
#include <eoTopology.h>
|
||||
|
||||
/**
|
||||
@addtogroup Initializators
|
||||
@{
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
* Abstract class for initialization of algorithm PSO
|
||||
*/
|
||||
template <class POT> class eoInitializerBase : public eoFunctorBase
|
||||
{
|
||||
public :
|
||||
|
||||
virtual ~eoInitializerBase()
|
||||
{}
|
||||
|
||||
virtual void operator()()
|
||||
{};
|
||||
};
|
||||
|
||||
/**
|
||||
Base (name) class for Initialization of algorithm PSO
|
||||
|
||||
@see eoInitializerBase eoUF apply
|
||||
*/
|
||||
template <class POT> class eoParticleInitializer : public eoInitializerBase <POT>
|
||||
{
|
||||
public:
|
||||
|
||||
//! Constructor
|
||||
//! @param _proc Evaluation function
|
||||
//! @param _initVelo Initialization of the velocity
|
||||
//! @param _initBest Initialization of the best
|
||||
//! @param _topology Topology to use
|
||||
//! @param _pop Population
|
||||
eoParticleFullInitializer(
|
||||
eoUF<POT&, void>& _proc,
|
||||
eoVelocityInit < POT > &_initVelo,
|
||||
eoParticleBestInit <POT> &_initBest,
|
||||
eoTopology <POT> &_topology,
|
||||
eoPop < POT > &_pop
|
||||
) : proc(_proc), procPara(dummyEval), initVelo(_initVelo), initBest(_initBest), topology(_topology), pop(_pop) {}
|
||||
|
||||
|
||||
//! Constructor for parallel evaluation
|
||||
//! @param _proc Evaluation function
|
||||
//! @param _initVelo Initialization of the velocity
|
||||
//! @param _initBest Initialization of the best
|
||||
//! @param _topology Topology to use
|
||||
//! @param _pop Population
|
||||
eoParticleFullInitializer(
|
||||
eoPopEvalFunc <POT>& _proc,
|
||||
eoVelocityInit < POT > &_initVelo,
|
||||
eoParticleBestInit <POT> &_initBest,
|
||||
eoTopology <POT> &_topology,
|
||||
eoPop < POT > &_pop
|
||||
) : proc(dummy), procPara(_proc), initVelo(_initVelo), initBest(_initBest), topology(_topology), pop(_pop)
|
||||
{}
|
||||
|
||||
|
||||
//! Give the name of the class
|
||||
//! @return The name of the class
|
||||
virtual std::string className (void) const
|
||||
{
|
||||
return "eoInitializer";
|
||||
}
|
||||
|
||||
|
||||
|
||||
virtual void operator () ()
|
||||
{
|
||||
eoPop<POT> empty_pop;
|
||||
|
||||
// evaluates using either the "sequential" evaluator ...
|
||||
apply(proc, pop);
|
||||
|
||||
// ... or the parallel one
|
||||
procPara(empty_pop, pop);
|
||||
|
||||
// no matter what is the eval operator, initializes the velocities and the particle's best
|
||||
apply < POT > (initVelo, pop);
|
||||
apply < POT > (initBest, pop);
|
||||
|
||||
// finally setup the topology. We have now all we need to do so.
|
||||
topology.setup(pop);
|
||||
}
|
||||
|
||||
private :
|
||||
|
||||
/*
|
||||
@param proc First evaluation
|
||||
@param initVelo Initialization of the velocity
|
||||
@param initBest Initialization of the best
|
||||
|
||||
*/
|
||||
eoPop < POT > & pop;
|
||||
eoUF<POT&, void>& proc;
|
||||
eoPopEvalFunc <POT>& procPara;
|
||||
eoVelocityInit < POT > & initVelo;
|
||||
eoParticleBestInit <POT> & initBest;
|
||||
eoTopology <POT> & topology;
|
||||
class eoDummyEval : public eoPopEvalFunc<POT>
|
||||
{
|
||||
public:
|
||||
void operator()(eoPop<POT> &,eoPop<POT> &_pop)
|
||||
{}
|
||||
}
|
||||
dummyEval;
|
||||
class eoDummy : public eoUF<POT&, void>
|
||||
{
|
||||
public:
|
||||
void operator()(POT &)
|
||||
{}
|
||||
|
||||
}
|
||||
dummy;
|
||||
};
|
||||
#endif /*_eoParticleFullInitializer_H*/
|
||||
|
||||
/** @} */
|
||||
255
trunk/eo/src/eoPerf2Worth.h
Normal file
255
trunk/eo/src/eoPerf2Worth.h
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
/** -*- 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
|
||||
|
||||
@ingroup Selectors
|
||||
@ingroup Utilities
|
||||
*/
|
||||
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
|
||||
@ingroup Selectors
|
||||
@ingroup Utilities
|
||||
*/
|
||||
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
|
||||
@ingroup Selectors
|
||||
@ingroup Utilities
|
||||
*/
|
||||
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
|
||||
55
trunk/eo/src/eoPeriodicContinue.h
Normal file
55
trunk/eo/src/eoPeriodicContinue.h
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
// (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>
|
||||
|
||||
/** A continue that becomes true periodically.
|
||||
*/
|
||||
template <class EOT> class eoPeriodicContinue: public eoContinue <EOT> {
|
||||
|
||||
public:
|
||||
|
||||
/** Constructor. The period is given in parameter. */
|
||||
eoPeriodicContinue (unsigned __period, unsigned __init_counter = 0) :
|
||||
period (__period), counter (__init_counter)
|
||||
{}
|
||||
|
||||
|
||||
/** It returns 'true' only if the current number of generations modulo
|
||||
the period doen't equal to zero. */
|
||||
bool operator () (const eoPop <EOT> & /*pop*/)
|
||||
{
|
||||
return ((++ counter) % period) != 0 ;
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
|
||||
unsigned period;
|
||||
|
||||
unsigned counter;
|
||||
|
||||
};
|
||||
#endif
|
||||
14
trunk/eo/src/eoPersistent.cpp
Normal file
14
trunk/eo/src/eoPersistent.cpp
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
#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;
|
||||
}
|
||||
66
trunk/eo/src/eoPersistent.h
Normal file
66
trunk/eo/src/eoPersistent.h
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
// -*- 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
|
||||
|
||||
|
||||
#include <iostream> // std::istream, std::ostream
|
||||
#include <string> // para std::string
|
||||
|
||||
#include "eoPrintable.h"
|
||||
|
||||
/**
|
||||
@addtogroup Core
|
||||
@{
|
||||
*/
|
||||
|
||||
/**
|
||||
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
|
||||
|
||||
/** @} */
|
||||
339
trunk/eo/src/eoPop.h
Normal file
339
trunk/eo/src/eoPop.h
Normal file
|
|
@ -0,0 +1,339 @@
|
|||
// -*- 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
|
||||
*
|
||||
* @ingroup Core
|
||||
*/
|
||||
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;
|
||||
#if defined(__CUDACC__)
|
||||
typedef typename std::vector<EOT>::iterator iterator;
|
||||
typedef typename std::vector<EOT>::const_iterator const_iterator;
|
||||
#endif
|
||||
|
||||
/** 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));
|
||||
}
|
||||
};
|
||||
|
||||
/** appends random guys at end of pop.
|
||||
Can be used to initialize it pop is empty
|
||||
|
||||
@param _newPopSize 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); }
|
||||
};
|
||||
/// helper struct for comparing (EA or PSO)
|
||||
struct Cmp2
|
||||
{
|
||||
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(), Cmp2());
|
||||
}
|
||||
|
||||
/** 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 */
|
||||
#if defined(__CUDACC__)
|
||||
eoPop<EOT>::iterator it_best_element()
|
||||
{
|
||||
eoPop<EOT>:: iterator it = std::max_element(begin(), end());
|
||||
#else
|
||||
typename eoPop<EOT>::iterator it_best_element() {
|
||||
typename eoPop<EOT>::iterator it = std::max_element(begin(), end());
|
||||
#endif
|
||||
return it;
|
||||
}
|
||||
|
||||
/** returns an iterator to the best individual DOES NOT MOVE ANYBODY */
|
||||
const EOT & best_element() const
|
||||
{
|
||||
#if defined(__CUDACC__)
|
||||
eoPop<EOT>::const_iterator it = std::max_element(begin(), end());
|
||||
#else
|
||||
typename eoPop<EOT>::const_iterator it = std::max_element(begin(), end());
|
||||
#endif
|
||||
return (*it);
|
||||
}
|
||||
|
||||
/** returns a const reference to the worse individual DOES NOT MOVE ANYBODY */
|
||||
const EOT & worse_element() const
|
||||
{
|
||||
#if defined(__CUDACC__)
|
||||
eoPop<EOT>::const_iterator it = std::min_element(begin(), end());
|
||||
#else
|
||||
typename eoPop<EOT>::const_iterator it = std::min_element(begin(), end());
|
||||
#endif
|
||||
return (*it);
|
||||
}
|
||||
|
||||
/** returns an iterator to the worse individual DOES NOT MOVE ANYBODY */
|
||||
#if defined(__CUDACC__)
|
||||
eoPop<EOT>::iterator it_worse_element()
|
||||
{
|
||||
eoPop<EOT>::iterator it = std::min_element(begin(), end());
|
||||
#else
|
||||
typename eoPop<EOT>::iterator it_worse_element()
|
||||
{
|
||||
typename eoPop<EOT>::iterator it = std::min_element(begin(), end());
|
||||
#endif
|
||||
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.
|
||||
*/
|
||||
#if defined(__CUDACC__)
|
||||
eoPop<EOT>::iterator nth_element(int nth)
|
||||
{
|
||||
eoPop<EOT>::iterator it = begin() + nth;
|
||||
#else
|
||||
typename eoPop<EOT>::iterator nth_element(int nth)
|
||||
{
|
||||
typename eoPop<EOT>::iterator it = begin() + nth;
|
||||
#endif
|
||||
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();
|
||||
}
|
||||
};
|
||||
|
||||
#endif
|
||||
107
trunk/eo/src/eoPopEvalFunc.h
Normal file
107
trunk/eo/src/eoPopEvalFunc.h
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
/** -*- 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
|
||||
*
|
||||
* @ingroup Evaluation
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @ingroup Evaluation
|
||||
*/
|
||||
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)
|
||||
{
|
||||
(void)_parents;
|
||||
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
|
||||
*
|
||||
* @ingroup Evaluation
|
||||
*/
|
||||
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
|
||||
211
trunk/eo/src/eoPopulator.h
Normal file
211
trunk/eo/src/eoPopulator.h
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
// -*- 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
|
||||
@see eoOpContainer
|
||||
|
||||
@ingroup Core
|
||||
@ingroup Utilities
|
||||
*/
|
||||
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
|
||||
21
trunk/eo/src/eoPrintable.cpp
Normal file
21
trunk/eo/src/eoPrintable.cpp
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
#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;
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
62
trunk/eo/src/eoPrintable.h
Normal file
62
trunk/eo/src/eoPrintable.h
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
// -*- 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
|
||||
|
||||
/*
|
||||
This functionality was separated from eoObject, since it makes no sense to print
|
||||
some objects (for instance, a #eoFactory# or a random number generator.
|
||||
*/
|
||||
|
||||
/**
|
||||
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<<".
|
||||
|
||||
@ingroup Core
|
||||
*/
|
||||
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
|
||||
89
trunk/eo/src/eoPropGAGenOp.h
Normal file
89
trunk/eo/src/eoPropGAGenOp.h
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
// -*- 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
|
||||
*
|
||||
* @ingroup Combination
|
||||
*/
|
||||
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
|
||||
234
trunk/eo/src/eoProportionalCombinedOp.h
Normal file
234
trunk/eo/src/eoProportionalCombinedOp.h
Normal file
|
|
@ -0,0 +1,234 @@
|
|||
// -*- 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>
|
||||
#include <utils/eoLogger.h>
|
||||
|
||||
/**
|
||||
\defgroup Utilities Utilities
|
||||
|
||||
Classes that may help you write elegant code.
|
||||
*/
|
||||
|
||||
/**
|
||||
@defgroup Combination Operators combination
|
||||
|
||||
Classes that permits to combine several operators in a single one.
|
||||
|
||||
@ingroup Utilities
|
||||
@{
|
||||
*/
|
||||
|
||||
/** @name PropCombined Genetic operators
|
||||
|
||||
Combination of same-type 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( eo::log << eo::logging );
|
||||
}
|
||||
|
||||
// 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];
|
||||
eo::log << eo::logging << "In " << className() << std::endl ;
|
||||
for (i=0; i<ops.size(); i++)
|
||||
eo::log << eo::logging << ops[i]->className() << " with rate " << 100*rates[i]/total << " %" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
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"; }
|
||||
|
||||
virtual void add(eoQuadOp<EOT> & _op, const double _rate, bool _verbose)
|
||||
{
|
||||
#ifndef DEPRECATED_MESSAGES
|
||||
#pragma message "The use of the verbose parameter in eoPropCombinedQuadOp::add is deprecated and will be removed in the next release."
|
||||
eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoPropCombinedQuadOp::add is deprecated and will be removed in the next release." << std::endl;
|
||||
#endif // !DEPRECATED_MESSAGES
|
||||
|
||||
add(_op,_rate);
|
||||
}
|
||||
|
||||
// addition of a true operator
|
||||
virtual void add(eoQuadOp<EOT> & _op, const double _rate)
|
||||
{
|
||||
ops.push_back(&_op);
|
||||
rates.push_back(_rate);
|
||||
// compute the relative rates in percent - to warn the user!
|
||||
printOn( eo::log << eo::logging );
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
/** @} */
|
||||
87
trunk/eo/src/eoProportionalSelect.h
Normal file
87
trunk/eo/src/eoProportionalSelect.h
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
// -*- 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)
|
||||
|
||||
@ingroup Selectors
|
||||
*/
|
||||
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;
|
||||
};
|
||||
/** @example t-eoRoulette.cpp
|
||||
*/
|
||||
|
||||
#endif
|
||||
80
trunk/eo/src/eoRandomRealWeightUp.h
Normal file
80
trunk/eo/src/eoRandomRealWeightUp.h
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// eoRandomRealWeightUp.h
|
||||
// (c) OPAC 2007
|
||||
/*
|
||||
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: thomas.legrand@lifl.fr
|
||||
*/
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#ifndef EORANDOMREALWEIGHTUP_H
|
||||
#define EORANDOMREALWEIGHTUP_H
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
#include <eoWeightUpdater.h>
|
||||
#include <utils/eoRNG.h>
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Update an inertia weight by assigning it an (uniform) random value.
|
||||
* The weight is a basic feature to evaluate the velocity of a particle in
|
||||
* swarm optimization.
|
||||
*
|
||||
* @ingroup Variators
|
||||
*/
|
||||
class eoRandomRealWeightUp:public eoWeightUpdater<double>
|
||||
{
|
||||
public:
|
||||
|
||||
/**
|
||||
* Default constructor
|
||||
* @param _min - The minimum bound for the weight
|
||||
* @param _max - The maximum bound for the weight
|
||||
*/
|
||||
eoRandomRealWeightUp(
|
||||
double _min,
|
||||
double _max
|
||||
):min(_min),max(_max)
|
||||
{
|
||||
// consistency check
|
||||
if (min > max)
|
||||
{
|
||||
std::string s;
|
||||
s.append (" min > max in eoRandomRealWeightUp");
|
||||
throw std::runtime_error (s);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate an real random number in [min,max] and assign it to _weight
|
||||
* @param _weight - The assigned (real) weight
|
||||
*/
|
||||
void operator() (double & _weight)
|
||||
{
|
||||
_weight=rng.uniform(max-min)+min;
|
||||
}
|
||||
|
||||
|
||||
protected:
|
||||
double min,max;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif/*EORANDOMREALWEIGHTUP_H*/
|
||||
93
trunk/eo/src/eoRandomSelect.h
Normal file
93
trunk/eo/src/eoRandomSelect.h
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
// -*- 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
|
||||
*
|
||||
* @ingroup Selectors
|
||||
*/
|
||||
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)
|
||||
*
|
||||
* @ingroup Selectors
|
||||
*/
|
||||
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
|
||||
*
|
||||
* @ingroup Selectors
|
||||
*/
|
||||
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
|
||||
112
trunk/eo/src/eoRanking.h
Normal file
112
trunk/eo/src/eoRanking.h
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
/** -*- 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).
|
||||
*
|
||||
* @ingroup Selectors
|
||||
*/
|
||||
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
|
||||
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