* 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,13 +11,14 @@ 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

@ -128,18 +128,18 @@ public:
// 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,11 +151,11 @@ 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

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

@ -87,12 +87,12 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
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,14 +100,14 @@ 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);
} }
@ -115,42 +115,42 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF
{ {
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
@ -246,22 +246,22 @@ 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);
@ -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);
} }
@ -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

@ -84,7 +84,7 @@ 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");
@ -97,12 +97,12 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
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);
} }
@ -112,14 +112,14 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
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,14 +127,14 @@ 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);
} }
@ -142,42 +142,42 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
{ {
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)
@ -233,14 +233,14 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
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);
} }
@ -253,14 +253,14 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
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);
} }
@ -268,14 +268,14 @@ eoAlgo<EOT> & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc
{ {
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);
} }

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

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

@ -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>;
} }
@ -144,7 +144,7 @@ eoReplacement<EOT> & make_general_replacement(
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

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

@ -45,13 +45,13 @@ public :
*/ */
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),
@ -64,14 +64,14 @@ public :
} }
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),
@ -93,39 +93,39 @@ public :
for (unsigned i = 0 ; i < pop.size () ; i ++) { for (unsigned i = 0 ; i < pop.size () ; i ++) {
// Who are neighbouring to the current individual ? // Who are neighbouring to the current individual ?
eoPop <EOT> neigh = neighbours (pop, i) ; eoPop <EOT> neigh = neighbours (pop, i) ;
// To select a partner // To select a partner
EOT part, old_sol = pop [i] ; EOT part, old_sol = pop [i] ;
part = sel_neigh (neigh) ; part = sel_neigh (neigh) ;
// To perform cross-over // To perform cross-over
cross (pop [i], part) ; cross (pop [i], part) ;
// To perform mutation // To perform mutation
mut (pop [i]) ; mut (pop [i]) ;
mut (part) ; mut (part) ;
pop [i].invalidate () ; pop [i].invalidate () ;
part.invalidate () ; part.invalidate () ;
eval (pop [i]) ; eval (pop [i]) ;
eval (part) ; eval (part) ;
// To choose one of the two children ... // To choose one of the two children ...
eoPop <EOT> pop_loc ; eoPop <EOT> pop_loc ;
pop_loc.push_back (pop [i]) ; pop_loc.push_back (pop [i]) ;
pop_loc.push_back (part) ; pop_loc.push_back (part) ;
pop [i] = sel_child (pop_loc) ; pop [i] = sel_child (pop_loc) ;
// To choose only one between the new made child and the old individual // To choose only one between the new made child and the old individual
pop_loc.clear () ; pop_loc.clear () ;
pop_loc.push_back (pop [i]) ; pop_loc.push_back (pop [i]) ;
pop_loc.push_back (old_sol) ; pop_loc.push_back (old_sol) ;
pop [i] = sel_repl (pop_loc) ; pop [i] = sel_repl (pop_loc) ;
} }
} while (cont (pop)) ; } while (cont (pop)) ;

View file

@ -80,4 +80,3 @@ virtual bool operator()(EOT& , EOT& ) {return false;}
#endif #endif
/** @} */ /** @} */

View file

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

View file

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

@ -191,20 +191,19 @@ 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

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

@ -68,4 +68,3 @@ public:
}; };
#endif #endif

View file

@ -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.
@ -79,9 +79,9 @@ 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.
@ -133,9 +133,9 @@ 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.

View file

@ -84,4 +84,3 @@ public:
#endif #endif
/** @} */ /** @} */

View file

@ -58,10 +58,10 @@ 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);
@ -71,16 +71,16 @@ class eoDetSelect : public eoSelect<EOT>
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);
} }
} }

View file

@ -71,4 +71,3 @@ template <class EOT> class eoDetTournamentSelect: public eoSelectOne<EOT>
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif #endif

View file

@ -45,7 +45,7 @@
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

@ -267,7 +267,7 @@ public:
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)
@ -314,4 +314,3 @@ protected:
/** @} */ /** @} */
#endif // _eoDualFitness_h_ #endif // _eoDualFitness_h_

View file

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

