* indentations + whitespace cleanup

This commit is contained in:
Caner Candan 2011-05-05 16:54:00 +02:00
commit 56c6edab04
285 changed files with 6068 additions and 6223 deletions

View file

@ -11,14 +11,15 @@ INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
SET(EO_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib) SET(EO_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib)
SET(LIBRARY_OUTPUT_PATH ${EO_LIB_OUTPUT_PATH}) SET(LIBRARY_OUTPUT_PATH ${EO_LIB_OUTPUT_PATH})
SET (EO_SOURCES eoFunctorStore.cpp SET(EO_SOURCES
eoPersistent.cpp eoFunctorStore.cpp
eoPrintable.cpp eoPersistent.cpp
eoCtrlCContinue.cpp eoPrintable.cpp
eoScalarFitnessAssembled.cpp eoCtrlCContinue.cpp
eoSIGContinue.cpp) eoScalarFitnessAssembled.cpp
eoSIGContinue.cpp
)
ADD_LIBRARY(eo STATIC ${EO_SOURCES}) ADD_LIBRARY(eo STATIC ${EO_SOURCES})
INSTALL(TARGETS eo ARCHIVE DESTINATION lib COMPONENT libraries) INSTALL(TARGETS eo ARCHIVE DESTINATION lib COMPONENT libraries)
@ -42,6 +43,6 @@ ADD_SUBDIRECTORY(ga)
ADD_SUBDIRECTORY(gp) ADD_SUBDIRECTORY(gp)
ADD_SUBDIRECTORY(other) ADD_SUBDIRECTORY(other)
ADD_SUBDIRECTORY(utils) ADD_SUBDIRECTORY(utils)
ADD_SUBDIRECTORY(pyeo)
###################################################################################### ######################################################################################

View file

@ -40,17 +40,17 @@
*/ */
/** EO is the base class for objects with a fitness. /** EO is the base class for objects with a fitness.
Those evolvable objects are the subjects of Those evolvable objects are the subjects of
evolution. EOs have only got a fitness, which at the same time needs to be 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 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 good is the object; evolution or change of these objects is left to the
genetic operators. genetic operators.
A fitness less than another means a worse fitness, in A fitness less than another means a worse fitness, in
whatever the context; thus, fitness is always maximized; although it can whatever the context; thus, fitness is always maximized; although it can
be minimized with a proper definition of the < operator. 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. 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. @ref Operators that effectively modify EO objects must invalidate them.
@ -123,23 +123,23 @@ public:
* @throw runtime_std::exception If a valid object can't be read. * @throw runtime_std::exception If a valid object can't be read.
*/ */
virtual void readFrom(std::istream& _is) { virtual void readFrom(std::istream& _is) {
// the new version of the reafFrom function. // the new version of the reafFrom function.
// It can distinguish between valid and invalid fitness values. // It can distinguish between valid and invalid fitness values.
std::string fitness_str; std::string fitness_str;
int pos = _is.tellg(); int pos = _is.tellg();
_is >> fitness_str; _is >> fitness_str;
if (fitness_str == "INVALID") if (fitness_str == "INVALID")
{ {
invalidFitness = true; invalidFitness = true;
} }
else else
{ {
invalidFitness = false; invalidFitness = false;
_is.seekg(pos); // rewind _is.seekg(pos); // rewind
_is >> repFitness; _is >> repFitness;
} }
} }
/** /**
@ -151,13 +151,13 @@ public:
// the latest version of the code. Very similar to the old code // the latest version of the code. Very similar to the old code
if (invalid()) { if (invalid()) {
_os << "INVALID "; _os << "INVALID ";
} }
else else
{ {
_os << repFitness << ' '; _os << repFitness << ' ';
} }
} }
//@} //@}
@ -171,4 +171,3 @@ private:
#endif #endif
/** @} */ /** @} */

View file

