Migration from SVN

This commit is contained in:
quemy 2012-08-30 11:30:11 +02:00
commit 8cd56f37db
338 changed files with 0 additions and 4096888 deletions

54
eo/src/CMakeLists.txt Normal file
View 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 local/${LIB} COMPONENT libraries)
FILE(GLOB HDRS *.h eo)
INSTALL(FILES ${HDRS} DESTINATION local/include${INSTALL_SUB_DIR}/eo COMPONENT headers)
INSTALL(DIRECTORY do es ga gp other utils
DESTINATION local/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
eo/src/EO.h Normal file
View 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
eo/src/PO.h Normal file
View 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
eo/src/apply.h Normal file
View 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
eo/src/do/Readme Normal file
View 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
eo/src/do/make_algo_easea.h Normal file
View 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

View 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
eo/src/do/make_checkpoint.h Normal file
View 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

View 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

View 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
eo/src/do/make_continue.h Normal file
View 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

View 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
eo/src/do/make_pop.h Normal file
View 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
eo/src/do/make_run.h Normal file
View 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
eo/src/eo Normal file
View 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
eo/src/eoAlgo.h Normal file
View 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
eo/src/eoBinaryFlight.h Normal file
View 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
eo/src/eoBitParticle.h Normal file
View 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
eo/src/eoBreed.h Normal file
View 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
eo/src/eoCellularEasyEA.h Normal file
View 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

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