@ -36,12 +36,12 @@
* 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
*/ */
@ -90,7 +90,7 @@ 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
@ -171,21 +171,21 @@ 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;
}; };
/** /**

View file

@ -40,7 +40,7 @@ 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
*/ */
@ -49,7 +49,7 @@ public:
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;
} }

View file

@ -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;
@ -84,4 +84,3 @@ private :
}; };
#endif // __eoEvalCounterThrowException_h__ #endif // __eoEvalCounterThrowException_h__

View file

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

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

@ -65,4 +65,3 @@ struct eoEvalFuncPtr: public eoEvalFunc<EOT> {
}; };
#endif #endif

View file

@ -66,7 +66,7 @@ public:
* @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,
@ -145,14 +145,14 @@ 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());
@ -161,9 +161,9 @@ public:
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))
@ -186,10 +186,10 @@ public:
//! 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;
@ -199,9 +199,9 @@ protected:
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

@ -46,28 +46,28 @@ class eoFactory: public eoObject {
public: public:
/// @name ctors and dtors /// @name ctors and dtors
//{@ //{@
/// constructor /// constructor
eoFactory( ) {} eoFactory( ) {}
/// destructor /// destructor
virtual ~eoFactory() {} virtual ~eoFactory() {}
//@} //@}
/** Another factory methods: creates an object from an std::istream, reading from /** 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\\ it whatever is needed to create the object. Usually, the format for the std::istream will be\\
objectType parameter1 parameter2 ... parametern\\ objectType parameter1 parameter2 ... parametern\\
*/ */
virtual EOClass* make(std::istream& _is) = 0; virtual EOClass* make(std::istream& _is) = 0;
///@name eoObject methods ///@name eoObject methods
//@{ //@{
/** Return the class id */ /** Return the class id */
virtual std::string className() const { return "eoFactory"; } 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

@ -49,8 +49,7 @@ public:
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

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

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

@ -62,8 +62,8 @@ 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;
} }
@ -76,7 +76,7 @@ public :
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,9 +100,9 @@ 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;
} }
@ -114,7 +114,7 @@ public :
} }
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

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

@ -87,7 +87,7 @@ 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();
} }
}; };
@ -124,7 +124,7 @@ 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();
} }
}; };
@ -164,7 +164,7 @@ 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();
} }
}; };

View file

@ -63,23 +63,23 @@ public:
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

@ -41,22 +41,22 @@ 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++;
@ -64,21 +64,21 @@ public:
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( )
@ -112,4 +112,3 @@ private:
}; };
#endif #endif

View file

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

View file

@ -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,11 +43,11 @@
*/ */
/** @{*/ /** @{*/
/** /**
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>
@ -120,8 +120,8 @@ 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");
@ -172,7 +172,7 @@ class eoInitPermutation: public eoInit<EOT>
{ {
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();

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

@ -64,7 +64,7 @@ public:
* @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,
@ -82,8 +82,8 @@ 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
@ -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))),
@ -171,10 +171,10 @@ public:
//! 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;
@ -183,9 +183,9 @@ protected:
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;
@ -193,4 +193,3 @@ protected:
#endif /*EOINTEGERVELOCITY_H */ #endif /*EOINTEGERVELOCITY_H */

View file

@ -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))
@ -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,7 +207,7 @@ 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;
@ -215,11 +215,3 @@ protected:
}; };
#endif /*EOLINEARTOPOLOGY_H_ */ #endif /*EOLINEARTOPOLOGY_H_ */

View file

@ -52,7 +52,7 @@ 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)
@ -60,7 +60,7 @@ public:
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;
} }
} }
@ -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();
@ -85,14 +85,14 @@ public:
// 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:

View file

@ -66,17 +66,17 @@ 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;
} }
} }
@ -85,7 +85,7 @@ public :
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;
@ -98,7 +98,7 @@ public :
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]);
} }
} }

View file

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

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)

View file

@ -49,20 +49,9 @@ public:
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

@ -73,4 +73,3 @@ class eoObject
}; };
#endif #endif

View file

@ -60,9 +60,9 @@ class eoOneToOneBreeder: public eoBreed<EOT>
*/ */
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) {}
@ -82,29 +82,29 @@ class eoOneToOneBreeder: public eoBreed<EOT>
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

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