@ -1,5 +1,5 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// PO.h // PO.h
// (c) OPAC 2007 // (c) OPAC 2007
@ -43,11 +43,11 @@ template < class F > class PO:public EO < F >
public: public:
#if defined(__CUDACC__) #if defined(__CUDACC__)
typedef typename EO < F >::Fitness Fitness; typedef typename EO < F >::Fitness Fitness;
#else #else
typedef typename PO<F>::Fitness Fitness; typedef typename PO<F>::Fitness Fitness;
#endif #endif
/** Default constructor. /** Default constructor.
Fitness must have a ctor which takes 0 as a value. Best fitness mush also have the same constructor. Fitness must have a ctor which takes 0 as a value. Best fitness mush also have the same constructor.

View file

@ -9,11 +9,11 @@ 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 and in EO test dir the t-eoGA.cpp file that is a sample program that uses
the whole facility. the whole facility.
All make_XXX.h file define some parser-based constructions of basic All make_XXX.h file define some parser-based constructions of basic
Evolutionary Algorithms components, using state-based memory management Evolutionary Algorithms components, using state-based memory management
(see in src/utils dir, or read the tutorial). (see in src/utils dir, or read the tutorial).
In this src/do dir, the following ***representation indedendent*** code In this src/do dir, the following ***representation indedendent*** code
is defined is defined
make_algo_scalar.h The selection/replacement for scalar fitnesses make_algo_scalar.h The selection/replacement for scalar fitnesses
@ -23,7 +23,7 @@ make_pop.h Init of the population (from an EOT initializer)
make_run.h Run the algorithm make_run.h Run the algorithm
See also (NOW MOVED TO util DIR, as it was useful everywhere) See also (NOW MOVED TO util DIR, as it was useful everywhere)
make_help.cpp Help on demand (+ status file) make_help.cpp Help on demand (+ status file)
Note: Note:
----- -----

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// make_algo_easea.h // make_algo_easea.h
// (c) Marc Schoenauer and Pierre Collet, 2002 // (c) Marc Schoenauer and Pierre Collet, 2002
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -81,18 +81,18 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
eoParamParamType & ppSelect = selectionParam.value(); // std::pair<std::string,std::vector<std::string> > eoParamParamType & ppSelect = selectionParam.value(); // std::pair<std::string,std::vector<std::string> >
eoSelectOne<EOT>* select ; eoSelectOne<EOT>* select ;
if (ppSelect.first == std::string("DetTour")) if (ppSelect.first == std::string("DetTour"))
{ {
unsigned detSize; unsigned detSize;
if (!ppSelect.second.size()) // no parameter added if (!ppSelect.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl;
detSize = 2; detSize = 2;
// put back 2 in parameter for consistency (and status file) // put back 2 in parameter for consistency (and status file)
ppSelect.second.push_back(std::string("2")); ppSelect.second.push_back(std::string("2"));
} }
else // parameter passed by user as DetTour(T) else // parameter passed by user as DetTour(T)
detSize = atoi(ppSelect.second[0].c_str()); detSize = atoi(ppSelect.second[0].c_str());
select = new eoDetTournamentSelect<EOT>(detSize); select = new eoDetTournamentSelect<EOT>(detSize);
} }
@ -100,57 +100,57 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
{ {
double p; double p;
if (!ppSelect.second.size()) // no parameter added if (!ppSelect.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl;
p = 1; p = 1;
// put back p in parameter for consistency (and status file) // put back p in parameter for consistency (and status file)
ppSelect.second.push_back(std::string("1")); ppSelect.second.push_back(std::string("1"));
} }
else // parameter passed by user as DetTour(T) else // parameter passed by user as DetTour(T)
p = atof(ppSelect.second[0].c_str()); p = atof(ppSelect.second[0].c_str());
select = new eoStochTournamentSelect<EOT>(p); select = new eoStochTournamentSelect<EOT>(p);
} }
else if (ppSelect.first == std::string("Ranking")) else if (ppSelect.first == std::string("Ranking"))
{ {
double p,e; double p,e;
if (ppSelect.second.size()==2) // 2 parameters: pressure and exponent if (ppSelect.second.size()==2) // 2 parameters: pressure and exponent
{ {
p = atof(ppSelect.second[0].c_str()); p = atof(ppSelect.second[0].c_str());
e = atof(ppSelect.second[1].c_str()); e = atof(ppSelect.second[1].c_str());
} }
else if (ppSelect.second.size()==1) // 1 parameter: pressure else if (ppSelect.second.size()==1) // 1 parameter: pressure
{ {
std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl; std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl;
e = 1; e = 1;
ppSelect.second.push_back(std::string("1")); ppSelect.second.push_back(std::string("1"));
p = atof(ppSelect.second[0].c_str()); p = atof(ppSelect.second[0].c_str());
} }
else // no parameters ... or garbage else // no parameters ... or garbage
{ {
std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl; std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl;
p=2; p=2;
e=1; e=1;
// put back in parameter for consistency (and status file) // put back in parameter for consistency (and status file)
ppSelect.second.resize(2); // just in case ppSelect.second.resize(2); // just in case
ppSelect.second[0] = (std::string("2")); ppSelect.second[0] = (std::string("2"));
ppSelect.second[1] = (std::string("1")); ppSelect.second[1] = (std::string("1"));
} }
// check for authorized values // check for authorized values
// pressure in (0,1] // pressure in (0,1]
if ( (p<=1) || (p>2) ) if ( (p<=1) || (p>2) )
{ {
std::cerr << "WARNING, selective pressure must be in (1,2] in Ranking, using 2\n"; std::cerr << "WARNING, selective pressure must be in (1,2] in Ranking, using 2\n";
p=2; p=2;
ppSelect.second[0] = (std::string("2")); ppSelect.second[0] = (std::string("2"));
} }
// exponent >0 // exponent >0
if (e<=0) if (e<=0)
{ {
std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n"; std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n";
e=1; e=1;
ppSelect.second[1] = (std::string("1")); ppSelect.second[1] = (std::string("1"));
} }
// now we're OK // now we're OK
eoPerf2Worth<EOT> & p2w = _state.storeFunctor( new eoRanking<EOT>(p,e) ); eoPerf2Worth<EOT> & p2w = _state.storeFunctor( new eoRanking<EOT>(p,e) );
select = new eoRouletteWorthSelect<EOT>(p2w); select = new eoRouletteWorthSelect<EOT>(p2w);
@ -159,13 +159,13 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
{ {
bool b; bool b;
if (ppSelect.second.size() == 0) // no argument -> default = ordered if (ppSelect.second.size() == 0) // no argument -> default = ordered
{ {
b=true; b=true;
// put back in parameter for consistency (and status file) // put back in parameter for consistency (and status file)
ppSelect.second.push_back(std::string("ordered")); ppSelect.second.push_back(std::string("ordered"));
} }
else else
b = !(ppSelect.second[0] == std::string("unordered")); b = !(ppSelect.second[0] == std::string("unordered"));
select = new eoSequentialSelect<EOT>(b); select = new eoSequentialSelect<EOT>(b);
} }
else if (ppSelect.first == std::string("EliteSequential")) // Best first, one after the other in random order afterwards else if (ppSelect.first == std::string("EliteSequential")) // Best first, one after the other in random order afterwards
@ -188,7 +188,7 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
_state.storeFunctor(select); _state.storeFunctor(select);
// the number of offspring // the number of offspring
eoValueParam<eoHowMany>& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine"); eoValueParam<eoHowMany>& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine");
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
@ -196,7 +196,7 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
/** Replacement type - high level: predefined replacements /** Replacement type - high level: predefined replacements
* ESComma : * ESComma :
* elite = 0 * elite = 0
* surviveParents=0 (no reduce) * surviveParents=0 (no reduce)
* surviveOffspring=100% (no reduce) * surviveOffspring=100% (no reduce)
@ -208,8 +208,8 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
* GGA : generational GA - idem ESComma except for * GGA : generational GA - idem ESComma except for
* offspringRate = 100% * offspringRate = 100%
* all reducers are unused * all reducers are unused
* *
* SSGA(T/t) : Steady-State GA * SSGA(T/t) : Steady-State GA
* surviveParents = 1.0 - offspringRate * surviveParents = 1.0 - offspringRate
* reduceFinal = DetTour(T>1) ou StochTour(0.5<t<1) * reduceFinal = DetTour(T>1) ou StochTour(0.5<t<1)
* *
@ -246,28 +246,28 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
// the tournament size // the tournament size
if (!replacementParam.second.size()) // no parameter added if (!replacementParam.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to MGG replacement, using 2" << std::endl; std::cerr << "WARNING, no parameter passed to MGG replacement, using 2" << std::endl;
tSize = 2; tSize = 2;
// put back 2 in parameter for consistency (and status file) // put back 2 in parameter for consistency (and status file)
replacementParam.second.push_back(std::string("2")); replacementParam.second.push_back(std::string("2"));
} }
else else
{ {
t = atof(replacementParam.second[0].c_str()); t = atof(replacementParam.second[0].c_str());
if (t>=2) if (t>=2)
{ // build the appropriate deafult value { // build the appropriate deafult value
tSize = unsigned(t); tSize = unsigned(t);
} }
else else
{ {
throw std::runtime_error("Sorry, only deterministic tournament available at the moment"); throw std::runtime_error("Sorry, only deterministic tournament available at the moment");
} }
} }
ptReplace = new eoMGGReplacement<EOT>(-surviveParents, tSize); ptReplace = new eoMGGReplacement<EOT>(-surviveParents, tSize);
_state.storeFunctor(ptReplace); _state.storeFunctor(ptReplace);
} }
else { // until the end of what was the only loop/switch else { // until the end of what was the only loop/switch
// the default deafult values // the default deafult values
eoHowMany elite (0.0); eoHowMany elite (0.0);
bool strongElitism (false); bool strongElitism (false);
@ -283,12 +283,12 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
// ---------- General // ---------- General
if (replacementParam.first == std::string("General")) if (replacementParam.first == std::string("General"))
{ {
; // defaults OK ; // defaults OK
} }
// ---------- ESComma // ---------- ESComma
else if (replacementParam.first == std::string("ESComma")) else if (replacementParam.first == std::string("ESComma"))
{ {
; // OK too ; // OK too
} }
// ---------- ESPlus // ---------- ESPlus
else if (replacementParam.first == std::string("ESPlus")) else if (replacementParam.first == std::string("ESPlus"))
@ -298,16 +298,16 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
// ---------- Generational // ---------- Generational
else if (replacementParam.first == std::string("Generational")) else if (replacementParam.first == std::string("Generational"))
{ {
; // OK too (we should check nb of offspring) ; // OK too (we should check nb of offspring)
} }
// ---------- EP // ---------- EP
else if (replacementParam.first == std::string("EP")) else if (replacementParam.first == std::string("EP"))
{ {
if (!replacementParam.second.size()) // no parameter added if (!replacementParam.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to EP replacement, using 6" << std::endl; std::cerr << "WARNING, no parameter passed to EP replacement, using 6" << std::endl;
// put back 6 in parameter for consistency (and status file) // put back 6 in parameter for consistency (and status file)
replacementParam.second.push_back(std::string("6")); replacementParam.second.push_back(std::string("6"));
} }
// by coincidence, the syntax for the EP reducer is the same than here: // by coincidence, the syntax for the EP reducer is the same than here:
reduceFinalType = replacementParam; reduceFinalType = replacementParam;
@ -318,28 +318,28 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
{ {
if (!replacementParam.second.size()) // no parameter added if (!replacementParam.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to SSGA replacement, using 2" << std::endl; std::cerr << "WARNING, no parameter passed to SSGA replacement, using 2" << std::endl;
// put back 2 in parameter for consistency (and status file) // put back 2 in parameter for consistency (and status file)
replacementParam.second.push_back(std::string("2")); replacementParam.second.push_back(std::string("2"));
reduceParentType = eoParamParamType(std::string("DetTour(2)")); reduceParentType = eoParamParamType(std::string("DetTour(2)"));
} }
else else
{ {
t = atof(replacementParam.second[0].c_str()); t = atof(replacementParam.second[0].c_str());
if (t>=2) if (t>=2)
{ // build the appropriate deafult value { // build the appropriate deafult value
reduceParentType = eoParamParamType(std::string("DetTour(") + replacementParam.second[0].c_str() + ")"); reduceParentType = eoParamParamType(std::string("DetTour(") + replacementParam.second[0].c_str() + ")");
} }
else // check for [0.5,1] will be made in make_general_replacement else // check for [0.5,1] will be made in make_general_replacement
{ // build the appropriate deafult value { // build the appropriate deafult value
reduceParentType = eoParamParamType(std::string("StochTour(") + replacementParam.second[0].c_str() + ")"); reduceParentType = eoParamParamType(std::string("StochTour(") + replacementParam.second[0].c_str() + ")");
} }
} }
// //
surviveParents = eoHowMany(-1); surviveParents = eoHowMany(-1);
surviveOffspring = eoHowMany(1); surviveOffspring = eoHowMany(1);
} }
else // no replacement recognized else // no replacement recognized
{ {
throw std::runtime_error("Invalid replacement type " + replacementParam.first); throw std::runtime_error("Invalid replacement type " + replacementParam.first);
} }
@ -353,7 +353,7 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
/////////////////////////////// ///////////////////////////////
// the general breeder // the general breeder
/////////////////////////////// ///////////////////////////////
eoGeneralBreeder<EOT> *breed = eoGeneralBreeder<EOT> *breed =
new eoGeneralBreeder<EOT>(*select, _op, offspringRateParam.value()); new eoGeneralBreeder<EOT>(*select, _op, offspringRateParam.value());
_state.storeFunctor(breed); _state.storeFunctor(breed);
@ -381,7 +381,7 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
template <class EOT> template <class EOT>
eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc<EOT>& _eval, eoContinue<EOT>& _continue, eoGenOp<EOT>& _op) 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); do_make_algo_scalar( _parser, _state, *(new eoPopLoopEval<EOT>(_eval)), _continue, _op);
} }

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// make_algo_scalar.h // make_algo_scalar.h
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -84,42 +84,42 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
if (_dist == NULL) if (_dist == NULL)
comment = "Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e) or Sequential(ordered/unordered)"; comment = "Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e) or Sequential(ordered/unordered)";
else else
comment = "Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e), Sharing(sigma_share) or Sequential(ordered/unordered)"; 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"); 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> > eoParamParamType & ppSelect = selectionParam.value(); // std::pair<std::string,std::vector<std::string> >
eoSelectOne<EOT>* select ; eoSelectOne<EOT>* select ;
if (ppSelect.first == std::string("DetTour")) if (ppSelect.first == std::string("DetTour"))
{ {
unsigned detSize; unsigned detSize;
if (!ppSelect.second.size()) // no parameter added if (!ppSelect.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl;
detSize = 2; detSize = 2;
// put back 2 in parameter for consistency (and status file) // put back 2 in parameter for consistency (and status file)
ppSelect.second.push_back(std::string("2")); ppSelect.second.push_back(std::string("2"));
} }
else // parameter passed by user as DetTour(T) else // parameter passed by user as DetTour(T)
detSize = atoi(ppSelect.second[0].c_str()); detSize = atoi(ppSelect.second[0].c_str());
select = new eoDetTournamentSelect<EOT>(detSize); select = new eoDetTournamentSelect<EOT>(detSize);
} }
else if (ppSelect.first == std::string("Sharing")) else if (ppSelect.first == std::string("Sharing"))
{ {
double nicheSize; double nicheSize;
if (!ppSelect.second.size()) // no parameter added if (!ppSelect.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to Sharing, using 0.5" << std::endl; std::cerr << "WARNING, no parameter passed to Sharing, using 0.5" << std::endl;
nicheSize = 0.5; nicheSize = 0.5;
// put back 2 in parameter for consistency (and status file) // put back 2 in parameter for consistency (and status file)
ppSelect.second.push_back(std::string("0.5")); ppSelect.second.push_back(std::string("0.5"));
} }
else // parameter passed by user as DetTour(T) else // parameter passed by user as DetTour(T)
nicheSize = atof(ppSelect.second[0].c_str()); nicheSize = atof(ppSelect.second[0].c_str());
if (_dist == NULL) // no distance if (_dist == NULL) // no distance
throw std::runtime_error("You didn't specify a distance when calling make_algo_scalar and using sharing"); throw std::runtime_error("You didn't specify a distance when calling make_algo_scalar and using sharing");
select = new eoSharingSelect<EOT>(nicheSize, *_dist); select = new eoSharingSelect<EOT>(nicheSize, *_dist);
} }
@ -127,57 +127,57 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
{ {
double p; double p;
if (!ppSelect.second.size()) // no parameter added if (!ppSelect.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl;
p = 1; p = 1;
// put back p in parameter for consistency (and status file) // put back p in parameter for consistency (and status file)
ppSelect.second.push_back(std::string("1")); ppSelect.second.push_back(std::string("1"));
} }
else // parameter passed by user as DetTour(T) else // parameter passed by user as DetTour(T)
p = atof(ppSelect.second[0].c_str()); p = atof(ppSelect.second[0].c_str());
select = new eoStochTournamentSelect<EOT>(p); select = new eoStochTournamentSelect<EOT>(p);
} }
else if (ppSelect.first == std::string("Ranking")) else if (ppSelect.first == std::string("Ranking"))
{ {
double p,e; double p,e;
if (ppSelect.second.size()==2) // 2 parameters: pressure and exponent if (ppSelect.second.size()==2) // 2 parameters: pressure and exponent
{ {
p = atof(ppSelect.second[0].c_str()); p = atof(ppSelect.second[0].c_str());
e = atof(ppSelect.second[1].c_str()); e = atof(ppSelect.second[1].c_str());
} }
else if (ppSelect.second.size()==1) // 1 parameter: pressure else if (ppSelect.second.size()==1) // 1 parameter: pressure
{ {
std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl; std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl;
e = 1; e = 1;
ppSelect.second.push_back(std::string("1")); ppSelect.second.push_back(std::string("1"));
p = atof(ppSelect.second[0].c_str()); p = atof(ppSelect.second[0].c_str());
} }
else // no parameters ... or garbage else // no parameters ... or garbage
{ {
std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl; std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl;
p=2; p=2;
e=1; e=1;
// put back in parameter for consistency (and status file) // put back in parameter for consistency (and status file)
ppSelect.second.resize(2); // just in case ppSelect.second.resize(2); // just in case
ppSelect.second[0] = (std::string("2")); ppSelect.second[0] = (std::string("2"));
ppSelect.second[1] = (std::string("1")); ppSelect.second[1] = (std::string("1"));
} }
// check for authorized values // check for authorized values
// pressure in (0,1] // pressure in (0,1]
if ( (p<=1) || (p>2) ) if ( (p<=1) || (p>2) )
{ {
std::cerr << "WARNING, selective pressure must be in (0,1] in Ranking, using 2\n"; std::cerr << "WARNING, selective pressure must be in (0,1] in Ranking, using 2\n";
p=2; p=2;
ppSelect.second[0] = (std::string("2")); ppSelect.second[0] = (std::string("2"));
} }
// exponent >0 // exponent >0
if (e<=0) if (e<=0)
{ {
std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n"; std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n";
e=1; e=1;
ppSelect.second[1] = (std::string("1")); ppSelect.second[1] = (std::string("1"));
} }
// now we're OK // now we're OK
eoPerf2Worth<EOT> & p2w = _state.storeFunctor( new eoRanking<EOT>(p,e) ); eoPerf2Worth<EOT> & p2w = _state.storeFunctor( new eoRanking<EOT>(p,e) );
select = new eoRouletteWorthSelect<EOT>(p2w); select = new eoRouletteWorthSelect<EOT>(p2w);
@ -186,13 +186,13 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
{ {
bool b; bool b;
if (ppSelect.second.size() == 0) // no argument -> default = ordered if (ppSelect.second.size() == 0) // no argument -> default = ordered
{ {
b=true; b=true;
// put back in parameter for consistency (and status file) // put back in parameter for consistency (and status file)
ppSelect.second.push_back(std::string("ordered")); ppSelect.second.push_back(std::string("ordered"));
} }
else else
b = !(ppSelect.second[0] == std::string("unordered")); b = !(ppSelect.second[0] == std::string("unordered"));
select = new eoSequentialSelect<EOT>(b); select = new eoSequentialSelect<EOT>(b);
} }
else if (ppSelect.first == std::string("Roulette")) // no argument (yet) else if (ppSelect.first == std::string("Roulette")) // no argument (yet)
@ -211,7 +211,7 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
_state.storeFunctor(select); _state.storeFunctor(select);
// the number of offspring // the number of offspring
eoValueParam<eoHowMany>& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine"); eoValueParam<eoHowMany>& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine");
// the replacement // the replacement
@ -231,16 +231,16 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
else if (ppReplace.first == std::string("EPTour")) else if (ppReplace.first == std::string("EPTour"))
{ {
unsigned detSize; unsigned detSize;
if (!ppReplace.second.size()) // no parameter added if (!ppReplace.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to EPTour, using 6" << std::endl; std::cerr << "WARNING, no parameter passed to EPTour, using 6" << std::endl;
detSize = 6; detSize = 6;
// put back in parameter for consistency (and status file) // put back in parameter for consistency (and status file)
ppReplace.second.push_back(std::string("6")); ppReplace.second.push_back(std::string("6"));
} }
else // parameter passed by user as EPTour(T) else // parameter passed by user as EPTour(T)
detSize = atoi(ppSelect.second[0].c_str()); detSize = atoi(ppSelect.second[0].c_str());
replace = new eoEPReplacement<EOT>(detSize); replace = new eoEPReplacement<EOT>(detSize);
} }
@ -251,32 +251,32 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
else if (ppReplace.first == std::string("SSGADet")) else if (ppReplace.first == std::string("SSGADet"))
{ {
unsigned detSize; unsigned detSize;
if (!ppReplace.second.size()) // no parameter added if (!ppReplace.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to SSGADet, using 2" << std::endl; std::cerr << "WARNING, no parameter passed to SSGADet, using 2" << std::endl;
detSize = 2; detSize = 2;
// put back in parameter for consistency (and status file) // put back in parameter for consistency (and status file)
ppReplace.second.push_back(std::string("2")); ppReplace.second.push_back(std::string("2"));
} }
else // parameter passed by user as SSGADet(T) else // parameter passed by user as SSGADet(T)
detSize = atoi(ppSelect.second[0].c_str()); detSize = atoi(ppSelect.second[0].c_str());
replace = new eoSSGADetTournamentReplacement<EOT>(detSize); replace = new eoSSGADetTournamentReplacement<EOT>(detSize);
} }
else if (ppReplace.first == std::string("SSGAStoch")) else if (ppReplace.first == std::string("SSGAStoch"))
{ {
double p; double p;
if (!ppReplace.second.size()) // no parameter added if (!ppReplace.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to SSGAStoch, using 1" << std::endl; std::cerr << "WARNING, no parameter passed to SSGAStoch, using 1" << std::endl;
p = 1; p = 1;
// put back in parameter for consistency (and status file) // put back in parameter for consistency (and status file)
ppReplace.second.push_back(std::string("1")); ppReplace.second.push_back(std::string("1"));
} }
else // parameter passed by user as SSGADet(T) else // parameter passed by user as SSGADet(T)
p = atof(ppSelect.second[0].c_str()); p = atof(ppSelect.second[0].c_str());
replace = new eoSSGAStochTournamentReplacement<EOT>(p); replace = new eoSSGAStochTournamentReplacement<EOT>(p);
} }
else else
@ -294,10 +294,10 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
eoReplacement<EOT> *replaceTmp = replace; eoReplacement<EOT> *replaceTmp = replace;
replace = new eoWeakElitistReplacement<EOT>(*replaceTmp); replace = new eoWeakElitistReplacement<EOT>(*replaceTmp);
_state.storeFunctor(replace); _state.storeFunctor(replace);
} }
// the general breeder // the general breeder
eoGeneralBreeder<EOT> *breed = eoGeneralBreeder<EOT> *breed =
new eoGeneralBreeder<EOT>(*select, _op, offspringRateParam.value()); new eoGeneralBreeder<EOT>(*select, _op, offspringRateParam.value());
_state.storeFunctor(breed); _state.storeFunctor(breed);

View file

@ -129,7 +129,7 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
eoValueParam<bool>& eraseParam = _parser.createParam(true, "eraseDir", "erase files in dirName if any", '\0', "Output - Disk"); eoValueParam<bool>& eraseParam = _parser.createParam(true, "eraseDir", "erase files in dirName if any", '\0', "Output - Disk");
bool dirOK = false; // not tested yet bool dirOK = false; // not tested yet
@ -179,15 +179,15 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
{ {
bestStat = new eoBestFitnessStat<EOT>; bestStat = new eoBestFitnessStat<EOT>;
// store it // store it
_state.storeFunctor(bestStat); _state.storeFunctor(bestStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*bestStat); checkpoint->add(*bestStat);
} }
@ -203,15 +203,15 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
{ {
averageStat = new eoAverageStat<EOT>; averageStat = new eoAverageStat<EOT>;
// store it // store it
_state.storeFunctor(averageStat); _state.storeFunctor(averageStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*averageStat); checkpoint->add(*averageStat);
} }
@ -223,19 +223,19 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
eoSecondMomentStats<EOT> *secondStat = NULL; eoSecondMomentStats<EOT> *secondStat = NULL;
if ( printBestParam.value() || fileBestParam.value() ) // we need it for screen output or file output if ( printBestParam.value() || fileBestParam.value() ) // we need it for screen output or file output
{ {
secondStat = new eoSecondMomentStats<EOT>; secondStat = new eoSecondMomentStats<EOT>;
// store it // store it
_state.storeFunctor(secondStat); _state.storeFunctor(secondStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*secondStat); checkpoint->add(*secondStat);
} }
@ -255,15 +255,15 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
{ {
popStat = new eoSortedPopStat<EOT>; popStat = new eoSortedPopStat<EOT>;
// store it // store it
_state.storeFunctor(popStat); _state.storeFunctor(popStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*popStat); checkpoint->add(*popStat);
} }
@ -287,7 +287,7 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
bool needStdoutMonitor = printBestParam.value() bool needStdoutMonitor = printBestParam.value()
|| printPopParam.value() ; || printPopParam.value() ;
@ -297,53 +297,53 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
{ {
eoStdoutMonitor *monitor = new eoStdoutMonitor(false); eoStdoutMonitor *monitor = new eoStdoutMonitor(false);
_state.storeFunctor(monitor); _state.storeFunctor(monitor);
// when called by the checkpoint (i.e. at every generation) // when called by the checkpoint (i.e. at every generation)
checkpoint->add(*monitor); checkpoint->add(*monitor);
// the monitor will output a series of parameters: add them // the monitor will output a series of parameters: add them
monitor->add(*generationCounter); monitor->add(*generationCounter);
if (useEvalParam.value()) // we want nb of evaluations if (useEvalParam.value()) // we want nb of evaluations
monitor->add(_eval); monitor->add(_eval);
if (useTimeParam.value()) // we want time if (useTimeParam.value()) // we want time
{ {
tCounter = new eoTimeCounter; tCounter = new eoTimeCounter;
_state.storeFunctor(tCounter); _state.storeFunctor(tCounter);
checkpoint->add(*tCounter); checkpoint->add(*tCounter);
monitor->add(*tCounter); monitor->add(*tCounter);
} }
if (printBestParam.value()) if (printBestParam.value())
{ {
monitor->add(*bestStat); monitor->add(*bestStat);
monitor->add(*secondStat); monitor->add(*secondStat);
} }
if ( printPopParam.value()) if ( printPopParam.value())
monitor->add(*popStat); monitor->add(*popStat);
} }
@ -353,9 +353,9 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
if ( ( fileBestParam.value() || plotBestParam.value() || if ( ( fileBestParam.value() || plotBestParam.value() ||
plotHistogramParam.value() ) plotHistogramParam.value() )
&& !dirOK ) // just in case we add something before && !dirOK ) // just in case we add something before
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
@ -367,41 +367,41 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
#ifdef _MSVC #ifdef _MSVC
std::string stmp = dirNameParam.value() + "\best.xg"; std::string stmp = dirNameParam.value() + "\best.xg";
#else #else
std::string stmp = dirNameParam.value() + "/best.xg"; std::string stmp = dirNameParam.value() + "/best.xg";
#endif #endif
eoFileMonitor *fileMonitor = new eoFileMonitor(stmp); eoFileMonitor *fileMonitor = new eoFileMonitor(stmp);
// save and give to checkpoint // save and give to checkpoint
_state.storeFunctor(fileMonitor); _state.storeFunctor(fileMonitor);
checkpoint->add(*fileMonitor); checkpoint->add(*fileMonitor);
// and feed with some statistics // and feed with some statistics
fileMonitor->add(*generationCounter); fileMonitor->add(*generationCounter);
fileMonitor->add(_eval); fileMonitor->add(_eval);
if (tCounter) // we want the time as well if (tCounter) // we want the time as well
{ {
// std::cout << "On met timecounter\n"; // std::cout << "On met timecounter\n";
fileMonitor->add(*tCounter); fileMonitor->add(*tCounter);
} }
fileMonitor->add(*bestStat); fileMonitor->add(*bestStat);
fileMonitor->add(*secondStat); fileMonitor->add(*secondStat);
} }
@ -413,33 +413,33 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
{ {
std::string stmp = dirNameParam.value() + "/gnu_best.xg"; std::string stmp = dirNameParam.value() + "/gnu_best.xg";
eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness<EOT>()); eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness<EOT>());
// save and give to checkpoint // save and give to checkpoint
_state.storeFunctor(gnuMonitor); _state.storeFunctor(gnuMonitor);
checkpoint->add(*gnuMonitor); checkpoint->add(*gnuMonitor);
// and feed with some statistics // and feed with some statistics
if (useEvalParam.value()) // do we want eval as X coordinate if (useEvalParam.value()) // do we want eval as X coordinate
gnuMonitor->add(_eval); gnuMonitor->add(_eval);
else if (tCounter) // or time? else if (tCounter) // or time?
gnuMonitor->add(*tCounter); gnuMonitor->add(*tCounter);
else // default: generation else // default: generation
gnuMonitor->add(*generationCounter); gnuMonitor->add(*generationCounter);
gnuMonitor->add(*bestStat); gnuMonitor->add(*bestStat);
gnuMonitor->add(*averageStat); gnuMonitor->add(*averageStat);
} }
@ -451,25 +451,25 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
{ {
eoScalarFitnessStat<EOT> *fitStat = new eoScalarFitnessStat<EOT>; eoScalarFitnessStat<EOT> *fitStat = new eoScalarFitnessStat<EOT>;
_state.storeFunctor(fitStat); _state.storeFunctor(fitStat);
checkpoint->add(*fitStat); checkpoint->add(*fitStat);
// a gnuplot-based monitor for snapshots: needs a dir name // a gnuplot-based monitor for snapshots: needs a dir name
eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value()); eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value());
_state.storeFunctor(fitSnapshot); _state.storeFunctor(fitSnapshot);
// add any stat that is a std::vector<double> to it // add any stat that is a std::vector<double> to it
fitSnapshot->add(*fitStat); fitSnapshot->add(*fitStat);
// and of course add it to the checkpoint // and of course add it to the checkpoint
checkpoint->add(*fitSnapshot); checkpoint->add(*fitSnapshot);
} }
@ -499,7 +499,7 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
if (! dirOK ) if (! dirOK )
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
@ -537,7 +537,7 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
if (! dirOK ) if (! dirOK )
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
@ -570,4 +570,3 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu
#endif #endif

View file

@ -70,7 +70,7 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval
eoValueParam<std::string>& dirNameParam = _parser.createParam(std::string("Res"), "resDir", "Directory to store DISK outputs", '\0', "Output - Disk"); eoValueParam<std::string>& dirNameParam = _parser.createParam(std::string("Res"), "resDir", "Directory to store DISK outputs", '\0', "Output - Disk");
// shoudl we empty it if exists // shoudl we empty it if exists
eoValueParam<bool>& eraseParam = _parser.createParam(false, "eraseDir", "erase files in dirName if any", '\0', "Output - Disk"); eoValueParam<bool>& eraseParam = _parser.createParam(false, "eraseDir", "erase files in dirName if any", '\0', "Output - Disk");
bool dirOK = false; // not tested yet bool dirOK = false; // not tested yet
///////////////////////////////////////// /////////////////////////////////////////
// now some statistics on the population: // now some statistics on the population:
@ -98,11 +98,11 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval
if ( printBestParam.value() || plotBestParam.value() || fileBestParam.value() ) if ( printBestParam.value() || plotBestParam.value() || fileBestParam.value() )
// we need the bestStat for at least one of the 3 above // we need the bestStat for at least one of the 3 above
{ {
bestStat = new eoBestFitnessStat<EOT>; bestStat = new eoBestFitnessStat<EOT>;
// store it // store it
_state.storeFunctor(bestStat); _state.storeFunctor(bestStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*bestStat); checkpoint->add(*bestStat);
} }
// Average fitness alone // Average fitness alone
@ -110,11 +110,11 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval
eoAverageStat<EOT> *averageStat = NULL; // do we need averageStat? eoAverageStat<EOT> *averageStat = NULL; // do we need averageStat?
if ( plotBestParam.value() ) // we need it for gnuplot output if ( plotBestParam.value() ) // we need it for gnuplot output
{ {
averageStat = new eoAverageStat<EOT>; averageStat = new eoAverageStat<EOT>;
// store it // store it
_state.storeFunctor(averageStat); _state.storeFunctor(averageStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*averageStat); checkpoint->add(*averageStat);
} }
// Second moment stats: average and stdev // Second moment stats: average and stdev
@ -122,11 +122,11 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval
eoSecondMomentStats<EOT> *secondStat = NULL; eoSecondMomentStats<EOT> *secondStat = NULL;
if ( printBestParam.value() ) // we need it for sreen output if ( printBestParam.value() ) // we need it for sreen output
{ {
secondStat = new eoSecondMomentStats<EOT>; secondStat = new eoSecondMomentStats<EOT>;
// store it // store it
_state.storeFunctor(secondStat); _state.storeFunctor(secondStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*secondStat); checkpoint->add(*secondStat);
} }
@ -136,11 +136,11 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval
eoValueParam<bool>& printPopParam = _parser.createParam(false, "printPop", "Print sorted pop. every gen.", '\0', "Output"); eoValueParam<bool>& printPopParam = _parser.createParam(false, "printPop", "Print sorted pop. every gen.", '\0', "Output");
if ( printPopParam.value() ) // we do want pop dump if ( printPopParam.value() ) // we do want pop dump
{ {
popStat = new eoSortedPopStat<EOT>("Dump of whole population"); popStat = new eoSortedPopStat<EOT>("Dump of whole population");
// store it // store it
_state.storeFunctor(popStat); _state.storeFunctor(popStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*popStat); checkpoint->add(*popStat);
} }
@ -152,14 +152,14 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval
eoFDCStat<EOT> *fdcStat = NULL; eoFDCStat<EOT> *fdcStat = NULL;
if ( printFDCParam.value() || plotFDCParam.value() ) // we need FDCStat if ( printFDCParam.value() || plotFDCParam.value() ) // we need FDCStat
{ {
// need first an object to compute the distances - here Hamming dist. // need first an object to compute the distances - here Hamming dist.
eoQuadDistance<EOT> *dist = new eoQuadDistance<EOT>; eoQuadDistance<EOT> *dist = new eoQuadDistance<EOT>;
_state.storeFunctor(dist); _state.storeFunctor(dist);
fdcStat = new eoFDCStat<EOT>(*dist); fdcStat = new eoFDCStat<EOT>(*dist);
// storeFunctor it // storeFunctor it
_state.storeFunctor(fdcStat); _state.storeFunctor(fdcStat);
// add it to the checkpoint // add it to the checkpoint
checkpoint->add(*fdcStat); checkpoint->add(*fdcStat);
} }
// do we wnat some histogram of fitnesses snpashots? // do we wnat some histogram of fitnesses snpashots?
@ -170,95 +170,95 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval
/////////////// ///////////////
// do we want an eoStdoutMonitor? // do we want an eoStdoutMonitor?
bool needStdoutMonitor = printBestParam.value() || printFDCParam.value() bool needStdoutMonitor = printBestParam.value() || printFDCParam.value()
|| printPopParam.value() ; || printPopParam.value() ;
// The Stdout monitor will print parameters to the screen ... // The Stdout monitor will print parameters to the screen ...
if ( needStdoutMonitor ) if ( needStdoutMonitor )
{ {
eoStdoutMonitor *monitor = new eoStdoutMonitor(false); eoStdoutMonitor *monitor = new eoStdoutMonitor(false);
_state.storeFunctor(monitor); _state.storeFunctor(monitor);
// when called by the checkpoint (i.e. at every generation) // when called by the checkpoint (i.e. at every generation)
checkpoint->add(*monitor); checkpoint->add(*monitor);
// the monitor will output a series of parameters: add them // the monitor will output a series of parameters: add them
monitor->add(*generationCounter); monitor->add(*generationCounter);
if (useEvalParam.value()) // we want nb of evaluations if (useEvalParam.value()) // we want nb of evaluations
monitor->add(_eval); monitor->add(_eval);
if (printBestParam.value()) if (printBestParam.value())
{ {
monitor->add(*bestStat); monitor->add(*bestStat);
monitor->add(*secondStat); monitor->add(*secondStat);
} }
if (printFDCParam.value()) if (printFDCParam.value())
monitor->add(*fdcStat); monitor->add(*fdcStat);
if ( printPopParam.value()) if ( printPopParam.value())
monitor->add(*popStat); monitor->add(*popStat);
} }
// first handle the dir test - if we need at least one file // first handle the dir test - if we need at least one file
if ( ( fileBestParam.value() || plotBestParam.value() || if ( ( fileBestParam.value() || plotBestParam.value() ||
plotFDCParam.value() || plotHistogramParam.value() ) plotFDCParam.value() || plotHistogramParam.value() )
&& !dirOK ) // just in case we add something before && !dirOK ) // just in case we add something before
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
if (fileBestParam.value()) // A file monitor for best & secondMoment if (fileBestParam.value()) // A file monitor for best & secondMoment
{ {
std::string stmp = dirNameParam.value() + "/best.xg"; std::string stmp = dirNameParam.value() + "/best.xg";
eoFileMonitor *fileMonitor = new eoFileMonitor(stmp); eoFileMonitor *fileMonitor = new eoFileMonitor(stmp);
// save and give to checkpoint // save and give to checkpoint
_state.storeFunctor(fileMonitor); _state.storeFunctor(fileMonitor);
checkpoint->add(*fileMonitor); checkpoint->add(*fileMonitor);
// and feed with some statistics // and feed with some statistics
fileMonitor->add(*generationCounter); fileMonitor->add(*generationCounter);
fileMonitor->add(_eval); fileMonitor->add(_eval);
fileMonitor->add(*bestStat); fileMonitor->add(*bestStat);
fileMonitor->add(*secondStat); fileMonitor->add(*secondStat);
} }
if (plotBestParam.value()) // an eoGnuplot1DMonitor for best & average if (plotBestParam.value()) // an eoGnuplot1DMonitor for best & average
{ {
std::string stmp = dirNameParam.value() + "_gnu_best.xg"; std::string stmp = dirNameParam.value() + "_gnu_best.xg";
eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness<EOT>()); eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness<EOT>());
// save and give to checkpoint // save and give to checkpoint
_state.storeFunctor(gnuMonitor); _state.storeFunctor(gnuMonitor);
checkpoint->add(*gnuMonitor); checkpoint->add(*gnuMonitor);
// and feed with some statistics // and feed with some statistics
if (useEvalParam.value()) if (useEvalParam.value())
gnuMonitor->add(_eval); gnuMonitor->add(_eval);
else else
gnuMonitor->add(*generationCounter); gnuMonitor->add(*generationCounter);
gnuMonitor->add(*bestStat); gnuMonitor->add(*bestStat);
gnuMonitor->add(*averageStat); gnuMonitor->add(*averageStat);
} }
if (plotFDCParam.value()) // a specific plot monitor for FDC if (plotFDCParam.value()) // a specific plot monitor for FDC
{ {
// first into a file (it adds everything ti itself // first into a file (it adds everything ti itself
eoFDCFileSnapshot<EOT> *fdcFileSnapshot = new eoFDCFileSnapshot<EOT>(*fdcStat, dirNameParam.value()); eoFDCFileSnapshot<EOT> *fdcFileSnapshot = new eoFDCFileSnapshot<EOT>(*fdcStat, dirNameParam.value());
_state.storeFunctor(fdcFileSnapshot); _state.storeFunctor(fdcFileSnapshot);
// then to a Gnuplot monitor // then to a Gnuplot monitor
eoGnuplot1DSnapshot *fdcGnuplot = new eoGnuplot1DSnapshot(*fdcFileSnapshot); eoGnuplot1DSnapshot *fdcGnuplot = new eoGnuplot1DSnapshot(*fdcFileSnapshot);
_state.storeFunctor(fdcGnuplot); _state.storeFunctor(fdcGnuplot);
// and of course add them to the checkPoint // and of course add them to the checkPoint
checkpoint->add(*fdcFileSnapshot); checkpoint->add(*fdcFileSnapshot);
checkpoint->add(*fdcGnuplot); checkpoint->add(*fdcGnuplot);
} }
// historgram? // historgram?
if (plotHistogramParam.value()) // want to see how the fitness is spread? if (plotHistogramParam.value()) // want to see how the fitness is spread?
{ {
eoScalarFitnessStat<EOT> *fitStat = new eoScalarFitnessStat<EOT>; eoScalarFitnessStat<EOT> *fitStat = new eoScalarFitnessStat<EOT>;
_state.storeFunctor(fitStat); _state.storeFunctor(fitStat);
checkpoint->add(*fitStat); checkpoint->add(*fitStat);
// a gnuplot-based monitor for snapshots: needs a dir name // a gnuplot-based monitor for snapshots: needs a dir name
eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value()); eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value());
_state.storeFunctor(fitSnapshot); _state.storeFunctor(fitSnapshot);
// add any stat that is a std::vector<double> to it // add any stat that is a std::vector<double> to it
fitSnapshot->add(*fitStat); fitSnapshot->add(*fitStat);
// and of course add it to the checkpoint // and of course add it to the checkpoint
checkpoint->add(*fitSnapshot); checkpoint->add(*fitSnapshot);
} }
////////////////////////////////// //////////////////////////////////
@ -273,7 +273,7 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval
{ {
// first make sure dirName is OK // first make sure dirName is OK
if (! dirOK ) if (! dirOK )
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX ); unsigned freq = (saveFrequencyParam.value()>0 ? saveFrequencyParam.value() : UINT_MAX );
std::string stmp = dirNameParam.value() + "/generations"; std::string stmp = dirNameParam.value() + "/generations";
@ -288,7 +288,7 @@ eoCheckPoint<EOT>& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval
{ {
// first make sure dirName is OK // first make sure dirName is OK
if (! dirOK ) if (! dirOK )
dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE
std::string stmp = dirNameParam.value() + "/time"; std::string stmp = dirNameParam.value() + "/time";
eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp); eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp);

View file

@ -49,7 +49,7 @@
bool testDirRes(std::string _dirName, bool _erase); bool testDirRes(std::string _dirName, bool _erase);
/////////////////// The checkpoint and other I/O ////////////// /////////////////// The checkpoint and other I/O //////////////
/** Of course, Fitness needs to be an eoScalarFitnessAssembled!!! /** Of course, Fitness needs to be an eoScalarFitnessAssembled!!!
* *
* *
* @ingroup Builders * @ingroup Builders
@ -153,7 +153,7 @@ eoCheckPoint<EOT>& do_make_checkpoint_assembled(eoParser& _parser, eoState& _sta
_state.storeFunctor(fitStat); _state.storeFunctor(fitStat);
checkpoint->add(*fitStat); checkpoint->add(*fitStat);
#ifdef HAVE_GNUPLOT #ifdef HAVE_GNUPLOT
// a gnuplot-based monitor for snapshots: needs a dir name // a gnuplot-based monitor for snapshots: needs a dir name
eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirName); eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirName);
_state.storeFunctor(fitSnapshot); _state.storeFunctor(fitSnapshot);
// add any stat that is a vector<double> to it // add any stat that is a vector<double> to it

View file

@ -55,7 +55,7 @@ It can then be instantiated, and compiled on its own for a given EOType
template <class Indi> template <class Indi>
eoCombinedContinue<Indi> * make_combinedContinue(eoCombinedContinue<Indi> *_combined, eoContinue<Indi> *_cont) eoCombinedContinue<Indi> * make_combinedContinue(eoCombinedContinue<Indi> *_combined, eoContinue<Indi> *_cont)
{ {
if (_combined) // already exists if (_combined) // already exists
_combined->add(*_cont); _combined->add(*_cont);
else else
_combined = new eoCombinedContinue<Indi>(*_cont); _combined = new eoCombinedContinue<Indi>(*_cont);
@ -81,10 +81,10 @@ eoContinue<Indi> & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu
if (maxGenParam.value()) // positive: -> define and store if (maxGenParam.value()) // positive: -> define and store
{ {
eoGenContinue<Indi> *genCont = new eoGenContinue<Indi>(maxGenParam.value()); eoGenContinue<Indi> *genCont = new eoGenContinue<Indi>(maxGenParam.value());
_state.storeFunctor(genCont); _state.storeFunctor(genCont);
// and "add" to combined // and "add" to combined
continuator = make_combinedContinue<Indi>(continuator, genCont); continuator = make_combinedContinue<Indi>(continuator, genCont);
} }
// the steadyGen continue - only if user imput // the steadyGen continue - only if user imput
@ -92,12 +92,12 @@ eoContinue<Indi> & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu
eoValueParam<unsigned>& minGenParam = _parser.createParam(unsigned(0), "minGen", "Minimum number of generations",'g', "Stopping criterion"); eoValueParam<unsigned>& minGenParam = _parser.createParam(unsigned(0), "minGen", "Minimum number of generations",'g', "Stopping criterion");
if (_parser.isItThere(steadyGenParam)) if (_parser.isItThere(steadyGenParam))
{ {
eoSteadyFitContinue<Indi> *steadyCont = new eoSteadyFitContinue<Indi> eoSteadyFitContinue<Indi> *steadyCont = new eoSteadyFitContinue<Indi>
(minGenParam.value(), steadyGenParam.value()); (minGenParam.value(), steadyGenParam.value());
// store // store
_state.storeFunctor(steadyCont); _state.storeFunctor(steadyCont);
// add to combinedContinue // add to combinedContinue
continuator = make_combinedContinue<Indi>(continuator, steadyCont); continuator = make_combinedContinue<Indi>(continuator, steadyCont);
} }
// Same thing with Eval - but here default value is 0 // Same thing with Eval - but here default value is 0
@ -108,10 +108,10 @@ eoContinue<Indi> & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu
if (maxEvalParam.value()) // positive: -> define and store if (maxEvalParam.value()) // positive: -> define and store
{ {
eoEvalContinue<Indi> *evalCont = new eoEvalContinue<Indi>(_eval, maxEvalParam.value()); eoEvalContinue<Indi> *evalCont = new eoEvalContinue<Indi>(_eval, maxEvalParam.value());
_state.storeFunctor(evalCont); _state.storeFunctor(evalCont);
// and "add" to combined // and "add" to combined
continuator = make_combinedContinue<Indi>(continuator, evalCont); continuator = make_combinedContinue<Indi>(continuator, evalCont);
} }
/* /*
// the steadyEval continue - only if user imput // the steadyEval continue - only if user imput
@ -119,12 +119,12 @@ eoContinue<Indi> & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu
eoValueParam<unsigned>& minGenParam = _parser.createParam(unsigned(0), "minGen", "Minimum number of generations",'g', "Stopping criterion"); eoValueParam<unsigned>& minGenParam = _parser.createParam(unsigned(0), "minGen", "Minimum number of generations",'g', "Stopping criterion");
if (_parser.isItThere(steadyGenParam)) if (_parser.isItThere(steadyGenParam))
{ {
eoSteadyGenContinue<Indi> *steadyCont = new eoSteadyFitContinue<Indi> eoSteadyGenContinue<Indi> *steadyCont = new eoSteadyFitContinue<Indi>
(minGenParam.value(), steadyGenParam.value()); (minGenParam.value(), steadyGenParam.value());
// store // store
_state.storeFunctor(steadyCont); _state.storeFunctor(steadyCont);
// add to combinedContinue // add to combinedContinue
continuator = make_combinedContinue<Indi>(continuator, steadyCont); continuator = make_combinedContinue<Indi>(continuator, steadyCont);
} }
*/ */
// the target fitness // the target fitness
@ -132,12 +132,12 @@ eoContinue<Indi> & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu
eoValueParam<double>& targetFitnessParam = _parser.createParam(double(0.0), "targetFitness", "Stop when fitness reaches",'T', "Stopping criterion"); eoValueParam<double>& targetFitnessParam = _parser.createParam(double(0.0), "targetFitness", "Stop when fitness reaches",'T', "Stopping criterion");
if (_parser.isItThere(targetFitnessParam)) if (_parser.isItThere(targetFitnessParam))
{ {
fitCont = new eoFitContinue<Indi> fitCont = new eoFitContinue<Indi>
(targetFitnessParam.value()); (targetFitnessParam.value());
// store // store
_state.storeFunctor(fitCont); _state.storeFunctor(fitCont);
// add to combinedContinue // add to combinedContinue
continuator = make_combinedContinue<Indi>(continuator, fitCont); continuator = make_combinedContinue<Indi>(continuator, fitCont);
} }
#ifndef _MSC_VER #ifndef _MSC_VER
@ -146,11 +146,11 @@ eoContinue<Indi> & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu
eoValueParam<bool>& ctrlCParam = _parser.createParam(false, "CtrlC", "Terminate current generation upon Ctrl C",'C', "Stopping criterion"); eoValueParam<bool>& ctrlCParam = _parser.createParam(false, "CtrlC", "Terminate current generation upon Ctrl C",'C', "Stopping criterion");
if (ctrlCParam.value()) if (ctrlCParam.value())
{ {
ctrlCCont = new eoCtrlCContinue<Indi>; ctrlCCont = new eoCtrlCContinue<Indi>;
// store // store
_state.storeFunctor(ctrlCCont); _state.storeFunctor(ctrlCCont);
// add to combinedContinue // add to combinedContinue
continuator = make_combinedContinue<Indi>(continuator, ctrlCCont); continuator = make_combinedContinue<Indi>(continuator, ctrlCCont);
} }
#endif #endif

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// make_general_replacement.h // make_general_replacement.h
// (c) Marc Schoenauer and Pierre Collet, 2002 // (c) Marc Schoenauer and Pierre Collet, 2002
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -49,8 +49,8 @@ eoReduce<EOT> & decode_reduce(eoParamParamType & _ppReduce, eoState & _state)
eoReduce<EOT> * ptReduce; eoReduce<EOT> * ptReduce;
// ---------- Deterministic // ---------- Deterministic
if ( (_ppReduce.first == std::string("Deterministic")) || if ( (_ppReduce.first == std::string("Deterministic")) ||
(_ppReduce.first == std::string("Sequential")) (_ppReduce.first == std::string("Sequential"))
) )
{ {
ptReduce = new eoTruncate<EOT>; ptReduce = new eoTruncate<EOT>;
@ -65,7 +65,7 @@ eoReduce<EOT> & decode_reduce(eoParamParamType & _ppReduce, eoState & _state)
// put back 6 in parameter for consistency (and status file) // put back 6 in parameter for consistency (and status file)
_ppReduce.second.push_back(std::string("6")); _ppReduce.second.push_back(std::string("6"));
} }
else // parameter passed by user as EP(T) else // parameter passed by user as EP(T)
detSize = atoi(_ppReduce.second[0].c_str()); detSize = atoi(_ppReduce.second[0].c_str());
ptReduce = new eoEPReduce<EOT>(detSize); ptReduce = new eoEPReduce<EOT>(detSize);
} }
@ -74,12 +74,12 @@ eoReduce<EOT> & decode_reduce(eoParamParamType & _ppReduce, eoState & _state)
{ {
if (!_ppReduce.second.size()) // no parameter added if (!_ppReduce.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl;
detSize = 2; detSize = 2;
// put back 2 in parameter for consistency (and status file) // put back 2 in parameter for consistency (and status file)
_ppReduce.second.push_back(std::string("2")); _ppReduce.second.push_back(std::string("2"));
} }
else // parameter passed by user as DetTour(T) else // parameter passed by user as DetTour(T)
detSize = atoi(_ppReduce.second[0].c_str()); detSize = atoi(_ppReduce.second[0].c_str());
ptReduce = new eoDetTournamentTruncate<EOT>(detSize); ptReduce = new eoDetTournamentTruncate<EOT>(detSize);
} }
@ -87,24 +87,24 @@ eoReduce<EOT> & decode_reduce(eoParamParamType & _ppReduce, eoState & _state)
{ {
double p; double p;
if (!_ppReduce.second.size()) // no parameter added if (!_ppReduce.second.size()) // no parameter added
{ {
std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl;
p = 1; p = 1;
// put back p in parameter for consistency (and status file) // put back p in parameter for consistency (and status file)
_ppReduce.second.push_back(std::string("1")); _ppReduce.second.push_back(std::string("1"));
} }
else // parameter passed by user as DetTour(T) else // parameter passed by user as DetTour(T)
{ {
p = atof(_ppReduce.second[0].c_str()); p = atof(_ppReduce.second[0].c_str());
if ( (p<=0.5) || (p>1) ) if ( (p<=0.5) || (p>1) )
throw std::runtime_error("Stochastic tournament size should be in [0.5,1]"); throw std::runtime_error("Stochastic tournament size should be in [0.5,1]");
} }
ptReduce = new eoStochTournamentTruncate<EOT>(p); ptReduce = new eoStochTournamentTruncate<EOT>(p);
} }
else if ( (_ppReduce.first == std::string("Uniform")) || else if ( (_ppReduce.first == std::string("Uniform")) ||
(_ppReduce.first == std::string("Random")) (_ppReduce.first == std::string("Random"))
) )
{ {
ptReduce = new eoRandomReduce<EOT>; ptReduce = new eoRandomReduce<EOT>;
} }
@ -117,10 +117,10 @@ eoReduce<EOT> & decode_reduce(eoParamParamType & _ppReduce, eoState & _state)
return (*ptReduce); return (*ptReduce);
} }
/** Helper function that creates a replacement from the class /** Helper function that creates a replacement from the class
* eoReduceMergeReduce using 6 parameters * eoReduceMergeReduce using 6 parameters
* (after the usual eoState and eoParser) * (after the usual eoState and eoParser)
* *
* eoHowMany _elite the number of elite parents (0 = no elitism) * eoHowMany _elite the number of elite parents (0 = no elitism)
* see below * see below
* bool _strongElitism if elite > 0, std::string elitism or weak elitism * bool _strongElitism if elite > 0, std::string elitism or weak elitism
@ -136,15 +136,15 @@ eoReduce<EOT> & decode_reduce(eoParamParamType & _ppReduce, eoState & _state)
*/ */
template <class EOT> template <class EOT>
eoReplacement<EOT> & make_general_replacement( eoReplacement<EOT> & make_general_replacement(
eoParser& _parser, eoState& _state, eoParser& _parser, eoState& _state,
eoHowMany _elite = eoHowMany(0), eoHowMany _elite = eoHowMany(0),
bool _strongElitism = false, bool _strongElitism = false,
eoHowMany _surviveParents = eoHowMany(0.0), eoHowMany _surviveParents = eoHowMany(0.0),
eoParamParamType & _reduceParentType = eoParamParamType("Deterministic"), eoParamParamType & _reduceParentType = eoParamParamType("Deterministic"),
eoHowMany _surviveOffspring = eoHowMany(1.0), eoHowMany _surviveOffspring = eoHowMany(1.0),
eoParamParamType & _reduceOffspringType = eoParamParamType("Deterministic"), eoParamParamType & _reduceOffspringType = eoParamParamType("Deterministic"),
eoParamParamType & _reduceFinalType = eoParamParamType("Deterministic") eoParamParamType & _reduceFinalType = eoParamParamType("Deterministic")
) )
{ {
///////////////////////////////////////////////////// /////////////////////////////////////////////////////
// the replacement // the replacement
@ -157,14 +157,14 @@ eoReplacement<EOT> & make_general_replacement(
// reduce the parents // reduce the parents
eoHowMany surviveParents = _parser.createParam(_surviveParents, "surviveParents", "Nb of surviving parents (percentage or absolute)", '\0', "Evolution Engine / Replacement").value(); 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(); 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); eoReduce<EOT> & reduceParent = decode_reduce<EOT>(reduceParentType, _state);
// reduce the offspring // reduce the offspring
eoHowMany surviveOffspring = _parser.createParam(_surviveOffspring, "surviveOffspring", "Nb of surviving offspring (percentage or absolute)", '\0', "Evolution Engine / Replacement").value(); 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(); 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); eoReduce<EOT> & reduceOffspring = decode_reduce<EOT>(reduceOffspringType, _state);

View file

@ -59,7 +59,7 @@ eoPop<EOT>& do_make_pop(eoParser & _parser, eoState& _state, eoInit<EOT> & _ini
// random seed // random seed
eoValueParam<uint32_t>& seedParam = _parser.getORcreateParam(uint32_t(0), "seed", "Random number seed", 'S'); eoValueParam<uint32_t>& seedParam = _parser.getORcreateParam(uint32_t(0), "seed", "Random number seed", 'S');
if (seedParam.value() == 0) if (seedParam.value() == 0)
seedParam.value() = time(0); seedParam.value() = time(0);
eoValueParam<unsigned>& popSize = _parser.getORcreateParam(unsigned(20), "popSize", "Population Size", 'P', "Evolution Engine"); eoValueParam<unsigned>& popSize = _parser.getORcreateParam(unsigned(20), "popSize", "Population Size", 'P', "Evolution Engine");
// Either load or initialize // Either load or initialize
@ -82,17 +82,17 @@ eoPop<EOT>& do_make_pop(eoParser & _parser, eoState& _state, eoInit<EOT> & _ini
// the fitness is read in the file: // the fitness is read in the file:
// do only evaluate the pop if the fitness has changed // do only evaluate the pop if the fitness has changed
if (recomputeFitnessParam.value()) if (recomputeFitnessParam.value())
{ {
for (unsigned i=0; i<pop.size(); i++) for (unsigned i=0; i<pop.size(); i++)
pop[i].invalidate(); pop[i].invalidate();
} }
if (pop.size() < popSize.value()) 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; 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()) if (pop.size() > popSize.value())
{ {
std::cerr << "WARNING, Load file contained too many individuals. Only the best will be retained" << std::endl; std::cerr << "WARNING, Load file contained too many individuals. Only the best will be retained" << std::endl;
pop.resize(popSize.value()); pop.resize(popSize.value());
} }
} }
else // nothing loaded from a file else // nothing loaded from a file
{ {

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// make_run.h // make_run.h
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either

View file

@ -8,16 +8,16 @@
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: cahon@lifl.fr Contact: cahon@lifl.fr
*/ */
@ -32,26 +32,26 @@
#include <eoOp.h> #include <eoOp.h>
/** /**
The abstract cellular easy algorithm. The abstract cellular easy algorithm.
@ingroup Algorithms @ingroup Algorithms
*/ */
template <class EOT> class eoCellularEasyEA : public eoAlgo <EOT> { template <class EOT> class eoCellularEasyEA : public eoAlgo <EOT> {
public : public :
/** /**
Two constructors Two constructors
*/ */
eoCellularEasyEA (eoContinue <EOT> & _cont, // Stop. criterion eoCellularEasyEA (eoContinue <EOT> & _cont, // Stop. criterion
eoEvalFunc <EOT> & _eval, // Evaluation function eoEvalFunc <EOT> & _eval, // Evaluation function
eoSelectOne <EOT> & _sel_neigh, // To choose a partner eoSelectOne <EOT> & _sel_neigh, // To choose a partner
eoBinOp <EOT> & _cross, // Cross-over operator eoBinOp <EOT> & _cross, // Cross-over operator
eoMonOp <EOT> & _mut, // Mutation operator eoMonOp <EOT> & _mut, // Mutation operator
eoSelectOne <EOT> & _sel_repl /* Which to keep between the new eoSelectOne <EOT> & _sel_repl /* Which to keep between the new
child and the old individual ? */ child and the old individual ? */
) : ) :
cont (_cont), cont (_cont),
eval (_eval), eval (_eval),
popEval (_eval), popEval (_eval),
@ -60,18 +60,18 @@ public :
mut (_mut), mut (_mut),
sel_child (eoSelectFirstOne ()), sel_child (eoSelectFirstOne ()),
sel_repl (_sel_repl) { sel_repl (_sel_repl) {
} }
eoCellularEasyEA (eoContinue <EOT> & _cont, eoCellularEasyEA (eoContinue <EOT> & _cont,
eoEvalFunc <EOT> & _eval, eoEvalFunc <EOT> & _eval,
eoSelectOne <EOT> & _sel_neigh, eoSelectOne <EOT> & _sel_neigh,
eoQuadOp <EOT> & _cross, eoQuadOp <EOT> & _cross,
eoMonOp <EOT> & _mut, eoMonOp <EOT> & _mut,
eoSelectOne <EOT> & _sel_child, /* To choose one from eoSelectOne <EOT> & _sel_child, /* To choose one from
the both children */ the both children */
eoSelectOne <EOT> & _sel_repl eoSelectOne <EOT> & _sel_repl
) : ) :
cont (_cont), cont (_cont),
eval (_eval), eval (_eval),
popEval (_eval), popEval (_eval),
@ -80,7 +80,7 @@ public :
mut (_mut), mut (_mut),
sel_child (_sel_child), sel_child (_sel_child),
sel_repl (_sel_repl) { sel_repl (_sel_repl) {
} }
/** /**
@ -88,55 +88,55 @@ public :
*/ */
void operator () (eoPop <EOT> & pop) { void operator () (eoPop <EOT> & pop) {
do { do {
for (unsigned i = 0 ; i < pop.size () ; i ++) { 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 // Who are neighbouring to the current individual ?
cross (pop [i], part) ; eoPop <EOT> neigh = neighbours (pop, i) ;
// To perform mutation // To select a partner
mut (pop [i]) ; EOT part, old_sol = pop [i] ;
mut (part) ; part = sel_neigh (neigh) ;
pop [i].invalidate () ;
part.invalidate () ;
eval (pop [i]) ;
eval (part) ;
// To choose one of the two children ... // To perform cross-over
eoPop <EOT> pop_loc ; cross (pop [i], part) ;
pop_loc.push_back (pop [i]) ;
pop_loc.push_back (part) ;
pop [i] = sel_child (pop_loc) ; // To perform mutation
mut (pop [i]) ;
mut (part) ;
// To choose only one between the new made child and the old individual pop [i].invalidate () ;
pop_loc.clear () ; part.invalidate () ;
pop_loc.push_back (pop [i]) ; eval (pop [i]) ;
eval (part) ;
pop_loc.push_back (old_sol) ;
// To choose one of the two children ...
pop [i] = sel_repl (pop_loc) ; 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)) ; } while (cont (pop)) ;
} }
protected : protected :
virtual eoPop <EOT> neighbours (const eoPop <EOT> & pop, int rank) = 0 ; virtual eoPop <EOT> neighbours (const eoPop <EOT> & pop, int rank) = 0 ;
private : private :
eoContinue <EOT> & cont ; eoContinue <EOT> & cont ;
eoEvalFunc <EOT> & eval ; eoEvalFunc <EOT> & eval ;
eoPopLoopEval <EOT> popEval ; eoPopLoopEval <EOT> popEval ;
@ -145,18 +145,18 @@ private :
eoMonOp <EOT> & mut ; eoMonOp <EOT> & mut ;
eoSelectOne <EOT> & sel_child ; eoSelectOne <EOT> & sel_child ;
eoSelectOne <EOT> & sel_repl ; eoSelectOne <EOT> & sel_repl ;
class eoSelectFirstOne : public eoSelectOne <EOT> { class eoSelectFirstOne : public eoSelectOne <EOT> {
public : public :
const EOT & operator () (const eoPop <EOT> & pop) { const EOT & operator () (const eoPop <EOT> & pop) {
return pop [0] ; return pop [0] ;
} }
} ; } ;
} ; } ;
#endif #endif

View file

@ -2,7 +2,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoCloneOps.h // eoCloneOps.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -18,7 +18,7 @@
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
CVS Info: $Date: 2003-02-27 19:26:09 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoCloneOps.h,v 1.2 2003-02-27 19:26:09 okoenig Exp $ $Author: okoenig $ CVS Info: $Date: 2003-02-27 19:26:09 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoCloneOps.h,v 1.2 2003-02-27 19:26:09 okoenig Exp $ $Author: okoenig $
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -29,9 +29,9 @@
/** /**
* The different null-variation operators (i.e. they do nothing) * The different null-variation operators (i.e. they do nothing)
* *
* eoQuadCloneOp at least is useful to emulate the standard * eoQuadCloneOp at least is useful to emulate the standard
* crossover(pCross) + mutation(pMut) * crossover(pCross) + mutation(pMut)
* within the eoGenOp framework * within the eoGenOp framework
* eoMonCloneOp will probably be useful as the copy operator * eoMonCloneOp will probably be useful as the copy operator
* eoBinCloneOp will certainly never been used - but let's be complete :-) * eoBinCloneOp will certainly never been used - but let's be complete :-)
@ -80,4 +80,3 @@ virtual bool operator()(EOT& , EOT& ) {return false;}
#endif #endif
/** @} */ /** @} */

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoCombinedContinue.h // eoCombinedContinue.h
// (c) Maarten Keijzer, GeNeura Team, 1999, 2000 // (c) Maarten Keijzer, GeNeura Team, 1999, 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -27,7 +27,7 @@
#include <eoContinue.h> #include <eoContinue.h>
/** /**
Combined continuators - logical AND: Combined continuators - logical AND:
Continues until one of the embedded continuators says halt! Continues until one of the embedded continuators says halt!
@ -35,7 +35,7 @@
to be consistent with other Combined constructs to be consistent with other Combined constructs
and allow to easily handle more than 2 continuators and allow to easily handle more than 2 continuators
02/2003 Ramón Casero Cañas - added the removeLast() method 02/2003 Ramón Casero Cañas - added the removeLast() method
@ingroup Combination @ingroup Combination
*/ */
@ -90,4 +90,3 @@ private:
}; };
#endif #endif

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoCombinedInit.h // eoCombinedInit.h
// (c) Maarten Keijzer, GeNeura Team, Marc Schoenauer 2004 // (c) Maarten Keijzer, GeNeura Team, Marc Schoenauer 2004
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -27,7 +27,7 @@
#include <eoInit.h> #include <eoInit.h>
/** /**
Combined INIT: a proportional recombination of eoInit objects Combined INIT: a proportional recombination of eoInit objects
@ingroup Initializators @ingroup Initializators
@ -49,7 +49,7 @@ public:
eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoCombinedInit::add is deprecated and will be removed in the next release." << std::endl; eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoCombinedInit::add is deprecated and will be removed in the next release." << std::endl;
add( _init, _rate ); add( _init, _rate );
} }
/** The usual method to add objects to the combination /** The usual method to add objects to the combination
*/ */
void add(eoInit<EOT> & _init, double _rate) void add(eoInit<EOT> & _init, double _rate)
@ -78,7 +78,7 @@ public:
virtual void operator() ( EOT & _eo ) virtual void operator() ( EOT & _eo )
{ {
unsigned what = rng.roulette_wheel(rates); // choose one op unsigned what = rng.roulette_wheel(rates); // choose one op
(*initializers[what])(_eo); // apply it (*initializers[what])(_eo); // apply it
return; return;
} }
@ -90,4 +90,3 @@ std::vector<double> rates;
}; };
#endif #endif

View file