@ -38,70 +38,70 @@ 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 /// destructor
virtual ~eoOpSelMason() {}; virtual ~eoOpSelMason() {};
//@} //@}
/** Factory methods: creates an object from an std::istream, reading from /** Factory methods: creates an object from an std::istream, reading from
it whatever is needed to create the object. The format is it whatever is needed to create the object. The format is
opSelClassName\\ opSelClassName\\
rate 1 operator1\\ rate 1 operator1\\
rate 2 operator2\\ rate 2 operator2\\
...\\ ...\\
Stores all operators built in a database (#allocMap#), so that somebody Stores all operators built in a database (#allocMap#), so that somebody
can destroy them later. The Mason is in charge or destroying the operators, 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 since the built object can´t do it itself. The objects built must be destroyed
from outside, using the "destroy" method from outside, using the "destroy" method
*/ */
virtual eoOpSelector<eoClass>* make(std::istream& _is) { virtual eoOpSelector<eoClass>* make(std::istream& _is) {
std::string opSelName; std::string opSelName;
_is >> opSelName; _is >> opSelName;
eoOpSelector<eoClass>* opSelectorP; eoOpSelector<eoClass>* opSelectorP;
// Build the operator selector // Build the operator selector
if ( opSelName == "eoProportionalOpSel" ) { if ( opSelName == "eoProportionalOpSel" ) {
opSelectorP = new eoProportionalOpSel<eoClass>(); opSelectorP = new eoProportionalOpSel<eoClass>();
} }
// Temp std::vector for storing pointers // Temp std::vector for storing pointers
vOpP tmpPVec; vOpP tmpPVec;
// read operator rate and name // read operator rate and name
while ( _is ) { while ( _is ) {
float rate; float rate;
_is >> rate; _is >> rate;
if ( _is ) { if ( _is ) {
eoOp<eoClass>* op = operatorFactory.make( _is ); // This reads the rest of the line 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 // Add the operators to the selector, don´t pay attention to the IDs
opSelectorP->addOp( *op, rate ); opSelectorP->addOp( *op, rate );
// Keep it in the store, to destroy later // Keep it in the store, to destroy later
tmpPVec.push_back( op ); tmpPVec.push_back( op );
} // if } // if
} // while } // while
// Put it in the map // Put it in the map
allocMap.insert( MEV::value_type( opSelectorP, tmpPVec ) ); allocMap.insert( MEV::value_type( opSelectorP, tmpPVec ) );
return opSelectorP; return opSelectorP;
}; };
///@name eoObject methods ///@name eoObject methods
//@{ //@{
/** Return the class id */ /** Return the class id */
virtual std::string className() const { return "eoOpSelMason"; } 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

@ -26,64 +26,64 @@
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 * @return true if the chromosome has changed
* @param _chrom1 The first chromosome which will be crossed with chrom2. * @param _chrom1 The first chromosome which will be crossed with chrom2.
* @param _chrom2 The second chromosome which will be crossed with chrom1. * @param _chrom2 The second chromosome which will be crossed with chrom1.
*/ */
bool operator()(Chrom& _chrom1, Chrom& _chrom2){ bool operator()(Chrom& _chrom1, Chrom& _chrom2){
char direction=eo::rng.flip()? 1 : -1; char direction=eo::rng.flip()? 1 : -1;
unsigned cut2= 1 + eo::rng.random(_chrom1.size()); unsigned cut2= 1 + eo::rng.random(_chrom1.size());
unsigned cut1= eo::rng.random(cut2); unsigned cut1= eo::rng.random(cut2);
Chrom tmp1= _chrom1; Chrom tmp1= _chrom1;
Chrom tmp2= _chrom2; Chrom tmp2= _chrom2;
cross(tmp1, tmp2, _chrom1, direction, cut1, cut2); cross(tmp1, tmp2, _chrom1, direction, cut1, cut2);
cross(tmp2, tmp1, _chrom2, direction, cut1, cut2); cross(tmp2, tmp1, _chrom2, direction, cut1, cut2);
_chrom1.invalidate(); _chrom1.invalidate();
_chrom2.invalidate(); _chrom2.invalidate();
return true; return true;
} }
private: private:
/** /**
* @param _chrom1 The first parent chromosome. * @param _chrom1 The first parent chromosome.
* @param _chrom2 The second parent chromosome. * @param _chrom2 The second parent chromosome.
* @param _child The result chromosome. * @param _child The result chromosome.
* @param _direction The direction of the OrderXover (left: -1 or right: 1) * @param _direction The direction of the OrderXover (left: -1 or right: 1)
* @param _cut1 index of the first cut * @param _cut1 index of the first cut
* @param _cut2 index of the second cut * @param _cut2 index of the second cut
*/ */
void cross(Chrom& _chrom1, Chrom& _chrom2, Chrom& _child, char _direction, unsigned _cut1, unsigned _cut2){ void cross(Chrom& _chrom1, Chrom& _chrom2, Chrom& _child, char _direction, unsigned _cut1, unsigned _cut2){
unsigned size, id=0, from=0; unsigned size, id=0, from=0;
size= _chrom1.size(); size= _chrom1.size();
std::vector<bool> verif(size, false); std::vector<bool> verif(size, false);
for(unsigned i= _cut1; i<_cut2; i++){ for(unsigned i= _cut1; i<_cut2; i++){
_child[id++]= _chrom1[i]; _child[id++]= _chrom1[i];
verif[_chrom1[i] % size] = true; verif[_chrom1[i] % size] = true;
} }
while(_chrom2[from] != _child[_cut2 - 1]) while(_chrom2[from] != _child[_cut2 - 1])
from++; from++;
for(unsigned i=0; i<size; i++){ for(unsigned i=0; i<size; i++){
unsigned j= (_direction*i + from + size) % size; unsigned j= (_direction*i + from + size) % size;
if(!verif[_chrom2[j] % size]){ if(!verif[_chrom2[j] % size]){
_child[id++]=_chrom2[j]; _child[id++]=_chrom2[j];
verif[_chrom2[j]%size]=true; 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>
{ {
@ -104,28 +104,28 @@ template <class POT> class eoParticleInitializer : public eoInitializerBase <POT
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;
@ -153,4 +153,3 @@ template <class POT> class eoParticleInitializer : public eoInitializerBase <POT
#endif /*_eoParticleFullInitializer_H*/ #endif /*_eoParticleFullInitializer_H*/
/** @} */ /** @} */

View file

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

View file

@ -68,46 +68,46 @@ public:
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));
} }
}; };
@ -120,7 +120,7 @@ public:
} }
/** Empty Dtor */ /** Empty Dtor */
virtual ~eoPop() {} virtual ~eoPop() {}
/// helper struct for getting a pointer /// helper struct for getting a pointer
@ -132,12 +132,12 @@ public:
}; };
/// 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);
} }
}; };
@ -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);
} }
@ -223,7 +223,7 @@ public:
#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;
} }
@ -239,7 +239,7 @@ public:
#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;
@ -291,7 +291,7 @@ public:
_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;
} }
} }
@ -337,4 +337,3 @@ public:
}; };
#endif #endif

View file

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

View file

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

View file

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

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

@ -51,7 +51,7 @@ class eoPropGAGenOp : public eoGenOp<EOT>
* * 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),

View file

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

@ -61,7 +61,7 @@ public:
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];
} }
} }

View file

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

@ -50,7 +50,7 @@ public:
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;
} }
}; };
@ -76,18 +76,18 @@ 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)

View file

@ -56,8 +56,8 @@ 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);
@ -73,12 +73,12 @@ 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);
} }
}; };
@ -98,7 +98,7 @@ typedef typename EOT::Fitness Fitness;
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;
} }
} }
@ -110,7 +110,7 @@ typedef typename EOT::Fitness Fitness;
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;
} }
}; };
@ -122,46 +122,46 @@ typedef typename EOT::Fitness Fitness;
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;
@ -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);
} }
} }
}; };
@ -203,7 +203,7 @@ public:
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,14 +223,14 @@ 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) );
} }
} }
@ -252,12 +252,12 @@ public:
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,14 +276,14 @@ 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

@ -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 :
@ -96,7 +96,7 @@ 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;
@ -113,7 +113,7 @@ 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

@ -50,12 +50,12 @@ 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),
@ -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

@ -73,7 +73,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 ;
@ -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);
} }
} }
@ -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 ;
@ -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 ;
} }
@ -213,14 +213,14 @@ public:
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);
} }
} }
@ -264,19 +264,19 @@ public:
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

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