@ -56,9 +56,9 @@ public:
* @param _topology - The topology to get the global/local/other best * @param _topology - The topology to get the global/local/other best
* @param _coeff - The constriction coefficient * @param _coeff - The constriction coefficient
* @param _weightUpdater - An eoWeightUpdater used to update the inertia weight * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
@ -85,9 +85,9 @@ public:
* @param _topology - The topology to get the global/local/other best * @param _topology - The topology to get the global/local/other best
* @param _coeff - The constriction coefficient * @param _coeff - The constriction coefficient
* @param _weightUpdater - An eoWeightUpdater used to update the inertia weight * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
*/ */
@ -112,8 +112,8 @@ public:
* @param _topology - The topology to get the global/local/other best* * @param _topology - The topology to get the global/local/other best*
* @param _coeff - The constriction coefficient * @param _coeff - The constriction coefficient
* @param _weightUpdater - An eoWeightUpdater used to update the inertia weight * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
*/ */
eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology, eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology,
@ -134,7 +134,7 @@ public:
/** /**
* Evaluate the new velocities of the given particle. Need an indice to identify the particle * Evaluate the new velocities of the given particle. Need an indice to identify the particle
* into the topology. Steps are : * into the topology. Steps are :
* - evaluate r1 and r2, the customed learning factors * - evaluate r1 and r2, the customed learning factors
* - adjust the size of the bounds (even if dummy) * - adjust the size of the bounds (even if dummy)
* - update the weight with the weightUpdater (use the dummy updater if there's no updater provided) * - update the weight with the weightUpdater (use the dummy updater if there's no updater provided)
@ -189,22 +189,21 @@ public:
protected: protected:
eoTopology < POT > & topology; eoTopology < POT > & topology;
const VelocityType & coeff; // the fixed constriction coefficient const VelocityType & coeff; // the fixed constriction coefficient
eoWeightUpdater<VelocityType> & weightUpdater; // the updater used to make the weight evoluate eoWeightUpdater<VelocityType> & weightUpdater; // the updater used to make the weight evoluate
const VelocityType & c1; // learning factor 1 const VelocityType & c1; // learning factor 1
const VelocityType & c2; // learning factor 2 const VelocityType & c2; // learning factor 2
eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type.
eoRealBoundModifier & bndsModifier; eoRealBoundModifier & bndsModifier;
VelocityType weight; VelocityType weight;
eoRng & gen; // the random generator eoRng & gen; // the random generator
// If the bound modifier doesn't need to be used, use the dummy instance // If the bound modifier doesn't need to be used, use the dummy instance
eoDummyRealBoundModifier dummyModifier; eoDummyRealBoundModifier dummyModifier;
}; };
#endif /*EOCONSTRICTEDVARIABLEWEIGHTVELOCITY_H*/ #endif /*EOCONSTRICTEDVARIABLEWEIGHTVELOCITY_H*/

View file

@ -56,9 +56,9 @@ public:
/** Full constructor: Bounds and bound modifier required /** Full constructor: Bounds and bound modifier required
* @param _topology - The topology to get the global/local/other best * @param _topology - The topology to get the global/local/other best
* @param _coeff - The constriction coefficient * @param _coeff - The constriction coefficient
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
@ -82,9 +82,9 @@ public:
/** Constructor: No bound updater required <-> fixed bounds /** Constructor: No bound updater required <-> fixed bounds
* @param _topology - The topology to get the global/local/other best * @param _topology - The topology to get the global/local/other best
* @param _coeff - The constriction coefficient * @param _coeff - The constriction coefficient
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
*/ */
@ -106,8 +106,8 @@ public:
/** Constructor: Neither bounds nor bound updater required <-> free velocity /** Constructor: Neither bounds nor bound updater required <-> free velocity
* @param _topology - The topology to get the global/local/other best * @param _topology - The topology to get the global/local/other best
* @param _coeff - The constriction coefficient * @param _coeff - The constriction coefficient
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
*/ */
eoConstrictedVelocity (eoTopology < POT > & _topology, eoConstrictedVelocity (eoTopology < POT > & _topology,
@ -126,7 +126,7 @@ public:
/** /**
* Evaluate the new velocities of the given particle. Need an indice to identify the particle * Evaluate the new velocities of the given particle. Need an indice to identify the particle
* into the topology. Steps are : * into the topology. Steps are :
* - evaluate r1 and r2, the customed learning factors * - evaluate r1 and r2, the customed learning factors
* - adjust the size of the bounds (even if dummy) * - adjust the size of the bounds (even if dummy)
* - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided) * - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided)
@ -173,20 +173,20 @@ public:
topology.updateNeighborhood(_po,_indice); topology.updateNeighborhood(_po,_indice);
} }
//! eoTopology<POT> getTopology //! eoTopology<POT> getTopology
//! @return topology //! @return topology
eoTopology<POT> & getTopology () eoTopology<POT> & getTopology ()
{ {
return topology; return topology;
} }
protected: protected:
eoTopology < POT > & topology; eoTopology < POT > & topology;
const VelocityType & c1; // learning factor 1 const VelocityType & c1; // learning factor 1
const VelocityType & c2; // learning factor 2 const VelocityType & c2; // learning factor 2
const VelocityType & coeff; // the fixed constriction coefficient const VelocityType & coeff; // the fixed constriction coefficient
eoRng & gen; // the random generator eoRng & gen; // the random generator
eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type.
eoRealBoundModifier & bndsModifier; eoRealBoundModifier & bndsModifier;
@ -197,4 +197,3 @@ protected:
#endif /*EOCONSTRICTEDVELOCITY_H */ #endif /*EOCONSTRICTEDVELOCITY_H */

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoContinue.h // eoContinue.h
// (c) Maarten Keijzer, Geneura Team, 1999, 2000 // (c) Maarten Keijzer, Geneura Team, 1999, 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -31,7 +31,7 @@
/** @defgroup Continuators Stopping criteria /** @defgroup Continuators Stopping criteria
* *
* A stopping criterion is called a "continue". This is a functor that is called at each generation end * A stopping criterion is called a "continue". This is a functor that is called at each generation end
* and that return true if one should stop the search. * and that return true if one should stop the search.
* *
* @ingroup Utilities * @ingroup Utilities
@ -39,13 +39,13 @@
/** Termination condition for the genetic algorithm /** Termination condition for the genetic algorithm
* Takes the population as input, returns true for continue, * Takes the population as input, returns true for continue,
* false for termination * false for termination
* *
* @ingroup Continuators * @ingroup Continuators
* @ingroup Core * @ingroup Core
*/ */
template< class EOT> template< class EOT>
class eoContinue : public eoUF<const eoPop<EOT>&, bool>, public eoPersistent class eoContinue : public eoUF<const eoPop<EOT>&, bool>, public eoPersistent
{ {
public: public:
virtual std::string className(void) const { return "eoContinue"; } virtual std::string className(void) const { return "eoContinue"; }
@ -57,7 +57,7 @@ public:
(void)__is; (void)__is;
/* It should be implemented by subclasses ! */ /* It should be implemented by subclasses ! */
} }
/** Print on a stream /** Print on a stream
* @param __os ostream to print on * @param __os ostream to print on
*/ */
@ -68,4 +68,3 @@ public:
}; };
#endif #endif

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoCounter.h // eoCounter.h
// (c) Maarten Keijzer 2000 // (c) Maarten Keijzer 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -31,9 +31,9 @@
#include <utils/eoParam.h> #include <utils/eoParam.h>
/** /**
Generic counter class that counts the number of times Generic counter class that counts the number of times
a procedure is used. Add a procedure through its ctor and a procedure is used. Add a procedure through its ctor and
use this class instead of it. use this class instead of it.
It is derived from eoValueParam so you can add it to a monitor. It is derived from eoValueParam so you can add it to a monitor.
@ -44,21 +44,21 @@ class eoProcedureCounter : public Procedure, public eoValueParam<unsigned long>
{ {
public: public:
eoProcedureCounter(Procedure& _proc, std::string _name = "proc_counter") eoProcedureCounter(Procedure& _proc, std::string _name = "proc_counter")
: eoValueParam<unsigned long>(0, _name), proc(_proc) {} : eoValueParam<unsigned long>(0, _name), proc(_proc) {}
/** Calls the embedded function and increments the counter /** Calls the embedded function and increments the counter
Note for MSVC users, if this code does not compile, you are quite Note for MSVC users, if this code does not compile, you are quite
likely trying to count a function that has a non-void return type. likely trying to count a function that has a non-void return type.
Don't look at us, look at the MSVC builders. Code like "return void;" Don't look at us, look at the MSVC builders. Code like "return void;"
is perfectly legal according to the ANSI standard, but the guys at is perfectly legal according to the ANSI standard, but the guys at
Microsoft didn't get to implementing it yet. Microsoft didn't get to implementing it yet.
We had two choices: assuming (and compiling ) code that returns void or code that returns non-void. We had two choices: assuming (and compiling ) code that returns void or code that returns non-void.
Given that in EO most functors return void, it was chosen to support void. Given that in EO most functors return void, it was chosen to support void.
But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite
capable of compiling return void; type of code. We'll try to change the signature then. capable of compiling return void; type of code. We'll try to change the signature then.
You happy GNU (and other compiler) users will not have a problem with this.. You happy GNU (and other compiler) users will not have a problem with this..
@ -79,39 +79,39 @@ class eoProcedureCounter : public Procedure, public eoValueParam<unsigned long>
}; };
/** /**
Generic counter class that counts the number of times Generic counter class that counts the number of times
a unary function is used. Add a unary function through its ctor and a unary function is used. Add a unary function through its ctor and
use this class instead of it. use this class instead of it.
It is derived from eoValueParam so you can add it to a monitor. It is derived from eoValueParam so you can add it to a monitor.
Example: suppose you have an eoEvalFunc called myeval, to count the Example: suppose you have an eoEvalFunc called myeval, to count the
number of evaluations, just define: number of evaluations, just define:
eoUnaryFunctorCounter<void, EoType> evalCounter(myeval); eoUnaryFunctorCounter<void, EoType> evalCounter(myeval);
and use evalCounter now instead of myeval. and use evalCounter now instead of myeval.
*/ */
template <class UnaryFunctor> template <class UnaryFunctor>
class eoUnaryFunctorCounter : public UnaryFunctor, public eoValueParam<unsigned long> class eoUnaryFunctorCounter : public UnaryFunctor, public eoValueParam<unsigned long>
{ {
public: public:
eoUnaryFunctorCounter(UnaryFunctor& _func, std::string _name = "uf_counter") eoUnaryFunctorCounter(UnaryFunctor& _func, std::string _name = "uf_counter")
: eoValueParam<unsigned long>(0, _name), func(_func) {} : eoValueParam<unsigned long>(0, _name), func(_func) {}
/** Calls the embedded function and increments the counter /** Calls the embedded function and increments the counter
Note for MSVC users, if this code does not compile, you are quite Note for MSVC users, if this code does not compile, you are quite
likely trying to count a function that has a non-void return type. likely trying to count a function that has a non-void return type.
Don't look at us, look at the MSVC builders. Code like "return void;" Don't look at us, look at the MSVC builders. Code like "return void;"
is perfectly legal according to the ANSI standard, but the guys at is perfectly legal according to the ANSI standard, but the guys at
Microsoft didn't get to implementing it yet. Microsoft didn't get to implementing it yet.
We had two choices: assuming (and compiling ) code that returns void or code that returns non-void. We had two choices: assuming (and compiling ) code that returns void or code that returns non-void.
Given that in EO most functors return void, it was chosen to support void. Given that in EO most functors return void, it was chosen to support void.
But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite
capable of compiling return void; type of code. We'll try to change the signature then. capable of compiling return void; type of code. We'll try to change the signature then.
You happy GNU (and other compiler) users will not have a problem with this. You happy GNU (and other compiler) users will not have a problem with this.
@ -133,10 +133,10 @@ class eoUnaryFunctorCounter : public UnaryFunctor, public eoValueParam<unsigned
}; };
/** /**
Generic counter class that counts the number of times Generic counter class that counts the number of times
a binary function is used. Add a binary function through its ctor and a binary function is used. Add a binary function through its ctor and
use this class instead of it. use this class instead of it.
It is derived from eoValueParam so you can add it to a monitor. It is derived from eoValueParam so you can add it to a monitor.
*/ */
@ -144,28 +144,28 @@ template <class BinaryFunctor>
class eoBinaryFunctorCounter : public BinaryFunctor, public eoValueParam<unsigned long> class eoBinaryFunctorCounter : public BinaryFunctor, public eoValueParam<unsigned long>
{ {
public: public:
eoBinaryFunctorCounter(BinaryFunctor& _func, std::string _name = "proc_counter") eoBinaryFunctorCounter(BinaryFunctor& _func, std::string _name = "proc_counter")
: eoValueParam<unsigned long>(0, _name), func(_func) {} : eoValueParam<unsigned long>(0, _name), func(_func) {}
/** Calls the embedded function and increments the counter /** Calls the embedded function and increments the counter
Note for MSVC users, if this code does not compile, you are quite Note for MSVC users, if this code does not compile, you are quite
likely trying to count a function that has a non-void return type. likely trying to count a function that has a non-void return type.
Don't look at us, look at the MSVC builders. Code like "return void;" Don't look at us, look at the MSVC builders. Code like "return void;"
is perfectly legal according to the ANSI standard, but the guys at is perfectly legal according to the ANSI standard, but the guys at
Microsoft didn't get to implementing it yet. Microsoft didn't get to implementing it yet.
We had two choices: assuming (and compiling ) code that returns void or code that returns non-void. We had two choices: assuming (and compiling ) code that returns void or code that returns non-void.
Given that in EO most functors return void, it was chosen to support void. Given that in EO most functors return void, it was chosen to support void.
But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite
capable of compiling return void; type of code. We'll try to change the signature then. capable of compiling return void; type of code. We'll try to change the signature then.
You happy GNU (and other compiler) users will not have a problem with this. You happy GNU (and other compiler) users will not have a problem with this.
*/ */
typename BinaryFunctor::result_type operator() typename BinaryFunctor::result_type operator()
(typename BinaryFunctor::first_argument_type _arg1, (typename BinaryFunctor::first_argument_type _arg1,
typename BinaryFunctor::second_argument_type _arg2) typename BinaryFunctor::second_argument_type _arg2)
{ {
value()++; value()++;
@ -185,7 +185,7 @@ class eoBinaryFunctorCounter : public BinaryFunctor, public eoValueParam<unsigne
how it works... how it works...
by using the xxx_function_tag structure defined in eoFunctionBase, you by using the xxx_function_tag structure defined in eoFunctionBase, you
can easily create a counter from a general class (say eoEval<EOT>), by can easily create a counter from a general class (say eoEval<EOT>), by
simply stating: simply stating:

View file

@ -1,23 +1,23 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoCtrlCContinue.cpp // eoCtrlCContinue.cpp
// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 // (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr Marc.Schoenauer@polytechnique.fr
mak@dhi.dk mak@dhi.dk
@ -26,7 +26,7 @@
#ifdef _MSC_VER #ifdef _MSC_VER
// to avoid long name warnings // to avoid long name warnings
#pragma warning(disable:4786) #pragma warning(disable:4786)
#endif #endif
#include <utils/eoLogger.h> #include <utils/eoLogger.h>

View file

@ -1,23 +1,23 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoCtrlCContinue.h // eoCtrlCContinue.h
// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 // (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr Marc.Schoenauer@polytechnique.fr
mak@dhi.dk mak@dhi.dk
@ -50,14 +50,14 @@ template< class EOT>
class eoCtrlCContinue: public eoContinue<EOT> class eoCtrlCContinue: public eoContinue<EOT>
{ {
public: public:
/// Ctor : installs the signal handler /// Ctor : installs the signal handler
eoCtrlCContinue() eoCtrlCContinue()
{ {
// First checks that no other eoCtrlCContinue does exist // First checks that no other eoCtrlCContinue does exist
if (existCtrlCContinue) if (existCtrlCContinue)
throw std::runtime_error("A signal handler for Ctrl C is already defined!\n"); throw std::runtime_error("A signal handler for Ctrl C is already defined!\n");
#ifndef _WINDOWS #ifndef _WINDOWS
#ifdef SIGQUIT #ifdef SIGQUIT
signal( SIGINT, signal_handler ); signal( SIGINT, signal_handler );
@ -65,9 +65,9 @@ public:
existCtrlCContinue = true; existCtrlCContinue = true;
#endif #endif
#endif #endif
} }
/** Returns false when Ctrl C has been typed in /** Returns false when Ctrl C has been typed in
* reached */ * reached */
virtual bool operator() ( const eoPop<EOT>& _vEO ) virtual bool operator() ( const eoPop<EOT>& _vEO )
@ -84,4 +84,3 @@ public:
#endif #endif
/** @} */ /** @} */

View file

@ -1,9 +1,9 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoDetSelect.h eoDetSelect.h
(c) Marc Schoenauer, Maarten Keijzer, GeNeura Team, 2000 (c) Marc Schoenauer, Maarten Keijzer, GeNeura Team, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -48,7 +48,7 @@ class eoDetSelect : public eoSelect<EOT>
/** /**
@param _source the source population @param _source the source population
@param _dest the resulting population (size of this population is @param _dest the resulting population (size of this population is
given by the HowMany data given by the HowMany data
It empties the destination and adds the selection into it) It empties the destination and adds the selection into it)
*/ */
@ -58,32 +58,32 @@ class eoDetSelect : public eoSelect<EOT>
size_t target = howMany(pSize); size_t target = howMany(pSize);
if ( target == 0 ) if ( target == 0 )
{ {
eo::log << eo::warnings << "Call to a eoHowMany instance returns 0 (target=" << target << ") it will be replaced by 1 to continue." << std::endl; eo::log << eo::warnings << "Call to a eoHowMany instance returns 0 (target=" << target << ") it will be replaced by 1 to continue." << std::endl;
target = 1; target = 1;
} }
_dest.resize(target); _dest.resize(target);
unsigned remain = target % pSize; unsigned remain = target % pSize;
unsigned entireCopy = target / pSize; unsigned entireCopy = target / pSize;
typename eoPop<EOT>::iterator it = _dest.begin(); typename eoPop<EOT>::iterator it = _dest.begin();
if (target >= pSize) if (target >= pSize)
{ {
for (unsigned i=0; i<entireCopy; i++) for (unsigned i=0; i<entireCopy; i++)
{ {
std::copy(_source.begin(), _source.end(), it); std::copy(_source.begin(), _source.end(), it);
it += pSize; it += pSize;
} }
} }
// the last ones // the last ones
if (remain) if (remain)
{ {
std::copy(_source.begin(), _source.begin()+remain, it); std::copy(_source.begin(), _source.begin()+remain, it);
} }
} }
private : private :
eoHowMany howMany; eoHowMany howMany;
}; };

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoDetTournament.h // eoDetTournament.h
// (c) GeNeura Team, 1998 - EEAAX 1999 // (c) GeNeura Team, 1998 - EEAAX 1999
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -28,7 +28,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#include <functional> // #include <functional> //
#include <numeric> // accumulate #include <numeric> // accumulate
#include <eoFunctor.h> #include <eoFunctor.h>
@ -37,7 +37,7 @@
#include <utils/selectors.h> #include <utils/selectors.h>
/** eoDetTournamentSelect: a selection method that selects ONE individual by /** eoDetTournamentSelect: a selection method that selects ONE individual by
deterministic tournament deterministic tournament
-MS- 24/10/99 -MS- 24/10/99
@ingroup Selectors @ingroup Selectors
@ -45,7 +45,7 @@
template <class EOT> class eoDetTournamentSelect: public eoSelectOne<EOT> template <class EOT> class eoDetTournamentSelect: public eoSelectOne<EOT>
{ {
public: public:
/* (Default) Constructor - /* (Default) Constructor -
@param _tSize tournament size @param _tSize tournament size
*/ */
eoDetTournamentSelect(unsigned _tSize = 2 ):eoSelectOne<EOT>(), tSize(_tSize) { eoDetTournamentSelect(unsigned _tSize = 2 ):eoSelectOne<EOT>(), tSize(_tSize) {
@ -55,15 +55,15 @@ template <class EOT> class eoDetTournamentSelect: public eoSelectOne<EOT>
tSize = 2; tSize = 2;
} }
} }
/* Perform deterministic tournament calling the appropriate fn /* Perform deterministic tournament calling the appropriate fn
see selectors.h see selectors.h
*/ */
virtual const EOT& operator()(const eoPop<EOT>& _pop) virtual const EOT& operator()(const eoPop<EOT>& _pop)
{ {
return deterministic_tournament(_pop, tSize); return deterministic_tournament(_pop, tSize);
} }
private: private:
unsigned tSize; unsigned tSize;
}; };
@ -71,4 +71,3 @@ template <class EOT> class eoDetTournamentSelect: public eoSelectOne<EOT>
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif #endif

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoDistribUpdater.h // eoDistribUpdater.h
// (c) Marc Schoenauer, Maarten Keijzer, 2001 // (c) Marc Schoenauer, Maarten Keijzer, 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -32,7 +32,7 @@
#include <eoPop.h> #include <eoPop.h>
/** /**
* Base class for Distribution Evolution Algorithms within EO: * Base class for Distribution Evolution Algorithms within EO:
* the update rule of distribution * the update rule of distribution
* *
* It takes one distribution and updates it according to one population * It takes one distribution and updates it according to one population
@ -40,7 +40,7 @@
* @ingroup Core * @ingroup Core
*/ */
template <class EOT> template <class EOT>
class eoDistribUpdater : class eoDistribUpdater :
public eoBF<eoDistribution<EOT> &, eoPop<EOT> &, void> public eoBF<eoDistribution<EOT> &, eoPop<EOT> &, void>
{ {
public: public:

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoDistribution.h // eoDistribution.h
// (c) Marc Schoenauer, Maarten Keijzer, 2001 // (c) Marc Schoenauer, Maarten Keijzer, 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -44,8 +44,8 @@
*/ */
template <class EOT> template <class EOT>
class eoDistribution : public eoInit<EOT>, class eoDistribution : public eoInit<EOT>,
public eoPersistent, public eoObject public eoPersistent, public eoObject
{ {
public: public:
virtual void operator()(EOT &) = 0; // DO NOT FORGET TO INVALIDATE the EOT virtual void operator()(EOT &) = 0; // DO NOT FORGET TO INVALIDATE the EOT

View file

@ -4,7 +4,7 @@
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; version 2 License as published by the Free Software Foundation; version 2
of the License. of the License.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
@ -40,7 +40,7 @@ Authors:
//! A fitness class that permits to compare feasible and unfeasible individuals and guaranties that a feasible individual will always be better than an unfeasible one. //! A fitness class that permits to compare feasible and unfeasible individuals and guaranties that a feasible individual will always be better than an unfeasible one.
/** /**
* Use this class as fitness if you have some kind of individuals * Use this class as fitness if you have some kind of individuals
* that must be always considered as better than others while having the same fitness type. * that must be always considered as better than others while having the same fitness type.
* *
* Wraps a scalar fitness _values such as a double or int, with the option of * Wraps a scalar fitness _values such as a double or int, with the option of
@ -52,7 +52,7 @@ Authors:
* *
* When changing the fitness, you can use: * When changing the fitness, you can use:
* individual.fitness( std::make_pair<BaseType,bool>( fitness, feasibility ) ); * individual.fitness( std::make_pair<BaseType,bool>( fitness, feasibility ) );
* *
* Be aware that, when printing or reading an eDualFitness instance on a iostream, * Be aware that, when printing or reading an eDualFitness instance on a iostream,
* friend IO classes use a space separator. * friend IO classes use a space separator.
* *
@ -80,19 +80,19 @@ public:
/*! /*!
* Unfeasible by default * Unfeasible by default
*/ */
eoDualFitness() : eoDualFitness() :
_value(), _value(),
_is_feasible(false) _is_feasible(false)
{} {}
//! Copy constructor //! Copy constructor
eoDualFitness(const eoDualFitness& other) : eoDualFitness(const eoDualFitness& other) :
_value(other._value), _value(other._value),
_is_feasible(other._is_feasible) _is_feasible(other._is_feasible)
{} {}
//! Constructor from explicit value/feasibility //! Constructor from explicit value/feasibility
eoDualFitness(const BaseType& v, const bool& is_feasible) : eoDualFitness(const BaseType& v, const bool& is_feasible) :
_value(v), _value(v),
_is_feasible(is_feasible) _is_feasible(is_feasible)
{} {}
@ -118,15 +118,15 @@ public:
{ {
_value = v.first; _value = v.first;
_is_feasible = v.second; _is_feasible = v.second;
return *this; return *this;
} }
//! Copy operator from another eoDualFitness //! Copy operator from another eoDualFitness
template <class F, class Cmp> template <class F, class Cmp>
eoDualFitness<F,Cmp> & operator=(const eoDualFitness<BaseType, Compare>& other ) eoDualFitness<F,Cmp> & operator=(const eoDualFitness<BaseType, Compare>& other )
{ {
if (this != &other) { if (this != &other) {
this->_value = other._value; this->_value = other._value;
this->_is_feasible = other._is_feasible; this->_is_feasible = other._is_feasible;
} }
return *this; return *this;
@ -135,12 +135,12 @@ public:
//! Comparison that separate feasible individuals from unfeasible ones. Feasible are always better //! Comparison that separate feasible individuals from unfeasible ones. Feasible are always better
/*! /*!
* Use less as a default comparison operator * Use less as a default comparison operator
* (see the "Compare" template of the class to change this behaviour, * (see the "Compare" template of the class to change this behaviour,
* @see eoMinimizingDualFitness for an example). * @see eoMinimizingDualFitness for an example).
*/ */
bool operator<(const eoDualFitness& other) const bool operator<(const eoDualFitness& other) const
{ {
// am I better (less, by default) than the other ? // am I better (less, by default) than the other ?
// if I'm feasible and the other is not // if I'm feasible and the other is not
@ -152,7 +152,7 @@ public:
// yes, a feasible fitness is always better than an unfeasible one // yes, a feasible fitness is always better than an unfeasible one
return true; return true;
} else { } else {
// the two fitness are of the same type // the two fitness are of the same type
// lets rely on the comparator // lets rely on the comparator
return Compare()(_value, other._value); return Compare()(_value, other._value);
@ -168,7 +168,7 @@ public:
//! Greater or equal: if the other is not greater than me //! Greater or equal: if the other is not greater than me
bool operator>=(const eoDualFitness<BaseType, Compare>& other ) const { return !(*this < other); } bool operator>=(const eoDualFitness<BaseType, Compare>& other ) const { return !(*this < other); }
public: public:
//! Add a given fitness to the current one //! Add a given fitness to the current one
@ -199,7 +199,7 @@ public:
// Add this fitness's value to that other, and return a _new_ instance with the result. // Add this fitness's value to that other, and return a _new_ instance with the result.
template <class F, class Cmp> template <class F, class Cmp>
eoDualFitness<F,Cmp> operator+(const eoDualFitness<F,Cmp> & that) eoDualFitness<F,Cmp> operator+(const eoDualFitness<F,Cmp> & that)
{ {
eoDualFitness<F,Cmp> from( *this ); eoDualFitness<F,Cmp> from( *this );
return from += that; return from += that;
@ -207,7 +207,7 @@ public:
// Add this fitness's value to that other, and return a _new_ instance with the result. // Add this fitness's value to that other, and return a _new_ instance with the result.
template <class F, class Cmp> template <class F, class Cmp>
eoDualFitness<F,Cmp> operator-(const eoDualFitness<F,Cmp> & that) eoDualFitness<F,Cmp> operator-(const eoDualFitness<F,Cmp> & that)
{ {
eoDualFitness<F,Cmp> from( *this ); eoDualFitness<F,Cmp> from( *this );
return from -= that; return from -= that;
@ -224,7 +224,7 @@ public:
//! Read an eoDualFitness instance as a pair of numbers, separated by a space //! Read an eoDualFitness instance as a pair of numbers, separated by a space
template <class F, class Cmp> template <class F, class Cmp>
friend friend
std::istream& operator>>(std::istream& is, eoDualFitness<F, Cmp>& f) std::istream& operator>>(std::istream& is, eoDualFitness<F, Cmp>& f)
{ {
F value; F value;
@ -265,11 +265,11 @@ public:
// eoDualStatSwitch( eoStat<EOT,T> & stat_feasible, eoStat<EOT,T> & stat_unfeasible, std::string sep=" " ) : // eoDualStatSwitch( eoStat<EOT,T> & stat_feasible, eoStat<EOT,T> & stat_unfeasible, std::string sep=" " ) :
eoDualStatSwitch( EOSTAT & stat_feasible, EOSTAT & stat_unfeasible, std::string sep=" " ) : eoDualStatSwitch( EOSTAT & stat_feasible, EOSTAT & stat_unfeasible, std::string sep=" " ) :
eoStat<EOT,std::string>( eoStat<EOT,std::string>(
"?"+sep+"?", "?"+sep+"?",
stat_feasible.longName()+sep+stat_unfeasible.longName() stat_feasible.longName()+sep+stat_unfeasible.longName()
), ),
_stat_feasible(stat_feasible), _stat_feasible(stat_feasible),
_stat_unfeasible(stat_unfeasible), _stat_unfeasible(stat_unfeasible),
_sep(sep) _sep(sep)
{ } { }
@ -277,7 +277,7 @@ public:
{ {
eoPop<EOT> pop_feasible; eoPop<EOT> pop_feasible;
pop_feasible.reserve(pop.size()); pop_feasible.reserve(pop.size());
eoPop<EOT> pop_unfeasible; eoPop<EOT> pop_unfeasible;
pop_unfeasible.reserve(pop.size()); pop_unfeasible.reserve(pop.size());
@ -296,7 +296,7 @@ public:
_stat_feasible( pop_feasible ); _stat_feasible( pop_feasible );
_stat_unfeasible( pop_unfeasible ); _stat_unfeasible( pop_unfeasible );
std::ostringstream out; std::ostringstream out;
out << _stat_feasible.value() << _sep << _stat_unfeasible.value(); out << _stat_feasible.value() << _sep << _stat_unfeasible.value();
@ -311,7 +311,6 @@ protected:
std::string _sep; std::string _sep;
}; };
/** @} */ /** @} */
#endif // _eoDualFitness_h_ #endif // _eoDualFitness_h_

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoEDA.h // eoEDA.h
// (c) Marc Schoenauer, Maarten Keijzer, 2001 // (c) Marc Schoenauer, Maarten Keijzer, 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -30,8 +30,8 @@
#include <eoDistribution.h> #include <eoDistribution.h>
/** The abstract class for estimation of disribution algorithms. /** The abstract class for estimation of disribution algorithms.
* This design evolve a probability distribution * This design evolve a probability distribution
* on the spaces of populations rather than a population * on the spaces of populations rather than a population
* *
* It IS NOT an eoAlgo, as it evolves a distribution, not a population. * It IS NOT an eoAlgo, as it evolves a distribution, not a population.
@ -44,4 +44,3 @@ template<class EOT> class eoEDA: public eoUF<eoDistribution<EOT>&, void>
}; };
#endif #endif

View file

@ -97,7 +97,7 @@ template<class EOT> class eoEasyEA: public eoAlgo<EOT>
mergeReduce(dummyMerge, dummyReduce), mergeReduce(dummyMerge, dummyReduce),
replace(_replace) replace(_replace)
{ {
offspring.reserve(_offspringSize); // This line avoids an incremental resize of offsprings. offspring.reserve(_offspringSize); // This line avoids an incremental resize of offsprings.
} }
/* /*
@ -135,8 +135,8 @@ template<class EOT> class eoEasyEA: public eoAlgo<EOT>
{} {}
/// Ctor eoSelect, eoTransform, eoReplacement and an eoPopEval /// Ctor eoSelect, eoTransform, eoReplacement and an eoPopEval
eoEasyEA( eoEasyEA(
eoContinue<EOT>& _continuator, eoContinue<EOT>& _continuator,
eoPopEvalFunc<EOT>& _eval, eoPopEvalFunc<EOT>& _eval,
eoSelect<EOT>& _select, eoSelect<EOT>& _select,
@ -185,7 +185,7 @@ template<class EOT> class eoEasyEA: public eoAlgo<EOT>
mergeReduce(dummyMerge, dummyReduce), mergeReduce(dummyMerge, dummyReduce),
replace(_replace) replace(_replace)
{} {}
/// Ctor eoSelect, eoTransform, eoMerge and eoReduce. /// Ctor eoSelect, eoTransform, eoMerge and eoReduce.
eoEasyEA( eoEasyEA(
eoContinue<EOT>& _continuator, eoContinue<EOT>& _continuator,
@ -291,7 +291,7 @@ template<class EOT> class eoEasyEA: public eoAlgo<EOT>
eoMergeReduce<EOT> mergeReduce; eoMergeReduce<EOT> mergeReduce;
eoReplacement<EOT>& replace; eoReplacement<EOT>& replace;
eoPop<EOT> offspring; eoPop<EOT> offspring;
// Friend classes // Friend classes
friend class eoIslandsEasyEA <EOT> ; friend class eoIslandsEasyEA <EOT> ;
@ -303,4 +303,3 @@ Example of a test program building an EA algorithm.
*/ */
#endif #endif

View file

@ -32,16 +32,16 @@
#include <eoFlight.h> #include <eoFlight.h>
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** An easy-to-use particle swarm algorithm. /** An easy-to-use particle swarm algorithm.
* Use any particle, any flight, any topology... * Use any particle, any flight, any topology...
* *
* The main steps are : * The main steps are :
* (The population is expected to be already evaluated) * (The population is expected to be already evaluated)
* - for each generation and each particle pi * - for each generation and each particle pi
* - evaluate the velocities * - evaluate the velocities
* -- perform the fligth of pi * -- perform the fligth of pi
* -- evaluate pi * -- evaluate pi
* -- update the neighborhoods * -- update the neighborhoods
* *
* @ingroup Algorithms * @ingroup Algorithms
*/ */
@ -54,7 +54,7 @@ public:
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system * @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
* @param _eval - An eoEvalFunc: the evaluation performer * @param _eval - An eoEvalFunc: the evaluation performer
* @param _velocity - An eoVelocity that defines how to compute the velocities * @param _velocity - An eoVelocity that defines how to compute the velocities
* @param _flight - An eoFlight that defines how to make the particle flying: that means how * @param _flight - An eoFlight that defines how to make the particle flying: that means how
* to modify the positions according to the velocities * to modify the positions according to the velocities
*/ */
eoEasyPSO ( eoEasyPSO (
@ -90,11 +90,11 @@ public:
{} {}
/* Constructor without eoInitializerBase. Assume the initialization is done before running the algorithm /* Constructor without eoInitializerBase. Assume the initialization is done before running the algorithm
* @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system * @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system
* @param _eval - An eoEvalFunc: the evaluation performer * @param _eval - An eoEvalFunc: the evaluation performer
* @param _velocity - An eoVelocity that defines how to compute the velocities * @param _velocity - An eoVelocity that defines how to compute the velocities
* @param _flight - An eoFlight that defines how to make the particle flying: that means how * @param _flight - An eoFlight that defines how to make the particle flying: that means how
* to modify the positions according to the velocities * to modify the positions according to the velocities
*/ */
eoEasyPSO ( eoEasyPSO (
@ -125,7 +125,7 @@ public:
velocity (_velocity), velocity (_velocity),
flight (dummyFlight) flight (dummyFlight)
{} {}
/// Apply a few iteration of flight to the population (=swarm). /// Apply a few iteration of flight to the population (=swarm).
virtual void operator () (eoPop < POT > &_pop) virtual void operator () (eoPop < POT > &_pop)
{ {
@ -171,22 +171,22 @@ protected:
eoVelocity < POT > &velocity; eoVelocity < POT > &velocity;
eoFlight < POT > &flight; eoFlight < POT > &flight;
// if the flight does not need to be used, use the dummy flight instance // if the flight does not need to be used, use the dummy flight instance
class eoDummyFlight:public eoFlight < POT > class eoDummyFlight:public eoFlight < POT >
{ {
public: public:
eoDummyFlight () {} eoDummyFlight () {}
void operator () (POT & _po) {} void operator () (POT & _po) {}
}dummyFlight; }dummyFlight;
// if the initializer does not need to be used, use the dummy one instead // if the initializer does not need to be used, use the dummy one instead
class eoDummyInitializer:public eoInitializerBase < POT > class eoDummyInitializer:public eoInitializerBase < POT >
{ {
public: public:
eoDummyInitializer () {} eoDummyInitializer () {}
void operator () (POT & _po) {} void operator () (POT & _po) {}
}dummyInit; }dummyInit;
}; };
/** /**
* @example t-eoEasyPSO.cpp * @example t-eoEasyPSO.cpp

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoEvalContinue.h // eoEvalContinue.h
// (c) GeNeura Team, 1999, Marc Schoenauer 2001 // (c) GeNeura Team, 1999, Marc Schoenauer 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -29,7 +29,7 @@
#include <eoContinue.h> #include <eoContinue.h>
#include <eoEvalFuncCounter.h> #include <eoEvalFuncCounter.h>
/** /**
* Continues until a number of evaluations has been made * Continues until a number of evaluations has been made
* *
* @ingroup Continuators * @ingroup Continuators
@ -38,28 +38,28 @@ template< class EOT>
class eoEvalContinue: public eoContinue<EOT> class eoEvalContinue: public eoContinue<EOT>
{ {
public: public:
/// Ctor /// Ctor
eoEvalContinue( eoEvalFuncCounter<EOT> & _eval, unsigned long _totalEval) eoEvalContinue( eoEvalFuncCounter<EOT> & _eval, unsigned long _totalEval)
: eval(_eval), repTotalEvaluations( _totalEval ) {}; : eval(_eval), repTotalEvaluations( _totalEval ) {};
/** Returns false when a certain number of evaluations has been done /** Returns false when a certain number of evaluations has been done
*/ */
virtual bool operator() ( const eoPop<EOT>& _vEO ) { virtual bool operator() ( const eoPop<EOT>& _vEO ) {
(void)_vEO; (void)_vEO;
if (eval.value() >= repTotalEvaluations) if (eval.value() >= repTotalEvaluations)
{ {
eo::log << eo::progress << "STOP in eoEvalContinue: Reached maximum number of evaluations [" << repTotalEvaluations << "]" << std::endl; eo::log << eo::progress << "STOP in eoEvalContinue: Reached maximum number of evaluations [" << repTotalEvaluations << "]" << std::endl;
return false; return false;
} }
return true; return true;
} }
/** Returns the number of generations to reach*/ /** Returns the number of generations to reach*/
virtual unsigned long totalEvaluations( ) virtual unsigned long totalEvaluations( )
{ {
return repTotalEvaluations; return repTotalEvaluations;
}; };
virtual std::string className(void) const { return "eoEvalContinue"; } virtual std::string className(void) const { return "eoEvalContinue"; }
private: private:
eoEvalFuncCounter<EOT> & eval; eoEvalFuncCounter<EOT> & eval;

View file

@ -1,4 +1,4 @@
/* /*
(c) Thales group, 2010 (c) Thales group, 2010
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
@ -17,7 +17,7 @@
Contact: http://eodev.sourceforge.net Contact: http://eodev.sourceforge.net
Authors: Authors:
Johann Dréo <johann.dreo@thalesgroup.com> Johann Dréo <johann.dreo@thalesgroup.com>
Caner Candan <caner.candan@thalesgroup.com> Caner Candan <caner.candan@thalesgroup.com>
@ -49,7 +49,7 @@ class eoEvalCounterThrowException : public eoEvalFuncCounter< EOT >
{ {
public : public :
eoEvalCounterThrowException( eoEvalFunc<EOT>& func, unsigned long max_evals, std::string name = "Eval. ") eoEvalCounterThrowException( eoEvalFunc<EOT>& func, unsigned long max_evals, std::string name = "Eval. ")
: eoEvalFuncCounter< EOT >( func, name ), _threshold( max_evals ) : eoEvalFuncCounter< EOT >( func, name ), _threshold( max_evals )
{} {}
using eoEvalFuncCounter< EOT >::value; using eoEvalFuncCounter< EOT >::value;
@ -60,8 +60,8 @@ public :
// bypass already evaluated individuals // bypass already evaluated individuals
if (eo.invalid()) { if (eo.invalid()) {
// increment the value of the self parameter // increment the value of the self parameter
// (eoEvalFuncCounter inherits from @see eoValueParam) // (eoEvalFuncCounter inherits from @see eoValueParam)
value()++; value()++;
// if we have reached the maximum // if we have reached the maximum
@ -84,4 +84,3 @@ private :
}; };
#endif // __eoEvalCounterThrowException_h__ #endif // __eoEvalCounterThrowException_h__

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoEvalFunc.h // eoEvalFunc.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -37,8 +37,8 @@
The requirements on the types with which this class is to be The requirements on the types with which this class is to be
instantiated with are null, or else, they depend on the particular instantiated with are null, or else, they depend on the particular
class it's going to be applied to; EO does not impose any requirement class it's going to be applied to; EO does not impose any requirement
on it. If you subclass this abstract class, and use it to evaluate an on it. If you subclass this abstract class, and use it to evaluate an
EO, the requirements on this EO will depend on the evaluator. EO, the requirements on this EO will depend on the evaluator.
@ingroup Evaluation @ingroup Evaluation
@ -49,7 +49,7 @@ template<class EOT> class eoEvalFunc : public eoUF<EOT&, void>
public : public :
typedef EOT EOType; typedef EOT EOType;
typedef typename EOT::Fitness EOFitT; typedef typename EOT::Fitness EOFitT;
}; };
#endif #endif

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoEvalFuncCounter.h // eoEvalFuncCounter.h
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000 // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -30,7 +30,7 @@
#include <eoEvalFunc.h> #include <eoEvalFunc.h>
#include <utils/eoParam.h> #include <utils/eoParam.h>
/** /**
Counts the number of evaluations actually performed. Counts the number of evaluations actually performed.
@ingroup Evaluation @ingroup Evaluation
@ -38,7 +38,7 @@ Counts the number of evaluations actually performed.
template<class EOT> class eoEvalFuncCounter : public eoEvalFunc<EOT>, public eoValueParam<unsigned long> template<class EOT> class eoEvalFuncCounter : public eoEvalFunc<EOT>, public eoValueParam<unsigned long>
{ {
public : public :
eoEvalFuncCounter(eoEvalFunc<EOT>& _func, std::string _name = "Eval. ") eoEvalFuncCounter(eoEvalFunc<EOT>& _func, std::string _name = "Eval. ")
: eoValueParam<unsigned long>(0, _name), func(_func) {} : eoValueParam<unsigned long>(0, _name), func(_func) {}
virtual void operator()(EOT& _eo) virtual void operator()(EOT& _eo)

View file

@ -8,7 +8,7 @@
* @{ * @{
*/ */
/** The exception raised by eoEvalFuncCounterBounder /** The exception raised by eoEvalFuncCounterBounder
* when the maximum number of allowed evaluations is reached. * when the maximum number of allowed evaluations is reached.
*/ */
class eoEvalFuncCounterBounderException : public std::exception class eoEvalFuncCounterBounderException : public std::exception
@ -18,9 +18,9 @@ public:
const char* what() const throw() const char* what() const throw()
{ {
std::ostringstream ss; std::ostringstream ss;
ss << "STOP in eoEvalFuncCounterBounderException: the maximum number of evaluation has been reached (" << _threshold << ")."; ss << "STOP in eoEvalFuncCounterBounderException: the maximum number of evaluation has been reached (" << _threshold << ").";
return ss.str().c_str(); return ss.str().c_str();
} }
private: private:
@ -31,7 +31,7 @@ private:
* when the maximum number of allowed evaluations is reached. * when the maximum number of allowed evaluations is reached.
* *
* This eval counter permits to stop a search during a generation, without waiting for a continue to be * This eval counter permits to stop a search during a generation, without waiting for a continue to be
* checked at the end of the loop. Useful if you have 10 individuals and 10 generations, * checked at the end of the loop. Useful if you have 10 individuals and 10 generations,
* but want to stop after 95 evaluations. * but want to stop after 95 evaluations.
*/ */
template < typename EOT > template < typename EOT >
@ -39,21 +39,21 @@ class eoEvalFuncCounterBounder : public eoEvalFuncCounter< EOT >
{ {
public : public :
eoEvalFuncCounterBounder(eoEvalFunc<EOT>& func, unsigned long threshold, std::string name = "Eval. ") eoEvalFuncCounterBounder(eoEvalFunc<EOT>& func, unsigned long threshold, std::string name = "Eval. ")
: eoEvalFuncCounter< EOT >( func, name ), _threshold( threshold ) : eoEvalFuncCounter< EOT >( func, name ), _threshold( threshold )
{} {}
using eoEvalFuncCounter< EOT >::value; using eoEvalFuncCounter< EOT >::value;
virtual void operator()(EOT& eo) virtual void operator()(EOT& eo)
{ {
if (eo.invalid()) if (eo.invalid())
{ {
value()++; value()++;
if (_threshold > 0 && value() >= _threshold) if (_threshold > 0 && value() >= _threshold)
{ {
throw eoEvalFuncCounterBounderException(_threshold); throw eoEvalFuncCounterBounderException(_threshold);
} }
func(eo); func(eo);
} }

View file

@ -6,7 +6,7 @@
evaluation object evaluation object
(c) GeNeura Team, 2000 (c) GeNeura Team, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -52,17 +52,16 @@ struct eoEvalFuncPtr: public eoEvalFunc<EOT> {
*/ */
eoEvalFuncPtr( FitT (* _eval)( FunctionArg ) ) eoEvalFuncPtr( FitT (* _eval)( FunctionArg ) )
: eoEvalFunc<EOT>(), evalFunc( _eval ) {}; : eoEvalFunc<EOT>(), evalFunc( _eval ) {};
/// Effectively applies the evaluation function to an EO /// Effectively applies the evaluation function to an EO
virtual void operator() ( EOT & _eo ) virtual void operator() ( EOT & _eo )
{ {
if (_eo.invalid()) if (_eo.invalid())
_eo.fitness((*evalFunc)( _eo )); _eo.fitness((*evalFunc)( _eo ));
}; };
private: private:
FitT (* evalFunc )( FunctionArg ); FitT (* evalFunc )( FunctionArg );
}; };
#endif #endif

View file

@ -1,4 +1,4 @@
/* /*
(c) Thales group, 2010 (c) Thales group, 2010
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
@ -17,7 +17,7 @@
Contact: http://eodev.sourceforge.net Contact: http://eodev.sourceforge.net
Authors: Authors:
Johann Dréo <johann.dreo@thalesgroup.com> Johann Dréo <johann.dreo@thalesgroup.com>
*/ */

View file

@ -1,4 +1,4 @@
/* /*
(c) Thales group, 2010 (c) Thales group, 2010
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
@ -17,7 +17,7 @@
Contact: http://eodev.sourceforge.net Contact: http://eodev.sourceforge.net
Authors: Authors:
Johann Dréo <johann.dreo@thalesgroup.com> Johann Dréo <johann.dreo@thalesgroup.com>
*/ */

View file

@ -1,4 +1,4 @@
/* /*
(c) Thales group, 2010 (c) Thales group, 2010
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
@ -17,7 +17,7 @@
Contact: http://eodev.sourceforge.net Contact: http://eodev.sourceforge.net
Authors: Authors:
Johann Dréo <johann.dreo@thalesgroup.com> Johann Dréo <johann.dreo@thalesgroup.com>
*/ */

View file

@ -35,7 +35,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** Extended velocity performer for particle swarm optimization. /** Extended velocity performer for particle swarm optimization.
* *
* Derivated from abstract eoVelocity, * Derivated from abstract eoVelocity,
* At step t: v(t+1)= w * v(t) + c1 * r1 * ( xbest(t)-x(t) ) + c2 * r2 * ( lbest(t) - x(t) ) + c3 * r3 * ( gbest(t) - x(t) ) * At step t: v(t+1)= w * v(t) + c1 * r1 * ( xbest(t)-x(t) ) + c2 * r2 * ( lbest(t) - x(t) ) + c3 * r3 * ( gbest(t) - x(t) )
@ -57,16 +57,16 @@ public:
/** Full constructor: Bounds and bound modifier required /** Full constructor: Bounds and bound modifier required
* @param _topology - The topology * @param _topology - The topology
* @param _w - The weight factor. * @param _w - The weight factor.
* @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - Learning factor used for the local best * @param _c2 - Learning factor used for the local best
* @param _c3 - Learning factor used for the global best * @param _c3 - Learning factor used for the global best
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
*/ */
eoExtendedVelocity (eoTopology < POT > & _topology, eoExtendedVelocity (eoTopology < POT > & _topology,
const VelocityType & _w, const VelocityType & _w,
const VelocityType & _c1, const VelocityType & _c1,
const VelocityType & _c2, const VelocityType & _c2,
const VelocityType & _c3, const VelocityType & _c3,
@ -86,10 +86,10 @@ public:
/** Constructor: No bound updater required <-> fixed bounds /** Constructor: No bound updater required <-> fixed bounds
* @param _topology - The topology * @param _topology - The topology
* @param _w - The weight factor. * @param _w - The weight factor.
* @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType * @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType
* @param _c3 - Learning factor used for the global best * @param _c3 - Learning factor used for the global best
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
*/ */
@ -113,8 +113,8 @@ public:
/** Constructor: Neither bounds nor bound updater required <-> free velocity /** Constructor: Neither bounds nor bound updater required <-> free velocity
* @param _topology - The topology * @param _topology - The topology
* @param _w - The weight factor. * @param _w - The weight factor.
* @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType * @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType
* @param _c3 - Learning factor used for the global best * @param _c3 - Learning factor used for the global best
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
*/ */
@ -145,25 +145,25 @@ public:
{ {
VelocityType r1; VelocityType r1;
VelocityType r2; VelocityType r2;
VelocityType r3; VelocityType r3;
VelocityType newVelocity; VelocityType newVelocity;
// cast the learning factors to VelocityType // cast the learning factors to VelocityType
r1 = (VelocityType) rng.uniform (1) * c1; r1 = (VelocityType) rng.uniform (1) * c1;
r2 = (VelocityType) rng.uniform (1) * c2; r2 = (VelocityType) rng.uniform (1) * c2;
r3 = (VelocityType) rng.uniform (1) * c3; r3 = (VelocityType) rng.uniform (1) * c3;
// need to resize the bounds even if there are dummy because of "isBounded" call // need to resize the bounds even if there are dummy because of "isBounded" call
bounds.adjust_size(_po.size()); bounds.adjust_size(_po.size());
// assign the new velocities // assign the new velocities
for (unsigned j = 0; j < _po.size (); j++) for (unsigned j = 0; j < _po.size (); j++)
{ {
newVelocity= omega * _po.velocities[j] newVelocity= omega * _po.velocities[j]
+ r1 * (_po.bestPositions[j] - _po[j]) + r1 * (_po.bestPositions[j] - _po[j])
+ r2 * (topology.best (_indice)[j] - _po[j]) + r2 * (topology.best (_indice)[j] - _po[j])
+ r3 * (topology.globalBest()[j] - _po[j]); + r3 * (topology.globalBest()[j] - _po[j]);
/* check bounds */ /* check bounds */
if (bounds.isMinBounded(j)) if (bounds.isMinBounded(j))
@ -182,27 +182,27 @@ public:
{ {
topology.updateNeighborhood(_po,_indice); topology.updateNeighborhood(_po,_indice);
} }
//! eoTopology<POT> getTopology //! eoTopology<POT> getTopology
//! @return topology //! @return topology
eoTopology<POT> & getTopology () eoTopology<POT> & getTopology ()
{ {
return topology; return topology;
} }
protected: protected:
eoTopology < POT > & topology; eoTopology < POT > & topology;
const VelocityType & omega; // social/cognitive coefficient const VelocityType & omega; // social/cognitive coefficient
const VelocityType & c1; const VelocityType & c1;
const VelocityType & c2; // social/cognitive coefficient const VelocityType & c2; // social/cognitive coefficient
const VelocityType & c3; // social/cognitive coefficient const VelocityType & c3; // social/cognitive coefficient
eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type.
eoRealBoundModifier & bndsModifier; eoRealBoundModifier & bndsModifier;
eoRng & gen; // the random generator
eoRng & gen; // the random generator
// If the bound modifier doesn't need to be used, use the dummy instance // If the bound modifier doesn't need to be used, use the dummy instance
eoDummyRealBoundModifier dummyModifier; eoDummyRealBoundModifier dummyModifier;
}; };
@ -211,4 +211,3 @@ protected:
* Example of a test program using this class: * Example of a test program using this class:
*/ */
#endif /*eoExtendedVelocity_H */ #endif /*eoExtendedVelocity_H */

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoFactory.h // eoFactory.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -43,32 +43,32 @@ have to be modified
*/ */
template<class EOClass> template<class EOClass>
class eoFactory: public eoObject { class eoFactory: public eoObject {
public: public:
/// @name ctors and dtors
//{@
/// constructor
eoFactory( ) {}
/// destructor
virtual ~eoFactory() {}
//@}
/** Another factory methods: creates an object from an std::istream, reading from /// @name ctors and dtors
it whatever is needed to create the object. Usually, the format for the std::istream will be\\ //{@
objectType parameter1 parameter2 ... parametern\\ /// constructor
*/ eoFactory( ) {}
virtual EOClass* make(std::istream& _is) = 0;
///@name eoObject methods /// destructor
//@{ virtual ~eoFactory() {}
/** Return the class id */ //@}
virtual std::string className() const { return "eoFactory"; }
/** Another factory methods: creates an object from an std::istream, reading from
it whatever is needed to create the object. Usually, the format for the std::istream will be\\
objectType parameter1 parameter2 ... parametern\\
*/
virtual EOClass* make(std::istream& _is) = 0;
///@name eoObject methods
//@{
/** Return the class id */
virtual std::string className() const { return "eoFactory"; }
/** Read and print are left without implementation */
//@}
/** Read and print are left without implementation */
//@}
}; };

View file

@ -49,15 +49,15 @@ public:
/** Returns false when a fitness criterium is reached. Assumes pop is not sorted! */ /** Returns false when a fitness criterium is reached. Assumes pop is not sorted! */
virtual bool operator() ( const eoPop<EOT>& _pop ) virtual bool operator() ( const eoPop<EOT>& _pop )
{ {
//FitnessType bestCurrentFitness = _pop.nth_element_fitness(0); //FitnessType bestCurrentFitness = _pop.nth_element_fitness(0);
FitnessType bestCurrentFitness = _pop.best_element().fitness(); FitnessType bestCurrentFitness = _pop.best_element().fitness();
if (bestCurrentFitness >= optimum) if (bestCurrentFitness >= optimum)
{ {
eo::log << eo::logging << "STOP in eoFitContinue: Best fitness has reached " << eo::log << eo::logging << "STOP in eoFitContinue: Best fitness has reached " <<
bestCurrentFitness << "\n"; bestCurrentFitness << "\n";
return false; return false;
} }
return true; return true;
} }
virtual std::string className(void) const { return "eoFitContinue"; } virtual std::string className(void) const { return "eoFitContinue"; }

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoFitnessScalingSelect.h // eoFitnessScalingSelect.h
// (c) GeNeura Team, 1998, Maarten Keijzer 2000, Marc Schoenauer 2001 // (c) GeNeura Team, 1998, Maarten Keijzer 2000, Marc Schoenauer 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -32,25 +32,24 @@
#include <eoSelectFromWorth.h> #include <eoSelectFromWorth.h>
#include <eoLinearFitScaling.h> #include <eoLinearFitScaling.h>
/** eoFitnessScalingSelect: select an individual proportional to the /** eoFitnessScalingSelect: select an individual proportional to the
* linearly scaled fitness that is computed by the private * linearly scaled fitness that is computed by the private
* eoLinearFitScaling object * eoLinearFitScaling object
* *
* @ingroup Selectors * @ingroup Selectors
*/ */
template <class EOT> template <class EOT>
class eoFitnessScalingSelect: public eoRouletteWorthSelect<EOT, double> class eoFitnessScalingSelect: public eoRouletteWorthSelect<EOT, double>
{ {
public: public:
/** Ctor: /** Ctor:
* @param _p the selective pressure, should be in [1,2] (2 is the default) * @param _p the selective pressure, should be in [1,2] (2 is the default)
*/ */
eoFitnessScalingSelect(double _p = 2.0): eoFitnessScalingSelect(double _p = 2.0):
eoRouletteWorthSelect<EOT, double>(scaling), scaling(_p) {} eoRouletteWorthSelect<EOT, double>(scaling), scaling(_p) {}
private : private :
eoLinearFitScaling<EOT> scaling; // derived from eoPerf2Worth eoLinearFitScaling<EOT> scaling; // derived from eoPerf2Worth
}; };
#endif #endif

View file

@ -54,9 +54,9 @@ public:
/** Full constructor: Bounds and bound modifier required /** Full constructor: Bounds and bound modifier required
* @param _topology - The topology to get the global/local/other best * @param _topology - The topology to get the global/local/other best
* @param _weight - The weight with type VelocityType * @param _weight - The weight with type VelocityType
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
@ -80,9 +80,9 @@ public:
/** Constructor: No bound updater required <-> fixed bounds /** Constructor: No bound updater required <-> fixed bounds
* @param _topology - The topology to get the global/local/other best * @param _topology - The topology to get the global/local/other best
* @param _weight - The weight with type VelocityType * @param _weight - The weight with type VelocityType
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
*/ */
@ -104,8 +104,8 @@ public:
/** Constructor: Neither bounds nor bound updater required <-> free velocity /** Constructor: Neither bounds nor bound updater required <-> free velocity
* @param _topology - The topology to get the global/local/other best * @param _topology - The topology to get the global/local/other best
* @param _weight - The weight with type VelocityType * @param _weight - The weight with type VelocityType
* @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
*/ */
eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology, eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology,
@ -124,7 +124,7 @@ public:
/** /**
* Evaluate the new velocities of the given particle. Need an indice to identify the particle * Evaluate the new velocities of the given particle. Need an indice to identify the particle
* into the topology. Steps are : * into the topology. Steps are :
* - evaluate r1 and r2, the customed learning factors * - evaluate r1 and r2, the customed learning factors
* - adjust the size of the bounds (even if dummy) * - adjust the size of the bounds (even if dummy)
* - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided) * - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided)
@ -175,10 +175,10 @@ public:
protected: protected:
eoTopology < POT > & topology; eoTopology < POT > & topology;
const VelocityType & c1; // learning factor 1 const VelocityType & c1; // learning factor 1
const VelocityType & c2; // learning factor 2 const VelocityType & c2; // learning factor 2
const VelocityType & weight; // the fixed weight const VelocityType & weight; // the fixed weight
eoRng & gen; // the random generator eoRng & gen; // the random generator
eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type.
eoRealBoundModifier & bndsModifier; eoRealBoundModifier & bndsModifier;
@ -189,4 +189,3 @@ protected:
#endif /*EOFIXEDINERTIAWEIGHTEDVELOCITY_H */ #endif /*EOFIXEDINERTIAWEIGHTEDVELOCITY_H */

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoFlOrBinOp.h // eoFlOrBinOp.h
// (c) Marc Schoenauer - Maarten Keijzer 2000-2003 // (c) Marc Schoenauer - Maarten Keijzer 2000-2003
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -35,11 +35,11 @@
/** Generic eoBinOps on fixed length genotypes. /** Generic eoBinOps on fixed length genotypes.
* Contains exchange crossovers (1pt and uniform) * Contains exchange crossovers (1pt and uniform)
* and crossovers that applies an Atom crossover * and crossovers that applies an Atom crossover
* to all components with given rate, or * to all components with given rate, or
* to a fixed prescribed nb of components * to a fixed prescribed nb of components
* *
* Example: the standard bitstring 1-point and uniform crossovers * Example: the standard bitstring 1-point and uniform crossovers
* could be implemented as resp. eoFlOr1ptBinOp and eoFlOrUniformBinOp * could be implemented as resp. eoFlOr1ptBinOp and eoFlOrUniformBinOp
*/ */
@ -65,14 +65,14 @@ public :
{ {
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw runtime_error(s);
} }
bool changed = false; bool changed = false;
for ( unsigned i = 0; i < _eo1.size(); i++ ) { for ( unsigned i = 0; i < _eo1.size(); i++ ) {
if ( rng.flip( rate ) ) { if ( rng.flip( rate ) ) {
bool changedHere = op( _eo1[i], _eo2[i] ); bool changedHere = op( _eo1[i], _eo2[i] );
changed |= changedHere; changed |= changedHere;
} }
} }
return changed; return changed;
@ -108,16 +108,16 @@ public :
{ {
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw runtime_error(s);
} }
bool changed = false; bool changed = false;
for ( unsigned i = 0; i < k; i++ ) //! @todo check that we don't do twice the same for ( unsigned i = 0; i < k; i++ ) //! @todo check that we don't do twice the same
{ {
unsigned where = eo::rng.random(_eo1.size()); unsigned where = eo::rng.random(_eo1.size());
bool changedHere = op( _eo1[where], _eo2[where] ); bool changedHere = op( _eo1[where], _eo2[where] );
changed |= changedHere; changed |= changedHere;
} }
return changed; return changed;
} }
@ -154,17 +154,17 @@ public :
Atom tmp; Atom tmp;
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw runtime_error(s);
} }
bool hasChanged = false; bool hasChanged = false;
for (unsigned i=0; i<_eo1.size(); i++) for (unsigned i=0; i<_eo1.size(); i++)
{ {
if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) ) if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) )
{ {
_eo1[i] = _eo2[i]; _eo1[i] = _eo2[i];
hasChanged = true; hasChanged = true;
} }
} }
return hasChanged; return hasChanged;
} }
@ -198,18 +198,18 @@ public :
Atom tmp; Atom tmp;
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw runtime_error(s);
} }
bool hasChanged = false; bool hasChanged = false;
unsigned where = eo::rng.random(_eo1.size()-1); unsigned where = eo::rng.random(_eo1.size()-1);
for (unsigned i=where+1; i<_eo1.size(); i++) for (unsigned i=where+1; i<_eo1.size(); i++)
{ {
if ( (_eo1[i]!=_eo2[i]) ) if ( (_eo1[i]!=_eo2[i]) )
{ {
_eo1[i] = _eo2[i]; _eo1[i] = _eo2[i];
hasChanged = true; hasChanged = true;
} }
} }
return hasChanged; return hasChanged;
} }

View file

@ -39,7 +39,7 @@
* eoFlOrAllMutation applies the atom mutation to all components with given rate * eoFlOrAllMutation applies the atom mutation to all components with given rate
* eoFlOrKMutation applies the atom mutation to a fixed nb of components * eoFlOrKMutation applies the atom mutation to a fixed nb of components
* *
* Remark: the standard bit-flip mutation is an eoFlOrAllMutation * Remark: the standard bit-flip mutation is an eoFlOrAllMutation
* with atom mutation == bitflipping * with atom mutation == bitflipping
*/ */
@ -62,21 +62,21 @@ public :
bool modified=false; bool modified=false;
for (unsigned i=0; i<_eo.size(); i++) for (unsigned i=0; i<_eo.size(); i++)
if (eo::rng.flip(rate)) if (eo::rng.flip(rate))
if (atomMutation(_eo[i])) if (atomMutation(_eo[i]))
modified = true; modified = true;
return modified; return modified;
} }
/** inherited className() */ /** inherited className() */
virtual std::string className() const virtual std::string className() const
{ {
return "eoFlOrAllMutation(" + atomMutation.className() + ")"; return "eoFlOrAllMutation(" + atomMutation.className() + ")";
} }
private: private:
eoMonOp<AtomType> & atomMutation; // the atom mutation eoMonOp<AtomType> & atomMutation; // the atom mutation
double rate; // the mutation rate PER ATOM double rate; // the mutation rate PER ATOM
}; };
/** Applies an atomic mutation to a fixed /** Applies an atomic mutation to a fixed
@ -100,21 +100,21 @@ public :
bool modified=false; bool modified=false;
for (unsigned k=0; k<nb; k++) for (unsigned k=0; k<nb; k++)
{ {
unsigned i = rng.random(_eo.size()); // we don't test for duplicates... unsigned i = rng.random(_eo.size()); // we don't test for duplicates...
if (atomMutation(_eo[i])) if (atomMutation(_eo[i]))
modified = true; modified = true;
} }
return modified; return modified;
} }
/** inherited className() */ /** inherited className() */
virtual std::string className() const virtual std::string className() const
{ {
return "eoFlOrKMutation(" + atomMutation.className() + ")"; return "eoFlOrKMutation(" + atomMutation.className() + ")";
} }
private: private:
unsigned nb; // the number of atoms to mutate unsigned nb; // the number of atoms to mutate
eoMonOp<AtomType> & atomMutation; // the atom mutation eoMonOp<AtomType> & atomMutation; // the atom mutation
}; };

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoFlOrQuadOp.h // eoFlOrQuadOp.h
// (c) Marc Schoenauer - Maarten Keijzer 2000-2003 // (c) Marc Schoenauer - Maarten Keijzer 2000-2003
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -35,7 +35,7 @@
/** Generic eoQuadOps on fixed length genotypes. /** Generic eoQuadOps on fixed length genotypes.
* Contains exchange crossovers (1pt and uniform) * Contains exchange crossovers (1pt and uniform)
* and crossovers that applies an Atom crossover * and crossovers that applies an Atom crossover
* to all components with given rate, or * to all components with given rate, or
* to a fixed prescribed nb of components * to a fixed prescribed nb of components
*/ */
@ -63,8 +63,8 @@ public :
bool changed = false; bool changed = false;
for ( unsigned i = 0; i < _eo1.size(); i++ ) { for ( unsigned i = 0; i < _eo1.size(); i++ ) {
if ( rng.flip( rate ) ) { if ( rng.flip( rate ) ) {
bool changedHere = op( _eo1[i], _eo2[i] ); bool changedHere = op( _eo1[i], _eo2[i] );
changed |= changedHere; changed |= changedHere;
} }
} }
return changed; return changed;
@ -100,16 +100,16 @@ public :
{ {
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw runtime_error(s);
} }
bool changed = false; bool changed = false;
for ( unsigned i = 0; i < k; i++ ) //! @todo check that we don't do twice the same for ( unsigned i = 0; i < k; i++ ) //! @todo check that we don't do twice the same
{ {
unsigned where = eo::rng.random(_eo1.size()); unsigned where = eo::rng.random(_eo1.size());
bool changedHere = op( _eo1[where], _eo2[where] ); bool changedHere = op( _eo1[where], _eo2[where] );
changed |= changedHere; changed |= changedHere;
} }
return changed; return changed;
} }
@ -145,19 +145,19 @@ public :
Atom tmp; Atom tmp;
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw runtime_error(s);
} }
bool hasChanged = false; bool hasChanged = false;
for (unsigned i=0; i<_eo1.size(); i++) for (unsigned i=0; i<_eo1.size(); i++)
{ {
if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) ) if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) )
{ {
tmp = _eo1[i]; tmp = _eo1[i];
_eo1[i] = _eo2[i]; _eo1[i] = _eo2[i];
_eo2[i] = tmp; _eo2[i] = tmp;
hasChanged = true; hasChanged = true;
} }
} }
return hasChanged; return hasChanged;
} }
@ -190,20 +190,20 @@ public :
Atom tmp; Atom tmp;
if (_eo1.size() != _eo2.size()) if (_eo1.size() != _eo2.size())
{ {
string s = "Operand size don't match in " + className(); string s = "Operand size don't match in " + className();
throw runtime_error(s); throw runtime_error(s);
} }
bool hasChanged = false; bool hasChanged = false;
unsigned where = eo::rng.random(_eo1.size()-1); unsigned where = eo::rng.random(_eo1.size()-1);
for (unsigned i=where+1; i<_eo1.size(); i++) for (unsigned i=where+1; i<_eo1.size(); i++)
{ {
if ( (_eo1[i]!=_eo2[i]) ) if ( (_eo1[i]!=_eo2[i]) )
{ {
tmp = _eo1[i]; tmp = _eo1[i];
_eo1[i] = _eo2[i]; _eo1[i] = _eo2[i];
_eo2[i] = tmp; _eo2[i] = tmp;
hasChanged = true; hasChanged = true;
} }
} }
return hasChanged; return hasChanged;
} }

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoFunctor.h // eoFunctor.h
// (c) Maarten Keijzer 2000 // (c) Maarten Keijzer 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -20,7 +20,7 @@
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
mak@dhi.dk mak@dhi.dk
CVS Info: $Date: 2004-12-01 09:22:48 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoFunctor.h,v 1.7 2004-12-01 09:22:48 evomarc Exp $ $Author: evomarc $ CVS Info: $Date: 2004-12-01 09:22:48 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoFunctor.h,v 1.7 2004-12-01 09:22:48 evomarc Exp $ $Author: evomarc $
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -87,12 +87,12 @@ public :
/// tag to identify a procedure in compile time function selection @see functor_category /// tag to identify a procedure in compile time function selection @see functor_category
static eoFunctorBase::procedure_tag functor_category() static eoFunctorBase::procedure_tag functor_category()
{ {
return eoFunctorBase::procedure_tag(); return eoFunctorBase::procedure_tag();
} }
}; };
/** /**
Overloaded function that can help in the compile time detection Overloaded function that can help in the compile time detection
of the type of functor we are dealing with of the type of functor we are dealing with
@see eoCounter, make_counter @see eoCounter, make_counter
@ -103,8 +103,8 @@ eoFunctorBase::procedure_tag functor_category(const eoF<R>&)
return eoFunctorBase::procedure_tag(); return eoFunctorBase::procedure_tag();
} }
/** /**
Basic Unary Functor. Derive from this class when defining Basic Unary Functor. Derive from this class when defining
any unary function. First template argument is the first_argument_type, any unary function. First template argument is the first_argument_type,
second result_type. second result_type.
Argument and result types can be any type including void for Argument and result types can be any type including void for
@ -124,12 +124,12 @@ public :
/// tag to identify a procedure in compile time function selection @see functor_category /// tag to identify a procedure in compile time function selection @see functor_category
static eoFunctorBase::unary_function_tag functor_category() static eoFunctorBase::unary_function_tag functor_category()
{ {
return eoFunctorBase::unary_function_tag(); return eoFunctorBase::unary_function_tag();
} }
}; };
/** /**
Overloaded function that can help in the compile time detection Overloaded function that can help in the compile time detection
of the type of functor we are dealing with of the type of functor we are dealing with
@see eoCounter, make_counter @see eoCounter, make_counter
*/ */
@ -140,8 +140,8 @@ eoFunctorBase::unary_function_tag functor_category(const eoUF<A1, R>&)
} }
/** /**
Basic Binary Functor. Derive from this class when defining Basic Binary Functor. Derive from this class when defining
any binary function. First template argument is result_type, second any binary function. First template argument is result_type, second
is first_argument_type, third is second_argument_type. is first_argument_type, third is second_argument_type.
Argument and result types can be any type including void for Argument and result types can be any type including void for
@ -153,7 +153,7 @@ class eoBF : public eoFunctorBase, public std::binary_function<A1, A2, R>
public : public :
/// virtual dtor here so there is no need to define it in derived classes /// virtual dtor here so there is no need to define it in derived classes
virtual ~eoBF() {} virtual ~eoBF() {}
//typedef R result_type; //typedef R result_type;
//typedef A1 first_argument_type; //typedef A1 first_argument_type;
//typedef A2 second_argument_type; //typedef A2 second_argument_type;
@ -164,12 +164,12 @@ public :
/// tag to identify a procedure in compile time function selection @see functor_category /// tag to identify a procedure in compile time function selection @see functor_category
static eoFunctorBase::binary_function_tag functor_category() static eoFunctorBase::binary_function_tag functor_category()
{ {
return eoFunctorBase::binary_function_tag(); return eoFunctorBase::binary_function_tag();
} }
}; };
/** /**
Overloaded function that can help in the compile time detection Overloaded function that can help in the compile time detection
of the type of functor we are dealing with of the type of functor we are dealing with
@see eoCounter, make_counter @see eoCounter, make_counter
*/ */

View file

@ -1,9 +1,9 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoG3Replacement.h eoG3Replacement.h
(c) Maarten Keijzer, Marc Schoenauer, 2002 (c) Maarten Keijzer, Marc Schoenauer, 2002
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -52,34 +52,34 @@ class eoG3Replacement : public eoReplacement<EOT>
public: public:
eoG3Replacement(eoHowMany _howManyEliminatedParents = eoHowMany(2, false)) : eoG3Replacement(eoHowMany _howManyEliminatedParents = eoHowMany(2, false)) :
// split truncates the parents and returns eliminated parents // split truncates the parents and returns eliminated parents
split(_howManyEliminatedParents, true), split(_howManyEliminatedParents, true),
// reduce truncates the offpsring and does not return eliminated guys // reduce truncates the offpsring and does not return eliminated guys
reduce(-_howManyEliminatedParents, false) reduce(-_howManyEliminatedParents, false)
{} {}
void operator()(eoPop<EOT> & _parents, eoPop<EOT> & _offspring) void operator()(eoPop<EOT> & _parents, eoPop<EOT> & _offspring)
{ {
eoPop<EOT> temp; eoPop<EOT> temp;
split(_parents, temp); split(_parents, temp);
unsigned toKeep = temp.size(); // how many to keep from merged populations unsigned toKeep = temp.size(); // how many to keep from merged populations
// merge temp into offspring // merge temp into offspring
plus(temp, _offspring); // add temp to _offspring (a little inconsistent!) plus(temp, _offspring); // add temp to _offspring (a little inconsistent!)
// reduce merged // reduce merged
reduce(_offspring, temp); // temp dummy arg. will not be modified reduce(_offspring, temp); // temp dummy arg. will not be modified
// minimla check: // minimla check:
if (_offspring.size() != toKeep) if (_offspring.size() != toKeep)
{ {
std::cerr << "Les tailles " << _offspring.size() << " " << toKeep << std::endl; std::cerr << "Les tailles " << _offspring.size() << " " << toKeep << std::endl;
throw std::runtime_error("eoG3Replacement: wrong number of remaining offspring"); throw std::runtime_error("eoG3Replacement: wrong number of remaining offspring");
} }
// and put back into _parents // and put back into _parents
plus(_offspring, _parents); plus(_offspring, _parents);
} }
private: private:
eoLinearTruncateSplit<EOT> split; // few parents to truncate -> linear eoLinearTruncateSplit<EOT> split; // few parents to truncate -> linear
eoTruncateSplit<EOT> reduce; // supposedly many offspring to truncate eoTruncateSplit<EOT> reduce; // supposedly many offspring to truncate
eoPlus<EOT> plus; eoPlus<EOT> plus;
}; };