@ -5,7 +5,7 @@
// (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
@ -68,15 +68,15 @@ 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;
} }
@ -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);
} }
} }
@ -134,7 +134,7 @@ public:
*/ */
POT & best (unsigned _indice) POT & best (unsigned _indice)
{ {
unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice); unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice);
return (neighborhoods[theGoodNhbd].best()); return (neighborhoods[theGoodNhbd].best());
} }
@ -157,27 +157,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();
} }

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

@ -52,7 +52,7 @@ class eoSGAGenOp : public eoGenOp<EOT>
* 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),
@ -63,7 +63,7 @@ class eoSGAGenOp : public eoGenOp<EOT>
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
} }

View file

@ -50,7 +50,7 @@ template<class EOT> class eoSGATransform : public eoTransform<EOT>
/// 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),
@ -67,19 +67,19 @@ template<class EOT> class eoSGATransform : public eoTransform<EOT>
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]);
} }
} }
}; };
@ -105,7 +105,7 @@ template<class EOT> class eoDynSGATransform : public eoTransform<EOT>
/// 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),
@ -115,7 +115,7 @@ template<class EOT> class eoDynSGATransform : public eoTransform<EOT>
// 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),
@ -132,19 +132,19 @@ template<class EOT> class eoDynSGATransform : public eoTransform<EOT>
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]);
} }
} }
}; };

View file

@ -21,8 +21,8 @@
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

View file

@ -21,8 +21,8 @@
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;

View file

@ -121,4 +121,3 @@ class eoSTLBF : public std::binary_function<A1, A2, R>
/** @} */ /** @} */
#endif #endif

View file

@ -63,8 +63,8 @@ class eoScalarFitness
bool operator<(const eoScalarFitness& other) const bool operator<(const eoScalarFitness& other) const
{ return Compare()(value, other.value); } { return Compare()(value, other.value); }
/// Comparison, using less by default /// Comparison, using less by default
// needed for MSVC 8 (MSVC 2005) added by J.Eggermont 20-11-2006 // needed for MSVC 8 (MSVC 2005) added by J.Eggermont 20-11-2006
bool operator<(const ScalarType& other) const bool operator<(const ScalarType& other) const
{ return Compare()(value, other); } { return Compare()(value, other); }

View file

@ -36,6 +36,3 @@
// need to allocate the static variables of class eoScalarFitnessAssembledTraits // need to allocate the static variables of class eoScalarFitnessAssembledTraits
std::vector<std::string> eoScalarFitnessAssembledTraits::TermDescriptions; std::vector<std::string> eoScalarFitnessAssembledTraits::TermDescriptions;

View file