View file

@ -32,7 +32,7 @@
/** /**
* Update an inertia weight by assigning it a Gaussian randomized value * Update an inertia weight by assigning it a Gaussian randomized value
* (used for the velocity in particle swarm optimization). * (used for the velocity in particle swarm optimization).
* *
* @ingroup Variators * @ingroup Variators

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoGenContinue.h // eoGenContinue.h
// (c) GeNeura Team, 1999 // (c) GeNeura Team, 1999
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -29,7 +29,7 @@
#include <utils/eoParam.h> #include <utils/eoParam.h>
#include <utils/eoLogger.h> #include <utils/eoLogger.h>
/** /**
Generational continuator: continues until a number of generations is reached Generational continuator: continues until a number of generations is reached
@ingroup Continuators @ingroup Continuators
@ -41,68 +41,68 @@ public:
/// Ctor for setting a /// Ctor for setting a
eoGenContinue( unsigned long _totalGens) eoGenContinue( unsigned long _totalGens)
: eoValueParam<unsigned>(0, "Generations", "Generations"), : eoValueParam<unsigned>(0, "Generations", "Generations"),
repTotalGenerations( _totalGens ), repTotalGenerations( _totalGens ),
thisGenerationPlaceHolder(0), thisGenerationPlaceHolder(0),
thisGeneration(thisGenerationPlaceHolder) thisGeneration(thisGenerationPlaceHolder)
{}; {};
/// Ctor for enabling the save/load the no. of generations counted /// Ctor for enabling the save/load the no. of generations counted
eoGenContinue( unsigned long _totalGens, unsigned long& _currentGen) eoGenContinue( unsigned long _totalGens, unsigned long& _currentGen)
: eoValueParam<unsigned>(0, "Generations", "Generations"), : eoValueParam<unsigned>(0, "Generations", "Generations"),
repTotalGenerations( _totalGens ), repTotalGenerations( _totalGens ),
thisGenerationPlaceHolder(0), thisGenerationPlaceHolder(0),
thisGeneration(_currentGen) thisGeneration(_currentGen)
{}; {};
/** Returns false when a certain number of generations is /** Returns false when a certain number of generations is
* reached */ * reached */
virtual bool operator() ( const eoPop<EOT>& _vEO ) { virtual bool operator() ( const eoPop<EOT>& _vEO ) {
(void)_vEO; (void)_vEO;
thisGeneration++; thisGeneration++;
value() = thisGeneration; value() = thisGeneration;
if (thisGeneration >= repTotalGenerations) if (thisGeneration >= repTotalGenerations)
{ {
eo::log << eo::logging << "STOP in eoGenContinue: Reached maximum number of generations [" << thisGeneration << "/" << repTotalGenerations << "]\n"; eo::log << eo::logging << "STOP in eoGenContinue: Reached maximum number of generations [" << thisGeneration << "/" << repTotalGenerations << "]\n";
return false; return false;
} }
return true; return true;
} }
/** Sets the number of generations to reach /** Sets the number of generations to reach
and sets the current generation to 0 (the begin) and sets the current generation to 0 (the begin)
@todo replace this by an "init" method @todo replace this by an "init" method
*/ */
virtual void totalGenerations( unsigned long _tg ) { virtual void totalGenerations( unsigned long _tg ) {
repTotalGenerations = _tg; repTotalGenerations = _tg;
thisGeneration = 0; thisGeneration = 0;
}; };
/** Returns the number of generations to reach*/ /** Returns the number of generations to reach*/
virtual unsigned long totalGenerations( ) virtual unsigned long totalGenerations( )
{ {
return repTotalGenerations; return repTotalGenerations;
}; };
virtual std::string className(void) const { return "eoGenContinue"; } virtual std::string className(void) const { return "eoGenContinue"; }
/** Read from a stream /** Read from a stream
* @param __is the istream to read from * @param __is the istream to read from
*/ */
void readFrom (std :: istream & __is) { void readFrom (std :: istream & __is) {
__is >> thisGeneration; /* Loading the number of generations counted */ __is >> thisGeneration; /* Loading the number of generations counted */
} }
/** Print on a stream /** Print on a stream
* @param __os the ostream to print on * @param __os the ostream to print on
*/ */
void printOn (std :: ostream & __os) const { void printOn (std :: ostream & __os) const {
__os << thisGeneration << std :: endl; /* Saving the number of generations counted */ __os << thisGeneration << std :: endl; /* Saving the number of generations counted */
} }
private: private:
@ -112,4 +112,3 @@ private:
}; };
#endif #endif

View file

@ -53,7 +53,7 @@ the original population, is an instantiation of the next population and
has often a selection function embedded in it to select new individuals. has often a selection function embedded in it to select new individuals.
Note that the actual work is performed in the apply function. Note that the actual work is performed in the apply function.
AND that the apply function is responsible for invalidating AND that the apply function is responsible for invalidating
the object if necessary the object if necessary
*/ */
template <class EOT> template <class EOT>
@ -72,8 +72,8 @@ class eoGenOp : public eoOp<EOT>, public eoUF<eoPopulator<EOT> &, void>
void operator()(eoPopulator<EOT>& _pop) void operator()(eoPopulator<EOT>& _pop)
{ {
_pop.reserve( max_production() ); _pop.reserve( max_production() );
apply(_pop); apply(_pop);
} }
//protected : //protected :
@ -114,10 +114,10 @@ class eoBinGenOp : public eoGenOp<EOT>
public: public:
eoBinGenOp(eoBinOp<EOT>& _op) : op(_op) {} eoBinGenOp(eoBinOp<EOT>& _op) : op(_op) {}
unsigned max_production(void) { return 1; } unsigned max_production(void) { return 1; }
/** do the work: get 2 individuals from the population, modifies /** do the work: get 2 individuals from the population, modifies
only one (it's a eoBinOp) only one (it's a eoBinOp)
*/ */
void apply(eoPopulator<EOT>& _pop) void apply(eoPopulator<EOT>& _pop)
{ {
@ -169,9 +169,9 @@ class eoQuadGenOp : public eoGenOp<EOT>
void apply(eoPopulator<EOT>& _pop) void apply(eoPopulator<EOT>& _pop)
{ {
EOT& a = *_pop; EOT& a = *_pop;
EOT& b = *++_pop; EOT& b = *++_pop;
if(op(a, b)) if(op(a, b))
{ {
a.invalidate(); a.invalidate();

View file

@ -1,9 +1,9 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoGeneralBreeder.h // eoGeneralBreeder.h
// (c) Maarten Keijzer and Marc Schoenauer, 2001 // (c) Maarten Keijzer and Marc Schoenauer, 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -58,7 +58,7 @@ class eoGeneralBreeder: public eoBreed<EOT>
eoGeneralBreeder( eoGeneralBreeder(
eoSelectOne<EOT>& _select, eoSelectOne<EOT>& _select,
eoGenOp<EOT>& _op, eoGenOp<EOT>& _op,
double _rate=1.0, double _rate=1.0,
bool _interpret_as_rate = true) : bool _interpret_as_rate = true) :
select( _select ), op(_op), howMany(_rate, _interpret_as_rate) {} select( _select ), op(_op), howMany(_rate, _interpret_as_rate) {}
@ -71,7 +71,7 @@ class eoGeneralBreeder: public eoBreed<EOT>
eoGeneralBreeder( eoGeneralBreeder(
eoSelectOne<EOT>& _select, eoSelectOne<EOT>& _select,
eoGenOp<EOT>& _op, eoGenOp<EOT>& _op,
eoHowMany _howMany ) : eoHowMany _howMany ) :
select( _select ), op(_op), howMany(_howMany) {} select( _select ), op(_op), howMany(_howMany) {}
/** The breeder: simply calls the genOp on a selective populator! /** The breeder: simply calls the genOp on a selective populator!
@ -87,10 +87,10 @@ class eoGeneralBreeder: public eoBreed<EOT>
eoSelectivePopulator<EOT> it(_parents, _offspring, select); eoSelectivePopulator<EOT> it(_parents, _offspring, select);
while (_offspring.size() < target) while (_offspring.size() < target)
{ {
op(it); op(it);
++it; ++it;
} }
_offspring.resize(target); // you might have generated a few more _offspring.resize(target); // you might have generated a few more
} }
@ -105,4 +105,3 @@ class eoGeneralBreeder: public eoBreed<EOT>
}; };
#endif #endif

View file

@ -43,24 +43,24 @@
*/ */
/** @{*/ /** @{*/
/** /**
Base (name) class for Initialization of chromosomes, used in a population Base (name) class for Initialization of chromosomes, used in a population
contructor. It is derived from eoMonOp, so it can be used contructor. It is derived from eoMonOp, so it can be used
inside the algorithm as well. inside the algorithm as well.
@see eoPop @see eoPop
*/ */
template <class EOT> template <class EOT>
class eoInit : public eoUF<EOT&, void> class eoInit : public eoUF<EOT&, void>
{ {
public: public:
/** className: Mandatory because of eoCombinedInit. /** className: Mandatory because of eoCombinedInit.
SHould be pure virtual, but then we should go over the whole SHould be pure virtual, but then we should go over the whole
* code to write the method for all derived classes ... MS 16/7/04 */ * code to write the method for all derived classes ... MS 16/7/04 */
virtual std::string className(void) const { return "eoInit"; } virtual std::string className(void) const { return "eoInit"; }
}; };
/** turning an eoInit into a generator /** turning an eoInit into a generator
* probably we should only use genrators - and suppress eoInit ??? * probably we should only use genrators - and suppress eoInit ???
* MS - July 2001 * MS - July 2001
*/ */
@ -115,13 +115,13 @@ template <class EOT>
class eoInitVariableLength: public eoInit<EOT> class eoInitVariableLength: public eoInit<EOT>
{ {
public: public:
typedef typename EOT::AtomType AtomType; typedef typename EOT::AtomType AtomType;
// /** Ctor from a generator */ // /** Ctor from a generator */
// eoInitVariableLength(unsigned _minSize, unsigned _maxSize, eoF<typename EOT::AtomType> & _generator = Gen()) // eoInitVariableLength(unsigned _minSize, unsigned _maxSize, eoF<typename EOT::AtomType> & _generator = Gen())
// : offset(_minSize), extent(_maxSize - _minSize), // : offset(_minSize), extent(_maxSize - _minSize),
// repGenerator( eoInitGenerator<typename EOT::AtomType>(*(new eoInit<EOT>)) ), // repGenerator( eoInitGenerator<typename EOT::AtomType>(*(new eoInit<EOT>)) ),
// generator(_generator) // generator(_generator)
// { // {
// if (_minSize >= _maxSize) // if (_minSize >= _maxSize)
// throw std::logic_error("eoInitVariableLength: minSize larger or equal to maxSize"); // throw std::logic_error("eoInitVariableLength: minSize larger or equal to maxSize");
@ -170,11 +170,11 @@ class eoInitPermutation: public eoInit<EOT>
virtual void operator()(EOT& chrom) virtual void operator()(EOT& chrom)
{ {
chrom.resize(chromSize); chrom.resize(chromSize);
for(unsigned idx=0;idx <chrom.size();idx++) for(unsigned idx=0;idx <chrom.size();idx++)
chrom[idx]=idx+startFrom; chrom[idx]=idx+startFrom;
std::random_shuffle(chrom.begin(), chrom.end(),gen); std::random_shuffle(chrom.begin(), chrom.end(),gen);
chrom.invalidate(); chrom.invalidate();
} }
@ -191,7 +191,7 @@ class eoInitPermutation: public eoInit<EOT>
eoInitAdaptor changes the place in the hierarchy eoInitAdaptor changes the place in the hierarchy
from eoInit to eoMonOp. This is mainly a type conversion, from eoInit to eoMonOp. This is mainly a type conversion,
nothing else nothing else
@see eoInit, eoMonOp @see eoInit, eoMonOp
*/ */
template <class EOT> template <class EOT>

View file

@ -54,9 +54,9 @@ public :
}; };
/** /**
Base (name) class for Initialization of algorithm PSO Base (name) class for Initialization of algorithm PSO
@see eoInitializerBase eoUF apply @see eoInitializerBase eoUF apply
*/ */
template <class POT> class eoInitializer : public eoInitializerBase <POT> template <class POT> class eoInitializer : public eoInitializerBase <POT>
{ {
@ -115,9 +115,9 @@ public:
private : private :
/* /*
@param proc First evaluation @param proc First evaluation
@param initVelo Initialization of the velocity @param initVelo Initialization of the velocity
@param initBest Initialization of the best @param initBest Initialization of the best
*/ */
eoUF<POT&, void>& proc; eoUF<POT&, void>& proc;
eoVelocityInit < POT > & initVelo; eoVelocityInit < POT > & initVelo;
@ -145,4 +145,3 @@ class eoDummy : public eoUF<POT&, void>
#endif #endif
/** @} */ /** @} */

View file

@ -17,7 +17,7 @@
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: thomas.legrand@lifl.fr Contact: thomas.legrand@lifl.fr
todos@geneura.ugr.es, http://geneura.ugr.es todos@geneura.ugr.es, http://geneura.ugr.es
mkeijzer@dhi.dk mkeijzer@dhi.dk
*/ */

View file

@ -55,16 +55,16 @@ public:
/** Full constructor: Bounds and bound modifier required /** Full constructor: Bounds and bound modifier required
* @param _topology - The topology to get the global/local/other best * @param _topology - The topology to get the global/local/other best
* @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only).
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
*/ */
eoIntegerVelocity (eoTopology < POT > & _topology, eoIntegerVelocity (eoTopology < POT > & _topology,
const VelocityType & _c1, const VelocityType & _c1,
const VelocityType & _c2, const VelocityType & _c2,
const VelocityType & _c3, const VelocityType & _c3,
eoRealVectorBounds & _bounds, eoRealVectorBounds & _bounds,
@ -81,10 +81,10 @@ public:
/** Constructor: No bound updater required <-> fixed bounds /** Constructor: No bound updater required <-> fixed bounds
* @param _topology - The topology to get the global/local/other best * @param _topology - The topology to get the global/local/other best
* @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities.
* If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ?
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
*/ */
@ -105,9 +105,9 @@ public:
/** Constructor: Neither bounds nor bound updater required <-> free velocity /** Constructor: Neither bounds nor bound updater required <-> free velocity
* @param _topology the topology to use * @param _topology the topology to use
* @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType
* @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType
* @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType
* @param _gen - The eo random generator, default=rng * @param _gen - The eo random generator, default=rng
*/ */
eoIntegerVelocity (eoTopology < POT > & _topology, eoIntegerVelocity (eoTopology < POT > & _topology,
@ -116,7 +116,7 @@ public:
const VelocityType & _c3, const VelocityType & _c3,
eoRng & _gen = rng): eoRng & _gen = rng):
topology(_topology), topology(_topology),
c1 (_c1), c1 (_c1),
c2 (_c2), c2 (_c2),
c3 (_c3), c3 (_c3),
bounds(*(new eoRealVectorNoBounds(0))), bounds(*(new eoRealVectorNoBounds(0))),
@ -167,30 +167,29 @@ public:
{ {
topology.updateNeighborhood(_po,_indice); topology.updateNeighborhood(_po,_indice);
} }
//! eoTopology<POT> getTopology //! eoTopology<POT> getTopology
//! @return topology //! @return topology
eoTopology<POT> & getTopology () eoTopology<POT> & getTopology ()
{ {
return topology; return topology;
} }
protected: protected:
eoTopology < POT > & topology; eoTopology < POT > & topology;
const VelocityType & c1; // social/cognitive coefficient const VelocityType & c1; // social/cognitive coefficient
const VelocityType & c2; // social/cognitive coefficient const VelocityType & c2; // social/cognitive coefficient
const VelocityType & c3; // social/cognitive coefficient const VelocityType & c3; // social/cognitive coefficient
eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type.
eoRealBoundModifier & bndsModifier; eoRealBoundModifier & bndsModifier;
eoRng & gen; // the random generator
eoRng & gen; // the random generator
// If the bound modifier doesn't need to be used, use the dummy instance // If the bound modifier doesn't need to be used, use the dummy instance
eoDummyRealBoundModifier dummyModifier; eoDummyRealBoundModifier dummyModifier;
}; };
#endif /*EOINTEGERVELOCITY_H */ #endif /*EOINTEGERVELOCITY_H */

View file

@ -57,7 +57,7 @@ class eoInvalidateMonOp : public eoMonOp<EOT>
return true; return true;
} }
return false; return false;
} }
private: private:

View file

@ -48,7 +48,7 @@ public:
/** /**
* Build the topology made of _neighborhoodSize neighborhoods. * Build the topology made of _neighborhoodSize neighborhoods.
* @param _neighborhoodSize - The size of each neighborhood. * @param _neighborhoodSize - The size of each neighborhood.
*/ */
eoLinearTopology (unsigned _neighborhoodSize):neighborhoodSize (_neighborhoodSize),isSetup(false){} eoLinearTopology (unsigned _neighborhoodSize):neighborhoodSize (_neighborhoodSize),isSetup(false){}
@ -119,7 +119,7 @@ public:
*/ */
unsigned retrieveNeighborhoodByIndice(unsigned _indice) unsigned retrieveNeighborhoodByIndice(unsigned _indice)
{ {
unsigned i=0; unsigned i=0;
for (i=0;i< neighborhoods.size();i++) for (i=0;i< neighborhoods.size();i++)
{ {
if (neighborhoods[i].contains(_indice)) if (neighborhoods[i].contains(_indice))
@ -131,7 +131,7 @@ public:
} }
/** /**
* Update the neighborhood: update the particle's best fitness and the best particle * Update the neighborhood: update the particle's best fitness and the best particle
* of the corresponding neighborhood. * of the corresponding neighborhood.
*/ */
void updateNeighborhood(POT & _po,unsigned _indice) void updateNeighborhood(POT & _po,unsigned _indice)
@ -139,9 +139,9 @@ public:
// update the best fitness of the particle // update the best fitness of the particle
if (_po.fitness() > _po.best()) if (_po.fitness() > _po.best())
{ {
_po.best(_po.fitness()); _po.best(_po.fitness());
for(unsigned i=0;i<_po.size();i++) for(unsigned i=0;i<_po.size();i++)
_po.bestPositions[i]=_po[i]; _po.bestPositions[i]=_po[i];
} }
// update the best in its neighborhood // update the best in its neighborhood
@ -166,27 +166,27 @@ public:
/* /*
* Return the global best of the topology * Return the global best of the topology
*/ */
virtual POT & globalBest() virtual POT & globalBest()
{ {
POT gBest,tmp; POT gBest,tmp;
unsigned indGlobalBest=0; unsigned indGlobalBest=0;
if(neighborhoods.size()==1) if(neighborhoods.size()==1)
return neighborhoods[0].best(); return neighborhoods[0].best();
gBest=neighborhoods[0].best(); gBest=neighborhoods[0].best();
for(unsigned i=1;i<neighborhoods.size();i++) for(unsigned i=1;i<neighborhoods.size();i++)
{ {
tmp=neighborhoods[i].best(); tmp=neighborhoods[i].best();
if(gBest.best() < tmp.best()) if(gBest.best() < tmp.best())
{ {
gBest=tmp; gBest=tmp;
indGlobalBest=i; indGlobalBest=i;
} }
} }
return neighborhoods[indGlobalBest].best(); return neighborhoods[indGlobalBest].best();
} }
/** /**
@ -207,19 +207,11 @@ public:
protected: protected:
std::vector<eoSocialNeighborhood<POT> > neighborhoods; std::vector<eoSocialNeighborhood<POT> > neighborhoods;
unsigned neighborhoodSize; // the size of each neighborhood unsigned neighborhoodSize; // the size of each neighborhood
bool isSetup; bool isSetup;
}; };
#endif /*EOLINEARTOPOLOGY_H_ */ #endif /*EOLINEARTOPOLOGY_H_ */

View file

@ -1,9 +1,9 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoMGGReplacement.h eoMGGReplacement.h
(c) Maarten Keijzer, Marc Schoenauer, 2002 (c) Maarten Keijzer, Marc Schoenauer, 2002
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -52,18 +52,18 @@ class eoMGGReplacement : public eoReplacement<EOT>
{ {
public: public:
eoMGGReplacement(eoHowMany _howManyEliminatedParents = eoHowMany(2, false), eoMGGReplacement(eoHowMany _howManyEliminatedParents = eoHowMany(2, false),
unsigned _tSize=2) : unsigned _tSize=2) :
// split truncates the parents and returns eliminated parents // split truncates the parents and returns eliminated parents
split(_howManyEliminatedParents, true), split(_howManyEliminatedParents, true),
tSize(_tSize) tSize(_tSize)
{ {
if (tSize < 2) if (tSize < 2)
{ {
eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncateSplit adjusted to 2" << std::endl; eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncateSplit adjusted to 2" << std::endl;
tSize = 2; tSize = 2;
} }
} }
void operator()(eoPop<EOT> & _parents, eoPop<EOT> & _offspring) void operator()(eoPop<EOT> & _parents, eoPop<EOT> & _offspring)
{ {
eoPop<EOT> temp; eoPop<EOT> temp;
@ -71,7 +71,7 @@ public:
unsigned toKeep = temp.size(); // how many to keep from merged populations unsigned toKeep = temp.size(); // how many to keep from merged populations
// minimal check // minimal check
if (toKeep < 2) if (toKeep < 2)
throw std::runtime_error("Not enough parents killed in eoMGGReplacement"); throw std::runtime_error("Not enough parents killed in eoMGGReplacement");
// select best offspring // select best offspring
typename eoPop<EOT>::iterator it = _offspring.it_best_element(); typename eoPop<EOT>::iterator it = _offspring.it_best_element();
@ -82,21 +82,21 @@ public:
// merge temp into offspring // merge temp into offspring
plus(temp, _offspring); plus(temp, _offspring);
// repeatedly add selected offspring to parents // repeatedly add selected offspring to parents
for (unsigned i=0; i<toKeep-1; i++) for (unsigned i=0; i<toKeep-1; i++)
{ {
// select // select
it = deterministic_tournament(_offspring.begin(), _offspring.end(), tSize); it = deterministic_tournament(_offspring.begin(), _offspring.end(), tSize);
// add to parents // add to parents
_parents.push_back(*it); _parents.push_back(*it);
// remove from offspring // remove from offspring
_offspring.erase(it); _offspring.erase(it);
} }
} }
private: private:
eoLinearTruncateSplit<EOT> split; // few parents to truncate -> linear eoLinearTruncateSplit<EOT> split; // few parents to truncate -> linear
eoPlus<EOT> plus; eoPlus<EOT> plus;
unsigned int tSize; unsigned int tSize;
}; };

View file

@ -4,7 +4,7 @@
// eoMerge.h // eoMerge.h
// Base class for elitist-merging classes // Base class for elitist-merging classes
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -36,13 +36,13 @@
#include <utils/eoLogger.h> #include <utils/eoLogger.h>
/** /**
* eoMerge: Base class for elitist replacement algorithms. * eoMerge: Base class for elitist replacement algorithms.
* Merges the old population (first argument), with the new generation * Merges the old population (first argument), with the new generation
* *
* Its signature is exactly * Its signature is exactly
* that of the selection base eoSelect, but its purpose is to merge the * that of the selection base eoSelect, but its purpose is to merge the
* two populations into one (the second argument). * two populations into one (the second argument).
* Note that the algorithms assume that the second argument denotes the * Note that the algorithms assume that the second argument denotes the
* next generation. * next generation.
* *
* @ingroup Core * @ingroup Core
@ -55,7 +55,7 @@ template<class Chrom> class eoMerge: public eoBF<const eoPop<Chrom>&, eoPop<Chro
/** /**
Straightforward elitism class, specify the number of individuals to copy Straightforward elitism class, specify the number of individuals to copy
into new geneneration or the rate w.r.t. pop size into new geneneration or the rate w.r.t. pop size
@ingroup Replacors @ingroup Replacors
*/ */
template <class EOT> class eoElitism : public eoMerge<EOT> template <class EOT> class eoElitism : public eoMerge<EOT>
@ -66,42 +66,42 @@ public :
{ {
if (_interpret_as_rate) if (_interpret_as_rate)
{ {
if ( (_rate<0) || (_rate>1) ) if ( (_rate<0) || (_rate>1) )
throw std::logic_error("eoElitism: rate shoud be in [0,1]"); throw std::logic_error("eoElitism: rate shoud be in [0,1]");
rate = _rate; rate = _rate;
} }
else else
{ {
if (_rate<0) if (_rate<0)
throw std::logic_error("Negative number of offspring in eoElitism!"); throw std::logic_error("Negative number of offspring in eoElitism!");
combien = (unsigned int)_rate; combien = (unsigned int)_rate;
if (combien != _rate) if (combien != _rate)
eo::log << eo::warnings << "Warning: Number of guys to merge in eoElitism was rounded" << std::endl; eo::log << eo::warnings << "Warning: Number of guys to merge in eoElitism was rounded" << std::endl;
} }
} }
void operator()(const eoPop<EOT>& _pop, eoPop<EOT>& _offspring) void operator()(const eoPop<EOT>& _pop, eoPop<EOT>& _offspring)
{ {
if ((combien == 0) && (rate == 0.0)) if ((combien == 0) && (rate == 0.0))
return; return;
unsigned combienLocal; unsigned combienLocal;
if (combien == 0) // rate is specified if (combien == 0) // rate is specified
combienLocal = (unsigned int) (rate * _pop.size()); combienLocal = (unsigned int) (rate * _pop.size());
else else
combienLocal = combien; combienLocal = combien;
if (combienLocal > _pop.size()) if (combienLocal > _pop.size())
throw std::logic_error("Elite larger than population"); throw std::logic_error("Elite larger than population");
std::vector<const EOT*> result; std::vector<const EOT*> result;
_pop.nth_element(combienLocal, result); _pop.nth_element(combienLocal, result);
for (size_t i = 0; i < result.size(); ++i) for (size_t i = 0; i < result.size(); ++i)
{ {
_offspring.push_back(*result[i]); _offspring.push_back(*result[i]);
} }
} }
private : private :
double rate; double rate;
unsigned combien; unsigned combien;
@ -139,4 +139,4 @@ template <class EOT> class eoPlus : public eoMerge<EOT>
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif #endif

View file

@ -1,9 +1,9 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoMergeReduce.h eoMergeReduce.h
(c) Maarten Keijzer, GeNeura Team, 2000 (c) Maarten Keijzer, GeNeura Team, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -34,7 +34,7 @@
#include <eoReplacement.h> #include <eoReplacement.h>
#include <utils/eoHowMany.h> #include <utils/eoHowMany.h>
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** /**
Replacement strategies that combine en eoMerge and an eoReduce. Replacement strategies that combine en eoMerge and an eoReduce.
@class eoMergeReduce, the base (pure abstract) class @class eoMergeReduce, the base (pure abstract) class
@ -43,7 +43,7 @@ Replacement strategies that combine en eoMerge and an eoReduce.
*/ */
/** /**
eoMergeReduce: abstract replacement strategy that is just an application of eoMergeReduce: abstract replacement strategy that is just an application of
an embedded merge, followed by an embedded reduce an embedded merge, followed by an embedded reduce
@ingroup Replacors @ingroup Replacors
*/ */
@ -59,7 +59,7 @@ class eoMergeReduce : public eoReplacement<EOT>
{ {
merge(_parents, _offspring); // parents untouched, result in offspring merge(_parents, _offspring); // parents untouched, result in offspring
reduce(_offspring, _parents.size()); reduce(_offspring, _parents.size());
_parents.swap(_offspring); _parents.swap(_offspring);
} }
private : private :
@ -98,7 +98,7 @@ class eoCommaReplacement : public eoMergeReduce<EOT>
}; };
/** /**
EP type of replacement strategy: first add parents to population, EP type of replacement strategy: first add parents to population,
then truncate using EP tournament then truncate using EP tournament
@ingroup Replacors @ingroup Replacors
*/ */

View file

@ -61,35 +61,35 @@ class eoNDSorting : public eoPerf2WorthCached<EOT, double>
void calculate_worths(const eoPop<EOT>& _pop) void calculate_worths(const eoPop<EOT>& _pop)
{ {
// resize the worths beforehand // resize the worths beforehand
value().resize(_pop.size()); value().resize(_pop.size());
typedef typename EOT::Fitness::fitness_traits traits; typedef typename EOT::Fitness::fitness_traits traits;
switch (traits::nObjectives()) switch (traits::nObjectives())
{ {
case 1: case 1:
{ {
one_objective(_pop); one_objective(_pop);
return; return;
} }
case 2: case 2:
{ {
two_objectives(_pop); two_objectives(_pop);
return; return;
} }
default : default :
{ {
m_objectives(_pop); m_objectives(_pop);
} }
} }
} }
private : private :
/** used in fast nondominated sorting /** used in fast nondominated sorting
DummyEO is just a storage place for fitnesses and DummyEO is just a storage place for fitnesses and
to store the original index to store the original index
*/ */
class DummyEO : public EO<typename EOT::Fitness> class DummyEO : public EO<typename EOT::Fitness>
{ {
@ -98,8 +98,8 @@ private :
void one_objective(const eoPop<EOT>& _pop) void one_objective(const eoPop<EOT>& _pop)
{ {
unsigned i; unsigned i;
std::vector<DummyEO> tmp_pop; std::vector<DummyEO> tmp_pop;
tmp_pop.resize(_pop.size()); tmp_pop.resize(_pop.size());
// copy pop to dummy population (only need the fitnesses) // copy pop to dummy population (only need the fitnesses)
@ -109,14 +109,14 @@ private :
tmp_pop[i].index = i; tmp_pop[i].index = i;
} }
std::sort(tmp_pop.begin(), tmp_pop.end(), std::greater<DummyEO>()); std::sort(tmp_pop.begin(), tmp_pop.end(), std::greater<DummyEO>());
for (i = 0; i < _pop.size(); ++i) for (i = 0; i < _pop.size(); ++i)
{ {
value()[tmp_pop[i].index] = _pop.size() - i; // set rank value()[tmp_pop[i].index] = _pop.size() - i; // set rank
} }
// no point in calculcating niche penalty, as every distinct fitness value has a distinct rank // no point in calculcating niche penalty, as every distinct fitness value has a distinct rank
} }
/** /**
@ -139,134 +139,134 @@ private :
void two_objectives(const eoPop<EOT>& _pop) void two_objectives(const eoPop<EOT>& _pop)
{ {
unsigned i; unsigned i;
typedef typename EOT::Fitness::fitness_traits traits; typedef typename EOT::Fitness::fitness_traits traits;
assert(traits::nObjectives() == 2); assert(traits::nObjectives() == 2);
std::vector<unsigned> sort1(_pop.size()); // index into population sorted on first objective std::vector<unsigned> sort1(_pop.size()); // index into population sorted on first objective
for (i = 0; i < _pop.size(); ++i) for (i = 0; i < _pop.size(); ++i)
{ {
sort1[i] = i; sort1[i] = i;
} }
std::sort(sort1.begin(), sort1.end(), Sorter(_pop)); std::sort(sort1.begin(), sort1.end(), Sorter(_pop));
// Ok, now the meat of the algorithm // Ok, now the meat of the algorithm
unsigned last_front = 0; unsigned last_front = 0;
double max1 = -1e+20; double max1 = -1e+20;
for (i = 0; i < _pop.size(); ++i) for (i = 0; i < _pop.size(); ++i)
{ {
max1 = std::max(max1, _pop[i].fitness()[1]); max1 = std::max(max1, _pop[i].fitness()[1]);
} }
max1 = max1 + 1.0; // add a bit to it so that it is a real upperbound max1 = max1 + 1.0; // add a bit to it so that it is a real upperbound
unsigned prev_front = 0; unsigned prev_front = 0;
std::vector<double> d; std::vector<double> d;
d.resize(_pop.size(), max1); // initialize with the value max1 everywhere d.resize(_pop.size(), max1); // initialize with the value max1 everywhere
std::vector<std::vector<unsigned> > fronts(_pop.size()); // to store indices into the front std::vector<std::vector<unsigned> > fronts(_pop.size()); // to store indices into the front
for (i = 0; i < _pop.size(); ++i) for (i = 0; i < _pop.size(); ++i)
{ {
unsigned index = sort1[i]; unsigned index = sort1[i];
// check for clones and delete them // check for clones and delete them
if (i > 0) if (i > 0)
{ {
unsigned prev = sort1[i-1]; unsigned prev = sort1[i-1];
if ( _pop[index].fitness() == _pop[prev].fitness()) if ( _pop[index].fitness() == _pop[prev].fitness())
{ // it's a clone, give it the worst rank! { // it's a clone, give it the worst rank!
if (nasty_declone_flag_that_only_is_implemented_for_two_objectives) if (nasty_declone_flag_that_only_is_implemented_for_two_objectives)
//declone //declone
fronts.back().push_back(index); fronts.back().push_back(index);
else // assign it the rank of the previous else // assign it the rank of the previous
fronts[prev_front].push_back(index); fronts[prev_front].push_back(index);
continue; continue;
} }
} }
double value2 = _pop[index].fitness()[1]; double value2 = _pop[index].fitness()[1];
if (traits::maximizing(1)) if (traits::maximizing(1))
value2 = max1 - value2; value2 = max1 - value2;
// perform binary search using std::upper_bound, a log n operation for each member // perform binary search using std::upper_bound, a log n operation for each member
std::vector<double>::iterator it = std::vector<double>::iterator it =
std::upper_bound(d.begin(), d.begin() + last_front, value2); std::upper_bound(d.begin(), d.begin() + last_front, value2);
unsigned front = unsigned(it - d.begin()); unsigned front = unsigned(it - d.begin());
if (front == last_front) ++last_front; if (front == last_front) ++last_front;
assert(it != d.end()); assert(it != d.end());
*it = value2; //update d *it = value2; //update d
fronts[front].push_back(index); // add it to the front fronts[front].push_back(index); // add it to the front
prev_front = front; prev_front = front;
} }
// ok, and finally the niche penalty // ok, and finally the niche penalty
for (i = 0; i < fronts.size(); ++i) for (i = 0; i < fronts.size(); ++i)
{ {
if (fronts[i].size() == 0) continue; if (fronts[i].size() == 0) continue;
// Now we have the indices to the current front in current_front, do the niching // Now we have the indices to the current front in current_front, do the niching
std::vector<double> niche_count = niche_penalty(fronts[i], _pop); std::vector<double> niche_count = niche_penalty(fronts[i], _pop);
// Check whether the derived class was nice // Check whether the derived class was nice
if (niche_count.size() != fronts[i].size()) if (niche_count.size() != fronts[i].size())
{ {
throw std::logic_error("eoNDSorting: niche and front should have the same size"); throw std::logic_error("eoNDSorting: niche and front should have the same size");
} }
double max_niche = *std::max_element(niche_count.begin(), niche_count.end()); double max_niche = *std::max_element(niche_count.begin(), niche_count.end());
for (unsigned j = 0; j < fronts[i].size(); ++j) for (unsigned j = 0; j < fronts[i].size(); ++j)
{ {
value()[fronts[i][j]] = i + niche_count[j] / (max_niche + 1.); // divide by max_niche + 1 to ensure that this front does not overlap with the next value()[fronts[i][j]] = i + niche_count[j] / (max_niche + 1.); // divide by max_niche + 1 to ensure that this front does not overlap with the next
} }
} }
// invert ranks to obtain a 'bigger is better' score // invert ranks to obtain a 'bigger is better' score
rank_to_worth(); rank_to_worth();
} }
class Sorter class Sorter
{ {
public: public:
Sorter(const eoPop<EOT>& _pop) : pop(_pop) {} Sorter(const eoPop<EOT>& _pop) : pop(_pop) {}
bool operator()(unsigned i, unsigned j) const bool operator()(unsigned i, unsigned j) const
{ {
typedef typename EOT::Fitness::fitness_traits traits; typedef typename EOT::Fitness::fitness_traits traits;
double diff = pop[i].fitness()[0] - pop[j].fitness()[0]; double diff = pop[i].fitness()[0] - pop[j].fitness()[0];
if (fabs(diff) < traits::tol()) if (fabs(diff) < traits::tol())
{ {
diff = pop[i].fitness()[1] - pop[j].fitness()[1]; diff = pop[i].fitness()[1] - pop[j].fitness()[1];
if (fabs(diff) < traits::tol()) if (fabs(diff) < traits::tol())
return false; return false;
if (traits::maximizing(1)) if (traits::maximizing(1))
return diff > 0.; return diff > 0.;
return diff < 0.; return diff < 0.;
} }
if (traits::maximizing(0)) if (traits::maximizing(0))
return diff > 0.; return diff > 0.;
return diff < 0.; return diff < 0.;
} }
const eoPop<EOT>& pop; const eoPop<EOT>& pop;
}; };
void m_objectives(const eoPop<EOT>& _pop) void m_objectives(const eoPop<EOT>& _pop)
@ -485,7 +485,7 @@ class eoNDSorting_II : public eoNDSorting<EOT>
for (i = 0; i < nc.size(); ++i) for (i = 0; i < nc.size(); ++i)
{ {
niche_count[i] += (max_dist + 1 - nc[i]); niche_count[i] += (max_dist + 1 - nc[i]);
} }
} }

View file

@ -47,22 +47,11 @@ public:
virtual POT & best()=0; virtual POT & best()=0;
virtual void best(POT _particle)=0; virtual void best(POT _particle)=0;
/// Virtual dtor /// Virtual dtor
virtual ~eoNeighborhood() {}; virtual ~eoNeighborhood() {};
}; };
#endif /* EONEIGHBORHOOD_H_ */ #endif /* EONEIGHBORHOOD_H_ */

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoObject.h // eoObject.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -34,9 +34,9 @@
#include <utils/compatibility.h> #include <utils/compatibility.h>
/* /*
eoObject used to be the base class for the whole hierarchy, but this has eoObject used to be the base class for the whole hierarchy, but this has
changed. eoObject is used to define a name (#className#) changed. eoObject is used to define a name (#className#)
that is used when loading or saving the state. that is used when loading or saving the state.
Previously, this object also defined a print and read Previously, this object also defined a print and read
interface, but it´s been moved to eoPrintable and eoPersistent. interface, but it´s been moved to eoPrintable and eoPersistent.
@ -58,19 +58,18 @@ class eoObject
public: public:
/// Virtual dtor. They are needed in virtual class hierarchies. /// Virtual dtor. They are needed in virtual class hierarchies.
virtual ~eoObject() {} virtual ~eoObject() {}
/** Return the class id. This should be redefined in each class. /** Return the class id. This should be redefined in each class.
Only "leaf" classes can be non-virtual. Only "leaf" classes can be non-virtual.
Maarten: removed the default implementation as this proved to Maarten: removed the default implementation as this proved to
be too error-prone: I found several classes that had a typo in be too error-prone: I found several classes that had a typo in
className (like classname), which would print eoObject instead of className (like classname), which would print eoObject instead of
their own. Having it pure will force the implementor to provide a their own. Having it pure will force the implementor to provide a
name. name.
*/ */
virtual std::string className() const = 0; virtual std::string className() const = 0;
}; };
#endif #endif

View file

@ -1,9 +1,9 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoOneToOneBreeder.h // eoOneToOneBreeder.h
// (c) Maarten Keijzer and Marc Schoenauer, 2001 // (c) Maarten Keijzer and Marc Schoenauer, 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -38,12 +38,12 @@
#include <eoPopulator.h> #include <eoPopulator.h>
#include <utils/eoHowMany.h> #include <utils/eoHowMany.h>
/** eoOneToOneBreeder: transforms a population using /** eoOneToOneBreeder: transforms a population using
* - an operator that MODIFIES only one parent from the populator * - an operator that MODIFIES only one parent from the populator
* (though it can use any number aside) and thus generates ONE offspring) * (though it can use any number aside) and thus generates ONE offspring)
* - a local replacement between the parent and its offspring * - a local replacement between the parent and its offspring
* *
* Typically, Differential Evolution (Storn and Price 94) and Deb et al's * Typically, Differential Evolution (Storn and Price 94) and Deb et al's
* G3 can be built on this * G3 can be built on this
* *
* @ingroup Combination * @ingroup Combination
@ -54,16 +54,16 @@ class eoOneToOneBreeder: public eoBreed<EOT>
public: public:
/** Ctor: /** Ctor:
* @param _op a general operator (must MODIFY only ONE parent) * @param _op a general operator (must MODIFY only ONE parent)
* @param _eval an eoEvalFunc to evaluate the offspring * @param _eval an eoEvalFunc to evaluate the offspring
* @param _pReplace probability that the best of parent/offspring wins [1] * @param _pReplace probability that the best of parent/offspring wins [1]
* @param _howMany eoHowMany offpsring to generate [100%] * @param _howMany eoHowMany offpsring to generate [100%]
*/ */
eoOneToOneBreeder( eoOneToOneBreeder(
eoGenOp<EOT>& _op, eoGenOp<EOT>& _op,
eoEvalFunc<EOT> & _eval, eoEvalFunc<EOT> & _eval,
double _pReplace = 1.0, double _pReplace = 1.0,
eoHowMany _howMany = eoHowMany(1.0) ) : eoHowMany _howMany = eoHowMany(1.0) ) :
op(_op), eval(_eval), select( false ), op(_op), eval(_eval), select( false ),
pReplace(_pReplace), howMany(_howMany) {} pReplace(_pReplace), howMany(_howMany) {}
@ -77,34 +77,34 @@ class eoOneToOneBreeder: public eoBreed<EOT>
void operator()(const eoPop<EOT>& _parents, eoPop<EOT>& _offspring) void operator()(const eoPop<EOT>& _parents, eoPop<EOT>& _offspring)
{ {
unsigned target = howMany(_parents.size()); unsigned target = howMany(_parents.size());
_offspring.clear(); _offspring.clear();
eoSelectivePopulator<EOT> popit(_parents, _offspring, select); eoSelectivePopulator<EOT> popit(_parents, _offspring, select);
for (unsigned iParent=0; iParent<target; iParent++) for (unsigned iParent=0; iParent<target; iParent++)
{ {
unsigned pos = popit.tellp(); // remember current position unsigned pos = popit.tellp(); // remember current position
EOT theParent = *popit; // remember the parent itself EOT theParent = *popit; // remember the parent itself
// now apply operator - will modify the parent // now apply operator - will modify the parent
op(popit); op(popit);
// replacement // replacement
EOT & leOffspring = *popit; EOT & leOffspring = *popit;
// check: only one offspring? // check: only one offspring?
unsigned posEnd = popit.tellp(); unsigned posEnd = popit.tellp();
if (posEnd != pos) if (posEnd != pos)
throw std::runtime_error("Operator can only generate a SINGLE offspring in eoOneToOneBreeder"); throw std::runtime_error("Operator can only generate a SINGLE offspring in eoOneToOneBreeder");
// do the tournament between parent and offspring // do the tournament between parent and offspring
eval(leOffspring); // first need to evaluate the offspring eval(leOffspring); // first need to evaluate the offspring
if (theParent > leOffspring) // old parent better than offspring if (theParent > leOffspring) // old parent better than offspring
if (rng.uniform() < pReplace) // if probability if (rng.uniform() < pReplace) // if probability
leOffspring = theParent; // replace leOffspring = theParent; // replace
// finally, go to next guy to handle // finally, go to next guy to handle
++popit; ++popit;
} }
} }
/// The class name. /// The class name.
@ -119,4 +119,3 @@ class eoOneToOneBreeder: public eoBreed<EOT>
}; };
#endif #endif

View file

@ -2,7 +2,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoOp.h // eoOp.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -18,7 +18,7 @@
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
CVS Info: $Date: 2004-08-10 17:19:46 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoOp.h,v 1.29 2004-08-10 17:19:46 jmerelo Exp $ $Author: jmerelo $ CVS Info: $Date: 2004-08-10 17:19:46 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoOp.h,v 1.29 2004-08-10 17:19:46 jmerelo Exp $ $Author: jmerelo $
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -171,13 +171,13 @@ public:
*/ */
bool operator()(EOT & _eo1, const EOT & _eo2) bool operator()(EOT & _eo1, const EOT & _eo2)
{ {
EOT eoTmp = _eo2; // a copy that can be modified EOT eoTmp = _eo2; // a copy that can be modified
// if the embedded eoQuadOp is not symmetrical, // if the embedded eoQuadOp is not symmetrical,
// the result might be biased - hence the flip ... // the result might be biased - hence the flip ...
if (eo::rng.flip(0.5)) if (eo::rng.flip(0.5))
return quadOp(_eo1, eoTmp); // both are modified - that's all return quadOp(_eo1, eoTmp); // both are modified - that's all
else else
return quadOp(eoTmp, _eo1); // both are modified - that's all return quadOp(eoTmp, _eo1); // both are modified - that's all
} }
private: private:

View file

@ -100,7 +100,7 @@ public:
void apply(eoPopulator<EOT>& _pop) { void apply(eoPopulator<EOT>& _pop) {
_pop.reserve( this->max_production() ); _pop.reserve( this->max_production() );
position_type pos = _pop.tellp(); position_type pos = _pop.tellp();
for (size_t i = 0; i < rates.size(); ++i) { for (size_t i = 0; i < rates.size(); ++i) {
@ -118,10 +118,10 @@ public:
// } // }
// check for out of individuals and do nothing with that... // check for out of individuals and do nothing with that...
// catch(eoPopulator<EOT>::OutOfIndividuals&) // catch(eoPopulator<EOT>::OutOfIndividuals&)
// { // {
// std::cout << "Warning: not enough individuals to handle\n"; // std::cout << "Warning: not enough individuals to handle\n";
// return ; // return ;
// } // }
} }
if (!_pop.exhausted()) if (!_pop.exhausted())
@ -156,7 +156,7 @@ public:
try try
{ {
(*ops[i])(_pop); (*ops[i])(_pop);
++_pop; ++_pop;
} }
catch( typename eoPopulator<EOT>::OutOfIndividuals&) catch( typename eoPopulator<EOT>::OutOfIndividuals&)
{} {}
@ -166,4 +166,3 @@ public:
#endif #endif

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoOpSelMason.h // eoOpSelMason.h
// (c) GeNeura Team, 1999 // (c) GeNeura Team, 1999
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -36,72 +36,72 @@ to the objects it builds, and then deallocate it when it gets out of scope
*/ */
template<class eoClass> template<class eoClass>
class eoOpSelMason: public eoFactory<eoOpSelector<eoClass> > { class eoOpSelMason: public eoFactory<eoOpSelector<eoClass> > {
public: public:
typedef std::vector<eoOp<eoClass>* > vOpP; typedef std::vector<eoOp<eoClass>* > vOpP;
typedef map<eoOpSelector<eoClass>*, vOpP > MEV; typedef map<eoOpSelector<eoClass>*, vOpP > MEV;
/// @name ctors and dtors /// @name ctors and dtors
//{@ //{@
/// constructor /// constructor
eoOpSelMason( eoOpFactory<eoClass>& _opFact): operatorFactory( _opFact ) {}; eoOpSelMason( eoOpFactory<eoClass>& _opFact): operatorFactory( _opFact ) {};
/// destructor
virtual ~eoOpSelMason() {};
//@}
/** Factory methods: creates an object from an std::istream, reading from /// destructor
it whatever is needed to create the object. The format is virtual ~eoOpSelMason() {};
opSelClassName\\ //@}
rate 1 operator1\\
rate 2 operator2\\
...\\
Stores all operators built in a database (#allocMap#), so that somebody
can destroy them later. The Mason is in charge or destroying the operators,
since the built object can´t do it itself. The objects built must be destroyed
from outside, using the "destroy" method
*/
virtual eoOpSelector<eoClass>* make(std::istream& _is) {
std::string opSelName; /** Factory methods: creates an object from an std::istream, reading from
_is >> opSelName; it whatever is needed to create the object. The format is
eoOpSelector<eoClass>* opSelectorP; opSelClassName\\
// Build the operator selector rate 1 operator1\\
if ( opSelName == "eoProportionalOpSel" ) { rate 2 operator2\\
opSelectorP = new eoProportionalOpSel<eoClass>(); ...\\
} Stores all operators built in a database (#allocMap#), so that somebody
can destroy them later. The Mason is in charge or destroying the operators,
since the built object can´t do it itself. The objects built must be destroyed
from outside, using the "destroy" method
*/
virtual eoOpSelector<eoClass>* make(std::istream& _is) {
// Temp std::vector for storing pointers std::string opSelName;
vOpP tmpPVec; _is >> opSelName;
// read operator rate and name eoOpSelector<eoClass>* opSelectorP;
while ( _is ) { // Build the operator selector
float rate; if ( opSelName == "eoProportionalOpSel" ) {
_is >> rate; opSelectorP = new eoProportionalOpSel<eoClass>();
if ( _is ) { }
eoOp<eoClass>* op = operatorFactory.make( _is ); // This reads the rest of the line
// Add the operators to the selector, don´t pay attention to the IDs
opSelectorP->addOp( *op, rate );
// Keep it in the store, to destroy later
tmpPVec.push_back( op );
} // if
} // while
// Put it in the map // Temp std::vector for storing pointers
allocMap.insert( MEV::value_type( opSelectorP, tmpPVec ) ); vOpP tmpPVec;
// read operator rate and name
return opSelectorP; while ( _is ) {
}; float rate;
_is >> rate;
if ( _is ) {
eoOp<eoClass>* op = operatorFactory.make( _is ); // This reads the rest of the line
// Add the operators to the selector, don´t pay attention to the IDs
opSelectorP->addOp( *op, rate );
// Keep it in the store, to destroy later
tmpPVec.push_back( op );
} // if
} // while
///@name eoObject methods // Put it in the map
//@{ allocMap.insert( MEV::value_type( opSelectorP, tmpPVec ) );
/** Return the class id */
virtual std::string className() const { return "eoOpSelMason"; } return opSelectorP;
};
///@name eoObject methods
//@{
/** Return the class id */
virtual std::string className() const { return "eoOpSelMason"; }
//@}
//@}
private: private:
map<eoOpSelector<eoClass>*,std::vector<eoOp<eoClass>* > > allocMap; map<eoOpSelector<eoClass>*,std::vector<eoOp<eoClass>* > > allocMap;
eoOpFactory<eoClass>& operatorFactory; eoOpFactory<eoClass>& operatorFactory;
}; };

View file

@ -10,7 +10,7 @@
#include <algorithm> #include <algorithm>
#include <utils/eoRNG.h> #include <utils/eoRNG.h>
#include <eoInit.h> #include <eoInit.h>
/** /**
* apply orderXover on two chromosomes. * apply orderXover on two chromosomes.
@ -26,65 +26,65 @@
template<class Chrom> class eoOrderXover: public eoQuadOp<Chrom> template<class Chrom> class eoOrderXover: public eoQuadOp<Chrom>
{ {
public: public:
/// The class name. /// The class name.
virtual std::string className() const { return "eoOrderXover"; } virtual std::string className() const { return "eoOrderXover"; }
/**
* @return true if the chromosome has changed
* @param _chrom1 The first chromosome which will be crossed with chrom2.
* @param _chrom2 The second chromosome which will be crossed with chrom1.
*/
bool operator()(Chrom& _chrom1, Chrom& _chrom2){
char direction=eo::rng.flip()? 1 : -1;
unsigned cut2= 1 + eo::rng.random(_chrom1.size());
unsigned cut1= eo::rng.random(cut2);
Chrom tmp1= _chrom1;
Chrom tmp2= _chrom2;
cross(tmp1, tmp2, _chrom1, direction, cut1, cut2);
cross(tmp2, tmp1, _chrom2, direction, cut1, cut2);
_chrom1.invalidate();
_chrom2.invalidate();
return true;
}
/**
* @return true if the chromosome has changed
* @param _chrom1 The first chromosome which will be crossed with chrom2.
* @param _chrom2 The second chromosome which will be crossed with chrom1.
*/
bool operator()(Chrom& _chrom1, Chrom& _chrom2){
char direction=eo::rng.flip()? 1 : -1;
unsigned cut2= 1 + eo::rng.random(_chrom1.size());
unsigned cut1= eo::rng.random(cut2);
Chrom tmp1= _chrom1;
Chrom tmp2= _chrom2;
cross(tmp1, tmp2, _chrom1, direction, cut1, cut2);
cross(tmp2, tmp1, _chrom2, direction, cut1, cut2);
_chrom1.invalidate();
_chrom2.invalidate();
return true;
}
private: private:
/**
* @param _chrom1 The first parent chromosome.
* @param _chrom2 The second parent chromosome.
* @param _child The result chromosome.
* @param _direction The direction of the OrderXover (left: -1 or right: 1)
* @param _cut1 index of the first cut
* @param _cut2 index of the second cut
*/
void cross(Chrom& _chrom1, Chrom& _chrom2, Chrom& _child, char _direction, unsigned _cut1, unsigned _cut2){
unsigned size, id=0, from=0;
size= _chrom1.size();
std::vector<bool> verif(size, false); /**
* @param _chrom1 The first parent chromosome.
for(unsigned i= _cut1; i<_cut2; i++){ * @param _chrom2 The second parent chromosome.
_child[id++]= _chrom1[i]; * @param _child The result chromosome.
verif[_chrom1[i] % size] = true; * @param _direction The direction of the OrderXover (left: -1 or right: 1)
} * @param _cut1 index of the first cut
* @param _cut2 index of the second cut
while(_chrom2[from] != _child[_cut2 - 1]) */
from++; void cross(Chrom& _chrom1, Chrom& _chrom2, Chrom& _child, char _direction, unsigned _cut1, unsigned _cut2){
for(unsigned i=0; i<size; i++){ unsigned size, id=0, from=0;
unsigned j= (_direction*i + from + size) % size; size= _chrom1.size();
if(!verif[_chrom2[j] % size]){
_child[id++]=_chrom2[j]; std::vector<bool> verif(size, false);
verif[_chrom2[j]%size]=true;
} for(unsigned i= _cut1; i<_cut2; i++){
} _child[id++]= _chrom1[i];
} verif[_chrom1[i] % size] = true;
}
while(_chrom2[from] != _child[_cut2 - 1])
from++;
for(unsigned i=0; i<size; i++){
unsigned j= (_direction*i + from + size) % size;
if(!verif[_chrom2[j] % size]){
_child[id++]=_chrom2[j];
verif[_chrom2[j]%size]=true;
}
}
}
}; };
/** @example t-eoOrderXover.cpp /** @example t-eoOrderXover.cpp
*/ */

View file

@ -67,8 +67,8 @@ public:
void operator () (POT & _po1) void operator () (POT & _po1)
{ {
//Set the bestPositions //Set the bestPositions
_po1.bestPositions = _po1 ; _po1.bestPositions = _po1 ;
// set the fitness // set the fitness
@ -80,4 +80,3 @@ public:
#endif /*_EOPARTICLEBESTINIT_H */ #endif /*_EOPARTICLEBESTINIT_H */
/** @} */ /** @} */

View file

@ -54,9 +54,9 @@ template <class POT> class eoInitializerBase : public eoFunctorBase
}; };
/** /**
Base (name) class for Initialization of algorithm PSO Base (name) class for Initialization of algorithm PSO
@see eoInitializerBase eoUF apply @see eoInitializerBase eoUF apply
*/ */
template <class POT> class eoParticleInitializer : public eoInitializerBase <POT> template <class POT> class eoParticleInitializer : public eoInitializerBase <POT>
{ {
@ -99,34 +99,34 @@ template <class POT> class eoParticleInitializer : public eoInitializerBase <POT
{ {
return "eoInitializer"; return "eoInitializer";
} }
virtual void operator () () virtual void operator () ()
{ {
eoPop<POT> empty_pop; eoPop<POT> empty_pop;
// evaluates using either the "sequential" evaluator ... // evaluates using either the "sequential" evaluator ...
apply(proc, pop); apply(proc, pop);
// ... or the parallel one // ... or the parallel one
procPara(empty_pop, pop); procPara(empty_pop, pop);
// no matter what is the eval operator, initializes the velocities and the particle's best // no matter what is the eval operator, initializes the velocities and the particle's best
apply < POT > (initVelo, pop); apply < POT > (initVelo, pop);
apply < POT > (initBest, pop); apply < POT > (initBest, pop);
// finally setup the topology. We have now all we need to do so. // finally setup the topology. We have now all we need to do so.
topology.setup(pop); topology.setup(pop);
} }
private : private :
/* /*
@param proc First evaluation @param proc First evaluation
@param initVelo Initialization of the velocity @param initVelo Initialization of the velocity
@param initBest Initialization of the best @param initBest Initialization of the best
*/ */
eoPop < POT > & pop; eoPop < POT > & pop;
eoUF<POT&, void>& proc; eoUF<POT&, void>& proc;
@ -146,11 +146,10 @@ template <class POT> class eoParticleInitializer : public eoInitializerBase <POT
public: public:
void operator()(POT &) void operator()(POT &)
{} {}
} }
dummy; dummy;
}; };
#endif /*_eoParticleFullInitializer_H*/ #endif /*_eoParticleFullInitializer_H*/
/** @} */ /** @} */

View file

@ -6,17 +6,17 @@
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: cahon@lifl.fr Contact: cahon@lifl.fr
*/ */
#ifndef __eoPeriodicContinue_h #ifndef __eoPeriodicContinue_h
@ -30,27 +30,26 @@
template <class EOT> class eoPeriodicContinue: public eoContinue <EOT> { template <class EOT> class eoPeriodicContinue: public eoContinue <EOT> {
public: public:
/** Constructor. The period is given in parameter. */ /** Constructor. The period is given in parameter. */
eoPeriodicContinue (unsigned __period, unsigned __init_counter = 0) : eoPeriodicContinue (unsigned __period, unsigned __init_counter = 0) :
period (__period), counter (__init_counter) period (__period), counter (__init_counter)
{} {}
/** It returns 'true' only if the current number of generations modulo /** It returns 'true' only if the current number of generations modulo
the period doen't equal to zero. */ the period doen't equal to zero. */
bool operator () (const eoPop <EOT> & pop) bool operator () (const eoPop <EOT> & pop)
{ {
return ((++ counter) % period) != 0 ; return ((++ counter) % period) != 0 ;
} }
private: private:
unsigned period; unsigned period;
unsigned counter; unsigned counter;
}; };
#endif #endif

View file

@ -1,7 +1,7 @@
#ifdef _MSC_VER #ifdef _MSC_VER
// to avoid long name warnings // to avoid long name warnings
#pragma warning(disable:4786) #pragma warning(disable:4786)
#endif #endif
#include <eoPersistent.h> #include <eoPersistent.h>

View file

@ -6,7 +6,7 @@
// eoPersistent.h // eoPersistent.h
// (c) GeNeura Team, 1999 // (c) GeNeura Team, 1999
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -48,14 +48,14 @@ class eoPersistent: public eoPrintable
public: public:
/// Virtual dtor. They are needed in virtual class hierarchies. /// Virtual dtor. They are needed in virtual class hierarchies.
virtual ~eoPersistent() {} virtual ~eoPersistent() {}
/** /**
* Read object. * Read object.
* @param _is A std::istream. * @param _is A std::istream.
* @throw runtime_std::exception If a valid object can't be read. * @throw runtime_std::exception If a valid object can't be read.
*/ */
virtual void readFrom(std::istream& _is) = 0; virtual void readFrom(std::istream& _is) = 0;
}; };
///Standard input for all objects in the EO hierarchy ///Standard input for all objects in the EO hierarchy

View file

@ -1,9 +1,9 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoPop.h // eoPop.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -36,16 +36,16 @@
#include <eoInit.h> #include <eoInit.h>
#include <utils/rnd_generators.h> // for shuffle method #include <utils/rnd_generators.h> // for shuffle method
/** A std::vector of EO object, to be used in all algorithms /** A std::vector of EO object, to be used in all algorithms
* (selectors, operators, replacements, ...). * (selectors, operators, replacements, ...).
* *
* We have no idea if a population can be * We have no idea if a population can be
* some other thing that a std::vector, but if somebody thinks of it, this concrete * some other thing that a std::vector, but if somebody thinks of it, this concrete
* implementation can be moved to "generic" and an abstract Population * implementation can be moved to "generic" and an abstract Population
* interface be provided. * interface be provided.
* *
* The template can be instantiated with anything that accepts a "size" * The template can be instantiated with anything that accepts a "size"
* and eoInit derived object. in the ctor. * and eoInit derived object. in the ctor.
* EOT must also have a copy ctor, since temporaries are created and then * EOT must also have a copy ctor, since temporaries are created and then
* passed to the eoInit object * passed to the eoInit object
* *
@ -55,62 +55,62 @@ template<class EOT>
class eoPop: public std::vector<EOT>, public eoObject, public eoPersistent class eoPop: public std::vector<EOT>, public eoObject, public eoPersistent
{ {
public: public:
using std::vector<EOT>::size; using std::vector<EOT>::size;
using std::vector<EOT>::resize; using std::vector<EOT>::resize;
using std::vector<EOT>::operator[]; using std::vector<EOT>::operator[];
using std::vector<EOT>::begin; using std::vector<EOT>::begin;
using std::vector<EOT>::end; using std::vector<EOT>::end;
typedef typename EOT::Fitness Fitness; typedef typename EOT::Fitness Fitness;
#if defined(__CUDACC__) #if defined(__CUDACC__)
typedef typename std::vector<EOT>::iterator iterator; typedef typename std::vector<EOT>::iterator iterator;
typedef typename std::vector<EOT>::const_iterator const_iterator; typedef typename std::vector<EOT>::const_iterator const_iterator;
#endif #endif
/** Default ctor. Creates empty pop /** Default ctor. Creates empty pop
*/ */
eoPop() : std::vector<EOT>(), eoObject(), eoPersistent() {}; eoPop() : std::vector<EOT>(), eoObject(), eoPersistent() {};
/** Ctor for the initialization of chromosomes /** Ctor for the initialization of chromosomes
@param _popSize total population size @param _popSize total population size
@param _chromInit Initialization routine, produces EO's, needs to be an eoInit @param _chromInit Initialization routine, produces EO's, needs to be an eoInit
*/ */
eoPop( unsigned _popSize, eoInit<EOT>& _chromInit ) eoPop( unsigned _popSize, eoInit<EOT>& _chromInit )
:std::vector<EOT>() :std::vector<EOT>()
{ {
resize(_popSize); resize(_popSize);
for ( unsigned i = 0; i < _popSize; i++ ) for ( unsigned i = 0; i < _popSize; i++ )
{ {
_chromInit(operator[](i)); _chromInit(operator[](i));
} }
}; };
/** appends random guys at end of pop. /** appends random guys at end of pop.
Can be used to initialize it pop is empty Can be used to initialize it pop is empty
@param _newPopSize total population size @param _newPopSize total population size
@param _chromInit Initialization routine, produces EO's, needs to be an eoInit @param _chromInit Initialization routine, produces EO's, needs to be an eoInit
*/ */
void append( unsigned _newPopSize, eoInit<EOT>& _chromInit ) void append( unsigned _newPopSize, eoInit<EOT>& _chromInit )
{ {
unsigned oldSize = size(); unsigned oldSize = size();
if (_newPopSize < oldSize) if (_newPopSize < oldSize)
{ {
throw std::runtime_error("New size smaller than old size in pop.append"); throw std::runtime_error("New size smaller than old size in pop.append");
return; return;
} }
if (_newPopSize == oldSize) if (_newPopSize == oldSize)
return; return;
resize(_newPopSize); // adjust the size resize(_newPopSize); // adjust the size
for ( unsigned i = oldSize; i < _newPopSize; i++ ) for ( unsigned i = oldSize; i < _newPopSize; i++ )
{ {
_chromInit(operator[](i)); _chromInit(operator[](i));
} }
}; };
/** Ctor from an std::istream; reads the population from a stream, /** Ctor from an std::istream; reads the population from a stream,
each element should be in different lines each element should be in different lines
@param _is the stream @param _is the stream
@ -118,9 +118,9 @@ public:
eoPop( std::istream& _is ) :std::vector<EOT>() { eoPop( std::istream& _is ) :std::vector<EOT>() {
readFrom( _is ); readFrom( _is );
} }
/** Empty Dtor */ /** Empty Dtor */
virtual ~eoPop() {} virtual ~eoPop() {}
/// helper struct for getting a pointer /// helper struct for getting a pointer
@ -130,16 +130,16 @@ public:
bool operator()(const EOT* a, const EOT* b) const bool operator()(const EOT* a, const EOT* b) const
{ return b->operator<(*a); } { return b->operator<(*a); }
}; };
/// helper struct for comparing (EA or PSO) /// helper struct for comparing (EA or PSO)
struct Cmp2 struct Cmp2
{ {
bool operator()(const EOT & a,const EOT & b) const bool operator()(const EOT & a,const EOT & b) const
{ {
return b.operator<(a); return b.operator<(a);
} }
}; };
/** /**
sort the population. Use this member to sort in order sort the population. Use this member to sort in order
@ -185,10 +185,10 @@ public:
#if defined(__CUDACC__) #if defined(__CUDACC__)
eoPop<EOT>::iterator it_best_element() eoPop<EOT>::iterator it_best_element()
{ {
eoPop<EOT>:: iterator it = std::max_element(begin(), end()); eoPop<EOT>:: iterator it = std::max_element(begin(), end());
#else #else
typename eoPop<EOT>::iterator it_best_element() { typename eoPop<EOT>::iterator it_best_element() {
typename eoPop<EOT>::iterator it = std::max_element(begin(), end()); typename eoPop<EOT>::iterator it = std::max_element(begin(), end());
#endif #endif
return it; return it;
} }
@ -199,7 +199,7 @@ public:
#if defined(__CUDACC__) #if defined(__CUDACC__)
eoPop<EOT>::const_iterator it = std::max_element(begin(), end()); eoPop<EOT>::const_iterator it = std::max_element(begin(), end());
#else #else
typename eoPop<EOT>::const_iterator it = std::max_element(begin(), end()); typename eoPop<EOT>::const_iterator it = std::max_element(begin(), end());
#endif #endif
return (*it); return (*it);
} }
@ -210,7 +210,7 @@ public:
#if defined(__CUDACC__) #if defined(__CUDACC__)
eoPop<EOT>::const_iterator it = std::min_element(begin(), end()); eoPop<EOT>::const_iterator it = std::min_element(begin(), end());
#else #else
typename eoPop<EOT>::const_iterator it = std::min_element(begin(), end()); typename eoPop<EOT>::const_iterator it = std::min_element(begin(), end());
#endif #endif
return (*it); return (*it);
} }
@ -221,9 +221,9 @@ public:
{ {
eoPop<EOT>::iterator it = std::min_element(begin(), end()); eoPop<EOT>::iterator it = std::min_element(begin(), end());
#else #else
typename eoPop<EOT>::iterator it_worse_element() typename eoPop<EOT>::iterator it_worse_element()
{ {
typename eoPop<EOT>::iterator it = std::min_element(begin(), end()); typename eoPop<EOT>::iterator it = std::min_element(begin(), end());
#endif #endif
return it; return it;
} }
@ -232,25 +232,25 @@ public:
slightly faster algorithm than sort to find all individuals that are better slightly faster algorithm than sort to find all individuals that are better
than the nth individual. INDIVIDUALS ARE MOVED AROUND in the pop. than the nth individual. INDIVIDUALS ARE MOVED AROUND in the pop.
*/ */
#if defined(__CUDACC__) #if defined(__CUDACC__)
eoPop<EOT>::iterator nth_element(int nth) eoPop<EOT>::iterator nth_element(int nth)
{ {
eoPop<EOT>::iterator it = begin() + nth; eoPop<EOT>::iterator it = begin() + nth;
#else #else
typename eoPop<EOT>::iterator nth_element(int nth) typename eoPop<EOT>::iterator nth_element(int nth)
{ {
typename eoPop<EOT>::iterator it = begin() + nth; typename eoPop<EOT>::iterator it = begin() + nth;
#endif #endif
std::nth_element(begin(), it, end(), std::greater<EOT>()); std::nth_element(begin(), it, end(), std::greater<EOT>());
return it; return it;
} }
struct GetFitness { Fitness operator()(const EOT& _eo) const { return _eo.fitness(); } }; struct GetFitness { Fitness operator()(const EOT& _eo) const { return _eo.fitness(); } };
/** returns the fitness of the nth element */ /** returns the fitness of the nth element */
Fitness nth_element_fitness(int which) const Fitness nth_element_fitness(int which) const
{ // probably not the fastest way to do this, but what the heck { // probably not the fastest way to do this, but what the heck
std::vector<Fitness> fitness(size()); std::vector<Fitness> fitness(size());
std::transform(begin(), end(), fitness.begin(), GetFitness()); std::transform(begin(), end(), fitness.begin(), GetFitness());
@ -259,15 +259,15 @@ public:
return *it; return *it;
} }
/** const nth_element function, returns pointers to sorted individuals /** const nth_element function, returns pointers to sorted individuals
* up the the nth * up the the nth
*/ */
void nth_element(int which, std::vector<const EOT*>& result) const void nth_element(int which, std::vector<const EOT*>& result) const
{ {
result.resize(size()); result.resize(size());
std::transform(begin(), end(), result.begin(), Ref()); std::transform(begin(), end(), result.begin(), Ref());
typename std::vector<const EOT*>::iterator it = result.begin() + which; typename std::vector<const EOT*>::iterator it = result.begin() + which;
std::nth_element(result.begin(), it, result.end(), Cmp()); std::nth_element(result.begin(), it, result.end(), Cmp());
@ -278,28 +278,28 @@ public:
{ {
std::swap(static_cast<std::vector<EOT>& >(*this), static_cast<std::vector<EOT>& >(other)); std::swap(static_cast<std::vector<EOT>& >(*this), static_cast<std::vector<EOT>& >(other));
} }
/** /**
* Prints sorted pop but does NOT modify it! * Prints sorted pop but does NOT modify it!
* *
* @param _os A std::ostream. * @param _os A std::ostream.
*/ */
virtual void sortedPrintOn(std::ostream& _os) const virtual void sortedPrintOn(std::ostream& _os) const
{ {
std::vector<const EOT*> result; std::vector<const EOT*> result;
sort(result); sort(result);
_os << size() << '\n'; _os << size() << '\n';
for (unsigned i = 0; i < size(); ++i) for (unsigned i = 0; i < size(); ++i)
{ {
_os << *result[i] << std::endl; _os << *result[i] << std::endl;
} }
} }
/** /**
* Write object. It's called printOn since it prints the object _on_ a stream. * Write object. It's called printOn since it prints the object _on_ a stream.
* @param _os A std::ostream. * @param _os A std::ostream.
*/ */
virtual void printOn(std::ostream& _os) const virtual void printOn(std::ostream& _os) const
{ {
_os << size() << '\n'; _os << size() << '\n';
std::copy( begin(), end(), std::ostream_iterator<EOT>( _os, "\n") ); std::copy( begin(), end(), std::ostream_iterator<EOT>( _os, "\n") );
@ -309,16 +309,16 @@ public:
//@{ //@{
/** /**
* Read object. The EOT class must have a ctor from a stream; * Read object. The EOT class must have a ctor from a stream;
* @param _is A std::istream. * @param _is A std::istream.
*/ */
virtual void readFrom(std::istream& _is) virtual void readFrom(std::istream& _is)
{ {
size_t sz; size_t sz;
_is >> sz; _is >> sz;
resize(sz); resize(sz);
for (size_t i = 0; i < sz; ++i) { for (size_t i = 0; i < sz; ++i) {
operator[](i).readFrom( _is ); operator[](i).readFrom( _is );
} }
} }
@ -337,4 +337,3 @@ public:
}; };
#endif #endif

View file

@ -5,7 +5,7 @@
Abstract class for global evaluation of the population Abstract class for global evaluation of the population
(c) GeNeura Team, 2000 (c) GeNeura Team, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -30,32 +30,32 @@
#include <eoEvalFunc.h> #include <eoEvalFunc.h>
#include <apply.h> #include <apply.h>
/** eoPopEvalFunc: This abstract class is for GLOBAL evaluators /** eoPopEvalFunc: This abstract class is for GLOBAL evaluators
* of a population after variation. * of a population after variation.
* It takes 2 populations (typically the parents and the offspring) * It takes 2 populations (typically the parents and the offspring)
* and is suppposed to evaluate them alltogether * and is suppposed to evaluate them alltogether
* *
* Basic use: apply an embedded eoEvalFunc to the offspring * Basic use: apply an embedded eoEvalFunc to the offspring
* *
* Time-varying fitness: apply the embedded eoEvalFunc to both * Time-varying fitness: apply the embedded eoEvalFunc to both
* offspring and parents * offspring and parents
* *
* Advanced uses: Co-evolution or "parisian" approach, or ... * Advanced uses: Co-evolution or "parisian" approach, or ...
* *
* Basic parallelization (synchronous standard evolution engine): * Basic parallelization (synchronous standard evolution engine):
* call the slaves and wait for the results * call the slaves and wait for the results
* *
* @ingroup Evaluation * @ingroup Evaluation
*/ */
template<class EOT> template<class EOT>
class eoPopEvalFunc : public eoBF<eoPop<EOT> & , eoPop<EOT> &, void> class eoPopEvalFunc : public eoBF<eoPop<EOT> & , eoPop<EOT> &, void>
{}; {};
///////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////
// eoPopLoopEval // eoPopLoopEval
///////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////
/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies /** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies
* a private eoEvalFunc to all offspring * a private eoEvalFunc to all offspring
* *
* @ingroup Evaluation * @ingroup Evaluation
@ -81,9 +81,9 @@ private:
// eoTimeVaryingLoopEval // eoTimeVaryingLoopEval
///////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////
/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies /** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies
* a private eoEvalFunc to all offspring AND ALL PARENTS * a private eoEvalFunc to all offspring AND ALL PARENTS
* as the fitness is supposed here to vary * as the fitness is supposed here to vary
* *
* @ingroup Evaluation * @ingroup Evaluation
*/ */
@ -105,4 +105,3 @@ private:
}; };
#endif #endif

View file

@ -209,4 +209,3 @@ private:
}; };
#endif #endif