@ -110,8 +110,8 @@ public:
{} {}
eoScalarFitnessAssembled( size_type _n, eoScalarFitnessAssembled( size_type _n,
const ScalarType& _val, const ScalarType& _val,
const std::string& _descr="Unnamed variable" ) const std::string& _descr="Unnamed variable" )
: baseVector(_n, _val), : baseVector(_n, _val),
feasible(true), failed(false), msg("") feasible(true), failed(false), msg("")
{ {
@ -225,8 +225,8 @@ public:
//! Comparison with ScalarTypes. Explicit definition needed to compile with VS 8.0 //! Comparison with ScalarTypes. Explicit definition needed to compile with VS 8.0
bool operator<(ScalarType x) const{ bool operator<(ScalarType x) const{
eoScalarFitnessAssembled ScalarFitness(x); eoScalarFitnessAssembled ScalarFitness(x);
return this->operator<(ScalarFitness); return this->operator<(ScalarFitness);
} }
// implementation of the other operators // implementation of the other operators
@ -282,4 +282,3 @@ std::istream& operator>>(std::istream& is, eoScalarFitnessAssembled<F, Cmp, Fitn
/** @} */ /** @} */
#endif #endif

View file

@ -74,4 +74,3 @@ public:
*/ */
#endif #endif

View file

@ -44,48 +44,48 @@ class eoSelectFactory: public eoFactory<eoSelect< EOT> > {
public: public:
/// @name ctors and dtors /// @name ctors and dtors
//{@ //{@
/// constructor /// constructor
eoSelectFactory( ) {} eoSelectFactory( ) {}
/// destructor /// destructor
virtual ~eoSelectFactory() {} virtual ~eoSelectFactory() {}
//@} //@}
/** Another factory methods: creates an object from an std::istream, reading from /** 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\\ it whatever is needed to create the object. Usually, the format for the std::istream will be\\
objectType parameter1 parameter2 ... parametern\\ objectType parameter1 parameter2 ... parametern\\
*/ */
virtual eoSelect<EOT>* make(std::istream& _is) { virtual eoSelect<EOT>* make(std::istream& _is) {
eoSelect<EOT> * selectPtr; eoSelect<EOT> * selectPtr;
std::string objectTypeStr; std::string objectTypeStr;
_is >> objectTypeStr; _is >> objectTypeStr;
// All selectors have a rate, the proportion of the original population // All selectors have a rate, the proportion of the original population
float rate; float rate;
_is >> rate; _is >> rate;
if ( objectTypeStr == "eoTournament") { if ( objectTypeStr == "eoTournament") {
// another parameter is necessary // another parameter is necessary
unsigned tSize; unsigned tSize;
_is >> tSize; _is >> tSize;
selectPtr = new eoTournament<EOT>( rate, tSize ); selectPtr = new eoTournament<EOT>( rate, tSize );
} else { } else {
if ( objectTypeStr == "eoRandomSelect" ) { if ( objectTypeStr == "eoRandomSelect" ) {
selectPtr = new eoRandomSelect<EOT>( rate ); selectPtr = new eoRandomSelect<EOT>( rate );
} else { } else {
throw std::runtime_error( "Incorrect selector type" ); throw std::runtime_error( "Incorrect selector type" );
} }
} }
return selectPtr; return selectPtr;
} }
///@name eoObject methods ///@name eoObject methods
//@{ //@{
void printOn( std::ostream& _os ) const {}; void printOn( std::ostream& _os ) const {};
void readFrom( std::istream& _is ){}; void readFrom( std::istream& _is ){};
/** className is inherited */ /** className is inherited */
//@} //@}
}; };

View file

@ -194,7 +194,7 @@ public:
eoSelectFromWorth<EOT, WorthT>::setup(_pop); eoSelectFromWorth<EOT, WorthT>::setup(_pop);
total = 0.0; total = 0.0;
for (worthIterator it = perf2Worth.value().begin(); for (worthIterator it = perf2Worth.value().begin();
it<perf2Worth.value().end(); ++it) it<perf2Worth.value().end(); ++it)
total += (*it); total += (*it);
} }
@ -205,8 +205,8 @@ public:
virtual const EOT& operator()(const eoPop<EOT>& _pop) { virtual const EOT& operator()(const eoPop<EOT>& _pop) {
// cout << "On affiche les worths\n"; // cout << "On affiche les worths\n";
// for (unsigned i=0; // for (unsigned i=0;
// i<perf2Worth.value().size(); // i<perf2Worth.value().size();
// i++) // i++)
// cout << perf2Worth.value().operator[](i) << "\n"; // cout << perf2Worth.value().operator[](i) << "\n";
// cout << endl; // cout << endl;
worthIterator it = roulette_wheel(perf2Worth.value().begin(), worthIterator it = roulette_wheel(perf2Worth.value().begin(),
@ -229,4 +229,3 @@ private:
}; };
#endif #endif

View file

@ -49,7 +49,7 @@ class eoSelectMany : public eoSelect<EOT>
public: public:
/// init /// init
eoSelectMany(eoSelectOne<EOT>& _select, eoSelectMany(eoSelectOne<EOT>& _select,
double _rate, bool _interpret_as_rate = true) double _rate, bool _interpret_as_rate = true)
: select(_select), howMany(_rate, _interpret_as_rate) {} : select(_select), howMany(_rate, _interpret_as_rate) {}
// Ctor with eoHowMany // Ctor with eoHowMany

View file

@ -50,7 +50,7 @@ class eoSelectOne : public eoUF<const eoPop<EOT>&, const EOT&>
/// virtual function to setup some population stats (for instance eoProportional can benefit greatly from this) /// virtual function to setup some population stats (for instance eoProportional can benefit greatly from this)
virtual void setup(const eoPop<EOT>& _pop) virtual void setup(const eoPop<EOT>& _pop)
{ {
(void)_pop; (void)_pop;
} }
}; };
/** @example t-selectOne.cpp /** @example t-selectOne.cpp

View file

@ -58,13 +58,13 @@ template <class EOT> class eoSequentialSelect: public eoSelectOne<EOT>
not very elegant, maybe ... not very elegant, maybe ...
*/ */
eoSequentialSelect(bool _ordered = true) eoSequentialSelect(bool _ordered = true)
: ordered(_ordered), current(std::numeric_limits<unsigned>::max()) {} : ordered(_ordered), current(std::numeric_limits<unsigned>::max()) {}
void setup(const eoPop<EOT>& _pop) void setup(const eoPop<EOT>& _pop)
{ {
eoPters.resize(_pop.size()); eoPters.resize(_pop.size());
if (ordered) // probably we could have a marker to avoid re-sorting if (ordered) // probably we could have a marker to avoid re-sorting
_pop.sort(eoPters); _pop.sort(eoPters);
else else
_pop.shuffle(eoPters); _pop.shuffle(eoPters);
current=0; current=0;
@ -118,10 +118,10 @@ template <class EOT> class eoEliteSequentialSelect: public eoSelectOne<EOT>
throw std::runtime_error("Trying eoEliteSequentialSelect with only one individual!"); throw std::runtime_error("Trying eoEliteSequentialSelect with only one individual!");
for (unsigned i=1; i<_pop.size(); i++) for (unsigned i=1; i<_pop.size(); i++)
if (*eoPters[i]>*best) if (*eoPters[i]>*best)
{ {
ibest = i; ibest = i;
best = eoPters[ibest]; best = eoPters[ibest];
} }
// and put it upfront // and put it upfront
const EOT *ptmp = eoPters[0]; const EOT *ptmp = eoPters[0];
eoPters[0]=best; eoPters[0]=best;

View file

@ -60,16 +60,16 @@ class dMatrix : public std::vector<double>
{ {
unsigned index=0; unsigned index=0;
for (unsigned i=0; i<rSize; i++) for (unsigned i=0; i<rSize; i++)
{ {
for (unsigned j=0; j<rSize; j++) for (unsigned j=0; j<rSize; j++)
_os << this->operator[](index++) << " " ; _os << this->operator[](index++) << " " ;
_os << std::endl; _os << std::endl;
} }
_os << std::endl; _os << std::endl;
} }
private: private:
unsigned rSize; // row size (== number of columns!) unsigned rSize; // row size (== number of columns!)
}; };
@ -89,8 +89,8 @@ public:
/* Ctor requires a distance - cannot have a default distance! */ /* Ctor requires a distance - cannot have a default distance! */
eoSharing(double _nicheSize, eoDistance<EOT> & _dist) : eoPerf2Worth<EOT>("Sharing"), eoSharing(double _nicheSize, eoDistance<EOT> & _dist) : eoPerf2Worth<EOT>("Sharing"),
nicheSize(_nicheSize), nicheSize(_nicheSize),
dist(_dist) dist(_dist)
{} {}
/** Computes shared fitnesses /** Computes shared fitnesses
@ -98,33 +98,33 @@ public:
void operator()(const eoPop<EOT>& _pop) void operator()(const eoPop<EOT>& _pop)
{ {
unsigned i, j, unsigned i, j,
pSize=_pop.size(); pSize=_pop.size();
if (pSize <= 1) if (pSize <= 1)
throw std::runtime_error("Apptempt to do sharing with population of size 1"); throw std::runtime_error("Apptempt to do sharing with population of size 1");
value().resize(pSize); value().resize(pSize);
std::vector<double> sim(pSize); // to hold the similarities std::vector<double> sim(pSize); // to hold the similarities
dMatrix distMatrix(pSize); // to hold the distances dMatrix distMatrix(pSize); // to hold the distances
// compute the similarities (wrong name for distMatrix, I know) // compute the similarities (wrong name for distMatrix, I know)
distMatrix(0,0)=1; distMatrix(0,0)=1;
for (i=1; i<pSize; i++) for (i=1; i<pSize; i++)
{ {
distMatrix(i,i)=1; distMatrix(i,i)=1;
for (j=0; j<i; j++) for (j=0; j<i; j++)
{ {
double d = dist(_pop[i], _pop[j]); double d = dist(_pop[i], _pop[j]);
distMatrix(i,j) = distMatrix(i,j) =
distMatrix(j,i) = ( d>nicheSize ? 0 : 1-(d/nicheSize) ); distMatrix(j,i) = ( d>nicheSize ? 0 : 1-(d/nicheSize) );
} }
} }
for (i=0; i<pSize; i++) for (i=0; i<pSize; i++)
{ {
double sum=0.0; double sum=0.0;
for (j=0; j<pSize; j++) for (j=0; j<pSize; j++)
sum += distMatrix(i,j); sum += distMatrix(i,j);
sim[i] = sum; sim[i] = sum;
} }
// now set the worthes values // now set the worthes values
for (i = 0; i < _pop.size(); ++i) for (i = 0; i < _pop.size(); ++i)
@ -133,7 +133,7 @@ public:
// private data of class eoSharing // private data of class eoSharing
private: private:
double nicheSize; double nicheSize;
eoDistance<EOT> & dist; // specific distance eoDistance<EOT> & dist; // specific distance
}; };

View file

@ -52,7 +52,7 @@ public:
eoRouletteWorthSelect<EOT, double>(sharing), sharing(_sigma, _dist) {} eoRouletteWorthSelect<EOT, double>(sharing), sharing(_sigma, _dist) {}
private : private :
eoSharing<EOT> sharing; // derived from eoPerf2Worth eoSharing<EOT> sharing; // derived from eoPerf2Worth
}; };
/** @example t-eoSharing.cpp /** @example t-eoSharing.cpp
*/ */