View file

@ -1,7 +1,7 @@
#ifdef _MSC_VER #ifdef _MSC_VER
// to avoid long name warnings // to avoid long name warnings
#pragma warning(disable:4786) #pragma warning(disable:4786)
#endif #endif
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoPrintable.cpp // eoPrintable.cpp
@ -14,9 +14,8 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
std::ostream & operator << ( std::ostream& _os, const eoPrintable& _o ) { std::ostream & operator << ( std::ostream& _os, const eoPrintable& _o ) {
_o.printOn(_os); _o.printOn(_os);
return _os; return _os;
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoPrintable.h // eoPrintable.h
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -37,7 +37,7 @@ some objects (for instance, a #eoFactory# or a random number generator.
/** /**
Base class for objects that can print themselves Base class for objects that can print themselves
(#printOn#). Besides, this file defines the standard output for all the objects; (#printOn#). Besides, this file defines the standard output for all the objects;
if the objects define printOn there's no need to define "operator<<". if the objects define printOn there's no need to define "operator<<".
@ingroup Core @ingroup Core
@ -47,7 +47,7 @@ class eoPrintable
public: public:
/// Virtual dtor. They are needed in virtual class hierarchies. /// Virtual dtor. They are needed in virtual class hierarchies.
virtual ~eoPrintable() {} virtual ~eoPrintable() {}
/** /**
* Write object. It's called printOn since it prints the object on a stream. * Write object. It's called printOn since it prints the object on a stream.
* @param _os A std::ostream. * @param _os A std::ostream.
@ -60,4 +60,3 @@ class eoPrintable
std::ostream & operator << ( std::ostream& _os, const eoPrintable& _o ); std::ostream & operator << ( std::ostream& _os, const eoPrintable& _o );
#endif #endif

View file

@ -33,36 +33,36 @@
// class eoSGAGenOp // class eoSGAGenOp
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
/** /**
* eoPropGAGenOp (for Simple GA, but Proportional) * eoPropGAGenOp (for Simple GA, but Proportional)
* choice between Crossover, mutation or cloining * choice between Crossover, mutation or cloining
* with respect to given relatve weights * with respect to given relatve weights
* *
* @ingroup Combination * @ingroup Combination
*/ */
template<class EOT> template<class EOT>
class eoPropGAGenOp : public eoGenOp<EOT> class eoPropGAGenOp : public eoGenOp<EOT>
{ {
public: public:
/** Ctor from /** Ctor from
* * weight of clone * * weight of clone
* * crossover (with weight) * * crossover (with weight)
* * mutation (with weight) * * mutation (with weight)
*/ */
eoPropGAGenOp(double _wClone, eoQuadOp<EOT>& _cross, double _wCross, eoPropGAGenOp(double _wClone, eoQuadOp<EOT>& _cross, double _wCross,
eoMonOp<EOT>& _mut, double _wMut) eoMonOp<EOT>& _mut, double _wMut)
: wClone(_wClone), : wClone(_wClone),
cross(_cross), cross(_cross),
wCross(_wCross), wCross(_wCross),
mut(_mut), mut(_mut),
wMut(_wMut) wMut(_wMut)
{ {
propOp.add(cross, wCross); // the crossover - with weight wCross propOp.add(cross, wCross); // the crossover - with weight wCross
propOp.add(mut, wMut); // mutation with weight wMut propOp.add(mut, wMut); // mutation with weight wMut
propOp.add(monClone, wClone); propOp.add(monClone, wClone);
} }
/** do the job: delegate to op */ /** do the job: delegate to op */
virtual void apply(eoPopulator<EOT>& _pop) virtual void apply(eoPopulator<EOT>& _pop)
{ {

View file

@ -2,7 +2,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoCombinedOp.h // eoCombinedOp.h
// (c) GeNeura Team, 1998, Marc Schoenauer, 2000 // (c) GeNeura Team, 1998, Marc Schoenauer, 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -105,7 +105,7 @@ public:
virtual bool operator()(EOT & _indi) virtual bool operator()(EOT & _indi)
{ {
unsigned what = rng.roulette_wheel(rates); // choose one op unsigned what = rng.roulette_wheel(rates); // choose one op
return (*ops[what])(_indi); // apply it return (*ops[what])(_indi); // apply it
} }
protected: protected:
std::vector<eoMonOp<EOT>*> ops; std::vector<eoMonOp<EOT>*> ops;
@ -139,20 +139,20 @@ virtual void add(eoBinOp<EOT> & _op, const double _rate, bool _verbose=false)
// compute the relative rates in percent - to warn the user! // compute the relative rates in percent - to warn the user!
if (_verbose) if (_verbose)
{ {
double total = 0; double total = 0;
unsigned i; unsigned i;
for (i=0; i<ops.size(); i++) for (i=0; i<ops.size(); i++)
total += rates[i]; total += rates[i];
eo::log << eo::logging << "In " << className() << std::endl ; eo::log << eo::logging << "In " << className() << std::endl ;
for (i=0; i<ops.size(); i++) for (i=0; i<ops.size(); i++)
eo::log << eo::logging << ops[i]->className() << " with rate " << 100*rates[i]/total << " %" << std::endl; eo::log << eo::logging << ops[i]->className() << " with rate " << 100*rates[i]/total << " %" << std::endl;
} }
} }
virtual void operator()(EOT & _indi1, const EOT & _indi2) virtual void operator()(EOT & _indi1, const EOT & _indi2)
{ {
unsigned what = rng.roulette_wheel(rates); // choose one op index unsigned what = rng.roulette_wheel(rates); // choose one op index
return (*ops[what])(_indi1, _indi2); // apply it return (*ops[what])(_indi1, _indi2); // apply it
} }
private: private:
std::vector<eoBinOp<EOT>*> ops; std::vector<eoBinOp<EOT>*> ops;
@ -216,7 +216,7 @@ public:
virtual bool operator()(EOT & _indi1, EOT & _indi2) virtual bool operator()(EOT & _indi1, EOT & _indi2)
{ {
unsigned what = rng.roulette_wheel(rates); // choose one op index unsigned what = rng.roulette_wheel(rates); // choose one op index
return (*ops[what])(_indi1, _indi2); // apply it return (*ops[what])(_indi1, _indi2); // apply it
} }
private: private:
std::vector<eoQuadOp<EOT>*> ops; std::vector<eoQuadOp<EOT>*> ops;

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoProportionalSelect.h // eoProportionalSelect.h
// (c) GeNeura Team, 1998 - EEAAX 1999, Maarten Keijzer 2000 // (c) GeNeura Team, 1998 - EEAAX 1999, Maarten Keijzer 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -35,18 +35,18 @@
#include <eoPop.h> #include <eoPop.h>
/** eoProportionalSelect: select an individual proportional to her stored fitness /** eoProportionalSelect: select an individual proportional to her stored fitness
value value
Changed the algorithm to make use of a cumulative array of fitness scores, Changed the algorithm to make use of a cumulative array of fitness scores,
This changes the algorithm from O(n) per call to O(log n) per call. (MK) This changes the algorithm from O(n) per call to O(log n) per call. (MK)
@ingroup Selectors @ingroup Selectors
*/ */
template <class EOT> class eoProportionalSelect: public eoSelectOne<EOT> template <class EOT> class eoProportionalSelect: public eoSelectOne<EOT>
{ {
public: public:
/// Sanity check /// Sanity check
eoProportionalSelect(const eoPop<EOT>& pop = eoPop<EOT>()) eoProportionalSelect(const eoPop<EOT>& pop = eoPop<EOT>())
{ {
if (minimizing_fitness<EOT>()) if (minimizing_fitness<EOT>())
throw std::logic_error("eoProportionalSelect: minimizing fitness"); throw std::logic_error("eoProportionalSelect: minimizing fitness");
@ -55,23 +55,23 @@ public:
void setup(const eoPop<EOT>& _pop) void setup(const eoPop<EOT>& _pop)
{ {
if (_pop.size() == 0) return; if (_pop.size() == 0) return;
cumulative.resize(_pop.size()); cumulative.resize(_pop.size());
cumulative[0] = _pop[0].fitness(); cumulative[0] = _pop[0].fitness();
for (unsigned i = 1; i < _pop.size(); ++i) for (unsigned i = 1; i < _pop.size(); ++i)
{ {
cumulative[i] = _pop[i].fitness() + cumulative[i-1]; cumulative[i] = _pop[i].fitness() + cumulative[i-1];
} }
} }
/** do the selection, /** do the selection,
*/ */
const EOT& operator()(const eoPop<EOT>& _pop) const EOT& operator()(const eoPop<EOT>& _pop)
{ {
if (cumulative.size() == 0) setup(_pop); if (cumulative.size() == 0) setup(_pop);
double fortune = rng.uniform() * cumulative.back(); double fortune = rng.uniform() * cumulative.back();
typename FitVec::iterator result = std::upper_bound(cumulative.begin(), cumulative.end(), fortune); typename FitVec::iterator result = std::upper_bound(cumulative.begin(), cumulative.end(), fortune);
return _pop[result - cumulative.begin()]; return _pop[result - cumulative.begin()];
} }

View file

@ -31,7 +31,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** /**
* Update an inertia weight by assigning it an (uniform) random value. * Update an inertia weight by assigning it an (uniform) random value.
* The weight is a basic feature to evaluate the velocity of a particle in * The weight is a basic feature to evaluate the velocity of a particle in
* swarm optimization. * swarm optimization.
* *

View file

@ -35,7 +35,7 @@
#include <utils/eoRNG.h> #include <utils/eoRNG.h>
#include <eoSelectOne.h> #include <eoSelectOne.h>
/** eoRandomSelect: a selection method that selects ONE individual randomly /** eoRandomSelect: a selection method that selects ONE individual randomly
* *
* @ingroup Selectors * @ingroup Selectors
*/ */
@ -91,4 +91,3 @@ private:
}; };
#endif #endif

View file

@ -55,10 +55,10 @@ public:
{ {
typename eoPop<EOT>::const_iterator it; typename eoPop<EOT>::const_iterator it;
for (it=_pop.begin(); it<_pop.end(); it++) for (it=_pop.begin(); it<_pop.end(); it++)
{ {
if (_eo == &(*it)) if (_eo == &(*it))
return it-_pop.begin(); return it-_pop.begin();
} }
throw std::runtime_error("Not found in eoLinearRanking"); throw std::runtime_error("Not found in eoLinearRanking");
} }
@ -74,33 +74,33 @@ public:
unsigned int pSizeMinusOne = pSize-1; unsigned int pSizeMinusOne = pSize-1;
if (pSize <= 1) if (pSize <= 1)
throw std::runtime_error("Cannot do ranking with population of size <= 1"); throw std::runtime_error("Cannot do ranking with population of size <= 1");
// value() refers to the std::vector of worthes (we're in an eoParamvalue) // value() refers to the std::vector of worthes (we're in an eoParamvalue)
value().resize(pSize); value().resize(pSize);
double beta = (2-pressure)/pSize; double beta = (2-pressure)/pSize;
if (exponent == 1.0) // no need for exponetial then if (exponent == 1.0) // no need for exponetial then
{ {
double alpha = (2*pressure-2)/(pSize*pSizeMinusOne); double alpha = (2*pressure-2)/(pSize*pSizeMinusOne);
for (unsigned i=0; i<pSize; i++) for (unsigned i=0; i<pSize; i++)
{ {
int which = lookfor(rank[i], _pop); int which = lookfor(rank[i], _pop);
value()[which] = alpha*(pSize-i)+beta; // worst -> 1/[P(P-1)/2] value()[which] = alpha*(pSize-i)+beta; // worst -> 1/[P(P-1)/2]
} }
} }
else // exponent != 1 else // exponent != 1
{ {
double gamma = (2*pressure-2)/pSize; double gamma = (2*pressure-2)/pSize;
for (unsigned i=0; i<pSize; i++) for (unsigned i=0; i<pSize; i++)
{ {
int which = lookfor(rank[i], _pop); int which = lookfor(rank[i], _pop);
// value in in [0,1] // value in in [0,1]
double tmp = ((double)(pSize-i))/pSize; double tmp = ((double)(pSize-i))/pSize;
// to the exponent, and back to [m,M] // to the exponent, and back to [m,M]
value()[which] = gamma*pow(tmp, exponent)+beta; value()[which] = gamma*pow(tmp, exponent)+beta;
} }
} }
} }
private: private:
double pressure; // selective pressure double pressure; // selective pressure

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoRankingSelect.h // eoRankingSelect.h
// (c) GeNeura Team, 1998, Maarten Keijzer 2000, Marc Schoenauer 2001 // (c) GeNeura Team, 1998, Maarten Keijzer 2000, Marc Schoenauer 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -38,19 +38,19 @@
* *
* @ingroup Selectors * @ingroup Selectors
*/ */
template <class EOT> template <class EOT>
class eoRankingSelect: public eoRouletteWorthSelect<EOT, double> class eoRankingSelect: public eoRouletteWorthSelect<EOT, double>
{ {
public: public:
/** Ctor: /** Ctor:
* @param _p the selective pressure, should be in [1,2] (2 is the default) * @param _p the selective pressure, should be in [1,2] (2 is the default)
* @param _e exponent (1 == linear) * @param _e exponent (1 == linear)
*/ */
eoRankingSelect(double _p = 2.0, double _e=1.0): eoRankingSelect(double _p = 2.0, double _e=1.0):
eoRouletteWorthSelect<EOT, double>(ranking), ranking(_p, _e) {} eoRouletteWorthSelect<EOT, double>(ranking), ranking(_p, _e) {}
private : private :
eoRanking<EOT> ranking; // derived from eoPerf2Worth eoRanking<EOT> ranking; // derived from eoPerf2Worth
}; };
#endif #endif

View file

@ -56,8 +56,8 @@ public:
void operator() (eoRealBaseVectorBounds & _bnds,unsigned _i) void operator() (eoRealBaseVectorBounds & _bnds,unsigned _i)
{ {
(void)_bnds; (void)_bnds;
(void)_i; (void)_i;
} }
}; };
@ -70,26 +70,26 @@ public:
* - t, the current iteration, is given with an eoValueParam<unsigned> * - t, the current iteration, is given with an eoValueParam<unsigned>
* - Nt is the stopping criteria <=> the total number of iterations * - Nt is the stopping criteria <=> the total number of iterations
* - alpha a coefficient * - alpha a coefficient
* *
*/ */
class eoExpDecayingBoundModifier: public eoRealBoundModifier class eoExpDecayingBoundModifier: public eoRealBoundModifier
{ {
public: public:
/** /**
* Constructor * Constructor
* @param _stopCriteria - The total number of iterations * @param _stopCriteria - The total number of iterations
* @param _alpha * @param _alpha
* @param _genCounter - An eoValueParam<unsigned> that gives the current iteration * @param _genCounter - An eoValueParam<unsigned> that gives the current iteration
*/ */
eoExpDecayingBoundModifier (unsigned _stopCriteria, eoExpDecayingBoundModifier (unsigned _stopCriteria,
double _alpha, double _alpha,
eoValueParam<unsigned> & _genCounter): eoValueParam<unsigned> & _genCounter):
stopCriteria(_stopCriteria), stopCriteria(_stopCriteria),
alpha(_alpha), alpha(_alpha),
genCounter(_genCounter){} genCounter(_genCounter){}
void operator() (eoRealBaseVectorBounds & _bnds,unsigned _i) void operator() (eoRealBaseVectorBounds & _bnds,unsigned _i)
{ {
double newMaxBound=(1-pow((double)genCounter.value()/stopCriteria,alpha))*_bnds.maximum(_i); double newMaxBound=(1-pow((double)genCounter.value()/stopCriteria,alpha))*_bnds.maximum(_i);

View file

@ -4,7 +4,7 @@
// eoReduce.h // eoReduce.h
// Base class for population-merging classes // Base class for population-merging classes
// (c) GeNeura Team, 1998 // (c) GeNeura Team, 1998
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -39,7 +39,7 @@
/** /**
* eoReduce: .reduce the new generation to the specified size * eoReduce: .reduce the new generation to the specified size
At the moment, limited to truncation - with 2 different methods, At the moment, limited to truncation - with 2 different methods,
one that sorts the whole population, and one that repeatidely kills one that sorts the whole population, and one that repeatidely kills
the worst. Ideally, we should be able to choose at run-time!!! the worst. Ideally, we should be able to choose at run-time!!!
@ingroup Replacors @ingroup Replacors
@ -47,7 +47,7 @@
template<class EOT> class eoReduce: public eoBF<eoPop<EOT>&, unsigned, void> template<class EOT> class eoReduce: public eoBF<eoPop<EOT>&, unsigned, void>
{}; {};
/** truncation method using sort /** truncation method using sort
@ingroup Replacors @ingroup Replacors
*/ */
template <class EOT> class eoTruncate : public eoReduce<EOT> template <class EOT> class eoTruncate : public eoReduce<EOT>
@ -56,15 +56,15 @@ template <class EOT> class eoTruncate : public eoReduce<EOT>
{ {
if (_newgen.size() == _newsize) if (_newgen.size() == _newsize)
return; return;
if (_newgen.size() < _newsize) if (_newgen.size() < _newsize)
throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n"); throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n");
_newgen.sort(); _newgen.sort();
_newgen.resize(_newsize); _newgen.resize(_newsize);
} }
}; };
/** random truncation /** random truncation
@ingroup Replacors @ingroup Replacors
* */ * */
template <class EOT> class eoRandomReduce : public eoReduce<EOT> template <class EOT> class eoRandomReduce : public eoReduce<EOT>
@ -73,16 +73,16 @@ template <class EOT> class eoRandomReduce : public eoReduce<EOT>
{ {
if (_newgen.size() == _newsize) if (_newgen.size() == _newsize)
return; return;
if (_newgen.size() < _newsize) if (_newgen.size() < _newsize)
throw std::logic_error("eoRandomReduce: Cannot truncate to a larger size!\n"); throw std::logic_error("eoRandomReduce: Cannot truncate to a larger size!\n");
// shuffle the population, then trucate // shuffle the population, then trucate
_newgen.shuffle(); _newgen.shuffle();
_newgen.resize(_newsize); _newgen.resize(_newsize);
} }
}; };
/** /**
EP truncation method (some global stochastic tournament + sort) EP truncation method (some global stochastic tournament + sort)
Softer selective pressure than pure truncate Softer selective pressure than pure truncate
@ingroup Replacors @ingroup Replacors
@ -90,15 +90,15 @@ Softer selective pressure than pure truncate
template <class EOT> class eoEPReduce : public eoReduce<EOT> template <class EOT> class eoEPReduce : public eoReduce<EOT>
{ {
public: public:
typedef typename EOT::Fitness Fitness; typedef typename EOT::Fitness Fitness;
eoEPReduce(unsigned _t_size ): eoEPReduce(unsigned _t_size ):
t_size(_t_size) t_size(_t_size)
{ {
if (t_size < 2) if (t_size < 2)
{ {
eo::log << eo::warnings << "Warning: EP tournament size should be >= 2. Adjusted" << std::endl; eo::log << eo::warnings << "Warning: EP tournament size should be >= 2. Adjusted" << std::endl;
t_size = 2; t_size = 2;
} }
} }
@ -108,60 +108,60 @@ typedef typename EOT::Fitness Fitness;
typedef std::pair<float, typename eoPop<EOT>::iterator> EPpair; typedef std::pair<float, typename eoPop<EOT>::iterator> EPpair;
struct Cmp { struct Cmp {
bool operator()(const EPpair a, const EPpair b) const bool operator()(const EPpair a, const EPpair b) const
{ {
if (b.first == a.first) if (b.first == a.first)
return (*b.second < *a.second); return (*b.second < *a.second);
return b.first < a.first; return b.first < a.first;
} }
}; };
void operator()(eoPop<EOT>& _newgen, unsigned _newsize) void operator()(eoPop<EOT>& _newgen, unsigned _newsize)
{ {
unsigned int presentSize = _newgen.size(); unsigned int presentSize = _newgen.size();
if (presentSize == _newsize) if (presentSize == _newsize)
return; return;
if (presentSize < _newsize) if (presentSize < _newsize)
throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n"); throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n");
std::vector<EPpair> scores(presentSize); std::vector<EPpair> scores(presentSize);
for (unsigned i=0; i<presentSize; i++) for (unsigned i=0; i<presentSize; i++)
{ {
scores[i].second = _newgen.begin()+i; scores[i].second = _newgen.begin()+i;
Fitness fit = _newgen[i].fitness(); Fitness fit = _newgen[i].fitness();
for (unsigned itourn = 0; itourn < t_size; ++itourn) for (unsigned itourn = 0; itourn < t_size; ++itourn)
{ {
const EOT & competitor = _newgen[rng.random(presentSize)]; const EOT & competitor = _newgen[rng.random(presentSize)];
if (fit > competitor.fitness()) if (fit > competitor.fitness())
scores[i].first += 1; scores[i].first += 1;
else if (fit == competitor.fitness()) else if (fit == competitor.fitness())
scores[i].first += 0.5; scores[i].first += 0.5;
} }
} }
// now we have the scores // now we have the scores
typename std::vector<EPpair>::iterator it = scores.begin() + _newsize; typename std::vector<EPpair>::iterator it = scores.begin() + _newsize;
std::nth_element(scores.begin(), it, scores.end(), Cmp()); std::nth_element(scores.begin(), it, scores.end(), Cmp());
// sort(scores.begin(), scores.end(), Cmp()); // sort(scores.begin(), scores.end(), Cmp());
unsigned j; unsigned j;
// std::cout << "Les scores apres tri\n"; // std::cout << "Les scores apres tri\n";
// for (j=0; j<scores.size(); j++) // for (j=0; j<scores.size(); j++)
// { // {
// std::cout << scores[j].first << " " << *scores[j].second << std::endl; // std::cout << scores[j].first << " " << *scores[j].second << std::endl;
// } // }
eoPop<EOT> tmPop; eoPop<EOT> tmPop;
for (j=0; j<_newsize; j++) for (j=0; j<_newsize; j++)
{ {
tmPop.push_back(*scores[j].second); tmPop.push_back(*scores[j].second);
} }
_newgen.swap(tmPop); _newgen.swap(tmPop);
// erase does not work, but I'm sure there is a way in STL to mark // erase does not work, but I'm sure there is a way in STL to mark
// and later delete all inside a std::vector ?????? // and later delete all inside a std::vector ??????
// this would avoid all copies here // this would avoid all copies here
// it = scores.begin() + _newsize; // it = scores.begin() + _newsize;
// while (it < scores.end()) // while (it < scores.end())
// _newgen.erase(it->second); // _newgen.erase(it->second);
} }
private: private:
unsigned t_size; unsigned t_size;
@ -171,7 +171,7 @@ private:
To be used in SSGA-like replacements (e.g. see eoSSGAWorseReplacement) To be used in SSGA-like replacements (e.g. see eoSSGAWorseReplacement)
@ingroup Replacors @ingroup Replacors
*/ */
template <class EOT> template <class EOT>
class eoLinearTruncate : public eoReduce<EOT> class eoLinearTruncate : public eoReduce<EOT>
{ {
void operator()(eoPop<EOT>& _newgen, unsigned _newsize) void operator()(eoPop<EOT>& _newgen, unsigned _newsize)
@ -183,8 +183,8 @@ class eoLinearTruncate : public eoReduce<EOT>
throw std::logic_error("eoLinearTruncate: Cannot truncate to a larger size!\n"); throw std::logic_error("eoLinearTruncate: Cannot truncate to a larger size!\n");
for (unsigned i=0; i<oldSize - _newsize; i++) for (unsigned i=0; i<oldSize - _newsize; i++)
{ {
typename eoPop<EOT>::iterator it = _newgen.it_worse_element(); typename eoPop<EOT>::iterator it = _newgen.it_worse_element();
_newgen.erase(it); _newgen.erase(it);
} }
} }
}; };
@ -193,7 +193,7 @@ class eoLinearTruncate : public eoReduce<EOT>
To be used in SSGA-like replacements (e.g. see eoSSGADetTournamentReplacement) To be used in SSGA-like replacements (e.g. see eoSSGADetTournamentReplacement)
@ingroup Replacors @ingroup Replacors
*/ */
template <class EOT> template <class EOT>
class eoDetTournamentTruncate : public eoReduce<EOT> class eoDetTournamentTruncate : public eoReduce<EOT>
{ {
public: public:
@ -201,9 +201,9 @@ public:
t_size(_t_size) t_size(_t_size)
{ {
if (t_size < 2) if (t_size < 2)
{ {
eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncate adjusted to 2" << std::endl; eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncate adjusted to 2" << std::endl;
t_size = 2; t_size = 2;
} }
} }
@ -212,8 +212,8 @@ public:
unsigned oldSize = _newgen.size(); unsigned oldSize = _newgen.size();
if (_newsize == 0) if (_newsize == 0)
{ {
_newgen.resize(0); _newgen.resize(0);
return; return;
} }
if (oldSize == _newsize) if (oldSize == _newsize)
return; return;
@ -223,15 +223,15 @@ public:
// Now OK to erase some losers // Now OK to erase some losers
for (unsigned i=0; i<oldSize - _newsize; i++) for (unsigned i=0; i<oldSize - _newsize; i++)
{ {
//OLDCODE EOT & eo = inverse_deterministic_tournament<EOT>(_newgen, t_size); //OLDCODE EOT & eo = inverse_deterministic_tournament<EOT>(_newgen, t_size);
//OLDCODE _newgen.erase(&eo); //OLDCODE _newgen.erase(&eo);
// Jeroen Eggermont stdc++v3 patch // Jeroen Eggermont stdc++v3 patch
// in the new code from stdc++v3 an iterator from a container<T> is no longer an pointer to T // in the new code from stdc++v3 an iterator from a container<T> is no longer an pointer to T
// Because eo already contained a fuction using eoPop<EOT>::iterator's we will use the following // Because eo already contained a fuction using eoPop<EOT>::iterator's we will use the following
_newgen.erase( inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size) ); _newgen.erase( inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size) );
} }
} }
private: private:
@ -242,7 +242,7 @@ private:
To be used in SSGA-like replacements (e.g. see eoSSGAStochTournamentReplacement) To be used in SSGA-like replacements (e.g. see eoSSGAStochTournamentReplacement)
@ingroup Replacors @ingroup Replacors
*/ */
template <class EOT> template <class EOT>
class eoStochTournamentTruncate : public eoReduce<EOT> class eoStochTournamentTruncate : public eoReduce<EOT>
{ {
public: public:
@ -250,14 +250,14 @@ public:
t_rate(_t_rate) t_rate(_t_rate)
{ {
if (t_rate <= 0.5) if (t_rate <= 0.5)
{ {
eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncate adjusted to 0.51" << std::endl; eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncate adjusted to 0.51" << std::endl;
t_rate = 0.51; t_rate = 0.51;
} }
if (t_rate > 1) if (t_rate > 1)
{ {
eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncate adjusted to 1" << std::endl; eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncate adjusted to 1" << std::endl;
t_rate = 1; t_rate = 1;
} }
} }
@ -266,8 +266,8 @@ public:
unsigned oldSize = _newgen.size(); unsigned oldSize = _newgen.size();
if (_newsize == 0) if (_newsize == 0)
{ {
_newgen.resize(0); _newgen.resize(0);
return; return;
} }
if (oldSize == _newsize) if (oldSize == _newsize)
return; return;
@ -276,16 +276,16 @@ public:
// Now OK to erase some losers // Now OK to erase some losers
for (unsigned i=0; i<oldSize - _newsize; i++) for (unsigned i=0; i<oldSize - _newsize; i++)
{ {
//OLDCODE EOT & eo = inverse_stochastic_tournament<EOT>(_newgen, t_rate); //OLDCODE EOT & eo = inverse_stochastic_tournament<EOT>(_newgen, t_rate);
//OLDCODE _newgen.erase(&eo); //OLDCODE _newgen.erase(&eo);
// Jeroen Eggermont stdc++v3 patch // Jeroen Eggermont stdc++v3 patch
// in the new code from stdc++v3 an iterator from a container<T> is no longer an pointer to T // in the new code from stdc++v3 an iterator from a container<T> is no longer an pointer to T
// Because eo already contained a fuction using eoPop<EOT>::iterator's we will use the following // Because eo already contained a fuction using eoPop<EOT>::iterator's we will use the following
_newgen.erase( inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate) ); _newgen.erase( inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate) );
} }
} }

View file

@ -1,9 +1,9 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoReduceMerge.h eoReduceMerge.h
(c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000 (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -41,8 +41,8 @@
* @{ * @{
*/ */
/** /**
eoReduceMerge: Replacement strategies that start by reducing the parents, eoReduceMerge: Replacement strategies that start by reducing the parents,
then merge with the offspring then merge with the offspring
This is the way to do SSGA: the offspring gets inserted in the population This is the way to do SSGA: the offspring gets inserted in the population
@ -63,10 +63,10 @@ class eoReduceMerge : public eoReplacement<EOT>
void operator()(eoPop<EOT>& _parents, eoPop<EOT>& _offspring) void operator()(eoPop<EOT>& _parents, eoPop<EOT>& _offspring)
{ {
if (_parents.size() < _offspring.size()) if (_parents.size() < _offspring.size())
throw std::logic_error("eoReduceMerge: More offspring than parents!\n"); throw std::logic_error("eoReduceMerge: More offspring than parents!\n");
reduce(_parents, _parents.size() - _offspring.size()); reduce(_parents, _parents.size() - _offspring.size());
merge(_offspring, _parents); merge(_offspring, _parents);
} }
private : private :
@ -74,10 +74,10 @@ class eoReduceMerge : public eoReplacement<EOT>
eoMerge<EOT>& merge; eoMerge<EOT>& merge;
}; };
/** /**
SSGA replace worst. Is an eoReduceMerge. SSGA replace worst. Is an eoReduceMerge.
*/ */
template <class EOT> template <class EOT>
class eoSSGAWorseReplacement : public eoReduceMerge<EOT> class eoSSGAWorseReplacement : public eoReduceMerge<EOT>
{ {
public : public :
@ -88,15 +88,15 @@ class eoSSGAWorseReplacement : public eoReduceMerge<EOT>
eoPlus<EOT> plus; eoPlus<EOT> plus;
}; };
/** /**
SSGA deterministic tournament replacement. Is an eoReduceMerge. SSGA deterministic tournament replacement. Is an eoReduceMerge.
*/ */
template <class EOT> template <class EOT>
class eoSSGADetTournamentReplacement : public eoReduceMerge<EOT> class eoSSGADetTournamentReplacement : public eoReduceMerge<EOT>
{ {
public : public :
eoSSGADetTournamentReplacement(unsigned _t_size) : eoSSGADetTournamentReplacement(unsigned _t_size) :
eoReduceMerge<EOT>(truncate, plus), truncate(_t_size) {} eoReduceMerge<EOT>(truncate, plus), truncate(_t_size) {}
private : private :
eoDetTournamentTruncate<EOT> truncate; eoDetTournamentTruncate<EOT> truncate;
@ -104,16 +104,16 @@ class eoSSGADetTournamentReplacement : public eoReduceMerge<EOT>
}; };
/** SSGA stochastic tournament replacement. Is an eoReduceMerge. /** SSGA stochastic tournament replacement. Is an eoReduceMerge.
It much cleaner to insert directly the offspring in the parent population, It much cleaner to insert directly the offspring in the parent population,
but it is NOT equivalent in case of more than 1 offspring as already but it is NOT equivalent in case of more than 1 offspring as already
replaced could be removed , which is not possible in the eoReduceMerge replaced could be removed , which is not possible in the eoReduceMerge
So what the heck ! */ So what the heck ! */
template <class EOT> template <class EOT>
class eoSSGAStochTournamentReplacement : public eoReduceMerge<EOT> class eoSSGAStochTournamentReplacement : public eoReduceMerge<EOT>
{ {
public : public :
eoSSGAStochTournamentReplacement(double _t_rate) : eoSSGAStochTournamentReplacement(double _t_rate) :
eoReduceMerge<EOT>(truncate, plus), truncate(_t_rate) {} eoReduceMerge<EOT>(truncate, plus), truncate(_t_rate) {}
private : private :
eoStochTournamentTruncate<EOT> truncate; eoStochTournamentTruncate<EOT> truncate;

View file

@ -1,9 +1,9 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoReduceMergeReduce.h eoReduceMergeReduce.h
(c) Maarten Keijzer, Marc Schoenauer, 2002 (c) Maarten Keijzer, Marc Schoenauer, 2002
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -49,13 +49,13 @@ template <class EOT>
class eoReduceMergeReduce : public eoReplacement<EOT> class eoReduceMergeReduce : public eoReplacement<EOT>
{ {
public: public:
eoReduceMergeReduce(eoHowMany _howManyElite, eoReduceMergeReduce(eoHowMany _howManyElite,
bool _strongElitism, bool _strongElitism,
eoHowMany _howManyReducedParents, eoHowMany _howManyReducedParents,
eoReduce<EOT> & _reduceParents, eoReduce<EOT> & _reduceParents,
eoHowMany _howManyReducedOffspring, eoHowMany _howManyReducedOffspring,
eoReduce<EOT> & _reduceOffspring, eoReduce<EOT> & _reduceOffspring,
eoReduce<EOT> & _reduceFinal) : eoReduce<EOT> & _reduceFinal) :
howManyElite(_howManyElite), howManyElite(_howManyElite),
strongElitism(_strongElitism), strongElitism(_strongElitism),
howManyReducedParents(_howManyReducedParents), howManyReducedParents(_howManyReducedParents),
@ -64,7 +64,7 @@ public:
reduceOffspring(_reduceOffspring), reduceOffspring(_reduceOffspring),
reduceFinal(_reduceFinal) reduceFinal(_reduceFinal)
{} {}
void operator()(eoPop<EOT> & _parents, eoPop<EOT> & _offspring) void operator()(eoPop<EOT> & _parents, eoPop<EOT> & _offspring)
{ {
eoPop<EOT> temp; eoPop<EOT> temp;
@ -72,66 +72,66 @@ public:
unsigned int offSize = _offspring.size(); unsigned int offSize = _offspring.size();
unsigned int elite = howManyElite(finalPopSize); unsigned int elite = howManyElite(finalPopSize);
if (elite) // some parents MUST be saved somewhere if (elite) // some parents MUST be saved somewhere
{ {
temp.resize(elite); temp.resize(elite);
_parents.nth_element(elite); _parents.nth_element(elite);
std::copy(_parents.begin(), _parents.begin()+elite, temp.begin()); std::copy(_parents.begin(), _parents.begin()+elite, temp.begin());
_parents.erase(_parents.begin(), _parents.begin()+elite); _parents.erase(_parents.begin(), _parents.begin()+elite);
} }
// the reduce steps. First the parents // the reduce steps. First the parents
unsigned reducedParentSize = howManyReducedParents(_parents.size()); unsigned reducedParentSize = howManyReducedParents(_parents.size());
if (!reducedParentSize) if (!reducedParentSize)
_parents.clear(); _parents.clear();
else if (reducedParentSize != _parents.size()) else if (reducedParentSize != _parents.size())
reduceParents(_parents, reducedParentSize); reduceParents(_parents, reducedParentSize);
// then the offspring // then the offspring
unsigned reducedOffspringSize = howManyReducedOffspring(offSize); unsigned reducedOffspringSize = howManyReducedOffspring(offSize);
if (!reducedOffspringSize) if (!reducedOffspringSize)
throw std::runtime_error("No offspring left after reduction!"); throw std::runtime_error("No offspring left after reduction!");
if (reducedOffspringSize != offSize) // need reduction if (reducedOffspringSize != offSize) // need reduction
reduceOffspring(_offspring, reducedOffspringSize); reduceOffspring(_offspring, reducedOffspringSize);
// now merge reduced populations // now merge reduced populations
_parents.resize(reducedParentSize + _offspring.size()); _parents.resize(reducedParentSize + _offspring.size());
std::copy(_offspring.begin(), _offspring.end(), std::copy(_offspring.begin(), _offspring.end(),
_parents.begin()+reducedParentSize); _parents.begin()+reducedParentSize);
// reduce the resulting population // reduce the resulting population
// size depstd::ends on elitism // size depstd::ends on elitism
if (elite && strongElitism) if (elite && strongElitism)
{ {
if (_parents.size() != finalPopSize-elite) if (_parents.size() != finalPopSize-elite)
reduceFinal(_parents, finalPopSize-elite); reduceFinal(_parents, finalPopSize-elite);
// and put back the elite // and put back the elite
unsigned oldPSize = _parents.size(); unsigned oldPSize = _parents.size();
_parents.resize(_parents.size()+elite); _parents.resize(_parents.size()+elite);
std::copy(temp.begin(), temp.end(), _parents.begin()+oldPSize); std::copy(temp.begin(), temp.end(), _parents.begin()+oldPSize);
} }
else else
{ // only reduce final pop to right size { // only reduce final pop to right size
if (_parents.size() != finalPopSize) if (_parents.size() != finalPopSize)
reduceFinal(_parents, finalPopSize); reduceFinal(_parents, finalPopSize);
if (elite) // then treat weak elitism if (elite) // then treat weak elitism
{ {
unsigned toSave = 0; unsigned toSave = 0;
_parents.sort(); _parents.sort();
EOT & eoLimit = _parents[elite-1]; EOT & eoLimit = _parents[elite-1];
unsigned index=0; unsigned index=0;
while ( (temp[index++] > eoLimit) && (index < temp.size()) ) while ( (temp[index++] > eoLimit) && (index < temp.size()) )
toSave++; toSave++;
if (toSave) if (toSave)
for (unsigned i=0; i<toSave; i++) for (unsigned i=0; i<toSave; i++)
_parents[finalPopSize-1-i] = temp[i]; _parents[finalPopSize-1-i] = temp[i];
} }
} }
} }
private: private:
eoHowMany howManyElite; // if 0, no elitism at all eoHowMany howManyElite; // if 0, no elitism at all
bool strongElitism; // if false -> weak estd::listism bool strongElitism; // if false -> weak estd::listism
eoHowMany howManyReducedParents; // if 0, no parent in final replacement eoHowMany howManyReducedParents; // if 0, no parent in final replacement
eoHowMany howManyReducedOffspring; // if 0, std::runtime_error eoHowMany howManyReducedOffspring; // if 0, std::runtime_error
// the reducers // the reducers

View file

@ -4,7 +4,7 @@
// eoReduceSplit.h // eoReduceSplit.h
// Base class for population-reducing classes - retaining the poor losers // Base class for population-reducing classes - retaining the poor losers
// (c) GeNeura Team, 1998, Marc Schoenauer, 2002 // (c) GeNeura Team, 1998, Marc Schoenauer, 2002
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -47,16 +47,16 @@ template<class EOT> class eoReduceSplit: public eoBF<eoPop<EOT>&, eoPop<EOT> &,
{}; {};
/** deterministic truncation method using sort */ /** deterministic truncation method using sort */
template <class EOT> template <class EOT>
class eoTruncateSplit : public eoReduceSplit<EOT> class eoTruncateSplit : public eoReduceSplit<EOT>
{ {
public: public:
/** Ctor: must provide amount of reduction, /** Ctor: must provide amount of reduction,
and whether or not you need to return the eliminated guys and whether or not you need to return the eliminated guys
*/ */
eoTruncateSplit(eoHowMany _howMany, bool _returnEliminated = false): eoTruncateSplit(eoHowMany _howMany, bool _returnEliminated = false):
howMany(_howMany), returnEliminated(_returnEliminated) {} howMany(_howMany), returnEliminated(_returnEliminated) {}
/** do the jonb */ /** do the jonb */
void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated) void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated)
{ {
@ -67,13 +67,13 @@ public:
unsigned newsize = popSize - eliminated; unsigned newsize = popSize - eliminated;
if (newsize < 0) if (newsize < 0)
throw std::logic_error("eoTruncateSplit: Cannot truncate to a larger size!\n"); throw std::logic_error("eoTruncateSplit: Cannot truncate to a larger size!\n");
_newgen.nth_element(newsize); _newgen.nth_element(newsize);
// save poor losers if necessary // save poor losers if necessary
if (returnEliminated) if (returnEliminated)
for (unsigned i=0; i<eliminated; i++) for (unsigned i=0; i<eliminated; i++)
_eliminated.push_back(_newgen[newsize+i]); _eliminated.push_back(_newgen[newsize+i]);
// truncate // truncate
_newgen.resize(newsize); _newgen.resize(newsize);
return ; return ;
@ -87,16 +87,16 @@ private:
/** a ReduceSplit class that does not sort, but repeatidely kills the worse. /** a ReduceSplit class that does not sort, but repeatidely kills the worse.
To be used in SSGA-like replacements (e.g. see eoSSGAWorseReplacement) To be used in SSGA-like replacements (e.g. see eoSSGAWorseReplacement)
*/ */
template <class EOT> template <class EOT>
class eoLinearTruncateSplit : public eoReduceSplit<EOT> class eoLinearTruncateSplit : public eoReduceSplit<EOT>
{ {
public: public:
/** Ctor: must provide amount of reduction, /** Ctor: must provide amount of reduction,
and whether or not you need to return the eliminated guys and whether or not you need to return the eliminated guys
*/ */
eoLinearTruncateSplit(eoHowMany _howMany, bool _returnEliminated = false): eoLinearTruncateSplit(eoHowMany _howMany, bool _returnEliminated = false):
howMany(_howMany), returnEliminated(_returnEliminated) {} howMany(_howMany), returnEliminated(_returnEliminated) {}
/** do the job */ /** do the job */
void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated) void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated)
{ {
@ -111,10 +111,10 @@ public:
_eliminated.reserve(_eliminated.size()+eliminated); //in case not empty? _eliminated.reserve(_eliminated.size()+eliminated); //in case not empty?
for (unsigned i=0; i<eliminated; i++) for (unsigned i=0; i<eliminated; i++)
{ {
typename eoPop<EOT>::iterator it = _newgen.it_worse_element(); typename eoPop<EOT>::iterator it = _newgen.it_worse_element();
if (returnEliminated) if (returnEliminated)
_eliminated.push_back(*it); _eliminated.push_back(*it);
_newgen.erase(it); _newgen.erase(it);
} }
} }
@ -124,16 +124,16 @@ private:
}; };
/** random truncation - batch version */ /** random truncation - batch version */
template <class EOT> template <class EOT>
class eoRandomSplit : public eoReduceSplit<EOT> class eoRandomSplit : public eoReduceSplit<EOT>
{ {
public: public:
/** Ctor: must provide amount of reduction, /** Ctor: must provide amount of reduction,
and whether or not you need to return the eliminated guys and whether or not you need to return the eliminated guys
*/ */
eoRandomSplit(eoHowMany _howMany, bool _returnEliminated = false): eoRandomSplit(eoHowMany _howMany, bool _returnEliminated = false):
howMany(_howMany), returnEliminated(_returnEliminated) {} howMany(_howMany), returnEliminated(_returnEliminated) {}
/** do the job */ /** do the job */
void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated) void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated)
{ {
@ -150,7 +150,7 @@ public:
// save poor losers if necessary // save poor losers if necessary
if (returnEliminated) if (returnEliminated)
for (unsigned i=0; i<eliminated; i++) for (unsigned i=0; i<eliminated; i++)
_eliminated.push_back(_newgen[newsize+i]); _eliminated.push_back(_newgen[newsize+i]);
// truncate // truncate
_newgen.resize(newsize); _newgen.resize(newsize);
return ; return ;
@ -163,16 +163,16 @@ private:
/** random truncation - linear version */ /** random truncation - linear version */
template <class EOT> template <class EOT>
class eoLinearRandomSplit : public eoReduceSplit<EOT> class eoLinearRandomSplit : public eoReduceSplit<EOT>
{ {
public: public:
/** Ctor: must provide amount of reduction, /** Ctor: must provide amount of reduction,
and whether or not you need to return the eliminated guys and whether or not you need to return the eliminated guys
*/ */
eoLinearRandomSplit(eoHowMany _howMany, bool _returnEliminated = false): eoLinearRandomSplit(eoHowMany _howMany, bool _returnEliminated = false):
howMany(_howMany), returnEliminated(_returnEliminated) {} howMany(_howMany), returnEliminated(_returnEliminated) {}
/** do the job */ /** do the job */
void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated) void operator()(eoPop<EOT>& _newgen, eoPop<EOT> & _eliminated)
{ {
@ -187,11 +187,11 @@ public:
_eliminated.reserve(_eliminated.size()+eliminated); //in case not empty? _eliminated.reserve(_eliminated.size()+eliminated); //in case not empty?
for (unsigned i=0; i<eliminated; i++) for (unsigned i=0; i<eliminated; i++)
{ {
unsigned loser=random(_newgen.size()); unsigned loser=random(_newgen.size());
typename eoPop<EOT>::iterator it = _newgen.begin()+loser; typename eoPop<EOT>::iterator it = _newgen.begin()+loser;
if (returnEliminated) if (returnEliminated)
_eliminated.push_back(*it); _eliminated.push_back(*it);
_newgen.erase(it); _newgen.erase(it);
} }
return ; return ;
} }
@ -205,22 +205,22 @@ private:
/** a ReduceSplit class based on a repeated deterministic (reverse!) tournament /** a ReduceSplit class based on a repeated deterministic (reverse!) tournament
To be used in SSGA-like replacements (e.g. see eoSSGADetTournamentReplacement) To be used in SSGA-like replacements (e.g. see eoSSGADetTournamentReplacement)
*/ */
template <class EOT> template <class EOT>
class eoDetTournamentTruncateSplit : public eoReduceSplit<EOT> class eoDetTournamentTruncateSplit : public eoReduceSplit<EOT>
{ {
public: public:
/** Ctor: must provide amount of reduction, /** Ctor: must provide amount of reduction,
and whether or not you need to return the eliminated guys and whether or not you need to return the eliminated guys
*/ */
eoDetTournamentTruncateSplit(unsigned _t_size, eoHowMany _howMany, eoDetTournamentTruncateSplit(unsigned _t_size, eoHowMany _howMany,
bool _returnEliminated = false): bool _returnEliminated = false):
t_size(_t_size), howMany(_howMany), t_size(_t_size), howMany(_howMany),
returnEliminated(_returnEliminated) returnEliminated(_returnEliminated)
{ {
if (t_size < 2) if (t_size < 2)
{ {
eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncateSplit adjusted to 2" << std::endl; eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncateSplit adjusted to 2" << std::endl;
t_size = 2; t_size = 2;
} }
} }
@ -240,10 +240,10 @@ public:
_eliminated.reserve(_eliminated.size()+eliminated); //in case not empty? _eliminated.reserve(_eliminated.size()+eliminated); //in case not empty?
for (unsigned i=0; i<eliminated; i++) for (unsigned i=0; i<eliminated; i++)
{ {
typename eoPop<EOT>::iterator it = inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size); typename eoPop<EOT>::iterator it = inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size);
if (returnEliminated) if (returnEliminated)
_eliminated.push_back(*it); _eliminated.push_back(*it);
_newgen.erase(it); _newgen.erase(it);
} }
} }
@ -256,27 +256,27 @@ private:
/** a ReduceSplit class based on a repeated deterministic (reverse!) tournament /** a ReduceSplit class based on a repeated deterministic (reverse!) tournament
To be used in SSGA-like replacements (e.g. see eoSSGAStochTournamentReplacement) To be used in SSGA-like replacements (e.g. see eoSSGAStochTournamentReplacement)
*/ */
template <class EOT> template <class EOT>
class eoStochTournamentTruncateSplit : public eoReduce<EOT> class eoStochTournamentTruncateSplit : public eoReduce<EOT>
{ {
public: public:
/** Ctor: must provide amount of reduction, /** Ctor: must provide amount of reduction,
and whether or not you need to return the eliminated guys and whether or not you need to return the eliminated guys
*/ */
eoStochTournamentTruncateSplit(double _t_rate, eoHowMany _howMany, eoStochTournamentTruncateSplit(double _t_rate, eoHowMany _howMany,
bool _returnEliminated = false): bool _returnEliminated = false):
t_rate(_t_rate), howMany(_howMany), t_rate(_t_rate), howMany(_howMany),
returnEliminated(_returnEliminated) returnEliminated(_returnEliminated)
{ {
if (t_rate <= 0.5) if (t_rate <= 0.5)
{ {
eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncateSplit adjusted to 0.51" << std::endl; eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncateSplit adjusted to 0.51" << std::endl;
t_rate = 0.51; t_rate = 0.51;
} }
if (t_rate > 1) if (t_rate > 1)
{ {
eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncateSplit adjusted to 1" << std::endl; eo::log << eo::warnings << "Warning, Rate for eoStochTournamentTruncateSplit adjusted to 1" << std::endl;
t_rate = 1; t_rate = 1;
} }
} }
@ -285,7 +285,7 @@ public:
//BUG??? void operator()(eoPop<EOT>& _newgen, unsigned _newsize) //BUG??? void operator()(eoPop<EOT>& _newgen, unsigned _newsize)
{ {
/* old version /* old version
if (!_eliminated.size()) // nothing to do if (!_eliminated.size()) // nothing to do
return; return;
unsigned oldSize = _newgen.size(); unsigned oldSize = _newgen.size();
unsigned newSize = oldSize - _eliminated.size(); unsigned newSize = oldSize - _eliminated.size();
@ -308,10 +308,10 @@ end of old version */
_eliminated.reserve(_eliminated.size()+eliminated); //in case not empty? _eliminated.reserve(_eliminated.size()+eliminated); //in case not empty?
for (unsigned i=0; i<_eliminated.size(); i++) for (unsigned i=0; i<_eliminated.size(); i++)
{ {
typename eoPop<EOT>::iterator it = inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate); typename eoPop<EOT>::iterator it = inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate);
if (returnEliminated) if (returnEliminated)
_eliminated.push_back(*it); _eliminated.push_back(*it);
_newgen.erase(it); _newgen.erase(it);
} }
} }

View file

@ -1,9 +1,9 @@
/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
----------------------------------------------------------------------------- -----------------------------------------------------------------------------
eoReplacement.h eoReplacement.h
(c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000 (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -36,9 +36,9 @@
#include <utils/eoHowMany.h> #include <utils/eoHowMany.h>
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
/** /**
--- ---
The eoMergeReduce, combination of eoMerge and eoReduce, can be found The eoMergeReduce, combination of eoMerge and eoReduce, can be found
in file eoMergeReduce.h in file eoMergeReduce.h
The eoReduceMergeReduce that reduces the parents and the offspring, The eoReduceMergeReduce that reduces the parents and the offspring,
@ -47,15 +47,15 @@ population, can be found in eoReduceMergeReduce.h
LOG LOG
--- ---
Removed the const before first argument: though it makes too many classes Removed the const before first argument: though it makes too many classes
with the same interface, it allows to minimize the number of actual copies with the same interface, it allows to minimize the number of actual copies
by choosing the right destination by choosing the right destination
I also removed the enforced "swap" in the eoEasyAlgo and hence the generational I also removed the enforced "swap" in the eoEasyAlgo and hence the generational
replacement gets a class of its own that only does the swap (instead of the replacement gets a class of its own that only does the swap (instead of the
eoNoReplacement that did nothing, relying on the algo to swap popualtions). eoNoReplacement that did nothing, relying on the algo to swap popualtions).
MS 12/12/2000 MS 12/12/2000
@see eoMerge, eoReduce, eoMergeReduce, eoReduceMerge @see eoMerge, eoReduce, eoMergeReduce, eoReduceMerge
@class eoReplacement, base (pure abstract) class @class eoReplacement, base (pure abstract) class
@class eoGenerationalReplacement, as it says ... @class eoGenerationalReplacement, as it says ...
@ -67,7 +67,7 @@ MS 12/12/2000
NOTE: two eoPop as arguments NOTE: two eoPop as arguments
the resulting population should be in the first argument (replace the resulting population should be in the first argument (replace
parents by offspring)! The second argument can contain any rubbish parents by offspring)! The second argument can contain any rubbish
@ingroup Replacors @ingroup Replacors
*/ */
@ -91,10 +91,10 @@ class eoGenerationalReplacement : public eoReplacement<EOT>
} }
}; };
/** /**
eoWeakElitistReplacement: a wrapper for other replacement procedures. eoWeakElitistReplacement: a wrapper for other replacement procedures.
Copies in the new pop the best individual from the old pop, Copies in the new pop the best individual from the old pop,
AFTER normal replacement, if the best of the new pop is worse than the best AFTER normal replacement, if the best of the new pop is worse than the best
of the old pop. Removes the worse individual from the new pop. of the old pop. Removes the worse individual from the new pop.
This could be changed by adding a selector there... This could be changed by adding a selector there...
@ -114,11 +114,11 @@ public :
void operator()(eoPop<EOT>& _pop, eoPop<EOT>& _offspring) void operator()(eoPop<EOT>& _pop, eoPop<EOT>& _offspring)
{ {
const EOT oldChamp = _pop.best_element(); const EOT oldChamp = _pop.best_element();
replace(_pop, _offspring); // "normal" replacement, parents are the new replace(_pop, _offspring); // "normal" replacement, parents are the new
if (_pop.best_element() < oldChamp) // need to do something if (_pop.best_element() < oldChamp) // need to do something
{ {
typename eoPop<EOT>::iterator itPoorGuy = _pop.it_worse_element(); typename eoPop<EOT>::iterator itPoorGuy = _pop.it_worse_element();
(*itPoorGuy) = oldChamp; (*itPoorGuy) = oldChamp;
} }
} }
private: private:

View file

@ -3,10 +3,10 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoRingTopology.h // eoRingTopology.h
// (c) INRIA Futurs DOLPHIN 2007 // (c) INRIA Futurs DOLPHIN 2007
/* /*
Clive Canape Clive Canape
Thomas Legrand Thomas Legrand
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -48,7 +48,7 @@ template < class POT > class eoRingTopology:public eoTopology <POT>
public: public:
/** /**
* The only Ctor. * The only Ctor.
* @param _neighborhoodSize - The size of each neighborhood. * @param _neighborhoodSize - The size of each neighborhood.
*/ */
eoRingTopology (unsigned _neighborhoodSize):neighborhoodSize (_neighborhoodSize),isSetup(false){} eoRingTopology (unsigned _neighborhoodSize):neighborhoodSize (_neighborhoodSize),isSetup(false){}
@ -68,16 +68,16 @@ public:
int k = neighborhoodSize/2; int k = neighborhoodSize/2;
for (unsigned i=0;i < _pop.size();i++) for (unsigned i=0;i < _pop.size();i++)
{ {
eoSocialNeighborhood<POT> currentNghd; eoSocialNeighborhood<POT> currentNghd;
currentNghd.best(_pop[i]); currentNghd.best(_pop[i]);
for (unsigned j=0; j < neighborhoodSize; j++) for (unsigned j=0; j < neighborhoodSize; j++)
{ {
currentNghd.put((_pop.size()+i-k+j)%_pop.size()); currentNghd.put((_pop.size()+i-k+j)%_pop.size());
if(_pop[(_pop.size()+i-k+j)%_pop.size()].fitness() > currentNghd.best().fitness()) if(_pop[(_pop.size()+i-k+j)%_pop.size()].fitness() > currentNghd.best().fitness())
currentNghd.best(_pop[(_pop.size()+i-k+j)%_pop.size()]); currentNghd.best(_pop[(_pop.size()+i-k+j)%_pop.size()]);
} }
neighborhoods.push_back(currentNghd); neighborhoods.push_back(currentNghd);
} }
isSetup=true; isSetup=true;
} }
else else
@ -90,7 +90,7 @@ public:
*/ */
} }
} }
/** /**
* Retrieves the neighboorhood of a particle. * Retrieves the neighboorhood of a particle.
* @return _indice - The particle indice (in the population) * @return _indice - The particle indice (in the population)
@ -109,20 +109,20 @@ public:
*/ */
void updateNeighborhood(POT & _po,unsigned _indice) void updateNeighborhood(POT & _po,unsigned _indice)
{ {
//this->printOn();exit(0); //this->printOn();exit(0);
// update the best fitness of the particle // update the best fitness of the particle
if (_po.fitness() > _po.best()) if (_po.fitness() > _po.best())
{ {
_po.best(_po.fitness()); _po.best(_po.fitness());
for(unsigned i=0;i<_po.size();i++) for(unsigned i=0;i<_po.size();i++)
_po.bestPositions[i]=_po[i]; _po.bestPositions[i]=_po[i];
} }
// update the global best if the given particle is "better" // update the global best if the given particle is "better"
for (unsigned i=-neighborhoodSize+1; i < neighborhoodSize; i++) for (unsigned i=-neighborhoodSize+1; i < neighborhoodSize; i++)
{ {
unsigned indi = (_po.size()+_indice+i)%_po.size(); unsigned indi = (_po.size()+_indice+i)%_po.size();
if (_po.fitness() > neighborhoods[indi].best().fitness()) if (_po.fitness() > neighborhoods[indi].best().fitness())
neighborhoods[indi].best(_po); neighborhoods[indi].best(_po);
} }
} }
@ -132,9 +132,9 @@ public:
* @param _indice - The indice of a particle in the population * @param _indice - The indice of a particle in the population
* @return POT & - The best particle in the neighborhood of the particle whose indice is _indice * @return POT & - The best particle in the neighborhood of the particle whose indice is _indice
*/ */
POT & best (unsigned _indice) POT & best (unsigned _indice)
{ {
unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice); unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice);
return (neighborhoods[theGoodNhbd].best()); return (neighborhoods[theGoodNhbd].best());
} }
@ -155,35 +155,35 @@ public:
std::cout << "}" << std::endl; std::cout << "}" << std::endl;
} }
} }
/* /*
* Return the global best of the topology * Return the global best of the topology
*/ */
virtual POT & globalBest() virtual POT & globalBest()
{ {
POT gBest,tmp; POT gBest,tmp;
unsigned indGlobalBest=0; unsigned indGlobalBest=0;
if(neighborhoods.size()==1) if(neighborhoods.size()==1)
return neighborhoods[0].best(); return neighborhoods[0].best();
gBest=neighborhoods[0].best(); gBest=neighborhoods[0].best();
for(unsigned i=1;i<neighborhoods.size();i++) for(unsigned i=1;i<neighborhoods.size();i++)
{ {
tmp=neighborhoods[i].best(); tmp=neighborhoods[i].best();
if(gBest.best() < tmp.best()) if(gBest.best() < tmp.best())
{ {
gBest=tmp; gBest=tmp;
indGlobalBest=i; indGlobalBest=i;
} }
} }
return neighborhoods[indGlobalBest].best(); return neighborhoods[indGlobalBest].best();
} }
protected: protected:
std::vector<eoSocialNeighborhood<POT> > neighborhoods; std::vector<eoSocialNeighborhood<POT> > neighborhoods;
unsigned neighborhoodSize; unsigned neighborhoodSize;
bool isSetup; bool isSetup;
}; };
/** @example t-eoRingTopology.cpp /** @example t-eoRingTopology.cpp

View file

@ -58,7 +58,7 @@ public :
eoQuadOp<EOT>& _cross, float _crate, eoQuadOp<EOT>& _cross, float _crate,
eoMonOp<EOT>& _mutate, float _mrate, eoMonOp<EOT>& _mutate, float _mrate,
eoEvalFunc<EOT>& _eval, eoEvalFunc<EOT>& _eval,
eoContinue<EOT>& _cont) eoContinue<EOT>& _cont)
: cont(_cont), : cont(_cont),
mutate(_mutate), mutate(_mutate),
mutationRate(_mrate), mutationRate(_mrate),
@ -73,34 +73,34 @@ public :
do do
{ {
select(_pop, offspring); select(_pop, offspring);
unsigned i; unsigned i;
for (i=0; i<_pop.size()/2; i++) for (i=0; i<_pop.size()/2; i++)
{ {
if ( rng.flip(crossoverRate) ) if ( rng.flip(crossoverRate) )
{ {
// this crossover generates 2 offspring from two parents // this crossover generates 2 offspring from two parents
if (cross(offspring[2*i], offspring[2*i+1])) if (cross(offspring[2*i], offspring[2*i+1]))
{ {
offspring[2*i].invalidate(); offspring[2*i].invalidate();
offspring[2*i+1].invalidate(); offspring[2*i+1].invalidate();
} }
} }
} }
for (i=0; i < offspring.size(); i++) for (i=0; i < offspring.size(); i++)
{ {
if (rng.flip(mutationRate) ) if (rng.flip(mutationRate) )
{ {
if (mutate(offspring[i])) if (mutate(offspring[i]))
offspring[i].invalidate(); offspring[i].invalidate();
} }
} }
_pop.swap(offspring); _pop.swap(offspring);
apply<EOT>(eval, _pop); apply<EOT>(eval, _pop);
} while (cont(_pop)); } while (cont(_pop));
} }

View file

@ -33,40 +33,40 @@
// class eoSGAGenOp // class eoSGAGenOp
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
/** /**
* eoSGAGenOp (for Simple GA) mimicks the usual crossover with proba pCross + * eoSGAGenOp (for Simple GA) mimicks the usual crossover with proba pCross +
* mutation with proba pMut inside an eoGeneralOp * mutation with proba pMut inside an eoGeneralOp
* It does it exactly as class eoSGATransform, i.e. only accepts * It does it exactly as class eoSGATransform, i.e. only accepts
* quadratic crossover and unary mutation * quadratic crossover and unary mutation
* It was introduced for didactic reasons, but seems to be popular :-) * It was introduced for didactic reasons, but seems to be popular :-)
* *
* @ingroup Combination * @ingroup Combination
*/ */
template<class EOT> template<class EOT>
class eoSGAGenOp : public eoGenOp<EOT> class eoSGAGenOp : public eoGenOp<EOT>
{ {
public: public:
/** Ctor from crossover (with proba) and mutation (with proba) /** Ctor from crossover (with proba) and mutation (with proba)
* Builds the sequential op that first applies a proportional choice * Builds the sequential op that first applies a proportional choice
* between the crossover and nothing (cloning), then the mutation * between the crossover and nothing (cloning), then the mutation
*/ */
eoSGAGenOp(eoQuadOp<EOT>& _cross, double _pCross, eoSGAGenOp(eoQuadOp<EOT>& _cross, double _pCross,
eoMonOp<EOT>& _mut, double _pMut) eoMonOp<EOT>& _mut, double _pMut)
: cross(_cross), : cross(_cross),
pCross(_pCross), pCross(_pCross),
mut(_mut), mut(_mut),
pMut(_pMut) pMut(_pMut)
{ {
// the crossover - with probability pCross // the crossover - with probability pCross
propOp.add(cross, pCross); // crossover, with proba pcross propOp.add(cross, pCross); // crossover, with proba pcross
propOp.add(quadClone, 1-pCross); // nothing, with proba 1-pcross propOp.add(quadClone, 1-pCross); // nothing, with proba 1-pcross
// now the sequential // now the sequential
op.add(propOp, 1.0); // always do combined crossover op.add(propOp, 1.0); // always do combined crossover
op.add(mut, pMut); // then mutation, with proba pmut op.add(mut, pMut); // then mutation, with proba pmut
} }
/** do the job: delegate to op */ /** do the job: delegate to op */
virtual void apply(eoPopulator<EOT>& _pop) virtual void apply(eoPopulator<EOT>& _pop)
{ {

View file

@ -38,7 +38,7 @@
#include <eoTransform.h> #include <eoTransform.h>
/** eoSGATransform: transforms a population using genetic operators. /** eoSGATransform: transforms a population using genetic operators.
* It does it exactly as class eoSGA, i.e. only accepts * It does it exactly as class eoSGA, i.e. only accepts
* quadratic crossover and unary mutation * quadratic crossover and unary mutation
* It is here mainly for tutorial reasons * It is here mainly for tutorial reasons
* *
@ -47,13 +47,13 @@
template<class EOT> class eoSGATransform : public eoTransform<EOT> template<class EOT> class eoSGATransform : public eoTransform<EOT>
{ {
public: public:
/// Default constructor. /// Default constructor.
eoSGATransform(eoQuadOp<EOT>& _cross, double _cProba, eoSGATransform(eoQuadOp<EOT>& _cross, double _cProba,
eoMonOp<EOT>& _mutate, double _mProba) eoMonOp<EOT>& _mutate, double _mProba)
: cross(_cross), : cross(_cross),
crossoverProba(_cProba), crossoverProba(_cProba),
mutate(_mutate), mutate(_mutate),
mutationProba(_mProba) {} mutationProba(_mProba) {}
@ -61,29 +61,29 @@ template<class EOT> class eoSGATransform : public eoTransform<EOT>
* Transforms a population. * Transforms a population.
* @param _pop The population to be transformed. * @param _pop The population to be transformed.
*/ */
void operator()(eoPop<EOT>& _pop) void operator()(eoPop<EOT>& _pop)
{ {
unsigned i; unsigned i;
for (i=0; i<_pop.size()/2; i++) for (i=0; i<_pop.size()/2; i++)
{ {
if ( rng.flip(crossoverProba) ) if ( rng.flip(crossoverProba) )
{ {
// this crossover generates 2 offspring from two parents // this crossover generates 2 offspring from two parents
cross(_pop[2*i], _pop[2*i+1]); cross(_pop[2*i], _pop[2*i+1]);
} }
} }
for (i=0; i < _pop.size(); i++) for (i=0; i < _pop.size(); i++)
{ {
if (rng.flip(mutationProba) ) if (rng.flip(mutationProba) )
{ {
mutate(_pop[i]); mutate(_pop[i]);
} }
} }
}; };
private: private:
eoInvalidateQuadOp<EOT> cross; eoInvalidateQuadOp<EOT> cross;
double crossoverProba; double crossoverProba;
@ -93,7 +93,7 @@ template<class EOT> class eoSGATransform : public eoTransform<EOT>
/** eoDynSGATransform: transforms a population using genetic operators. /** eoDynSGATransform: transforms a population using genetic operators.
* It is the Dynamic version of the above eoSGATransform * It is the Dynamic version of the above eoSGATransform
* i.e. the operators probabilities can be passed as an eoValueParam, * i.e. the operators probabilities can be passed as an eoValueParam,
* and hence can be modified from outside * and hence can be modified from outside
* It is here mainly for tutorial reasons * It is here mainly for tutorial reasons
* *
@ -102,23 +102,23 @@ template<class EOT> class eoSGATransform : public eoTransform<EOT>
template<class EOT> class eoDynSGATransform : public eoTransform<EOT> template<class EOT> class eoDynSGATransform : public eoTransform<EOT>
{ {
public: public:
/// Default constructor - receives values /// Default constructor - receives values
eoDynSGATransform(eoQuadOp<EOT>& _cross, double _cProba, eoDynSGATransform(eoQuadOp<EOT>& _cross, double _cProba,
eoMonOp<EOT>& _mutate, double _mProba) eoMonOp<EOT>& _mutate, double _mProba)
: cross(_cross), : cross(_cross),
crossoverProbaHolder(_cProba), crossoverProba(crossoverProbaHolder), crossoverProbaHolder(_cProba), crossoverProba(crossoverProbaHolder),
mutate(_mutate), mutate(_mutate),
mutationProbaHolder(_mProba), mutationProba(mutationProbaHolder) {} mutationProbaHolder(_mProba), mutationProba(mutationProbaHolder) {}
/// This constructor receives pointers /// This constructor receives pointers
// these will usually be some eoValueParam<double>.value() // these will usually be some eoValueParam<double>.value()
// hence the ...Holder data will bever be used in this case // hence the ...Holder data will bever be used in this case
eoDynSGATransform(eoQuadOp<EOT>& _cross, double* _cProbaRef, eoDynSGATransform(eoQuadOp<EOT>& _cross, double* _cProbaRef,
eoMonOp<EOT>& _mutate, double* _mProbaRef) eoMonOp<EOT>& _mutate, double* _mProbaRef)
: cross(_cross), : cross(_cross),
crossoverProbaHolder(0), crossoverProba(*_cProbaRef), crossoverProbaHolder(0), crossoverProba(*_cProbaRef),
mutate(_mutate), mutate(_mutate),
mutationProbaHolder(0), mutationProba(*_mProbaRef) {} mutationProbaHolder(0), mutationProba(*_mProbaRef) {}
@ -126,34 +126,34 @@ template<class EOT> class eoDynSGATransform : public eoTransform<EOT>
* Transforms a population. * Transforms a population.
* @param _pop The population to be transformed. * @param _pop The population to be transformed.
*/ */
void operator()(eoPop<EOT>& _pop) void operator()(eoPop<EOT>& _pop)
{ {
unsigned i; unsigned i;
for (i=0; i<_pop.size()/2; i++) for (i=0; i<_pop.size()/2; i++)
{ {
if ( rng.flip(crossoverProba) ) if ( rng.flip(crossoverProba) )
{ {
// this crossover generates 2 offspring from two parents // this crossover generates 2 offspring from two parents
cross(_pop[2*i], _pop[2*i+1]); cross(_pop[2*i], _pop[2*i+1]);
} }
} }
for (i=0; i < _pop.size(); i++) for (i=0; i < _pop.size(); i++)
{ {
if (rng.flip(mutationProba) ) if (rng.flip(mutationProba) )
{ {
mutate(_pop[i]); mutate(_pop[i]);
} }
} }
}; };
// accessors - mainly for EASEA // accessors - mainly for EASEA
double & PCrossHandle() { return crossoverProba;} double & PCrossHandle() { return crossoverProba;}
double & PMutHandle() { return mutationProba;} double & PMutHandle() { return mutationProba;}
private: private:
// difference with eoSGATransform: the operator probabilities // difference with eoSGATransform: the operator probabilities
// they can be passed by reference or by value. // they can be passed by reference or by value.
// hence we need here to use a reference, and to eventually store a value // hence we need here to use a reference, and to eventually store a value
eoInvalidateQuadOp<EOT> cross; eoInvalidateQuadOp<EOT> cross;

View file

@ -1,34 +1,34 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoSIGContinue.cpp // eoSIGContinue.cpp
// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 // (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr Marc.Schoenauer@polytechnique.fr
mak@dhi.dk mak@dhi.dk
Johann Dréo <nojhan@gmail.com> Johann Dréo <nojhan@gmail.com>
Caner Candan <caner@candan.fr> Caner Candan <caner@candan.fr>
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#ifdef _MSC_VER #ifdef _MSC_VER
// to avoid long name warnings // to avoid long name warnings
#pragma warning(disable:4786) #pragma warning(disable:4786)
#endif #endif
#include <signal.h> #include <signal.h>
#include <iostream> #include <iostream>

View file

@ -1,28 +1,28 @@
// -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*-
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoSIGContinue.h // eoSIGContinue.h
// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 // (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version. version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details. Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact: todos@geneura.ugr.es, http://geneura.ugr.es Contact: todos@geneura.ugr.es, http://geneura.ugr.es
Marc.Schoenauer@polytechnique.fr Marc.Schoenauer@polytechnique.fr
mak@dhi.dk mak@dhi.dk
Johann Dréo <nojhan@gmail.com> Johann Dréo <nojhan@gmail.com>
Caner Candan <caner@candan.fr> Caner Candan <caner@candan.fr>
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// the same thing can probably be done in MS environement, but I hoave no way // the same thing can probably be done in MS environement, but I hoave no way
@ -75,8 +75,8 @@ public:
{ {
if (call_func) if (call_func)
{ {
_fct(_sig); _fct(_sig);
call_func = false; call_func = false;
} }
return true; return true;

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