View file

@ -20,7 +20,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
thomas.legrand@lifl.fr thomas.legrand@lifl.fr
Marc.Schoenauer@polytechnique.fr Marc.Schoenauer@polytechnique.fr
mak@dhi.dk mak@dhi.dk
*/ */
@ -74,7 +74,7 @@ template<class EOT> class eoShiftMutation: public eoMonOp<EOT>
// shift // shift
for(unsigned int k=to ; k > from ; k--) for(unsigned int k=to ; k > from ; k--)
_eo[k]=_eo[k-1]; _eo[k]=_eo[k-1];
// shift the first component // shift the first component
_eo[from]=tmp; _eo[from]=tmp;
@ -89,4 +89,3 @@ template<class EOT> class eoShiftMutation: public eoMonOp<EOT>
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#endif #endif

View file

@ -19,7 +19,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
clive.canape@inria.fr clive.canape@inria.fr
*/ */
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -33,14 +33,14 @@
/** /**
* Binary flight for particle swarm optimization based on the sigmoid function. Velocities are expected to be "double" * Binary flight for particle swarm optimization based on the sigmoid function. Velocities are expected to be "double"
* Consider Pi to be the i-th position of a particle and Vi to be the i-th velocity of the same particle : * Consider Pi to be the i-th position of a particle and Vi to be the i-th velocity of the same particle :
* if rand[0;1] < sig(Vi) (Vi <=> double) * if rand[0;1] < sig(Vi) (Vi <=> double)
* Pi=1 * Pi=1
* else * else
* Pi=0 * Pi=0
* *
* @ingroup Variators * @ingroup Variators
*/ */
template < class POT > class eoSigBinaryFlight:public eoBinaryFlight < POT > template < class POT > class eoSigBinaryFlight:public eoBinaryFlight < POT >
{ {
@ -85,7 +85,7 @@ public:
} }
private : private :
unsigned slope; unsigned slope;
}; };

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