diff --git a/eo/src/CMakeLists.txt b/eo/src/CMakeLists.txt index 70e2c755..97b74866 100644 --- a/eo/src/CMakeLists.txt +++ b/eo/src/CMakeLists.txt @@ -11,14 +11,15 @@ INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) SET(EO_LIB_OUTPUT_PATH ${EO_BINARY_DIR}/lib) SET(LIBRARY_OUTPUT_PATH ${EO_LIB_OUTPUT_PATH}) -SET (EO_SOURCES eoFunctorStore.cpp - eoPersistent.cpp - eoPrintable.cpp - eoCtrlCContinue.cpp - eoScalarFitnessAssembled.cpp - eoSIGContinue.cpp) +SET(EO_SOURCES + eoFunctorStore.cpp + eoPersistent.cpp + eoPrintable.cpp + eoCtrlCContinue.cpp + eoScalarFitnessAssembled.cpp + eoSIGContinue.cpp + ) - ADD_LIBRARY(eo STATIC ${EO_SOURCES}) INSTALL(TARGETS eo ARCHIVE DESTINATION lib COMPONENT libraries) @@ -42,6 +43,6 @@ ADD_SUBDIRECTORY(ga) ADD_SUBDIRECTORY(gp) ADD_SUBDIRECTORY(other) ADD_SUBDIRECTORY(utils) +ADD_SUBDIRECTORY(pyeo) ###################################################################################### - diff --git a/eo/src/EO.h b/eo/src/EO.h index 2c43b2c8..f904559d 100644 --- a/eo/src/EO.h +++ b/eo/src/EO.h @@ -40,17 +40,17 @@ */ /** EO is the base class for objects with a fitness. - + Those evolvable objects are the subjects of evolution. EOs have only got a fitness, which at the same time needs to be only an object with the operation less than (<) defined. Fitness says how good is the object; evolution or change of these objects is left to the - genetic operators. - + genetic operators. + A fitness less than another means a worse fitness, in whatever the context; thus, fitness is always maximized; although it can - be minimized with a proper definition of the < operator. - + be minimized with a proper definition of the < operator. + A fitness can be invalid if undefined, trying to read an invalid fitness will raise an error. @ref Operators that effectively modify EO objects must invalidate them. @@ -123,23 +123,23 @@ public: * @throw runtime_std::exception If a valid object can't be read. */ virtual void readFrom(std::istream& _is) { - + // the new version of the reafFrom function. - // It can distinguish between valid and invalid fitness values. + // It can distinguish between valid and invalid fitness values. std::string fitness_str; int pos = _is.tellg(); - _is >> fitness_str; + _is >> fitness_str; - if (fitness_str == "INVALID") - { - invalidFitness = true; - } - else - { - invalidFitness = false; - _is.seekg(pos); // rewind - _is >> repFitness; - } + if (fitness_str == "INVALID") + { + invalidFitness = true; + } + else + { + invalidFitness = false; + _is.seekg(pos); // rewind + _is >> repFitness; + } } /** @@ -151,13 +151,13 @@ public: // the latest version of the code. Very similar to the old code if (invalid()) { - _os << "INVALID "; + _os << "INVALID "; } else { - _os << repFitness << ' '; + _os << repFitness << ' '; } - + } //@} @@ -171,4 +171,3 @@ private: #endif /** @} */ - diff --git a/eo/src/PO.h b/eo/src/PO.h index 1cb4f50a..0c246135 100644 --- a/eo/src/PO.h +++ b/eo/src/PO.h @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // PO.h // (c) OPAC 2007 @@ -43,11 +43,11 @@ template < class F > class PO:public EO < F > public: - #if defined(__CUDACC__) - typedef typename EO < F >::Fitness Fitness; - #else - typedef typename PO::Fitness Fitness; - #endif + #if defined(__CUDACC__) + typedef typename EO < F >::Fitness Fitness; + #else + typedef typename PO::Fitness Fitness; + #endif /** Default constructor. Fitness must have a ctor which takes 0 as a value. Best fitness mush also have the same constructor. diff --git a/eo/src/do/Readme b/eo/src/do/Readme index cd3e5acd..0b3ccd8a 100644 --- a/eo/src/do/Readme +++ b/eo/src/do/Readme @@ -9,11 +9,11 @@ the functions here for eoBit AND eoBit and in EO test dir the t-eoGA.cpp file that is a sample program that uses the whole facility. -All make_XXX.h file define some parser-based constructions of basic +All make_XXX.h file define some parser-based constructions of basic Evolutionary Algorithms components, using state-based memory management (see in src/utils dir, or read the tutorial). -In this src/do dir, the following ***representation indedendent*** code +In this src/do dir, the following ***representation indedendent*** code is defined make_algo_scalar.h The selection/replacement for scalar fitnesses @@ -23,7 +23,7 @@ make_pop.h Init of the population (from an EOT initializer) make_run.h Run the algorithm See also (NOW MOVED TO util DIR, as it was useful everywhere) -make_help.cpp Help on demand (+ status file) +make_help.cpp Help on demand (+ status file) Note: ----- diff --git a/eo/src/do/make_algo_easea.h b/eo/src/do/make_algo_easea.h index a6522ef9..c432c1e8 100644 --- a/eo/src/do/make_algo_easea.h +++ b/eo/src/do/make_algo_easea.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_algo_easea.h // (c) Marc Schoenauer and Pierre Collet, 2002 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -81,18 +81,18 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF eoParamParamType & ppSelect = selectionParam.value(); // std::pair > eoSelectOne* select ; - if (ppSelect.first == std::string("DetTour")) + if (ppSelect.first == std::string("DetTour")) { unsigned detSize; if (!ppSelect.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; - detSize = 2; - // put back 2 in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("2")); + std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; + detSize = 2; + // put back 2 in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("2")); } - else // parameter passed by user as DetTour(T) + else // parameter passed by user as DetTour(T) detSize = atoi(ppSelect.second[0].c_str()); select = new eoDetTournamentSelect(detSize); } @@ -100,57 +100,57 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF { double p; if (!ppSelect.second.size()) // no parameter added - { - std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; - p = 1; - // put back p in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("1")); - } - else // parameter passed by user as DetTour(T) - p = atof(ppSelect.second[0].c_str()); - + { + std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; + p = 1; + // put back p in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("1")); + } + else // parameter passed by user as DetTour(T) + p = atof(ppSelect.second[0].c_str()); + select = new eoStochTournamentSelect(p); } else if (ppSelect.first == std::string("Ranking")) { double p,e; if (ppSelect.second.size()==2) // 2 parameters: pressure and exponent - { - p = atof(ppSelect.second[0].c_str()); - e = atof(ppSelect.second[1].c_str()); - } - else if (ppSelect.second.size()==1) // 1 parameter: pressure - { - std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl; - e = 1; - ppSelect.second.push_back(std::string("1")); - p = atof(ppSelect.second[0].c_str()); - } + { + p = atof(ppSelect.second[0].c_str()); + e = atof(ppSelect.second[1].c_str()); + } + else if (ppSelect.second.size()==1) // 1 parameter: pressure + { + std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl; + e = 1; + ppSelect.second.push_back(std::string("1")); + p = atof(ppSelect.second[0].c_str()); + } else // no parameters ... or garbage - { - std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl; - p=2; - e=1; - // put back in parameter for consistency (and status file) - ppSelect.second.resize(2); // just in case - ppSelect.second[0] = (std::string("2")); - ppSelect.second[1] = (std::string("1")); - } + { + std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl; + p=2; + e=1; + // put back in parameter for consistency (and status file) + ppSelect.second.resize(2); // just in case + ppSelect.second[0] = (std::string("2")); + ppSelect.second[1] = (std::string("1")); + } // check for authorized values // pressure in (0,1] if ( (p<=1) || (p>2) ) - { - std::cerr << "WARNING, selective pressure must be in (1,2] in Ranking, using 2\n"; - p=2; - ppSelect.second[0] = (std::string("2")); - } + { + std::cerr << "WARNING, selective pressure must be in (1,2] in Ranking, using 2\n"; + p=2; + ppSelect.second[0] = (std::string("2")); + } // exponent >0 if (e<=0) - { - std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n"; - e=1; - ppSelect.second[1] = (std::string("1")); - } + { + std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n"; + e=1; + ppSelect.second[1] = (std::string("1")); + } // now we're OK eoPerf2Worth & p2w = _state.storeFunctor( new eoRanking(p,e) ); select = new eoRouletteWorthSelect(p2w); @@ -159,13 +159,13 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF { bool b; if (ppSelect.second.size() == 0) // no argument -> default = ordered - { - b=true; - // put back in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("ordered")); - } + { + b=true; + // put back in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("ordered")); + } else - b = !(ppSelect.second[0] == std::string("unordered")); + b = !(ppSelect.second[0] == std::string("unordered")); select = new eoSequentialSelect(b); } else if (ppSelect.first == std::string("EliteSequential")) // Best first, one after the other in random order afterwards @@ -188,7 +188,7 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF _state.storeFunctor(select); - // the number of offspring + // the number of offspring eoValueParam& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine"); ///////////////////////////////////////////////////// @@ -196,7 +196,7 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF ///////////////////////////////////////////////////// /** Replacement type - high level: predefined replacements - * ESComma : + * ESComma : * elite = 0 * surviveParents=0 (no reduce) * surviveOffspring=100% (no reduce) @@ -208,8 +208,8 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF * GGA : generational GA - idem ESComma except for * offspringRate = 100% * all reducers are unused - * - * SSGA(T/t) : Steady-State GA + * + * SSGA(T/t) : Steady-State GA * surviveParents = 1.0 - offspringRate * reduceFinal = DetTour(T>1) ou StochTour(0.5 & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF // the tournament size if (!replacementParam.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to MGG replacement, using 2" << std::endl; - tSize = 2; - // put back 2 in parameter for consistency (and status file) - replacementParam.second.push_back(std::string("2")); + std::cerr << "WARNING, no parameter passed to MGG replacement, using 2" << std::endl; + tSize = 2; + // put back 2 in parameter for consistency (and status file) + replacementParam.second.push_back(std::string("2")); } else { - t = atof(replacementParam.second[0].c_str()); - if (t>=2) - { // build the appropriate deafult value - tSize = unsigned(t); - } - else - { - throw std::runtime_error("Sorry, only deterministic tournament available at the moment"); - } + t = atof(replacementParam.second[0].c_str()); + if (t>=2) + { // build the appropriate deafult value + tSize = unsigned(t); + } + else + { + throw std::runtime_error("Sorry, only deterministic tournament available at the moment"); + } } - ptReplace = new eoMGGReplacement(-surviveParents, tSize); + ptReplace = new eoMGGReplacement(-surviveParents, tSize); _state.storeFunctor(ptReplace); } else { // until the end of what was the only loop/switch - + // the default deafult values eoHowMany elite (0.0); bool strongElitism (false); @@ -283,12 +283,12 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF // ---------- General if (replacementParam.first == std::string("General")) { - ; // defaults OK + ; // defaults OK } // ---------- ESComma else if (replacementParam.first == std::string("ESComma")) { - ; // OK too + ; // OK too } // ---------- ESPlus else if (replacementParam.first == std::string("ESPlus")) @@ -298,16 +298,16 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF // ---------- 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 else if (replacementParam.first == std::string("EP")) { if (!replacementParam.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to EP replacement, using 6" << std::endl; - // put back 6 in parameter for consistency (and status file) - replacementParam.second.push_back(std::string("6")); + std::cerr << "WARNING, no parameter passed to EP replacement, using 6" << std::endl; + // put back 6 in parameter for consistency (and status file) + replacementParam.second.push_back(std::string("6")); } // by coincidence, the syntax for the EP reducer is the same than here: reduceFinalType = replacementParam; @@ -318,28 +318,28 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF { if (!replacementParam.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to SSGA replacement, using 2" << std::endl; - // put back 2 in parameter for consistency (and status file) - replacementParam.second.push_back(std::string("2")); - reduceParentType = eoParamParamType(std::string("DetTour(2)")); + std::cerr << "WARNING, no parameter passed to SSGA replacement, using 2" << std::endl; + // put back 2 in parameter for consistency (and status file) + replacementParam.second.push_back(std::string("2")); + reduceParentType = eoParamParamType(std::string("DetTour(2)")); } else { - t = atof(replacementParam.second[0].c_str()); - if (t>=2) - { // build the appropriate deafult value - reduceParentType = eoParamParamType(std::string("DetTour(") + replacementParam.second[0].c_str() + ")"); - } - else // check for [0.5,1] will be made in make_general_replacement - { // build the appropriate deafult value - reduceParentType = eoParamParamType(std::string("StochTour(") + replacementParam.second[0].c_str() + ")"); - } + t = atof(replacementParam.second[0].c_str()); + if (t>=2) + { // build the appropriate deafult value + reduceParentType = eoParamParamType(std::string("DetTour(") + replacementParam.second[0].c_str() + ")"); + } + else // check for [0.5,1] will be made in make_general_replacement + { // build the appropriate deafult value + reduceParentType = eoParamParamType(std::string("StochTour(") + replacementParam.second[0].c_str() + ")"); + } } - // + // surviveParents = eoHowMany(-1); surviveOffspring = eoHowMany(1); } - else // no replacement recognized + else // no replacement recognized { throw std::runtime_error("Invalid replacement type " + replacementParam.first); } @@ -353,7 +353,7 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF /////////////////////////////// // the general breeder /////////////////////////////// - eoGeneralBreeder *breed = + eoGeneralBreeder *breed = new eoGeneralBreeder(*select, _op, offspringRateParam.value()); _state.storeFunctor(breed); @@ -381,7 +381,7 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoPopEvalF template eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc& _eval, eoContinue& _continue, eoGenOp& _op) { - do_make_algo_scalar( _parser, _state, *(new eoPopLoopEval(_eval)), _continue, _op); + do_make_algo_scalar( _parser, _state, *(new eoPopLoopEval(_eval)), _continue, _op); } diff --git a/eo/src/do/make_algo_scalar.h b/eo/src/do/make_algo_scalar.h index 5a63eb9d..52df8f4f 100644 --- a/eo/src/do/make_algo_scalar.h +++ b/eo/src/do/make_algo_scalar.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_algo_scalar.h // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -84,42 +84,42 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc if (_dist == NULL) comment = "Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e) or Sequential(ordered/unordered)"; else - comment = "Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e), Sharing(sigma_share) or Sequential(ordered/unordered)"; + comment = "Selection: DetTour(T), StochTour(t), Roulette, Ranking(p,e), Sharing(sigma_share) or Sequential(ordered/unordered)"; eoValueParam& selectionParam = _parser.createParam(eoParamParamType("DetTour(2)"), "selection", comment, 'S', "Evolution Engine"); eoParamParamType & ppSelect = selectionParam.value(); // std::pair > eoSelectOne* select ; - if (ppSelect.first == std::string("DetTour")) + if (ppSelect.first == std::string("DetTour")) { unsigned detSize; if (!ppSelect.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; - detSize = 2; - // put back 2 in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("2")); + std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; + detSize = 2; + // put back 2 in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("2")); } - else // parameter passed by user as DetTour(T) + else // parameter passed by user as DetTour(T) detSize = atoi(ppSelect.second[0].c_str()); select = new eoDetTournamentSelect(detSize); } - else if (ppSelect.first == std::string("Sharing")) + else if (ppSelect.first == std::string("Sharing")) { double nicheSize; if (!ppSelect.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to Sharing, using 0.5" << std::endl; - nicheSize = 0.5; - // put back 2 in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("0.5")); + std::cerr << "WARNING, no parameter passed to Sharing, using 0.5" << std::endl; + nicheSize = 0.5; + // put back 2 in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("0.5")); } - else // parameter passed by user as DetTour(T) + else // parameter passed by user as DetTour(T) 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"); select = new eoSharingSelect(nicheSize, *_dist); } @@ -127,57 +127,57 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc { double p; if (!ppSelect.second.size()) // no parameter added - { - std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; - p = 1; - // put back p in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("1")); - } - else // parameter passed by user as DetTour(T) - p = atof(ppSelect.second[0].c_str()); - + { + std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; + p = 1; + // put back p in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("1")); + } + else // parameter passed by user as DetTour(T) + p = atof(ppSelect.second[0].c_str()); + select = new eoStochTournamentSelect(p); } else if (ppSelect.first == std::string("Ranking")) { double p,e; if (ppSelect.second.size()==2) // 2 parameters: pressure and exponent - { - p = atof(ppSelect.second[0].c_str()); - e = atof(ppSelect.second[1].c_str()); - } - else if (ppSelect.second.size()==1) // 1 parameter: pressure - { - std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl; - e = 1; - ppSelect.second.push_back(std::string("1")); - p = atof(ppSelect.second[0].c_str()); - } + { + p = atof(ppSelect.second[0].c_str()); + e = atof(ppSelect.second[1].c_str()); + } + else if (ppSelect.second.size()==1) // 1 parameter: pressure + { + std::cerr << "WARNING, no exponent to Ranking, using 1" << std::endl; + e = 1; + ppSelect.second.push_back(std::string("1")); + p = atof(ppSelect.second[0].c_str()); + } else // no parameters ... or garbage - { - std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl; - p=2; - e=1; - // put back in parameter for consistency (and status file) - ppSelect.second.resize(2); // just in case - ppSelect.second[0] = (std::string("2")); - ppSelect.second[1] = (std::string("1")); - } + { + std::cerr << "WARNING, no parameter to Ranking, using (2,1)" << std::endl; + p=2; + e=1; + // put back in parameter for consistency (and status file) + ppSelect.second.resize(2); // just in case + ppSelect.second[0] = (std::string("2")); + ppSelect.second[1] = (std::string("1")); + } // check for authorized values // pressure in (0,1] if ( (p<=1) || (p>2) ) - { - std::cerr << "WARNING, selective pressure must be in (0,1] in Ranking, using 2\n"; - p=2; - ppSelect.second[0] = (std::string("2")); - } + { + std::cerr << "WARNING, selective pressure must be in (0,1] in Ranking, using 2\n"; + p=2; + ppSelect.second[0] = (std::string("2")); + } // exponent >0 if (e<=0) - { - std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n"; - e=1; - ppSelect.second[1] = (std::string("1")); - } + { + std::cerr << "WARNING, exponent must be positive in Ranking, using 1\n"; + e=1; + ppSelect.second[1] = (std::string("1")); + } // now we're OK eoPerf2Worth & p2w = _state.storeFunctor( new eoRanking(p,e) ); select = new eoRouletteWorthSelect(p2w); @@ -186,13 +186,13 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc { bool b; if (ppSelect.second.size() == 0) // no argument -> default = ordered - { - b=true; - // put back in parameter for consistency (and status file) - ppSelect.second.push_back(std::string("ordered")); - } + { + b=true; + // put back in parameter for consistency (and status file) + ppSelect.second.push_back(std::string("ordered")); + } else - b = !(ppSelect.second[0] == std::string("unordered")); + b = !(ppSelect.second[0] == std::string("unordered")); select = new eoSequentialSelect(b); } else if (ppSelect.first == std::string("Roulette")) // no argument (yet) @@ -211,7 +211,7 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc _state.storeFunctor(select); - // the number of offspring + // the number of offspring eoValueParam& offspringRateParam = _parser.createParam(eoHowMany(1.0), "nbOffspring", "Nb of offspring (percentage or absolute)", 'O', "Evolution Engine"); // the replacement @@ -231,16 +231,16 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc else if (ppReplace.first == std::string("EPTour")) { unsigned detSize; - + if (!ppReplace.second.size()) // no parameter added - { - std::cerr << "WARNING, no parameter passed to EPTour, using 6" << std::endl; - detSize = 6; - // put back in parameter for consistency (and status file) - ppReplace.second.push_back(std::string("6")); - } - else // parameter passed by user as EPTour(T) - detSize = atoi(ppSelect.second[0].c_str()); + { + std::cerr << "WARNING, no parameter passed to EPTour, using 6" << std::endl; + detSize = 6; + // put back in parameter for consistency (and status file) + ppReplace.second.push_back(std::string("6")); + } + else // parameter passed by user as EPTour(T) + detSize = atoi(ppSelect.second[0].c_str()); replace = new eoEPReplacement(detSize); } @@ -251,32 +251,32 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc else if (ppReplace.first == std::string("SSGADet")) { unsigned detSize; - + if (!ppReplace.second.size()) // no parameter added - { - std::cerr << "WARNING, no parameter passed to SSGADet, using 2" << std::endl; - detSize = 2; - // put back in parameter for consistency (and status file) - ppReplace.second.push_back(std::string("2")); - } - else // parameter passed by user as SSGADet(T) - detSize = atoi(ppSelect.second[0].c_str()); - + { + std::cerr << "WARNING, no parameter passed to SSGADet, using 2" << std::endl; + detSize = 2; + // put back in parameter for consistency (and status file) + ppReplace.second.push_back(std::string("2")); + } + else // parameter passed by user as SSGADet(T) + detSize = atoi(ppSelect.second[0].c_str()); + replace = new eoSSGADetTournamentReplacement(detSize); } else if (ppReplace.first == std::string("SSGAStoch")) { double p; if (!ppReplace.second.size()) // no parameter added - { - std::cerr << "WARNING, no parameter passed to SSGAStoch, using 1" << std::endl; - p = 1; - // put back in parameter for consistency (and status file) - ppReplace.second.push_back(std::string("1")); - } - else // parameter passed by user as SSGADet(T) - p = atof(ppSelect.second[0].c_str()); - + { + std::cerr << "WARNING, no parameter passed to SSGAStoch, using 1" << std::endl; + p = 1; + // put back in parameter for consistency (and status file) + ppReplace.second.push_back(std::string("1")); + } + else // parameter passed by user as SSGADet(T) + p = atof(ppSelect.second[0].c_str()); + replace = new eoSSGAStochTournamentReplacement(p); } else @@ -294,10 +294,10 @@ eoAlgo & do_make_algo_scalar(eoParser& _parser, eoState& _state, eoEvalFunc eoReplacement *replaceTmp = replace; replace = new eoWeakElitistReplacement(*replaceTmp); _state.storeFunctor(replace); - } + } // the general breeder - eoGeneralBreeder *breed = + eoGeneralBreeder *breed = new eoGeneralBreeder(*select, _op, offspringRateParam.value()); _state.storeFunctor(breed); diff --git a/eo/src/do/make_checkpoint.h b/eo/src/do/make_checkpoint.h index 37cf5d0a..7958ed5b 100644 --- a/eo/src/do/make_checkpoint.h +++ b/eo/src/do/make_checkpoint.h @@ -129,7 +129,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu eoValueParam& 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& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu { - bestStat = new eoBestFitnessStat; + bestStat = new eoBestFitnessStat; - // 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& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu { - averageStat = new eoAverageStat; + averageStat = new eoAverageStat; - // 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& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu eoSecondMomentStats *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; + secondStat = new eoSecondMomentStats; - // 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& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu { - popStat = new eoSortedPopStat; + popStat = new eoSortedPopStat; - // 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& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu bool needStdoutMonitor = printBestParam.value() - || printPopParam.value() ; + || printPopParam.value() ; @@ -297,53 +297,53 @@ eoCheckPoint& 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& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu 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 @@ -367,41 +367,41 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu #ifdef _MSVC - std::string stmp = dirNameParam.value() + "\best.xg"; + std::string stmp = dirNameParam.value() + "\best.xg"; #else - std::string stmp = dirNameParam.value() + "/best.xg"; + std::string stmp = dirNameParam.value() + "/best.xg"; #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& 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()); + eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness()); - // 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& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu { - eoScalarFitnessStat *fitStat = new eoScalarFitnessStat; + eoScalarFitnessStat *fitStat = new eoScalarFitnessStat; - _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 to it + // add any stat that is a std::vector 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& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu if (! dirOK ) - dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE + dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE @@ -537,7 +537,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu if (! dirOK ) - dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE + dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE @@ -570,4 +570,3 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoValu #endif - diff --git a/eo/src/do/make_checkpoint_FDC.h b/eo/src/do/make_checkpoint_FDC.h index 1c2ec493..33c7f720 100644 --- a/eo/src/do/make_checkpoint_FDC.h +++ b/eo/src/do/make_checkpoint_FDC.h @@ -70,7 +70,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval eoValueParam& dirNameParam = _parser.createParam(std::string("Res"), "resDir", "Directory to store DISK outputs", '\0', "Output - Disk"); // shoudl we empty it if exists eoValueParam& 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: @@ -98,11 +98,11 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval if ( printBestParam.value() || plotBestParam.value() || fileBestParam.value() ) // we need the bestStat for at least one of the 3 above { - bestStat = new eoBestFitnessStat; - // store it - _state.storeFunctor(bestStat); - // add it to the checkpoint - checkpoint->add(*bestStat); + bestStat = new eoBestFitnessStat; + // store it + _state.storeFunctor(bestStat); + // add it to the checkpoint + checkpoint->add(*bestStat); } // Average fitness alone @@ -110,11 +110,11 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval eoAverageStat *averageStat = NULL; // do we need averageStat? if ( plotBestParam.value() ) // we need it for gnuplot output { - averageStat = new eoAverageStat; - // store it - _state.storeFunctor(averageStat); - // add it to the checkpoint - checkpoint->add(*averageStat); + averageStat = new eoAverageStat; + // store it + _state.storeFunctor(averageStat); + // add it to the checkpoint + checkpoint->add(*averageStat); } // Second moment stats: average and stdev @@ -122,11 +122,11 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval eoSecondMomentStats *secondStat = NULL; if ( printBestParam.value() ) // we need it for sreen output { - secondStat = new eoSecondMomentStats; - // store it - _state.storeFunctor(secondStat); - // add it to the checkpoint - checkpoint->add(*secondStat); + secondStat = new eoSecondMomentStats; + // store it + _state.storeFunctor(secondStat); + // add it to the checkpoint + checkpoint->add(*secondStat); } @@ -136,11 +136,11 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval eoValueParam& printPopParam = _parser.createParam(false, "printPop", "Print sorted pop. every gen.", '\0', "Output"); if ( printPopParam.value() ) // we do want pop dump { - popStat = new eoSortedPopStat("Dump of whole population"); - // store it - _state.storeFunctor(popStat); - // add it to the checkpoint - checkpoint->add(*popStat); + popStat = new eoSortedPopStat("Dump of whole population"); + // store it + _state.storeFunctor(popStat); + // add it to the checkpoint + checkpoint->add(*popStat); } @@ -152,14 +152,14 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval eoFDCStat *fdcStat = NULL; if ( printFDCParam.value() || plotFDCParam.value() ) // we need FDCStat { - // need first an object to compute the distances - here Hamming dist. - eoQuadDistance *dist = new eoQuadDistance; - _state.storeFunctor(dist); - fdcStat = new eoFDCStat(*dist); - // storeFunctor it - _state.storeFunctor(fdcStat); - // add it to the checkpoint - checkpoint->add(*fdcStat); + // need first an object to compute the distances - here Hamming dist. + eoQuadDistance *dist = new eoQuadDistance; + _state.storeFunctor(dist); + fdcStat = new eoFDCStat(*dist); + // storeFunctor it + _state.storeFunctor(fdcStat); + // add it to the checkpoint + checkpoint->add(*fdcStat); } // do we wnat some histogram of fitnesses snpashots? @@ -170,95 +170,95 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval /////////////// // do we want an eoStdoutMonitor? bool needStdoutMonitor = printBestParam.value() || printFDCParam.value() - || printPopParam.value() ; + || printPopParam.value() ; // The Stdout monitor will print parameters to the screen ... if ( needStdoutMonitor ) { - eoStdoutMonitor *monitor = new eoStdoutMonitor(false); - _state.storeFunctor(monitor); + eoStdoutMonitor *monitor = new eoStdoutMonitor(false); + _state.storeFunctor(monitor); - // when called by the checkpoint (i.e. at every generation) - checkpoint->add(*monitor); + // when called by the checkpoint (i.e. at every generation) + checkpoint->add(*monitor); - // the monitor will output a series of parameters: add them - monitor->add(*generationCounter); - if (useEvalParam.value()) // we want nb of evaluations - monitor->add(_eval); - if (printBestParam.value()) - { - monitor->add(*bestStat); - monitor->add(*secondStat); - } - if (printFDCParam.value()) - monitor->add(*fdcStat); - if ( printPopParam.value()) - monitor->add(*popStat); + // the monitor will output a series of parameters: add them + monitor->add(*generationCounter); + if (useEvalParam.value()) // we want nb of evaluations + monitor->add(_eval); + if (printBestParam.value()) + { + monitor->add(*bestStat); + monitor->add(*secondStat); + } + if (printFDCParam.value()) + monitor->add(*fdcStat); + if ( printPopParam.value()) + monitor->add(*popStat); } // first handle the dir test - if we need at least one file if ( ( fileBestParam.value() || plotBestParam.value() || - plotFDCParam.value() || plotHistogramParam.value() ) - && !dirOK ) // just in case we add something before + plotFDCParam.value() || plotHistogramParam.value() ) + && !dirOK ) // just in case we add something before dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE if (fileBestParam.value()) // A file monitor for best & secondMoment { - std::string stmp = dirNameParam.value() + "/best.xg"; - eoFileMonitor *fileMonitor = new eoFileMonitor(stmp); - // save and give to checkpoint - _state.storeFunctor(fileMonitor); - checkpoint->add(*fileMonitor); - // and feed with some statistics - fileMonitor->add(*generationCounter); - fileMonitor->add(_eval); - fileMonitor->add(*bestStat); - fileMonitor->add(*secondStat); + std::string stmp = dirNameParam.value() + "/best.xg"; + eoFileMonitor *fileMonitor = new eoFileMonitor(stmp); + // save and give to checkpoint + _state.storeFunctor(fileMonitor); + checkpoint->add(*fileMonitor); + // and feed with some statistics + fileMonitor->add(*generationCounter); + fileMonitor->add(_eval); + fileMonitor->add(*bestStat); + fileMonitor->add(*secondStat); } if (plotBestParam.value()) // an eoGnuplot1DMonitor for best & average { - std::string stmp = dirNameParam.value() + "_gnu_best.xg"; - eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness()); - // save and give to checkpoint - _state.storeFunctor(gnuMonitor); - checkpoint->add(*gnuMonitor); - // and feed with some statistics - if (useEvalParam.value()) - gnuMonitor->add(_eval); - else - gnuMonitor->add(*generationCounter); - gnuMonitor->add(*bestStat); - gnuMonitor->add(*averageStat); + std::string stmp = dirNameParam.value() + "_gnu_best.xg"; + eoGnuplot1DMonitor *gnuMonitor = new eoGnuplot1DMonitor(stmp,minimizing_fitness()); + // save and give to checkpoint + _state.storeFunctor(gnuMonitor); + checkpoint->add(*gnuMonitor); + // and feed with some statistics + if (useEvalParam.value()) + gnuMonitor->add(_eval); + else + gnuMonitor->add(*generationCounter); + gnuMonitor->add(*bestStat); + gnuMonitor->add(*averageStat); } if (plotFDCParam.value()) // a specific plot monitor for FDC { - // first into a file (it adds everything ti itself - eoFDCFileSnapshot *fdcFileSnapshot = new eoFDCFileSnapshot(*fdcStat, dirNameParam.value()); - _state.storeFunctor(fdcFileSnapshot); - // then to a Gnuplot monitor - eoGnuplot1DSnapshot *fdcGnuplot = new eoGnuplot1DSnapshot(*fdcFileSnapshot); - _state.storeFunctor(fdcGnuplot); + // first into a file (it adds everything ti itself + eoFDCFileSnapshot *fdcFileSnapshot = new eoFDCFileSnapshot(*fdcStat, dirNameParam.value()); + _state.storeFunctor(fdcFileSnapshot); + // then to a Gnuplot monitor + eoGnuplot1DSnapshot *fdcGnuplot = new eoGnuplot1DSnapshot(*fdcFileSnapshot); + _state.storeFunctor(fdcGnuplot); - // and of course add them to the checkPoint - checkpoint->add(*fdcFileSnapshot); - checkpoint->add(*fdcGnuplot); + // and of course add them to the checkPoint + checkpoint->add(*fdcFileSnapshot); + checkpoint->add(*fdcGnuplot); } // historgram? if (plotHistogramParam.value()) // want to see how the fitness is spread? { - eoScalarFitnessStat *fitStat = new eoScalarFitnessStat; - _state.storeFunctor(fitStat); - checkpoint->add(*fitStat); - // a gnuplot-based monitor for snapshots: needs a dir name - eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value()); - _state.storeFunctor(fitSnapshot); - // add any stat that is a std::vector to it - fitSnapshot->add(*fitStat); - // and of course add it to the checkpoint - checkpoint->add(*fitSnapshot); + eoScalarFitnessStat *fitStat = new eoScalarFitnessStat; + _state.storeFunctor(fitStat); + checkpoint->add(*fitStat); + // a gnuplot-based monitor for snapshots: needs a dir name + eoGnuplot1DSnapshot *fitSnapshot = new eoGnuplot1DSnapshot(dirNameParam.value()); + _state.storeFunctor(fitSnapshot); + // add any stat that is a std::vector to it + fitSnapshot->add(*fitStat); + // and of course add it to the checkpoint + checkpoint->add(*fitSnapshot); } ////////////////////////////////// @@ -273,7 +273,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval { // first make sure dirName is OK 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 ); std::string stmp = dirNameParam.value() + "/generations"; @@ -288,7 +288,7 @@ eoCheckPoint& do_make_checkpoint(eoParser& _parser, eoState& _state, eoEval { // first make sure dirName is OK if (! dirOK ) - dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE + dirOK = testDirRes(dirNameParam.value(), eraseParam.value()); // TRUE std::string stmp = dirNameParam.value() + "/time"; eoTimedStateSaver *stateSaver2 = new eoTimedStateSaver(saveTimeIntervalParam.value(), _state, stmp); diff --git a/eo/src/do/make_checkpoint_assembled.h b/eo/src/do/make_checkpoint_assembled.h index 656b1376..26463fab 100644 --- a/eo/src/do/make_checkpoint_assembled.h +++ b/eo/src/do/make_checkpoint_assembled.h @@ -49,7 +49,7 @@ bool testDirRes(std::string _dirName, bool _erase); /////////////////// The checkpoint and other I/O ////////////// -/** Of course, Fitness needs to be an eoScalarFitnessAssembled!!! +/** Of course, Fitness needs to be an eoScalarFitnessAssembled!!! * * * @ingroup Builders @@ -153,7 +153,7 @@ eoCheckPoint& do_make_checkpoint_assembled(eoParser& _parser, eoState& _sta _state.storeFunctor(fitStat); checkpoint->add(*fitStat); #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); _state.storeFunctor(fitSnapshot); // add any stat that is a vector to it diff --git a/eo/src/do/make_continue.h b/eo/src/do/make_continue.h index 62862438..27b4e945 100644 --- a/eo/src/do/make_continue.h +++ b/eo/src/do/make_continue.h @@ -55,7 +55,7 @@ It can then be instantiated, and compiled on its own for a given EOType template eoCombinedContinue * make_combinedContinue(eoCombinedContinue *_combined, eoContinue *_cont) { - if (_combined) // already exists + if (_combined) // already exists _combined->add(*_cont); else _combined = new eoCombinedContinue(*_cont); @@ -81,10 +81,10 @@ eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu if (maxGenParam.value()) // positive: -> define and store { - eoGenContinue *genCont = new eoGenContinue(maxGenParam.value()); - _state.storeFunctor(genCont); - // and "add" to combined - continuator = make_combinedContinue(continuator, genCont); + eoGenContinue *genCont = new eoGenContinue(maxGenParam.value()); + _state.storeFunctor(genCont); + // and "add" to combined + continuator = make_combinedContinue(continuator, genCont); } // the steadyGen continue - only if user imput @@ -92,12 +92,12 @@ eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu eoValueParam& minGenParam = _parser.createParam(unsigned(0), "minGen", "Minimum number of generations",'g', "Stopping criterion"); if (_parser.isItThere(steadyGenParam)) { - eoSteadyFitContinue *steadyCont = new eoSteadyFitContinue - (minGenParam.value(), steadyGenParam.value()); - // store - _state.storeFunctor(steadyCont); - // add to combinedContinue - continuator = make_combinedContinue(continuator, steadyCont); + eoSteadyFitContinue *steadyCont = new eoSteadyFitContinue + (minGenParam.value(), steadyGenParam.value()); + // store + _state.storeFunctor(steadyCont); + // add to combinedContinue + continuator = make_combinedContinue(continuator, steadyCont); } // Same thing with Eval - but here default value is 0 @@ -108,10 +108,10 @@ eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu if (maxEvalParam.value()) // positive: -> define and store { - eoEvalContinue *evalCont = new eoEvalContinue(_eval, maxEvalParam.value()); - _state.storeFunctor(evalCont); - // and "add" to combined - continuator = make_combinedContinue(continuator, evalCont); + eoEvalContinue *evalCont = new eoEvalContinue(_eval, maxEvalParam.value()); + _state.storeFunctor(evalCont); + // and "add" to combined + continuator = make_combinedContinue(continuator, evalCont); } /* // the steadyEval continue - only if user imput @@ -119,12 +119,12 @@ eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu eoValueParam& minGenParam = _parser.createParam(unsigned(0), "minGen", "Minimum number of generations",'g', "Stopping criterion"); if (_parser.isItThere(steadyGenParam)) { - eoSteadyGenContinue *steadyCont = new eoSteadyFitContinue - (minGenParam.value(), steadyGenParam.value()); - // store - _state.storeFunctor(steadyCont); - // add to combinedContinue - continuator = make_combinedContinue(continuator, steadyCont); + eoSteadyGenContinue *steadyCont = new eoSteadyFitContinue + (minGenParam.value(), steadyGenParam.value()); + // store + _state.storeFunctor(steadyCont); + // add to combinedContinue + continuator = make_combinedContinue(continuator, steadyCont); } */ // the target fitness @@ -132,12 +132,12 @@ eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu eoValueParam& targetFitnessParam = _parser.createParam(double(0.0), "targetFitness", "Stop when fitness reaches",'T', "Stopping criterion"); if (_parser.isItThere(targetFitnessParam)) { - fitCont = new eoFitContinue - (targetFitnessParam.value()); - // store - _state.storeFunctor(fitCont); - // add to combinedContinue - continuator = make_combinedContinue(continuator, fitCont); + fitCont = new eoFitContinue + (targetFitnessParam.value()); + // store + _state.storeFunctor(fitCont); + // add to combinedContinue + continuator = make_combinedContinue(continuator, fitCont); } #ifndef _MSC_VER @@ -146,11 +146,11 @@ eoContinue & do_make_continue(eoParser& _parser, eoState& _state, eoEvalFu eoValueParam& ctrlCParam = _parser.createParam(false, "CtrlC", "Terminate current generation upon Ctrl C",'C', "Stopping criterion"); if (ctrlCParam.value()) { - ctrlCCont = new eoCtrlCContinue; - // store - _state.storeFunctor(ctrlCCont); - // add to combinedContinue - continuator = make_combinedContinue(continuator, ctrlCCont); + ctrlCCont = new eoCtrlCContinue; + // store + _state.storeFunctor(ctrlCCont); + // add to combinedContinue + continuator = make_combinedContinue(continuator, ctrlCCont); } #endif diff --git a/eo/src/do/make_general_replacement.h b/eo/src/do/make_general_replacement.h index 4f1f52e8..1d42345c 100644 --- a/eo/src/do/make_general_replacement.h +++ b/eo/src/do/make_general_replacement.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_general_replacement.h // (c) Marc Schoenauer and Pierre Collet, 2002 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -49,8 +49,8 @@ eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) eoReduce * ptReduce; // ---------- Deterministic - if ( (_ppReduce.first == std::string("Deterministic")) || - (_ppReduce.first == std::string("Sequential")) + if ( (_ppReduce.first == std::string("Deterministic")) || + (_ppReduce.first == std::string("Sequential")) ) { ptReduce = new eoTruncate; @@ -65,7 +65,7 @@ eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) // put back 6 in parameter for consistency (and status file) _ppReduce.second.push_back(std::string("6")); } - else // parameter passed by user as EP(T) + else // parameter passed by user as EP(T) detSize = atoi(_ppReduce.second[0].c_str()); ptReduce = new eoEPReduce(detSize); } @@ -74,12 +74,12 @@ eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) { if (!_ppReduce.second.size()) // no parameter added { - std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; - detSize = 2; - // put back 2 in parameter for consistency (and status file) - _ppReduce.second.push_back(std::string("2")); + std::cerr << "WARNING, no parameter passed to DetTour, using 2" << std::endl; + detSize = 2; + // put back 2 in parameter for consistency (and status file) + _ppReduce.second.push_back(std::string("2")); } - else // parameter passed by user as DetTour(T) + else // parameter passed by user as DetTour(T) detSize = atoi(_ppReduce.second[0].c_str()); ptReduce = new eoDetTournamentTruncate(detSize); } @@ -87,24 +87,24 @@ eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) { double p; if (!_ppReduce.second.size()) // no parameter added - { - std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; - p = 1; - // put back p in parameter for consistency (and status file) - _ppReduce.second.push_back(std::string("1")); - } - else // parameter passed by user as DetTour(T) - { - p = atof(_ppReduce.second[0].c_str()); - if ( (p<=0.5) || (p>1) ) - throw std::runtime_error("Stochastic tournament size should be in [0.5,1]"); - } - + { + std::cerr << "WARNING, no parameter passed to StochTour, using 1" << std::endl; + p = 1; + // put back p in parameter for consistency (and status file) + _ppReduce.second.push_back(std::string("1")); + } + else // parameter passed by user as DetTour(T) + { + p = atof(_ppReduce.second[0].c_str()); + if ( (p<=0.5) || (p>1) ) + throw std::runtime_error("Stochastic tournament size should be in [0.5,1]"); + } + ptReduce = new eoStochTournamentTruncate(p); } - else if ( (_ppReduce.first == std::string("Uniform")) || - (_ppReduce.first == std::string("Random")) - ) + else if ( (_ppReduce.first == std::string("Uniform")) || + (_ppReduce.first == std::string("Random")) + ) { ptReduce = new eoRandomReduce; } @@ -117,10 +117,10 @@ eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) return (*ptReduce); } -/** Helper function that creates a replacement from the class - * eoReduceMergeReduce using 6 parameters +/** Helper function that creates a replacement from the class + * eoReduceMergeReduce using 6 parameters * (after the usual eoState and eoParser) - * + * * eoHowMany _elite the number of elite parents (0 = no elitism) * see below * bool _strongElitism if elite > 0, std::string elitism or weak elitism @@ -136,15 +136,15 @@ eoReduce & decode_reduce(eoParamParamType & _ppReduce, eoState & _state) */ template eoReplacement & make_general_replacement( - eoParser& _parser, eoState& _state, - eoHowMany _elite = eoHowMany(0), + eoParser& _parser, eoState& _state, + eoHowMany _elite = eoHowMany(0), bool _strongElitism = false, eoHowMany _surviveParents = eoHowMany(0.0), eoParamParamType & _reduceParentType = eoParamParamType("Deterministic"), eoHowMany _surviveOffspring = eoHowMany(1.0), eoParamParamType & _reduceOffspringType = eoParamParamType("Deterministic"), eoParamParamType & _reduceFinalType = eoParamParamType("Deterministic") - ) + ) { ///////////////////////////////////////////////////// // the replacement @@ -157,14 +157,14 @@ eoReplacement & make_general_replacement( // reduce the parents eoHowMany surviveParents = _parser.createParam(_surviveParents, "surviveParents", "Nb of surviving parents (percentage or absolute)", '\0', "Evolution Engine / Replacement").value(); - + eoParamParamType & reduceParentType = _parser.createParam(_reduceParentType, "reduceParents", "Parents reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform", '\0', "Evolution Engine / Replacement").value(); eoReduce & reduceParent = decode_reduce(reduceParentType, _state); // reduce the offspring eoHowMany surviveOffspring = _parser.createParam(_surviveOffspring, "surviveOffspring", "Nb of surviving offspring (percentage or absolute)", '\0', "Evolution Engine / Replacement").value(); - + eoParamParamType & reduceOffspringType = _parser.createParam(_reduceOffspringType, "reduceOffspring", "Offspring reducer: Deterministic, EP(T), DetTour(T), StochTour(t), Uniform", '\0', "Evolution Engine / Replacement").value(); eoReduce & reduceOffspring = decode_reduce(reduceOffspringType, _state); diff --git a/eo/src/do/make_pop.h b/eo/src/do/make_pop.h index 191ab065..c2a1d1a8 100644 --- a/eo/src/do/make_pop.h +++ b/eo/src/do/make_pop.h @@ -59,7 +59,7 @@ eoPop& do_make_pop(eoParser & _parser, eoState& _state, eoInit & _ini // random seed eoValueParam& seedParam = _parser.getORcreateParam(uint32_t(0), "seed", "Random number seed", 'S'); if (seedParam.value() == 0) - seedParam.value() = time(0); + seedParam.value() = time(0); eoValueParam& popSize = _parser.getORcreateParam(unsigned(20), "popSize", "Population Size", 'P', "Evolution Engine"); // Either load or initialize @@ -82,17 +82,17 @@ eoPop& do_make_pop(eoParser & _parser, eoState& _state, eoInit & _ini // the fitness is read in the file: // do only evaluate the pop if the fitness has changed if (recomputeFitnessParam.value()) - { - for (unsigned i=0; i popSize.value()) - { - std::cerr << "WARNING, Load file contained too many individuals. Only the best will be retained" << std::endl; - pop.resize(popSize.value()); - } + { + std::cerr << "WARNING, Load file contained too many individuals. Only the best will be retained" << std::endl; + pop.resize(popSize.value()); + } } else // nothing loaded from a file { diff --git a/eo/src/do/make_run.h b/eo/src/do/make_run.h index 7e1e2889..485cb870 100644 --- a/eo/src/do/make_run.h +++ b/eo/src/do/make_run.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_run.h // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either diff --git a/eo/src/eoCellularEasyEA.h b/eo/src/eoCellularEasyEA.h index 98595ae0..fbf3085f 100644 --- a/eo/src/eoCellularEasyEA.h +++ b/eo/src/eoCellularEasyEA.h @@ -8,16 +8,16 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: cahon@lifl.fr */ @@ -32,26 +32,26 @@ #include /** - The abstract cellular easy algorithm. + The abstract cellular easy algorithm. @ingroup Algorithms */ template class eoCellularEasyEA : public eoAlgo { - + public : - + /** Two constructors */ eoCellularEasyEA (eoContinue & _cont, // Stop. criterion - eoEvalFunc & _eval, // Evaluation function - eoSelectOne & _sel_neigh, // To choose a partner - eoBinOp & _cross, // Cross-over operator - eoMonOp & _mut, // Mutation operator - eoSelectOne & _sel_repl /* Which to keep between the new - child and the old individual ? */ - ) : + eoEvalFunc & _eval, // Evaluation function + eoSelectOne & _sel_neigh, // To choose a partner + eoBinOp & _cross, // Cross-over operator + eoMonOp & _mut, // Mutation operator + eoSelectOne & _sel_repl /* Which to keep between the new + child and the old individual ? */ + ) : cont (_cont), eval (_eval), popEval (_eval), @@ -60,18 +60,18 @@ public : mut (_mut), sel_child (eoSelectFirstOne ()), sel_repl (_sel_repl) { - + } - + eoCellularEasyEA (eoContinue & _cont, - eoEvalFunc & _eval, - eoSelectOne & _sel_neigh, - eoQuadOp & _cross, - eoMonOp & _mut, - eoSelectOne & _sel_child, /* To choose one from - the both children */ - eoSelectOne & _sel_repl - ) : + eoEvalFunc & _eval, + eoSelectOne & _sel_neigh, + eoQuadOp & _cross, + eoMonOp & _mut, + eoSelectOne & _sel_child, /* To choose one from + the both children */ + eoSelectOne & _sel_repl + ) : cont (_cont), eval (_eval), popEval (_eval), @@ -80,7 +80,7 @@ public : mut (_mut), sel_child (_sel_child), sel_repl (_sel_repl) { - + } /** @@ -88,55 +88,55 @@ public : */ void operator () (eoPop & pop) { - + do { - + for (unsigned i = 0 ; i < pop.size () ; i ++) { - - // Who are neighbouring to the current individual ? - eoPop neigh = neighbours (pop, i) ; - - // To select a partner - EOT part, old_sol = pop [i] ; - part = sel_neigh (neigh) ; - // To perform cross-over - cross (pop [i], part) ; + // Who are neighbouring to the current individual ? + eoPop neigh = neighbours (pop, i) ; - // To perform mutation - mut (pop [i]) ; - mut (part) ; - - pop [i].invalidate () ; - part.invalidate () ; - eval (pop [i]) ; - eval (part) ; + // To select a partner + EOT part, old_sol = pop [i] ; + part = sel_neigh (neigh) ; - // To choose one of the two children ... - eoPop pop_loc ; - pop_loc.push_back (pop [i]) ; - pop_loc.push_back (part) ; + // To perform cross-over + cross (pop [i], part) ; - pop [i] = sel_child (pop_loc) ; + // To perform mutation + mut (pop [i]) ; + mut (part) ; - // To choose only one between the new made child and the old individual - pop_loc.clear () ; - pop_loc.push_back (pop [i]) ; - - pop_loc.push_back (old_sol) ; - - pop [i] = sel_repl (pop_loc) ; + pop [i].invalidate () ; + part.invalidate () ; + eval (pop [i]) ; + eval (part) ; + + // To choose one of the two children ... + eoPop pop_loc ; + pop_loc.push_back (pop [i]) ; + pop_loc.push_back (part) ; + + pop [i] = sel_child (pop_loc) ; + + // To choose only one between the new made child and the old individual + pop_loc.clear () ; + pop_loc.push_back (pop [i]) ; + + pop_loc.push_back (old_sol) ; + + pop [i] = sel_repl (pop_loc) ; } - + } while (cont (pop)) ; } protected : - + virtual eoPop neighbours (const eoPop & pop, int rank) = 0 ; private : - + eoContinue & cont ; eoEvalFunc & eval ; eoPopLoopEval popEval ; @@ -145,18 +145,18 @@ private : eoMonOp & mut ; eoSelectOne & sel_child ; eoSelectOne & sel_repl ; - + class eoSelectFirstOne : public eoSelectOne { - + public : - + const EOT & operator () (const eoPop & pop) { - - return pop [0] ; + + return pop [0] ; } - - } ; - + + } ; + } ; #endif diff --git a/eo/src/eoCloneOps.h b/eo/src/eoCloneOps.h index bdb9f041..e53cbd74 100644 --- a/eo/src/eoCloneOps.h +++ b/eo/src/eoCloneOps.h @@ -2,7 +2,7 @@ //----------------------------------------------------------------------------- // eoCloneOps.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -18,7 +18,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: todos@geneura.ugr.es, http://geneura.ugr.es - CVS Info: $Date: 2003-02-27 19:26:09 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoCloneOps.h,v 1.2 2003-02-27 19:26:09 okoenig Exp $ $Author: okoenig $ + CVS Info: $Date: 2003-02-27 19:26:09 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoCloneOps.h,v 1.2 2003-02-27 19:26:09 okoenig Exp $ $Author: okoenig $ */ //----------------------------------------------------------------------------- @@ -29,9 +29,9 @@ /** * The different null-variation operators (i.e. they do nothing) - * - * eoQuadCloneOp at least is useful to emulate the standard - * crossover(pCross) + mutation(pMut) + * + * eoQuadCloneOp at least is useful to emulate the standard + * crossover(pCross) + mutation(pMut) * within the eoGenOp framework * eoMonCloneOp will probably be useful as the copy operator * eoBinCloneOp will certainly never been used - but let's be complete :-) @@ -80,4 +80,3 @@ virtual bool operator()(EOT& , EOT& ) {return false;} #endif /** @} */ - diff --git a/eo/src/eoCombinedContinue.h b/eo/src/eoCombinedContinue.h index 2788f415..4dac4d69 100644 --- a/eo/src/eoCombinedContinue.h +++ b/eo/src/eoCombinedContinue.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoCombinedContinue.h // (c) Maarten Keijzer, GeNeura Team, 1999, 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #include -/** +/** Combined continuators - logical AND: Continues until one of the embedded continuators says halt! @@ -35,7 +35,7 @@ to be consistent with other Combined constructs and allow to easily handle more than 2 continuators -02/2003 Ramón Casero Cañas - added the removeLast() method +02/2003 Ramón Casero Cañas - added the removeLast() method @ingroup Combination */ @@ -90,4 +90,3 @@ private: }; #endif - diff --git a/eo/src/eoCombinedInit.h b/eo/src/eoCombinedInit.h index 67fa0230..d41122d8 100644 --- a/eo/src/eoCombinedInit.h +++ b/eo/src/eoCombinedInit.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoCombinedInit.h // (c) Maarten Keijzer, GeNeura Team, Marc Schoenauer 2004 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #include -/** +/** Combined INIT: a proportional recombination of eoInit objects @ingroup Initializators @@ -49,7 +49,7 @@ public: eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoCombinedInit::add is deprecated and will be removed in the next release." << std::endl; add( _init, _rate ); } - + /** The usual method to add objects to the combination */ void add(eoInit & _init, double _rate) @@ -78,7 +78,7 @@ public: virtual void operator() ( EOT & _eo ) { unsigned what = rng.roulette_wheel(rates); // choose one op - (*initializers[what])(_eo); // apply it + (*initializers[what])(_eo); // apply it return; } @@ -90,4 +90,3 @@ std::vector rates; }; #endif - diff --git a/eo/src/eoConstrictedVariableWeightVelocity.h b/eo/src/eoConstrictedVariableWeightVelocity.h index fd0dc13b..9e96d7ef 100644 --- a/eo/src/eoConstrictedVariableWeightVelocity.h +++ b/eo/src/eoConstrictedVariableWeightVelocity.h @@ -56,9 +56,9 @@ public: * @param _topology - The topology to get the global/local/other best * @param _coeff - The constriction coefficient * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng @@ -85,9 +85,9 @@ public: * @param _topology - The topology to get the global/local/other best * @param _coeff - The constriction coefficient * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -112,8 +112,8 @@ public: * @param _topology - The topology to get the global/local/other best* * @param _coeff - The constriction coefficient * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _gen - The eo random generator, default=rng */ eoConstrictedVariableWeightVelocity (eoTopology < POT > & _topology, @@ -134,7 +134,7 @@ public: /** * Evaluate the new velocities of the given particle. Need an indice to identify the particle - * into the topology. Steps are : + * into the topology. Steps are : * - evaluate r1 and r2, the customed learning factors * - adjust the size of the bounds (even if dummy) * - update the weight with the weightUpdater (use the dummy updater if there's no updater provided) @@ -189,22 +189,21 @@ public: protected: eoTopology < POT > & topology; - + const VelocityType & coeff; // the fixed constriction coefficient - eoWeightUpdater & weightUpdater; // the updater used to make the weight evoluate - - const VelocityType & c1; // learning factor 1 - const VelocityType & c2; // learning factor 2 - + eoWeightUpdater & weightUpdater; // the updater used to make the weight evoluate + + const VelocityType & c1; // learning factor 1 + const VelocityType & c2; // learning factor 2 + eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. eoRealBoundModifier & bndsModifier; - + VelocityType weight; - eoRng & gen; // the random generator - + eoRng & gen; // the random generator + // If the bound modifier doesn't need to be used, use the dummy instance eoDummyRealBoundModifier dummyModifier; }; #endif /*EOCONSTRICTEDVARIABLEWEIGHTVELOCITY_H*/ - diff --git a/eo/src/eoConstrictedVelocity.h b/eo/src/eoConstrictedVelocity.h index bd68f042..45f6e03d 100644 --- a/eo/src/eoConstrictedVelocity.h +++ b/eo/src/eoConstrictedVelocity.h @@ -56,9 +56,9 @@ public: /** Full constructor: Bounds and bound modifier required * @param _topology - The topology to get the global/local/other best * @param _coeff - The constriction coefficient - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng @@ -82,9 +82,9 @@ public: /** Constructor: No bound updater required <-> fixed bounds * @param _topology - The topology to get the global/local/other best * @param _coeff - The constriction coefficient - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -106,8 +106,8 @@ public: /** Constructor: Neither bounds nor bound updater required <-> free velocity * @param _topology - The topology to get the global/local/other best * @param _coeff - The constriction coefficient - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _gen - The eo random generator, default=rng */ eoConstrictedVelocity (eoTopology < POT > & _topology, @@ -126,7 +126,7 @@ public: /** * Evaluate the new velocities of the given particle. Need an indice to identify the particle - * into the topology. Steps are : + * into the topology. Steps are : * - evaluate r1 and r2, the customed learning factors * - adjust the size of the bounds (even if dummy) * - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided) @@ -173,20 +173,20 @@ public: topology.updateNeighborhood(_po,_indice); } - //! eoTopology getTopology + //! eoTopology getTopology //! @return topology - eoTopology & getTopology () - { - return topology; - } + eoTopology & getTopology () + { + return topology; + } protected: eoTopology < POT > & topology; - const VelocityType & c1; // learning factor 1 - const VelocityType & c2; // learning factor 2 + const VelocityType & c1; // learning factor 1 + const VelocityType & c2; // learning factor 2 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. eoRealBoundModifier & bndsModifier; @@ -197,4 +197,3 @@ protected: #endif /*EOCONSTRICTEDVELOCITY_H */ - diff --git a/eo/src/eoContinue.h b/eo/src/eoContinue.h index 98321512..dbbf2480 100644 --- a/eo/src/eoContinue.h +++ b/eo/src/eoContinue.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoContinue.h // (c) Maarten Keijzer, Geneura Team, 1999, 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -31,7 +31,7 @@ /** @defgroup Continuators Stopping criteria * - * A stopping criterion is called a "continue". This is a functor that is called at each generation end + * A stopping criterion is called a "continue". This is a functor that is called at each generation end * and that return true if one should stop the search. * * @ingroup Utilities @@ -39,13 +39,13 @@ /** Termination condition for the genetic algorithm * Takes the population as input, returns true for continue, - * false for termination + * false for termination * * @ingroup Continuators * @ingroup Core */ template< class EOT> -class eoContinue : public eoUF&, bool>, public eoPersistent +class eoContinue : public eoUF&, bool>, public eoPersistent { public: virtual std::string className(void) const { return "eoContinue"; } @@ -57,7 +57,7 @@ public: (void)__is; /* It should be implemented by subclasses ! */ } - + /** Print on a stream * @param __os ostream to print on */ @@ -68,4 +68,3 @@ public: }; #endif - diff --git a/eo/src/eoCounter.h b/eo/src/eoCounter.h index cb0b57cf..afd7fd2e 100644 --- a/eo/src/eoCounter.h +++ b/eo/src/eoCounter.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoCounter.h // (c) Maarten Keijzer 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -31,9 +31,9 @@ #include /** - Generic counter class that counts the number of times - a procedure is used. Add a procedure through its ctor and - use this class instead of it. + Generic counter class that counts the number of times + a procedure is used. Add a procedure through its ctor and + use this class instead of it. It is derived from eoValueParam so you can add it to a monitor. @@ -44,21 +44,21 @@ class eoProcedureCounter : public Procedure, public eoValueParam { public: - eoProcedureCounter(Procedure& _proc, std::string _name = "proc_counter") + eoProcedureCounter(Procedure& _proc, std::string _name = "proc_counter") : eoValueParam(0, _name), proc(_proc) {} /** Calls the embedded function and increments the counter - + Note for MSVC users, if this code does not compile, you are quite likely trying to count a function that has a non-void return type. Don't look at us, look at the MSVC builders. Code like "return void;" is perfectly legal according to the ANSI standard, but the guys at - Microsoft didn't get to implementing it yet. - + Microsoft didn't get to implementing it yet. + We had two choices: assuming (and compiling ) code that returns void or code that returns non-void. Given that in EO most functors return void, it was chosen to support void. - But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite + But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite capable of compiling return void; type of code. We'll try to change the signature then. You happy GNU (and other compiler) users will not have a problem with this.. @@ -79,39 +79,39 @@ class eoProcedureCounter : public Procedure, public eoValueParam }; /** - Generic counter class that counts the number of times - a unary function is used. Add a unary function through its ctor and - use this class instead of it. - + Generic counter class that counts the number of times + a unary function is used. Add a unary function through its ctor and + use this class instead of it. + It is derived from eoValueParam so you can add it to a monitor. - Example: suppose you have an eoEvalFunc called myeval, to count the + Example: suppose you have an eoEvalFunc called myeval, to count the number of evaluations, just define: eoUnaryFunctorCounter evalCounter(myeval); - and use evalCounter now instead of myeval. + and use evalCounter now instead of myeval. */ template class eoUnaryFunctorCounter : public UnaryFunctor, public eoValueParam { public: - eoUnaryFunctorCounter(UnaryFunctor& _func, std::string _name = "uf_counter") + eoUnaryFunctorCounter(UnaryFunctor& _func, std::string _name = "uf_counter") : eoValueParam(0, _name), func(_func) {} - + /** Calls the embedded function and increments the counter - + Note for MSVC users, if this code does not compile, you are quite likely trying to count a function that has a non-void return type. Don't look at us, look at the MSVC builders. Code like "return void;" is perfectly legal according to the ANSI standard, but the guys at - Microsoft didn't get to implementing it yet. - + Microsoft didn't get to implementing it yet. + We had two choices: assuming (and compiling ) code that returns void or code that returns non-void. Given that in EO most functors return void, it was chosen to support void. - But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite + But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite capable of compiling return void; type of code. We'll try to change the signature then. You happy GNU (and other compiler) users will not have a problem with this. @@ -133,10 +133,10 @@ class eoUnaryFunctorCounter : public UnaryFunctor, public eoValueParam class eoBinaryFunctorCounter : public BinaryFunctor, public eoValueParam { public: - eoBinaryFunctorCounter(BinaryFunctor& _func, std::string _name = "proc_counter") + eoBinaryFunctorCounter(BinaryFunctor& _func, std::string _name = "proc_counter") : eoValueParam(0, _name), func(_func) {} /** Calls the embedded function and increments the counter - + Note for MSVC users, if this code does not compile, you are quite likely trying to count a function that has a non-void return type. Don't look at us, look at the MSVC builders. Code like "return void;" is perfectly legal according to the ANSI standard, but the guys at - Microsoft didn't get to implementing it yet. - + Microsoft didn't get to implementing it yet. + We had two choices: assuming (and compiling ) code that returns void or code that returns non-void. Given that in EO most functors return void, it was chosen to support void. - But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite + But also please let me know if you have a compiler that defines _MSC_VER (lot's of windows compilers do), but is quite capable of compiling return void; type of code. We'll try to change the signature then. - + You happy GNU (and other compiler) users will not have a problem with this. */ typename BinaryFunctor::result_type operator() - (typename BinaryFunctor::first_argument_type _arg1, + (typename BinaryFunctor::first_argument_type _arg1, typename BinaryFunctor::second_argument_type _arg2) { value()++; @@ -185,7 +185,7 @@ class eoBinaryFunctorCounter : public BinaryFunctor, public eoValueParam), by simply stating: diff --git a/eo/src/eoCtrlCContinue.cpp b/eo/src/eoCtrlCContinue.cpp index 0e04422a..b7ee7fea 100644 --- a/eo/src/eoCtrlCContinue.cpp +++ b/eo/src/eoCtrlCContinue.cpp @@ -1,23 +1,23 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoCtrlCContinue.cpp -// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 +// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 /* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es Marc.Schoenauer@polytechnique.fr mak@dhi.dk @@ -26,7 +26,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #include diff --git a/eo/src/eoCtrlCContinue.h b/eo/src/eoCtrlCContinue.h index 9b1aac0f..9bbcf9c0 100644 --- a/eo/src/eoCtrlCContinue.h +++ b/eo/src/eoCtrlCContinue.h @@ -1,23 +1,23 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoCtrlCContinue.h -// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 +// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 /* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es Marc.Schoenauer@polytechnique.fr mak@dhi.dk @@ -50,14 +50,14 @@ template< class EOT> class eoCtrlCContinue: public eoContinue { public: - + /// Ctor : installs the signal handler eoCtrlCContinue() { // First checks that no other eoCtrlCContinue does exist if (existCtrlCContinue) throw std::runtime_error("A signal handler for Ctrl C is already defined!\n"); - + #ifndef _WINDOWS #ifdef SIGQUIT signal( SIGINT, signal_handler ); @@ -65,9 +65,9 @@ public: existCtrlCContinue = true; #endif #endif - + } - + /** Returns false when Ctrl C has been typed in * reached */ virtual bool operator() ( const eoPop& _vEO ) @@ -84,4 +84,3 @@ public: #endif /** @} */ - diff --git a/eo/src/eoDetSelect.h b/eo/src/eoDetSelect.h index 2ad6cde0..4a0858b6 100644 --- a/eo/src/eoDetSelect.h +++ b/eo/src/eoDetSelect.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoDetSelect.h + eoDetSelect.h (c) Marc Schoenauer, Maarten Keijzer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -48,7 +48,7 @@ class eoDetSelect : public eoSelect /** @param _source the source population - @param _dest the resulting population (size of this population is + @param _dest the resulting population (size of this population is given by the HowMany data It empties the destination and adds the selection into it) */ @@ -58,32 +58,32 @@ class eoDetSelect : public eoSelect size_t target = howMany(pSize); if ( target == 0 ) - { - eo::log << eo::warnings << "Call to a eoHowMany instance returns 0 (target=" << target << ") it will be replaced by 1 to continue." << std::endl; - target = 1; - } + { + eo::log << eo::warnings << "Call to a eoHowMany instance returns 0 (target=" << target << ") it will be replaced by 1 to continue." << std::endl; + target = 1; + } _dest.resize(target); unsigned remain = target % pSize; unsigned entireCopy = target / pSize; typename eoPop::iterator it = _dest.begin(); - + if (target >= pSize) { - for (unsigned i=0; i // +#include // #include // accumulate #include @@ -37,7 +37,7 @@ #include /** eoDetTournamentSelect: a selection method that selects ONE individual by - deterministic tournament + deterministic tournament -MS- 24/10/99 @ingroup Selectors @@ -45,7 +45,7 @@ template class eoDetTournamentSelect: public eoSelectOne { public: - /* (Default) Constructor - + /* (Default) Constructor - @param _tSize tournament size */ eoDetTournamentSelect(unsigned _tSize = 2 ):eoSelectOne(), tSize(_tSize) { @@ -55,15 +55,15 @@ template class eoDetTournamentSelect: public eoSelectOne tSize = 2; } } - - /* Perform deterministic tournament calling the appropriate fn + + /* Perform deterministic tournament calling the appropriate fn see selectors.h */ - virtual const EOT& operator()(const eoPop& _pop) + virtual const EOT& operator()(const eoPop& _pop) { return deterministic_tournament(_pop, tSize); } - + private: unsigned tSize; }; @@ -71,4 +71,3 @@ template class eoDetTournamentSelect: public eoSelectOne //----------------------------------------------------------------------------- #endif - diff --git a/eo/src/eoDistribUpdater.h b/eo/src/eoDistribUpdater.h index 6166e733..79b22814 100644 --- a/eo/src/eoDistribUpdater.h +++ b/eo/src/eoDistribUpdater.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoDistribUpdater.h // (c) Marc Schoenauer, Maarten Keijzer, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -32,7 +32,7 @@ #include /** - * Base class for Distribution Evolution Algorithms within EO: + * Base class for Distribution Evolution Algorithms within EO: * the update rule of distribution * * It takes one distribution and updates it according to one population @@ -40,7 +40,7 @@ * @ingroup Core */ template -class eoDistribUpdater : +class eoDistribUpdater : public eoBF &, eoPop &, void> { public: diff --git a/eo/src/eoDistribution.h b/eo/src/eoDistribution.h index 1f38ab94..6ca90fe4 100644 --- a/eo/src/eoDistribution.h +++ b/eo/src/eoDistribution.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoDistribution.h // (c) Marc Schoenauer, Maarten Keijzer, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -44,8 +44,8 @@ */ template -class eoDistribution : public eoInit, - public eoPersistent, public eoObject +class eoDistribution : public eoInit, + public eoPersistent, public eoObject { public: virtual void operator()(EOT &) = 0; // DO NOT FORGET TO INVALIDATE the EOT diff --git a/eo/src/eoDualFitness.h b/eo/src/eoDualFitness.h index 4cd34c6a..4803361f 100644 --- a/eo/src/eoDualFitness.h +++ b/eo/src/eoDualFitness.h @@ -4,7 +4,7 @@ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; version 2 + License as published by the Free Software Foundation; version 2 of the License. This library is distributed in the hope that it will be useful, @@ -40,7 +40,7 @@ Authors: //! A fitness class that permits to compare feasible and unfeasible individuals and guaranties that a feasible individual will always be better than an unfeasible one. /** - * Use this class as fitness if you have some kind of individuals + * Use this class as fitness if you have some kind of individuals * that must be always considered as better than others while having the same fitness type. * * Wraps a scalar fitness _values such as a double or int, with the option of @@ -52,7 +52,7 @@ Authors: * * When changing the fitness, you can use: * individual.fitness( std::make_pair( fitness, feasibility ) ); - * + * * Be aware that, when printing or reading an eDualFitness instance on a iostream, * friend IO classes use a space separator. * @@ -80,19 +80,19 @@ public: /*! * Unfeasible by default */ - eoDualFitness() : - _value(), - _is_feasible(false) + eoDualFitness() : + _value(), + _is_feasible(false) {} //! Copy constructor eoDualFitness(const eoDualFitness& other) : _value(other._value), - _is_feasible(other._is_feasible) + _is_feasible(other._is_feasible) {} //! Constructor from explicit value/feasibility - eoDualFitness(const BaseType& v, const bool& is_feasible) : + eoDualFitness(const BaseType& v, const bool& is_feasible) : _value(v), _is_feasible(is_feasible) {} @@ -118,15 +118,15 @@ public: { _value = v.first; _is_feasible = v.second; - return *this; + return *this; } - + //! Copy operator from another eoDualFitness template eoDualFitness & operator=(const eoDualFitness& other ) { if (this != &other) { - this->_value = other._value; + this->_value = other._value; this->_is_feasible = other._is_feasible; } return *this; @@ -135,12 +135,12 @@ public: //! Comparison that separate feasible individuals from unfeasible ones. Feasible are always better /*! - * Use less as a default comparison operator + * Use less as a default comparison operator * (see the "Compare" template of the class to change this behaviour, * @see eoMinimizingDualFitness for an example). */ bool operator<(const eoDualFitness& other) const - { + { // am I better (less, by default) than the other ? // if I'm feasible and the other is not @@ -152,7 +152,7 @@ public: // yes, a feasible fitness is always better than an unfeasible one return true; - } else { + } else { // the two fitness are of the same type // lets rely on the comparator return Compare()(_value, other._value); @@ -168,7 +168,7 @@ public: //! Greater or equal: if the other is not greater than me bool operator>=(const eoDualFitness& other ) const { return !(*this < other); } - + public: //! Add a given fitness to the current one @@ -199,7 +199,7 @@ public: // Add this fitness's value to that other, and return a _new_ instance with the result. template - eoDualFitness operator+(const eoDualFitness & that) + eoDualFitness operator+(const eoDualFitness & that) { eoDualFitness from( *this ); return from += that; @@ -207,7 +207,7 @@ public: // Add this fitness's value to that other, and return a _new_ instance with the result. template - eoDualFitness operator-(const eoDualFitness & that) + eoDualFitness operator-(const eoDualFitness & that) { eoDualFitness from( *this ); return from -= that; @@ -224,7 +224,7 @@ public: //! Read an eoDualFitness instance as a pair of numbers, separated by a space template - friend + friend std::istream& operator>>(std::istream& is, eoDualFitness& f) { F value; @@ -265,11 +265,11 @@ public: // eoDualStatSwitch( eoStat & stat_feasible, eoStat & stat_unfeasible, std::string sep=" " ) : eoDualStatSwitch( EOSTAT & stat_feasible, EOSTAT & stat_unfeasible, std::string sep=" " ) : eoStat( - "?"+sep+"?", - stat_feasible.longName()+sep+stat_unfeasible.longName() - ), - _stat_feasible(stat_feasible), - _stat_unfeasible(stat_unfeasible), + "?"+sep+"?", + stat_feasible.longName()+sep+stat_unfeasible.longName() + ), + _stat_feasible(stat_feasible), + _stat_unfeasible(stat_unfeasible), _sep(sep) { } @@ -277,7 +277,7 @@ public: { eoPop pop_feasible; pop_feasible.reserve(pop.size()); - + eoPop pop_unfeasible; pop_unfeasible.reserve(pop.size()); @@ -296,7 +296,7 @@ public: _stat_feasible( pop_feasible ); _stat_unfeasible( pop_unfeasible ); - + std::ostringstream out; out << _stat_feasible.value() << _sep << _stat_unfeasible.value(); @@ -311,7 +311,6 @@ protected: std::string _sep; }; - + /** @} */ #endif // _eoDualFitness_h_ - diff --git a/eo/src/eoEDA.h b/eo/src/eoEDA.h index 896c5a97..553b751f 100644 --- a/eo/src/eoEDA.h +++ b/eo/src/eoEDA.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoEDA.h // (c) Marc Schoenauer, Maarten Keijzer, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -30,8 +30,8 @@ #include -/** The abstract class for estimation of disribution algorithms. - * This design evolve a probability distribution +/** The abstract class for estimation of disribution algorithms. + * This design evolve a probability distribution * on the spaces of populations rather than a population * * It IS NOT an eoAlgo, as it evolves a distribution, not a population. @@ -44,4 +44,3 @@ template class eoEDA: public eoUF&, void> }; #endif - diff --git a/eo/src/eoEasyEA.h b/eo/src/eoEasyEA.h index 2ca8d37e..eb773969 100644 --- a/eo/src/eoEasyEA.h +++ b/eo/src/eoEasyEA.h @@ -97,7 +97,7 @@ template class eoEasyEA: public eoAlgo mergeReduce(dummyMerge, dummyReduce), 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 eoEasyEA: public eoAlgo {} - /// Ctor eoSelect, eoTransform, eoReplacement and an eoPopEval - eoEasyEA( + /// Ctor eoSelect, eoTransform, eoReplacement and an eoPopEval + eoEasyEA( eoContinue& _continuator, eoPopEvalFunc& _eval, eoSelect& _select, @@ -185,7 +185,7 @@ template class eoEasyEA: public eoAlgo mergeReduce(dummyMerge, dummyReduce), replace(_replace) {} - + /// Ctor eoSelect, eoTransform, eoMerge and eoReduce. eoEasyEA( eoContinue& _continuator, @@ -291,7 +291,7 @@ template class eoEasyEA: public eoAlgo eoMergeReduce mergeReduce; eoReplacement& replace; - eoPop offspring; + eoPop offspring; // Friend classes friend class eoIslandsEasyEA ; @@ -303,4 +303,3 @@ Example of a test program building an EA algorithm. */ #endif - diff --git a/eo/src/eoEasyPSO.h b/eo/src/eoEasyPSO.h index bcfc891a..da071bc0 100644 --- a/eo/src/eoEasyPSO.h +++ b/eo/src/eoEasyPSO.h @@ -32,16 +32,16 @@ #include //----------------------------------------------------------------------------- -/** An easy-to-use particle swarm algorithm. -* Use any particle, any flight, any topology... +/** An easy-to-use particle swarm algorithm. +* Use any particle, any flight, any topology... * * The main steps are : -* (The population is expected to be already evaluated) -* - for each generation and each particle pi -* - evaluate the velocities -* -- perform the fligth of pi -* -- evaluate pi -* -- update the neighborhoods +* (The population is expected to be already evaluated) +* - for each generation and each particle pi +* - evaluate the velocities +* -- perform the fligth of pi +* -- evaluate pi +* -- update the neighborhoods * * @ingroup Algorithms */ @@ -54,7 +54,7 @@ public: * @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system * @param _eval - An eoEvalFunc: the evaluation performer * @param _velocity - An eoVelocity that defines how to compute the velocities - * @param _flight - An eoFlight that defines how to make the particle flying: that means how + * @param _flight - An eoFlight that defines how to make the particle flying: that means how * to modify the positions according to the velocities */ eoEasyPSO ( @@ -90,11 +90,11 @@ public: {} - /* Constructor without eoInitializerBase. Assume the initialization is done before running the algorithm + /* Constructor without eoInitializerBase. Assume the initialization is done before running the algorithm * @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system * @param _eval - An eoEvalFunc: the evaluation performer * @param _velocity - An eoVelocity that defines how to compute the velocities - * @param _flight - An eoFlight that defines how to make the particle flying: that means how + * @param _flight - An eoFlight that defines how to make the particle flying: that means how * to modify the positions according to the velocities */ eoEasyPSO ( @@ -125,7 +125,7 @@ public: velocity (_velocity), flight (dummyFlight) {} - + /// Apply a few iteration of flight to the population (=swarm). virtual void operator () (eoPop < POT > &_pop) { @@ -171,22 +171,22 @@ protected: eoVelocity < POT > &velocity; eoFlight < POT > &flight; - // if the flight does not need to be used, use the dummy flight instance - class eoDummyFlight:public eoFlight < POT > - { - public: - eoDummyFlight () {} - void operator () (POT & _po) {} - }dummyFlight; - - // if the initializer does not need to be used, use the dummy one instead - class eoDummyInitializer:public eoInitializerBase < POT > - { - public: - eoDummyInitializer () {} - void operator () (POT & _po) {} - }dummyInit; - + // if the flight does not need to be used, use the dummy flight instance + class eoDummyFlight:public eoFlight < POT > + { + public: + eoDummyFlight () {} + void operator () (POT & _po) {} + }dummyFlight; + + // if the initializer does not need to be used, use the dummy one instead + class eoDummyInitializer:public eoInitializerBase < POT > + { + public: + eoDummyInitializer () {} + void operator () (POT & _po) {} + }dummyInit; + }; /** * @example t-eoEasyPSO.cpp diff --git a/eo/src/eoEvalContinue.h b/eo/src/eoEvalContinue.h index 05ac2f0a..ef74e075 100644 --- a/eo/src/eoEvalContinue.h +++ b/eo/src/eoEvalContinue.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoEvalContinue.h // (c) GeNeura Team, 1999, Marc Schoenauer 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -29,7 +29,7 @@ #include #include -/** +/** * Continues until a number of evaluations has been made * * @ingroup Continuators @@ -38,28 +38,28 @@ template< class EOT> class eoEvalContinue: public eoContinue { public: - /// Ctor + /// Ctor eoEvalContinue( eoEvalFuncCounter & _eval, unsigned long _totalEval) - : eval(_eval), repTotalEvaluations( _totalEval ) {}; - + : eval(_eval), repTotalEvaluations( _totalEval ) {}; + /** Returns false when a certain number of evaluations has been done */ virtual bool operator() ( const eoPop& _vEO ) { (void)_vEO; - if (eval.value() >= repTotalEvaluations) + if (eval.value() >= repTotalEvaluations) { eo::log << eo::progress << "STOP in eoEvalContinue: Reached maximum number of evaluations [" << repTotalEvaluations << "]" << std::endl; - return false; + return false; } return true; } - + /** Returns the number of generations to reach*/ - virtual unsigned long totalEvaluations( ) - { - return repTotalEvaluations; + virtual unsigned long totalEvaluations( ) + { + return repTotalEvaluations; }; - + virtual std::string className(void) const { return "eoEvalContinue"; } private: eoEvalFuncCounter & eval; diff --git a/eo/src/eoEvalCounterThrowException.h b/eo/src/eoEvalCounterThrowException.h index 133d3afb..4eb4fccc 100644 --- a/eo/src/eoEvalCounterThrowException.h +++ b/eo/src/eoEvalCounterThrowException.h @@ -1,4 +1,4 @@ -/* +/* (c) Thales group, 2010 This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ Contact: http://eodev.sourceforge.net -Authors: +Authors: Johann Dréo Caner Candan @@ -49,7 +49,7 @@ class eoEvalCounterThrowException : public eoEvalFuncCounter< EOT > { public : eoEvalCounterThrowException( eoEvalFunc& 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; @@ -60,8 +60,8 @@ public : // bypass already evaluated individuals if (eo.invalid()) { - // increment the value of the self parameter - // (eoEvalFuncCounter inherits from @see eoValueParam) + // increment the value of the self parameter + // (eoEvalFuncCounter inherits from @see eoValueParam) value()++; // if we have reached the maximum @@ -84,4 +84,3 @@ private : }; #endif // __eoEvalCounterThrowException_h__ - diff --git a/eo/src/eoEvalFunc.h b/eo/src/eoEvalFunc.h index 275c5185..b05b667b 100644 --- a/eo/src/eoEvalFunc.h +++ b/eo/src/eoEvalFunc.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoEvalFunc.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -37,8 +37,8 @@ The requirements on the types with which this class is to be instantiated with are null, or else, they depend on the particular - class it's going to be applied to; EO does not impose any requirement - on it. If you subclass this abstract class, and use it to evaluate an + class it's going to be applied to; EO does not impose any requirement + on it. If you subclass this abstract class, and use it to evaluate an EO, the requirements on this EO will depend on the evaluator. @ingroup Evaluation @@ -49,7 +49,7 @@ template class eoEvalFunc : public eoUF public : typedef EOT EOType; - typedef typename EOT::Fitness EOFitT; + typedef typename EOT::Fitness EOFitT; }; #endif diff --git a/eo/src/eoEvalFuncCounter.h b/eo/src/eoEvalFuncCounter.h index 55973d06..a63821d6 100644 --- a/eo/src/eoEvalFuncCounter.h +++ b/eo/src/eoEvalFuncCounter.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoEvalFuncCounter.h // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -30,7 +30,7 @@ #include #include -/** +/** Counts the number of evaluations actually performed. @ingroup Evaluation @@ -38,7 +38,7 @@ Counts the number of evaluations actually performed. template class eoEvalFuncCounter : public eoEvalFunc, public eoValueParam { public : - eoEvalFuncCounter(eoEvalFunc& _func, std::string _name = "Eval. ") + eoEvalFuncCounter(eoEvalFunc& _func, std::string _name = "Eval. ") : eoValueParam(0, _name), func(_func) {} virtual void operator()(EOT& _eo) diff --git a/eo/src/eoEvalFuncCounterBounder.h b/eo/src/eoEvalFuncCounterBounder.h index 68c9770c..1c8a29b1 100644 --- a/eo/src/eoEvalFuncCounterBounder.h +++ b/eo/src/eoEvalFuncCounterBounder.h @@ -8,7 +8,7 @@ * @{ */ -/** The exception raised by eoEvalFuncCounterBounder +/** The exception raised by eoEvalFuncCounterBounder * when the maximum number of allowed evaluations is reached. */ class eoEvalFuncCounterBounderException : public std::exception @@ -18,9 +18,9 @@ public: const char* what() const throw() { - std::ostringstream ss; - ss << "STOP in eoEvalFuncCounterBounderException: the maximum number of evaluation has been reached (" << _threshold << ")."; - return ss.str().c_str(); + std::ostringstream ss; + ss << "STOP in eoEvalFuncCounterBounderException: the maximum number of evaluation has been reached (" << _threshold << ")."; + return ss.str().c_str(); } private: @@ -31,7 +31,7 @@ private: * when the maximum number of allowed evaluations is reached. * * This eval counter permits to stop a search during a generation, without waiting for a continue to be - * checked at the end of the loop. Useful if you have 10 individuals and 10 generations, + * checked at the end of the loop. Useful if you have 10 individuals and 10 generations, * but want to stop after 95 evaluations. */ template < typename EOT > @@ -39,21 +39,21 @@ class eoEvalFuncCounterBounder : public eoEvalFuncCounter< EOT > { public : eoEvalFuncCounterBounder(eoEvalFunc& func, unsigned long threshold, std::string name = "Eval. ") - : eoEvalFuncCounter< EOT >( func, name ), _threshold( threshold ) + : eoEvalFuncCounter< EOT >( func, name ), _threshold( threshold ) {} using eoEvalFuncCounter< EOT >::value; virtual void operator()(EOT& eo) { - if (eo.invalid()) + if (eo.invalid()) { value()++; - if (_threshold > 0 && value() >= _threshold) - { - throw eoEvalFuncCounterBounderException(_threshold); - } + if (_threshold > 0 && value() >= _threshold) + { + throw eoEvalFuncCounterBounderException(_threshold); + } func(eo); } diff --git a/eo/src/eoEvalFuncPtr.h b/eo/src/eoEvalFuncPtr.h index d493b9b0..f4952c21 100644 --- a/eo/src/eoEvalFuncPtr.h +++ b/eo/src/eoEvalFuncPtr.h @@ -6,7 +6,7 @@ evaluation object (c) GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -52,17 +52,16 @@ struct eoEvalFuncPtr: public eoEvalFunc { */ eoEvalFuncPtr( FitT (* _eval)( FunctionArg ) ) : eoEvalFunc(), evalFunc( _eval ) {}; - - /// Effectively applies the evaluation function to an EO - virtual void operator() ( EOT & _eo ) + + /// Effectively applies the evaluation function to an EO + virtual void operator() ( EOT & _eo ) { if (_eo.invalid()) _eo.fitness((*evalFunc)( _eo )); }; - + private: FitT (* evalFunc )( FunctionArg ); }; #endif - diff --git a/eo/src/eoEvalTimeThrowException.h b/eo/src/eoEvalTimeThrowException.h index 752fafba..be0e149a 100644 --- a/eo/src/eoEvalTimeThrowException.h +++ b/eo/src/eoEvalTimeThrowException.h @@ -1,4 +1,4 @@ -/* +/* (c) Thales group, 2010 This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ Contact: http://eodev.sourceforge.net -Authors: +Authors: Johann Dréo */ diff --git a/eo/src/eoEvalUserTimeThrowException.h b/eo/src/eoEvalUserTimeThrowException.h index c237c09b..5d1f4c8a 100644 --- a/eo/src/eoEvalUserTimeThrowException.h +++ b/eo/src/eoEvalUserTimeThrowException.h @@ -1,4 +1,4 @@ -/* +/* (c) Thales group, 2010 This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ Contact: http://eodev.sourceforge.net -Authors: +Authors: Johann Dréo */ diff --git a/eo/src/eoExceptions.h b/eo/src/eoExceptions.h index 9760efc6..3b888436 100644 --- a/eo/src/eoExceptions.h +++ b/eo/src/eoExceptions.h @@ -1,4 +1,4 @@ -/* +/* (c) Thales group, 2010 This library is free software; you can redistribute it and/or @@ -17,7 +17,7 @@ Contact: http://eodev.sourceforge.net -Authors: +Authors: Johann Dréo */ diff --git a/eo/src/eoExtendedVelocity.h b/eo/src/eoExtendedVelocity.h index 5aec4c21..e7667204 100644 --- a/eo/src/eoExtendedVelocity.h +++ b/eo/src/eoExtendedVelocity.h @@ -35,7 +35,7 @@ //----------------------------------------------------------------------------- -/** Extended velocity performer for particle swarm optimization. +/** Extended velocity performer for particle swarm optimization. * * Derivated from abstract eoVelocity, * At step t: v(t+1)= w * v(t) + c1 * r1 * ( xbest(t)-x(t) ) + c2 * r2 * ( lbest(t) - x(t) ) + c3 * r3 * ( gbest(t) - x(t) ) @@ -57,16 +57,16 @@ public: /** Full constructor: Bounds and bound modifier required * @param _topology - The topology * @param _w - The weight factor. - * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType * @param _c2 - Learning factor used for the local best - * @param _c3 - Learning factor used for the global best - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c3 - Learning factor used for the global best + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng */ eoExtendedVelocity (eoTopology < POT > & _topology, - const VelocityType & _w, + const VelocityType & _w, const VelocityType & _c1, const VelocityType & _c2, const VelocityType & _c3, @@ -86,10 +86,10 @@ public: /** Constructor: No bound updater required <-> fixed bounds * @param _topology - The topology * @param _w - The weight factor. - * @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType + * @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType * @param _c3 - Learning factor used for the global best - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -113,8 +113,8 @@ public: /** Constructor: Neither bounds nor bound updater required <-> free velocity * @param _topology - The topology * @param _w - The weight factor. - * @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType + * @param _c1 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The third learning factor used for the local best. Type must be POT::ParticleVelocityType * @param _c3 - Learning factor used for the global best * @param _gen - The eo random generator, default=rng */ @@ -145,25 +145,25 @@ public: { VelocityType r1; VelocityType r2; - VelocityType r3; - + VelocityType r3; + VelocityType newVelocity; // cast the learning factors to VelocityType r1 = (VelocityType) rng.uniform (1) * c1; r2 = (VelocityType) rng.uniform (1) * c2; - r3 = (VelocityType) rng.uniform (1) * c3; - + r3 = (VelocityType) rng.uniform (1) * c3; + // need to resize the bounds even if there are dummy because of "isBounded" call bounds.adjust_size(_po.size()); // assign the new velocities for (unsigned j = 0; j < _po.size (); j++) { - newVelocity= omega * _po.velocities[j] - + r1 * (_po.bestPositions[j] - _po[j]) - + r2 * (topology.best (_indice)[j] - _po[j]) - + r3 * (topology.globalBest()[j] - _po[j]); + newVelocity= omega * _po.velocities[j] + + r1 * (_po.bestPositions[j] - _po[j]) + + r2 * (topology.best (_indice)[j] - _po[j]) + + r3 * (topology.globalBest()[j] - _po[j]); /* check bounds */ if (bounds.isMinBounded(j)) @@ -182,27 +182,27 @@ public: { topology.updateNeighborhood(_po,_indice); } - + //! eoTopology getTopology //! @return topology - eoTopology & getTopology () - { - return topology; - } + eoTopology & getTopology () + { + return topology; + } protected: eoTopology < POT > & topology; - const VelocityType & omega; // social/cognitive coefficient + const VelocityType & omega; // social/cognitive coefficient const VelocityType & c1; - const VelocityType & c2; // social/cognitive coefficient - const VelocityType & c3; // social/cognitive coefficient - - eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. - eoRealBoundModifier & bndsModifier; + const VelocityType & c2; // social/cognitive coefficient + const VelocityType & c3; // social/cognitive coefficient + + eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. + eoRealBoundModifier & bndsModifier; + + eoRng & gen; // the random generator - eoRng & gen; // the random generator - // If the bound modifier doesn't need to be used, use the dummy instance eoDummyRealBoundModifier dummyModifier; }; @@ -211,4 +211,3 @@ protected: * Example of a test program using this class: */ #endif /*eoExtendedVelocity_H */ - diff --git a/eo/src/eoFactory.h b/eo/src/eoFactory.h index 7e02d124..73a8faf1 100644 --- a/eo/src/eoFactory.h +++ b/eo/src/eoFactory.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoFactory.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -43,32 +43,32 @@ have to be modified */ template class eoFactory: public eoObject { - + public: - - /// @name ctors and dtors - //{@ - /// constructor - eoFactory( ) {} - - /// destructor - virtual ~eoFactory() {} - //@} - /** Another factory methods: creates an object from an std::istream, reading from - it whatever is needed to create the object. Usually, the format for the std::istream will be\\ - objectType parameter1 parameter2 ... parametern\\ - */ - virtual EOClass* make(std::istream& _is) = 0; + /// @name ctors and dtors + //{@ + /// constructor + eoFactory( ) {} - ///@name eoObject methods - //@{ - /** Return the class id */ - virtual std::string className() const { return "eoFactory"; } + /// destructor + virtual ~eoFactory() {} + //@} + + /** Another factory methods: creates an object from an std::istream, reading from + it whatever is needed to create the object. Usually, the format for the std::istream will be\\ + objectType parameter1 parameter2 ... parametern\\ + */ + virtual EOClass* make(std::istream& _is) = 0; + + ///@name eoObject methods + //@{ + /** Return the class id */ + virtual std::string className() const { return "eoFactory"; } + + /** Read and print are left without implementation */ + //@} - /** Read and print are left without implementation */ - //@} - }; diff --git a/eo/src/eoFitContinue.h b/eo/src/eoFitContinue.h index 96401451..2db88f80 100644 --- a/eo/src/eoFitContinue.h +++ b/eo/src/eoFitContinue.h @@ -49,15 +49,15 @@ public: /** Returns false when a fitness criterium is reached. Assumes pop is not sorted! */ virtual bool operator() ( const eoPop& _pop ) { - //FitnessType bestCurrentFitness = _pop.nth_element_fitness(0); - FitnessType bestCurrentFitness = _pop.best_element().fitness(); - if (bestCurrentFitness >= optimum) - { - eo::log << eo::logging << "STOP in eoFitContinue: Best fitness has reached " << - bestCurrentFitness << "\n"; - return false; - } - return true; + //FitnessType bestCurrentFitness = _pop.nth_element_fitness(0); + FitnessType bestCurrentFitness = _pop.best_element().fitness(); + if (bestCurrentFitness >= optimum) + { + eo::log << eo::logging << "STOP in eoFitContinue: Best fitness has reached " << + bestCurrentFitness << "\n"; + return false; + } + return true; } virtual std::string className(void) const { return "eoFitContinue"; } diff --git a/eo/src/eoFitnessScalingSelect.h b/eo/src/eoFitnessScalingSelect.h index 7ea61607..c1753201 100644 --- a/eo/src/eoFitnessScalingSelect.h +++ b/eo/src/eoFitnessScalingSelect.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoFitnessScalingSelect.h // (c) GeNeura Team, 1998, Maarten Keijzer 2000, Marc Schoenauer 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -32,25 +32,24 @@ #include #include -/** eoFitnessScalingSelect: select an individual proportional to the +/** eoFitnessScalingSelect: select an individual proportional to the * linearly scaled fitness that is computed by the private * eoLinearFitScaling object * * @ingroup Selectors */ -template -class eoFitnessScalingSelect: public eoRouletteWorthSelect +template +class eoFitnessScalingSelect: public eoRouletteWorthSelect { public: /** Ctor: * @param _p the selective pressure, should be in [1,2] (2 is the default) */ - eoFitnessScalingSelect(double _p = 2.0): + eoFitnessScalingSelect(double _p = 2.0): eoRouletteWorthSelect(scaling), scaling(_p) {} private : - eoLinearFitScaling scaling; // derived from eoPerf2Worth + eoLinearFitScaling scaling; // derived from eoPerf2Worth }; -#endif - +#endif diff --git a/eo/src/eoFixedInertiaWeightedVelocity.h b/eo/src/eoFixedInertiaWeightedVelocity.h index b19d36a9..291c85a0 100644 --- a/eo/src/eoFixedInertiaWeightedVelocity.h +++ b/eo/src/eoFixedInertiaWeightedVelocity.h @@ -54,9 +54,9 @@ public: /** Full constructor: Bounds and bound modifier required * @param _topology - The topology to get the global/local/other best * @param _weight - The weight with type VelocityType - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng @@ -80,9 +80,9 @@ public: /** Constructor: No bound updater required <-> fixed bounds * @param _topology - The topology to get the global/local/other best * @param _weight - The weight with type VelocityType - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -104,8 +104,8 @@ public: /** Constructor: Neither bounds nor bound updater required <-> free velocity * @param _topology - The topology to get the global/local/other best * @param _weight - The weight with type VelocityType - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _gen - The eo random generator, default=rng */ eoFixedInertiaWeightedVelocity (eoTopology < POT > & _topology, @@ -124,7 +124,7 @@ public: /** * Evaluate the new velocities of the given particle. Need an indice to identify the particle - * into the topology. Steps are : + * into the topology. Steps are : * - evaluate r1 and r2, the customed learning factors * - adjust the size of the bounds (even if dummy) * - modify the bounds with the bounds modifier (use the dummy modifier if there's no modifier provided) @@ -175,10 +175,10 @@ public: protected: eoTopology < POT > & topology; - const VelocityType & c1; // learning factor 1 - const VelocityType & c2; // learning factor 2 + const VelocityType & c1; // learning factor 1 + const VelocityType & c2; // learning factor 2 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. eoRealBoundModifier & bndsModifier; @@ -189,4 +189,3 @@ protected: #endif /*EOFIXEDINERTIAWEIGHTEDVELOCITY_H */ - diff --git a/eo/src/eoFlOrBinOp.h b/eo/src/eoFlOrBinOp.h index dd1ff617..bcdc9c5c 100644 --- a/eo/src/eoFlOrBinOp.h +++ b/eo/src/eoFlOrBinOp.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoFlOrBinOp.h // (c) Marc Schoenauer - Maarten Keijzer 2000-2003 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -35,11 +35,11 @@ /** Generic eoBinOps on fixed length genotypes. * Contains exchange crossovers (1pt and uniform) - * and crossovers that applies an Atom crossover + * and crossovers that applies an Atom crossover * to all components with given rate, or * to a fixed prescribed nb of components * - * Example: the standard bitstring 1-point and uniform crossovers + * Example: the standard bitstring 1-point and uniform crossovers * could be implemented as resp. eoFlOr1ptBinOp and eoFlOrUniformBinOp */ @@ -65,14 +65,14 @@ public : { if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool changed = false; for ( unsigned i = 0; i < _eo1.size(); i++ ) { if ( rng.flip( rate ) ) { - bool changedHere = op( _eo1[i], _eo2[i] ); - changed |= changedHere; + bool changedHere = op( _eo1[i], _eo2[i] ); + changed |= changedHere; } } return changed; @@ -108,16 +108,16 @@ public : { if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool changed = false; for ( unsigned i = 0; i < k; i++ ) //! @todo check that we don't do twice the same { - unsigned where = eo::rng.random(_eo1.size()); - bool changedHere = op( _eo1[where], _eo2[where] ); - changed |= changedHere; + unsigned where = eo::rng.random(_eo1.size()); + bool changedHere = op( _eo1[where], _eo2[where] ); + changed |= changedHere; } return changed; } @@ -154,17 +154,17 @@ public : Atom tmp; if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool hasChanged = false; for (unsigned i=0; i<_eo1.size(); i++) { - if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) ) - { - _eo1[i] = _eo2[i]; - hasChanged = true; - } + if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) ) + { + _eo1[i] = _eo2[i]; + hasChanged = true; + } } return hasChanged; } @@ -198,18 +198,18 @@ public : Atom tmp; if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool hasChanged = false; unsigned where = eo::rng.random(_eo1.size()-1); for (unsigned i=where+1; i<_eo1.size(); i++) { - if ( (_eo1[i]!=_eo2[i]) ) - { - _eo1[i] = _eo2[i]; - hasChanged = true; - } + if ( (_eo1[i]!=_eo2[i]) ) + { + _eo1[i] = _eo2[i]; + hasChanged = true; + } } return hasChanged; } diff --git a/eo/src/eoFlOrMonOp.h b/eo/src/eoFlOrMonOp.h index 102acc11..63dae9cb 100644 --- a/eo/src/eoFlOrMonOp.h +++ b/eo/src/eoFlOrMonOp.h @@ -39,7 +39,7 @@ * eoFlOrAllMutation applies the atom mutation to all components with given rate * eoFlOrKMutation applies the atom mutation to a fixed nb of components * - * Remark: the standard bit-flip mutation is an eoFlOrAllMutation + * Remark: the standard bit-flip mutation is an eoFlOrAllMutation * with atom mutation == bitflipping */ @@ -62,21 +62,21 @@ public : bool modified=false; for (unsigned i=0; i<_eo.size(); i++) if (eo::rng.flip(rate)) - if (atomMutation(_eo[i])) - modified = true; + if (atomMutation(_eo[i])) + modified = true; return modified; } /** inherited className() */ - virtual std::string className() const - { + virtual std::string className() const + { return "eoFlOrAllMutation(" + atomMutation.className() + ")"; } private: eoMonOp & 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 @@ -100,21 +100,21 @@ public : bool modified=false; for (unsigned k=0; k & atomMutation; // the atom mutation }; diff --git a/eo/src/eoFlOrQuadOp.h b/eo/src/eoFlOrQuadOp.h index f9c0373c..91618aa5 100644 --- a/eo/src/eoFlOrQuadOp.h +++ b/eo/src/eoFlOrQuadOp.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoFlOrQuadOp.h // (c) Marc Schoenauer - Maarten Keijzer 2000-2003 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -35,7 +35,7 @@ /** Generic eoQuadOps on fixed length genotypes. * Contains exchange crossovers (1pt and uniform) - * and crossovers that applies an Atom crossover + * and crossovers that applies an Atom crossover * to all components with given rate, or * to a fixed prescribed nb of components */ @@ -63,8 +63,8 @@ public : bool changed = false; for ( unsigned i = 0; i < _eo1.size(); i++ ) { if ( rng.flip( rate ) ) { - bool changedHere = op( _eo1[i], _eo2[i] ); - changed |= changedHere; + bool changedHere = op( _eo1[i], _eo2[i] ); + changed |= changedHere; } } return changed; @@ -100,16 +100,16 @@ public : { if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool changed = false; for ( unsigned i = 0; i < k; i++ ) //! @todo check that we don't do twice the same { - unsigned where = eo::rng.random(_eo1.size()); - bool changedHere = op( _eo1[where], _eo2[where] ); - changed |= changedHere; + unsigned where = eo::rng.random(_eo1.size()); + bool changedHere = op( _eo1[where], _eo2[where] ); + changed |= changedHere; } return changed; } @@ -145,19 +145,19 @@ public : Atom tmp; if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool hasChanged = false; for (unsigned i=0; i<_eo1.size(); i++) { - if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) ) - { - tmp = _eo1[i]; - _eo1[i] = _eo2[i]; - _eo2[i] = tmp; - hasChanged = true; - } + if ( (_eo1[i]!=_eo2[i]) && (eo::rng.filp(rate)) ) + { + tmp = _eo1[i]; + _eo1[i] = _eo2[i]; + _eo2[i] = tmp; + hasChanged = true; + } } return hasChanged; } @@ -190,20 +190,20 @@ public : Atom tmp; if (_eo1.size() != _eo2.size()) { - string s = "Operand size don't match in " + className(); - throw runtime_error(s); + string s = "Operand size don't match in " + className(); + throw runtime_error(s); } bool hasChanged = false; unsigned where = eo::rng.random(_eo1.size()-1); for (unsigned i=where+1; i<_eo1.size(); i++) { - if ( (_eo1[i]!=_eo2[i]) ) - { - tmp = _eo1[i]; - _eo1[i] = _eo2[i]; - _eo2[i] = tmp; - hasChanged = true; - } + if ( (_eo1[i]!=_eo2[i]) ) + { + tmp = _eo1[i]; + _eo1[i] = _eo2[i]; + _eo2[i] = tmp; + hasChanged = true; + } } return hasChanged; } diff --git a/eo/src/eoFunctor.h b/eo/src/eoFunctor.h index e782328a..465f0bc4 100644 --- a/eo/src/eoFunctor.h +++ b/eo/src/eoFunctor.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoFunctor.h // (c) Maarten Keijzer 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -20,7 +20,7 @@ Contact: todos@geneura.ugr.es, http://geneura.ugr.es mak@dhi.dk - CVS Info: $Date: 2004-12-01 09:22:48 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoFunctor.h,v 1.7 2004-12-01 09:22:48 evomarc Exp $ $Author: evomarc $ + CVS Info: $Date: 2004-12-01 09:22:48 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoFunctor.h,v 1.7 2004-12-01 09:22:48 evomarc Exp $ $Author: evomarc $ */ //----------------------------------------------------------------------------- @@ -87,12 +87,12 @@ public : /// tag to identify a procedure in compile time function selection @see functor_category static eoFunctorBase::procedure_tag functor_category() { - return eoFunctorBase::procedure_tag(); + return eoFunctorBase::procedure_tag(); } }; /** - Overloaded function that can help in the compile time detection + Overloaded function that can help in the compile time detection of the type of functor we are dealing with @see eoCounter, make_counter @@ -103,8 +103,8 @@ eoFunctorBase::procedure_tag functor_category(const eoF&) return eoFunctorBase::procedure_tag(); } -/** - Basic Unary Functor. Derive from this class when defining +/** + Basic Unary Functor. Derive from this class when defining any unary function. First template argument is the first_argument_type, second result_type. Argument and result types can be any type including void for @@ -124,12 +124,12 @@ public : /// tag to identify a procedure in compile time function selection @see functor_category static eoFunctorBase::unary_function_tag functor_category() { - return eoFunctorBase::unary_function_tag(); + return eoFunctorBase::unary_function_tag(); } }; /** - Overloaded function that can help in the compile time detection + Overloaded function that can help in the compile time detection of the type of functor we are dealing with @see eoCounter, make_counter */ @@ -140,8 +140,8 @@ eoFunctorBase::unary_function_tag functor_category(const eoUF&) } -/** - Basic Binary Functor. Derive from this class when defining +/** + Basic Binary Functor. Derive from this class when defining any binary function. First template argument is result_type, second is first_argument_type, third is second_argument_type. Argument and result types can be any type including void for @@ -153,7 +153,7 @@ class eoBF : public eoFunctorBase, public std::binary_function public : /// virtual dtor here so there is no need to define it in derived classes virtual ~eoBF() {} - + //typedef R result_type; //typedef A1 first_argument_type; //typedef A2 second_argument_type; @@ -164,12 +164,12 @@ public : /// tag to identify a procedure in compile time function selection @see functor_category static eoFunctorBase::binary_function_tag functor_category() { - return eoFunctorBase::binary_function_tag(); + return eoFunctorBase::binary_function_tag(); } }; /** - Overloaded function that can help in the compile time detection + Overloaded function that can help in the compile time detection of the type of functor we are dealing with @see eoCounter, make_counter */ diff --git a/eo/src/eoG3Replacement.h b/eo/src/eoG3Replacement.h index aab7866f..a235244f 100644 --- a/eo/src/eoG3Replacement.h +++ b/eo/src/eoG3Replacement.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoG3Replacement.h + eoG3Replacement.h (c) Maarten Keijzer, Marc Schoenauer, 2002 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -52,34 +52,34 @@ class eoG3Replacement : public eoReplacement public: eoG3Replacement(eoHowMany _howManyEliminatedParents = eoHowMany(2, false)) : // split truncates the parents and returns eliminated parents - split(_howManyEliminatedParents, true), + split(_howManyEliminatedParents, true), // reduce truncates the offpsring and does not return eliminated guys - reduce(-_howManyEliminatedParents, false) + reduce(-_howManyEliminatedParents, false) {} - + void operator()(eoPop & _parents, eoPop & _offspring) { eoPop temp; split(_parents, temp); unsigned toKeep = temp.size(); // how many to keep from merged populations // merge temp into offspring - plus(temp, _offspring); // add temp to _offspring (a little inconsistent!) - + plus(temp, _offspring); // add temp to _offspring (a little inconsistent!) + // reduce merged - reduce(_offspring, temp); // temp dummy arg. will not be modified + reduce(_offspring, temp); // temp dummy arg. will not be modified // minimla check: if (_offspring.size() != toKeep) - { - std::cerr << "Les tailles " << _offspring.size() << " " << toKeep << std::endl; - throw std::runtime_error("eoG3Replacement: wrong number of remaining offspring"); - } + { + std::cerr << "Les tailles " << _offspring.size() << " " << toKeep << std::endl; + throw std::runtime_error("eoG3Replacement: wrong number of remaining offspring"); + } // and put back into _parents - plus(_offspring, _parents); + plus(_offspring, _parents); } private: - eoLinearTruncateSplit split; // few parents to truncate -> linear - eoTruncateSplit reduce; // supposedly many offspring to truncate + eoLinearTruncateSplit split; // few parents to truncate -> linear + eoTruncateSplit reduce; // supposedly many offspring to truncate eoPlus plus; }; diff --git a/eo/src/eoGaussRealWeightUp.h b/eo/src/eoGaussRealWeightUp.h index 0da27b34..47edc321 100644 --- a/eo/src/eoGaussRealWeightUp.h +++ b/eo/src/eoGaussRealWeightUp.h @@ -32,7 +32,7 @@ /** - * Update an inertia weight by assigning it a Gaussian randomized value + * Update an inertia weight by assigning it a Gaussian randomized value * (used for the velocity in particle swarm optimization). * * @ingroup Variators diff --git a/eo/src/eoGenContinue.h b/eo/src/eoGenContinue.h index fac89d5d..0d01bb0a 100644 --- a/eo/src/eoGenContinue.h +++ b/eo/src/eoGenContinue.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoGenContinue.h // (c) GeNeura Team, 1999 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -29,7 +29,7 @@ #include #include -/** +/** Generational continuator: continues until a number of generations is reached @ingroup Continuators @@ -41,68 +41,68 @@ public: /// Ctor for setting a eoGenContinue( unsigned long _totalGens) - : eoValueParam(0, "Generations", "Generations"), - repTotalGenerations( _totalGens ), - thisGenerationPlaceHolder(0), - thisGeneration(thisGenerationPlaceHolder) + : eoValueParam(0, "Generations", "Generations"), + repTotalGenerations( _totalGens ), + thisGenerationPlaceHolder(0), + thisGeneration(thisGenerationPlaceHolder) {}; - + /// Ctor for enabling the save/load the no. of generations counted eoGenContinue( unsigned long _totalGens, unsigned long& _currentGen) - : eoValueParam(0, "Generations", "Generations"), - repTotalGenerations( _totalGens ), - thisGenerationPlaceHolder(0), - thisGeneration(_currentGen) + : eoValueParam(0, "Generations", "Generations"), + repTotalGenerations( _totalGens ), + thisGenerationPlaceHolder(0), + thisGeneration(_currentGen) {}; - + /** Returns false when a certain number of generations is - * reached */ + * reached */ virtual bool operator() ( const eoPop& _vEO ) { (void)_vEO; thisGeneration++; value() = thisGeneration; - - if (thisGeneration >= repTotalGenerations) + + if (thisGeneration >= repTotalGenerations) { - eo::log << eo::logging << "STOP in eoGenContinue: Reached maximum number of generations [" << thisGeneration << "/" << repTotalGenerations << "]\n"; - return false; + eo::log << eo::logging << "STOP in eoGenContinue: Reached maximum number of generations [" << thisGeneration << "/" << repTotalGenerations << "]\n"; + return false; } return true; } - - /** Sets the number of generations to reach - and sets the current generation to 0 (the begin) - - @todo replace this by an "init" method + + /** Sets the number of generations to reach + and sets the current generation to 0 (the begin) + + @todo replace this by an "init" method */ - virtual void totalGenerations( unsigned long _tg ) { - repTotalGenerations = _tg; - thisGeneration = 0; - }; - + virtual void totalGenerations( unsigned long _tg ) { + repTotalGenerations = _tg; + thisGeneration = 0; + }; + /** Returns the number of generations to reach*/ - virtual unsigned long totalGenerations( ) - { - return repTotalGenerations; + virtual unsigned long totalGenerations( ) + { + return repTotalGenerations; }; - - + + virtual std::string className(void) const { return "eoGenContinue"; } /** Read from a stream * @param __is the istream to read from */ void readFrom (std :: istream & __is) { - + __is >> thisGeneration; /* Loading the number of generations counted */ } - + /** Print on a stream * @param __os the ostream to print on */ void printOn (std :: ostream & __os) const { - - __os << thisGeneration << std :: endl; /* Saving the number of generations counted */ + + __os << thisGeneration << std :: endl; /* Saving the number of generations counted */ } private: @@ -112,4 +112,3 @@ private: }; #endif - diff --git a/eo/src/eoGenOp.h b/eo/src/eoGenOp.h index c304ec64..f0d70c7b 100644 --- a/eo/src/eoGenOp.h +++ b/eo/src/eoGenOp.h @@ -53,7 +53,7 @@ the original population, is an instantiation of the next population and has often a selection function embedded in it to select new individuals. Note that the actual work is performed in the apply function. -AND that the apply function is responsible for invalidating +AND that the apply function is responsible for invalidating the object if necessary */ template @@ -72,8 +72,8 @@ class eoGenOp : public eoOp, public eoUF &, void> void operator()(eoPopulator& _pop) { - _pop.reserve( max_production() ); - apply(_pop); + _pop.reserve( max_production() ); + apply(_pop); } //protected : @@ -114,10 +114,10 @@ class eoBinGenOp : public eoGenOp public: eoBinGenOp(eoBinOp& _op) : op(_op) {} - unsigned max_production(void) { return 1; } + unsigned max_production(void) { return 1; } /** do the work: get 2 individuals from the population, modifies - only one (it's a eoBinOp) + only one (it's a eoBinOp) */ void apply(eoPopulator& _pop) { @@ -169,9 +169,9 @@ class eoQuadGenOp : public eoGenOp void apply(eoPopulator& _pop) { EOT& a = *_pop; - EOT& b = *++_pop; - - + EOT& b = *++_pop; + + if(op(a, b)) { a.invalidate(); diff --git a/eo/src/eoGeneralBreeder.h b/eo/src/eoGeneralBreeder.h index 34d9220d..dc598ba7 100644 --- a/eo/src/eoGeneralBreeder.h +++ b/eo/src/eoGeneralBreeder.h @@ -1,9 +1,9 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- -// eoGeneralBreeder.h +// eoGeneralBreeder.h // (c) Maarten Keijzer and Marc Schoenauer, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -58,7 +58,7 @@ class eoGeneralBreeder: public eoBreed eoGeneralBreeder( eoSelectOne& _select, eoGenOp& _op, - double _rate=1.0, + double _rate=1.0, bool _interpret_as_rate = true) : select( _select ), op(_op), howMany(_rate, _interpret_as_rate) {} @@ -71,7 +71,7 @@ class eoGeneralBreeder: public eoBreed eoGeneralBreeder( eoSelectOne& _select, eoGenOp& _op, - eoHowMany _howMany ) : + eoHowMany _howMany ) : select( _select ), op(_op), howMany(_howMany) {} /** The breeder: simply calls the genOp on a selective populator! @@ -87,10 +87,10 @@ class eoGeneralBreeder: public eoBreed eoSelectivePopulator it(_parents, _offspring, select); while (_offspring.size() < target) - { - op(it); - ++it; - } + { + op(it); + ++it; + } _offspring.resize(target); // you might have generated a few more } @@ -105,4 +105,3 @@ class eoGeneralBreeder: public eoBreed }; #endif - diff --git a/eo/src/eoInit.h b/eo/src/eoInit.h index c751b4a2..7b460d94 100644 --- a/eo/src/eoInit.h +++ b/eo/src/eoInit.h @@ -43,24 +43,24 @@ */ /** @{*/ /** - Base (name) class for Initialization of chromosomes, used in a population - contructor. It is derived from eoMonOp, so it can be used + Base (name) class for Initialization of chromosomes, used in a population + contructor. It is derived from eoMonOp, so it can be used inside the algorithm as well. - @see eoPop + @see eoPop */ template class eoInit : public eoUF { public: - /** className: Mandatory because of eoCombinedInit. + /** className: Mandatory because of eoCombinedInit. SHould be pure virtual, but then we should go over the whole * code to write the method for all derived classes ... MS 16/7/04 */ virtual std::string className(void) const { return "eoInit"; } }; -/** turning an eoInit into a generator +/** turning an eoInit into a generator * probably we should only use genrators - and suppress eoInit ??? * MS - July 2001 */ @@ -115,13 +115,13 @@ template class eoInitVariableLength: public eoInit { public: -typedef typename EOT::AtomType AtomType; +typedef typename EOT::AtomType AtomType; // /** Ctor from a generator */ // eoInitVariableLength(unsigned _minSize, unsigned _maxSize, eoF & _generator = Gen()) -// : offset(_minSize), extent(_maxSize - _minSize), -// repGenerator( eoInitGenerator(*(new eoInit)) ), -// generator(_generator) +// : offset(_minSize), extent(_maxSize - _minSize), +// repGenerator( eoInitGenerator(*(new eoInit)) ), +// generator(_generator) // { // if (_minSize >= _maxSize) // throw std::logic_error("eoInitVariableLength: minSize larger or equal to maxSize"); @@ -170,11 +170,11 @@ class eoInitPermutation: public eoInit virtual void operator()(EOT& chrom) { - chrom.resize(chromSize); + chrom.resize(chromSize); for(unsigned idx=0;idx eoInitAdaptor changes the place in the hierarchy from eoInit to eoMonOp. This is mainly a type conversion, nothing else - + @see eoInit, eoMonOp */ template diff --git a/eo/src/eoInitializer.h b/eo/src/eoInitializer.h index 26cb61de..506fcf73 100644 --- a/eo/src/eoInitializer.h +++ b/eo/src/eoInitializer.h @@ -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 eoInitializer : public eoInitializerBase { @@ -115,9 +115,9 @@ public: private : /* - @param proc First evaluation - @param initVelo Initialization of the velocity - @param initBest Initialization of the best + @param proc First evaluation + @param initVelo Initialization of the velocity + @param initBest Initialization of the best */ eoUF& proc; eoVelocityInit < POT > & initVelo; @@ -145,4 +145,3 @@ class eoDummy : public eoUF #endif /** @} */ - diff --git a/eo/src/eoInt.h b/eo/src/eoInt.h index bc16728d..41c87724 100644 --- a/eo/src/eoInt.h +++ b/eo/src/eoInt.h @@ -17,7 +17,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: thomas.legrand@lifl.fr - todos@geneura.ugr.es, http://geneura.ugr.es + todos@geneura.ugr.es, http://geneura.ugr.es mkeijzer@dhi.dk */ diff --git a/eo/src/eoIntegerVelocity.h b/eo/src/eoIntegerVelocity.h index 190db1b0..b00b17bf 100644 --- a/eo/src/eoIntegerVelocity.h +++ b/eo/src/eoIntegerVelocity.h @@ -55,16 +55,16 @@ public: /** Full constructor: Bounds and bound modifier required * @param _topology - The topology to get the global/local/other best - * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng */ eoIntegerVelocity (eoTopology < POT > & _topology, - const VelocityType & _c1, + const VelocityType & _c1, const VelocityType & _c2, const VelocityType & _c3, eoRealVectorBounds & _bounds, @@ -81,10 +81,10 @@ public: /** Constructor: No bound updater required <-> fixed bounds * @param _topology - The topology to get the global/local/other best - * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -105,9 +105,9 @@ public: /** Constructor: Neither bounds nor bound updater required <-> free velocity * @param _topology the topology to use - * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _c1 - The first learning factor quantify how much the particle trusts itself. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c3 - The third learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _gen - The eo random generator, default=rng */ eoIntegerVelocity (eoTopology < POT > & _topology, @@ -116,7 +116,7 @@ public: const VelocityType & _c3, eoRng & _gen = rng): topology(_topology), - c1 (_c1), + c1 (_c1), c2 (_c2), c3 (_c3), bounds(*(new eoRealVectorNoBounds(0))), @@ -167,30 +167,29 @@ public: { topology.updateNeighborhood(_po,_indice); } - + //! eoTopology getTopology //! @return topology - eoTopology & getTopology () - { - return topology; - } + eoTopology & getTopology () + { + return topology; + } protected: eoTopology < POT > & topology; - const VelocityType & c1; // social/cognitive coefficient - const VelocityType & c2; // social/cognitive coefficient - const VelocityType & c3; // social/cognitive coefficient - - eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. - eoRealBoundModifier & bndsModifier; + const VelocityType & c1; // social/cognitive coefficient + const VelocityType & c2; // social/cognitive coefficient + const VelocityType & c3; // social/cognitive coefficient + + eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. + eoRealBoundModifier & bndsModifier; + + eoRng & gen; // the random generator - eoRng & gen; // the random generator - // If the bound modifier doesn't need to be used, use the dummy instance eoDummyRealBoundModifier dummyModifier; }; #endif /*EOINTEGERVELOCITY_H */ - diff --git a/eo/src/eoInvalidateOps.h b/eo/src/eoInvalidateOps.h index ecc470ab..97dd39f5 100644 --- a/eo/src/eoInvalidateOps.h +++ b/eo/src/eoInvalidateOps.h @@ -57,7 +57,7 @@ class eoInvalidateMonOp : public eoMonOp return true; } - return false; + return false; } private: diff --git a/eo/src/eoLinearTopology.h b/eo/src/eoLinearTopology.h index b7c72416..813e99b9 100644 --- a/eo/src/eoLinearTopology.h +++ b/eo/src/eoLinearTopology.h @@ -48,7 +48,7 @@ public: /** * Build the topology made of _neighborhoodSize neighborhoods. - * @param _neighborhoodSize - The size of each neighborhood. + * @param _neighborhoodSize - The size of each neighborhood. */ eoLinearTopology (unsigned _neighborhoodSize):neighborhoodSize (_neighborhoodSize),isSetup(false){} @@ -119,7 +119,7 @@ public: */ unsigned retrieveNeighborhoodByIndice(unsigned _indice) { - unsigned i=0; + unsigned i=0; for (i=0;i< neighborhoods.size();i++) { if (neighborhoods[i].contains(_indice)) @@ -131,7 +131,7 @@ public: } /** - * Update the neighborhood: update the particle's best fitness and the best particle + * Update the neighborhood: update the particle's best fitness and the best particle * of the corresponding neighborhood. */ void updateNeighborhood(POT & _po,unsigned _indice) @@ -139,9 +139,9 @@ public: // update the best fitness of the particle if (_po.fitness() > _po.best()) { - _po.best(_po.fitness()); - for(unsigned i=0;i<_po.size();i++) - _po.bestPositions[i]=_po[i]; + _po.best(_po.fitness()); + for(unsigned i=0;i<_po.size();i++) + _po.bestPositions[i]=_po[i]; } // update the best in its neighborhood @@ -166,27 +166,27 @@ public: /* - * Return the global best of the topology - */ - virtual POT & globalBest() + * Return the global best of the topology + */ + virtual POT & globalBest() { - POT gBest,tmp; - unsigned indGlobalBest=0; - if(neighborhoods.size()==1) - return neighborhoods[0].best(); - - gBest=neighborhoods[0].best(); - for(unsigned i=1;i > neighborhoods; + std::vector > neighborhoods; unsigned neighborhoodSize; // the size of each neighborhood - + bool isSetup; }; #endif /*EOLINEARTOPOLOGY_H_ */ - - - - - - - - diff --git a/eo/src/eoMGGReplacement.h b/eo/src/eoMGGReplacement.h index a625e1e8..e2eebbfa 100644 --- a/eo/src/eoMGGReplacement.h +++ b/eo/src/eoMGGReplacement.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoMGGReplacement.h + eoMGGReplacement.h (c) Maarten Keijzer, Marc Schoenauer, 2002 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -52,18 +52,18 @@ class eoMGGReplacement : public eoReplacement { public: eoMGGReplacement(eoHowMany _howManyEliminatedParents = eoHowMany(2, false), - unsigned _tSize=2) : + unsigned _tSize=2) : // split truncates the parents and returns eliminated parents - split(_howManyEliminatedParents, true), + split(_howManyEliminatedParents, true), tSize(_tSize) { if (tSize < 2) - { + { eo::log << eo::warnings << "Warning, Size for eoDetTournamentTruncateSplit adjusted to 2" << std::endl; - tSize = 2; + tSize = 2; } } - + void operator()(eoPop & _parents, eoPop & _offspring) { eoPop temp; @@ -71,7 +71,7 @@ public: unsigned toKeep = temp.size(); // how many to keep from merged populations // minimal check if (toKeep < 2) - throw std::runtime_error("Not enough parents killed in eoMGGReplacement"); + throw std::runtime_error("Not enough parents killed in eoMGGReplacement"); // select best offspring typename eoPop::iterator it = _offspring.it_best_element(); @@ -82,21 +82,21 @@ public: // merge temp into offspring plus(temp, _offspring); - + // repeatedly add selected offspring to parents for (unsigned i=0; i split; // few parents to truncate -> linear + eoLinearTruncateSplit split; // few parents to truncate -> linear eoPlus plus; unsigned int tSize; }; diff --git a/eo/src/eoMerge.h b/eo/src/eoMerge.h index 01ada3f9..31da70f0 100644 --- a/eo/src/eoMerge.h +++ b/eo/src/eoMerge.h @@ -4,7 +4,7 @@ // eoMerge.h // Base class for elitist-merging classes // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -36,13 +36,13 @@ #include /** - * eoMerge: Base class for elitist replacement algorithms. + * eoMerge: Base class for elitist replacement algorithms. * Merges the old population (first argument), with the new generation * * Its signature is exactly - * that of the selection base eoSelect, but its purpose is to merge the + * that of the selection base eoSelect, but its purpose is to merge the * two populations into one (the second argument). - * Note that the algorithms assume that the second argument denotes the + * Note that the algorithms assume that the second argument denotes the * next generation. * * @ingroup Core @@ -55,7 +55,7 @@ template class eoMerge: public eoBF&, eoPop class eoElitism : public eoMerge @@ -66,42 +66,42 @@ public : { if (_interpret_as_rate) { - if ( (_rate<0) || (_rate>1) ) - throw std::logic_error("eoElitism: rate shoud be in [0,1]"); - rate = _rate; + if ( (_rate<0) || (_rate>1) ) + throw std::logic_error("eoElitism: rate shoud be in [0,1]"); + rate = _rate; } else { - if (_rate<0) - throw std::logic_error("Negative number of offspring in eoElitism!"); - combien = (unsigned int)_rate; - if (combien != _rate) - eo::log << eo::warnings << "Warning: Number of guys to merge in eoElitism was rounded" << std::endl; + if (_rate<0) + throw std::logic_error("Negative number of offspring in eoElitism!"); + combien = (unsigned int)_rate; + if (combien != _rate) + eo::log << eo::warnings << "Warning: Number of guys to merge in eoElitism was rounded" << std::endl; } } - + void operator()(const eoPop& _pop, eoPop& _offspring) { if ((combien == 0) && (rate == 0.0)) return; unsigned combienLocal; - if (combien == 0) // rate is specified + if (combien == 0) // rate is specified combienLocal = (unsigned int) (rate * _pop.size()); else combienLocal = combien; - + if (combienLocal > _pop.size()) throw std::logic_error("Elite larger than population"); - + std::vector result; _pop.nth_element(combienLocal, result); - + for (size_t i = 0; i < result.size(); ++i) { - _offspring.push_back(*result[i]); + _offspring.push_back(*result[i]); } } - + private : double rate; unsigned combien; @@ -139,4 +139,4 @@ template class eoPlus : public eoMerge //----------------------------------------------------------------------------- -#endif +#endif diff --git a/eo/src/eoMergeReduce.h b/eo/src/eoMergeReduce.h index 8524f1d8..b3cb5b99 100644 --- a/eo/src/eoMergeReduce.h +++ b/eo/src/eoMergeReduce.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoMergeReduce.h + eoMergeReduce.h (c) Maarten Keijzer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -34,7 +34,7 @@ #include #include //----------------------------------------------------------------------------- -/** +/** Replacement strategies that combine en eoMerge and an eoReduce. @class eoMergeReduce, the base (pure abstract) class @@ -43,7 +43,7 @@ Replacement strategies that combine en eoMerge and an eoReduce. */ /** -eoMergeReduce: abstract replacement strategy that is just an application of +eoMergeReduce: abstract replacement strategy that is just an application of an embedded merge, followed by an embedded reduce @ingroup Replacors */ @@ -59,7 +59,7 @@ class eoMergeReduce : public eoReplacement { merge(_parents, _offspring); // parents untouched, result in offspring reduce(_offspring, _parents.size()); - _parents.swap(_offspring); + _parents.swap(_offspring); } private : @@ -98,7 +98,7 @@ class eoCommaReplacement : public eoMergeReduce }; /** -EP type of replacement strategy: first add parents to population, +EP type of replacement strategy: first add parents to population, then truncate using EP tournament @ingroup Replacors */ diff --git a/eo/src/eoNDSorting.h b/eo/src/eoNDSorting.h index b0710b6e..6ab86c17 100644 --- a/eo/src/eoNDSorting.h +++ b/eo/src/eoNDSorting.h @@ -61,35 +61,35 @@ class eoNDSorting : public eoPerf2WorthCached void calculate_worths(const eoPop& _pop) { - // resize the worths beforehand - value().resize(_pop.size()); + // resize the worths beforehand + value().resize(_pop.size()); - typedef typename EOT::Fitness::fitness_traits traits; + typedef typename EOT::Fitness::fitness_traits traits; - switch (traits::nObjectives()) - { - case 1: - { - one_objective(_pop); - return; - } - case 2: - { - two_objectives(_pop); - return; - } - default : - { - m_objectives(_pop); - } - } + switch (traits::nObjectives()) + { + case 1: + { + one_objective(_pop); + return; + } + case 2: + { + two_objectives(_pop); + return; + } + default : + { + m_objectives(_pop); + } + } } private : /** used in fast nondominated sorting - DummyEO is just a storage place for fitnesses and - to store the original index + DummyEO is just a storage place for fitnesses and + to store the original index */ class DummyEO : public EO { @@ -98,8 +98,8 @@ private : void one_objective(const eoPop& _pop) { - unsigned i; - std::vector tmp_pop; + unsigned i; + std::vector tmp_pop; tmp_pop.resize(_pop.size()); // copy pop to dummy population (only need the fitnesses) @@ -109,14 +109,14 @@ private : tmp_pop[i].index = i; } - std::sort(tmp_pop.begin(), tmp_pop.end(), std::greater()); + std::sort(tmp_pop.begin(), tmp_pop.end(), std::greater()); for (i = 0; i < _pop.size(); ++i) { value()[tmp_pop[i].index] = _pop.size() - i; // set rank } - // no point in calculcating niche penalty, as every distinct fitness value has a distinct rank + // 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& _pop) { - unsigned i; - typedef typename EOT::Fitness::fitness_traits traits; - assert(traits::nObjectives() == 2); + unsigned i; + typedef typename EOT::Fitness::fitness_traits traits; + assert(traits::nObjectives() == 2); - std::vector sort1(_pop.size()); // index into population sorted on first objective + std::vector sort1(_pop.size()); // index into population sorted on first objective - for (i = 0; i < _pop.size(); ++i) - { - sort1[i] = i; - } + for (i = 0; i < _pop.size(); ++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; - for (i = 0; i < _pop.size(); ++i) - { - max1 = std::max(max1, _pop[i].fitness()[1]); - } + double max1 = -1e+20; + for (i = 0; i < _pop.size(); ++i) + { + max1 = std::max(max1, _pop[i].fitness()[1]); + } - max1 = max1 + 1.0; // add a bit to it so that it is a real upperbound + max1 = max1 + 1.0; // add a bit to it so that it is a real upperbound - unsigned prev_front = 0; - std::vector d; - d.resize(_pop.size(), max1); // initialize with the value max1 everywhere + unsigned prev_front = 0; + std::vector d; + d.resize(_pop.size(), max1); // initialize with the value max1 everywhere - std::vector > fronts(_pop.size()); // to store indices into the front + std::vector > fronts(_pop.size()); // to store indices into the front - for (i = 0; i < _pop.size(); ++i) - { - unsigned index = sort1[i]; + for (i = 0; i < _pop.size(); ++i) + { + unsigned index = sort1[i]; - // check for clones and delete them - if (i > 0) - { - unsigned prev = sort1[i-1]; - if ( _pop[index].fitness() == _pop[prev].fitness()) - { // it's a clone, give it the worst rank! + // check for clones and delete them + if (i > 0) + { + unsigned prev = sort1[i-1]; + if ( _pop[index].fitness() == _pop[prev].fitness()) + { // it's a clone, give it the worst rank! - if (nasty_declone_flag_that_only_is_implemented_for_two_objectives) - //declone - fronts.back().push_back(index); - else // assign it the rank of the previous - fronts[prev_front].push_back(index); - continue; - } - } + if (nasty_declone_flag_that_only_is_implemented_for_two_objectives) + //declone + fronts.back().push_back(index); + else // assign it the rank of the previous + fronts[prev_front].push_back(index); + continue; + } + } - double value2 = _pop[index].fitness()[1]; + double value2 = _pop[index].fitness()[1]; - if (traits::maximizing(1)) - value2 = max1 - value2; + if (traits::maximizing(1)) + value2 = max1 - value2; - // perform binary search using std::upper_bound, a log n operation for each member - std::vector::iterator it = - std::upper_bound(d.begin(), d.begin() + last_front, value2); + // perform binary search using std::upper_bound, a log n operation for each member + std::vector::iterator it = + std::upper_bound(d.begin(), d.begin() + last_front, value2); - unsigned front = unsigned(it - d.begin()); - if (front == last_front) ++last_front; + unsigned front = unsigned(it - d.begin()); + if (front == last_front) ++last_front; - assert(it != d.end()); + assert(it != d.end()); - *it = value2; //update d - fronts[front].push_back(index); // add it to the front + *it = value2; //update d + 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) - { - if (fronts[i].size() == 0) continue; + for (i = 0; i < fronts.size(); ++i) + { + if (fronts[i].size() == 0) continue; - // Now we have the indices to the current front in current_front, do the niching - std::vector niche_count = niche_penalty(fronts[i], _pop); + // Now we have the indices to the current front in current_front, do the niching + std::vector niche_count = niche_penalty(fronts[i], _pop); - // Check whether the derived class was nice - if (niche_count.size() != fronts[i].size()) - { - throw std::logic_error("eoNDSorting: niche and front should have the same size"); - } + // Check whether the derived class was nice + if (niche_count.size() != fronts[i].size()) + { + throw std::logic_error("eoNDSorting: niche and front should have the same size"); + } - double max_niche = *std::max_element(niche_count.begin(), niche_count.end()); + double max_niche = *std::max_element(niche_count.begin(), niche_count.end()); - for (unsigned j = 0; j < fronts[i].size(); ++j) - { - value()[fronts[i][j]] = i + niche_count[j] / (max_niche + 1.); // divide by max_niche + 1 to ensure that this front does not overlap with the next - } + for (unsigned j = 0; j < fronts[i].size(); ++j) + { + value()[fronts[i][j]] = i + niche_count[j] / (max_niche + 1.); // divide by max_niche + 1 to ensure that this front does not overlap with the next + } - } + } - // invert ranks to obtain a 'bigger is better' score - rank_to_worth(); + // invert ranks to obtain a 'bigger is better' score + rank_to_worth(); } class Sorter { - public: - Sorter(const eoPop& _pop) : pop(_pop) {} + public: + Sorter(const eoPop& _pop) : pop(_pop) {} - bool operator()(unsigned i, unsigned j) const - { - typedef typename EOT::Fitness::fitness_traits traits; + bool operator()(unsigned i, unsigned j) const + { + 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()) - { - diff = pop[i].fitness()[1] - pop[j].fitness()[1]; + if (fabs(diff) < traits::tol()) + { + diff = pop[i].fitness()[1] - pop[j].fitness()[1]; - if (fabs(diff) < traits::tol()) - return false; + if (fabs(diff) < traits::tol()) + return false; - if (traits::maximizing(1)) - return diff > 0.; - return diff < 0.; - } + if (traits::maximizing(1)) + return diff > 0.; + return diff < 0.; + } - if (traits::maximizing(0)) - return diff > 0.; - return diff < 0.; - } + if (traits::maximizing(0)) + return diff > 0.; + return diff < 0.; + } - const eoPop& pop; + const eoPop& pop; }; void m_objectives(const eoPop& _pop) @@ -485,7 +485,7 @@ class eoNDSorting_II : public eoNDSorting for (i = 0; i < nc.size(); ++i) { - niche_count[i] += (max_dist + 1 - nc[i]); + niche_count[i] += (max_dist + 1 - nc[i]); } } diff --git a/eo/src/eoNeighborhood.h b/eo/src/eoNeighborhood.h index fa0edd3f..804dc107 100644 --- a/eo/src/eoNeighborhood.h +++ b/eo/src/eoNeighborhood.h @@ -47,22 +47,11 @@ public: virtual POT & best()=0; virtual void best(POT _particle)=0; - + /// Virtual dtor - virtual ~eoNeighborhood() {}; + virtual ~eoNeighborhood() {}; }; #endif /* EONEIGHBORHOOD_H_ */ - - - - - - - - - - - diff --git a/eo/src/eoObject.h b/eo/src/eoObject.h index 2e59f190..bac2f473 100644 --- a/eo/src/eoObject.h +++ b/eo/src/eoObject.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoObject.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -34,9 +34,9 @@ #include /* -eoObject used to be the base class for the whole hierarchy, but this has -changed. eoObject is used to define a name (#className#) -that is used when loading or saving the state. +eoObject used to be the base class for the whole hierarchy, but this has +changed. eoObject is used to define a name (#className#) +that is used when loading or saving the state. Previously, this object also defined a print and read interface, but it´s been moved to eoPrintable and eoPersistent. @@ -58,19 +58,18 @@ class eoObject public: /// Virtual dtor. They are needed in virtual class hierarchies. virtual ~eoObject() {} - - /** Return the class id. This should be redefined in each class. + + /** Return the class id. This should be redefined in each class. Only "leaf" classes can be non-virtual. - Maarten: removed the default implementation as this proved to - be too error-prone: I found several classes that had a typo in + Maarten: removed the default implementation as this proved to + be too error-prone: I found several classes that had a typo in className (like classname), which would print eoObject instead of - their own. Having it pure will force the implementor to provide a + their own. Having it pure will force the implementor to provide a name. */ - virtual std::string className() const = 0; + virtual std::string className() const = 0; }; #endif - diff --git a/eo/src/eoOneToOneBreeder.h b/eo/src/eoOneToOneBreeder.h index 2e593333..a4c18c0b 100644 --- a/eo/src/eoOneToOneBreeder.h +++ b/eo/src/eoOneToOneBreeder.h @@ -1,9 +1,9 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- -// eoOneToOneBreeder.h +// eoOneToOneBreeder.h // (c) Maarten Keijzer and Marc Schoenauer, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -38,12 +38,12 @@ #include #include -/** eoOneToOneBreeder: transforms a population using +/** eoOneToOneBreeder: transforms a population using * - an operator that MODIFIES only one parent from the populator * (though it can use any number aside) and thus generates ONE offspring) * - a local replacement between the parent and its offspring * - * Typically, Differential Evolution (Storn and Price 94) and Deb et al's + * Typically, Differential Evolution (Storn and Price 94) and Deb et al's * G3 can be built on this * * @ingroup Combination @@ -54,16 +54,16 @@ class eoOneToOneBreeder: public eoBreed public: /** Ctor: * @param _op a general operator (must MODIFY only ONE parent) - * @param _eval an eoEvalFunc to evaluate the offspring + * @param _eval an eoEvalFunc to evaluate the offspring * @param _pReplace probability that the best of parent/offspring wins [1] * @param _howMany eoHowMany offpsring to generate [100%] */ eoOneToOneBreeder( eoGenOp& _op, - eoEvalFunc & _eval, - double _pReplace = 1.0, - eoHowMany _howMany = eoHowMany(1.0) ) : - op(_op), eval(_eval), select( false ), + eoEvalFunc & _eval, + double _pReplace = 1.0, + eoHowMany _howMany = eoHowMany(1.0) ) : + op(_op), eval(_eval), select( false ), pReplace(_pReplace), howMany(_howMany) {} @@ -77,34 +77,34 @@ class eoOneToOneBreeder: public eoBreed void operator()(const eoPop& _parents, eoPop& _offspring) { unsigned target = howMany(_parents.size()); - + _offspring.clear(); eoSelectivePopulator popit(_parents, _offspring, select); - + for (unsigned iParent=0; iParent leOffspring) // old parent better than offspring - if (rng.uniform() < pReplace) // if probability - leOffspring = theParent; // replace - // finally, go to next guy to handle - ++popit; - } + // do the tournament between parent and offspring + eval(leOffspring); // first need to evaluate the offspring + if (theParent > leOffspring) // old parent better than offspring + if (rng.uniform() < pReplace) // if probability + leOffspring = theParent; // replace + // finally, go to next guy to handle + ++popit; + } } /// The class name. @@ -119,4 +119,3 @@ class eoOneToOneBreeder: public eoBreed }; #endif - diff --git a/eo/src/eoOp.h b/eo/src/eoOp.h index bd9fe4e1..b6ad783c 100644 --- a/eo/src/eoOp.h +++ b/eo/src/eoOp.h @@ -2,7 +2,7 @@ //----------------------------------------------------------------------------- // eoOp.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -18,7 +18,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: todos@geneura.ugr.es, http://geneura.ugr.es - CVS Info: $Date: 2004-08-10 17:19:46 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoOp.h,v 1.29 2004-08-10 17:19:46 jmerelo Exp $ $Author: jmerelo $ + CVS Info: $Date: 2004-08-10 17:19:46 $ $Header: /home/nojhan/dev/eodev/eodev_cvs/eo/src/eoOp.h,v 1.29 2004-08-10 17:19:46 jmerelo Exp $ $Author: jmerelo $ */ //----------------------------------------------------------------------------- @@ -171,13 +171,13 @@ public: */ bool operator()(EOT & _eo1, const EOT & _eo2) { - 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, // the result might be biased - hence the flip ... 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 - return quadOp(eoTmp, _eo1); // both are modified - that's all + return quadOp(eoTmp, _eo1); // both are modified - that's all } private: diff --git a/eo/src/eoOpContainer.h b/eo/src/eoOpContainer.h index d295f0ce..e1f43bdf 100644 --- a/eo/src/eoOpContainer.h +++ b/eo/src/eoOpContainer.h @@ -100,7 +100,7 @@ public: void apply(eoPopulator& _pop) { - _pop.reserve( this->max_production() ); + _pop.reserve( this->max_production() ); position_type pos = _pop.tellp(); for (size_t i = 0; i < rates.size(); ++i) { @@ -118,10 +118,10 @@ public: // } // check for out of individuals and do nothing with that... // catch(eoPopulator::OutOfIndividuals&) - // { + // { // std::cout << "Warning: not enough individuals to handle\n"; // return ; - // } + // } } if (!_pop.exhausted()) @@ -156,7 +156,7 @@ public: try { (*ops[i])(_pop); - ++_pop; + ++_pop; } catch( typename eoPopulator::OutOfIndividuals&) {} @@ -166,4 +166,3 @@ public: #endif - diff --git a/eo/src/eoOpSelMason.h b/eo/src/eoOpSelMason.h index 791b2607..577b5b56 100644 --- a/eo/src/eoOpSelMason.h +++ b/eo/src/eoOpSelMason.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoOpSelMason.h // (c) GeNeura Team, 1999 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -36,72 +36,72 @@ to the objects it builds, and then deallocate it when it gets out of scope */ template class eoOpSelMason: public eoFactory > { - + public: - typedef std::vector* > vOpP; - typedef map*, vOpP > MEV; + typedef std::vector* > vOpP; + typedef map*, vOpP > MEV; - /// @name ctors and dtors - //{@ - /// constructor - eoOpSelMason( eoOpFactory& _opFact): operatorFactory( _opFact ) {}; - - /// destructor - virtual ~eoOpSelMason() {}; - //@} + /// @name ctors and dtors + //{@ + /// constructor + eoOpSelMason( eoOpFactory& _opFact): operatorFactory( _opFact ) {}; - /** Factory methods: creates an object from an std::istream, reading from - it whatever is needed to create the object. The format is - opSelClassName\\ - rate 1 operator1\\ - rate 2 operator2\\ - ...\\ - Stores all operators built in a database (#allocMap#), so that somebody - can destroy them later. The Mason is in charge or destroying the operators, - since the built object can´t do it itself. The objects built must be destroyed - from outside, using the "destroy" method - */ - virtual eoOpSelector* make(std::istream& _is) { + /// destructor + virtual ~eoOpSelMason() {}; + //@} - std::string opSelName; - _is >> opSelName; - eoOpSelector* opSelectorP; - // Build the operator selector - if ( opSelName == "eoProportionalOpSel" ) { - opSelectorP = new eoProportionalOpSel(); - } + /** Factory methods: creates an object from an std::istream, reading from + it whatever is needed to create the object. The format is + opSelClassName\\ + rate 1 operator1\\ + rate 2 operator2\\ + ...\\ + Stores all operators built in a database (#allocMap#), so that somebody + can destroy them later. The Mason is in charge or destroying the operators, + since the built object can´t do it itself. The objects built must be destroyed + from outside, using the "destroy" method + */ + virtual eoOpSelector* make(std::istream& _is) { - // Temp std::vector for storing pointers - vOpP tmpPVec; - // read operator rate and name - while ( _is ) { - float rate; - _is >> rate; - if ( _is ) { - eoOp* op = operatorFactory.make( _is ); // This reads the rest of the line - // Add the operators to the selector, don´t pay attention to the IDs - opSelectorP->addOp( *op, rate ); - // Keep it in the store, to destroy later - tmpPVec.push_back( op ); - } // if - } // while + std::string opSelName; + _is >> opSelName; + eoOpSelector* opSelectorP; + // Build the operator selector + if ( opSelName == "eoProportionalOpSel" ) { + opSelectorP = new eoProportionalOpSel(); + } - // Put it in the map - allocMap.insert( MEV::value_type( opSelectorP, tmpPVec ) ); - - return opSelectorP; - }; + // Temp std::vector for storing pointers + vOpP tmpPVec; + // read operator rate and name + while ( _is ) { + float rate; + _is >> rate; + if ( _is ) { + eoOp* op = operatorFactory.make( _is ); // This reads the rest of the line + // Add the operators to the selector, don´t pay attention to the IDs + opSelectorP->addOp( *op, rate ); + // Keep it in the store, to destroy later + tmpPVec.push_back( op ); + } // if + } // while - ///@name eoObject methods - //@{ - /** Return the class id */ - virtual std::string className() const { return "eoOpSelMason"; } + // Put it in the map + allocMap.insert( MEV::value_type( opSelectorP, tmpPVec ) ); + + return opSelectorP; + }; + + ///@name eoObject methods + //@{ + /** Return the class id */ + virtual std::string className() const { return "eoOpSelMason"; } + + //@} - //@} - private: - map*,std::vector* > > allocMap; - eoOpFactory& operatorFactory; + map*,std::vector* > > allocMap; + eoOpFactory& operatorFactory; }; diff --git a/eo/src/eoOrderXover.h b/eo/src/eoOrderXover.h index 0c98990d..daaf52e0 100644 --- a/eo/src/eoOrderXover.h +++ b/eo/src/eoOrderXover.h @@ -10,7 +10,7 @@ #include #include -#include +#include /** * apply orderXover on two chromosomes. @@ -26,65 +26,65 @@ template class eoOrderXover: public eoQuadOp { public: - /// The class name. - virtual std::string className() const { return "eoOrderXover"; } + /// The class name. + virtual std::string className() const { return "eoOrderXover"; } + + /** + * @return true if the chromosome has changed + * @param _chrom1 The first chromosome which will be crossed with chrom2. + * @param _chrom2 The second chromosome which will be crossed with chrom1. + */ + bool operator()(Chrom& _chrom1, Chrom& _chrom2){ + + char direction=eo::rng.flip()? 1 : -1; + unsigned cut2= 1 + eo::rng.random(_chrom1.size()); + unsigned cut1= eo::rng.random(cut2); + Chrom tmp1= _chrom1; + Chrom tmp2= _chrom2; + + cross(tmp1, tmp2, _chrom1, direction, cut1, cut2); + cross(tmp2, tmp1, _chrom2, direction, cut1, cut2); + + _chrom1.invalidate(); + _chrom2.invalidate(); + + return true; + } - /** - * @return true if the chromosome has changed - * @param _chrom1 The first chromosome which will be crossed with chrom2. - * @param _chrom2 The second chromosome which will be crossed with chrom1. - */ - bool operator()(Chrom& _chrom1, Chrom& _chrom2){ - - char direction=eo::rng.flip()? 1 : -1; - unsigned cut2= 1 + eo::rng.random(_chrom1.size()); - unsigned cut1= eo::rng.random(cut2); - Chrom tmp1= _chrom1; - Chrom tmp2= _chrom2; - - cross(tmp1, tmp2, _chrom1, direction, cut1, cut2); - cross(tmp2, tmp1, _chrom2, direction, cut1, cut2); - - _chrom1.invalidate(); - _chrom2.invalidate(); - - return true; - } - private: - - /** - * @param _chrom1 The first parent chromosome. - * @param _chrom2 The second parent chromosome. - * @param _child The result chromosome. - * @param _direction The direction of the OrderXover (left: -1 or right: 1) - * @param _cut1 index of the first cut - * @param _cut2 index of the second cut - */ - void cross(Chrom& _chrom1, Chrom& _chrom2, Chrom& _child, char _direction, unsigned _cut1, unsigned _cut2){ - - unsigned size, id=0, from=0; - size= _chrom1.size(); - std::vector verif(size, false); - - for(unsigned i= _cut1; i<_cut2; i++){ - _child[id++]= _chrom1[i]; - verif[_chrom1[i] % size] = true; - } - - while(_chrom2[from] != _child[_cut2 - 1]) - from++; - - for(unsigned i=0; i verif(size, false); + + for(unsigned i= _cut1; i<_cut2; i++){ + _child[id++]= _chrom1[i]; + verif[_chrom1[i] % size] = true; + } + + while(_chrom2[from] != _child[_cut2 - 1]) + from++; + + for(unsigned i=0; i 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 eoParticleInitializer : public eoInitializerBase { @@ -99,34 +99,34 @@ template class eoParticleInitializer : public eoInitializerBase empty_pop; - - // evaluates using either the "sequential" evaluator ... - apply(proc, pop); - - // ... or the parallel one - procPara(empty_pop, pop); - - // no matter what is the eval operator, initializes the velocities and the particle's best + eoPop empty_pop; + + // evaluates using either the "sequential" evaluator ... + apply(proc, pop); + + // ... or the parallel one + procPara(empty_pop, pop); + + // no matter what is the eval operator, initializes the velocities and the particle's best apply < POT > (initVelo, pop); apply < POT > (initBest, pop); - + // finally setup the topology. We have now all we need to do so. - topology.setup(pop); + topology.setup(pop); } private : /* - @param proc First evaluation - @param initVelo Initialization of the velocity - @param initBest Initialization of the best - + @param proc First evaluation + @param initVelo Initialization of the velocity + @param initBest Initialization of the best + */ eoPop < POT > & pop; eoUF& proc; @@ -146,11 +146,10 @@ template class eoParticleInitializer : public eoInitializerBase class eoPeriodicContinue: public eoContinue { public: - - /** Constructor. The period is given in parameter. */ - eoPeriodicContinue (unsigned __period, unsigned __init_counter = 0) : - period (__period), counter (__init_counter) + + /** Constructor. The period is given in parameter. */ + eoPeriodicContinue (unsigned __period, unsigned __init_counter = 0) : + period (__period), counter (__init_counter) {} /** It returns 'true' only if the current number of generations modulo - the period doen't equal to zero. */ + the period doen't equal to zero. */ bool operator () (const eoPop & pop) { return ((++ counter) % period) != 0 ; } - + private: unsigned period; - + unsigned counter; }; #endif - diff --git a/eo/src/eoPersistent.cpp b/eo/src/eoPersistent.cpp index 63e906ca..c1334ebc 100644 --- a/eo/src/eoPersistent.cpp +++ b/eo/src/eoPersistent.cpp @@ -1,7 +1,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #include diff --git a/eo/src/eoPersistent.h b/eo/src/eoPersistent.h index 7c2f609e..ed3f581e 100644 --- a/eo/src/eoPersistent.h +++ b/eo/src/eoPersistent.h @@ -6,7 +6,7 @@ // eoPersistent.h // (c) GeNeura Team, 1999 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -48,14 +48,14 @@ class eoPersistent: public eoPrintable public: /// Virtual dtor. They are needed in virtual class hierarchies. virtual ~eoPersistent() {} - + /** * Read object. * @param _is A std::istream. * @throw runtime_std::exception If a valid object can't be read. */ virtual void readFrom(std::istream& _is) = 0; - + }; ///Standard input for all objects in the EO hierarchy diff --git a/eo/src/eoPop.h b/eo/src/eoPop.h index 5c63fb40..3ea53f46 100644 --- a/eo/src/eoPop.h +++ b/eo/src/eoPop.h @@ -1,9 +1,9 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- -// eoPop.h +// eoPop.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -36,16 +36,16 @@ #include #include // for shuffle method -/** A std::vector of EO object, to be used in all algorithms +/** A std::vector of EO object, to be used in all algorithms * (selectors, operators, replacements, ...). * * We have no idea if a population can be * some other thing that a std::vector, but if somebody thinks of it, this concrete - * implementation can be moved to "generic" and an abstract Population + * implementation can be moved to "generic" and an abstract Population * interface be provided. * - * The template can be instantiated with anything that accepts a "size" - * and eoInit derived object. in the ctor. + * The template can be instantiated with anything that accepts a "size" + * and eoInit derived object. in the ctor. * EOT must also have a copy ctor, since temporaries are created and then * passed to the eoInit object * @@ -55,62 +55,62 @@ template class eoPop: public std::vector, public eoObject, public eoPersistent { public: - + using std::vector::size; using std::vector::resize; using std::vector::operator[]; using std::vector::begin; using std::vector::end; - + typedef typename EOT::Fitness Fitness; #if defined(__CUDACC__) typedef typename std::vector::iterator iterator; typedef typename std::vector::const_iterator const_iterator; #endif - /** Default ctor. Creates empty pop - */ - eoPop() : std::vector(), eoObject(), eoPersistent() {}; - - /** Ctor for the initialization of chromosomes - - @param _popSize total population size - @param _chromInit Initialization routine, produces EO's, needs to be an eoInit - */ + /** Default ctor. Creates empty pop + */ + eoPop() : std::vector(), eoObject(), eoPersistent() {}; + + /** Ctor for the initialization of chromosomes + + @param _popSize total population size + @param _chromInit Initialization routine, produces EO's, needs to be an eoInit + */ eoPop( unsigned _popSize, eoInit& _chromInit ) - :std::vector() + :std::vector() { 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. - Can be used to initialize it pop is empty - - @param _newPopSize total population size - @param _chromInit Initialization routine, produces EO's, needs to be an eoInit - */ + /** appends random guys at end of pop. + Can be used to initialize it pop is empty + + @param _newPopSize total population size + @param _chromInit Initialization routine, produces EO's, needs to be an eoInit + */ void append( unsigned _newPopSize, eoInit& _chromInit ) { unsigned oldSize = size(); if (_newPopSize < oldSize) - { - throw std::runtime_error("New size smaller than old size in pop.append"); - return; - } + { + throw std::runtime_error("New size smaller than old size in pop.append"); + return; + } if (_newPopSize == oldSize) - return; - resize(_newPopSize); // adjust the size + return; + resize(_newPopSize); // adjust the size for ( unsigned i = oldSize; i < _newPopSize; i++ ) - { - _chromInit(operator[](i)); - } + { + _chromInit(operator[](i)); + } }; - - + + /** Ctor from an std::istream; reads the population from a stream, each element should be in different lines @param _is the stream @@ -118,9 +118,9 @@ public: eoPop( std::istream& _is ) :std::vector() { readFrom( _is ); } - + /** Empty Dtor */ - virtual ~eoPop() {} + virtual ~eoPop() {} /// helper struct for getting a pointer @@ -130,16 +130,16 @@ public: bool operator()(const EOT* a, const EOT* b) const { return b->operator<(*a); } }; - /// helper struct for comparing (EA or PSO) - struct Cmp2 - { - bool operator()(const EOT & a,const EOT & b) const - { - return b.operator<(a); - } - }; - - + /// helper struct for comparing (EA or PSO) + struct Cmp2 + { + bool operator()(const EOT & a,const EOT & b) const + { + return b.operator<(a); + } + }; + + /** sort the population. Use this member to sort in order @@ -185,10 +185,10 @@ public: #if defined(__CUDACC__) eoPop::iterator it_best_element() { - eoPop:: iterator it = std::max_element(begin(), end()); + eoPop:: iterator it = std::max_element(begin(), end()); #else - typename eoPop::iterator it_best_element() { - typename eoPop::iterator it = std::max_element(begin(), end()); + typename eoPop::iterator it_best_element() { + typename eoPop::iterator it = std::max_element(begin(), end()); #endif return it; } @@ -199,7 +199,7 @@ public: #if defined(__CUDACC__) eoPop::const_iterator it = std::max_element(begin(), end()); #else - typename eoPop::const_iterator it = std::max_element(begin(), end()); + typename eoPop::const_iterator it = std::max_element(begin(), end()); #endif return (*it); } @@ -210,7 +210,7 @@ public: #if defined(__CUDACC__) eoPop::const_iterator it = std::min_element(begin(), end()); #else - typename eoPop::const_iterator it = std::min_element(begin(), end()); + typename eoPop::const_iterator it = std::min_element(begin(), end()); #endif return (*it); } @@ -221,9 +221,9 @@ public: { eoPop::iterator it = std::min_element(begin(), end()); #else - typename eoPop::iterator it_worse_element() + typename eoPop::iterator it_worse_element() { - typename eoPop::iterator it = std::min_element(begin(), end()); + typename eoPop::iterator it = std::min_element(begin(), end()); #endif return it; } @@ -232,25 +232,25 @@ public: slightly faster algorithm than sort to find all individuals that are better than the nth individual. INDIVIDUALS ARE MOVED AROUND in the pop. */ -#if defined(__CUDACC__) +#if defined(__CUDACC__) eoPop::iterator nth_element(int nth) { eoPop::iterator it = begin() + nth; #else - typename eoPop::iterator nth_element(int nth) + typename eoPop::iterator nth_element(int nth) { - typename eoPop::iterator it = begin() + nth; + typename eoPop::iterator it = begin() + nth; #endif std::nth_element(begin(), it, end(), std::greater()); return it; } struct GetFitness { Fitness operator()(const EOT& _eo) const { return _eo.fitness(); } }; - + /** returns the fitness of the nth element */ Fitness nth_element_fitness(int which) const { // probably not the fastest way to do this, but what the heck - + std::vector fitness(size()); std::transform(begin(), end(), fitness.begin(), GetFitness()); @@ -259,15 +259,15 @@ public: return *it; } - /** const nth_element function, returns pointers to sorted individuals - * up the the nth + /** const nth_element function, returns pointers to sorted individuals + * up the the nth */ void nth_element(int which, std::vector& result) const { result.resize(size()); std::transform(begin(), end(), result.begin(), Ref()); - + typename std::vector::iterator it = result.begin() + which; std::nth_element(result.begin(), it, result.end(), Cmp()); @@ -278,28 +278,28 @@ public: { std::swap(static_cast& >(*this), static_cast& >(other)); } - + /** * Prints sorted pop but does NOT modify it! * - * @param _os A std::ostream. + * @param _os A std::ostream. */ - virtual void sortedPrintOn(std::ostream& _os) const + virtual void sortedPrintOn(std::ostream& _os) const { std::vector result; sort(result); _os << size() << '\n'; for (unsigned i = 0; i < size(); ++i) { - _os << *result[i] << std::endl; + _os << *result[i] << std::endl; } } /** * Write object. It's called printOn since it prints the object _on_ a stream. - * @param _os A std::ostream. + * @param _os A std::ostream. */ - virtual void printOn(std::ostream& _os) const + virtual void printOn(std::ostream& _os) const { _os << size() << '\n'; std::copy( begin(), end(), std::ostream_iterator( _os, "\n") ); @@ -309,16 +309,16 @@ public: //@{ /** * Read object. The EOT class must have a ctor from a stream; - * @param _is A std::istream. + * @param _is A std::istream. */ - virtual void readFrom(std::istream& _is) + virtual void readFrom(std::istream& _is) { size_t sz; _is >> sz; resize(sz); - for (size_t i = 0; i < sz; ++i) { + for (size_t i = 0; i < sz; ++i) { operator[](i).readFrom( _is ); } } @@ -337,4 +337,3 @@ public: }; #endif - diff --git a/eo/src/eoPopEvalFunc.h b/eo/src/eoPopEvalFunc.h index 2753e957..aba74d9a 100644 --- a/eo/src/eoPopEvalFunc.h +++ b/eo/src/eoPopEvalFunc.h @@ -5,7 +5,7 @@ Abstract class for global evaluation of the population (c) GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -30,32 +30,32 @@ #include #include -/** eoPopEvalFunc: This abstract class is for GLOBAL evaluators +/** eoPopEvalFunc: This abstract class is for GLOBAL evaluators * of a population after variation. * It takes 2 populations (typically the parents and the offspring) * and is suppposed to evaluate them alltogether * - * Basic use: apply an embedded eoEvalFunc to the offspring + * Basic use: apply an embedded eoEvalFunc to the offspring * - * Time-varying fitness: apply the embedded eoEvalFunc to both + * Time-varying fitness: apply the embedded eoEvalFunc to both * offspring and parents * * Advanced uses: Co-evolution or "parisian" approach, or ... * - * Basic parallelization (synchronous standard evolution engine): + * Basic parallelization (synchronous standard evolution engine): * call the slaves and wait for the results * * @ingroup Evaluation */ template -class eoPopEvalFunc : public eoBF & , eoPop &, void> +class eoPopEvalFunc : public eoBF & , eoPop &, void> {}; ///////////////////////////////////////////////////////////// // eoPopLoopEval ///////////////////////////////////////////////////////////// -/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies +/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies * a private eoEvalFunc to all offspring * * @ingroup Evaluation @@ -81,9 +81,9 @@ private: // eoTimeVaryingLoopEval ///////////////////////////////////////////////////////////// -/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies +/** eoPopLoopEval: an instance of eoPopEvalFunc that simply applies * a private eoEvalFunc to all offspring AND ALL PARENTS - * as the fitness is supposed here to vary + * as the fitness is supposed here to vary * * @ingroup Evaluation */ @@ -105,4 +105,3 @@ private: }; #endif - diff --git a/eo/src/eoPopulator.h b/eo/src/eoPopulator.h index eaf8f841..104aafe5 100644 --- a/eo/src/eoPopulator.h +++ b/eo/src/eoPopulator.h @@ -209,4 +209,3 @@ private: }; #endif - diff --git a/eo/src/eoPrintable.cpp b/eo/src/eoPrintable.cpp index a68536a5..ec6e3246 100644 --- a/eo/src/eoPrintable.cpp +++ b/eo/src/eoPrintable.cpp @@ -1,7 +1,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif //----------------------------------------------------------------------------- // eoPrintable.cpp @@ -14,9 +14,8 @@ //----------------------------------------------------------------------------- std::ostream & operator << ( std::ostream& _os, const eoPrintable& _o ) { - _o.printOn(_os); - return _os; + _o.printOn(_os); + return _os; } //----------------------------------------------------------------------------- - diff --git a/eo/src/eoPrintable.h b/eo/src/eoPrintable.h index 9d419047..1f2404a8 100644 --- a/eo/src/eoPrintable.h +++ b/eo/src/eoPrintable.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoPrintable.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -37,7 +37,7 @@ some objects (for instance, a #eoFactory# or a random number generator. /** Base class for objects that can print themselves -(#printOn#). Besides, this file defines the standard output for all the objects; +(#printOn#). Besides, this file defines the standard output for all the objects; if the objects define printOn there's no need to define "operator<<". @ingroup Core @@ -47,7 +47,7 @@ class eoPrintable public: /// Virtual dtor. They are needed in virtual class hierarchies. virtual ~eoPrintable() {} - + /** * Write object. It's called printOn since it prints the object on a stream. * @param _os A std::ostream. @@ -60,4 +60,3 @@ class eoPrintable std::ostream & operator << ( std::ostream& _os, const eoPrintable& _o ); #endif - diff --git a/eo/src/eoPropGAGenOp.h b/eo/src/eoPropGAGenOp.h index 44ccc7a5..5d2fd79c 100644 --- a/eo/src/eoPropGAGenOp.h +++ b/eo/src/eoPropGAGenOp.h @@ -33,36 +33,36 @@ // class eoSGAGenOp /////////////////////////////////////////////////////////////////////////////// -/** - * eoPropGAGenOp (for Simple GA, but Proportional) - * choice between Crossover, mutation or cloining +/** + * eoPropGAGenOp (for Simple GA, but Proportional) + * choice between Crossover, mutation or cloining * with respect to given relatve weights * * @ingroup Combination */ -template +template class eoPropGAGenOp : public eoGenOp { public: - - /** Ctor from + + /** Ctor from * * weight of clone * * crossover (with weight) * * mutation (with weight) */ - eoPropGAGenOp(double _wClone, eoQuadOp& _cross, double _wCross, - eoMonOp& _mut, double _wMut) + eoPropGAGenOp(double _wClone, eoQuadOp& _cross, double _wCross, + eoMonOp& _mut, double _wMut) : wClone(_wClone), cross(_cross), wCross(_wCross), - mut(_mut), - wMut(_wMut) + mut(_mut), + wMut(_wMut) { propOp.add(cross, wCross); // the crossover - with weight wCross propOp.add(mut, wMut); // mutation with weight wMut propOp.add(monClone, wClone); } - + /** do the job: delegate to op */ virtual void apply(eoPopulator& _pop) { diff --git a/eo/src/eoProportionalCombinedOp.h b/eo/src/eoProportionalCombinedOp.h index 892c9b47..123c634b 100644 --- a/eo/src/eoProportionalCombinedOp.h +++ b/eo/src/eoProportionalCombinedOp.h @@ -2,7 +2,7 @@ //----------------------------------------------------------------------------- // eoCombinedOp.h // (c) GeNeura Team, 1998, Marc Schoenauer, 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -105,7 +105,7 @@ public: virtual bool operator()(EOT & _indi) { unsigned what = rng.roulette_wheel(rates); // choose one op - return (*ops[what])(_indi); // apply it + return (*ops[what])(_indi); // apply it } protected: std::vector*> ops; @@ -139,20 +139,20 @@ virtual void add(eoBinOp & _op, const double _rate, bool _verbose=false) // compute the relative rates in percent - to warn the user! if (_verbose) { - double total = 0; - unsigned i; - for (i=0; iclassName() << " with rate " << 100*rates[i]/total << " %" << std::endl; + for (i=0; iclassName() << " with rate " << 100*rates[i]/total << " %" << std::endl; } } virtual void operator()(EOT & _indi1, const EOT & _indi2) { unsigned what = rng.roulette_wheel(rates); // choose one op index - return (*ops[what])(_indi1, _indi2); // apply it + return (*ops[what])(_indi1, _indi2); // apply it } private: std::vector*> ops; @@ -216,7 +216,7 @@ public: virtual bool operator()(EOT & _indi1, EOT & _indi2) { 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: std::vector*> ops; diff --git a/eo/src/eoProportionalSelect.h b/eo/src/eoProportionalSelect.h index bd788048..daa4428d 100644 --- a/eo/src/eoProportionalSelect.h +++ b/eo/src/eoProportionalSelect.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoProportionalSelect.h // (c) GeNeura Team, 1998 - EEAAX 1999, Maarten Keijzer 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -35,18 +35,18 @@ #include /** eoProportionalSelect: select an individual proportional to her stored fitness - value - - Changed the algorithm to make use of a cumulative array of fitness scores, + value + + Changed the algorithm to make use of a cumulative array of fitness scores, This changes the algorithm from O(n) per call to O(log n) per call. (MK) @ingroup Selectors */ -template class eoProportionalSelect: public eoSelectOne +template class eoProportionalSelect: public eoSelectOne { public: /// Sanity check - eoProportionalSelect(const eoPop& pop = eoPop()) + eoProportionalSelect(const eoPop& pop = eoPop()) { if (minimizing_fitness()) throw std::logic_error("eoProportionalSelect: minimizing fitness"); @@ -55,23 +55,23 @@ public: void setup(const eoPop& _pop) { if (_pop.size() == 0) return; - + cumulative.resize(_pop.size()); cumulative[0] = _pop[0].fitness(); - for (unsigned i = 1; i < _pop.size(); ++i) + for (unsigned i = 1; i < _pop.size(); ++i) { - cumulative[i] = _pop[i].fitness() + cumulative[i-1]; + cumulative[i] = _pop[i].fitness() + cumulative[i-1]; } } - - /** do the selection, + + /** do the selection, */ - const EOT& operator()(const eoPop& _pop) + const EOT& operator()(const eoPop& _pop) { if (cumulative.size() == 0) setup(_pop); - - double fortune = rng.uniform() * cumulative.back(); + + double fortune = rng.uniform() * cumulative.back(); typename FitVec::iterator result = std::upper_bound(cumulative.begin(), cumulative.end(), fortune); return _pop[result - cumulative.begin()]; } diff --git a/eo/src/eoRandomRealWeightUp.h b/eo/src/eoRandomRealWeightUp.h index b929504c..81521b51 100644 --- a/eo/src/eoRandomRealWeightUp.h +++ b/eo/src/eoRandomRealWeightUp.h @@ -31,7 +31,7 @@ //----------------------------------------------------------------------------- /** - * Update an inertia weight by assigning it an (uniform) random value. + * Update an inertia weight by assigning it an (uniform) random value. * The weight is a basic feature to evaluate the velocity of a particle in * swarm optimization. * diff --git a/eo/src/eoRandomSelect.h b/eo/src/eoRandomSelect.h index 6d99f17e..065f050f 100644 --- a/eo/src/eoRandomSelect.h +++ b/eo/src/eoRandomSelect.h @@ -35,7 +35,7 @@ #include #include -/** eoRandomSelect: a selection method that selects ONE individual randomly +/** eoRandomSelect: a selection method that selects ONE individual randomly * * @ingroup Selectors */ @@ -91,4 +91,3 @@ private: }; #endif - diff --git a/eo/src/eoRanking.h b/eo/src/eoRanking.h index ec812006..5e734291 100644 --- a/eo/src/eoRanking.h +++ b/eo/src/eoRanking.h @@ -55,10 +55,10 @@ public: { typename eoPop::const_iterator it; for (it=_pop.begin(); it<_pop.end(); it++) - { - if (_eo == &(*it)) - return it-_pop.begin(); - } + { + if (_eo == &(*it)) + return it-_pop.begin(); + } throw std::runtime_error("Not found in eoLinearRanking"); } @@ -74,33 +74,33 @@ public: unsigned int pSizeMinusOne = 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().resize(pSize); double beta = (2-pressure)/pSize; - if (exponent == 1.0) // no need for exponetial then - { - double alpha = (2*pressure-2)/(pSize*pSizeMinusOne); - for (unsigned i=0; i 1/[P(P-1)/2] - } - } - else // exponent != 1 - { - double gamma = (2*pressure-2)/pSize; - for (unsigned i=0; i 1/[P(P-1)/2] + } + } + else // exponent != 1 + { + double gamma = (2*pressure-2)/pSize; + for (unsigned i=0; i -class eoRankingSelect: public eoRouletteWorthSelect +template +class eoRankingSelect: public eoRouletteWorthSelect { public: /** Ctor: * @param _p the selective pressure, should be in [1,2] (2 is the default) * @param _e exponent (1 == linear) */ - eoRankingSelect(double _p = 2.0, double _e=1.0): + eoRankingSelect(double _p = 2.0, double _e=1.0): eoRouletteWorthSelect(ranking), ranking(_p, _e) {} private : - eoRanking ranking; // derived from eoPerf2Worth + eoRanking ranking; // derived from eoPerf2Worth }; #endif diff --git a/eo/src/eoRealBoundModifier.h b/eo/src/eoRealBoundModifier.h index e9d21c4c..9a9e032b 100644 --- a/eo/src/eoRealBoundModifier.h +++ b/eo/src/eoRealBoundModifier.h @@ -56,8 +56,8 @@ public: void operator() (eoRealBaseVectorBounds & _bnds,unsigned _i) { - (void)_bnds; - (void)_i; + (void)_bnds; + (void)_i; } }; @@ -70,26 +70,26 @@ public: * - t, the current iteration, is given with an eoValueParam * - Nt is the stopping criteria <=> the total number of iterations * - alpha a coefficient - * + * */ class eoExpDecayingBoundModifier: public eoRealBoundModifier { public: - - /** - * Constructor - * @param _stopCriteria - The total number of iterations - * @param _alpha - * @param _genCounter - An eoValueParam that gives the current iteration - */ + + /** + * Constructor + * @param _stopCriteria - The total number of iterations + * @param _alpha + * @param _genCounter - An eoValueParam that gives the current iteration + */ eoExpDecayingBoundModifier (unsigned _stopCriteria, double _alpha, eoValueParam & _genCounter): - stopCriteria(_stopCriteria), - alpha(_alpha), - genCounter(_genCounter){} - - + stopCriteria(_stopCriteria), + alpha(_alpha), + genCounter(_genCounter){} + + void operator() (eoRealBaseVectorBounds & _bnds,unsigned _i) { double newMaxBound=(1-pow((double)genCounter.value()/stopCriteria,alpha))*_bnds.maximum(_i); diff --git a/eo/src/eoReduce.h b/eo/src/eoReduce.h index 7b51d586..7cca6199 100644 --- a/eo/src/eoReduce.h +++ b/eo/src/eoReduce.h @@ -4,7 +4,7 @@ // eoReduce.h // Base class for population-merging classes // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -39,7 +39,7 @@ /** * eoReduce: .reduce the new generation to the specified size At the moment, limited to truncation - with 2 different methods, - one that sorts the whole population, and one that repeatidely kills + one that sorts the whole population, and one that repeatidely kills the worst. Ideally, we should be able to choose at run-time!!! @ingroup Replacors @@ -47,7 +47,7 @@ template class eoReduce: public eoBF&, unsigned, void> {}; -/** truncation method using sort +/** truncation method using sort @ingroup Replacors */ template class eoTruncate : public eoReduce @@ -56,15 +56,15 @@ template class eoTruncate : public eoReduce { if (_newgen.size() == _newsize) return; - if (_newgen.size() < _newsize) - throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n"); - + if (_newgen.size() < _newsize) + throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n"); + _newgen.sort(); _newgen.resize(_newsize); } }; -/** random truncation +/** random truncation @ingroup Replacors * */ template class eoRandomReduce : public eoReduce @@ -73,16 +73,16 @@ template class eoRandomReduce : public eoReduce { if (_newgen.size() == _newsize) return; - if (_newgen.size() < _newsize) - throw std::logic_error("eoRandomReduce: Cannot truncate to a larger size!\n"); + if (_newgen.size() < _newsize) + throw std::logic_error("eoRandomReduce: Cannot truncate to a larger size!\n"); - // shuffle the population, then trucate - _newgen.shuffle(); - _newgen.resize(_newsize); + // shuffle the population, then trucate + _newgen.shuffle(); + _newgen.resize(_newsize); } }; -/** +/** EP truncation method (some global stochastic tournament + sort) Softer selective pressure than pure truncate @ingroup Replacors @@ -90,15 +90,15 @@ Softer selective pressure than pure truncate template class eoEPReduce : public eoReduce { public: -typedef typename EOT::Fitness Fitness; +typedef typename EOT::Fitness Fitness; eoEPReduce(unsigned _t_size ): t_size(_t_size) { if (t_size < 2) - { + { eo::log << eo::warnings << "Warning: EP tournament size should be >= 2. Adjusted" << std::endl; - t_size = 2; + t_size = 2; } } @@ -108,60 +108,60 @@ typedef typename EOT::Fitness Fitness; typedef std::pair::iterator> EPpair; struct Cmp { bool operator()(const EPpair a, const EPpair b) const - { + { if (b.first == a.first) - return (*b.second < *a.second); - return b.first < a.first; + return (*b.second < *a.second); + return b.first < a.first; } }; - - + + void operator()(eoPop& _newgen, unsigned _newsize) { unsigned int presentSize = _newgen.size(); - + if (presentSize == _newsize) return; - if (presentSize < _newsize) - throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n"); - std::vector scores(presentSize); - for (unsigned i=0; i competitor.fitness()) - scores[i].first += 1; - else if (fit == competitor.fitness()) - scores[i].first += 0.5; - } - } + if (presentSize < _newsize) + throw std::logic_error("eoTruncate: Cannot truncate to a larger size!\n"); + std::vector scores(presentSize); + for (unsigned i=0; i competitor.fitness()) + scores[i].first += 1; + else if (fit == competitor.fitness()) + scores[i].first += 0.5; + } + } - // now we have the scores - typename std::vector::iterator it = scores.begin() + _newsize; + // now we have the scores + typename std::vector::iterator it = scores.begin() + _newsize; std::nth_element(scores.begin(), it, scores.end(), Cmp()); - // sort(scores.begin(), scores.end(), Cmp()); - unsigned j; -// std::cout << "Les scores apres tri\n"; -// for (j=0; j tmPop; - for (j=0; j<_newsize; j++) - { - tmPop.push_back(*scores[j].second); - } - _newgen.swap(tmPop); - // erase does not work, but I'm sure there is a way in STL to mark - // and later delete all inside a std::vector ?????? - // this would avoid all copies here + // sort(scores.begin(), scores.end(), Cmp()); + unsigned j; +// std::cout << "Les scores apres tri\n"; +// for (j=0; j tmPop; + for (j=0; j<_newsize; j++) + { + tmPop.push_back(*scores[j].second); + } + _newgen.swap(tmPop); + // erase does not work, but I'm sure there is a way in STL to mark + // and later delete all inside a std::vector ?????? + // this would avoid all copies here -// it = scores.begin() + _newsize; -// while (it < scores.end()) -// _newgen.erase(it->second); +// it = scores.begin() + _newsize; +// while (it < scores.end()) +// _newgen.erase(it->second); } private: unsigned t_size; @@ -171,7 +171,7 @@ private: To be used in SSGA-like replacements (e.g. see eoSSGAWorseReplacement) @ingroup Replacors */ -template +template class eoLinearTruncate : public eoReduce { void operator()(eoPop& _newgen, unsigned _newsize) @@ -183,8 +183,8 @@ class eoLinearTruncate : public eoReduce throw std::logic_error("eoLinearTruncate: Cannot truncate to a larger size!\n"); for (unsigned i=0; i::iterator it = _newgen.it_worse_element(); - _newgen.erase(it); + typename eoPop::iterator it = _newgen.it_worse_element(); + _newgen.erase(it); } } }; @@ -193,7 +193,7 @@ class eoLinearTruncate : public eoReduce To be used in SSGA-like replacements (e.g. see eoSSGADetTournamentReplacement) @ingroup Replacors */ -template +template class eoDetTournamentTruncate : public eoReduce { public: @@ -201,9 +201,9 @@ public: t_size(_t_size) { if (t_size < 2) - { + { 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(); if (_newsize == 0) { - _newgen.resize(0); - return; + _newgen.resize(0); + return; } if (oldSize == _newsize) return; @@ -223,15 +223,15 @@ public: // Now OK to erase some losers for (unsigned i=0; i(_newgen, t_size); - //OLDCODE _newgen.erase(&eo); - - // Jeroen Eggermont stdc++v3 patch - // in the new code from stdc++v3 an iterator from a container is no longer an pointer to T - // Because eo already contained a fuction using eoPop::iterator's we will use the following - - _newgen.erase( inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size) ); - + //OLDCODE EOT & eo = inverse_deterministic_tournament(_newgen, t_size); + //OLDCODE _newgen.erase(&eo); + + // Jeroen Eggermont stdc++v3 patch + // in the new code from stdc++v3 an iterator from a container is no longer an pointer to T + // Because eo already contained a fuction using eoPop::iterator's we will use the following + + _newgen.erase( inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size) ); + } } private: @@ -242,7 +242,7 @@ private: To be used in SSGA-like replacements (e.g. see eoSSGAStochTournamentReplacement) @ingroup Replacors */ -template +template class eoStochTournamentTruncate : public eoReduce { public: @@ -250,14 +250,14 @@ public: t_rate(_t_rate) { if (t_rate <= 0.5) - { + { 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) { 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(); if (_newsize == 0) { - _newgen.resize(0); - return; + _newgen.resize(0); + return; } if (oldSize == _newsize) return; @@ -276,16 +276,16 @@ public: // Now OK to erase some losers for (unsigned i=0; i(_newgen, t_rate); - //OLDCODE _newgen.erase(&eo); - - // Jeroen Eggermont stdc++v3 patch - // in the new code from stdc++v3 an iterator from a container is no longer an pointer to T - // Because eo already contained a fuction using eoPop::iterator's we will use the following - - _newgen.erase( inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate) ); - - + //OLDCODE EOT & eo = inverse_stochastic_tournament(_newgen, t_rate); + //OLDCODE _newgen.erase(&eo); + + // Jeroen Eggermont stdc++v3 patch + // in the new code from stdc++v3 an iterator from a container is no longer an pointer to T + // Because eo already contained a fuction using eoPop::iterator's we will use the following + + _newgen.erase( inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate) ); + + } } diff --git a/eo/src/eoReduceMerge.h b/eo/src/eoReduceMerge.h index 2e653018..02933b40 100644 --- a/eo/src/eoReduceMerge.h +++ b/eo/src/eoReduceMerge.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoReduceMerge.h + eoReduceMerge.h (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -41,8 +41,8 @@ * @{ */ -/** -eoReduceMerge: Replacement strategies that start by reducing the parents, +/** +eoReduceMerge: Replacement strategies that start by reducing the parents, then merge with the offspring This is the way to do SSGA: the offspring gets inserted in the population @@ -63,10 +63,10 @@ class eoReduceMerge : public eoReplacement void operator()(eoPop& _parents, eoPop& _offspring) { - if (_parents.size() < _offspring.size()) - throw std::logic_error("eoReduceMerge: More offspring than parents!\n"); - reduce(_parents, _parents.size() - _offspring.size()); - merge(_offspring, _parents); + if (_parents.size() < _offspring.size()) + throw std::logic_error("eoReduceMerge: More offspring than parents!\n"); + reduce(_parents, _parents.size() - _offspring.size()); + merge(_offspring, _parents); } private : @@ -74,10 +74,10 @@ class eoReduceMerge : public eoReplacement eoMerge& merge; }; -/** +/** SSGA replace worst. Is an eoReduceMerge. */ -template +template class eoSSGAWorseReplacement : public eoReduceMerge { public : @@ -88,15 +88,15 @@ class eoSSGAWorseReplacement : public eoReduceMerge eoPlus plus; }; -/** +/** SSGA deterministic tournament replacement. Is an eoReduceMerge. */ -template +template class eoSSGADetTournamentReplacement : public eoReduceMerge { public : - eoSSGADetTournamentReplacement(unsigned _t_size) : - eoReduceMerge(truncate, plus), truncate(_t_size) {} + eoSSGADetTournamentReplacement(unsigned _t_size) : + eoReduceMerge(truncate, plus), truncate(_t_size) {} private : eoDetTournamentTruncate truncate; @@ -104,16 +104,16 @@ class eoSSGADetTournamentReplacement : public eoReduceMerge }; /** SSGA stochastic tournament replacement. Is an eoReduceMerge. -It much cleaner to insert directly the offspring in the parent population, -but it is NOT equivalent in case of more than 1 offspring as already -replaced could be removed , which is not possible in the eoReduceMerge +It much cleaner to insert directly the offspring in the parent population, +but it is NOT equivalent in case of more than 1 offspring as already +replaced could be removed , which is not possible in the eoReduceMerge So what the heck ! */ -template +template class eoSSGAStochTournamentReplacement : public eoReduceMerge { public : - eoSSGAStochTournamentReplacement(double _t_rate) : - eoReduceMerge(truncate, plus), truncate(_t_rate) {} + eoSSGAStochTournamentReplacement(double _t_rate) : + eoReduceMerge(truncate, plus), truncate(_t_rate) {} private : eoStochTournamentTruncate truncate; diff --git a/eo/src/eoReduceMergeReduce.h b/eo/src/eoReduceMergeReduce.h index 41629267..17721f73 100644 --- a/eo/src/eoReduceMergeReduce.h +++ b/eo/src/eoReduceMergeReduce.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoReduceMergeReduce.h + eoReduceMergeReduce.h (c) Maarten Keijzer, Marc Schoenauer, 2002 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -49,13 +49,13 @@ template class eoReduceMergeReduce : public eoReplacement { public: - eoReduceMergeReduce(eoHowMany _howManyElite, - bool _strongElitism, - eoHowMany _howManyReducedParents, - eoReduce & _reduceParents, - eoHowMany _howManyReducedOffspring, - eoReduce & _reduceOffspring, - eoReduce & _reduceFinal) : + eoReduceMergeReduce(eoHowMany _howManyElite, + bool _strongElitism, + eoHowMany _howManyReducedParents, + eoReduce & _reduceParents, + eoHowMany _howManyReducedOffspring, + eoReduce & _reduceOffspring, + eoReduce & _reduceFinal) : howManyElite(_howManyElite), strongElitism(_strongElitism), howManyReducedParents(_howManyReducedParents), @@ -64,7 +64,7 @@ public: reduceOffspring(_reduceOffspring), reduceFinal(_reduceFinal) {} - + void operator()(eoPop & _parents, eoPop & _offspring) { eoPop temp; @@ -72,66 +72,66 @@ public: unsigned int offSize = _offspring.size(); unsigned int elite = howManyElite(finalPopSize); - if (elite) // some parents MUST be saved somewhere - { - temp.resize(elite); - _parents.nth_element(elite); - std::copy(_parents.begin(), _parents.begin()+elite, temp.begin()); - _parents.erase(_parents.begin(), _parents.begin()+elite); - } + if (elite) // some parents MUST be saved somewhere + { + temp.resize(elite); + _parents.nth_element(elite); + std::copy(_parents.begin(), _parents.begin()+elite, temp.begin()); + _parents.erase(_parents.begin(), _parents.begin()+elite); + } // the reduce steps. First the parents unsigned reducedParentSize = howManyReducedParents(_parents.size()); if (!reducedParentSize) - _parents.clear(); + _parents.clear(); else if (reducedParentSize != _parents.size()) - reduceParents(_parents, reducedParentSize); + reduceParents(_parents, reducedParentSize); // then the offspring unsigned reducedOffspringSize = howManyReducedOffspring(offSize); 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 - reduceOffspring(_offspring, reducedOffspringSize); + reduceOffspring(_offspring, reducedOffspringSize); // now merge reduced populations _parents.resize(reducedParentSize + _offspring.size()); - std::copy(_offspring.begin(), _offspring.end(), - _parents.begin()+reducedParentSize); + std::copy(_offspring.begin(), _offspring.end(), + _parents.begin()+reducedParentSize); // reduce the resulting population // size depstd::ends on elitism if (elite && strongElitism) - { - if (_parents.size() != finalPopSize-elite) - reduceFinal(_parents, finalPopSize-elite); - // and put back the elite - unsigned oldPSize = _parents.size(); - _parents.resize(_parents.size()+elite); - std::copy(temp.begin(), temp.end(), _parents.begin()+oldPSize); - } - else - { // only reduce final pop to right size - if (_parents.size() != finalPopSize) - reduceFinal(_parents, finalPopSize); - if (elite) // then treat weak elitism - { - unsigned toSave = 0; - _parents.sort(); - EOT & eoLimit = _parents[elite-1]; - unsigned index=0; - while ( (temp[index++] > eoLimit) && (index < temp.size()) ) - toSave++; - if (toSave) - for (unsigned i=0; i eoLimit) && (index < temp.size()) ) + toSave++; + if (toSave) + for (unsigned i=0; i weak estd::listism + eoHowMany howManyElite; // if 0, no elitism at all + bool strongElitism; // if false -> weak estd::listism eoHowMany howManyReducedParents; // if 0, no parent in final replacement eoHowMany howManyReducedOffspring; // if 0, std::runtime_error // the reducers diff --git a/eo/src/eoReduceSplit.h b/eo/src/eoReduceSplit.h index db119032..ce22d027 100644 --- a/eo/src/eoReduceSplit.h +++ b/eo/src/eoReduceSplit.h @@ -4,7 +4,7 @@ // eoReduceSplit.h // Base class for population-reducing classes - retaining the poor losers // (c) GeNeura Team, 1998, Marc Schoenauer, 2002 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -47,16 +47,16 @@ template class eoReduceSplit: public eoBF&, eoPop &, {}; /** deterministic truncation method using sort */ -template +template class eoTruncateSplit : public eoReduceSplit { public: - /** Ctor: must provide amount of reduction, + /** Ctor: must provide amount of reduction, and whether or not you need to return the eliminated guys */ eoTruncateSplit(eoHowMany _howMany, bool _returnEliminated = false): howMany(_howMany), returnEliminated(_returnEliminated) {} - + /** do the jonb */ void operator()(eoPop& _newgen, eoPop & _eliminated) { @@ -67,13 +67,13 @@ public: unsigned newsize = popSize - eliminated; if (newsize < 0) throw std::logic_error("eoTruncateSplit: Cannot truncate to a larger size!\n"); - + _newgen.nth_element(newsize); // save poor losers if necessary if (returnEliminated) for (unsigned i=0; i +template class eoLinearTruncateSplit : public eoReduceSplit { public: - /** Ctor: must provide amount of reduction, + /** Ctor: must provide amount of reduction, and whether or not you need to return the eliminated guys */ eoLinearTruncateSplit(eoHowMany _howMany, bool _returnEliminated = false): howMany(_howMany), returnEliminated(_returnEliminated) {} - + /** do the job */ void operator()(eoPop& _newgen, eoPop & _eliminated) { @@ -111,10 +111,10 @@ public: _eliminated.reserve(_eliminated.size()+eliminated); //in case not empty? for (unsigned i=0; i::iterator it = _newgen.it_worse_element(); - if (returnEliminated) - _eliminated.push_back(*it); - _newgen.erase(it); + typename eoPop::iterator it = _newgen.it_worse_element(); + if (returnEliminated) + _eliminated.push_back(*it); + _newgen.erase(it); } } @@ -124,16 +124,16 @@ private: }; /** random truncation - batch version */ -template +template class eoRandomSplit : public eoReduceSplit { public: - /** Ctor: must provide amount of reduction, + /** Ctor: must provide amount of reduction, and whether or not you need to return the eliminated guys */ eoRandomSplit(eoHowMany _howMany, bool _returnEliminated = false): howMany(_howMany), returnEliminated(_returnEliminated) {} - + /** do the job */ void operator()(eoPop& _newgen, eoPop & _eliminated) { @@ -150,7 +150,7 @@ public: // save poor losers if necessary if (returnEliminated) for (unsigned i=0; i +template class eoLinearRandomSplit : public eoReduceSplit { public: - /** Ctor: must provide amount of reduction, + /** Ctor: must provide amount of reduction, and whether or not you need to return the eliminated guys */ eoLinearRandomSplit(eoHowMany _howMany, bool _returnEliminated = false): howMany(_howMany), returnEliminated(_returnEliminated) {} - + /** do the job */ void operator()(eoPop& _newgen, eoPop & _eliminated) { @@ -187,11 +187,11 @@ public: _eliminated.reserve(_eliminated.size()+eliminated); //in case not empty? for (unsigned i=0; i::iterator it = _newgen.begin()+loser; - if (returnEliminated) - _eliminated.push_back(*it); - _newgen.erase(it); + unsigned loser=random(_newgen.size()); + typename eoPop::iterator it = _newgen.begin()+loser; + if (returnEliminated) + _eliminated.push_back(*it); + _newgen.erase(it); } return ; } @@ -205,22 +205,22 @@ private: /** a ReduceSplit class based on a repeated deterministic (reverse!) tournament To be used in SSGA-like replacements (e.g. see eoSSGADetTournamentReplacement) */ -template +template class eoDetTournamentTruncateSplit : public eoReduceSplit { public: - /** Ctor: must provide amount of reduction, + /** Ctor: must provide amount of reduction, and whether or not you need to return the eliminated guys */ - eoDetTournamentTruncateSplit(unsigned _t_size, eoHowMany _howMany, - bool _returnEliminated = false): - t_size(_t_size), howMany(_howMany), - returnEliminated(_returnEliminated) + eoDetTournamentTruncateSplit(unsigned _t_size, eoHowMany _howMany, + bool _returnEliminated = false): + t_size(_t_size), howMany(_howMany), + returnEliminated(_returnEliminated) { if (t_size < 2) - { + { 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? for (unsigned i=0; i::iterator it = inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size); - if (returnEliminated) - _eliminated.push_back(*it); - _newgen.erase(it); + typename eoPop::iterator it = inverse_deterministic_tournament(_newgen.begin(), _newgen.end(), t_size); + if (returnEliminated) + _eliminated.push_back(*it); + _newgen.erase(it); } } @@ -256,27 +256,27 @@ private: /** a ReduceSplit class based on a repeated deterministic (reverse!) tournament To be used in SSGA-like replacements (e.g. see eoSSGAStochTournamentReplacement) */ -template +template class eoStochTournamentTruncateSplit : public eoReduce { public: - /** Ctor: must provide amount of reduction, + /** Ctor: must provide amount of reduction, and whether or not you need to return the eliminated guys */ - eoStochTournamentTruncateSplit(double _t_rate, eoHowMany _howMany, - bool _returnEliminated = false): - t_rate(_t_rate), howMany(_howMany), - returnEliminated(_returnEliminated) + eoStochTournamentTruncateSplit(double _t_rate, eoHowMany _howMany, + bool _returnEliminated = false): + t_rate(_t_rate), howMany(_howMany), + returnEliminated(_returnEliminated) { if (t_rate <= 0.5) - { + { 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) { 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& _newgen, unsigned _newsize) { /* old version - if (!_eliminated.size()) // nothing to do + if (!_eliminated.size()) // nothing to do return; unsigned oldSize = _newgen.size(); unsigned newSize = oldSize - _eliminated.size(); @@ -308,10 +308,10 @@ end of old version */ _eliminated.reserve(_eliminated.size()+eliminated); //in case not empty? for (unsigned i=0; i<_eliminated.size(); i++) { - typename eoPop::iterator it = inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate); - if (returnEliminated) - _eliminated.push_back(*it); - _newgen.erase(it); + typename eoPop::iterator it = inverse_stochastic_tournament(_newgen.begin(), _newgen.end(), t_rate); + if (returnEliminated) + _eliminated.push_back(*it); + _newgen.erase(it); } } diff --git a/eo/src/eoReplacement.h b/eo/src/eoReplacement.h index 2c2d8984..033d441c 100644 --- a/eo/src/eoReplacement.h +++ b/eo/src/eoReplacement.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoReplacement.h + eoReplacement.h (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -36,9 +36,9 @@ #include //----------------------------------------------------------------------------- -/** +/** --- -The eoMergeReduce, combination of eoMerge and eoReduce, can be found +The eoMergeReduce, combination of eoMerge and eoReduce, can be found in file eoMergeReduce.h The eoReduceMergeReduce that reduces the parents and the offspring, @@ -47,15 +47,15 @@ population, can be found in eoReduceMergeReduce.h LOG --- -Removed the const before first argument: though it makes too many classes -with the same interface, it allows to minimize the number of actual copies +Removed the const before first argument: though it makes too many classes +with the same interface, it allows to minimize the number of actual copies by choosing the right destination I also removed the enforced "swap" in the eoEasyAlgo and hence the generational -replacement gets a class of its own that only does the swap (instead of the +replacement gets a class of its own that only does the swap (instead of the eoNoReplacement that did nothing, relying on the algo to swap popualtions). MS 12/12/2000 - @see eoMerge, eoReduce, eoMergeReduce, eoReduceMerge + @see eoMerge, eoReduce, eoMergeReduce, eoReduceMerge @class eoReplacement, base (pure abstract) class @class eoGenerationalReplacement, as it says ... @@ -67,7 +67,7 @@ MS 12/12/2000 NOTE: two eoPop as arguments the resulting population should be in the first argument (replace -parents by offspring)! The second argument can contain any rubbish +parents by offspring)! The second argument can contain any rubbish @ingroup Replacors */ @@ -91,10 +91,10 @@ class eoGenerationalReplacement : public eoReplacement } }; -/** -eoWeakElitistReplacement: a wrapper for other replacement procedures. -Copies in the new pop the best individual from the old pop, -AFTER normal replacement, if the best of the new pop is worse than the best +/** +eoWeakElitistReplacement: a wrapper for other replacement procedures. +Copies in the new pop the best individual from the old pop, +AFTER normal replacement, if the best of the new pop is worse than the best of the old pop. Removes the worse individual from the new pop. This could be changed by adding a selector there... @@ -114,11 +114,11 @@ public : void operator()(eoPop& _pop, eoPop& _offspring) { 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 { - typename eoPop::iterator itPoorGuy = _pop.it_worse_element(); - (*itPoorGuy) = oldChamp; + typename eoPop::iterator itPoorGuy = _pop.it_worse_element(); + (*itPoorGuy) = oldChamp; } } private: diff --git a/eo/src/eoRingTopology.h b/eo/src/eoRingTopology.h index 74705ac1..6bad13cd 100644 --- a/eo/src/eoRingTopology.h +++ b/eo/src/eoRingTopology.h @@ -3,10 +3,10 @@ //----------------------------------------------------------------------------- // eoRingTopology.h // (c) INRIA Futurs DOLPHIN 2007 -/* +/* Clive Canape - Thomas Legrand - + Thomas Legrand + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -48,7 +48,7 @@ template < class POT > class eoRingTopology:public eoTopology public: /** - * The only Ctor. + * The only Ctor. * @param _neighborhoodSize - The size of each neighborhood. */ eoRingTopology (unsigned _neighborhoodSize):neighborhoodSize (_neighborhoodSize),isSetup(false){} @@ -68,16 +68,16 @@ public: int k = neighborhoodSize/2; for (unsigned i=0;i < _pop.size();i++) { - eoSocialNeighborhood currentNghd; - currentNghd.best(_pop[i]); - for (unsigned j=0; j < neighborhoodSize; j++) - { - currentNghd.put((_pop.size()+i-k+j)%_pop.size()); - if(_pop[(_pop.size()+i-k+j)%_pop.size()].fitness() > currentNghd.best().fitness()) + eoSocialNeighborhood currentNghd; + currentNghd.best(_pop[i]); + for (unsigned j=0; j < neighborhoodSize; j++) + { + currentNghd.put((_pop.size()+i-k+j)%_pop.size()); + if(_pop[(_pop.size()+i-k+j)%_pop.size()].fitness() > currentNghd.best().fitness()) currentNghd.best(_pop[(_pop.size()+i-k+j)%_pop.size()]); } - neighborhoods.push_back(currentNghd); - } + neighborhoods.push_back(currentNghd); + } isSetup=true; } else @@ -90,7 +90,7 @@ public: */ } } - + /** * Retrieves the neighboorhood of a particle. * @return _indice - The particle indice (in the population) @@ -109,20 +109,20 @@ public: */ void updateNeighborhood(POT & _po,unsigned _indice) { - //this->printOn();exit(0); + //this->printOn();exit(0); // update the best fitness of the particle if (_po.fitness() > _po.best()) { _po.best(_po.fitness()); for(unsigned i=0;i<_po.size();i++) - _po.bestPositions[i]=_po[i]; + _po.bestPositions[i]=_po[i]; } // update the global best if the given particle is "better" for (unsigned i=-neighborhoodSize+1; i < neighborhoodSize; i++) - { - unsigned indi = (_po.size()+_indice+i)%_po.size(); - if (_po.fitness() > neighborhoods[indi].best().fitness()) - neighborhoods[indi].best(_po); + { + unsigned indi = (_po.size()+_indice+i)%_po.size(); + if (_po.fitness() > neighborhoods[indi].best().fitness()) + neighborhoods[indi].best(_po); } } @@ -132,9 +132,9 @@ public: * @param _indice - The indice of a particle in the population * @return POT & - The best particle in the neighborhood of the particle whose indice is _indice */ - POT & best (unsigned _indice) + POT & best (unsigned _indice) { - unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice); + unsigned theGoodNhbd= retrieveNeighborhoodByIndice(_indice); return (neighborhoods[theGoodNhbd].best()); } @@ -155,35 +155,35 @@ public: std::cout << "}" << std::endl; } } - + /* - * Return the global best of the topology - */ - virtual POT & globalBest() + * Return the global best of the topology + */ + virtual POT & globalBest() { - POT gBest,tmp; - unsigned indGlobalBest=0; - if(neighborhoods.size()==1) - return neighborhoods[0].best(); - - gBest=neighborhoods[0].best(); - for(unsigned i=1;i > neighborhoods; - unsigned neighborhoodSize; + unsigned neighborhoodSize; bool isSetup; }; /** @example t-eoRingTopology.cpp diff --git a/eo/src/eoSGA.h b/eo/src/eoSGA.h index d17d743d..b31dff04 100644 --- a/eo/src/eoSGA.h +++ b/eo/src/eoSGA.h @@ -58,7 +58,7 @@ public : eoQuadOp& _cross, float _crate, eoMonOp& _mutate, float _mrate, eoEvalFunc& _eval, - eoContinue& _cont) + eoContinue& _cont) : cont(_cont), mutate(_mutate), mutationRate(_mrate), @@ -73,34 +73,34 @@ public : do { - select(_pop, offspring); + select(_pop, offspring); - unsigned i; + unsigned i; - for (i=0; i<_pop.size()/2; i++) - { - if ( rng.flip(crossoverRate) ) - { - // this crossover generates 2 offspring from two parents - if (cross(offspring[2*i], offspring[2*i+1])) + for (i=0; i<_pop.size()/2; i++) + { + if ( rng.flip(crossoverRate) ) + { + // this crossover generates 2 offspring from two parents + if (cross(offspring[2*i], offspring[2*i+1])) { offspring[2*i].invalidate(); offspring[2*i+1].invalidate(); } } - } + } - for (i=0; i < offspring.size(); i++) - { - if (rng.flip(mutationRate) ) - { - if (mutate(offspring[i])) + for (i=0; i < offspring.size(); i++) + { + if (rng.flip(mutationRate) ) + { + if (mutate(offspring[i])) offspring[i].invalidate(); - } - } + } + } - _pop.swap(offspring); - apply(eval, _pop); + _pop.swap(offspring); + apply(eval, _pop); } while (cont(_pop)); } diff --git a/eo/src/eoSGAGenOp.h b/eo/src/eoSGAGenOp.h index 922a46ca..f08b2104 100644 --- a/eo/src/eoSGAGenOp.h +++ b/eo/src/eoSGAGenOp.h @@ -33,40 +33,40 @@ // class eoSGAGenOp /////////////////////////////////////////////////////////////////////////////// -/** - * eoSGAGenOp (for Simple GA) mimicks the usual crossover with proba pCross + +/** + * eoSGAGenOp (for Simple GA) mimicks the usual crossover with proba pCross + * mutation with proba pMut inside an eoGeneralOp - * It does it exactly as class eoSGATransform, i.e. only accepts + * It does it exactly as class eoSGATransform, i.e. only accepts * quadratic crossover and unary mutation * It was introduced for didactic reasons, but seems to be popular :-) * * @ingroup Combination */ - template + template class eoSGAGenOp : public eoGenOp { public: - + /** Ctor from crossover (with proba) and mutation (with proba) * Builds the sequential op that first applies a proportional choice * between the crossover and nothing (cloning), then the mutation */ - eoSGAGenOp(eoQuadOp& _cross, double _pCross, - eoMonOp& _mut, double _pMut) + eoSGAGenOp(eoQuadOp& _cross, double _pCross, + eoMonOp& _mut, double _pMut) : cross(_cross), pCross(_pCross), - mut(_mut), - pMut(_pMut) + mut(_mut), + pMut(_pMut) { // the crossover - with probability pCross propOp.add(cross, pCross); // crossover, with proba pcross propOp.add(quadClone, 1-pCross); // nothing, with proba 1-pcross - + // 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 } - + /** do the job: delegate to op */ virtual void apply(eoPopulator& _pop) { diff --git a/eo/src/eoSGATransform.h b/eo/src/eoSGATransform.h index 57d5ea81..55b5e5ed 100644 --- a/eo/src/eoSGATransform.h +++ b/eo/src/eoSGATransform.h @@ -38,7 +38,7 @@ #include /** eoSGATransform: transforms a population using genetic operators. - * It does it exactly as class eoSGA, i.e. only accepts + * It does it exactly as class eoSGA, i.e. only accepts * quadratic crossover and unary mutation * It is here mainly for tutorial reasons * @@ -47,13 +47,13 @@ template class eoSGATransform : public eoTransform { public: - + /// Default constructor. - eoSGATransform(eoQuadOp& _cross, double _cProba, - eoMonOp& _mutate, double _mProba) + eoSGATransform(eoQuadOp& _cross, double _cProba, + eoMonOp& _mutate, double _mProba) : cross(_cross), crossoverProba(_cProba), - mutate(_mutate), + mutate(_mutate), mutationProba(_mProba) {} @@ -61,29 +61,29 @@ template class eoSGATransform : public eoTransform * Transforms a population. * @param _pop The population to be transformed. */ - void operator()(eoPop& _pop) + void operator()(eoPop& _pop) { unsigned i; - - for (i=0; i<_pop.size()/2; i++) + + for (i=0; i<_pop.size()/2; i++) { - if ( rng.flip(crossoverProba) ) - { - // this crossover generates 2 offspring from two parents - cross(_pop[2*i], _pop[2*i+1]); - } + if ( rng.flip(crossoverProba) ) + { + // this crossover generates 2 offspring from two parents + 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) ) - { - mutate(_pop[i]); - } - + if (rng.flip(mutationProba) ) + { + mutate(_pop[i]); + } + } }; - + private: eoInvalidateQuadOp cross; double crossoverProba; @@ -93,7 +93,7 @@ template class eoSGATransform : public eoTransform /** eoDynSGATransform: transforms a population using genetic operators. * It is the Dynamic version of the above eoSGATransform - * i.e. the operators probabilities can be passed as an eoValueParam, + * i.e. the operators probabilities can be passed as an eoValueParam, * and hence can be modified from outside * It is here mainly for tutorial reasons * @@ -102,23 +102,23 @@ template class eoSGATransform : public eoTransform template class eoDynSGATransform : public eoTransform { public: - + /// Default constructor - receives values - eoDynSGATransform(eoQuadOp& _cross, double _cProba, - eoMonOp& _mutate, double _mProba) + eoDynSGATransform(eoQuadOp& _cross, double _cProba, + eoMonOp& _mutate, double _mProba) : cross(_cross), crossoverProbaHolder(_cProba), crossoverProba(crossoverProbaHolder), - mutate(_mutate), + mutate(_mutate), mutationProbaHolder(_mProba), mutationProba(mutationProbaHolder) {} /// This constructor receives pointers // these will usually be some eoValueParam.value() // hence the ...Holder data will bever be used in this case - eoDynSGATransform(eoQuadOp& _cross, double* _cProbaRef, - eoMonOp& _mutate, double* _mProbaRef) + eoDynSGATransform(eoQuadOp& _cross, double* _cProbaRef, + eoMonOp& _mutate, double* _mProbaRef) : cross(_cross), crossoverProbaHolder(0), crossoverProba(*_cProbaRef), - mutate(_mutate), + mutate(_mutate), mutationProbaHolder(0), mutationProba(*_mProbaRef) {} @@ -126,34 +126,34 @@ template class eoDynSGATransform : public eoTransform * Transforms a population. * @param _pop The population to be transformed. */ - void operator()(eoPop& _pop) + void operator()(eoPop& _pop) { unsigned i; - - for (i=0; i<_pop.size()/2; i++) + + for (i=0; i<_pop.size()/2; i++) { - if ( rng.flip(crossoverProba) ) - { - // this crossover generates 2 offspring from two parents - cross(_pop[2*i], _pop[2*i+1]); - } + if ( rng.flip(crossoverProba) ) + { + // this crossover generates 2 offspring from two parents + 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) ) - { - mutate(_pop[i]); - } - + if (rng.flip(mutationProba) ) + { + mutate(_pop[i]); + } + } }; // accessors - mainly for EASEA - double & PCrossHandle() { return crossoverProba;} + double & PCrossHandle() { return crossoverProba;} double & PMutHandle() { return mutationProba;} private: - // difference with eoSGATransform: the operator probabilities + // difference with eoSGATransform: the operator probabilities // they can be passed by reference or by value. // hence we need here to use a reference, and to eventually store a value eoInvalidateQuadOp cross; diff --git a/eo/src/eoSIGContinue.cpp b/eo/src/eoSIGContinue.cpp index 4bc4ca24..2f126ea9 100644 --- a/eo/src/eoSIGContinue.cpp +++ b/eo/src/eoSIGContinue.cpp @@ -1,34 +1,34 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoSIGContinue.cpp -// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 +// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 /* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es Marc.Schoenauer@polytechnique.fr mak@dhi.dk - Johann Dréo - Caner Candan + Johann Dréo + Caner Candan */ //----------------------------------------------------------------------------- #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #include #include diff --git a/eo/src/eoSIGContinue.h b/eo/src/eoSIGContinue.h index 36546fb0..d7db55d3 100644 --- a/eo/src/eoSIGContinue.h +++ b/eo/src/eoSIGContinue.h @@ -1,28 +1,28 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoSIGContinue.h -// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 +// (c) EEAAX 1996 - GeNeura Team, 1998 - Maarten Keijzer 2000 /* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es Marc.Schoenauer@polytechnique.fr mak@dhi.dk - Johann Dréo - Caner Candan + Johann Dréo + Caner Candan */ //----------------------------------------------------------------------------- // the same thing can probably be done in MS environement, but I hoave no way @@ -75,8 +75,8 @@ public: { if (call_func) { - _fct(_sig); - call_func = false; + _fct(_sig); + call_func = false; } return true; diff --git a/eo/src/eoSTLFunctor.h b/eo/src/eoSTLFunctor.h index c21f161c..04f96f9c 100644 --- a/eo/src/eoSTLFunctor.h +++ b/eo/src/eoSTLFunctor.h @@ -29,7 +29,7 @@ #include "eoFunctor.h" -/** @addtogroup Utilities +/** @addtogroup Utilities * @{ */ @@ -121,4 +121,3 @@ class eoSTLBF : public std::binary_function /** @} */ #endif - diff --git a/eo/src/eoScalarFitness.h b/eo/src/eoScalarFitness.h index aa8d57a1..f3a3a4bb 100644 --- a/eo/src/eoScalarFitness.h +++ b/eo/src/eoScalarFitness.h @@ -63,8 +63,8 @@ class eoScalarFitness bool operator<(const eoScalarFitness& other) const { return Compare()(value, other.value); } - /// Comparison, using less by default - // needed for MSVC 8 (MSVC 2005) added by J.Eggermont 20-11-2006 + /// Comparison, using less by default + // needed for MSVC 8 (MSVC 2005) added by J.Eggermont 20-11-2006 bool operator<(const ScalarType& other) const { return Compare()(value, other); } diff --git a/eo/src/eoScalarFitnessAssembled.cpp b/eo/src/eoScalarFitnessAssembled.cpp index a30289ab..58f7615f 100644 --- a/eo/src/eoScalarFitnessAssembled.cpp +++ b/eo/src/eoScalarFitnessAssembled.cpp @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoScalarFitnessAssembled.cpp // Marc Wintermantel & Oliver Koenig @@ -11,16 +11,16 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es Marc.Schoenauer@inria.fr mak@dhi.dk @@ -29,13 +29,10 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #include "eoScalarFitnessAssembled.h" // need to allocate the static variables of class eoScalarFitnessAssembledTraits std::vector eoScalarFitnessAssembledTraits::TermDescriptions; - - - diff --git a/eo/src/eoScalarFitnessAssembled.h b/eo/src/eoScalarFitnessAssembled.h index f84a805d..95168ec6 100644 --- a/eo/src/eoScalarFitnessAssembled.h +++ b/eo/src/eoScalarFitnessAssembled.h @@ -110,8 +110,8 @@ public: {} eoScalarFitnessAssembled( size_type _n, - const ScalarType& _val, - const std::string& _descr="Unnamed variable" ) + const ScalarType& _val, + const std::string& _descr="Unnamed variable" ) : baseVector(_n, _val), feasible(true), failed(false), msg("") { @@ -225,10 +225,10 @@ public: //! Comparison with ScalarTypes. Explicit definition needed to compile with VS 8.0 bool operator<(ScalarType x) const{ - eoScalarFitnessAssembled ScalarFitness(x); - return this->operator<(ScalarFitness); + eoScalarFitnessAssembled ScalarFitness(x); + return this->operator<(ScalarFitness); } - + // implementation of the other operators bool operator>( const eoScalarFitnessAssembled& y ) const { return y < *this; } @@ -239,7 +239,7 @@ public: bool operator>=(const eoScalarFitnessAssembled& y ) const { return !(*this < y); } }; -/** +/** * @example t-eoFitnessAssembledEA.cpp */ @@ -282,4 +282,3 @@ std::istream& operator>>(std::istream& is, eoScalarFitnessAssembled -/** +/** Timed continuator: continues until a number of seconds is used @ingroup Continuators @@ -44,29 +44,29 @@ public: virtual bool operator() ( const eoPop& _vEO ) { time_t now = time(0); time_t diff = now - start; - + if (diff >= seconds) return false; // stop return true; } - + virtual std::string className(void) const { return "eoSecondsElapsedContinue"; } /** REad from a stream * @param __is the ostream to read from */ void readFrom (std :: istream & __is) { - - __is >> start >> seconds; + + __is >> start >> seconds; } - + /** Print on a stream * @param __os the ostream to print on */ void printOn (std :: ostream & __os) const { - - __os << start << ' ' << seconds << std :: endl; + + __os << start << ' ' << seconds << std :: endl; } }; @@ -74,4 +74,3 @@ public: */ #endif - diff --git a/eo/src/eoSelect.h b/eo/src/eoSelect.h index ea5c8592..aae33843 100644 --- a/eo/src/eoSelect.h +++ b/eo/src/eoSelect.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoSelect.h + eoSelect.h (c) Maarten Keijzer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -30,7 +30,7 @@ #include //----------------------------------------------------------------------------- -/** +/** eoSelect selects a number of individuals from the first argument and puts it in the second. To emphasize that it should not try to enlarge the population, the second argument is an eoPopRange, a simple struct diff --git a/eo/src/eoSelectFactory.h b/eo/src/eoSelectFactory.h index 59d2306a..9dc19dab 100644 --- a/eo/src/eoSelectFactory.h +++ b/eo/src/eoSelectFactory.h @@ -4,7 +4,7 @@ //----------------------------------------------------------------------------- // EOFactory.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -41,52 +41,52 @@ eoSelect objects */ template< class EOT> class eoSelectFactory: public eoFactory > { - + public: - - /// @name ctors and dtors - //{@ - /// constructor - eoSelectFactory( ) {} - - /// destructor - virtual ~eoSelectFactory() {} - //@} - /** Another factory methods: creates an object from an std::istream, reading from - it whatever is needed to create the object. Usually, the format for the std::istream will be\\ - objectType parameter1 parameter2 ... parametern\\ - */ - virtual eoSelect* make(std::istream& _is) { - eoSelect * selectPtr; - std::string objectTypeStr; - _is >> objectTypeStr; - // All selectors have a rate, the proportion of the original population - float rate; - _is >> rate; - if ( objectTypeStr == "eoTournament") { - // another parameter is necessary - unsigned tSize; - _is >> tSize; - selectPtr = new eoTournament( rate, tSize ); - } else { - if ( objectTypeStr == "eoRandomSelect" ) { - selectPtr = new eoRandomSelect( rate ); - } else { - throw std::runtime_error( "Incorrect selector type" ); - } - } - return selectPtr; - } + /// @name ctors and dtors + //{@ + /// constructor + eoSelectFactory( ) {} - ///@name eoObject methods - //@{ - void printOn( std::ostream& _os ) const {}; - void readFrom( std::istream& _is ){}; + /// destructor + virtual ~eoSelectFactory() {} + //@} + + /** Another factory methods: creates an object from an std::istream, reading from + it whatever is needed to create the object. Usually, the format for the std::istream will be\\ + objectType parameter1 parameter2 ... parametern\\ + */ + virtual eoSelect* make(std::istream& _is) { + eoSelect * selectPtr; + std::string objectTypeStr; + _is >> objectTypeStr; + // All selectors have a rate, the proportion of the original population + float rate; + _is >> rate; + if ( objectTypeStr == "eoTournament") { + // another parameter is necessary + unsigned tSize; + _is >> tSize; + selectPtr = new eoTournament( rate, tSize ); + } else { + if ( objectTypeStr == "eoRandomSelect" ) { + selectPtr = new eoRandomSelect( rate ); + } else { + throw std::runtime_error( "Incorrect selector type" ); + } + } + return selectPtr; + } + + ///@name eoObject methods + //@{ + void printOn( std::ostream& _os ) const {}; + void readFrom( std::istream& _is ){}; + + /** className is inherited */ + //@} - /** className is inherited */ - //@} - }; diff --git a/eo/src/eoSelectFromWorth.h b/eo/src/eoSelectFromWorth.h index e338ea31..a2fd5ed2 100644 --- a/eo/src/eoSelectFromWorth.h +++ b/eo/src/eoSelectFromWorth.h @@ -194,7 +194,7 @@ public: eoSelectFromWorth::setup(_pop); total = 0.0; for (worthIterator it = perf2Worth.value().begin(); - it& _pop) { // cout << "On affiche les worths\n"; // for (unsigned i=0; - // i //----------------------------------------------------------------------------- -/** eoSelectMany selects many individuals using eoSelectOne as it's +/** eoSelectMany selects many individuals using eoSelectOne as it's mechanism. Therefore eoSelectMany needs an eoSelectOne in its ctor It will use an eoHowMnay to determine the number of guys to select, @@ -48,12 +48,12 @@ class eoSelectMany : public eoSelect { public: /// init - eoSelectMany(eoSelectOne& _select, - double _rate, bool _interpret_as_rate = true) + eoSelectMany(eoSelectOne& _select, + double _rate, bool _interpret_as_rate = true) : select(_select), howMany(_rate, _interpret_as_rate) {} // Ctor with eoHowMany - eoSelectMany(eoSelectOne& _select, eoHowMany _howMany) + eoSelectMany(eoSelectOne& _select, eoHowMany _howMany) : select(_select), howMany(_howMany) {} /** @@ -65,15 +65,15 @@ class eoSelectMany : public eoSelect virtual void operator()(const eoPop& _source, eoPop& _dest) { unsigned target = howMany(_source.size()); - + _dest.resize(target); - + select.setup(_source); - + for (size_t i = 0; i < _dest.size(); ++i) _dest[i] = select(_source); } - + private : eoSelectOne& select; eoHowMany howMany; diff --git a/eo/src/eoSelectNumber.h b/eo/src/eoSelectNumber.h index 52cee662..f6f094ef 100644 --- a/eo/src/eoSelectNumber.h +++ b/eo/src/eoSelectNumber.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoSelectNumber.h + eoSelectNumber.h (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -32,7 +32,7 @@ #include //----------------------------------------------------------------------------- -/** eoSelectNumber selects many individuals using eoSelectOne as it's +/** eoSelectNumber selects many individuals using eoSelectOne as it's mechanism. Therefore eoSelectNumber needs an eoSelectOne in its ctor It will select a fixed number of individuals and pushes them to @@ -45,7 +45,7 @@ class eoSelectNumber : public eoSelect { public: /// init - eoSelectNumber(eoSelectOne& _select, unsigned _nb_to_select = 1) + eoSelectNumber(eoSelectOne& _select, unsigned _nb_to_select = 1) : select(_select), nb_to_select(_nb_to_select) {} /** @@ -57,15 +57,15 @@ class eoSelectNumber : public eoSelect virtual void operator()(const eoPop& _source, eoPop& _dest) { size_t target = static_cast(nb_to_select); - + _dest.resize(target); - + select.setup(_source); - + for (size_t i = 0; i < _dest.size(); ++i) _dest[i] = select(_source); } - + private : eoSelectOne& select; unsigned nb_to_select; diff --git a/eo/src/eoSelectOne.h b/eo/src/eoSelectOne.h index 3b27a4e3..5afdd140 100644 --- a/eo/src/eoSelectOne.h +++ b/eo/src/eoSelectOne.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoSelectOne.h + eoSelectOne.h (c) Maarten Keijzer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -50,7 +50,7 @@ class eoSelectOne : public eoUF&, const EOT&> /// virtual function to setup some population stats (for instance eoProportional can benefit greatly from this) virtual void setup(const eoPop& _pop) { - (void)_pop; + (void)_pop; } }; /** @example t-selectOne.cpp diff --git a/eo/src/eoSelectPerc.h b/eo/src/eoSelectPerc.h index d4aacfda..131a3d59 100644 --- a/eo/src/eoSelectPerc.h +++ b/eo/src/eoSelectPerc.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoSelectPerc.h + eoSelectPerc.h (c) Maarten Keijzer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -32,7 +32,7 @@ #include //----------------------------------------------------------------------------- -/** eoSelectPerc selects many individuals using eoSelectOne as it's +/** eoSelectPerc selects many individuals using eoSelectOne as it's mechanism. Therefore eoSelectPerc needs an eoSelectOne in its ctor It will select floor(rate*pop.size()) individuals and pushes them to @@ -45,11 +45,11 @@ class eoSelectPerc : public eoSelect { public: /// init - eoSelectPerc(eoSelectOne& _select, float _rate = 1.0) + eoSelectPerc(eoSelectOne& _select, float _rate = 1.0) : select(_select), rate(_rate) {} /** - The implementation selects a percentage + The implementation selects a percentage @param _source the source population @param _dest the resulting population (size of this population is the number of times eoSelectOne is called. It empties the destination and adds the selection into it) @@ -57,15 +57,15 @@ class eoSelectPerc : public eoSelect virtual void operator()(const eoPop& _source, eoPop& _dest) { size_t target = static_cast(floor(rate * _source.size())); - + _dest.resize(target); - + select.setup(_source); - + for (size_t i = 0; i < _dest.size(); ++i) _dest[i] = select(_source); } - + private : eoSelectOne& select; float rate; diff --git a/eo/src/eoSequentialSelect.h b/eo/src/eoSequentialSelect.h index a30c9248..1a1f02e4 100644 --- a/eo/src/eoSequentialSelect.h +++ b/eo/src/eoSequentialSelect.h @@ -58,13 +58,13 @@ template class eoSequentialSelect: public eoSelectOne not very elegant, maybe ... */ eoSequentialSelect(bool _ordered = true) - : ordered(_ordered), current(std::numeric_limits::max()) {} + : ordered(_ordered), current(std::numeric_limits::max()) {} void setup(const eoPop& _pop) { eoPters.resize(_pop.size()); if (ordered) // probably we could have a marker to avoid re-sorting - _pop.sort(eoPters); + _pop.sort(eoPters); else _pop.shuffle(eoPters); current=0; @@ -118,10 +118,10 @@ template class eoEliteSequentialSelect: public eoSelectOne throw std::runtime_error("Trying eoEliteSequentialSelect with only one individual!"); for (unsigned i=1; i<_pop.size(); i++) if (*eoPters[i]>*best) - { - ibest = i; - best = eoPters[ibest]; - } + { + ibest = i; + best = eoPters[ibest]; + } // and put it upfront const EOT *ptmp = eoPters[0]; eoPters[0]=best; diff --git a/eo/src/eoSharing.h b/eo/src/eoSharing.h index b2a58653..170a03b9 100644 --- a/eo/src/eoSharing.h +++ b/eo/src/eoSharing.h @@ -33,7 +33,7 @@ * Goldberg and Richardson's basic sharing */ -/** A helper class for Sharing - to hold distances +/** A helper class for Sharing - to hold distances * * @ingroup Selectors * */ @@ -60,16 +60,16 @@ class dMatrix : public std::vector { unsigned index=0; for (unsigned i=0; ioperator[](index++) << " " ; - _os << std::endl; - } + { + for (unsigned j=0; joperator[](index++) << " " ; + _os << std::endl; + } _os << std::endl; } 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! */ eoSharing(double _nicheSize, eoDistance & _dist) : eoPerf2Worth("Sharing"), - nicheSize(_nicheSize), - dist(_dist) + nicheSize(_nicheSize), + dist(_dist) {} /** Computes shared fitnesses @@ -98,33 +98,33 @@ public: void operator()(const eoPop& _pop) { unsigned i, j, - pSize=_pop.size(); + pSize=_pop.size(); 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); - std::vector sim(pSize); // to hold the similarities + std::vector sim(pSize); // to hold the similarities dMatrix distMatrix(pSize); // to hold the distances // compute the similarities (wrong name for distMatrix, I know) distMatrix(0,0)=1; for (i=1; inicheSize ? 0 : 1-(d/nicheSize) ); - } - } + { + distMatrix(i,i)=1; + for (j=0; jnicheSize ? 0 : 1-(d/nicheSize) ); + } + } for (i=0; i & dist; // specific distance + eoDistance & dist; // specific distance }; diff --git a/eo/src/eoSharingSelect.h b/eo/src/eoSharingSelect.h index d9b56568..0754cdd0 100644 --- a/eo/src/eoSharingSelect.h +++ b/eo/src/eoSharingSelect.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoSharingSelect.h // (c) GeNeura Team, 1998, Maarten Keijzer 2000, Marc Schoenauer 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -31,28 +31,28 @@ #include #include -/** eoSharingSelect: select an individual by roulette wheel - * on its SHARED fitness. It is an eoRouletteWorthSelect, +/** eoSharingSelect: select an individual by roulette wheel + * on its SHARED fitness. It is an eoRouletteWorthSelect, * i.e. a selector using a std::vector of worthes * rather than the raw fitness (see eoSelectFromWorth.h) - * It uses an internal eoSharing object which is + * It uses an internal eoSharing object which is * an eoPerf2Worth * @ingroup Selectors */ -template -class eoSharingSelect: public eoRouletteWorthSelect +template +class eoSharingSelect: public eoRouletteWorthSelect { public: /** Ctor: * @param _sigma the sigma_share * @param _dist the distance object to use */ - eoSharingSelect(double _sigma, eoDistance & _dist): + eoSharingSelect(double _sigma, eoDistance & _dist): eoRouletteWorthSelect(sharing), sharing(_sigma, _dist) {} private : - eoSharing sharing; // derived from eoPerf2Worth + eoSharing sharing; // derived from eoPerf2Worth }; /** @example t-eoSharing.cpp */ diff --git a/eo/src/eoShiftMutation.h b/eo/src/eoShiftMutation.h index d1a13268..a9b71d66 100644 --- a/eo/src/eoShiftMutation.h +++ b/eo/src/eoShiftMutation.h @@ -4,7 +4,7 @@ // eoShiftMutation.h // (c) GeNeura Team, 2000 - EEAAX 2000 - Maarten Keijzer 2000 // (c) INRIA Futurs - Dolphin Team - Thomas Legrand 2007 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -20,7 +20,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: todos@geneura.ugr.es, http://geneura.ugr.es - thomas.legrand@lifl.fr + thomas.legrand@lifl.fr Marc.Schoenauer@polytechnique.fr mak@dhi.dk */ @@ -40,13 +40,13 @@ template class eoShiftMutation: public eoMonOp { public: - + typedef typename EOT::AtomType GeneType; - + /// CTor eoShiftMutation(){} - - + + /// The class name. virtual std::string className() const { return "eoShiftMutation"; } @@ -57,36 +57,35 @@ template class eoShiftMutation: public eoMonOp */ bool operator()(EOT& _eo) { - - unsigned i, j, from, to; + + unsigned i, j, from, to; GeneType tmp; - + // generate two different indices i=eo::rng.random(_eo.size()); - do j = eo::rng.random(_eo.size()); while (i == j); - + do j = eo::rng.random(_eo.size()); while (i == j); + // indexes from=std::min(i,j); to=std::max(i,j); // keep the first component to change - tmp=_eo[to]; - + tmp=_eo[to]; + // shift for(unsigned int k=to ; k > from ; k--) - _eo[k]=_eo[k-1]; - + _eo[k]=_eo[k-1]; + // shift the first component _eo[from]=tmp; return true; } - + }; /** @example t-eoShiftMutation.cpp - */ + */ //----------------------------------------------------------------------------- #endif - diff --git a/eo/src/eoSigBinaryFlight.h b/eo/src/eoSigBinaryFlight.h index a172484a..dccf2e5f 100644 --- a/eo/src/eoSigBinaryFlight.h +++ b/eo/src/eoSigBinaryFlight.h @@ -19,7 +19,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 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 : - * if rand[0;1] < sig(Vi) (Vi <=> double) - * Pi=1 - * else - * Pi=0 + * if rand[0;1] < sig(Vi) (Vi <=> double) + * Pi=1 + * else + * Pi=0 * - * @ingroup Variators + * @ingroup Variators */ template < class POT > class eoSigBinaryFlight:public eoBinaryFlight < POT > { @@ -65,7 +65,7 @@ public: /** * Apply the sigmoid binary flight to a particle. - * + * */ void operator () (POT & _po) { @@ -85,8 +85,8 @@ public: } private : - unsigned slope; - + unsigned slope; + }; diff --git a/eo/src/eoSimpleEDA.h b/eo/src/eoSimpleEDA.h index c2a75672..afbf152f 100644 --- a/eo/src/eoSimpleEDA.h +++ b/eo/src/eoSimpleEDA.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoSimpleEDA.h // (c) Marc Schoenauer, Maarten Keijzer, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -35,8 +35,8 @@ #include /** A very simple Estimation of Distribution Algorithm - * - * The algorithm that evolves a probability distribution + * + * The algorithm that evolves a probability distribution * on the spaces of populations with the loop * generate a population from the current distribution * evaluate that population @@ -53,19 +53,19 @@ template class eoSimpleEDA: public eoEDA * plus an eoEval and eoContinue of course. */ eoSimpleEDA(eoDistribUpdater& _update, - eoEvalFunc& _eval, - unsigned _popSize, - eoContinue& _continuator - ) : + eoEvalFunc& _eval, + unsigned _popSize, + eoContinue& _continuator + ) : update(_update), eval(_eval), popSize(_popSize), continuator(_continuator) {} - /** The algorithm: - * generate pop from distrib, - * evaluate pop, + /** The algorithm: + * generate pop from distrib, + * evaluate pop, * update distrib */ virtual void operator()(eoDistribution& _distrib) @@ -75,18 +75,18 @@ template class eoSimpleEDA: public eoEDA { try { - apply(_distrib, pop); // re-init. of _pop from distrib + apply(_distrib, pop); // re-init. of _pop from distrib - apply(eval, pop); // eval of current population + apply(eval, pop); // eval of current population + + update(_distrib, pop); // updates distrib from _pop - update(_distrib, pop); // updates distrib from _pop - } catch (std::exception& e) { - std::string s = e.what(); - s.append( " in eoSimpleEDA"); - throw std::runtime_error( s ); + std::string s = e.what(); + s.append( " in eoSimpleEDA"); + throw std::runtime_error( s ); } } while ( continuator( pop ) ); } @@ -95,7 +95,7 @@ template class eoSimpleEDA: public eoEDA eoDistribUpdater & update; eoEvalFunc& eval; - + unsigned popSize; eoContinue& continuator; @@ -104,4 +104,3 @@ template class eoSimpleEDA: public eoEDA //----------------------------------------------------------------------------- #endif - diff --git a/eo/src/eoSocialNeighborhood.h b/eo/src/eoSocialNeighborhood.h index cb8dd9f9..944031f9 100644 --- a/eo/src/eoSocialNeighborhood.h +++ b/eo/src/eoSocialNeighborhood.h @@ -52,7 +52,7 @@ public: } /** - * Return true if the neighborhood contains the indice (= that means "contains the + * Return true if the neighborhood contains the indice (= that means "contains the * particle whose indice is _oneIndice") * @param _oneIndice - The indice of the particle in its population. */ @@ -123,4 +123,3 @@ protected: #endif /* EOSOCIALNEIGHBORHOOD_H_ */ - diff --git a/eo/src/eoStandardFlight.h b/eo/src/eoStandardFlight.h index 0c8008be..228839eb 100644 --- a/eo/src/eoStandardFlight.h +++ b/eo/src/eoStandardFlight.h @@ -49,7 +49,7 @@ public: /** Constructor without bounds. - * + * */ eoStandardFlight ():bnds (*(new eoRealVectorNoBounds(0))){} diff --git a/eo/src/eoStandardVelocity.h b/eo/src/eoStandardVelocity.h index e2b6deb1..62abd487 100644 --- a/eo/src/eoStandardVelocity.h +++ b/eo/src/eoStandardVelocity.h @@ -38,7 +38,7 @@ /** Standard velocity performer for particle swarm optimization. Derivated from abstract eoVelocity, * At step t: v(t+1)= w * v(t) + c1 * r1 * ( xbest(t)-x(t) ) + c2 * r2 * ( lbest(t) - x(t) ) -* lbest depends on the topology evolved, when using eoStarTopology, lbest corresponds to the +* lbest depends on the topology evolved, when using eoStarTopology, lbest corresponds to the * global. Otherwise, lbest is a "local best", i.e the best in a neighborhood. * * @ingroup Variators @@ -56,15 +56,15 @@ public: /** Full constructor: Bounds and bound modifier required * @param _topology - The topology to get the global/local/other best * @param _w - The weight factor. - * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - Learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - Learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng */ eoStandardVelocity (eoTopology < POT > & _topology, - const VelocityType & _w, + const VelocityType & _w, const VelocityType & _c1, const VelocityType & _c2, eoRealVectorBounds & _bounds, @@ -82,9 +82,9 @@ public: /** Constructor: No bound updater required <-> fixed bounds * @param _topology - The topology to get the global/local/other best * @param _w - The weight factor. - * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - Learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - Learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -106,8 +106,8 @@ public: /** Constructor: Neither bounds nor bound updater required <-> free velocity * @param _topology - The topology to get the global/local/other best * @param _w - The weight factor. - * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - Learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _c1 - Learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - Learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _gen - The eo random generator, default=rng */ eoStandardVelocity (eoTopology < POT > & _topology, @@ -167,30 +167,29 @@ public: { topology.updateNeighborhood(_po,_indice); } - + //! eoTopology getTopology //! @return topology - eoTopology & getTopology () - { - return topology; - } + eoTopology & getTopology () + { + return topology; + } protected: eoTopology < POT > & topology; - const VelocityType & omega; // social/cognitive coefficient - const VelocityType & c1; // social/cognitive coefficient - const VelocityType & c2; // social/cognitive coefficient - - eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. - eoRealBoundModifier & bndsModifier; + const VelocityType & omega; // social/cognitive coefficient + const VelocityType & c1; // social/cognitive coefficient + const VelocityType & c2; // social/cognitive coefficient + + eoRealVectorBounds bounds; // REAL bounds even if the velocity could be of another type. + 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 eoDummyRealBoundModifier dummyModifier; }; #endif /*EOSTANDARDVELOCITY_H */ - diff --git a/eo/src/eoStarTopology.h b/eo/src/eoStarTopology.h index d491800c..02df64a9 100644 --- a/eo/src/eoStarTopology.h +++ b/eo/src/eoStarTopology.h @@ -91,9 +91,9 @@ public: // update the best fitness of the particle if (_po.fitness() > _po.best()) { - _po.best(_po.fitness()); - for(unsigned i=0;i<_po.size();i++) - _po.bestPositions[i]=_po[i]; + _po.best(_po.fitness()); + for(unsigned i=0;i<_po.size();i++) + _po.bestPositions[i]=_po[i]; } // update the global best if the given particle is "better" if (_po.fitness() > neighborhood.best().fitness()) @@ -109,14 +109,14 @@ public: * @return POT & - The best particle in the neighborhood of the particle whose indice is _indice */ POT & best (unsigned _indice) {return (neighborhood.best());} - + /* - * Return the global best of the topology - */ - - virtual POT & globalBest(const eoPop& _pop) + * Return the global best of the topology + */ + + virtual POT & globalBest(const eoPop& _pop) { - return neighborhood.best(); + return neighborhood.best(); } @@ -139,11 +139,3 @@ protected: }; #endif /*EOSTARTOPOLOGY_H_ */ - - - - - - - - diff --git a/eo/src/eoSteadyFitContinue.h b/eo/src/eoSteadyFitContinue.h index 7e5c8e21..229d93bc 100644 --- a/eo/src/eoSteadyFitContinue.h +++ b/eo/src/eoSteadyFitContinue.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoSteadyFitContinue.h // (c) GeNeura Team, 1999, Marc Schoenauer, 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -28,9 +28,9 @@ #include #include -/** +/** A continuator: does a minimum number of generations, then - stops whenever a given number of generations takes place without improvement + stops whenever a given number of generations takes place without improvement @ingroup Continuators */ @@ -45,10 +45,10 @@ public: : repMinGenerations( _minGens ), repSteadyGenerations( _steadyGens), steadyState(false), thisGenerationPlaceHolder(0), thisGeneration(thisGenerationPlaceHolder){}; - + /// Ctor for enabling the save/load the no. of generations counted eoSteadyFitContinue( unsigned long _minGens, unsigned long _steadyGen, - unsigned long& _currentGen) + unsigned long& _currentGen) : repMinGenerations( _minGens ), repSteadyGenerations( _steadyGen), steadyState(_currentGen>_minGens), thisGenerationPlaceHolder(0), thisGeneration(_currentGen){}; @@ -57,54 +57,54 @@ public: * reached withtout improvement */ virtual bool operator() ( const eoPop& _vEO ) { thisGeneration++; - + Fitness bestCurrentFitness = _vEO.nth_element_fitness(0); - if (steadyState) { // already after MinGenenerations + if (steadyState) { // already after MinGenenerations if (bestCurrentFitness > bestSoFar) { - bestSoFar = bestCurrentFitness; - lastImprovement = thisGeneration; + bestSoFar = bestCurrentFitness; + lastImprovement = thisGeneration; } else { - if (thisGeneration - lastImprovement > repSteadyGenerations) { - eo::log << eo::progress << "STOP in eoSteadyFitContinue: Done " << repSteadyGenerations - << " generations without improvement\n"; - return false; - } - } - } else { // not yet in steady state + if (thisGeneration - lastImprovement > repSteadyGenerations) { + eo::log << eo::progress << "STOP in eoSteadyFitContinue: Done " << repSteadyGenerations + << " generations without improvement\n"; + return false; + } + } + } else { // not yet in steady state if (thisGeneration > repMinGenerations) { // go to steady state - steadyState = true; - bestSoFar = bestCurrentFitness; - lastImprovement = thisGeneration; + steadyState = true; + bestSoFar = bestCurrentFitness; + lastImprovement = thisGeneration; eo::log << eo::progress << "eoSteadyFitContinue: Done the minimum number of generations\n"; } } return true; } - /** Sets the parameters (minimum nb of gen. + steady nb of gen.) + /** Sets the parameters (minimum nb of gen. + steady nb of gen.) and sets the current generation to 0 (the begin) - + @todo replace thi by an init method ? */ - virtual void totalGenerations( unsigned long _mg, unsigned long _sg ) { - repMinGenerations = _mg; + virtual void totalGenerations( unsigned long _mg, unsigned long _sg ) { + repMinGenerations = _mg; repSteadyGenerations = _sg; reset(); }; - /// Resets the state after it's been reached + /// Resets the state after it's been reached virtual void reset () { steadyState=false; thisGeneration = 0; } /** accessors*/ - virtual unsigned long minGenerations( ) - { return repMinGenerations; }; - virtual unsigned long steadyGenerations( ) - { return repSteadyGenerations; }; - + virtual unsigned long minGenerations( ) + { return repMinGenerations; }; + virtual unsigned long steadyGenerations( ) + { return repSteadyGenerations; }; + virtual std::string className(void) const { return "eoSteadyFitContinue"; } private: unsigned long repMinGenerations; @@ -117,4 +117,3 @@ private: }; #endif - diff --git a/eo/src/eoStochTournamentSelect.h b/eo/src/eoStochTournamentSelect.h index 952041e1..65004129 100644 --- a/eo/src/eoStochTournamentSelect.h +++ b/eo/src/eoStochTournamentSelect.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoStochTournamentSelect.h // (c) GeNeura Team, 1998 - EEAAX 1999 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -31,9 +31,9 @@ #include // stochastic_tournament /** eoStochTournamentSelect: a selection method that selects ONE individual by - binary stochastic tournament - -MS- 24/10/99 - + binary stochastic tournament + -MS- 24/10/99 + @ingroup Selectors */ template class eoStochTournamentSelect: public eoSelectOne @@ -41,7 +41,7 @@ template class eoStochTournamentSelect: public eoSelectOne public: /// - eoStochTournamentSelect(double _Trate = 1.0 ) : eoSelectOne(), Trate(_Trate) + eoStochTournamentSelect(double _Trate = 1.0 ) : eoSelectOne(), Trate(_Trate) { // consistency checks if (Trate < 0.5) { @@ -53,16 +53,15 @@ template class eoStochTournamentSelect: public eoSelectOne Trate = 1; } } - + /** Perform the stochastic tournament */ - virtual const EOT& operator()(const eoPop& pop) + virtual const EOT& operator()(const eoPop& pop) { return stochastic_tournament(pop, Trate); } - + private: double Trate; }; #endif - diff --git a/eo/src/eoStochasticUniversalSelect.h b/eo/src/eoStochasticUniversalSelect.h index 003c7012..fb1669ec 100644 --- a/eo/src/eoStochasticUniversalSelect.h +++ b/eo/src/eoStochasticUniversalSelect.h @@ -59,7 +59,7 @@ public: cumulative[0] = _pop[0].fitness(); for (unsigned i = 1; i < _pop.size(); ++i) { - cumulative[i] = _pop[i].fitness() + cumulative[i-1]; + cumulative[i] = _pop[i].fitness() + cumulative[i-1]; } indices.reserve(_pop.size()); @@ -72,19 +72,19 @@ public: while (indices.size() < _pop.size()) { - while (cumulative[i] < fortune) {i++;} // linear search is good enough as we average one step each time + while (cumulative[i] < fortune) {i++;} // linear search is good enough as we average one step each time - indices.push_back(i); - fortune += step; - if (fortune >= cumulative.back()) { // start at the beginning - fortune -= cumulative.back(); - i = 0; - } + indices.push_back(i); + fortune += step; + if (fortune >= cumulative.back()) { // start at the beginning + fortune -= cumulative.back(); + i = 0; + } } // shuffle for (int i = indices.size() - 1; i > 0; --i) { - int j = rng.random(i+1); - std::swap(indices[i], indices[j]); + int j = rng.random(i+1); + std::swap(indices[i], indices[j]); } } diff --git a/eo/src/eoSurviveAndDie.h b/eo/src/eoSurviveAndDie.h index 3650a536..63cf2219 100644 --- a/eo/src/eoSurviveAndDie.h +++ b/eo/src/eoSurviveAndDie.h @@ -59,8 +59,8 @@ class eoSurviveAndDie : public eoBF &, eoPop &, void> { public: eoSurviveAndDie(double _survive, double _die, bool _interpret_as_rate = true): - howmanySurvive(_survive, _interpret_as_rate), - howmanyDie(_die, _interpret_as_rate) + howmanySurvive(_survive, _interpret_as_rate), + howmanyDie(_die, _interpret_as_rate) {} protected: @@ -90,33 +90,33 @@ public: void operator()(eoPop & _pop, eoPop & _luckyGuys) { - unsigned pSize = _pop.size(); - unsigned nbSurvive = howmanySurvive(pSize); - // first, save the best into _luckyGuys - if (nbSurvive) - { - _pop.nth_element(nbSurvive); - // copy best - _luckyGuys.resize(nbSurvive); - std::copy(_pop.begin(), _pop.begin()+nbSurvive, _luckyGuys.begin()); - // erase them from pop - _pop.erase(_pop.begin(), _pop.begin()+nbSurvive); - } - unsigned nbRemaining = _pop.size(); + unsigned pSize = _pop.size(); + unsigned nbSurvive = howmanySurvive(pSize); + // first, save the best into _luckyGuys + if (nbSurvive) + { + _pop.nth_element(nbSurvive); + // copy best + _luckyGuys.resize(nbSurvive); + std::copy(_pop.begin(), _pop.begin()+nbSurvive, _luckyGuys.begin()); + // erase them from pop + _pop.erase(_pop.begin(), _pop.begin()+nbSurvive); + } + unsigned nbRemaining = _pop.size(); - // carefull, we can have a rate of 1 if we want to kill all remaining - unsigned nbDie = std::min(howmanyDie(pSize), pSize-nbSurvive); - if (nbDie > nbRemaining) - throw std::logic_error("eoDeterministicSurviveAndDie: Too many to kill!\n"); + // carefull, we can have a rate of 1 if we want to kill all remaining + unsigned nbDie = std::min(howmanyDie(pSize), pSize-nbSurvive); + if (nbDie > nbRemaining) + throw std::logic_error("eoDeterministicSurviveAndDie: Too many to kill!\n"); - if (!nbDie) - { - return; - } - // else - // kill the worse nbDie - _pop.nth_element(nbRemaining-nbDie); - _pop.resize(nbRemaining-nbDie); + if (!nbDie) + { + return; + } + // else + // kill the worse nbDie + _pop.nth_element(nbRemaining-nbDie); + _pop.resize(nbRemaining-nbDie); } }; @@ -139,45 +139,45 @@ class eoDeterministicSaDReplacement : public eoReplacement public: /** Constructor with reduce */ eoDeterministicSaDReplacement(eoReduce& _reduceGlobal, - double _surviveParents, double _dieParents=0, - double _surviveOffspring=0, double _dieOffspring=0, - bool _interpret_as_rate = true ) : - reduceGlobal(_reduceGlobal), - sAdParents(_surviveParents, _dieParents, _interpret_as_rate), - sAdOffspring(_surviveOffspring, _dieOffspring, _interpret_as_rate) + double _surviveParents, double _dieParents=0, + double _surviveOffspring=0, double _dieOffspring=0, + bool _interpret_as_rate = true ) : + reduceGlobal(_reduceGlobal), + sAdParents(_surviveParents, _dieParents, _interpret_as_rate), + sAdOffspring(_surviveOffspring, _dieOffspring, _interpret_as_rate) {} /** Constructor with default truncate used as reduce */ eoDeterministicSaDReplacement( - double _surviveParents, double _dieParents=0, - double _surviveOffspring=0, double _dieOffspring=0, - bool _interpret_as_rate = true ) : - reduceGlobal(truncate), - sAdParents(_surviveParents, _dieParents, _interpret_as_rate), - sAdOffspring(_surviveOffspring, _dieOffspring, _interpret_as_rate) + double _surviveParents, double _dieParents=0, + double _surviveOffspring=0, double _dieOffspring=0, + bool _interpret_as_rate = true ) : + reduceGlobal(truncate), + sAdParents(_surviveParents, _dieParents, _interpret_as_rate), + sAdOffspring(_surviveOffspring, _dieOffspring, _interpret_as_rate) {} void operator()(eoPop& _parents, eoPop& _offspring) { - unsigned pSize = _parents.size(); // target number of individuals + unsigned pSize = _parents.size(); // target number of individuals - eoPop luckyParents; // to hold the absolute survivors - sAdParents(_parents, luckyParents); + eoPop luckyParents; // to hold the absolute survivors + sAdParents(_parents, luckyParents); - eoPop luckyOffspring; // to hold the absolute survivors - sAdOffspring(_offspring, luckyOffspring); + eoPop luckyOffspring; // to hold the absolute survivors + sAdOffspring(_offspring, luckyOffspring); - unsigned survivorSize = luckyOffspring.size() + luckyParents.size(); - if (survivorSize > pSize) - throw std::logic_error("eoGeneralReplacement: More survivors than parents!\n"); + unsigned survivorSize = luckyOffspring.size() + luckyParents.size(); + if (survivorSize > pSize) + throw std::logic_error("eoGeneralReplacement: More survivors than parents!\n"); - plus(_parents, _offspring); // all that remain in _offspring + plus(_parents, _offspring); // all that remain in _offspring - reduceGlobal(_offspring, pSize - survivorSize); - plus(luckyParents, _offspring); - plus(luckyOffspring, _offspring); + reduceGlobal(_offspring, pSize - survivorSize); + plus(luckyParents, _offspring); + plus(luckyOffspring, _offspring); - _parents.swap(_offspring); + _parents.swap(_offspring); } @@ -195,4 +195,3 @@ private : /** @} */ #endif - diff --git a/eo/src/eoSwapMutation.h b/eo/src/eoSwapMutation.h index 63169a9b..58d3cf60 100644 --- a/eo/src/eoSwapMutation.h +++ b/eo/src/eoSwapMutation.h @@ -4,7 +4,7 @@ // eoSwapMutation.h // (c) GeNeura Team, 2000 - EEAAX 2000 - Maarten Keijzer 2000 // (c) INRIA Futurs - Dolphin Team - Thomas Legrand 2007 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -20,7 +20,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: todos@geneura.ugr.es, http://geneura.ugr.es - thomas.legrand@lifl.fr + thomas.legrand@lifl.fr Marc.Schoenauer@polytechnique.fr mak@dhi.dk */ @@ -40,15 +40,15 @@ template class eoSwapMutation: public eoMonOp { public: - + /// CTor - eoSwapMutation(const unsigned _howManySwaps=1): howManySwaps(_howManySwaps) + eoSwapMutation(const unsigned _howManySwaps=1): howManySwaps(_howManySwaps) { - // consistency check - if(howManySwaps < 1) - throw std::runtime_error("Invalid number of swaps in eoSwapMutation"); + // consistency check + if(howManySwaps < 1) + throw std::runtime_error("Invalid number of swaps in eoSwapMutation"); } - + /// The class name. virtual std::string className() const { return "eoSwapMutation"; } @@ -58,26 +58,25 @@ template class eoSwapMutation: public eoMonOp */ bool operator()(Chrom& chrom) { - unsigned i, j; - - for(unsigned int swap = 0; swap < howManySwaps; swap++) + unsigned i, j; + + for(unsigned int swap = 0; swap < howManySwaps; swap++) { - // generate two different indices - i=eo::rng.random(chrom.size()); - do j = eo::rng.random(chrom.size()); while (i == j); - - // swap - std::swap(chrom[i],chrom[j]); - } + // generate two different indices + i=eo::rng.random(chrom.size()); + do j = eo::rng.random(chrom.size()); while (i == j); + + // swap + std::swap(chrom[i],chrom[j]); + } return true; } - + private: - unsigned int howManySwaps; + unsigned int howManySwaps; }; /** @example t-eoSwapMutation.cpp */ //----------------------------------------------------------------------------- #endif - diff --git a/eo/src/eoSyncEasyPSO.h b/eo/src/eoSyncEasyPSO.h index aa1c9130..f05f15f6 100644 --- a/eo/src/eoSyncEasyPSO.h +++ b/eo/src/eoSyncEasyPSO.h @@ -34,15 +34,15 @@ //----------------------------------------------------------------------------- /** An easy-to-use synchronous particle swarm algorithm; you can use any particle, -* any flight, any topology... +* any flight, any topology... * * The main steps are : -* - perform a first evaluation of the population -* - for each generation -* - evaluate ALL the velocities -* -- perform the fligth of ALL the particles -* -- evaluate ALL the particles -* -- update the neighborhoods +* - perform a first evaluation of the population +* - for each generation +* - evaluate ALL the velocities +* -- perform the fligth of ALL the particles +* -- evaluate ALL the particles +* -- update the neighborhoods * * @ingroup Algorithms */ @@ -55,7 +55,7 @@ public: * @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system * @param _eval - An eoEvalFunc: the evaluation performer * @param _velocity - An eoVelocity that defines how to compute the velocities - * @param _flight - An eoFlight that defines how to make the particle flying: that means how + * @param _flight - An eoFlight that defines how to make the particle flying: that means how * to modify the positions according to the velocities */ eoSyncEasyPSO ( @@ -117,11 +117,11 @@ public: {} - /** Another constructor without initializer + /** Another constructor without initializer * @param _continuator - An eoContinue that manages the stopping criterion and the checkpointing system * @param _eval - An eoEvalFunc: the evaluation performer * @param _velocity - An eoVelocity that defines how to compute the velocities - * @param _flight - An eoFlight that defines how to make the particle flying: that means how + * @param _flight - An eoFlight that defines how to make the particle flying: that means how * to modify the positions according to the velocities */ eoSyncEasyPSO ( @@ -176,7 +176,7 @@ public: velocity (_velocity), flight (_flight) {} - + /// Apply a few iteration of flight to the population (=swarm). virtual void operator () (eoPop < POT > &_pop) { @@ -185,7 +185,7 @@ public: { // initializes the topology, velocity, best particle(s) init(); - + // just to use a loop eval eoPop empty_pop; @@ -229,29 +229,29 @@ private: eoFlight < POT > &flight; // if the eval does not need to be used, use the dummy eval instance - class eoDummyEval : public eoEvalFunc - { - public: - void operator()(POT &) - {} - } - dummyEval; + class eoDummyEval : public eoEvalFunc + { + public: + void operator()(POT &) + {} + } + dummyEval; + + class eoDummyFlight:public eoFlight < POT > + { + public: + eoDummyFlight () {} + void operator () (POT & _po) {} + }dummyFlight; + + // if the initializer does not need to be used, use the dummy one instead + class eoDummyInitializer:public eoInitializerBase < POT > + { + public: + eoDummyInitializer () {} + void operator () (POT & _po) {} + }dummyInit; - class eoDummyFlight:public eoFlight < POT > - { - public: - eoDummyFlight () {} - void operator () (POT & _po) {} - }dummyFlight; - - // if the initializer does not need to be used, use the dummy one instead - class eoDummyInitializer:public eoInitializerBase < POT > - { - public: - eoDummyInitializer () {} - void operator () (POT & _po) {} - }dummyInit; - }; /** @example t-eoSyncEasyPSO.cpp */ diff --git a/eo/src/eoTopology.h b/eo/src/eoTopology.h index 24bfe851..a12bf43d 100644 --- a/eo/src/eoTopology.h +++ b/eo/src/eoTopology.h @@ -70,9 +70,9 @@ public: virtual POT & best (unsigned ) = 0; - /* - * Return the global best of the topology - */ + /* + * Return the global best of the topology + */ virtual POT & globalBest() = 0; @@ -84,11 +84,3 @@ public: #endif /*EOTOPOLOGY_H_ */ - - - - - - - - diff --git a/eo/src/eoTransform.h b/eo/src/eoTransform.h index 67dd712a..f8823382 100644 --- a/eo/src/eoTransform.h +++ b/eo/src/eoTransform.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoTransform.h + eoTransform.h (c) Maarten Keijzer, GeNeura Team, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -30,7 +30,7 @@ #include //----------------------------------------------------------------------------- -/** +/** eoTransform transforms a population by applying genetic operators on it. @ingroup Combination diff --git a/eo/src/eoTruncSelect.h b/eo/src/eoTruncSelect.h index 8f75e215..e46b39bc 100644 --- a/eo/src/eoTruncSelect.h +++ b/eo/src/eoTruncSelect.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoTruncSelect.h + eoTruncSelect.h (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2002 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -35,7 +35,7 @@ //----------------------------------------------------------------------------- /** eoTruncSelect selects individuals after truncating the population - * using eoSelectOne as it's mechanism. + * using eoSelectOne as it's mechanism. * Therefore eoSelectMany needs an eoSelectOne in its ctor * It will use an eoHowMnay to determine the number of guys to keep, * @@ -46,9 +46,9 @@ class eoTruncSelect : public eoSelect { public: /** Ctor: from an eoSelect (and an eoMany to tell how many are kept for selectino */ - eoTruncSelect(eoSelectOne& _select, eoHowMany _howMany) + eoTruncSelect(eoSelectOne& _select, eoHowMany _howMany) : select(_select), howMany(_howMany) {} - + /** The implementation repeatidly selects an individual @@ -58,15 +58,15 @@ class eoTruncSelect : public eoSelect virtual void operator()(const eoPop& _source, eoPop& _dest) { unsigned target = howMany(_source.size()); - + _dest.resize(target); - + select.setup(_source); - + for (size_t i = 0; i < _dest.size(); ++i) _dest[i] = select(_source); } - + private : eoSelectOne& select; eoHowMany howMany; diff --git a/eo/src/eoTruncatedSelectMany.h b/eo/src/eoTruncatedSelectMany.h index 5e999459..1b3bad72 100644 --- a/eo/src/eoTruncatedSelectMany.h +++ b/eo/src/eoTruncatedSelectMany.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoTruncatedSelectMany.h + eoTruncatedSelectMany.h (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2002 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -35,7 +35,7 @@ #include //----------------------------------------------------------------------------- -/** eoTruncatedSelectMany selects many individuals using eoSelectOne as it's +/** eoTruncatedSelectMany selects many individuals using eoSelectOne as it's mechanism. Therefore eoSelectMany needs an eoSelectOne in its ctor It will use an eoHowMnay to determine the number of guys to select, @@ -43,10 +43,10 @@ And it will only perform selection from the top guys in the population. - It is NOT a special case of eoSelectMany because it needs to SORT + It is NOT a special case of eoSelectMany because it needs to SORT the population to discard the worst guys before doing the selection - However, the same result can be obtained by embedding an + However, the same result can be obtained by embedding an eoTruncatedSelectOne into an eoSelectMany ... @ingroup Selectors @@ -56,19 +56,19 @@ class eoTruncatedSelectMany : public eoSelect { public: /// Ctor - eoTruncatedSelectMany(eoSelectOne& _select, - double _rateGenitors, double _rateFertile, - bool _interpret_as_rateG = true, - bool _interpret_as_rateF = true) - : select(_select), - howManyGenitors(_rateGenitors, _interpret_as_rateG), - howManyFertile(_rateFertile, _interpret_as_rateF) {} + eoTruncatedSelectMany(eoSelectOne& _select, + double _rateGenitors, double _rateFertile, + bool _interpret_as_rateG = true, + bool _interpret_as_rateF = true) + : select(_select), + howManyGenitors(_rateGenitors, _interpret_as_rateG), + howManyFertile(_rateFertile, _interpret_as_rateF) {} // Ctor with eoHowManys - eoTruncatedSelectMany(eoSelectOne& _select, - eoHowMany _howManyGenitors, eoHowMany _howManyFertile) + eoTruncatedSelectMany(eoSelectOne& _select, + eoHowMany _howManyGenitors, eoHowMany _howManyFertile) : select(_select), howManyGenitors(_howManyGenitors), - howManyFertile(_howManyFertile) {} + howManyFertile(_howManyFertile) {} /** The implementation repeatidly selects an individual @@ -87,33 +87,33 @@ class eoTruncatedSelectMany : public eoSelect //revert to standard selection (see eoSelectMany) if no truncation if (nbFertile == _source.size()) { - select.setup(_source); - - for (size_t i = 0; i < _dest.size(); ++i) - _dest[i] = select(_source); + select.setup(_source); + + for (size_t i = 0; i < _dest.size(); ++i) + _dest[i] = select(_source); } else { // at the moment, brute force (rush rush, no good) // what we would need otherwise is a std::vector class // and selectors that act on such a thing - eoPop tmpPop = _source; // hum hum, could be a pain in the ass + eoPop tmpPop = _source; // hum hum, could be a pain in the ass - tmpPop.sort(); // maybe we could only do partial sort? - tmpPop.resize(nbFertile); // only the best guys here now - tmpPop.shuffle(); // as some selectors are order-sensitive + tmpPop.sort(); // maybe we could only do partial sort? + tmpPop.resize(nbFertile); // only the best guys here now + tmpPop.shuffle(); // as some selectors are order-sensitive - select.setup(tmpPop); - - for (size_t i = 0; i < _dest.size(); ++i) - _dest[i] = select(tmpPop); + select.setup(tmpPop); + + for (size_t i = 0; i < _dest.size(); ++i) + _dest[i] = select(tmpPop); } } - + private : - eoSelectOne& select; // selector for one guy - eoHowMany howManyGenitors; // number of guys to select - eoHowMany howManyFertile; // number of fertile guys + eoSelectOne& select; // selector for one guy + eoHowMany howManyGenitors; // number of guys to select + eoHowMany howManyFertile; // number of fertile guys }; #endif diff --git a/eo/src/eoTruncatedSelectOne.h b/eo/src/eoTruncatedSelectOne.h index c0fed203..e86cce81 100644 --- a/eo/src/eoTruncatedSelectOne.h +++ b/eo/src/eoTruncatedSelectOne.h @@ -1,9 +1,9 @@ /** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- ----------------------------------------------------------------------------- - eoTruncatedSelectOne.h + eoTruncatedSelectOne.h (c) Maarten Keijzer, Marc Schoenauer, GeNeura Team, 2002 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -35,7 +35,7 @@ #include //----------------------------------------------------------------------------- -/** eoTruncatedSelectOne selects one individual using eoSelectOne as it's +/** eoTruncatedSelectOne selects one individual using eoSelectOne as it's mechanism. Therefore eoTruncatedSelectOne needs an eoSelectOne in its ctor It will perform selection only from the top guys in the population. @@ -47,17 +47,17 @@ class eoTruncatedSelectOne : public eoSelectOne { public: /** Ctor from rate and bool */ - eoTruncatedSelectOne(eoSelectOne& _select, - double _rateFertile, - bool _interpret_as_rateF = true) - : select(_select), + eoTruncatedSelectOne(eoSelectOne& _select, + double _rateFertile, + bool _interpret_as_rateF = true) + : select(_select), howManyFertile(_rateFertile, _interpret_as_rateF), tmpPop(), actualPop(tmpPop) {} /** Ctor with eoHowMany */ - eoTruncatedSelectOne(eoSelectOne& _select, - eoHowMany _howManyFertile) + eoTruncatedSelectOne(eoSelectOne& _select, + eoHowMany _howManyFertile) : select(_select), howManyFertile(_howManyFertile), tmpPop(), actualPop(tmpPop) {} @@ -69,19 +69,19 @@ public: unsigned fertile = howManyFertile(_source.size()); if (fertile == _source.size()) // noting to do, all are fertile { - actualPop = _source; + actualPop = _source; } else { - // copy only best ferile to actualPop - tmpPop.resize(fertile); - std::vector result; - _source.nth_element(fertile, result); - for (unsigned i=0; i result; + _source.nth_element(fertile, result); + for (unsigned i=0; i& _pop) + const EOT& operator()(const eoPop& _pop) { return select(actualPop); } private : - eoSelectOne& select; // selector for one guy - eoHowMany howManyFertile; // number of fertile guys - eoPop tmpPop; // intermediate population - fertile guys - eoPop & actualPop; // to avoid copies when 100% fertility + eoSelectOne& select; // selector for one guy + eoHowMany howManyFertile; // number of fertile guys + eoPop tmpPop; // intermediate population - fertile guys + eoPop & actualPop; // to avoid copies when 100% fertility }; #endif diff --git a/eo/src/eoVariableInertiaWeightedVelocity.h b/eo/src/eoVariableInertiaWeightedVelocity.h index d281b39d..a926feee 100644 --- a/eo/src/eoVariableInertiaWeightedVelocity.h +++ b/eo/src/eoVariableInertiaWeightedVelocity.h @@ -56,9 +56,9 @@ public: /** Full constructor: Bounds and bound modifier required * @param _topology - The topology to get the global/local/other best * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _bndsModifier - An eoRealBoundModifier used to modify the bounds (for real bounds only). * @param _gen - The eo random generator, default=rng @@ -82,9 +82,9 @@ public: /** Constructor: No bound updater required <-> fixed bounds * @param _topology - The topology to get the global/local/other best * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType - * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _bounds - An eoRealBaseVectorBounds: real bounds for real velocities. * If the velocities are not real, they won't be bounded by default. Should have a eoBounds ? * @param _gen - The eo random generator, default=rng */ @@ -106,8 +106,8 @@ public: /** Constructor: Neither bounds nor bound updater required <-> free velocity * @param _topology - The topology to get the global/local/other best * @param _weightUpdater - An eoWeightUpdater used to update the inertia weight - * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType - * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType + * @param _c1 - The first learning factor used for the particle's best. Type must be POT::ParticleVelocityType + * @param _c2 - The second learning factor used for the local/global best(s). Type must be POT::ParticleVelocityType * @param _gen - The eo random generator, default=rng */ eoVariableInertiaWeightedVelocity (eoTopology < POT > & _topology, @@ -126,7 +126,7 @@ public: /** * Evaluate the new velocities of the given particle. Need an indice to identify the particle - * into the topology. Steps are : + * into the topology. Steps are : * - evaluate r1 and r2, the customed learning factors * - adjust the size of the bounds (even if dummy) * - update the weight with the weightUpdater (use the dummy updater if there's no updater provided) @@ -181,19 +181,18 @@ public: protected: eoTopology < POT > & topology; - eoWeightUpdater & weightUpdater; // the updater used to make the weight evoluate - const VelocityType & c1; // learning factor 1 - const VelocityType & c2; // learning factor 2 - - eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. + eoWeightUpdater & weightUpdater; // the updater used to make the weight evoluate + const VelocityType & c1; // learning factor 1 + const VelocityType & c2; // learning factor 2 + + eoRealVectorBounds & bounds; // REAL bounds even if the velocity could be of another type. eoRealBoundModifier & bndsModifier; - + VelocityType weight; - eoRng & gen; // the random generator + eoRng & gen; // the random generator // If the bound modifier doesn't need to be used, use the dummy instance eoDummyRealBoundModifier dummyModifier; }; #endif /*EOVARIABLEINERTIAWEIGHTEDVELOCITY_H*/ - diff --git a/eo/src/eoVariableLengthCrossover.h b/eo/src/eoVariableLengthCrossover.h index 5ad6de05..510fc9b0 100644 --- a/eo/src/eoVariableLengthCrossover.h +++ b/eo/src/eoVariableLengthCrossover.h @@ -66,7 +66,7 @@ public: { mask.resize(_size1 + _size2); for (unsigned i=0; i<_size1+_size2; i++) - mask[i]=eo::rng.flip(rate); + mask[i]=eo::rng.flip(rate); } /** the operator() simply returns the mask booleans in turn */ @@ -98,12 +98,12 @@ public : /** default ctor: requires bounds on number of genes + a rate */ eoVlAtomExchangeQuadOp(unsigned _Min, unsigned _Max, - eoAtomExchange& _atomExchange): + eoAtomExchange& _atomExchange): Min(_Min), Max(_Max), atomExchange(_atomExchange) {} bool operator()(EOT & _eo1, EOT & _eo2) { - EOT tmp1, tmp2; // empty individuals + EOT tmp1, tmp2; // empty individuals unsigned index=0; // main loop: until sizes are OK, do only simulated exchange unsigned i, i1, i2; @@ -113,47 +113,47 @@ public : // simulate crossover i1=i2=0; for (i=0; i<_eo1.size(); i++) - { - if (atomExchange(i, _eo1[i])) - i1++; - else - i2++; - } + { + if (atomExchange(i, _eo1[i])) + i1++; + else + i2++; + } for (i=0; i<_eo2.size(); i++) - { - if (atomExchange(i, _eo2[i])) - i2++; - else - i1++; - } + { + if (atomExchange(i, _eo2[i])) + i2++; + else + i1++; + } index++; } while ( ( (i1Max) || (i2>Max) ) - && (index<10000) ); + (i1>Max) || (i2>Max) ) + && (index<10000) ); if (index >= 10000) { eo::log << eo::warnings << "Warning: impossible to generate individual of the right size in 10000 trials" << std::endl; - return false; + return false; } // here we know we have the right sizes: do the actual exchange for (i=0; i<_eo1.size(); i++) - { - if (atomExchange(i, _eo1[i])) - tmp1.push_back(_eo1[i]); - else - tmp2.push_back(_eo1[i]); - } + { + if (atomExchange(i, _eo1[i])) + tmp1.push_back(_eo1[i]); + else + tmp2.push_back(_eo1[i]); + } for (i=0; i<_eo2.size(); i++) - { - if (atomExchange(i, _eo2[i])) - tmp2.push_back(_eo2[i]); - else - tmp1.push_back(_eo2[i]); - } + { + if (atomExchange(i, _eo2[i])) + tmp2.push_back(_eo2[i]); + else + tmp1.push_back(_eo2[i]); + } // and put everything back in place _eo1.swap(tmp1); _eo2.swap(tmp2); - return true; // should we test that? Yes, but no time now + return true; // should we test that? Yes, but no time now } /** the inherited className */ @@ -190,11 +190,11 @@ public : bool changed = false; for ( unsigned i = 0; i < minsize; i ++ ) { if ( rng.flip( rate ) ) { - bool changedHere = op( _eo1[i], _eo2[i] ); - changed |= changedHere; + bool changedHere = op( _eo1[i], _eo2[i] ); + changed |= changedHere; } } - return changed; // should we test that? Yes, but no time now + return changed; // should we test that? Yes, but no time now } virtual std::string className() const @@ -237,34 +237,34 @@ public : unsigned index=0; do { for (i=0; i<_eo1.size(); i++) - { - if (eo::rng.flip(rate)) - tmp1.push_back(_eo1[i]); - else - tmp2.push_back(_eo1[i]); - // here we should look for _eo1[i] inside _eo2 and erase it if found! - } + { + if (eo::rng.flip(rate)) + tmp1.push_back(_eo1[i]); + else + tmp2.push_back(_eo1[i]); + // here we should look for _eo1[i] inside _eo2 and erase it if found! + } for (i=0; i<_eo2.size(); i++) - { - if (eo::rng.flip(rate)) - tmp1.push_back(_eo2[i]); - else - tmp2.push_back(_eo2[i]); - } + { + if (eo::rng.flip(rate)) + tmp1.push_back(_eo2[i]); + else + tmp2.push_back(_eo2[i]); + } index++; } while ( ( (tmp1.size()Max) || (tmp2.size()>Max) ) - && (index<10000) ); + (tmp1.size()>Max) || (tmp2.size()>Max) ) + && (index<10000) ); //! @todo FIXME bad hardcoded limit, should use an algorithm that guarantee a correct size in a finite number of tries if (index >= 10000) { eo::log << eo::warnings << "Warning: impossible to generate individual of the right size in 10000 trials" << std::endl; - return false; + return false; } _eo1.swap(tmp1); _eo2.swap(tmp2); - return true; // should we test that? + return true; // should we test that? } private: unsigned Min, Max; @@ -300,47 +300,47 @@ public : unsigned index=0; do { for (i=0; i<_eo1.size(); i++) - { - if (eo::rng.flip(rate)) - { - tmp1.push_back(_eo1[i]); - tmpIsTwo = false; - } - else - tmpIsOne=false; - // we should look for _eo1[i] inside _eo2 and erase it there if found! - } + { + if (eo::rng.flip(rate)) + { + tmp1.push_back(_eo1[i]); + tmpIsTwo = false; + } + else + tmpIsOne=false; + // we should look for _eo1[i] inside _eo2 and erase it there if found! + } for (i=0; i<_eo2.size(); i++) - { - if (! eo::rng.flip(rate)) - { - tmp1.push_back(_eo2[i]); - tmpIsOne = false; - } - else - tmpIsTwo = false; - } + { + if (! eo::rng.flip(rate)) + { + tmp1.push_back(_eo2[i]); + tmpIsOne = false; + } + else + tmpIsTwo = false; + } index++; } while ( ( (tmp1.size()Max) ) - && (index<10000) ); + && (index<10000) ); // this while condition is not optimal, as it may take some time, see the FIXME above if (index >= 10000) { eo::log << eo::warnings << "Warning: impossible to generate individual of the right size in 10000 trials" << std::endl; - return false; + return false; } _eo1.swap(tmp1); if (tmpIsTwo) { - // _eo1.fitness(_eo2.fitness()); NO FITNESS EXISTS HERE! - return false; + // _eo1.fitness(_eo2.fitness()); NO FITNESS EXISTS HERE! + return false; } - if (tmpIsOne) // already has the right fitness - { // WRONG: NO FITNESS EXISTS HERE! - return false; + if (tmpIsOne) // already has the right fitness + { // WRONG: NO FITNESS EXISTS HERE! + return false; } - return true; // there were some modifications... + return true; // there were some modifications... } private: @@ -350,4 +350,3 @@ private: /** @} */ #endif - diff --git a/eo/src/eoVariableLengthMutation.h b/eo/src/eoVariableLengthMutation.h index aad778ba..542541d7 100644 --- a/eo/src/eoVariableLengthMutation.h +++ b/eo/src/eoVariableLengthMutation.h @@ -66,7 +66,7 @@ public : bool operator()(EOT & _eo) { if (_eo.size() >= nMax) - return false; // unmodifed + return false; // unmodifed AtomType atom; atomInit(atom); unsigned pos = rng.random(_eo.size()+1); @@ -100,7 +100,7 @@ public: eoUniformGeneChooser(){} unsigned operator()(EOT & _eo) { - return eo::rng.random(_eo.size()); + return eo::rng.random(_eo.size()); } virtual std::string className() const { return "eoUniformGeneChooser"; } }; @@ -137,7 +137,7 @@ public : bool operator()(EOT & _eo) { if (_eo.size() <= nMin) - return false; // unmodifed + return false; // unmodifed unsigned pos = chooser(_eo); _eo.erase(_eo.begin()+pos); return true; @@ -158,4 +158,3 @@ private: /** @} */ #endif - diff --git a/eo/src/eoVector.h b/eo/src/eoVector.h index 0e1b6d91..fce05d11 100644 --- a/eo/src/eoVector.h +++ b/eo/src/eoVector.h @@ -82,9 +82,9 @@ public: // with the copy Ctor void value(const std::vector& _v) { - if (_v.size() != size()) // safety check + if (_v.size() != size()) // safety check { - if (size()) // NOT an initial empty std::vector + if (size()) // NOT an initial empty std::vector eo::log << eo::warnings << "Warning: Changing size in eoVector assignation" << std::endl; resize(_v.size()); } diff --git a/eo/src/eoVectorParticle.h b/eo/src/eoVectorParticle.h index 4736639a..25cfcc9f 100644 --- a/eo/src/eoVectorParticle.h +++ b/eo/src/eoVectorParticle.h @@ -124,14 +124,14 @@ public: { velocities.resize (_size); } - + /// to avoid conflicts between EA and PSO bool operator<(const eoVectorParticle& _eo) const { - if (_eo.best() > this->best()) - return true; - else - return false; + if (_eo.best() > this->best()) + return true; + else + return false; } /** @@ -139,10 +139,10 @@ public: */ virtual void printOn(std::ostream& os) const { - PO::printOn(os); - os << ' '; - os << size() << ' '; - std::copy(bestPositions.begin(), bestPositions.end(), std::ostream_iterator(os, " ")); + PO::printOn(os); + os << ' '; + os << size() << ' '; + std::copy(bestPositions.begin(), bestPositions.end(), std::ostream_iterator(os, " ")); } /* public attributes */ diff --git a/eo/src/eoVelocity.h b/eo/src/eoVelocity.h index 5d4bdcd2..753c6af2 100644 --- a/eo/src/eoVelocity.h +++ b/eo/src/eoVelocity.h @@ -71,11 +71,10 @@ public: } } - - + + virtual eoTopology & getTopology () = 0; }; #endif /*EOVELOCITY_H_H */ - diff --git a/eo/src/eoVelocityInit.h b/eo/src/eoVelocityInit.h index 4a096f4c..8c57a689 100644 --- a/eo/src/eoVelocityInit.h +++ b/eo/src/eoVelocityInit.h @@ -64,7 +64,7 @@ public: init (p); return (p); } - + private: eoVelocityInit < POT > &init; }; @@ -144,4 +144,3 @@ private: #endif /*EOVELOCITYINIT_H */ /** @} */ - diff --git a/eo/src/eoWeightUpdater.h b/eo/src/eoWeightUpdater.h index 65619016..d4970eca 100644 --- a/eo/src/eoWeightUpdater.h +++ b/eo/src/eoWeightUpdater.h @@ -30,7 +30,7 @@ //----------------------------------------------------------------------------- /** - * Abstract class for (inertia) weight updater (particle swarm optimization). + * Abstract class for (inertia) weight updater (particle swarm optimization). * Used inside classes extending eoVelocity. * * @ingroup Core diff --git a/eo/src/es.h b/eo/src/es.h index 17545f3e..d5dffc2f 100644 --- a/eo/src/es.h +++ b/eo/src/es.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // es.h // (c) GeNeura Team 1998 - Maarten Keijzer 2000 - Marc Schoenauer 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -20,21 +20,21 @@ Contact: Marc.Schoenauer@polytechnique.fr mak@dhi.dk - todos@geneura.ugr.es, http://geneura.ugr.es + todos@geneura.ugr.es, http://geneura.ugr.es */ //----------------------------------------------------------------------------- #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #ifndef _es_h #define _es_h // contains the include specific to real representations, i.e. in src/es dir //----------------------------------------------------------------------------- - + // the genotypes - from plain std::vector to full correlated mutation #include #include diff --git a/eo/src/es/CMAParams.cpp b/eo/src/es/CMAParams.cpp index 1ded097d..131edb72 100644 --- a/eo/src/es/CMAParams.cpp +++ b/eo/src/es/CMAParams.cpp @@ -1,4 +1,3 @@ - /* * C++ification of Nikolaus Hansen's original C-source code for the * CMA-ES @@ -7,7 +6,7 @@ * the LGPL. Original copyright of Nikolaus Hansen can be found below * * - * + * */ /* --------------------------------------------------------- */ @@ -30,7 +29,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * + * * */ /* --- Changes : --- * 03/03/21: argument const double *rgFunVal of @@ -54,138 +53,138 @@ using namespace std; namespace eo { CMAParams::CMAParams(eoParser& parser, unsigned dimensionality) { - + string section = "CMA parameters"; - + n = parser.createParam(dimensionality, "dimensionality", "Dimensionality (N) of the problem", 'N', section, dimensionality == 0).value(); - + maxgen = parser.createParam( - 1000, - "max-gen", - "Maximum number of generations that the system will run (needed for damping)", - 'M', - section).value(); - - + 1000, + "max-gen", + "Maximum number of generations that the system will run (needed for damping)", + 'M', + section).value(); + + if (n == 0) { - return; + return; } - + defaults(n, maxgen); - + /* handle lambda */ lambda = parser.createParam( - lambda, - "lambda", - "Number of offspring", - 'l', - section).value(); + lambda, + "lambda", + "Number of offspring", + 'l', + section).value(); if (lambda < 2) { - lambda = 4+(int)(3*log((double) n)); - cerr << "Too small lambda specified, setting it to " << lambda << endl; + lambda = 4+(int)(3*log((double) n)); + cerr << "Too small lambda specified, setting it to " << lambda << endl; } - + /* handle mu */ mu = parser.createParam( - mu, - "mu", - "Population size", - 'm', - section).value(); + mu, + "mu", + "Population size", + 'm', + section).value(); if (mu >= lambda) { - mu = lambda/2; - cerr << "Mu set larger/equal to lambda, setting it to " << mu << endl; + mu = lambda/2; + cerr << "Mu set larger/equal to lambda, setting it to " << mu << endl; } - + /* handle selection weights */ - + int weight_type = parser.createParam( - 0, - "weighting", - "Weighting scheme (for 'selection'): 0 = logarithmic, 1 = equal, 2 = linear", - 'w', - section).value(); + 0, + "weighting", + "Weighting scheme (for 'selection'): 0 = logarithmic, 1 = equal, 2 = linear", + 'w', + section).value(); switch (weight_type) { - case 1: - { - for (unsigned i = 0; i < weights.size(); ++i) { - weights[i] = mu - i; - } - } - case 2: - { - weights = 1.; - } - default : - { - for (unsigned i = 0; i < weights.size(); ++i) { - weights[i] = log(mu+1.)-log(i+1.); - } - } - + case 1: + { + for (unsigned i = 0; i < weights.size(); ++i) { + weights[i] = mu - i; + } + } + case 2: + { + weights = 1.; + } + default : + { + for (unsigned i = 0; i < weights.size(); ++i) { + weights[i] = log(mu+1.)-log(i+1.); + } + } + } /* Normalize weights and set mu_eff */ double sumw = weights.sum(); mueff = sumw * sumw / (weights * weights).sum(); weights /= sumw; - + /* most of the rest depends on mu_eff, so needs to be set again */ - + /* set the others using Nikolaus logic. If you want to tweak, you can parameterize over these defaults */ mucov = mueff; ccumsig = (mueff + 2.) / (n + mueff + 3.); ccumcov = 4. / (n + 4); - + double t1 = 2. / ((n+1.4142)*(n+1.4142)); double t2 = (2.*mucov-1.) / ((n+2.)*(n+2.)+mucov); t2 = (t2 > 1) ? 1 : t2; t2 = (1./mucov) * t1 + (1.-1./mucov) * t2; - + ccov = t2; damp = 1 + std::max(0.3,(1.-(double)n/(double)maxgen)) - * (1+2*std::max(0.,sqrt((mueff-1.)/(n+1.))-1)) /* limit sigma increase */ - / ccumsig; - + * (1+2*std::max(0.,sqrt((mueff-1.)/(n+1.))-1)) /* limit sigma increase */ + / ccumsig; + vector mins(1,0.0); mins = parser.createParam( - mins, - "min-stdev", - "Array of minimum stdevs, last one will apply for all remaining axes", - 0, - section).value(); - + mins, + "min-stdev", + "Array of minimum stdevs, last one will apply for all remaining axes", + 0, + section).value(); + if (mins.size() > n) mins.resize(n); if (mins.size()) { - minStdevs = mins.back(); - for (unsigned i = 0; i < mins.size(); ++i) { - minStdevs[i] = mins[i]; - } + minStdevs = mins.back(); + for (unsigned i = 0; i < mins.size(); ++i) { + minStdevs[i] = mins[i]; + } } - + vector inits(1,0.3); inits = parser.createParam( - inits, - "init-stdev", - "Array of initial stdevs, last one will apply for all remaining axes", - 0, - section).value(); - + inits, + "init-stdev", + "Array of initial stdevs, last one will apply for all remaining axes", + 0, + section).value(); + if (inits.size() > n) inits.resize(n); if (inits.size()) { - initialStdevs = inits.back(); - for (unsigned i = 0; i < inits.size(); ++i) { - initialStdevs[i] = inits[i]; - } + initialStdevs = inits.back(); + for (unsigned i = 0; i < inits.size(); ++i) { + initialStdevs[i] = inits[i]; + } } - + } void CMAParams::defaults(unsigned n_, unsigned maxgen_) { @@ -194,39 +193,39 @@ void CMAParams::defaults(unsigned n_, unsigned maxgen_) { lambda = 4+(int)(3*log((double) n)); mu = lambda / 2; - + weights.resize(mu); - + for (unsigned i = 0; i < weights.size(); ++i) { - weights[i] = log(mu+1.)-log(i+1.); + weights[i] = log(mu+1.)-log(i+1.); } - + /* Normalize weights and set mu_eff */ double sumw = weights.sum(); mueff = sumw * sumw / (weights * weights).sum(); weights /= sumw; - + mucov = mueff; ccumsig *= (mueff + 2.) / (n + mueff + 3.); ccumcov = 4. / (n + 4); - + double t1 = 2. / ((n+1.4142)*(n+1.4142)); double t2 = (2.*mucov-1.) / ((n+2.)*(n+2.)+mucov); t2 = (t2 > 1) ? 1 : t2; t2 = (1./mucov) * t1 + (1.-1./mucov) * t2; - + ccov = t2; damp = 1 + std::max(0.3,(1.-(double)n/maxgen)) - * (1+2*std::max(0.,sqrt((mueff-1.)/(n+1.))-1)) /* limit sigma increase */ - / ccumsig; + * (1+2*std::max(0.,sqrt((mueff-1.)/(n+1.))-1)) /* limit sigma increase */ + / ccumsig; minStdevs.resize(n); minStdevs = 0.0; - + initialStdevs.resize(n); initialStdevs = 0.3; - + } diff --git a/eo/src/es/CMAParams.h b/eo/src/es/CMAParams.h index f59d6c92..90586904 100644 --- a/eo/src/es/CMAParams.h +++ b/eo/src/es/CMAParams.h @@ -1,12 +1,12 @@ /* * C++ification of Nikolaus Hansen's original C-source code for the - * CMA-ES. + * CMA-ES. * * Copyright (C) 1996, 2003, Nikolaus Hansen - * (C) 2005, Maarten Keijzer + * (C) 2005, Maarten Keijzer + * + * License: LGPL * - * License: LGPL - * */ #ifndef CMAPARAMS_H__ @@ -18,25 +18,25 @@ class eoParser; namespace eo { class CMAParams { - + public: - + CMAParams() { /* Call this and all values need to be set by hand */ } CMAParams(eoParser& parser, unsigned dimensionality = 0); // 0 dimensionality -> user needs to set it - + void defaults(unsigned n_, unsigned maxgen_); /* apply all defaults using n and maxgen */ - + unsigned n; unsigned maxgen; - + unsigned lambda; /* -> mu */ unsigned mu; /* -> weights, lambda */ - + std::valarray weights; /* <- mu, -> mueff -> mucov -> ccov */ double mueff; /* <- weights */ - + double mucov; - + double damp; /* <- ccumsig, maxeval, lambda */ double ccumsig; /* -> damp, <- N */ double ccumcov; @@ -49,4 +49,3 @@ class CMAParams { } // namespace eo #endif - diff --git a/eo/src/es/CMAState.cpp b/eo/src/es/CMAState.cpp index f44fdf5d..32855243 100644 --- a/eo/src/es/CMAState.cpp +++ b/eo/src/es/CMAState.cpp @@ -10,11 +10,11 @@ * algorithm: * * - Numerical issues are now treated 'before' going into the eigenvector decomposition - * (this was done out of convenience) + * (this was done out of convenience) * - dMaxSignifiKond (smallest x such that x == x + 1.0) replaced by - * numeric_limits::epsilon() (smallest x such that 1.0 != 1.0 + x) - * - * + * numeric_limits::epsilon() (smallest x such that 1.0 != 1.0 + x) + * + * */ /* --------------------------------------------------------- */ @@ -37,7 +37,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * + * * */ /* --- Changes : --- * 03/03/21: argument const double *rgFunVal of @@ -66,289 +66,289 @@ using namespace std; namespace eo { - + struct CMAStateImpl { - + CMAParams p; - + lower_triangular_matrix C; // Covariance matrix square_matrix B; // Eigen vectors (in columns) valarray d; // eigen values (diagonal matrix) valarray pc; // Evolution path valarray ps; // Evolution path for stepsize; - + vector mean; // current mean to sample around double sigma; // global step size - + unsigned gen; vector fitnessHistory; - - + + CMAStateImpl(const CMAParams& params_, const vector& m, double sigma_) : - p(params_), - C(p.n), B(p.n), d(p.n), pc(p.n), ps(p.n), mean(m), sigma(sigma_), - gen(0), fitnessHistory(3) + p(params_), + C(p.n), B(p.n), d(p.n), pc(p.n), ps(p.n), mean(m), sigma(sigma_), + gen(0), fitnessHistory(3) { - double trace = (p.initialStdevs * p.initialStdevs).sum(); - /* Initialize covariance structure */ - for (unsigned i = 0; i < p.n; ++i) - { - B[i][i] = 1.; - d[i] = p.initialStdevs[i] * sqrt(p.n / trace); - C[i][i] = d[i] * d[i]; - pc[i] = 0.; - ps[i] = 0.; - } - + double trace = (p.initialStdevs * p.initialStdevs).sum(); + /* Initialize covariance structure */ + for (unsigned i = 0; i < p.n; ++i) + { + B[i][i] = 1.; + d[i] = p.initialStdevs[i] * sqrt(p.n / trace); + C[i][i] = d[i] * d[i]; + pc[i] = 0.; + ps[i] = 0.; + } + } void sample(vector& v) { - unsigned n = p.n; - v.resize(n); - - vector tmp(n); - for (unsigned i = 0; i < n; ++i) - tmp[i] = d[i] * rng.normal(); - - /* add mutation (sigma * B * (D*z)) */ - for (unsigned i = 0; i < n; ++i) { - double sum = 0; - for (unsigned j = 0; j < n; ++j) { - sum += B[i][j] * tmp[j]; - } - v[i] = mean[i] + sigma * sum; - } + unsigned n = p.n; + v.resize(n); + + vector tmp(n); + for (unsigned i = 0; i < n; ++i) + tmp[i] = d[i] * rng.normal(); + + /* add mutation (sigma * B * (D*z)) */ + for (unsigned i = 0; i < n; ++i) { + double sum = 0; + for (unsigned j = 0; j < n; ++j) { + sum += B[i][j] * tmp[j]; + } + v[i] = mean[i] + sigma * sum; + } } - + void reestimate(const vector* >& pop, double muBest, double muWorst) { - - assert(pop.size() == p.mu); - - unsigned n = p.n; - fitnessHistory[gen % fitnessHistory.size()] = muBest; // needed for divergence check - - vector oldmean = mean; - valarray BDz(n); - - /* calculate xmean and rgBDz~N(0,C) */ - for (unsigned i = 0; i < n; ++i) { - mean[i] = 0.; - for (unsigned j = 0; j < pop.size(); ++j) { - mean[i] += p.weights[j] * (*pop[j])[i]; - } - BDz[i] = sqrt(p.mueff)*(mean[i] - oldmean[i])/sigma; - } + assert(pop.size() == p.mu); - vector tmp(n); - /* calculate z := D^(-1) * B^(-1) * rgBDz into rgdTmp */ - for (unsigned i = 0; i < n; ++i) { - double sum = 0.0; - for (unsigned j = 0; j < n; ++j) { - sum += B[j][i] * BDz[j]; - } - tmp[i] = sum / d[i]; - } + unsigned n = p.n; - /* cumulation for sigma (ps) using B*z */ - for (unsigned i = 0; i < n; ++i) { - double sum = 0.0; - for (unsigned j = 0; j < n; ++j) - sum += B[i][j] * tmp[j]; - - ps[i] = (1. - p.ccumsig) * ps[i] + sqrt(p.ccumsig * (2. - p.ccumsig)) * sum; - } + fitnessHistory[gen % fitnessHistory.size()] = muBest; // needed for divergence check - /* calculate norm(ps)^2 */ - double psxps = (ps * ps).sum(); + vector oldmean = mean; + valarray BDz(n); - - double chiN = sqrt((double) p.n) * (1. - 1./(4.*p.n) + 1./(21.*p.n*p.n)); - /* cumulation for covariance matrix (pc) using B*D*z~N(0,C) */ - double hsig = sqrt(psxps) / sqrt(1. - pow(1.-p.ccumsig, 2.*gen)) / chiN < 1.5 + 1./(p.n-0.5); - - pc = (1. - p.ccumcov) * pc + hsig * sqrt(p.ccumcov * (2. - p.ccumcov)) * BDz; - - /* stop initial phase (MK, this was not reachable in the org code, deleted) */ + /* calculate xmean and rgBDz~N(0,C) */ + for (unsigned i = 0; i < n; ++i) { + mean[i] = 0.; + for (unsigned j = 0; j < pop.size(); ++j) { + mean[i] += p.weights[j] * (*pop[j])[i]; + } + BDz[i] = sqrt(p.mueff)*(mean[i] - oldmean[i])/sigma; + } - /* remove momentum in ps, if ps is large and fitness is getting worse */ + vector tmp(n); + /* calculate z := D^(-1) * B^(-1) * rgBDz into rgdTmp */ + for (unsigned i = 0; i < n; ++i) { + double sum = 0.0; + for (unsigned j = 0; j < n; ++j) { + sum += B[j][i] * BDz[j]; + } + tmp[i] = sum / d[i]; + } - if (gen >= fitnessHistory.size()) { + /* cumulation for sigma (ps) using B*z */ + for (unsigned i = 0; i < n; ++i) { + double sum = 0.0; + for (unsigned j = 0; j < n; ++j) + sum += B[i][j] * tmp[j]; - // find direction from muBest and muWorst (muBest == muWorst handled seperately - double direction = muBest < muWorst? -1.0 : 1.0; - - unsigned now = gen % fitnessHistory.size(); - unsigned prev = (gen-1) % fitnessHistory.size(); - unsigned prevprev = (gen-2) % fitnessHistory.size(); + ps[i] = (1. - p.ccumsig) * ps[i] + sqrt(p.ccumsig * (2. - p.ccumsig)) * sum; + } - bool fitnessWorsens = (muBest == muWorst) || // <- increase norm also when population has converged (this deviates from Hansen's scheme) - ( (direction * fitnessHistory[now] < direction * fitnessHistory[prev]) - && - (direction * fitnessHistory[now] < direction * fitnessHistory[prevprev])); - - if(psxps/p.n > 1.5 + 10.*sqrt(2./p.n) && fitnessWorsens) { - double tfac = sqrt((1 + std::max(0., log(psxps/p.n))) * p.n / psxps); - ps *= tfac; - psxps *= tfac*tfac; - } - } + /* calculate norm(ps)^2 */ + double psxps = (ps * ps).sum(); - /* update of C */ - /* Adapt_C(t); not used anymore */ - if (p.ccov != 0.) { - //flgEigensysIsUptodate = 0; - /* update covariance matrix */ - for (unsigned i = 0; i < n; ++i) { - vector::iterator c_row = C[i]; - for (unsigned j = 0; j <= i; ++j) { - c_row[j] = - (1 - p.ccov) * c_row[j] - + - p.ccov * (1./p.mucov) * pc[i] * pc[j] - + - (1-hsig) * p.ccumcov * (2. - p.ccumcov) * c_row[j]; - - /*C[i][j] = (1 - p.ccov) * C[i][j] - + sp.ccov * (1./sp.mucov) - * (rgpc[i] * rgpc[j] - + (1-hsig)*sp.ccumcov*(2.-sp.ccumcov) * C[i][j]); */ - for (unsigned k = 0; k < p.mu; ++k) { /* additional rank mu update */ - c_row[j] += p.ccov * (1-1./p.mucov) * p.weights[k] - * ( (*pop[k])[i] - oldmean[i]) - * ( (*pop[k])[j] - oldmean[j]) - / sigma / sigma; - - // * (rgrgx[index[k]][i] - rgxold[i]) - // * (rgrgx[index[k]][j] - rgxold[j]) - // / sigma / sigma; - } - } - } - } + double chiN = sqrt((double) p.n) * (1. - 1./(4.*p.n) + 1./(21.*p.n*p.n)); + /* cumulation for covariance matrix (pc) using B*D*z~N(0,C) */ + double hsig = sqrt(psxps) / sqrt(1. - pow(1.-p.ccumsig, 2.*gen)) / chiN < 1.5 + 1./(p.n-0.5); - /* update of sigma */ - sigma *= exp(((sqrt(psxps)/chiN)-1.)/p.damp); - /* calculate eigensystem, must be done by caller */ - //cmaes_UpdateEigensystem(0); + pc = (1. - p.ccumcov) * pc + hsig * sqrt(p.ccumcov * (2. - p.ccumcov)) * BDz; - - /* treat minimal standard deviations and numeric problems - * Note that in contrast with the original code, some numerical issues are treated *before* we - * go into the eigenvalue calculation */ - - treatNumericalIssues(muBest, muWorst); + /* stop initial phase (MK, this was not reachable in the org code, deleted) */ - gen++; // increase generation + /* remove momentum in ps, if ps is large and fitness is getting worse */ + + if (gen >= fitnessHistory.size()) { + + // find direction from muBest and muWorst (muBest == muWorst handled seperately + double direction = muBest < muWorst? -1.0 : 1.0; + + unsigned now = gen % fitnessHistory.size(); + unsigned prev = (gen-1) % fitnessHistory.size(); + unsigned prevprev = (gen-2) % fitnessHistory.size(); + + bool fitnessWorsens = (muBest == muWorst) || // <- increase norm also when population has converged (this deviates from Hansen's scheme) + ( (direction * fitnessHistory[now] < direction * fitnessHistory[prev]) + && + (direction * fitnessHistory[now] < direction * fitnessHistory[prevprev])); + + if(psxps/p.n > 1.5 + 10.*sqrt(2./p.n) && fitnessWorsens) { + double tfac = sqrt((1 + std::max(0., log(psxps/p.n))) * p.n / psxps); + ps *= tfac; + psxps *= tfac*tfac; + } + } + + /* update of C */ + /* Adapt_C(t); not used anymore */ + if (p.ccov != 0.) { + //flgEigensysIsUptodate = 0; + + /* update covariance matrix */ + for (unsigned i = 0; i < n; ++i) { + vector::iterator c_row = C[i]; + for (unsigned j = 0; j <= i; ++j) { + c_row[j] = + (1 - p.ccov) * c_row[j] + + + p.ccov * (1./p.mucov) * pc[i] * pc[j] + + + (1-hsig) * p.ccumcov * (2. - p.ccumcov) * c_row[j]; + + /*C[i][j] = (1 - p.ccov) * C[i][j] + + sp.ccov * (1./sp.mucov) + * (rgpc[i] * rgpc[j] + + (1-hsig)*sp.ccumcov*(2.-sp.ccumcov) * C[i][j]); */ + for (unsigned k = 0; k < p.mu; ++k) { /* additional rank mu update */ + c_row[j] += p.ccov * (1-1./p.mucov) * p.weights[k] + * ( (*pop[k])[i] - oldmean[i]) + * ( (*pop[k])[j] - oldmean[j]) + / sigma / sigma; + + // * (rgrgx[index[k]][i] - rgxold[i]) + // * (rgrgx[index[k]][j] - rgxold[j]) + // / sigma / sigma; + } + } + } + } + + /* update of sigma */ + sigma *= exp(((sqrt(psxps)/chiN)-1.)/p.damp); + /* calculate eigensystem, must be done by caller */ + //cmaes_UpdateEigensystem(0); + + + /* treat minimal standard deviations and numeric problems + * Note that in contrast with the original code, some numerical issues are treated *before* we + * go into the eigenvalue calculation */ + + treatNumericalIssues(muBest, muWorst); + + gen++; // increase generation } void treatNumericalIssues(double best, double worst) { - - /* treat stdevs */ - for (unsigned i = 0; i < p.n; ++i) { - if (sigma * sqrt(C[i][i]) < p.minStdevs[i]) { - // increase stdev - sigma *= exp(0.05+1./p.damp); - break; - } - } - - /* treat convergence */ - if (best == worst) { - sigma *= exp(0.2 + 1./p.damp); - } - - /* Jede Hauptachse i testen, ob x == x + 0.1 * sigma * rgD[i] * B[i] */ - /* Test if all the means are not numerically out of whack with our coordinate system*/ - for (unsigned axis = 0; axis < p.n; ++axis) { - double fac = 0.1 * sigma * d[axis]; - unsigned coord; - for (coord = 0; coord < p.n; ++coord) { - if (mean[coord] != mean[coord] + fac * B[coord][axis]) { - break; - } - } - if (coord == p.n) { // means are way too big (little) for numerical accuraccy. Start rocking the craddle a bit more - sigma *= exp(0.2+1./p.damp); - } - - } - - /* Testen ob eine Komponente des Objektparameters festhaengt */ - /* Correct issues with scale between objective values and covariances */ - bool theresAnIssue = false; + /* treat stdevs */ + for (unsigned i = 0; i < p.n; ++i) { + if (sigma * sqrt(C[i][i]) < p.minStdevs[i]) { + // increase stdev + sigma *= exp(0.05+1./p.damp); + break; + } + } - for (unsigned i = 0; i < p.n; ++i) { - if (mean[i] == mean[i] + 0.2 * sigma * sqrt(C[i][i])) { - C[i][i] *= (1. + p.ccov); - theresAnIssue = true; - } - } + /* treat convergence */ + if (best == worst) { + sigma *= exp(0.2 + 1./p.damp); + } - if (theresAnIssue) { - sigma *= exp(0.05 + 1./p.damp); - } + /* Jede Hauptachse i testen, ob x == x + 0.1 * sigma * rgD[i] * B[i] */ + /* Test if all the means are not numerically out of whack with our coordinate system*/ + for (unsigned axis = 0; axis < p.n; ++axis) { + double fac = 0.1 * sigma * d[axis]; + unsigned coord; + for (coord = 0; coord < p.n; ++coord) { + if (mean[coord] != mean[coord] + fac * B[coord][axis]) { + break; + } + } + + if (coord == p.n) { // means are way too big (little) for numerical accuraccy. Start rocking the craddle a bit more + sigma *= exp(0.2+1./p.damp); + } + + } + + /* Testen ob eine Komponente des Objektparameters festhaengt */ + /* Correct issues with scale between objective values and covariances */ + bool theresAnIssue = false; + + for (unsigned i = 0; i < p.n; ++i) { + if (mean[i] == mean[i] + 0.2 * sigma * sqrt(C[i][i])) { + C[i][i] *= (1. + p.ccov); + theresAnIssue = true; + } + } + + if (theresAnIssue) { + sigma *= exp(0.05 + 1./p.damp); + } } - + bool updateEigenSystem(unsigned max_tries, unsigned max_iters) { - if (max_iters==0) max_iters = 30 * p.n; - - static double lastGoodMinimumEigenValue = 1.0; - - /* Try to get a valid calculation */ - for (unsigned tries = 0; tries < max_tries; ++tries) { - - unsigned iters = eig( p.n, C, d, B, max_iters); - if (iters < max_iters) - { // all is well - - /* find largest/smallest eigenvalues */ - double minEV = d.min(); - double maxEV = d.max(); + if (max_iters==0) max_iters = 30 * p.n; - /* (MK Original comment was) :Limit Condition of C to dMaxSignifKond+1 - * replaced dMaxSignifKond with 1./numeric_limits::epsilon() - * */ - if (maxEV * numeric_limits::epsilon() > minEV) { - double tmp = maxEV * numeric_limits::epsilon() - minEV; - minEV += tmp; - for (unsigned i=0;i::epsilon() + * */ + if (maxEV * numeric_limits::epsilon() > minEV) { + double tmp = maxEV * numeric_limits::epsilon() - minEV; + minEV += tmp; + for (unsigned i=0;i& initial_point, const double initial_sigma) +CMAState::CMAState(const CMAParams& params, const std::vector& initial_point, const double initial_sigma) : pimpl(new CMAStateImpl(params, initial_point, initial_sigma)) {} CMAState::~CMAState() { delete pimpl; } @@ -362,4 +362,3 @@ bool CMAState::updateEigenSystem(unsigned max_tries, unsigned max_iters) { retur } // namespace eo - diff --git a/eo/src/es/CMAState.h b/eo/src/es/CMAState.h index 505a31b7..85a80c52 100644 --- a/eo/src/es/CMAState.h +++ b/eo/src/es/CMAState.h @@ -1,13 +1,12 @@ - /* * C++ification of Nikolaus Hansen's original C-source code for the - * CMA-ES. + * CMA-ES. * * Copyright (C) 1996, 2003, Nikolaus Hansen - * (C) 2005, Maarten Keijzer + * (C) 2005, Maarten Keijzer * * License: LGPL (see source file) - * + * */ #ifndef CMASTATE_H_ @@ -17,14 +16,14 @@ #include namespace eo { - + class CMAStateImpl; class CMAParams; class CMAState { - + CMAStateImpl* pimpl; /* pointer to implementation, hidden in source file */ - + public: CMAState(const CMAParams&, const std::vector& initial_point, const double initial_sigma = 1.0); @@ -35,34 +34,34 @@ class CMAState { /** * sample a vector from the distribution * - * If the sample is not to your liking (i.e., not within bounds) - * you can do one of two things: + * If the sample is not to your liking (i.e., not within bounds) + * you can do one of two things: * - * a) Call sample again - * b) multiply the entire vector with a number between -1 and 1 - * - * Do not modify the sample in any other way as this will invalidate the - * internal consistency of the system. + * a) Call sample again + * b) multiply the entire vector with a number between -1 and 1 * - * A final approach is to copy the sample and modify the copy externally (in the evaluation function) - * and possibly add a penalty depending on the size of the modification. + * Do not modify the sample in any other way as this will invalidate the + * internal consistency of the system. + * + * A final approach is to copy the sample and modify the copy externally (in the evaluation function) + * and possibly add a penalty depending on the size of the modification. * */ void sample(std::vector& v) const; - + /** * Reestimate covariance matrix and other internal parameters * Does NOT update the eigen system (call that seperately) * * Needs a population of mu individuals, sorted on fitness, plus * - * muBest: the best fitness in the population + * muBest: the best fitness in the population * muWorst: the worst fitness in the population */ - + void reestimate(const std::vector* >& sorted_population, double muBest, double muWorst); - - /** + + /** * call this function after reestimate in order to update the eigen system * It is a seperate call to allow the user to periodically skip this expensive step * @@ -71,7 +70,7 @@ class CMAState { * If after max_tries still no numerically sound eigen system is constructed, * the function returns false */ - bool updateEigenSystem(unsigned max_tries = 1, unsigned max_iters = 0); + bool updateEigenSystem(unsigned max_tries = 1, unsigned max_iters = 0); }; } // namespace eo diff --git a/eo/src/es/eig.cpp b/eo/src/es/eig.cpp index 29998bcb..d7ddd41d 100644 --- a/eo/src/es/eig.cpp +++ b/eo/src/es/eig.cpp @@ -1,4 +1,3 @@ - /* * C++ification of Nikolaus Hansen's original C-source code for the * CMA-ES. These are the eigenvector calculations @@ -8,7 +7,7 @@ * * This algorithm is held almost completely intact. Some other datatypes are used, * but hardly any code has changed - * + * */ /* --------------------------------------------------------- */ @@ -31,7 +30,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * + * * */ /* --- Changes : --- * 03/03/21: argument const double *rgFunVal of @@ -49,21 +48,21 @@ using namespace std; /* ========================================================= */ -/* +/* Householder Transformation einer symmetrischen Matrix auf tridiagonale Form. -> n : Dimension -> ma : symmetrische nxn-Matrix - <- ma : Transformationsmatrix (ist orthogonal): + <- ma : Transformationsmatrix (ist orthogonal): Tridiag.-Matrix == <-ma * ->ma * (<-ma)^t <- diag : Diagonale der resultierenden Tridiagonalmatrix <- neben[0..n-1] : Nebendiagonale (==1..n-1) der res. Tridiagonalmatrix */ -static void +static void Householder( int N, square_matrix& ma, valarray& diag, double* neben) { - double epsilon; + double epsilon; int i, j, k; double h, sum, tmp, tmp2; @@ -82,34 +81,34 @@ Householder( int N, square_matrix& ma, valarray& diag, double* neben) else { for(k = i-1, sum = 0.0; k >= 0; --k) - { /* i-te Zeile von i-1 bis links normieren */ + { /* i-te Zeile von i-1 bis links normieren */ ma[i][k] /= epsilon; - sum += ma[i][k]*ma[i][k]; - } - tmp = (ma[i][i-1] > 0) ? -sqrt(sum) : sqrt(sum); - neben[i] = epsilon*tmp; - h = sum - ma[i][i-1]*tmp; - ma[i][i-1] -= tmp; - for (j = 0, sum = 0.0; j < i; ++j) - { - ma[j][i] = ma[i][j]/h; - tmp = 0.0; - for (k = j; k >= 0; --k) - tmp += ma[j][k]*ma[i][k]; - for (k = j+1; k < i; ++k) - tmp += ma[k][j]*ma[i][k]; - neben[j] = tmp/h; - sum += neben[j] * ma[i][j]; - } /* for j */ - sum /= 2.*h; - for (j = 0; j < i; ++j) - { - neben[j] -= ma[i][j]*sum; - tmp = ma[i][j]; - tmp2 = neben[j]; - for (k = j; k >= 0; --k) - ma[j][k] -= (tmp*neben[k] + tmp2*ma[i][k]); - } /* for j */ + sum += ma[i][k]*ma[i][k]; + } + tmp = (ma[i][i-1] > 0) ? -sqrt(sum) : sqrt(sum); + neben[i] = epsilon*tmp; + h = sum - ma[i][i-1]*tmp; + ma[i][i-1] -= tmp; + for (j = 0, sum = 0.0; j < i; ++j) + { + ma[j][i] = ma[i][j]/h; + tmp = 0.0; + for (k = j; k >= 0; --k) + tmp += ma[j][k]*ma[i][k]; + for (k = j+1; k < i; ++k) + tmp += ma[k][j]*ma[i][k]; + neben[j] = tmp/h; + sum += neben[j] * ma[i][j]; + } /* for j */ + sum /= 2.*h; + for (j = 0; j < i; ++j) + { + neben[j] -= ma[i][j]*sum; + tmp = ma[i][j]; + tmp2 = neben[j]; + for (k = j; k >= 0; --k) + ma[j][k] -= (tmp*neben[k] + tmp2*ma[i][k]); + } /* for j */ } /* else epsilon */ } /* else i == 1 */ diag[i] = h; @@ -117,16 +116,16 @@ Householder( int N, square_matrix& ma, valarray& diag, double* neben) diag[0] = 0.0; neben[0] = 0.0; - + for (i = 0; i < N; ++i) { if(diag[i] != 0.0) for (j = 0; j < i; ++j) { - for (k = i-1, tmp = 0.0; k >= 0; --k) - tmp += ma[i][k] * ma[k][j]; + for (k = i-1, tmp = 0.0; k >= 0; --k) + tmp += ma[i][k] * ma[k][j]; for (k = i-1; k >= 0; --k) - ma[k][j] -= tmp*ma[k][i]; + ma[k][j] -= tmp*ma[k][i]; } /* for j */ diag[i] = ma[i][i]; ma[i][i] = 1.0; @@ -137,21 +136,21 @@ Householder( int N, square_matrix& ma, valarray& diag, double* neben) /* QL-Algorithmus mit implizitem Shift, zur Berechnung von Eigenwerten - und -vektoren einer symmetrischen Tridiagonalmatrix. - -> n : Dimension. - -> diag : Diagonale der Tridiagonalmatrix. + und -vektoren einer symmetrischen Tridiagonalmatrix. + -> n : Dimension. + -> diag : Diagonale der Tridiagonalmatrix. -> neben[0..n-1] : Nebendiagonale (==0..n-2), n-1. Eintrag beliebig - -> mq : Matrix output von Householder() - -> maxIt : maximale Zahl der Iterationen + -> mq : Matrix output von Householder() + -> maxIt : maximale Zahl der Iterationen <- diag : Eigenwerte <- neben : Garbage <- mq : k-te Spalte ist normalisierter Eigenvektor zu diag[k] */ -static int -QLalgo( int N, valarray& diag, square_matrix& mq, - int maxIter, double* neben) +static int +QLalgo( int N, valarray& diag, square_matrix& mq, + int maxIter, double* neben) { int i, j, k, kp1, l; double tmp, diff, cneben, c1, c2, p; @@ -163,77 +162,77 @@ QLalgo( int N, valarray& diag, square_matrix& mq, { for (j = i; j < N-1; ++j) { - tmp = fabs(diag[j]) + fabs(diag[j+1]); - if (fabs(neben[j]) + tmp == tmp) - break; + tmp = fabs(diag[j]) + fabs(diag[j+1]); + if (fabs(neben[j]) + tmp == tmp) + break; } if (j != i) { - if (++iter > maxIter) return maxIter-1; - diff = (diag[i+1]-diag[i])/neben[i]/2.0; - if (diff >= 0) - diff = diag[j] - diag[i] + - neben[i] / (diff + sqrt(diff * diff + 1.0)); - else - diff = diag[j] - diag[i] + - neben[i] / (diff - sqrt(diff * diff + 1.0)); - c2 = c1 = 1.0; - p = 0.0; - for (k = j-1; k >= i; --k) - { - kp1 = k + 1; - tmp = c2 * neben[k]; - cneben = c1 * neben[k]; - if (fabs(tmp) >= fabs(diff)) - { - c1 = diff / tmp; - c2 = 1. / sqrt(c1*c1 + 1.0); - neben[kp1] = tmp / c2; - c1 *= c2; - } - else - { - c2 = tmp / diff; - c1 = 1. / sqrt(c2*c2 + 1.0); - neben[kp1] = diff / c1; - c2 *= c1; - } /* else */ - tmp = (diag[k] - diag[kp1] + p) * c2 + 2.0 * c1 * cneben; - diag[kp1] += tmp * c2 - p; - p = tmp * c2; - diff = tmp * c1 - cneben; - for (l = N-1; l >= 0; --l) /* TF-Matrix Q */ - { - tmp = mq[l][kp1]; - mq[l][kp1] = c2 * mq[l][k] + c1 * tmp; - mq[l][k] = c1 * mq[l][k] - c2 * tmp; - } /* for l */ - } /* for k */ - diag[i] -= p; - neben[i] = diff; - neben[j] = 0.0; + if (++iter > maxIter) return maxIter-1; + diff = (diag[i+1]-diag[i])/neben[i]/2.0; + if (diff >= 0) + diff = diag[j] - diag[i] + + neben[i] / (diff + sqrt(diff * diff + 1.0)); + else + diff = diag[j] - diag[i] + + neben[i] / (diff - sqrt(diff * diff + 1.0)); + c2 = c1 = 1.0; + p = 0.0; + for (k = j-1; k >= i; --k) + { + kp1 = k + 1; + tmp = c2 * neben[k]; + cneben = c1 * neben[k]; + if (fabs(tmp) >= fabs(diff)) + { + c1 = diff / tmp; + c2 = 1. / sqrt(c1*c1 + 1.0); + neben[kp1] = tmp / c2; + c1 *= c2; + } + else + { + c2 = tmp / diff; + c1 = 1. / sqrt(c2*c2 + 1.0); + neben[kp1] = diff / c1; + c2 *= c1; + } /* else */ + tmp = (diag[k] - diag[kp1] + p) * c2 + 2.0 * c1 * cneben; + diag[kp1] += tmp * c2 - p; + p = tmp * c2; + diff = tmp * c1 - cneben; + for (l = N-1; l >= 0; --l) /* TF-Matrix Q */ + { + tmp = mq[l][kp1]; + mq[l][kp1] = c2 * mq[l][k] + c1 * tmp; + mq[l][k] = c1 * mq[l][k] - c2 * tmp; + } /* for l */ + } /* for k */ + diag[i] -= p; + neben[i] = diff; + neben[j] = 0.0; } /* if */ } while (j != i); return iter; } /* QLalgo() */ /* ========================================================= */ -/* - Calculating eigenvalues and vectors. - Input: +/* + Calculating eigenvalues and vectors. + Input: N: dimension. C: lower_triangular NxN-matrix. - niter: number of maximal iterations for QL-Algorithm. - rgtmp: N+1-dimensional vector for temporal use. - Output: + niter: number of maximal iterations for QL-Algorithm. + rgtmp: N+1-dimensional vector for temporal use. + Output: diag: N eigenvalues. Q: Columns are normalized eigenvectors. return: number of iterations in QL-Algorithm. */ namespace eo { -int -eig( int N, const lower_triangular_matrix& C, valarray& diag, square_matrix& Q, +int +eig( int N, const lower_triangular_matrix& C, valarray& diag, square_matrix& Q, int niter) { int ret; @@ -245,15 +244,15 @@ eig( int N, const lower_triangular_matrix& C, valarray& diag, square_ma { vector::const_iterator row = C[i]; for (j = 0; j <= i; ++j) - Q[i][j] = Q[j][i] = row[j]; + Q[i][j] = Q[j][i] = row[j]; } - + double* rgtmp = new double[N+1]; Householder( N, Q, diag, rgtmp); ret = QLalgo( N, diag, Q, niter, rgtmp+1); delete [] rgtmp; - + return ret; -} +} } // namespace eo diff --git a/eo/src/es/eig.h b/eo/src/es/eig.h index 02aa36e0..65d9c53d 100644 --- a/eo/src/es/eig.h +++ b/eo/src/es/eig.h @@ -6,18 +6,18 @@ namespace eo { /* ========================================================= */ -/* - Calculating eigenvalues and vectors. - Input: +/* + Calculating eigenvalues and vectors. + Input: N: dimension. C: lower_triangular NxN-matrix. - niter: number of maximal iterations for QL-Algorithm. - Output: + niter: number of maximal iterations for QL-Algorithm. + Output: diag: N eigenvalues. Q: Columns are normalized eigenvectors. return: number of iterations in QL-Algorithm. */ -extern int eig( int N, const lower_triangular_matrix& C, std::valarray& diag, square_matrix& Q, +extern int eig( int N, const lower_triangular_matrix& C, std::valarray& diag, square_matrix& Q, int niter = 0); } // namespace eo diff --git a/eo/src/es/eoCMABreed.h b/eo/src/es/eoCMABreed.h index d55ab261..450654a7 100644 --- a/eo/src/es/eoCMABreed.h +++ b/eo/src/es/eoCMABreed.h @@ -34,43 +34,43 @@ /// @todo handle bounds template class eoCMABreed : public eoBreed< eoVector > { - + eo::CMAState& state; unsigned lambda; - + typedef eoVector EOT; - + public: eoCMABreed(eo::CMAState& state_, unsigned lambda_) : state(state_), lambda(lambda_) {} - + void operator()(const eoPop& parents, eoPop& offspring) { - - // two temporary arrays of pointers to store the sorted population - std::vector sorted(parents.size()); - + + // two temporary arrays of pointers to store the sorted population + std::vector sorted(parents.size()); + // mu stores population as vector (instead of eoPop) std::vector* > mu(parents.size()); - - parents.sort(sorted); - for (unsigned i = 0; i < sorted.size(); ++i) { - mu[i] = static_cast< const std::vector* >( sorted[i] ); - } - - // learn - state.reestimate(mu, sorted[0]->fitness(), sorted.back()->fitness()); - - if (!state.updateEigenSystem(10)) { - std::cerr << "No good eigensystem found" << std::endl; - } - - // generate - offspring.resize(lambda); - for (unsigned i = 0; i < lambda; ++i) { - state.sample( static_cast< std::vector& >( offspring[i] )); - offspring[i].invalidate(); - } - + parents.sort(sorted); + for (unsigned i = 0; i < sorted.size(); ++i) { + mu[i] = static_cast< const std::vector* >( sorted[i] ); + } + + // learn + state.reestimate(mu, sorted[0]->fitness(), sorted.back()->fitness()); + + if (!state.updateEigenSystem(10)) { + std::cerr << "No good eigensystem found" << std::endl; + } + + // generate + offspring.resize(lambda); + + for (unsigned i = 0; i < lambda; ++i) { + state.sample( static_cast< std::vector& >( offspring[i] )); + offspring[i].invalidate(); + } + } }; diff --git a/eo/src/es/eoCMAInit.h b/eo/src/es/eoCMAInit.h index bce9e5ba..2fdb967e 100644 --- a/eo/src/es/eoCMAInit.h +++ b/eo/src/es/eoCMAInit.h @@ -1,7 +1,7 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; fill-column: 80; -*- //----------------------------------------------------------------------------- -// eoCMAInit +// eoCMAInit // (c) Maarten Keijzer 2005 /* This library is free software; you can redistribute it and/or @@ -35,18 +35,18 @@ /// @todo handle bounds template class eoCMAInit : public eoInit< eoVector > { - + const eo::CMAState& state; typedef eoVector EOT; - + public: eoCMAInit(const eo::CMAState& state_) : state(state_) {} - + void operator()(EOT& v) { - state.sample(static_cast& >(v)); - v.invalidate(); + state.sample(static_cast& >(v)); + v.invalidate(); } }; diff --git a/eo/src/es/eoEsGlobalXover.h b/eo/src/es/eoEsGlobalXover.h index bac4ae27..5be4b506 100644 --- a/eo/src/es/eoEsGlobalXover.h +++ b/eo/src/es/eoEsGlobalXover.h @@ -75,12 +75,12 @@ public: // first, the object variables for (unsigned i=0; i used by _plop to get parents - const EOT& realParent1 = sel(_plop.source()); - const EOT& realParent2 = sel(_plop.source()); - parent[i] = realParent1[i]; - crossObj(parent[i], realParent2[i]); // apply eoBinOp + // get extra parents - use private selector + // _plop.source() is the eoPop used by _plop to get parents + const EOT& realParent1 = sel(_plop.source()); + const EOT& realParent2 = sel(_plop.source()); + parent[i] = realParent1[i]; + crossObj(parent[i], realParent2[i]); // apply eoBinOp } // then the self-adaptation parameters cross_self_adapt(parent, _plop.source()); @@ -110,10 +110,10 @@ private: { for (unsigned i=0; i<_parent.size(); i++) { - const EOT& realParent1 = sel(_pop); - const EOT& realParent2 = sel(_pop); - _parent.stdevs[i] = realParent1.stdevs[i]; - crossMut(_parent.stdevs[i], realParent2.stdevs[i]); // apply eoBinOp + const EOT& realParent1 = sel(_pop); + const EOT& realParent2 = sel(_pop); + _parent.stdevs[i] = realParent1.stdevs[i]; + crossMut(_parent.stdevs[i], realParent2.stdevs[i]); // apply eoBinOp } } @@ -127,18 +127,18 @@ private: // the StDev for (i=0; i<_parent.size(); i++) { - const EOT& realParent1 = sel(_pop); - const EOT& realParent2 = sel(_pop); - _parent.stdevs[i] = realParent1.stdevs[i]; - crossMut(_parent.stdevs[i], realParent2.stdevs[i]); // apply eoBinOp + const EOT& realParent1 = sel(_pop); + const EOT& realParent2 = sel(_pop); + _parent.stdevs[i] = realParent1.stdevs[i]; + crossMut(_parent.stdevs[i], realParent2.stdevs[i]); // apply eoBinOp } // the roataion angles for (i=0; i<_parent.correlations.size(); i++) { - const EOT& realParent1 = sel(_pop); - const EOT& realParent2 = sel(_pop); - _parent.correlations[i] = realParent1.correlations[i]; - crossMut(_parent.correlations[i], realParent2.correlations[i]); // apply eoBinOp + const EOT& realParent1 = sel(_pop); + const EOT& realParent2 = sel(_pop); + _parent.correlations[i] = realParent1.correlations[i]; + crossMut(_parent.correlations[i], realParent2.correlations[i]); // apply eoBinOp } } diff --git a/eo/src/es/eoEsMutate.h b/eo/src/es/eoEsMutate.h index 6ae09ef2..fd115268 100644 --- a/eo/src/es/eoEsMutate.h +++ b/eo/src/es/eoEsMutate.h @@ -99,7 +99,7 @@ public: { _eo.stdev *= exp(TauLcl * rng.normal()); if (_eo.stdev < stdev_eps) - _eo.stdev = stdev_eps; + _eo.stdev = stdev_eps; // now apply to all for (unsigned i = 0; i < _eo.size(); ++i) { @@ -218,7 +218,7 @@ public: unsigned size = bounds.size(); TauLcl = _init.TauLcl(); TauLcl /= sqrt(2*(double) size); - std::cout << "Init: tau local " << TauLcl << std::endl; + std::cout << "Init: tau local " << TauLcl << std::endl; } diff --git a/eo/src/es/eoEsMutationInit.h b/eo/src/es/eoEsMutationInit.h index 6ee74c2a..987de86b 100644 --- a/eo/src/es/eoEsMutationInit.h +++ b/eo/src/es/eoEsMutationInit.h @@ -55,7 +55,7 @@ public : @param _section Parser section for \f$\tau\f$-parameters. */ eoEsMutationInit(eoParser& _parser, - std::string _section="ES mutation parameters" ) : + std::string _section="ES mutation parameters" ) : parser(_parser), repSection(_section), TauLclParam(0), TauGlbParam(0), TauBetaParam(0) {} diff --git a/eo/src/es/eoEsStandardXover.h b/eo/src/es/eoEsStandardXover.h index 56d59be8..34739693 100644 --- a/eo/src/es/eoEsStandardXover.h +++ b/eo/src/es/eoEsStandardXover.h @@ -1,4 +1,4 @@ -/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- // eoEsLocalXover.h : ES global crossover @@ -8,16 +8,16 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: marc.schoenauer@polytechnique.fr http://eeaax.cmap.polytchnique.fr/ */ //----------------------------------------------------------------------------- @@ -45,7 +45,7 @@ * @ingroup Real * @ingroup Variators */ -template +template class eoEsStandardXover: public eoBinOp { public: @@ -70,13 +70,13 @@ public: // first, the object variables for (unsigned i=0; i<_eo1.size(); i++) { - bLoc |= crossObj(_eo1[i], _eo2[i]); // apply eoBinOp + bLoc |= crossObj(_eo1[i], _eo2[i]); // apply eoBinOp } // then the self-adaptation parameters bLoc |= cross_self_adapt(_eo1, _eo2); return bLoc; } - + private: // the method to cross slef-adaptation parameters: need to specialize @@ -91,7 +91,7 @@ private: bool bLoc=false; for (unsigned i=0; i<_parent1.size(); i++) { - bLoc |= crossMut(_parent1.stdevs[i], _parent2.stdevs[i]); // apply eoBinOp + bLoc |= crossMut(_parent1.stdevs[i], _parent2.stdevs[i]); // apply eoBinOp } return bLoc; } @@ -103,12 +103,12 @@ private: // the StDev for (i=0; i<_parent1.size(); i++) { - bLoc |= crossMut(_parent1.stdevs[i], _parent2.stdevs[i]); // apply eoBinOp + bLoc |= crossMut(_parent1.stdevs[i], _parent2.stdevs[i]); // apply eoBinOp } // the roataion angles for (i=0; i<_parent1.correlations.size(); i++) { - bLoc |= crossMut(_parent1.correlations[i], _parent2.correlations[i]); // apply eoBinOp + bLoc |= crossMut(_parent1.correlations[i], _parent2.correlations[i]); // apply eoBinOp } return bLoc; diff --git a/eo/src/es/eoNormalMutation.h b/eo/src/es/eoNormalMutation.h index 17447244..96dcf54c 100644 --- a/eo/src/es/eoNormalMutation.h +++ b/eo/src/es/eoNormalMutation.h @@ -69,13 +69,13 @@ template class eoNormalVecMutation: public eoMonOp * for each component, the sigma is scaled to the range of the bound, if bounded */ eoNormalVecMutation(eoRealVectorBounds & _bounds, - double _sigma, const double& _p_change = 1.0): + double _sigma, const double& _p_change = 1.0): sigma(_bounds.size(), _sigma), bounds(_bounds), p_change(_p_change) { // scale to the range - if any for (unsigned i=0; i class eoNormalVecMutation: public eoMonOp { bool hasChanged=false; for (unsigned lieu=0; lieu<_eo.size(); lieu++) - { - if (rng.flip(p_change)) - { - _eo[lieu] += sigma[lieu]*rng.normal(); - bounds.foldsInBounds(lieu, _eo[lieu]); - hasChanged = true; - } - } + { + if (rng.flip(p_change)) + { + _eo[lieu] += sigma[lieu]*rng.normal(); + bounds.foldsInBounds(lieu, _eo[lieu]); + hasChanged = true; + } + } return hasChanged; } @@ -138,7 +138,7 @@ public: * @param _p_change the probability to change a given coordinate */ eoNormalMutation(eoRealVectorBounds & _bounds, - double _sigma, const double& _p_change = 1.0): + double _sigma, const double& _p_change = 1.0): sigma(_sigma), bounds(_bounds), p_change(_p_change) {} /** The class name */ @@ -152,14 +152,14 @@ public: { bool hasChanged=false; for (unsigned lieu=0; lieu<_eo.size(); lieu++) - { - if (rng.flip(p_change)) - { - _eo[lieu] += sigma*rng.normal(); - bounds.foldsInBounds(lieu, _eo[lieu]); - hasChanged = true; - } - } + { + if (rng.flip(p_change)) + { + _eo[lieu] += sigma*rng.normal(); + bounds.foldsInBounds(lieu, _eo[lieu]); + hasChanged = true; + } + } return hasChanged; } @@ -199,8 +199,8 @@ public: * @param _threshold the threshold (the 1/5 - 0.2) */ eoOneFifthMutation(eoEvalFunc & _eval, double & _sigmaInit, - unsigned _windowSize = 10, double _updateFactor=0.83, - double _threshold=0.2): + unsigned _windowSize = 10, double _updateFactor=0.83, + double _threshold=0.2): eoNormalMutation(_sigmaInit), eval(_eval), threshold(_threshold), updateFactor(_updateFactor), nbMut(_windowSize, 0), nbSuccess(_windowSize, 0), genIndex(0) @@ -221,21 +221,21 @@ public: */ bool operator()(EOT & _eo) { - if (_eo.invalid()) // due to some crossover??? - eval(_eo); + if (_eo.invalid()) // due to some crossover??? + eval(_eo); Fitness oldFitness = _eo.fitness(); // save old fitness // call standard operator - then count the successes if (eoNormalMutation::operator()(_eo)) // _eo has been modified - { - _eo.invalidate(); // don't forget!!! - nbMut[genIndex]++; - eval(_eo); // compute fitness of offspring + { + _eo.invalidate(); // don't forget!!! + nbMut[genIndex]++; + eval(_eo); // compute fitness of offspring - if (_eo.fitness() > oldFitness) - nbSuccess[genIndex]++; // update counter - } - return false; // because eval has reset the validity flag + if (_eo.fitness() > oldFitness) + nbSuccess[genIndex]++; // update counter + } + return false; // because eval has reset the validity flag } /** the method that will be called every generation @@ -248,18 +248,18 @@ public: // compute the average stats over the time window for ( unsigned i=0; i threshold) { - Sigma() /= updateFactor; // increase sigma + Sigma() /= updateFactor; // increase sigma } else { - Sigma() *= updateFactor; // decrease sigma + Sigma() *= updateFactor; // decrease sigma } genIndex = (genIndex+1) % nbMut.size() ; nbMut[genIndex] = nbSuccess[genIndex] = 0; @@ -268,15 +268,14 @@ public: private: eoEvalFunc & eval; - double threshold; // 1/5 ! - double updateFactor ; // the multiplicative factor - std::vector nbMut; // total number of mutations per gen - std::vector nbSuccess; // number of successful mutations per gen - unsigned genIndex ; // current index in std::vectors (circular) + double threshold; // 1/5 ! + double updateFactor ; // the multiplicative factor + std::vector nbMut; // total number of mutations per gen + std::vector nbSuccess; // number of successful mutations per gen + unsigned genIndex ; // current index in std::vectors (circular) }; //----------------------------------------------------------------------------- //@} #endif - diff --git a/eo/src/es/eoReal.h b/eo/src/es/eoReal.h index 925d4a3a..ff1908a0 100644 --- a/eo/src/es/eoReal.h +++ b/eo/src/es/eoReal.h @@ -17,7 +17,7 @@ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact: Marc.Schoenauer@polytechnique.fr - todos@geneura.ugr.es, http://geneura.ugr.es + todos@geneura.ugr.es, http://geneura.ugr.es mkeijzer@dhi.dk */ diff --git a/eo/src/es/eoRealAtomXover.h b/eo/src/es/eoRealAtomXover.h index c5528734..4d4244dd 100644 --- a/eo/src/es/eoRealAtomXover.h +++ b/eo/src/es/eoRealAtomXover.h @@ -1,4 +1,4 @@ -/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- +/** -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- //----------------------------------------------------------------------------- // eoRealAtomXover.h : helper classes for std::vector crossover @@ -8,16 +8,16 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: marc.schoenauer@polytechnique.fr http://eeaax.cmap.polytchnique.fr/ */ //----------------------------------------------------------------------------- @@ -35,7 +35,7 @@ #include -/** +/** Discrete crossover == exchange of values * * @ingroup Real @@ -55,20 +55,20 @@ public: /** Exchanges or not the values */ - bool operator()(double& r1, const double& r2) + bool operator()(double& r1, const double& r2) { if (eo::rng.flip()) - if (r1 != r2) // if r1 == r2 you must return false - { - r1 = r2; - return true; - } + if (r1 != r2) // if r1 == r2 you must return false + { + r1 = r2; + return true; + } return false; } - + }; -/** +/** Intermediate crossover == linear combination * * @ingroup Real @@ -88,13 +88,13 @@ public: /** Linear combination of both parents */ - bool operator()(double& r1, const double& r2) + bool operator()(double& r1, const double& r2) { double alpha = eo::rng.uniform(); r1 = alpha * r2 + (1-alpha) * r1; return true; } - + }; #endif diff --git a/eo/src/es/eoRealInitBounded.h b/eo/src/es/eoRealInitBounded.h index d74c7698..6488dd05 100644 --- a/eo/src/es/eoRealInitBounded.h +++ b/eo/src/es/eoRealInitBounded.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoRealInitBounded.h // (c) EEAAX 2000 - Maarten Keijzer 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -33,8 +33,8 @@ #include #include -/** Simple initialization for any EOT that derives from std::vector - * uniformly in some bounds +/** Simple initialization for any EOT that derives from std::vector + * uniformly in some bounds * * @ingroup Real * @ingroup Variators @@ -44,7 +44,7 @@ class eoRealInitBounded : public eoInit { public: /** Ctor - from eoRealVectorBounds */ - eoRealInitBounded(eoRealVectorBounds & _bounds):bounds(_bounds) + eoRealInitBounded(eoRealVectorBounds & _bounds):bounds(_bounds) { if (!bounds.isBounded()) throw std::runtime_error("Needs bounded bounds to initialize a std::vector"); @@ -54,7 +54,7 @@ class eoRealInitBounded : public eoInit virtual void operator()(EOT & _eo) { bounds.uniform(_eo); // resizes, and fills uniformly in bounds - _eo.invalidate(); // was MISSING!!!! + _eo.invalidate(); // was MISSING!!!! } /** accessor to the bounds */ @@ -67,5 +67,4 @@ class eoRealInitBounded : public eoInit //----------------------------------------------------------------------------- //@} -#endif - +#endif diff --git a/eo/src/es/eoRealOp.h b/eo/src/es/eoRealOp.h index ab4d47e0..c8c6471a 100644 --- a/eo/src/es/eoRealOp.h +++ b/eo/src/es/eoRealOp.h @@ -66,14 +66,14 @@ template class eoUniformMutation: public eoMonOp * @param _p_change the one probability to change all coordinates */ eoUniformMutation(eoRealVectorBounds & _bounds, - const double& _epsilon, const double& _p_change = 1.0): + const double& _epsilon, const double& _p_change = 1.0): homogeneous(false), bounds(_bounds), epsilon(_bounds.size(), _epsilon), p_change(_bounds.size(), _p_change) { // scale to the range - if any for (unsigned i=0; i class eoUniformMutation: public eoMonOp * @param _p_change the VECTOR of probabilities for each coordinates */ eoUniformMutation(eoRealVectorBounds & _bounds, - const std::vector& _epsilon, - const std::vector& _p_change): + const std::vector& _epsilon, + const std::vector& _p_change): homogeneous(false), bounds(_bounds), epsilon(_epsilon), p_change(_p_change) {} @@ -98,43 +98,43 @@ template class eoUniformMutation: public eoMonOp bool operator()(EOT& _eo) { bool hasChanged=false; - if (homogeneous) // implies no bounds object - for (unsigned lieu=0; lieu<_eo.size(); lieu++) - { - if (rng.flip(p_change[0])) - { - _eo[lieu] += 2*epsilon[0]*rng.uniform()-epsilon[0]; - hasChanged = true; - } - } + if (homogeneous) // implies no bounds object + for (unsigned lieu=0; lieu<_eo.size(); lieu++) + { + if (rng.flip(p_change[0])) + { + _eo[lieu] += 2*epsilon[0]*rng.uniform()-epsilon[0]; + hasChanged = true; + } + } else - { - // sanity check ? - if (_eo.size() != bounds.size()) - throw std::runtime_error("Invalid size of indi in eoUniformMutation"); + { + // sanity check ? + if (_eo.size() != bounds.size()) + throw std::runtime_error("Invalid size of indi in eoUniformMutation"); - for (unsigned lieu=0; lieu<_eo.size(); lieu++) - if (rng.flip(p_change[lieu])) - { - // check the bounds - double emin = _eo[lieu]-epsilon[lieu]; - double emax = _eo[lieu]+epsilon[lieu]; - if (bounds.isMinBounded(lieu)) - emin = std::max(bounds.minimum(lieu), emin); - if (bounds.isMaxBounded(lieu)) - emax = std::min(bounds.maximum(lieu), emax); - _eo[lieu] = emin + (emax-emin)*rng.uniform(); - hasChanged = true; - } - } + for (unsigned lieu=0; lieu<_eo.size(); lieu++) + if (rng.flip(p_change[lieu])) + { + // check the bounds + double emin = _eo[lieu]-epsilon[lieu]; + double emax = _eo[lieu]+epsilon[lieu]; + if (bounds.isMinBounded(lieu)) + emin = std::max(bounds.minimum(lieu), emin); + if (bounds.isMaxBounded(lieu)) + emax = std::min(bounds.maximum(lieu), emax); + _eo[lieu] = emin + (emax-emin)*rng.uniform(); + hasChanged = true; + } + } return hasChanged; } private: bool homogeneous; // == no bounds passed in the ctor eoRealVectorBounds & bounds; - std::vector epsilon; // the ranges for mutation - std::vector p_change; // the proba that each variable is modified + std::vector epsilon; // the ranges for mutation + std::vector p_change; // the proba that each variable is modified }; /** eoDetUniformMutation --> changes exactly k values of the std::vector @@ -166,14 +166,14 @@ template class eoDetUniformMutation: public eoMonOp * @param _no number of coordinate to modify */ eoDetUniformMutation(eoRealVectorBounds & _bounds, - const double& _epsilon, const unsigned& _no = 1): + const double& _epsilon, const unsigned& _no = 1): homogeneous(false), bounds(_bounds), epsilon(_bounds.size(), _epsilon), no(_no) { // scale to the range - if any for (unsigned i=0; i class eoDetUniformMutation: public eoMonOp * @param _no number of coordinates to modify */ eoDetUniformMutation(eoRealVectorBounds & _bounds, - const std::vector& _epsilon, - const unsigned& _no = 1): + const std::vector& _epsilon, + const unsigned& _no = 1): homogeneous(false), bounds(_bounds), epsilon(_epsilon), no(_no) { // scale to the range - if any for (unsigned i=0; i class eoDetUniformMutation: public eoMonOp bool operator()(EOT& _eo) { if (homogeneous) - for (unsigned i=0; i epsilon; // the ranges of mutation + std::vector epsilon; // the ranges of mutation unsigned no; }; @@ -274,7 +274,7 @@ template class eoSegmentCrossover: public eoQuadOp * Must be positive */ eoSegmentCrossover(eoRealVectorBounds & _bounds, - const double& _alpha = 0.0) : + const double& _alpha = 0.0) : bounds(_bounds), alpha(_alpha), range(1+2*_alpha) {} /// The class name. @@ -291,47 +291,47 @@ template class eoSegmentCrossover: public eoQuadOp double r1, r2, fact; double alphaMin = -alpha; double alphaMax = 1+alpha; - if (alpha == 0.0) // no check to perform - fact = -alpha + rng.uniform(range); // in [-alpha,1+alpha) - else // look for the bounds for fact - { - for (i=0; i<_eo1.size(); i++) - { - r1=_eo1[i]; - r2=_eo2[i]; - if (r1 != r2) { // otherwise you'll get NAN's - double rmin = std::min(r1, r2); - double rmax = std::max(r1, r2); - double length = rmax - rmin; - if (bounds.isMinBounded(i)) - { - alphaMin = std::max(alphaMin, (bounds.minimum(i)-rmin)/length); - alphaMax = std::min(alphaMax, (rmax-bounds.minimum(i))/length); - } - if (bounds.isMaxBounded(i)) - { - alphaMax = std::min(alphaMax, (bounds.maximum(i)-rmin)/length); - alphaMin = std::max(alphaMin, (rmax-bounds.maximum(i))/length); - } - } - } - fact = alphaMin + (alphaMax-alphaMin)*rng.uniform(); - } + if (alpha == 0.0) // no check to perform + fact = -alpha + rng.uniform(range); // in [-alpha,1+alpha) + else // look for the bounds for fact + { + for (i=0; i<_eo1.size(); i++) + { + r1=_eo1[i]; + r2=_eo2[i]; + if (r1 != r2) { // otherwise you'll get NAN's + double rmin = std::min(r1, r2); + double rmax = std::max(r1, r2); + double length = rmax - rmin; + if (bounds.isMinBounded(i)) + { + alphaMin = std::max(alphaMin, (bounds.minimum(i)-rmin)/length); + alphaMax = std::min(alphaMax, (rmax-bounds.minimum(i))/length); + } + if (bounds.isMaxBounded(i)) + { + alphaMax = std::min(alphaMax, (bounds.maximum(i)-rmin)/length); + alphaMin = std::max(alphaMin, (rmax-bounds.maximum(i))/length); + } + } + } + fact = alphaMin + (alphaMax-alphaMin)*rng.uniform(); + } for (i=0; i<_eo1.size(); i++) - { - r1=_eo1[i]; - r2=_eo2[i]; - _eo1[i] = fact * r1 + (1-fact) * r2; - _eo2[i] = (1-fact) * r1 + fact * r2; - } - return true; // shoudl test if fact was 0 or 1 :-))) + { + r1=_eo1[i]; + r2=_eo2[i]; + _eo1[i] = fact * r1 + (1-fact) * r2; + _eo2[i] = (1-fact) * r1 + fact * r2; + } + return true; // shoudl test if fact was 0 or 1 :-))) } protected: eoRealVectorBounds & bounds; double alpha; - double range; // == 1+2*alpha + double range; // == 1+2*alpha }; /** eoHypercubeCrossover --> uniform choice in hypercube @@ -369,7 +369,7 @@ template class eoHypercubeCrossover: public eoQuadOp * Must be positive */ eoHypercubeCrossover(eoRealVectorBounds & _bounds, - const double& _alpha = 0.0): + const double& _alpha = 0.0): bounds(_bounds), alpha(_alpha), range(1+2*_alpha) { if (_alpha < 0) @@ -389,62 +389,62 @@ template class eoHypercubeCrossover: public eoQuadOp bool hasChanged = false; unsigned i; double r1, r2, fact; - if (alpha == 0.0) // no check to perform - for (i=0; i<_eo1.size(); i++) - { - r1=_eo1[i]; - r2=_eo2[i]; - if (r1 != r2) { // otherwise do nothing - fact = rng.uniform(range); // in [0,1) - _eo1[i] = fact * r1 + (1-fact) * r2; - _eo2[i] = (1-fact) * r1 + fact * r2; - hasChanged = true; // forget (im)possible alpha=0 - } - } - else // check the bounds - // do not try to get a bound on the linear factor, but rather - // on the object variables themselves - for (i=0; i<_eo1.size(); i++) - { - r1=_eo1[i]; - r2=_eo2[i]; - if (r1 != r2) { // otherwise do nothing - double rmin = std::min(r1, r2); - double rmax = std::max(r1, r2); + if (alpha == 0.0) // no check to perform + for (i=0; i<_eo1.size(); i++) + { + r1=_eo1[i]; + r2=_eo2[i]; + if (r1 != r2) { // otherwise do nothing + fact = rng.uniform(range); // in [0,1) + _eo1[i] = fact * r1 + (1-fact) * r2; + _eo2[i] = (1-fact) * r1 + fact * r2; + hasChanged = true; // forget (im)possible alpha=0 + } + } + else // check the bounds + // do not try to get a bound on the linear factor, but rather + // on the object variables themselves + for (i=0; i<_eo1.size(); i++) + { + r1=_eo1[i]; + r2=_eo2[i]; + if (r1 != r2) { // otherwise do nothing + double rmin = std::min(r1, r2); + double rmax = std::max(r1, r2); - // compute min and max for object variables - double objMin = -alpha * rmax + (1+alpha) * rmin; - double objMax = -alpha * rmin + (1+alpha) * rmax; + // compute min and max for object variables + double objMin = -alpha * rmax + (1+alpha) * rmin; + double objMax = -alpha * rmin + (1+alpha) * rmax; - // first find the limits on the alpha's - if (bounds.isMinBounded(i)) - { - objMin = std::max(objMin, bounds.minimum(i)); - } - if (bounds.isMaxBounded(i)) - { - objMax = std::min(objMax, bounds.maximum(i)); - } - // then draw variables - double median = (objMin+objMax)/2.0; // uniform within bounds - // double median = (rmin+rmax)/2.0; // Bounce on bounds - double valMin = objMin + (median-objMin)*rng.uniform(); - double valMax = median + (objMax-median)*rng.uniform(); - // don't always put large value in _eo1 - or what? - if (rng.flip(0.5)) - { - _eo1[i] = valMin; - _eo2[i] = valMax; - } - else - { - _eo1[i] = valMax; - _eo2[i] = valMin; - } - // seomthing has changed - hasChanged = true; // forget (im)possible alpha=0 - } - } + // first find the limits on the alpha's + if (bounds.isMinBounded(i)) + { + objMin = std::max(objMin, bounds.minimum(i)); + } + if (bounds.isMaxBounded(i)) + { + objMax = std::min(objMax, bounds.maximum(i)); + } + // then draw variables + double median = (objMin+objMax)/2.0; // uniform within bounds + // double median = (rmin+rmax)/2.0; // Bounce on bounds + double valMin = objMin + (median-objMin)*rng.uniform(); + double valMax = median + (objMax-median)*rng.uniform(); + // don't always put large value in _eo1 - or what? + if (rng.flip(0.5)) + { + _eo1[i] = valMin; + _eo2[i] = valMax; + } + else + { + _eo1[i] = valMax; + _eo2[i] = valMin; + } + // seomthing has changed + hasChanged = true; // forget (im)possible alpha=0 + } + } return hasChanged; } @@ -452,7 +452,7 @@ template class eoHypercubeCrossover: public eoQuadOp protected: eoRealVectorBounds & bounds; double alpha; - double range; // == 1+2*alphaMin + double range; // == 1+2*alphaMin }; @@ -473,7 +473,7 @@ template class eoRealUXover: public eoQuadOp eoRealUXover(const float& _preference = 0.5): preference(_preference) { if ( (_preference <= 0.0) || (_preference >= 1.0) ) - std::runtime_error("UxOver --> invalid preference"); + std::runtime_error("UxOver --> invalid preference"); } /// The class name. @@ -488,19 +488,19 @@ template class eoRealUXover: public eoQuadOp bool operator()(EOT& _eo1, EOT& _eo2) { if ( _eo1.size() != _eo2.size()) - std::runtime_error("UxOver --> chromosomes sizes don't match" ); + std::runtime_error("UxOver --> chromosomes sizes don't match" ); bool changed = false; for (unsigned int i=0; i<_eo1.size(); i++) - { - if (rng.flip(preference)) - if (_eo1[i] != _eo2[i]) - { - double tmp = _eo1[i]; - _eo1[i]=_eo2[i]; - _eo2[i] = tmp; - changed = true; - } - } + { + if (rng.flip(preference)) + if (_eo1[i] != _eo2[i]) + { + double tmp = _eo1[i]; + _eo1[i]=_eo2[i]; + _eo2[i] = tmp; + changed = true; + } + } return changed; } private: diff --git a/eo/src/es/eoSBXcross.h b/eo/src/es/eoSBXcross.h index e80e6c78..40f8ac36 100644 --- a/eo/src/es/eoSBXcross.h +++ b/eo/src/es/eoSBXcross.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoSBXcross.h // (c) Maarten Keijzer 2000 - Marc Schoenauer 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -43,7 +43,7 @@ template class eoSBXCrossover: public eoQuadOp * (Default) Constructor. * The bounds are initialized with the global object that says: no bounds. * - * + * */ eoSBXCrossover(const double& _eta = 1.0) : bounds(eoDummyVectorNoBounds), eta(_eta), range(1) {} @@ -54,7 +54,7 @@ template class eoSBXCrossover: public eoQuadOp /** * Constructor with bounds * @param _bounds an eoRealVectorBounds that contains the bounds - * @param _eta the amount of exploration OUTSIDE the parents + * @param _eta the amount of exploration OUTSIDE the parents * as in BLX-alpha notation (Eshelman and Schaffer) * 0 == contractive application * Must be positive @@ -62,8 +62,8 @@ template class eoSBXCrossover: public eoQuadOp - eoSBXCrossover(eoRealVectorBounds & _bounds, - const double& _eta = 1.0) : + eoSBXCrossover(eoRealVectorBounds & _bounds, + const double& _eta = 1.0) : bounds(_bounds), eta(_eta), range(1) {} /////////////////////////////////////////////// @@ -76,14 +76,14 @@ template class eoSBXCrossover: public eoQuadOp * eta, the SBX parameter */ - eoSBXCrossover(eoParser & _parser) : + eoSBXCrossover(eoParser & _parser) : // First, decide whether the objective variables are bounded // Warning, must be the same keywords than other possible objectBounds elsewhere bounds (_parser.getORcreateParam(eoDummyVectorNoBounds, "objectBounds", "Bounds for variables", 'B', "Variation Operators").value()) , // then get eta value eta (_parser.getORcreateParam(1.0, "eta", "SBX eta parameter", '\0', "Variation Operators").value()) , range(1) {} - + /// The class name. virtual std::string className() const { return "eoSBXCrossover"; } @@ -91,47 +91,45 @@ template class eoSBXCrossover: public eoQuadOp /***************************************** * SBX crossover - modifies both parents * * @param _eo1 The first parent * - * @param _eo2 The first parent * + * @param _eo2 The first parent * *****************************************/ bool operator()(EOT& _eo1, EOT& _eo2) { unsigned i; double r1, r2, beta; - for (i=0; i<_eo1.size(); i++) - { + for (i=0; i<_eo1.size(); i++) + { double u = rng.uniform(range) ; - if ( u <= 0.5 ) - beta = exp( (1/(eta+1))*log(2*u)); + if ( u <= 0.5 ) + beta = exp( (1/(eta+1))*log(2*u)); else - beta = exp((1/(eta+1))*log(1/(2*(1-u)))); - - - - r1=_eo1[i]; - r2=_eo2[i]; - _eo1[i] =0.5*((1+beta)*r1+(1-beta)*r2); - _eo2[i] =0.5*((1-beta)*r1+(1+beta)*r2); - - - if(!(bounds.isInBounds(i,_eo1[i]))) - bounds.foldsInBounds(i,_eo1[i]); - if(!(bounds.isInBounds(i,_eo2[i]))) - bounds.foldsInBounds(i,_eo2[i]); + beta = exp((1/(eta+1))*log(1/(2*(1-u)))); - } - return true; - } - - + r1=_eo1[i]; + r2=_eo2[i]; + _eo1[i] =0.5*((1+beta)*r1+(1-beta)*r2); + _eo2[i] =0.5*((1-beta)*r1+(1+beta)*r2); + + + if(!(bounds.isInBounds(i,_eo1[i]))) + bounds.foldsInBounds(i,_eo1[i]); + if(!(bounds.isInBounds(i,_eo2[i]))) + bounds.foldsInBounds(i,_eo2[i]); + + + + } + return true; + } + + protected: eoRealVectorBounds & bounds; double eta; - double range; // == 1 + double range; // == 1 }; - - diff --git a/eo/src/es/make_algo_scalar_es.cpp b/eo/src/es/make_algo_scalar_es.cpp index fa35cb36..47585a78 100644 --- a/eo/src/es/make_algo_scalar_es.cpp +++ b/eo/src/es/make_algo_scalar_es.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_algo_scalar_es.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of select/replace fns * of the library for evolution of ***eoEs genotypes*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/es.h * while the TEMPLATIZED code is define in make_algo_scalar.h in the src/do dir */ @@ -43,9 +43,9 @@ // The templatized code #include // the instanciating EOType(s) -#include // one Sigma per individual -#include // one sigmal per object variable -#include // full correlation matrix per indi +#include // one Sigma per individual +#include // one sigmal per object variable +#include // full correlation matrix per indi /// The following function merely call the templatized do_* functions above @@ -82,4 +82,3 @@ eoAlgo >& make_algo_scalar(eoParser& _parser, eoS { return do_make_algo_scalar(_parser, _state, _eval, _continue, _op); } - diff --git a/eo/src/es/make_algo_scalar_real.cpp b/eo/src/es/make_algo_scalar_real.cpp index 91b5ccd1..1a1796be 100644 --- a/eo/src/es/make_algo_scalar_real.cpp +++ b/eo/src/es/make_algo_scalar_real.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_algo_scalar_real.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of select/replace fns * of the library for evolution of ***eoReal*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/real.h * while the TEMPLATIZED code is define in make_algo_scalar.h in the src/do dir */ @@ -58,4 +58,3 @@ eoAlgo >& make_algo_scalar(eoParser& _parser, eoSta { return do_make_algo_scalar(_parser, _state, _eval, _continue, _op, _dist); } - diff --git a/eo/src/es/make_checkpoint_es.cpp b/eo/src/es/make_checkpoint_es.cpp index dea658dc..12bc7860 100644 --- a/eo/src/es/make_checkpoint_es.cpp +++ b/eo/src/es/make_checkpoint_es.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_checkpoint_es.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of checkpoint fns * of the library for evolution of ***ES genotypes*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/es.h * while the TEMPLATIZED code is define in make_checkpoint.h in the src/do dir */ @@ -43,11 +43,11 @@ // The templatized code #include // the instanciating EOType(s) -#include // one Sigma per individual -#include // one sigmal per object variable -#include // full correlation matrix per indi +#include // one Sigma per individual +#include // one sigmal per object variable +#include // full correlation matrix per indi -/// The following function merely call the templatized do_* functions +/// The following function merely call the templatized do_* functions // checkpoint ///////////// @@ -55,7 +55,7 @@ eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _ { return do_make_checkpoint(_parser, _state, _eval, _continue); } -eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } @@ -65,7 +65,7 @@ eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _s { return do_make_checkpoint(_parser, _state, _eval, _continue); } -eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } @@ -75,9 +75,7 @@ eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _st { return do_make_checkpoint(_parser, _state, _eval, _continue); } -eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } - - diff --git a/eo/src/es/make_checkpoint_real.cpp b/eo/src/es/make_checkpoint_real.cpp index 1995d78c..a1cf6d4f 100644 --- a/eo/src/es/make_checkpoint_real.cpp +++ b/eo/src/es/make_checkpoint_real.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_checkpoint_real.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of checkpoint fns * of the library for evolution of ***eoReal*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/real.h * while the TEMPLATIZED code is define in make_checkpoint.h in the src/do dir */ @@ -45,7 +45,7 @@ // the instanciating EOType #include -/// The following function merely call the templatized do_* functions +/// The following function merely call the templatized do_* functions // checkpoint ///////////// @@ -53,9 +53,7 @@ eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _stat { return do_make_checkpoint(_parser, _state, _eval, _continue); } -eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } - - diff --git a/eo/src/es/make_continue_es.cpp b/eo/src/es/make_continue_es.cpp index ca9d4fee..e5016795 100644 --- a/eo/src/es/make_continue_es.cpp +++ b/eo/src/es/make_continue_es.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_continue_es.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of continuator fns * of the library for evolution of ***ES genotypes*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/es.h * while the TEMPLATIZED code is define in make_continue.h in the src/do dir */ @@ -43,9 +43,9 @@ // The templatized code #include // the instanciating EOType(s) -#include // one Sigma per individual -#include // one sigmal per object variable -#include // full correlation matrix per indi +#include // one Sigma per individual +#include // one sigmal per object variable +#include // full correlation matrix per indi /// The following function merely call the templatized do_* functions @@ -79,5 +79,3 @@ eoContinue >& make_continue(eoParser& _parser, eoS { return do_make_continue(_parser, _state, _eval); } - - diff --git a/eo/src/es/make_continue_real.cpp b/eo/src/es/make_continue_real.cpp index 868e8eec..06085217 100644 --- a/eo/src/es/make_continue_real.cpp +++ b/eo/src/es/make_continue_real.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_continue_real.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of continuator fns * of the library for evolution of ***REAL vectors*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/real.h * while the TEMPLATIZED code is define in make_continue.h in the src/do dir */ @@ -57,5 +57,3 @@ eoContinue >& make_continue(eoParser& _parser, eoSta { return do_make_continue(_parser, _state, _eval); } - - diff --git a/eo/src/es/make_es.h b/eo/src/es/make_es.h index 27bfe4f6..46a4e23f 100644 --- a/eo/src/es/make_es.h +++ b/eo/src/es/make_es.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // es.h // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -24,20 +24,20 @@ */ //----------------------------------------------------------------------------- -/** This file contains all ***INSTANCIATED*** declarations of all components +/** This file contains all ***INSTANCIATED*** declarations of all components * of the library for ***ES-like gnptype*** evolution inside EO. * It should be included in the file that calls any of the corresponding fns * - * The corresponding ***INSTANCIATED*** definitions are contained in - * the different .cpp files in the src/es dir, + * The corresponding ***INSTANCIATED*** definitions are contained in + * the different .cpp files in the src/es dir, * while the TEMPLATIZED code is define in the different make_XXX.h files - * either in hte src/do dir for representation independant functions, + * either in hte src/do dir for representation independant functions, * or in the src/es dir for representation dependent stuff. * - * See also real.h for the similar declarations of eoReal genotypes + * See also real.h for the similar declarations of eoReal genotypes * i.e. ***without*** mutation parameters attached to individuals * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -54,9 +54,9 @@ #include #include -#include // one Sigma per individual -#include // one sigmal per object variable -#include // full correlation matrix per indi +#include // one Sigma per individual +#include // one sigmal per object variable +#include // full correlation matrix per indi // include all similar declaration for eoReal - i.e. real-valued genotyes // without self-adaptation @@ -68,7 +68,7 @@ //Representation dependent - rewrite everything anew for each representation ////////////////////////// -// the genotypes +// the genotypes eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoEsSimple _eo); eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoEsSimple _eo); diff --git a/eo/src/es/make_genotype_real.h b/eo/src/es/make_genotype_real.h index 7977bbf9..6ab62967 100644 --- a/eo/src/es/make_genotype_real.h +++ b/eo/src/es/make_genotype_real.h @@ -84,7 +84,7 @@ eoEsChromInit & do_make_genotype(eoParser& _parser, eoState& _state, EOT) eoValueParam& sigmaParam = _parser.getORcreateParam(std::string("0.3"), "sigmaInit", "Initial value for Sigmas (with a '%' -> scaled by the range of each variable)", - 's', "Genotype Initialization"); + 's', "Genotype Initialization"); // check for % bool to_scale = false; size_t pos = sigmaParam.value().find('%'); diff --git a/eo/src/es/make_op.h b/eo/src/es/make_op.h index 0bcda4f7..1c7fe50e 100644 --- a/eo/src/es/make_op.h +++ b/eo/src/es/make_op.h @@ -97,23 +97,23 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit v; std::vector::iterator it; for (it=ppBounds.second.begin(); itc_str()); - double r; - is >> r; - v.push_back(r); - } + { + istrstream is(it->c_str()); + double r; + is >> r; + v.push_back(r); + } // now create the eoRealVectorBounds object if (v.size() == 2) // a min and a max for all variables - ptBounds = new eoRealVectorBounds(vecSize, v[0], v[1]); - else // no time now - throw std::runtime_error("Sorry, only unique bounds for all variables implemented at the moment. Come back later"); + ptBounds = new eoRealVectorBounds(vecSize, v[0], v[1]); + else // no time now + throw std::runtime_error("Sorry, only unique bounds for all variables implemented at the moment. Come back later"); // we need to give ownership of this pointer to somebody /////////// end of temporary code } - else // no param for bounds was given + else // no param for bounds was given ptBounds = new eoRealVectorNoBounds(vecSize); // DON'T USE eoDummyVectorNoBounds - // as it does not have any dimension + // as it does not have any dimension // this is a temporary version(!), // while Maarten codes the full tree-structured general operator input @@ -185,7 +185,7 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit(*ptQuad, segmentRateParam.value()); - // arithmetic crossover + // arithmetic crossover ptQuad = new eoArithmeticCrossover(*ptBounds); _state.storeFunctor(ptQuad); ptCombinedQuadOp->add(*ptQuad, arithmeticRateParam.value()); @@ -258,7 +258,7 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit(*ptMon, uniformMutRateParam.value()); - // mutate exactly 1 component (uniformly) per individual + // mutate exactly 1 component (uniformly) per individual ptMon = new eoDetUniformMutation(*ptBounds, epsilonParam.value()); _state.storeFunctor(ptMon); ptCombinedMonOp->add(*ptMon, detMutRateParam.value()); @@ -289,7 +289,7 @@ eoGenOp & do_make_op(eoParameterLoader& _parser, eoState& _state, eoInit *op = new eoSequentialOp; _state.storeFunctor(op); - op->add(*cross, 1.0); // always crossover (but clone with prob 1-pCross + op->add(*cross, 1.0); // always crossover (but clone with prob 1-pCross op->add(*ptCombinedMonOp, pMutParam.value()); // that's it! diff --git a/eo/src/es/make_op_es.cpp b/eo/src/es/make_op_es.cpp index 7f463599..4dfbacf3 100644 --- a/eo/src/es/make_op_es.cpp +++ b/eo/src/es/make_op_es.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_op_real.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of operators fns * of the library for ***eoReal*** evolution inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in es.h in src/es dir * while the TEMPLATIZED code is define in make_op.h in the es dir * @@ -77,4 +77,3 @@ eoGenOp >& make_op(eoParser& _parser, eoState& _s { return do_make_op(_parser, _state, _init); } - diff --git a/eo/src/es/make_op_es.h b/eo/src/es/make_op_es.h index 0d93e060..00a3373f 100644 --- a/eo/src/es/make_op_es.h +++ b/eo/src/es/make_op_es.h @@ -154,10 +154,10 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoRealInitBounded< if (crossTypeParam.value() == std::string("global")) ptCross = new eoEsGlobalXover(*ptObjAtomCross, *ptStdevAtomCross); else if (crossTypeParam.value() == std::string("standard")) - { // using a standard eoBinOp, but wrap it into an eoGenOp + { // using a standard eoBinOp, but wrap it into an eoGenOp eoBinOp & crossTmp = _state.storeFunctor( - new eoEsStandardXover(*ptObjAtomCross, *ptStdevAtomCross) - ); + new eoEsStandardXover(*ptObjAtomCross, *ptStdevAtomCross) + ); ptCross = new eoBinGenOp(crossTmp); } else throw std::runtime_error("Invalide Object variable crossover type"); diff --git a/eo/src/es/make_op_real.cpp b/eo/src/es/make_op_real.cpp index 19435831..b429cd41 100644 --- a/eo/src/es/make_op_real.cpp +++ b/eo/src/es/make_op_real.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_op_real.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of operators fns * of the library for ***eoReal*** evolution inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in es.h in src/es dir * while the TEMPLATIZED code is define in make_op.h in the es dir * diff --git a/eo/src/es/make_op_real.h b/eo/src/es/make_op_real.h index 2792e638..19a8b16b 100644 --- a/eo/src/es/make_op_real.h +++ b/eo/src/es/make_op_real.h @@ -168,12 +168,12 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoRealInitBounded< _state.storeFunctor(ptQuad); ptCombinedQuadOp = new eoPropCombinedQuadOp(*ptQuad, segmentRateParam.value()); - // hypercube crossover + // hypercube crossover ptQuad = new eoHypercubeCrossover(boundsParam.value(), alphaParam.value()); _state.storeFunctor(ptQuad); ptCombinedQuadOp->add(*ptQuad, hypercubeRateParam.value()); - // uniform crossover + // uniform crossover ptQuad = new eoRealUXover(); _state.storeFunctor(ptQuad); ptCombinedQuadOp->add(*ptQuad, uxoverRateParam.value()); @@ -249,7 +249,7 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoRealInitBounded< // create the CombinedMonOp ptCombinedMonOp = new eoPropCombinedMonOp(*ptMon, uniformMutRateParam.value()); - // mutate exactly 1 component (uniformly) per individual + // mutate exactly 1 component (uniformly) per individual ptMon = new eoDetUniformMutation(boundsParam.value(), epsilonParam.value()); _state.storeFunctor(ptMon); ptCombinedMonOp->add(*ptMon, detMutRateParam.value()); @@ -279,7 +279,7 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoRealInitBounded< // now the sequential eoSequentialOp & op = _state.storeFunctor(new eoSequentialOp); - op.add(*cross, 1.0); // always crossover (but clone with prob 1-pCross + op.add(*cross, 1.0); // always crossover (but clone with prob 1-pCross op.add(*ptCombinedMonOp, pMutParam.value()); // that's it! diff --git a/eo/src/es/make_pop_es.cpp b/eo/src/es/make_pop_es.cpp index 4f77e2f5..4f72e344 100644 --- a/eo/src/es/make_pop_es.cpp +++ b/eo/src/es/make_pop_es.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_pop_es.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of pop. init. fns * of the library for evolution of ***ES genotypes*** indis inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/es.h * while the TEMPLATIZED code is define in make_pop.h in the src/do dir */ @@ -43,9 +43,9 @@ // The templatized code #include // the instanciating EOType(s) -#include // one Sigma per individual -#include // one sigmal per object variable -#include // full correlation matrix per indi +#include // one Sigma per individual +#include // one sigmal per object variable +#include // full correlation matrix per indi /// The following function merely call the templatized do_* functions above @@ -82,5 +82,3 @@ eoPop >& make_pop(eoParser& _parser, eoState& _st { return do_make_pop(_parser, _state, _init); } - - diff --git a/eo/src/es/make_pop_real.cpp b/eo/src/es/make_pop_real.cpp index eaa75baa..968e7251 100644 --- a/eo/src/es/make_pop_real.cpp +++ b/eo/src/es/make_pop_real.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_pop_real.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of pop. init. fns * of the library for evolution of ***eoReal*** indis inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/real.h * while the TEMPLATIZED code is define in make_pop.h in the src/do dir */ @@ -58,5 +58,3 @@ eoPop >& make_pop(eoParser& _parser, eoState& _stat { return do_make_pop(_parser, _state, _init); } - - diff --git a/eo/src/es/make_real.h b/eo/src/es/make_real.h index bb356fc7..bc04ba1f 100644 --- a/eo/src/es/make_real.h +++ b/eo/src/es/make_real.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // real.h // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -24,20 +24,20 @@ */ //----------------------------------------------------------------------------- -/** This file contains all ***INSTANCIATED*** declarations of all components +/** This file contains all ***INSTANCIATED*** declarations of all components * of the library for ***std::vector*** evolution inside EO. * It should be included in the file that calls any of the corresponding fns * - * The corresponding ***INSTANCIATED*** definitions are contained in - * the different .cpp files in the src/es dir, + * The corresponding ***INSTANCIATED*** definitions are contained in + * the different .cpp files in the src/es dir, * while the TEMPLATIZED code is define in the different make_XXX.h files - * either in hte src/do dir for representation independant functions, + * either in hte src/do dir for representation independant functions, * or in the src/es dir for representation dependent stuff. * - * See also es.h for the similar declarations of ES-like genotypes + * See also es.h for the similar declarations of ES-like genotypes * i.e. ***with*** mutation parameters attached to individuals * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -64,7 +64,7 @@ /** @addtogroup Builders * @{ */ -// the genotypes +// the genotypes eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoReal _eo); eoRealInitBounded > & make_genotype(eoParser& _parser, eoState& _state, eoReal _eo); diff --git a/eo/src/es/make_run_es.cpp b/eo/src/es/make_run_es.cpp index 77a45a08..59912a7f 100644 --- a/eo/src/es/make_run_es.cpp +++ b/eo/src/es/make_run_es.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_run_es.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains ***INSTANCIATED DEFINITIONS*** of run funs * of the library for evolution of ***ES genotypes*** inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/es/es.h * while the TEMPLATIZED code is define in make_run.h in the src/do dir */ @@ -43,9 +43,9 @@ // The templatized code #include // the instanciating EOType(s) -#include // one Sigma per individual -#include // one sigmal per object variable -#include // full correlation matrix per indi +#include // one Sigma per individual +#include // one sigmal per object variable +#include // full correlation matrix per indi // the instanciating fitnesses #include @@ -84,4 +84,3 @@ void run_ea(eoAlgo >& _ga, eoPop >& _ga, eoPop::iterator operator[](unsigned i) { return data.begin() + i * (i+1) / 2; } std::vector::const_iterator operator[](unsigned i) const { return data.begin() + i*(i+1)/2; } }; @@ -32,15 +32,14 @@ class square_matrix { public: square_matrix(unsigned n_ = 0) : n(n_), data(n * n) {}; - + void resize(unsigned n_) { - n = n_; - data.resize(n*n); + n = n_; + data.resize(n*n); } - + std::vector::iterator operator[](unsigned i) { return data.begin() + i * n; } std::vector::const_iterator operator[](unsigned i) const { return data.begin() + i*n; } }; #endif - diff --git a/eo/src/ga.h b/eo/src/ga.h index 87cc0e34..6abb0181 100644 --- a/eo/src/ga.h +++ b/eo/src/ga.h @@ -1,7 +1,7 @@ //----------------------------------------------------------------------------- // ga.h // (c) GeNeura Team 1998 - 2000, Marc Schoenauer 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -24,7 +24,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #ifndef _ga_h #define _ga_h diff --git a/eo/src/ga/Readme b/eo/src/ga/Readme index 69d7d466..3d9b8663 100644 --- a/eo/src/ga/Readme +++ b/eo/src/ga/Readme @@ -1,11 +1,11 @@ This directory contains: -- some standard EO source files, named eoXXXXX, that define objects +- some standard EO source files, named eoXXXXX, that define objects for the eoBit representation (bitstrings). - some make_XXX.cpp files that are instanciations for EO bitstrings -(eoBit AND eoBit) of the tempatized code -that is defined in the EO src/do dir. +(eoBit AND eoBit) of the tempatized code +that is defined in the EO src/do dir. This MK's trick allows to actually compile all these bits in a library (eolibga.a) and to only recompile the bits you need for your own (bitstring!) application. @@ -18,4 +18,3 @@ that constructs the EOType initializer (make_genotype.h) and the one that buils up the operators (make_op.h). MS, April 23, 2001CVS - diff --git a/eo/src/ga/eoBit.h b/eo/src/ga/eoBit.h index 7f91b886..c1bc9c75 100644 --- a/eo/src/ga/eoBit.h +++ b/eo/src/ga/eoBit.h @@ -106,11 +106,11 @@ public: std::string bits; is >> bits; if (is) - { - resize(bits.size()); - std::transform(bits.begin(), bits.end(), begin(), + { + resize(bits.size()); + std::transform(bits.begin(), bits.end(), begin(), std::bind2nd(std::equal_to(), '1')); - } + } } }; diff --git a/eo/src/ga/eoBitOp.h b/eo/src/ga/eoBitOp.h index 21205a3d..3e3f4fa5 100644 --- a/eo/src/ga/eoBitOp.h +++ b/eo/src/ga/eoBitOp.h @@ -87,10 +87,10 @@ template class eoDetBitFlip: public eoMonOp { // does not check for duplicate: if someone volunteers .... for (unsigned k=0; k class eoBitMutation: public eoMonOp double actualRate = (normalize ? rate/chrom.size() : rate); bool changed_something = false; for (unsigned i = 0; i < chrom.size(); i++) - if (eo::rng.flip(actualRate)) + if (eo::rng.flip(actualRate)) { - chrom[i] = !chrom[i]; + chrom[i] = !chrom[i]; changed_something = true; } @@ -137,7 +137,7 @@ template class eoBitMutation: public eoMonOp private: double rate; - bool normalize; // divide rate by chromSize + bool normalize; // divide rate by chromSize }; @@ -187,16 +187,16 @@ template class eoBitNext: public eoMonOp bool operator()(Chrom& chrom) { for (int i = chrom.size() - 1; i >= 0; i--) - if (chrom[i]) - { - chrom[i] = 0; - continue; - } - else - { - chrom[i] = 1; - break; - } + if (chrom[i]) + { + chrom[i] = 0; + continue; + } + else + { + chrom[i] = 1; + break; + } return true; } @@ -221,16 +221,16 @@ template class eoBitPrev: public eoMonOp bool operator()(Chrom& chrom) { for (int i = chrom.size() - 1; i >= 0; i--) - if (chrom[i]) - { - chrom[i] = 0; - break; - } - else - { - chrom[i] = 1; - continue; - } + if (chrom[i]) + { + chrom[i] = 0; + break; + } + else + { + chrom[i] = 1; + continue; + } return true; } @@ -281,7 +281,7 @@ template class eoUBitXover: public eoQuadOp eoUBitXover(const float& _preference = 0.5): preference(_preference) { if ( (_preference <= 0.0) || (_preference >= 1.0) ) - std::runtime_error("UxOver --> invalid preference"); + std::runtime_error("UxOver --> invalid preference"); } /// The class name. virtual std::string className() const { return "eoUBitXover"; } @@ -295,18 +295,18 @@ template class eoUBitXover: public eoQuadOp bool operator()(Chrom& chrom1, Chrom& chrom2) { if ( chrom1.size() != chrom2.size()) - std::runtime_error("UxOver --> chromosomes sizes don't match" ); + std::runtime_error("UxOver --> chromosomes sizes don't match" ); bool changed = false; for (unsigned int i=0; i class eoBitGxOver: public eoQuadOp gene_size(_gene_size), num_points(_num_points) { if (gene_size < 1) - std::runtime_error("GxOver --> invalid gene size"); + std::runtime_error("GxOver --> invalid gene size"); if (num_points < 1) - std::runtime_error("GxOver --> invalid number of points"); + std::runtime_error("GxOver --> invalid number of points"); } /// The class name @@ -412,22 +412,22 @@ template class eoBitGxOver: public eoQuadOp // selects genes to swap do { - unsigned bit = eo::rng.random(max_genes); - if (points[bit]) - continue; - else - { - points[bit] = true; - cut_genes--; - } + unsigned bit = eo::rng.random(max_genes); + if (points[bit]) + continue; + else + { + points[bit] = true; + cut_genes--; + } } while (cut_genes); // swaps genes for (unsigned i = 0; i < points.size(); i++) - if (points[i]) - std::swap_ranges(chrom1.begin() + i * gene_size, - chrom1.begin() + i * gene_size + gene_size, - chrom2.begin() + i * gene_size); + if (points[i]) + std::swap_ranges(chrom1.begin() + i * gene_size, + chrom1.begin() + i * gene_size + gene_size, + chrom2.begin() + i * gene_size); return true; } @@ -442,4 +442,3 @@ template class eoBitGxOver: public eoQuadOp //----------------------------------------------------------------------------- //@} #endif - diff --git a/eo/src/ga/eoBitOpFactory.h b/eo/src/ga/eoBitOpFactory.h index b16900e7..6511f937 100644 --- a/eo/src/ga/eoBitOpFactory.h +++ b/eo/src/ga/eoBitOpFactory.h @@ -4,7 +4,7 @@ //----------------------------------------------------------------------------- // eoOpFactory.h // (c) GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -39,135 +39,134 @@ that are created here @ingroup Variators */ template< class EOT> -class eoBitOpFactory: public eoFactory +class eoBitOpFactory: public eoFactory { - + public: - - /// @name ctors and dtors - //{@ - /// constructor - eoBitOpFactory( ) {}; - - /// destructor - virtual ~eoBitOpFactory() {}; - //@} - /** Another factory method: creates an object from an std::istream, reading from - it whatever is needed to create the object. Usually, the format for the std::istream will be\\ - objectType parameter1 parameter2 ... parametern\\ - If there are problems, an std::exception is raised; it should be caught at the - upper level, because it might be something for that level\\ - At the same time, it catches std::exceptions thrown at a lower level, which will - indicate that whatever is in the stream is for this method to process - @param _is an stream from where a single line will be read - @throw runtime_std::exception if the object type is not known - */ - virtual eoOp* make(std::istream& _is) + /// @name ctors and dtors + //{@ + /// constructor + eoBitOpFactory( ) {}; + + /// destructor + virtual ~eoBitOpFactory() {}; + //@} + + /** Another factory method: creates an object from an std::istream, reading from + it whatever is needed to create the object. Usually, the format for the std::istream will be\\ + objectType parameter1 parameter2 ... parametern\\ + If there are problems, an std::exception is raised; it should be caught at the + upper level, because it might be something for that level\\ + At the same time, it catches std::exceptions thrown at a lower level, which will + indicate that whatever is in the stream is for this method to process + @param _is an stream from where a single line will be read + @throw runtime_std::exception if the object type is not known + */ + virtual eoOp* make(std::istream& _is) { - eoOp * opPtr = NULL; - try { - opPtr = eoFactory::make( _is ); - } catch ( const std::string& objectTypeStr ) { - if ( objectTypeStr == "eoBinBitFlip" ) { - opPtr = new eoOneBitFlip( ); - } - // handles old operator names as well as new ones - if ( objectTypeStr == "eoOneBitFlip" ) { - opPtr = new eoOneBitFlip( ); - } + eoOp * opPtr = NULL; + try { + opPtr = eoFactory::make( _is ); + } catch ( const std::string& objectTypeStr ) { + if ( objectTypeStr == "eoBinBitFlip" ) { + opPtr = new eoOneBitFlip( ); + } + // handles old operator names as well as new ones + if ( objectTypeStr == "eoOneBitFlip" ) { + opPtr = new eoOneBitFlip( ); + } - // Standard BitFilp Mutation - if ( objectTypeStr == "eoBinMutation" ) { - float rate; - _is >> rate; - opPtr = new eoBitMutation( rate ); - } - if ( objectTypeStr == "eoBitMutation" ) { - float rate; - _is >> rate; - opPtr = new eoBitMutation( rate ); - } + // Standard BitFilp Mutation + if ( objectTypeStr == "eoBinMutation" ) { + float rate; + _is >> rate; + opPtr = new eoBitMutation( rate ); + } + if ( objectTypeStr == "eoBitMutation" ) { + float rate; + _is >> rate; + opPtr = new eoBitMutation( rate ); + } - // Bit inversion - if ( objectTypeStr == "eoBinInversion" ) { - opPtr = new eoBitInversion( ); - } - if ( objectTypeStr == "eoBitInversion" ) { - opPtr = new eoBitInversion( ); - } + // Bit inversion + if ( objectTypeStr == "eoBinInversion" ) { + opPtr = new eoBitInversion( ); + } + if ( objectTypeStr == "eoBitInversion" ) { + opPtr = new eoBitInversion( ); + } - // Next binary value - if ( objectTypeStr == "eoBinNext" ) { - opPtr = new eoBitNext( ); - } - if ( objectTypeStr == "eoBitNext" ) { - opPtr = new eoBitNext( ); - } + // Next binary value + if ( objectTypeStr == "eoBinNext" ) { + opPtr = new eoBitNext( ); + } + if ( objectTypeStr == "eoBitNext" ) { + opPtr = new eoBitNext( ); + } - // Previous binary value - if ( objectTypeStr == "eoBinPrev" ) { - opPtr = new eoBitPrev( ); - } - if ( objectTypeStr == "eoBitPrev" ) { - opPtr = new eoBitPrev( ); - } + // Previous binary value + if ( objectTypeStr == "eoBinPrev" ) { + opPtr = new eoBitPrev( ); + } + if ( objectTypeStr == "eoBitPrev" ) { + opPtr = new eoBitPrev( ); + } - // 1 point Xover - if ( objectTypeStr == "eoBinCrossover" ) { - opPtr = new eo1PtBitXover( ); - } - if ( objectTypeStr == "eo1PtBitXover" ) { - opPtr = new eo1PtBitXover( ); - } + // 1 point Xover + if ( objectTypeStr == "eoBinCrossover" ) { + opPtr = new eo1PtBitXover( ); + } + if ( objectTypeStr == "eo1PtBitXover" ) { + opPtr = new eo1PtBitXover( ); + } - // Npts Xover - if ( objectTypeStr == "eoBinNxOver" ) { - unsigned nPoints; - _is >> nPoints; - opPtr = new eoNPtsBitXover( nPoints ); - } - if ( objectTypeStr == "eoNPtsBitXover" ) { - unsigned nPoints; - _is >> nPoints; - opPtr = new eoNPtsBitXover( nPoints ); - } + // Npts Xover + if ( objectTypeStr == "eoBinNxOver" ) { + unsigned nPoints; + _is >> nPoints; + opPtr = new eoNPtsBitXover( nPoints ); + } + if ( objectTypeStr == "eoNPtsBitXover" ) { + unsigned nPoints; + _is >> nPoints; + opPtr = new eoNPtsBitXover( nPoints ); + } - // Gene Xover (obsolete) - if ( objectTypeStr == "eoBinGxOver" ) { - unsigned geneSize, nPoints; - _is >> geneSize >> nPoints; - opPtr = new eoBitGxOver( geneSize, nPoints ); - } - if ( objectTypeStr == "eoBitGxOver" ) { - unsigned geneSize, nPoints; - _is >> geneSize >> nPoints; - opPtr = new eoBitGxOver( geneSize, nPoints ); - } + // Gene Xover (obsolete) + if ( objectTypeStr == "eoBinGxOver" ) { + unsigned geneSize, nPoints; + _is >> geneSize >> nPoints; + opPtr = new eoBitGxOver( geneSize, nPoints ); + } + if ( objectTypeStr == "eoBitGxOver" ) { + unsigned geneSize, nPoints; + _is >> geneSize >> nPoints; + opPtr = new eoBitGxOver( geneSize, nPoints ); + } - // Uniform Xover - if ( objectTypeStr == "eoBinUxOver" ) { - float rate; - _is >> rate; - opPtr = new eoUBitXover( rate ); - } - if ( objectTypeStr == "eoUBitXover" ) { - float rate; - _is >> rate; - opPtr = new eoUBitXover( rate ); - } + // Uniform Xover + if ( objectTypeStr == "eoBinUxOver" ) { + float rate; + _is >> rate; + opPtr = new eoUBitXover( rate ); + } + if ( objectTypeStr == "eoUBitXover" ) { + float rate; + _is >> rate; + opPtr = new eoUBitXover( rate ); + } - // nothing read! - if ( !opPtr ) { // to be caught by the upper level - throw objectTypeStr; - } - } - return opPtr; - }; + // nothing read! + if ( !opPtr ) { // to be caught by the upper level + throw objectTypeStr; + } + } + return opPtr; + }; }; #endif - diff --git a/eo/src/ga/eoBoolFlip.h b/eo/src/ga/eoBoolFlip.h index be9d252b..47c43ee0 100644 --- a/eo/src/ga/eoBoolFlip.h +++ b/eo/src/ga/eoBoolFlip.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoBoolFlip.h // (c) Marc Schoenauer, 2003 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -33,7 +33,7 @@ @ingroup Variators */ class eoBoolFlip : public eoMonOp { -public: +public: /** simply flips the boolean argument */ bool operator()(bool & _b) { diff --git a/eo/src/ga/eoPBILAdditive.h b/eo/src/ga/eoPBILAdditive.h index dd360337..e57a05a2 100644 --- a/eo/src/ga/eoPBILAdditive.h +++ b/eo/src/ga/eoPBILAdditive.h @@ -49,8 +49,8 @@ public: * using the default values is equivalent to using eoPBILOrg */ eoPBILAdditive(double _LRBest, unsigned _nbBest = 1, - double _tolerance=0.0, - double _LRWorst = 0.0, unsigned _nbWorst = 0 ) : + double _tolerance=0.0, + double _LRWorst = 0.0, unsigned _nbWorst = 0 ) : maxBound(1.0-_tolerance), minBound(_tolerance), LR(0.0), nbBest(_nbBest), nbWorst(_nbWorst) { @@ -59,18 +59,18 @@ public: if (_nbBest) { - lrb = _LRBest/_nbBest; - LR += _LRBest; + lrb = _LRBest/_nbBest; + LR += _LRBest; } else - lrb=0.0; // just in case + lrb=0.0; // just in case if (_nbWorst) { - lrw = _LRWorst/_nbWorst; - LR += _LRWorst; + lrw = _LRWorst/_nbWorst; + LR += _LRWorst; } else - lrw=0.0; // just in case + lrw=0.0; // just in case } /** Update the distribution from the current population */ @@ -82,29 +82,29 @@ public: unsigned i, popSize=_pop.size(); std::vector result; - _pop.sort(result); // is it necessary to sort the whole population? - // but I'm soooooooo lazy !!! + _pop.sort(result); // is it necessary to sort the whole population? + // but I'm soooooooo lazy !!! for (unsigned g=0; g=popSize-nbWorst; i--) - { - const EOT & best = (*result[i]); - if ( !best[g] ) // if 0, increase proba - p[g] += lrw; - } - // stay in [0,1] (possibly strictly due to tolerance) - p[g] = std::min(maxBound, p[g]); - p[g] = std::max(minBound, p[g]); + p[g] *= (1-LR); // relaxation + if (nbBest) // update from some of the best + for (i=0; i=popSize-nbWorst; i--) + { + const EOT & best = (*result[i]); + if ( !best[g] ) // if 0, increase proba + p[g] += lrw; + } + // stay in [0,1] (possibly strictly due to tolerance) + p[g] = std::min(maxBound, p[g]); + p[g] = std::max(minBound, p[g]); } } diff --git a/eo/src/ga/eoPBILDistrib.h b/eo/src/ga/eoPBILDistrib.h index 91720acb..56556ba0 100644 --- a/eo/src/ga/eoPBILDistrib.h +++ b/eo/src/ga/eoPBILDistrib.h @@ -28,26 +28,26 @@ #include /** - * Distribution Class for PBIL algorithm + * Distribution Class for PBIL algorithm * (Population-Based Incremental Learning, Baluja and Caruana 96) * * It encodes a univariate distribution on the space of bitstrings, * i.e. one probability for each bit to be one * - * It is an eoValueParam > : + * It is an eoValueParam > : * the std::vector stores the probabilities that each bit is 1 * * It is still pure virtual, as the update method needs to be specified */ template -class eoPBILDistrib : public eoDistribution, - public eoValueParam > +class eoPBILDistrib : public eoDistribution, + public eoValueParam > { public: /** Ctor with size of genomes, and update parameters */ eoPBILDistrib(unsigned _genomeSize) : - eoDistribution(), + eoDistribution(), eoValueParam >(std::vector(_genomeSize, 0.5), "Distribution"), genomeSize(_genomeSize) {} @@ -55,10 +55,10 @@ public: /** the randomizer of indis */ virtual void operator()(EOT & _eo) { - _eo.resize(genomeSize); // just in case + _eo.resize(genomeSize); // just in case for (unsigned i=0; i> sz; - + value().resize(sz); unsigned i; - + for (i = 0; i < sz; ++i) { - double atom; - is >> atom; - value()[i] = atom; + double atom; + is >> atom; + value()[i] = atom; } } diff --git a/eo/src/ga/eoPBILOrg.h b/eo/src/ga/eoPBILOrg.h index 80bf2d09..45b95c84 100644 --- a/eo/src/ga/eoPBILOrg.h +++ b/eo/src/ga/eoPBILOrg.h @@ -58,15 +58,15 @@ public: for (unsigned g=0; g // for time(0) for random seeding +#include // for time(0) for random seeding #include #include #include @@ -51,21 +51,21 @@ eoPBILDistrib & do_make_PBILdistrib(eoParser & _parser, eoState& _state, E // First the random seed eoValueParam& seedParam = _parser.createParam(uint32_t(0), "seed", "Random number seed", 'S'); if (seedParam.value() == 0) - seedParam.value() = time(0); + seedParam.value() = time(0); // chromosome size: unsigned theSize; // but it might have been already read in the definition fo the performance eoParam* ptParam = _parser.getParamWithLongName(std::string("chromSize")); - if (!ptParam) // not already defined: read it here + if (!ptParam) // not already defined: read it here { - theSize = _parser.createParam(unsigned(10), "chromSize", "The length of the bitstrings", 'n',"Problem").value(); + theSize = _parser.createParam(unsigned(10), "chromSize", "The length of the bitstrings", 'n',"Problem").value(); } - else // it was read before, get its value + else // it was read before, get its value { - eoValueParam* ptChromSize = dynamic_cast*>(ptParam); - theSize = ptChromSize->value(); + eoValueParam* ptChromSize = dynamic_cast*>(ptParam); + theSize = ptChromSize->value(); } eoPBILDistrib * ptDistrib = new eoPBILDistrib(theSize); diff --git a/eo/src/ga/make_PBILupdate.h b/eo/src/ga/make_PBILupdate.h index 9b4ffd83..a8572136 100644 --- a/eo/src/ga/make_PBILupdate.h +++ b/eo/src/ga/make_PBILupdate.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_PBILupdate.h // (c) Marc Schoenauer, Maarten Keijzer, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -47,7 +47,7 @@ template eoDistribUpdater & do_make_PBILupdate(eoParser & _parser, eoState& _state, EOT) { - // ast the moment, a single update rule is available + // ast the moment, a single update rule is available // but at some point we'll have to choose among different rules std::string UType = _parser.createParam(std::string("PBIL"), "updateRule", "Type of update rule (only PBIL additive at the moment)", 'U', "Algorithm").value(); @@ -59,7 +59,7 @@ eoDistribUpdater & do_make_PBILupdate(eoParser & _parser, eoState& _state, double tolerance = _parser.createParam(0.0, "tolerance", "Keeping away from 0 and 1", 't', "Algorithm").value(); // a pointer to choose among several possible types - eoDistribUpdater * ptUpdate; + eoDistribUpdater * ptUpdate; if (UType == std::string("PBIL")) { @@ -72,7 +72,7 @@ eoDistribUpdater & do_make_PBILupdate(eoParser & _parser, eoState& _state, throw std::runtime_error("Only PBIL additive update rule available at the moment"); // done: don't forget to store the allocated pointers - _state.storeFunctor(ptUpdate); + _state.storeFunctor(ptUpdate); return *ptUpdate; } diff --git a/eo/src/ga/make_algo_scalar_ga.cpp b/eo/src/ga/make_algo_scalar_ga.cpp index aa9b2e05..631e6dad 100644 --- a/eo/src/ga/make_algo_scalar_ga.cpp +++ b/eo/src/ga/make_algo_scalar_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_algo_scalar_ga.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of pop. init. * of the library for ***BISTRING*** evolution inside EO. @@ -35,11 +35,11 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in src/ga/ga.h * while the TEMPLATIZED code is define in make_algo_scalar.h in the src/do dir * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -61,4 +61,3 @@ eoAlgo >& make_algo_scalar(eoParser& _parser, eoStat { return do_make_algo_scalar(_parser, _state, _eval, _continue, _op, _dist); } - diff --git a/eo/src/ga/make_checkpoint_ga.cpp b/eo/src/ga/make_checkpoint_ga.cpp index f7da6d4a..eecc40ca 100644 --- a/eo/src/ga/make_checkpoint_ga.cpp +++ b/eo/src/ga/make_checkpoint_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_checkpoint_ga.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of operators * of the library for ***BISTRING*** evolution inside EO. @@ -35,11 +35,11 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in make_checkpoint_ga.h * while the TEMPLATIZED code is define in make_checkpoint.h in the do dir * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -48,7 +48,7 @@ // the instanciating EOType #include -/// The following function merely call the templatized do_* functions +/// The following function merely call the templatized do_* functions // checkpoint ///////////// @@ -56,9 +56,7 @@ eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state { return do_make_checkpoint(_parser, _state, _eval, _continue); } -eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) +eoCheckPoint >& make_checkpoint(eoParser& _parser, eoState& _state, eoEvalFuncCounter >& _eval, eoContinue >& _continue) { return do_make_checkpoint(_parser, _state, _eval, _continue); } - - diff --git a/eo/src/ga/make_continue_ga.cpp b/eo/src/ga/make_continue_ga.cpp index e2dbb35a..1b25a0c8 100644 --- a/eo/src/ga/make_continue_ga.cpp +++ b/eo/src/ga/make_continue_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_continue_ga.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of operators * of the library for ***BISTRING*** evolution inside EO. @@ -35,11 +35,11 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in ga.h * while the TEMPLATIZED code is define in make_contninue.h in the src/do dir * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -60,5 +60,3 @@ eoContinue >& make_continue(eoParser& _parser, eoStat { return do_make_continue(_parser, _state, _eval); } - - diff --git a/eo/src/ga/make_ga.h b/eo/src/ga/make_ga.h index 6ce8a07a..ce594903 100644 --- a/eo/src/ga/make_ga.h +++ b/eo/src/ga/make_ga.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // ga.h // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -24,14 +24,14 @@ */ //----------------------------------------------------------------------------- -/** This file contains all ***INSTANCIATED*** declarations of all components +/** This file contains all ***INSTANCIATED*** declarations of all components * of the library for ***BISTRING*** evolution inside EO. * It should be included in the file that calls any of the corresponding fns * * The corresponding ***INSTANCIATED*** definitions are contained in ga.cpp * while the TEMPLATIZED code is define in the different makeXXX.h files * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -56,7 +56,7 @@ * @{ */ -// the genotypes +// the genotypes eoInit > & make_genotype(eoParser& _parser, eoState& _state, eoBit _eo); eoInit > & make_genotype(eoParser& _parser, eoState& _state, eoBit _eo); diff --git a/eo/src/ga/make_genotype_ga.cpp b/eo/src/ga/make_genotype_ga.cpp index 873093dc..4f9e69ef 100644 --- a/eo/src/ga/make_genotype_ga.cpp +++ b/eo/src/ga/make_genotype_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_genotype_ga.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of operators * of the library for ***BISTRING*** evolution inside EO. @@ -35,8 +35,8 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained - * in ga.h in src/ga dir + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * in ga.h in src/ga dir * while the TEMPLATIZED code is define in make_genotype_ga.h */ diff --git a/eo/src/ga/make_genotype_ga.h b/eo/src/ga/make_genotype_ga.h index 159b85cd..ea1b2005 100644 --- a/eo/src/ga/make_genotype_ga.h +++ b/eo/src/ga/make_genotype_ga.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_genotype.h // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -36,24 +36,24 @@ /////////////////// the bitstring //////////////// /* - * This fuction does the initialization of what's needed for a particular + * This fuction does the initialization of what's needed for a particular * genotype (here, bitstrings). - * It could be here tempatied only on the fitness, as it can be used to evolve + * It could be here tempatied only on the fitness, as it can be used to evolve * bitstrings with any fitness. - * However, for consistency reasons, it was finally chosen, as in - * the rest of EO, to templatize by the full EOT, as this eventually + * However, for consistency reasons, it was finally chosen, as in + * the rest of EO, to templatize by the full EOT, as this eventually * allows to choose the type of genotype at run time (see in es dir) * * It is instanciated in ga/ga.cpp - and incorporated in the ga/libga.a * - * It returns an eoInit > tha can later be used to initialize + * It returns an eoInit > tha can later be used to initialize * the population (see make_pop.h). * * It uses a parser (to get user parameters) and a state (to store the memory) * the last argument is to disambiguate the call upon different instanciations. * - * WARNING: that last argument will generally be the result of calling - * the default ctor of EOT, resulting in most cases in an EOT + * WARNING: that last argument will generally be the result of calling + * the default ctor of EOT, resulting in most cases in an EOT * that is ***not properly initialized*** * * @ingroup bitstring diff --git a/eo/src/ga/make_op.h b/eo/src/ga/make_op.h index 338557b5..8c46549f 100644 --- a/eo/src/ga/make_op.h +++ b/eo/src/ga/make_op.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_op.h // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -57,9 +57,9 @@ * This is why the template is the complete EOT even though only the fitness * is actually templatized here: the following only applies to bitstrings * - * Note : the last parameter is an eoInit: if some operator needs some info + * Note : the last parameter is an eoInit: if some operator needs some info * about the gneotypes, the init has it all (e.g. bounds, ...) - * Simply do + * Simply do * EOT myEO; * _init(myEO); * and myEO is then an ACTUAL object @@ -78,12 +78,12 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init eoValueParam& operatorParam = _parser.createParam(std::string("SGA"), "operator", "Description of the operator (SGA only now)", 'o', "Variation Operators"); if (operatorParam.value() != std::string("SGA")) - throw std::runtime_error("Only SGA-like operator available right now\n"); + throw std::runtime_error("Only SGA-like operator available right now\n"); - // now we read Pcross and Pmut, + // now we read Pcross and Pmut, // the relative weights for all crossovers -> proportional choice // the relative weights for all mutations -> proportional choice - // and create the eoGenOp that is exactly + // and create the eoGenOp that is exactly // crossover with pcross + mutation with pmut eoValueParam& pCrossParam = _parser.createParam(0.6, "pCross", "Probability of Crossover", 'C', "Variation Operators" ); @@ -118,10 +118,10 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init bool bCross = true; if (onePointRateParam.value()+twoPointsRateParam.value()+uRateParam.value()==0) { - std::cerr << "Warning: no crossover" << std::endl; - bCross = false; + std::cerr << "Warning: no crossover" << std::endl; + bCross = false; } - + // Create the CombinedQuadOp eoPropCombinedQuadOp *ptCombinedQuadOp = NULL; eoQuadOp *ptQuad = NULL; @@ -129,12 +129,12 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init ptQuad = new eo1PtBitXover; _state.storeFunctor(ptQuad); ptCombinedQuadOp = new eoPropCombinedQuadOp(*ptQuad, onePointRateParam.value()); - + // uniform crossover for bitstring ptQuad = new eoUBitXover; _state.storeFunctor(ptQuad); ptCombinedQuadOp->add(*ptQuad, uRateParam.value()); - + // 2-points xover ptQuad = new eoNPtsBitXover; _state.storeFunctor(ptQuad); @@ -155,7 +155,7 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init // minimum check if ( (bitFlipRateParam.value() < 0) ) throw std::runtime_error("Invalid bitFlipRate"); - + eoValueParam & oneBitRateParam = _parser.createParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'd', "Variation Operators" ); // minimum check if ( (oneBitRateParam.value() < 0) ) @@ -165,10 +165,10 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init bool bMut = true; if (bitFlipRateParam.value()+oneBitRateParam.value()==0) { - std::cerr << "Warning: no mutation" << std::endl; - bMut = false; + std::cerr << "Warning: no mutation" << std::endl; + bMut = false; } - + // Create the CombinedMonOp eoPropCombinedMonOp *ptCombinedMonOp = NULL; eoMonOp *ptMon = NULL; @@ -180,7 +180,7 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init ptCombinedMonOp = new eoPropCombinedMonOp(*ptMon, bitFlipRateParam.value()); // mutate exactly 1 bit per individual - ptMon = new eoDetBitFlip; + ptMon = new eoDetBitFlip; _state.storeFunctor(ptMon); ptCombinedMonOp->add(*ptMon, oneBitRateParam.value()); @@ -190,7 +190,7 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init // to simulate SGA (crossover with proba pCross + mutation with proba pMut // we must construct // a sequential combination of - // with proba 1, a proportional combination of + // with proba 1, a proportional combination of // a QuadCopy and our crossover // with proba pMut, our mutation @@ -205,7 +205,7 @@ eoGenOp & do_make_op(eoParser& _parser, eoState& _state, eoInit& _init // now the sequential eoSequentialOp *op = new eoSequentialOp; _state.storeFunctor(op); - op->add(*cross, 1.0); // always crossover (but clone with prob 1-pCross + op->add(*cross, 1.0); // always crossover (but clone with prob 1-pCross op->add(*ptCombinedMonOp, pMutParam.value()); // that's it! diff --git a/eo/src/ga/make_op_ga.cpp b/eo/src/ga/make_op_ga.cpp index 8bed5a66..e3a53d65 100644 --- a/eo/src/ga/make_op_ga.cpp +++ b/eo/src/ga/make_op_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_op_ga.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of operators * of the library for ***BISTRING*** evolution inside EO. @@ -35,11 +35,11 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in make_op_ga.h * while the TEMPLATIZED code is define in make_op.h in the ga dir * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -59,4 +59,3 @@ eoGenOp >& make_op(eoParser& _parser, eoState& _stat { return do_make_op(_parser, _state, _init); } - diff --git a/eo/src/ga/make_pop_ga.cpp b/eo/src/ga/make_pop_ga.cpp index 2ab0b5cd..31927979 100644 --- a/eo/src/ga/make_pop_ga.cpp +++ b/eo/src/ga/make_pop_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_pop_ga.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of population init * of the library for ***BISTRING*** evolution inside EO. @@ -35,7 +35,7 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in ga/make_ga.h * while the TEMPLATIZED code is define in make_pop.h in the src/do dir * @@ -59,5 +59,3 @@ eoPop >& make_pop(eoParser& _parser, eoState& _state { return do_make_pop(_parser, _state, _init); } - - diff --git a/eo/src/ga/make_run_ga.cpp b/eo/src/ga/make_run_ga.cpp index afdab3d9..d64d2b02 100644 --- a/eo/src/ga/make_run_ga.cpp +++ b/eo/src/ga/make_run_ga.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_run_ga.cpp // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif /** This file contains all ***INSTANCIATED DEFINITIONS*** of operators * of the library for ***BISTRING*** evolution inside EO. @@ -35,11 +35,11 @@ * Compiling this file allows one to generate part of the library (i.e. object * files that you just need to link with your own main and fitness code). * - * The corresponding ***INSTANCIATED DECLARATIONS*** are contained + * The corresponding ***INSTANCIATED DECLARATIONS*** are contained * in make_run_ga.h * while the TEMPLATIZED code is define in make_run.h in the do dir * - * Unlike most EO .h files, it does not (and should not) contain any code, + * Unlike most EO .h files, it does not (and should not) contain any code, * just declarations */ @@ -63,4 +63,3 @@ void run_ea(eoAlgo >& _ga, eoPop::printOn(os); + EO::printOn(os); os << ' '; os << size() << ' '; @@ -133,13 +133,13 @@ public: { - EO::readFrom(is); + EO::readFrom(is); unsigned sz; is >> sz; - std::vector v(sz); + std::vector v(sz); unsigned i; @@ -149,24 +149,24 @@ public: is >> node; v[i] = node; } - parse_tree tmp(v.begin(), v.end()); - swap(tmp); + parse_tree tmp(v.begin(), v.end()); + swap(tmp); - /* - * old code which caused problems for paradisEO - * - * this can be removed once it has proved itself - EO::readFrom(is); + /* + * old code which caused problems for paradisEO + * + * this can be removed once it has proved itself + EO::readFrom(is); - // even older code - FType fit; + // even older code + FType fit; is >> fit; fitness(fit); std::copy(std::istream_iterator(is), std::istream_iterator(), back_inserter(*this)); - */ + */ } }; /** @example t-eoSymreg.cpp diff --git a/eo/src/gp/eoParseTreeDepthInit.h b/eo/src/gp/eoParseTreeDepthInit.h index 687c83f2..18dc55b9 100644 --- a/eo/src/gp/eoParseTreeDepthInit.h +++ b/eo/src/gp/eoParseTreeDepthInit.h @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoParseTreeDepthInit.h : initializor for eoParseTree class // (c) Maarten Keijzer 2000 Jeroen Eggermont 2002 @@ -8,20 +8,20 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es - mak@dhi.dk - jeggermo@liacs.nl - + mak@dhi.dk + jeggermo@liacs.nl + */ //----------------------------------------------------------------------------- @@ -48,17 +48,17 @@ template class eoParseTreeDepthInit : public eoInit< eoParseTree > { protected: - // a binary predicate for sorting - // hopefully this will work with M$VC++ 6.0 - struct lt_arity:public std::binary_function - { - bool operator()(const Node &_node1, const Node &_node2) { return (_node1.arity() < _node2.arity());}; - }; + // a binary predicate for sorting + // hopefully this will work with M$VC++ 6.0 + struct lt_arity:public std::binary_function + { + bool operator()(const Node &_node1, const Node &_node2) { return (_node1.arity() < _node2.arity());}; + }; public : typedef eoParseTree EoType; - + /** * Constructor * @param _max_depth The maximum depth of a tree @@ -66,18 +66,18 @@ class eoParseTreeDepthInit : public eoInit< eoParseTree > * @param _grow False results in a full tree, True result is a randomly grown tree * @param _ramped_half_and_half True results in Ramped Half and Half Initialization */ - eoParseTreeDepthInit( + eoParseTreeDepthInit( unsigned _max_depth, - const std::vector& _initializor, + const std::vector& _initializor, bool _grow = true, - bool _ramped_half_and_half = false) + bool _ramped_half_and_half = false) : eoInit(), - max_depth(_max_depth), - initializor(_initializor), - grow(_grow), - ramped_half_and_half(_ramped_half_and_half), - current_depth(_max_depth) + max_depth(_max_depth), + initializor(_initializor), + grow(_grow), + ramped_half_and_half(_ramped_half_and_half), + current_depth(_max_depth) { if(initializor.empty()) { @@ -88,82 +88,82 @@ class eoParseTreeDepthInit : public eoInit< eoParseTree > stable_sort(initializor.begin(), initializor.end(), lt_arity()); } /// My class name - virtual std::string className() const { return "eoParseTreeDepthInit"; }; + virtual std::string className() const { return "eoParseTreeDepthInit"; }; /**initialize a tree * @param _tree : the tree to be initialized */ void operator()(EoType& _tree) - { + { std::list sequence; generate(sequence, current_depth); parse_tree tmp(sequence.begin(), sequence.end()); _tree.swap(tmp); - - if(ramped_half_and_half) - { - if(grow) - { - if (current_depth > 2) - current_depth--; - else - current_depth = max_depth; - } - // change the grow method from 'grow' to 'full' or from 'full' to 'grow' - grow = !grow; - }; - - } + + if(ramped_half_and_half) + { + if(grow) + { + if (current_depth > 2) + current_depth--; + else + current_depth = max_depth; + } + // change the grow method from 'grow' to 'full' or from 'full' to 'grow' + grow = !grow; + }; + + } private : void generate(std::list& sequence, int the_max, int last_terminal = -1) { - if (last_terminal == -1) - { // check where the last terminal in the sequence resides + if (last_terminal == -1) + { // check where the last terminal in the sequence resides typename std::vector::iterator it; - for (it = initializor.begin(); it != initializor.end(); ++it) - { - if (it->arity() > 0) - break; - } - - last_terminal = it - initializor.begin(); - } + for (it = initializor.begin(); it != initializor.end(); ++it) + { + if (it->arity() > 0) + break; + } - if (the_max == 1) - { // generate terminals only - typename std::vector::iterator it = initializor.begin() + rng.random(last_terminal); - it->randomize(); - sequence.push_front(*it); - return; - } - - typename std::vector::iterator what_it; + last_terminal = it - initializor.begin(); + } - if (grow) - { - what_it = initializor.begin() + rng.random(initializor.size()); - } - else // full - { - what_it = initializor.begin() + last_terminal + rng.random(initializor.size() - last_terminal); - } + if (the_max == 1) + { // generate terminals only + typename std::vector::iterator it = initializor.begin() + rng.random(last_terminal); + it->randomize(); + sequence.push_front(*it); + return; + } + + typename std::vector::iterator what_it; + + if (grow) + { + what_it = initializor.begin() + rng.random(initializor.size()); + } + else // full + { + what_it = initializor.begin() + last_terminal + rng.random(initializor.size() - last_terminal); + } what_it->randomize(); - sequence.push_front(*what_it); + sequence.push_front(*what_it); - for (int i = 0; i < what_it->arity(); ++i) - generate(sequence, the_max - 1, last_terminal); + for (int i = 0; i < what_it->arity(); ++i) + generate(sequence, the_max - 1, last_terminal); } - unsigned max_depth; - std::vector initializor; - bool grow; - bool ramped_half_and_half; - unsigned current_depth; + unsigned max_depth; + std::vector initializor; + bool grow; + bool ramped_half_and_half; + unsigned current_depth; }; /** @@ -172,46 +172,46 @@ class eoParseTreeDepthInit : public eoInit< eoParseTree > * @param population_size the size of the population to be created * @param init_max_depth the initial maximum tree depth * @param initializor A std::vector containing the possible nodes - + \ingroup ParseTree */ template void eoInitRampedHalfAndHalf(eoPop< eoParseTree > &pop, unsigned int population_size, unsigned int init_max_depth, std::vector &initializor) { - typedef eoParseTree EoType; - typedef eoPop< EoType > Pop; - - unsigned int M = init_max_depth - 1; - unsigned int part_pop_size = population_size / (2*M); - unsigned int m=0; + typedef eoParseTree EoType; + typedef eoPop< EoType > Pop; - std::cerr << "EO WARNING: Ramped Half and Half Initialization is now supported by eoParseTreeDepthInit." << std::endl; - std::cerr << " This function is now obsolete and might be removed in the future so you should"<< std::endl; - std::cerr << " update your code to use: " << std::endl << std::endl; - std::cerr << " eoParseTreeDepthInit( _max_depth, _initializer, bool _grow, bool _ramped_half_and_half)" << std::endl << std::endl; - - pop.clear(); - - // initialize with Depth's (D) -> 2 - for(m=init_max_depth; m >= 2; m--) - { - eoParseTreeDepthInit grow_initializer(m, initializor, true); - Pop grow(part_pop_size, grow_initializer); - pop.insert(pop.begin(), grow.begin(), grow.end()); - - eoParseTreeDepthInit full_initializer(m, initializor, false); - Pop full(part_pop_size, full_initializer); - pop.insert(pop.begin(), full.begin(), full.end()); - } - - bool g = true; - while (pop.size() < population_size) - { - eoParseTreeDepthInit initializer(init_max_depth, initializor, g); - Pop p(1, initializer); - pop.insert(pop.begin(), p.begin(), p.end()); - g= !g; - } + unsigned int M = init_max_depth - 1; + unsigned int part_pop_size = population_size / (2*M); + unsigned int m=0; + + std::cerr << "EO WARNING: Ramped Half and Half Initialization is now supported by eoParseTreeDepthInit." << std::endl; + std::cerr << " This function is now obsolete and might be removed in the future so you should"<< std::endl; + std::cerr << " update your code to use: " << std::endl << std::endl; + std::cerr << " eoParseTreeDepthInit( _max_depth, _initializer, bool _grow, bool _ramped_half_and_half)" << std::endl << std::endl; + + pop.clear(); + + // initialize with Depth's (D) -> 2 + for(m=init_max_depth; m >= 2; m--) + { + eoParseTreeDepthInit grow_initializer(m, initializor, true); + Pop grow(part_pop_size, grow_initializer); + pop.insert(pop.begin(), grow.begin(), grow.end()); + + eoParseTreeDepthInit full_initializer(m, initializor, false); + Pop full(part_pop_size, full_initializer); + pop.insert(pop.begin(), full.begin(), full.end()); + } + + bool g = true; + while (pop.size() < population_size) + { + eoParseTreeDepthInit initializer(init_max_depth, initializor, g); + Pop p(1, initializer); + pop.insert(pop.begin(), p.begin(), p.end()); + g= !g; + } } diff --git a/eo/src/gp/eoParseTreeOp.h b/eo/src/gp/eoParseTreeOp.h index 58824eea..0b623f3d 100644 --- a/eo/src/gp/eoParseTreeOp.h +++ b/eo/src/gp/eoParseTreeOp.h @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoParseTreeOp.h : crossover and mutation operator for the eoParseTree class // (c) Maarten Keijzer 2000 for eoSubtreeXOver, eoBranchMutation @@ -10,18 +10,18 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es - mak@dhi.dk + mak@dhi.dk jeggermo@liacs.nl */ //----------------------------------------------------------------------------- @@ -34,8 +34,8 @@ #include -/** eoSubtreeXOver --> subtree xover -\class eoSubtreeXOver eoParseTreeOp.h gp/eoParseTreeOp.h +/** eoSubtreeXOver --> subtree xover +\class eoSubtreeXOver eoParseTreeOp.h gp/eoParseTreeOp.h \ingroup ParseTree */ template @@ -63,23 +63,23 @@ public: */ bool operator()(EoType & _eo1, EoType & _eo2 ) { - int i = rng.random(_eo1.size()); - int j = rng.random(_eo2.size()); + int i = rng.random(_eo1.size()); + int j = rng.random(_eo2.size()); - typename parse_tree::subtree tmp = _eo1[i]; - _eo1[i] = _eo2[j]; // insert subtree - _eo2[j] = tmp; + typename parse_tree::subtree tmp = _eo1[i]; + _eo1[i] = _eo2[j]; // insert subtree + _eo2[j] = tmp; + + _eo1.pruneTree(max_length); + _eo2.pruneTree(max_length); - _eo1.pruneTree(max_length); - _eo2.pruneTree(max_length); - return true; } private: unsigned max_length; }; -/** eoBranchMutation --> replace a subtree with a randomly created subtree +/** eoBranchMutation --> replace a subtree with a randomly created subtree \class eoBranchMutation eoParseTreeOp.h gp/eoParseTreeOp.h \ingroup ParseTree */ @@ -97,29 +97,29 @@ public: eoBranchMutation(eoInit& _init, unsigned _max_length) : eoMonOp(), max_length(_max_length), initializer(_init) {}; - + /// the class name virtual std::string className() const { return "eoBranchMutation"; }; /// Dtor virtual ~eoBranchMutation() {}; - + /** * Mutate an individual * @param _eo1 The individual that is to be changed */ bool operator()(EoType& _eo1 ) { - int i = rng.random(_eo1.size()); + int i = rng.random(_eo1.size()); EoType eo2; initializer(eo2); - int j = rng.random(eo2.size()); + int j = rng.random(eo2.size()); - _eo1[i] = eo2[j]; // insert subtree + _eo1[i] = eo2[j]; // insert subtree - _eo1.pruneTree(max_length); + _eo1.pruneTree(max_length); return true; } @@ -130,7 +130,7 @@ private : eoInit& initializer; }; -// Additional Mutation operators from +// Additional Mutation operators from // TITLE:"Genetic Programming~An Introduction" // AUTHORS: Banzhaf, Nordin, Keller, Francone // ISBN: 3-920993-58-6 @@ -138,8 +138,8 @@ private : // // For the eoParseTree class -/** eoPointMutation --> replace a Node with a Node of the same arity -\class eoPointMutation eoParseTreeOp.h gp/eoParseTreeOp.h +/** eoPointMutation --> replace a Node with a Node of the same arity +\class eoPointMutation eoParseTreeOp.h gp/eoParseTreeOp.h \ingroup ParseTree */ @@ -157,7 +157,7 @@ public: eoPointMutation( std::vector& _initializor) : eoMonOp(), initializor(_initializor) {}; - + /// the class name virtual std::string className() const { return "eoPointMutation"; }; @@ -170,32 +170,32 @@ public: */ bool operator()(EoType& _eo1 ) { - // select a random node i that is to be mutated - int i = rng.random(_eo1.size()); - // request the arity of the node that is to be replaced - int arity = _eo1[i].arity(); - - int j=0; - - do - { - j = rng.random(initializor.size()); - - }while ((initializor[j].arity() != arity)); - - _eo1[i] = initializor[j]; - - - - return true; + // select a random node i that is to be mutated + int i = rng.random(_eo1.size()); + // request the arity of the node that is to be replaced + int arity = _eo1[i].arity(); + + int j=0; + + do + { + j = rng.random(initializor.size()); + + }while ((initializor[j].arity() != arity)); + + _eo1[i] = initializor[j]; + + + + return true; } private : - std::vector& initializor; + std::vector& initializor; }; -/** eoExpansionMutation --> replace a terminal with a randomly created subtree +/** eoExpansionMutation --> replace a terminal with a randomly created subtree \class eoExpansionMutation eoParseTreeOp.h gp/eoParseTreeOp.h \ingroup ParseTree */ @@ -206,7 +206,7 @@ class eoExpansionMutation: public eoMonOp< eoParseTree > public: typedef eoParseTree EoType; - + /** * Constructor * @param _init An instantiation of eoGpDepthInitializer @@ -215,7 +215,7 @@ public: eoExpansionMutation(eoInit& _init, unsigned _max_length) : eoMonOp(), max_length(_max_length), initializer(_init) {}; - + /// The class name virtual std::string className() const { return "eoExpansionMutation"; }; @@ -227,33 +227,33 @@ public: */ bool operator()(EoType& _eo1 ) { - int i = rng.random(_eo1.size()); - // look for a terminal + int i = rng.random(_eo1.size()); + // look for a terminal while (_eo1[i].arity() != 0) - { - i= rng.random(_eo1.size()); - }; - - // create a new tree to - EoType eo2; - // make sure we get a tree with more than just a terminal - do - { - initializer(eo2); - }while(eo2.size() == 1); - - int j = rng.random(eo2.size()); - // make sure we select a subtree (and not a terminal) - while((eo2[j].arity() == 0)) - { - j = rng.random(eo2.size()); - }; - + { + i= rng.random(_eo1.size()); + }; - _eo1[i] = eo2[j]; // insert subtree + // create a new tree to + EoType eo2; + // make sure we get a tree with more than just a terminal + do + { + initializer(eo2); + }while(eo2.size() == 1); + + int j = rng.random(eo2.size()); + // make sure we select a subtree (and not a terminal) + while((eo2[j].arity() == 0)) + { + j = rng.random(eo2.size()); + }; + + + _eo1[i] = eo2[j]; // insert subtree + + _eo1.pruneTree(max_length); - _eo1.pruneTree(max_length); - return true; } @@ -294,29 +294,29 @@ public: */ bool operator()(EoType& _eo1 ) { - int i = rng.random(_eo1.size()); - // look for a subtree + int i = rng.random(_eo1.size()); + // look for a subtree while ((_eo1[i].arity() == 0) && (_eo1.size() > 1)) - { - i= rng.random(_eo1.size()); - }; - - // create a new tree to - EoType eo2; - initializer(eo2); - - int j = rng.random(eo2.size()); - // make sure we select a subtree (and not a terminal) - while(eo2[j].arity() != 0) - { - j = rng.random(eo2.size()); - }; + { + i= rng.random(_eo1.size()); + }; + + // create a new tree to + EoType eo2; + initializer(eo2); + + int j = rng.random(eo2.size()); + // make sure we select a subtree (and not a terminal) + while(eo2[j].arity() != 0) + { + j = rng.random(eo2.size()); + }; + + _eo1[i] = eo2[j]; // insert subtree + + // we don't have to prune because the subtree is always smaller + _eo1.pruneTree(max_length); - _eo1[i] = eo2[j]; // insert subtree - - // we don't have to prune because the subtree is always smaller - _eo1.pruneTree(max_length); - return true; } @@ -327,11 +327,11 @@ private : }; -/** eoHoistMutation --> replace the individual with one of its subtree's +/** eoHoistMutation --> replace the individual with one of its subtree's \class eoHoistMutation eoParseTreeOp.h gp/eoParseTreeOp.h \ingroup ParseTree */ - + template class eoHoistMutation: public eoMonOp< eoParseTree > { @@ -345,7 +345,7 @@ public: eoHoistMutation() : eoMonOp() {}; - + /// The class name virtual std::string className() const { return "eoHoistMutation"; }; @@ -357,17 +357,17 @@ public: */ bool operator()(EoType& _eo1 ) { - - - // select a hoist point - int i = rng.random(_eo1.size()); - // and create a new tree - EoType eo2(_eo1[i]); - - // we don't have to prune because the new tree is always smaller - //_eo1.pruneTree(max_length); - - _eo1 = eo2; + + + // select a hoist point + int i = rng.random(_eo1.size()); + // and create a new tree + EoType eo2(_eo1[i]); + + // we don't have to prune because the new tree is always smaller + //_eo1.pruneTree(max_length); + + _eo1 = eo2; return true; } diff --git a/eo/src/gp/eoStParseTreeDepthInit.h b/eo/src/gp/eoStParseTreeDepthInit.h index 43c4c2a2..37b17887 100644 --- a/eo/src/gp/eoStParseTreeDepthInit.h +++ b/eo/src/gp/eoStParseTreeDepthInit.h @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoStParseTreeDepthInit.h : initializor strongly type GP // (c) Jeroen Eggermont 2001 @@ -8,19 +8,19 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es - jeggermo@liacs.nl - + jeggermo@liacs.nl + */ //----------------------------------------------------------------------------- @@ -49,7 +49,7 @@ using namespace gp_parse_tree; individual but now each node class must have two additional functions. \li int type(void) which returns the return type of the node \li int type(int child) which returns the required type for child 0, 1 or 2 - + Pruning strongly typed trees is not possible at the moment. \ingroup Representations @@ -66,7 +66,7 @@ class eoStParseTreeDepthInit : public eoInit< eoParseTree > public : typedef eoParseTree EoType; - + /** * Constructor * @param _max_depth The maximum depth of a tree @@ -74,121 +74,121 @@ class eoStParseTreeDepthInit : public eoInit< eoParseTree > * @param _return_type (JD_2010-11-09: don't know the use of this parameter, maybe to force implicit template instanciation?) * @param _grow False results in a full tree, True result is a randomly grown tree */ - eoStParseTreeDepthInit( + eoStParseTreeDepthInit( unsigned _max_depth, - const std::vector& _node, - const int& _return_type, + const std::vector& _node, + const int& _return_type, bool _grow = true) : eoInit(), - max_depth(_max_depth), - return_type(_return_type), - grow(_grow) + max_depth(_max_depth), + return_type(_return_type), + grow(_grow) { if(_node.empty()) { throw std::logic_error("eoStParseTreeDepthInit: uhm, wouldn't you rather give a non-empty set of Nodes?"); } - - + + unsigned int i=0; int arity=0; int type=0; std::vector node_vector; for(i=0; i < _node.size(); i++) { - arity = _node[i].arity(); - type = _node[i].type(); - if(arity==0) - { - node_vector = node[type][TERMINAL]; - node_vector.push_back(_node[i]); - node[type][TERMINAL]= node_vector; - } - else - //if (arity != 0) // non-terminal - { - node_vector = node[type][NONTERMINAL]; - node_vector.push_back(_node[i]); - node[type][NONTERMINAL] = node_vector; - } - node_vector = node[type][ALL]; - node_vector.push_back(_node[i]); - node[type][ALL] = node_vector; - + arity = _node[i].arity(); + type = _node[i].type(); + if(arity==0) + { + node_vector = node[type][TERMINAL]; + node_vector.push_back(_node[i]); + node[type][TERMINAL]= node_vector; + } + else + //if (arity != 0) // non-terminal + { + node_vector = node[type][NONTERMINAL]; + node_vector.push_back(_node[i]); + node[type][NONTERMINAL] = node_vector; + } + node_vector = node[type][ALL]; + node_vector.push_back(_node[i]); + node[type][ALL] = node_vector; + } - + } /// My class name - virtual std::string className() const { return "eoStParseTreeDepthInit"; }; + virtual std::string className() const { return "eoStParseTreeDepthInit"; }; /**initialize a tree * @param _tree : the tree to be initialized */ void operator()(EoType& _tree) - { - std::list sequence; - bool good_tree = false; - do - { - sequence.clear(); - good_tree = generate(sequence, max_depth, return_type); - }while (!good_tree); + { + std::list sequence; + bool good_tree = false; + do + { + sequence.clear(); + good_tree = generate(sequence, max_depth, return_type); + }while (!good_tree); - parse_tree tmp(sequence.begin(), sequence.end()); - _tree.swap(tmp); - } + parse_tree tmp(sequence.begin(), sequence.end()); + _tree.swap(tmp); + } private : bool generate(std::list& sequence, int the_max, int request_type) { - - int selected=0; - bool ok = true; - - if (the_max == 1) - { // generate terminals only - if( node[request_type][TERMINAL].empty() ) // no possible terminal node of this type - return false; // we have an invalid tree - else - { - selected = rng.random((node[request_type][TERMINAL]).size()); - sequence.push_front(node[request_type][TERMINAL][selected]); - return true; - } - - } - - int arity=0; - if (grow) - { - selected = rng.random((node[request_type][ALL]).size()); - arity = node[request_type][ALL][selected].arity(); - sequence.push_front(node[request_type][ALL][selected]); - for (int i = 0; i < arity; ++i) - ok &= generate(sequence, the_max - 1, node[request_type][ALL][selected].type(i)); - } - else // full - { - selected = rng.random((node[request_type][NONTERMINAL]).size()); - arity = node[request_type][NONTERMINAL][selected].arity(); - sequence.push_front(node[request_type][NONTERMINAL][selected]); - for (int i = 0; i < arity; ++i) - ok &=generate(sequence, the_max - 1, node[request_type][NONTERMINAL][selected].type(i)); - } - - return ok; - + + int selected=0; + bool ok = true; + + if (the_max == 1) + { // generate terminals only + if( node[request_type][TERMINAL].empty() ) // no possible terminal node of this type + return false; // we have an invalid tree + else + { + selected = rng.random((node[request_type][TERMINAL]).size()); + sequence.push_front(node[request_type][TERMINAL][selected]); + return true; + } + + } + + int arity=0; + if (grow) + { + selected = rng.random((node[request_type][ALL]).size()); + arity = node[request_type][ALL][selected].arity(); + sequence.push_front(node[request_type][ALL][selected]); + for (int i = 0; i < arity; ++i) + ok &= generate(sequence, the_max - 1, node[request_type][ALL][selected].type(i)); + } + else // full + { + selected = rng.random((node[request_type][NONTERMINAL]).size()); + arity = node[request_type][NONTERMINAL][selected].arity(); + sequence.push_front(node[request_type][NONTERMINAL][selected]); + for (int i = 0; i < arity; ++i) + ok &=generate(sequence, the_max - 1, node[request_type][NONTERMINAL][selected].type(i)); + } + + return ok; + } - - unsigned max_depth; - std::map < int, std::map < int, std::vector > > node; + + unsigned max_depth; + std::map < int, std::map < int, std::vector > > node; int return_type; - bool grow; + bool grow; }; #endif diff --git a/eo/src/gp/eoStParseTreeOp.h b/eo/src/gp/eoStParseTreeOp.h index eb0d1023..88020448 100644 --- a/eo/src/gp/eoStParseTreeOp.h +++ b/eo/src/gp/eoStParseTreeOp.h @@ -1,5 +1,5 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- - + //----------------------------------------------------------------------------- // eoStParseTreeOp.h : crossover and mutation operators for the strongly typed GP // (c) Jeroen Eggermont 2001 for other mutation operators @@ -9,18 +9,18 @@ modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. - + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - + Contact: todos@geneura.ugr.es, http://geneura.ugr.es - mak@dhi.dk + mak@dhi.dk jeggermo@liacs.nl */ //----------------------------------------------------------------------------- @@ -40,17 +40,17 @@ template void get_possible_nodes(const EOT &_eo, std::vector &possible_nodes, const int type) { - int n=0; - possible_nodes.clear(); - // collect the possible crossover points in _eo (nodes with the same type) - for(n=0; n < _eo.size(); n++) - if (type == _eo[n]->type()) - possible_nodes.push_back(n); -} + int n=0; + possible_nodes.clear(); + // collect the possible crossover points in _eo (nodes with the same type) + for(n=0; n < _eo.size(); n++) + if (type == _eo[n]->type()) + possible_nodes.push_back(n); +} /** eoStSubtreeXOver --> subtree xover for strongly typed tree-based genetic programming -\class eoStSubtreeXOver eoStParseTreeOp.h gp/eoStParseTreeOp.h +\class eoStSubtreeXOver eoStParseTreeOp.h gp/eoStParseTreeOp.h \ingroup StParseTree */ template @@ -78,54 +78,54 @@ public: */ bool operator()(EoType & _eo1, EoType & _eo2 ) { - int i = 0; - std::vector nodes; - int n = 0; - int type = 0; - int j = 0; - std::set test; - do - { - do // select a random node in _eo1 as crossover point, and check if we didn't try it already - { - i = rng.random(_eo1.size()); - }while(test.count(i) > 0); - - test.insert(i); - - type = _eo1[i]->type(); - - get_possible_nodes(_eo2, nodes, type); - - }while(nodes.empty() && (test.size() < _eo1.size())); - - if (nodes.empty()) // we failed to select a crossover point but tried all points (test.size() == _eo1.size()). - return true; // should this be false ?? + int i = 0; + std::vector nodes; + int n = 0; + int type = 0; + int j = 0; + std::set test; + do + { + do // select a random node in _eo1 as crossover point, and check if we didn't try it already + { + i = rng.random(_eo1.size()); + }while(test.count(i) > 0); - // we did find at least one possible crossover point in _eo2 - - n = rng.random(nodes.size()); - j = nodes[n]; - + test.insert(i); - - typename eoParseTree::subtree tmp = _eo1[i]; - _eo1[i] = _eo2[j]; // insert subtree - _eo2[j] = tmp; + type = _eo1[i]->type(); - // we can't prune anymore - /* + get_possible_nodes(_eo2, nodes, type); + + }while(nodes.empty() && (test.size() < _eo1.size())); + + if (nodes.empty()) // we failed to select a crossover point but tried all points (test.size() == _eo1.size()). + return true; // should this be false ?? + + // we did find at least one possible crossover point in _eo2 + + n = rng.random(nodes.size()); + j = nodes[n]; + + + + typename eoParseTree::subtree tmp = _eo1[i]; + _eo1[i] = _eo2[j]; // insert subtree + _eo2[j] = tmp; + + // we can't prune anymore + /* _eo1.pruneTree(max_length); _eo2.pruneTree(max_length); - */ - - return true; + */ + + return true; } private: unsigned max_length; }; -/** eoStBranchMutation --> replace a strongly typed subtree with a randomly created strongly typed subtree +/** eoStBranchMutation --> replace a strongly typed subtree with a randomly created strongly typed subtree \class eoStBranchMutation eoStParseTreeOp.h gp/eoStParseTreeOp.h \ingroup StParseTree */ @@ -143,42 +143,42 @@ public: eoStBranchMutation(eoInit& _init, unsigned _max_length) : eoMonOp(), max_length(_max_length), initializer(_init) {}; - + /// the class name virtual std::string className() const { return "eoStBranchMutation"; }; /// Dtor virtual ~eoStBranchMutation() {}; - + /** * Mutate an individual * @param _eo1 The individual that is to be changed */ bool operator()(EoType& _eo1 ) { - int i = rng.random(_eo1.size()); - std::vector nodes; - int type = _eo1[i]->type(); - int j=0; - int n=0; + int i = rng.random(_eo1.size()); + std::vector nodes; + int type = _eo1[i]->type(); + int j=0; + int n=0; - EoType eo2; - - do - { - initializer(eo2); - get_possible_nodes(eo2, nodes, type); - }while (nodes.empty()); + EoType eo2; - n = rng.random(nodes.size()); - j = nodes[n]; - - _eo1[i] = eo2[j]; // insert subtree - - // no more pruning - /* - _eo1.pruneTree(max_length); - */ + do + { + initializer(eo2); + get_possible_nodes(eo2, nodes, type); + }while (nodes.empty()); + + n = rng.random(nodes.size()); + j = nodes[n]; + + _eo1[i] = eo2[j]; // insert subtree + + // no more pruning + /* + _eo1.pruneTree(max_length); + */ return true; } @@ -208,22 +208,22 @@ public: eoStPointMutation( std::vector& _node) : eoMonOp() { - unsigned int i=0; + unsigned int i=0; int arity=0; int type=0; std::vector node_vector; for(i=0; i < _node.size(); i++) { - arity = _node[i].arity(); - type = _node[i].type(); - - node_vector = node[type][arity]; - node_vector.push_back(_node[i]); - node[type][arity]= node_vector; - + arity = _node[i].arity(); + type = _node[i].type(); + + node_vector = node[type][arity]; + node_vector.push_back(_node[i]); + node[type][arity]= node_vector; + }; }; - + /// the class name virtual std::string className() const { return "eoStPointMutation"; }; @@ -236,24 +236,24 @@ public: */ bool operator()(EoType& _eo1 ) { - // select a random node i that is to be mutated - int i = rng.random(_eo1.size()); - int arity = _eo1[i].arity(); - int type = _eo1[i]->type(); - int j = rng.random(node[type][arity].size()); + // select a random node i that is to be mutated + int i = rng.random(_eo1.size()); + int arity = _eo1[i].arity(); + int type = _eo1[i]->type(); + int j = rng.random(node[type][arity].size()); - - _eo1[i] = node[type][arity][j]; - return true; + + _eo1[i] = node[type][arity][j]; + return true; } private : - - std::map < int, std::map < int, std::vector > > node; + + std::map < int, std::map < int, std::vector > > node; }; - - /** eoStHoistMutation --> replace the individual with one of its strongly typed subtree's + + /** eoStHoistMutation --> replace the individual with one of its strongly typed subtree's \class eoStHoistMutation eoStParseTreeOp.h gp/eoStParseTreeOp.h \ingroup StParseTree */ @@ -271,13 +271,13 @@ public: eoStHoistMutation(eoInit& _init, unsigned _max_length) : eoMonOp(), max_length(_max_length), initializer(_init) {}; - + /// the class name virtual std::string className() const { return "eoStHoistMutation"; }; /// Dtor virtual ~eoStHoistMutation() {}; - + /** * Mutate an individual * @param _eo1 The individual that is to be changed @@ -285,19 +285,19 @@ public: bool operator()(EoType& _eo1 ) { - std::vector nodes; - // get the type of the current tree - int type = _eo1[ _eo1.size() - 1 ]->type(); + std::vector nodes; + // get the type of the current tree + int type = _eo1[ _eo1.size() - 1 ]->type(); - get_possible_nodes(_eo1, nodes, type); - - // select a subtree-node to replace the current tree - int n = rng.random(nodes.size()); - int i = nodes[n]; - - EoType eo2(_eo1[i]); - - _eo1 = eo2; + get_possible_nodes(_eo1, nodes, type); + + // select a subtree-node to replace the current tree + int n = rng.random(nodes.size()); + int i = nodes[n]; + + EoType eo2(_eo1[i]); + + _eo1 = eo2; return true; } diff --git a/eo/src/gp/node_pool.h b/eo/src/gp/node_pool.h index e3b41b8a..8935e7e2 100644 --- a/eo/src/gp/node_pool.h +++ b/eo/src/gp/node_pool.h @@ -1,13 +1,13 @@ /** * Pool allocator for the subtree and parse tree classes (homebrew and not compliant to ANSI allocator requirements) - * (c) copyright Maarten Keijzer 1999, 2000 + * (c) copyright Maarten Keijzer 1999, 2000 - * Permission to copy, use, modify, sell and distribute this software is granted provided + * Permission to copy, use, modify, sell and distribute this software is granted provided * this copyright notice appears in all copies. This software is provided "as is" without * express or implied warranty, and with no claim as to its suitability for * any purpose. - + * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. @@ -21,7 +21,7 @@ class MemPool { public : - + MemPool(unsigned int sz) : esize(sz(p)->next = + reinterpret_cast(p)->next = reinterpret_cast(p + esize); } - + reinterpret_cast(last)->next = 0; head = reinterpret_cast(start); } @@ -91,15 +91,15 @@ template class Node_alloc { public : - - T* allocate(void) + + T* allocate(void) { T* t = static_cast(mem.allocate()); t = new (t) T; return t; } - - T* construct(const T& org) + + T* construct(const T& org) { T* t = static_cast(mem.allocate()); t = new (t) T(org); @@ -117,7 +117,7 @@ private : }; -template +template class Standard_alloc { public : @@ -130,7 +130,7 @@ public : return new T [arity]; } - + T* construct(size_t arity, T* org) { if (arity == 0) @@ -154,7 +154,7 @@ public : }; -template +template class Standard_Node_alloc { public : @@ -270,19 +270,19 @@ public : switch(arity) { case 0: return; - case 3 : + case 3 : { t[2].~T(); t[1].~T(); t[0].~T(); mem3.deallocate(static_cast(t)); return; } - case 2 : + case 2 : { t[1].~T(); t[0].~T(); mem2.deallocate(static_cast(t)); return; } - case 1 : + case 1 : { t[0].~T(); mem1.deallocate(static_cast(t)); @@ -295,7 +295,7 @@ public : } } } - + private : static MemPool mem1; diff --git a/eo/src/gp/parse_tree.h b/eo/src/gp/parse_tree.h index 8437c0c7..84ec04d3 100644 --- a/eo/src/gp/parse_tree.h +++ b/eo/src/gp/parse_tree.h @@ -23,22 +23,22 @@ ****** Arity ****** \code - int arity(void) const + int arity(void) const \endcode - Note: the default constructor of a Node should provide a - Node with arity 0! + Note: the default constructor of a Node should provide a + Node with arity 0! ****** Evaluation ****** A parse_tree is evaluated through one of it's apply() members: - 1) parse_tree::apply(RetVal) + 1) parse_tree::apply(RetVal) - is the simplest evaluation, it will call + is the simplest evaluation, it will call \code - RetVal Node::operator()(RetVal, subtree::const_iterator) + RetVal Node::operator()(RetVal, subtree::const_iterator) \endcode (Unfortunately the first RetVal argument is mandatory (although you @@ -49,7 +49,7 @@ error. That is why you have to call tree.apply(double()) instead.) - 2) parse_tree::apply(RetVal v, It values) + 2) parse_tree::apply(RetVal v, It values) will call: @@ -58,10 +58,10 @@ \endcode where It is whatever type you desire (most of the time - this will be a std::vector containing the values of your - variables); + this will be a std::vector containing the values of your + variables); - 3) parse_tree::apply(RetVal, It values, It2 moreValues) + 3) parse_tree::apply(RetVal, It values, It2 moreValues) will call: @@ -69,26 +69,26 @@ RetVal Node::operator()(RetVal, subtree<... , It values, It2 moreValues) \endcode - although I do not see the immediate use of this, however... + although I do not see the immediate use of this, however... - 4) parse_tree::apply(RetVal, It values, It2 args, It3 adfs) + 4) parse_tree::apply(RetVal, It values, It2 args, It3 adfs) - that calls: + that calls: \code RetVal Node::operator()(subtree<... , It values, It2 args, It3 adfs) \endcode - can be useful for implementing adfs. + can be useful for implementing adfs. - In general it is a good idea to leave the specifics of the - arguments open so that different ways of evaluation remain - possible. Implement the simplest eval as: + In general it is a good idea to leave the specifics of the + arguments open so that different ways of evaluation remain + possible. Implement the simplest eval as: \code - template - RetVal operator()(RetVal dummy, It begin) const + template + RetVal operator()(RetVal dummy, It begin) const \endcode ****** Internal Structure ****** @@ -99,10 +99,10 @@ The nodes are stored in a tree like : - node4 - / \ - node3 node2 - / \ + node4 + / \ + node3 node2 + / \ node1 node0 where nodes 2 and 4 have arity 2 and nodes 0,1 and 3 arity 0 (terminals) @@ -129,9 +129,9 @@ will not crash and result in a tree structured as: - node4 - / \ - node3 node0 + node4 + / \ + node3 node0 Note that the rank numbers no longer specify their place in the tree: @@ -212,10 +212,10 @@ public : typedef subtree* iterator; typedef const subtree* const_iterator; - /* Constructors, assignments */ + /* Constructors, assignments */ subtree(void) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) - {} + {} subtree(const subtree& s) : content(node_allocator.allocate()), args(0), @@ -228,7 +228,7 @@ public : } subtree(const T& t) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) - { copy(t); } + { copy(t); } template subtree(It b, It e) : content(node_allocator.allocate()), args(0), parent(0), _cumulative_size(0), _depth(0), _size(1) @@ -239,57 +239,57 @@ public : virtual ~subtree(void) { tree_allocator.deallocate(args, arity()); node_allocator.deallocate(content); } subtree& operator=(const subtree& s) - { - if (s.get_root() == get_root()) + { + if (s.get_root() == get_root()) { // from the same tree, maybe a child. Don't take any chances subtree anotherS = s; return copy(anotherS); } - copy(s); + copy(s); updateAfterInsert(); return *this; - } + } subtree& operator=(const T& t) { copy(t); updateAfterInsert(); return *this; } - /* Access to the nodes */ + /* Access to the nodes */ T& operator*(void) { return *content; } const T& operator*(void) const { return *content; } T* operator->(void) { return content; } const T* operator->(void) const { return content; } - /* Equality, inequality check, Node needs to implement operator== */ + /* Equality, inequality check, Node needs to implement operator== */ - bool operator==(const subtree& other) const - { - if (! (*content == *other.content)) - return false; + bool operator==(const subtree& other) const + { + if (! (*content == *other.content)) + return false; - for (int i = 0; i < arity(); i++) - { - if (!(args[i] == other.args[i])) - return false; - } + for (int i = 0; i < arity(); i++) + { + if (!(args[i] == other.args[i])) + return false; + } - return true; - } + return true; + } - bool operator !=(const subtree& other) const - { - return !operator==(other); - } + bool operator !=(const subtree& other) const + { + return !operator==(other); + } - /* Arity */ + /* Arity */ int arity(void) const { return content->arity(); } - /* Evaluation with an increasing amount of user defined arguments */ - template - void apply(RetVal& v) const { (*content)(v, begin()); } + /* Evaluation with an increasing amount of user defined arguments */ + template + void apply(RetVal& v) const { (*content)(v, begin()); } - template - void apply(RetVal& v, It values) const + template + void apply(RetVal& v, It values) const { (*content)(v, begin(), values); } @@ -302,12 +302,12 @@ public : /* template - void apply(RetVal& v, It values, It2 moreValues) const - { (*content)(v, begin(), values, moreValues); } + void apply(RetVal& v, It values, It2 moreValues) const + { (*content)(v, begin(), values, moreValues); } - template - void apply(RetVal& v, It values, It2 moreValues, It3 evenMoreValues) const - { (*content)(v, begin(), values, moreValues, evenMoreValues); } + template + void apply(RetVal& v, It values, It2 moreValues, It3 evenMoreValues) const + { (*content)(v, begin(), values, moreValues, evenMoreValues); } */ template @@ -338,7 +338,7 @@ public : } } - /* Iterators */ + /* Iterators */ iterator begin(void) { return args; } const_iterator begin(void) const { return args; } @@ -346,10 +346,10 @@ public : iterator end(void) { return args + arity(); } const_iterator end(void) const { return args + arity(); } - subtree& operator[](int i) { return *(begin() + i); } - const subtree& operator[](int i) const { return *(begin() + i); } + subtree& operator[](int i) { return *(begin() + i); } + const subtree& operator[](int i) const { return *(begin() + i); } - /* Some statistics */ + /* Some statistics */ size_t size(void) const { return _size; } @@ -370,11 +370,11 @@ public : subtree* get_parent(void) { return parent; } const subtree* get_parent(void) const { return parent; } - void clear(void) - { tree_allocator.deallocate(args, arity()); args = 0; *content = T(); parent = 0; _cumulative_size = 0; _depth = 0; _size = 0; } + void clear(void) + { tree_allocator.deallocate(args, arity()); args = 0; *content = T(); parent = 0; _cumulative_size = 0; _depth = 0; _size = 0; } - void swap(subtree& y) - { + void swap(subtree& y) + { do_the_swap(content, y.content); do_the_swap(args, y.args); @@ -386,12 +386,12 @@ public : do_the_swap(_cumulative_size, y._cumulative_size); do_the_swap(_depth, y._depth); do_the_swap(_size, y._size); - updateAfterInsert(); - } + updateAfterInsert(); + } protected : - virtual void updateAfterInsert(void) + virtual void updateAfterInsert(void) { _depth = 0; _size = 1; @@ -419,7 +419,7 @@ private : // else for (int i = arity() - 1; i >= 0; --i) - { + { if (which < args[i]._cumulative_size) return args[i].imp_select_cumulative(which); which -= args[i]._cumulative_size; @@ -434,7 +434,7 @@ private : return *this; for (int i = arity() - 1; i >= 0; --i) - { + { unsigned c_size = args[i].size(); if (which < c_size) return args[i].imp_get_node(which); @@ -454,34 +454,34 @@ private : } subtree& copy(const subtree& s) { - int old_arity = arity(); + int old_arity = arity(); - int new_arity = s.arity(); + int new_arity = s.arity(); - if (new_arity != old_arity) - { - tree_allocator.deallocate(args, old_arity); + if (new_arity != old_arity) + { + tree_allocator.deallocate(args, old_arity); args = tree_allocator.allocate(new_arity); - } + } - switch(new_arity) - { - case 3 : args[2].copy(s.args[2]); args[2].parent = this; // no break! - case 2 : args[1].copy(s.args[1]); args[1].parent = this; - case 1 : args[0].copy(s.args[0]); args[0].parent = this; - case 0 : break; - default : - { - for (int i = 0; i < new_arity; ++i) - { - args[i].copy(s.args[i]); + switch(new_arity) + { + case 3 : args[2].copy(s.args[2]); args[2].parent = this; // no break! + case 2 : args[1].copy(s.args[1]); args[1].parent = this; + case 1 : args[0].copy(s.args[0]); args[0].parent = this; + case 0 : break; + default : + { + for (int i = 0; i < new_arity; ++i) + { + args[i].copy(s.args[i]); args[i].parent = this; - } - } - } + } + } + } - *content = *s.content; + *content = *s.content; _size = s._size; _depth = s._depth; _cumulative_size = s._cumulative_size; @@ -493,66 +493,66 @@ private : { int oldArity = arity(); - if (content != &t) + if (content != &t) *content = t; - else - oldArity = -1; + else + oldArity = -1; - int ar = arity(); + int ar = arity(); - if (ar != oldArity) - { + if (ar != oldArity) + { if (oldArity != -1) - tree_allocator.deallocate(args, oldArity); + tree_allocator.deallocate(args, oldArity); args = tree_allocator.allocate(ar); //if (ar > 0) - // args = new subtree [ar]; - //else - // args = 0; - } + // args = new subtree [ar]; + //else + // args = 0; + } adopt(); updateAfterInsert(); - return *this; + return *this; } - void disown(void) - { - switch(arity()) - { - case 3 : args[2].parent = 0; // no break! - case 2 : args[1].parent = 0; - case 1 : args[0].parent = 0; break; - case 0 : break; - default : - { - for (iterator it = begin(); it != end(); ++it) - { - it->parent = 0; - } - } - } + void disown(void) + { + switch(arity()) + { + case 3 : args[2].parent = 0; // no break! + case 2 : args[1].parent = 0; + case 1 : args[0].parent = 0; break; + case 0 : break; + default : + { + for (iterator it = begin(); it != end(); ++it) + { + it->parent = 0; + } + } + } - } + } void adopt(void) { - switch(arity()) - { - case 3 : args[2].parent = this; // no break! - case 2 : args[1].parent = this; - case 1 : args[0].parent = this; break; - case 0 : break; - default : - { - for (iterator it = begin(); it != end(); ++it) - { - it->parent = this; - } - } - } + switch(arity()) + { + case 3 : args[2].parent = this; // no break! + case 2 : args[1].parent = this; + case 1 : args[0].parent = this; break; + case 0 : break; + default : + { + for (iterator it = begin(); it != end(); ++it) + { + it->parent = this; + } + } + } } template @@ -581,7 +581,7 @@ private : subtree* args; subtree* parent; - size_t _cumulative_size; + size_t _cumulative_size; size_t _depth; size_t _size; }; @@ -590,7 +590,7 @@ private : typedef T value_type; - /* Constructors and Assignments */ + /* Constructors and Assignments */ parse_tree(void) : _root(), pushed() {} parse_tree(const parse_tree& org) : _root(org._root), pushed(org.pushed) { } @@ -602,33 +602,33 @@ private : virtual ~parse_tree(void) {} parse_tree& operator=(const parse_tree& org) { return copy(org); } - parse_tree& operator=(const subtree& sub) - { return copy(sub); } + parse_tree& operator=(const subtree& sub) + { return copy(sub); } - /* Equality and inequality */ + /* Equality and inequality */ - bool operator==(const parse_tree& other) const - { return _root == other._root; } + bool operator==(const parse_tree& other) const + { return _root == other._root; } - bool operator !=(const parse_tree& other) const - { return !operator==(other); } + bool operator !=(const parse_tree& other) const + { return !operator==(other); } - /* Simple tree statistics */ + /* Simple tree statistics */ size_t size(void) const { return _root.size(); } - size_t depth(void) const { return _root.depth(); } + size_t depth(void) const { return _root.depth(); } void clear(void) { _root.clear(); pushed.resize(0); } - /* Evaluation (application), with an increasing number of user defined arguments */ + /* Evaluation (application), with an increasing number of user defined arguments */ - template - void apply(RetVal& v) const - { _root.apply(v); } + template + void apply(RetVal& v) const + { _root.apply(v); } - template - void apply(RetVal& v, It varValues) const - { _root.apply(v, varValues); } + template + void apply(RetVal& v, It varValues) const + { _root.apply(v, varValues); } template void apply_mem_func(RetVal& v, It misc, void (T::* f)(RetVal&, typename subtree::iterator, It)) @@ -636,13 +636,13 @@ private : _root.apply_mem_func(v, misc, f); } - //template - // void apply(RetVal& v, It varValues, It2 moreValues) const - // { _root.apply(v, varValues, moreValues); } + //template + // void apply(RetVal& v, It varValues, It2 moreValues) const + // { _root.apply(v, varValues, moreValues); } - //template - // void apply(RetVal& v, It varValues, It2 moreValues, It3 evenMoreValues) const - // { _root.apply(v, varValues, moreValues, evenMoreValues); } + //template + // void apply(RetVal& v, It varValues, It2 moreValues, It3 evenMoreValues) const + // { _root.apply(v, varValues, moreValues, evenMoreValues); } template void find_nodes(std::vector& result, Pred& p) @@ -656,14 +656,14 @@ private : _root.find_nodes(p); } - /* Customized Swap */ - void swap(parse_tree& other) - { - do_the_swap(pushed, other.pushed); - _root.swap(other._root); - } + /* Customized Swap */ + void swap(parse_tree& other) + { + do_the_swap(pushed, other.pushed); + _root.swap(other._root); + } - /* Definitions of the iterators */ + /* Definitions of the iterators */ class base_iterator { @@ -680,19 +680,19 @@ private : bool operator!=(const base_iterator& org) const { return !operator==(org); } - base_iterator operator+(size_t n) const - { - base_iterator tmp = *this; + base_iterator operator+(size_t n) const + { + base_iterator tmp = *this; - for(;n != 0; --n) - { - ++tmp; - } + for(;n != 0; --n) + { + ++tmp; + } - return tmp; - } + return tmp; + } - base_iterator& operator++(void) + base_iterator& operator++(void) { subtree* parent = node->get_parent(); @@ -702,7 +702,7 @@ private : return *this; } // else - typename subtree::iterator it; + typename subtree::iterator it; for (it = parent->begin(); it != parent->end(); ++it) { if (node == &(*it)) @@ -801,7 +801,7 @@ private : return *this; } // else - typename subtree::const_iterator it; + typename subtree::const_iterator it; for (it = parent->begin(); it != parent->end(); ++it) { @@ -856,35 +856,35 @@ private : using base_const_iterator::node; - typedef std::forward_iterator_tag iterator_category; - typedef const T value_type; - typedef size_t distance_type; - typedef size_t difference_type; - typedef const T* pointer; - typedef const T& reference; + typedef std::forward_iterator_tag iterator_category; + typedef const T value_type; + typedef size_t distance_type; + typedef size_t difference_type; + typedef const T* pointer; + typedef const T& reference; embedded_const_iterator() : base_const_iterator() {} embedded_const_iterator(const subtree* n): base_const_iterator(n) {} embedded_const_iterator& operator=(const embedded_const_iterator& org) { base_const_iterator::operator=(org); return *this; } - embedded_const_iterator operator+(size_t n) const - { - embedded_const_iterator tmp = *this; + embedded_const_iterator operator+(size_t n) const + { + embedded_const_iterator tmp = *this; - for(;n != 0; --n) - { - ++tmp; - } + for(;n != 0; --n) + { + ++tmp; + } - return tmp; - } + return tmp; + } const T& operator*(void) const { return **node; } const T* operator->(void) const { return node->operator->(); } }; - /* Iterator access */ + /* Iterator access */ iterator begin(void) { return iterator(&operator[](0)); } const_iterator begin(void) const { return const_iterator(&operator[](0)); } @@ -899,32 +899,32 @@ private : bool empty(void) const { return size() == 0; } bool valid(void) const { return pushed.empty(); } - /* push_back */ + /* push_back */ - void push_back(const parse_tree& tree) - { - if (!empty()) - pushed.push_back(_root); + void push_back(const parse_tree& tree) + { + if (!empty()) + pushed.push_back(_root); - _root = tree.back(); - } + _root = tree.back(); + } void push_back(const T& t) { if (!empty()) pushed.push_back(_root); - _root = t; + _root = t; for (typename subtree::iterator it = _root.begin(); it != _root.end(); it++) { - *it = pushed.back(); + *it = pushed.back(); pushed.pop_back(); } } - /* Access to subtrees */ + /* Access to subtrees */ subtree& back(void) { return _root; } const subtree& back(void) const { return _root; } @@ -954,7 +954,7 @@ private : return *this; } - parse_tree& copy(const subtree& sub) + parse_tree& copy(const subtree& sub) { _root = sub; pushed.resize(0); return *this; } subtree _root; @@ -970,25 +970,25 @@ namespace std template inline std::forward_iterator_tag iterator_category(typename gp_parse_tree::parse_tree::embedded_iterator) { - return std::forward_iterator_tag(); + return std::forward_iterator_tag(); } template inline ptrdiff_t* distance_type(typename gp_parse_tree::parse_tree::embedded_iterator) { - return 0; + return 0; } template inline std::forward_iterator_tag iterator_category(typename gp_parse_tree::parse_tree::iterator) { - return std::forward_iterator_tag(); + return std::forward_iterator_tag(); } template inline ptrdiff_t* distance_type(typename gp_parse_tree::parse_tree::iterator) { - return 0; + return 0; } /* Put customized swaps also in std... diff --git a/eo/src/other/eoString.h b/eo/src/other/eoString.h index bc1cf88d..3071d1ee 100644 --- a/eo/src/other/eoString.h +++ b/eo/src/other/eoString.h @@ -37,8 +37,8 @@ // eoString //----------------------------------------------------------------------------- -/** Adaptor that turns an STL std::string into an EO - +/** Adaptor that turns an STL std::string into an EO + @ingroup Representations @ingroup Utilities */ @@ -82,4 +82,3 @@ public: }; #endif - diff --git a/eo/src/pyeo/Makefile b/eo/src/pyeo/Makefile index 6953249c..61c4f89f 100644 --- a/eo/src/pyeo/Makefile +++ b/eo/src/pyeo/Makefile @@ -1,37 +1,35 @@ # Note for however is foolish enough to attempt to build this thing # -# You need: +# You need: # Python 2.2 # Boost.Python v2 # -CXX = g++ +CXX = g++ CPPFLAGS = -Wall -O2 #-g #-O2 -LDFLAGS = +LDFLAGS = COMPILE = $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c -LINK = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) -INC=-I/usr/include/python2.6 -I.. -I../.. -ftemplate-depth-50 +LINK = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) +INC=-I/usr/include/python2.6 -I.. -I../.. -ftemplate-depth-50 OBJECTS=eoFunctorStore.o PyEO.o abstract1.o algos.o \ - random_numbers.o geneticOps.o selectOne.o continuators.o\ - reduce.o replacement.o selectors.o breeders.o\ - mergers.o valueParam.o perf2worth.o monitors.o\ - statistics.o + random_numbers.o geneticOps.o selectOne.o continuators.o\ + reduce.o replacement.o selectors.o breeders.o\ + mergers.o valueParam.o perf2worth.o monitors.o\ + statistics.o LIB=../libeo.a ../utils/libeoutils.a all: PyEO/PyEO.so clean: - rm PyEO/*.so *.o test/*.pyc + rm PyEO/*.so *.o test/*.pyc PyEO/PyEO.so: $(OBJECTS) - $(LINK) -o PyEO/PyEO.so $(OBJECTS) -lboost_python -lpython2.6 ${LIB} -shared #-lstlport + $(LINK) -o PyEO/PyEO.so $(OBJECTS) -lboost_python -lpython2.6 ${LIB} -shared #-lstlport eoFunctorStore.o: ../eoFunctorStore.h ../eoFunctorStore.cpp - $(COMPILE) -o eoFunctorStore.o ../eoFunctorStore.cpp $(INC) - -%.o:%.cpp PyEO.h def_abstract_functor.h - $(COMPILE) $< $(INC) - + $(COMPILE) -o eoFunctorStore.o ../eoFunctorStore.cpp $(INC) +%.o:%.cpp PyEO.h def_abstract_functor.h + $(COMPILE) $< $(INC) diff --git a/eo/src/pyeo/Makefile.rpm b/eo/src/pyeo/Makefile.rpm index dccf30ee..4db4bcca 100644 --- a/eo/src/pyeo/Makefile.rpm +++ b/eo/src/pyeo/Makefile.rpm @@ -5,7 +5,7 @@ CXXFLAGS = #-g #-DNDEBUG CPPFLAGS = -Wall -O2 LDFLAGS = -L/usr/lib/python2.2/config/ COMPILE = $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c -LINK = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) +LINK = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) INC=-I/usr/include/python2.2 -I/usr/include/stlport -I.. -ftemplate-depth-50 OBJECTS=eoFunctorStore.o PyEO.o abstract1.o algos.o \ @@ -25,7 +25,5 @@ PyEO.so: $(OBJECTS) eoFunctorStore.o: ../eoFunctorStore.h ../eoFunctorStore.cpp $(COMPILE) -o eoFunctorStore.o ../eoFunctorStore.cpp $(INC) -%.o:%.cpp PyEO.h def_abstract_functor.h +%.o:%.cpp PyEO.h def_abstract_functor.h $(COMPILE) $< $(INC) - - diff --git a/eo/src/pyeo/PyEO.h b/eo/src/pyeo/PyEO.h index 6cf3c003..188b7f8d 100644 --- a/eo/src/pyeo/PyEO.h +++ b/eo/src/pyeo/PyEO.h @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -21,112 +21,113 @@ #ifndef PYEO_H #define PYEO_H - #include #include #include #include #include -struct index_error : public std::exception { - index_error(std::string w) : what(w) {}; + +struct index_error : public std::exception +{ + index_error(std::string w) : what(w) {}; virtual ~index_error() throw() {} - std::string what; + std::string what; }; class PyFitness : public boost::python::object { - public : - +public : + typedef PyFitness fitness_traits; // it's its own traits class :-) - + PyFitness() : boost::python::object() {} - + template PyFitness(const T& o) : boost::python::object(o) {} - + static unsigned nObjectives() { return objective_info.size(); } static double tol() { return 1e-6; } static bool maximizing(int which) { return objective_info[which] > 0; } - + static void setObjectivesSize(int sz) { objective_info.resize(sz, 0); } static void setObjectivesValue(unsigned which, int value) { - if (which >= objective_info.size()) - { - throw index_error("Too few elements allocated, resize objectives first"); - } + if (which >= objective_info.size()) + { + throw index_error("Too few elements allocated, resize objectives first"); + } - objective_info[which] = value; + objective_info[which] = value; } - + static std::vector objective_info; - + bool dominates(const PyFitness& oth) const; - - double operator[](int i) const - { - boost::python::extract x(object::operator[](i)); - - if (!x.check()) - throw std::runtime_error("PyFitness: does not contain doubles"); - return x(); - } - - bool operator<(const PyFitness& other) const - { - if (objective_info.size() == 0) - { - const object& self = *this; - const object& oth = other; - return self < oth; - } - // otherwise use objective_info - - for (unsigned i = 0; i < objective_info.size(); ++i) - { - double a = objective_info[i] * operator[](i); - double b = objective_info[i] * other[i]; - if ( fabs(a - b) > tol()) - { - if (a < b) - return true; - return false; - } - } + double operator[](int i) const + { + boost::python::extract x(object::operator[](i)); - return false; + if (!x.check()) + throw std::runtime_error("PyFitness: does not contain doubles"); + return x(); } - - bool operator>(const PyFitness& other) const - { - return other.operator<(*this); + + bool operator<(const PyFitness& other) const + { + if (objective_info.size() == 0) + { + const object& self = *this; + const object& oth = other; + return self < oth; + } + // otherwise use objective_info + + for (unsigned i = 0; i < objective_info.size(); ++i) + { + double a = objective_info[i] * operator[](i); + double b = objective_info[i] * other[i]; + + if ( fabs(a - b) > tol()) + { + if (a < b) + return true; + return false; + } + } + + return false; } - + + bool operator>(const PyFitness& other) const + { + return other.operator<(*this); + } + void printOn(std::ostream& os) const { const boost::python::object& o = *this; boost::python::api::operator<<(os,o); } friend std::ostream& operator<<(std::ostream& os, const PyFitness& p) { p.printOn(os); return os; } friend std::istream& operator>>(std::istream& is, PyFitness& p) { boost::python::object o; is >> o; p = o; return is; } }; struct PyEO : public EO< PyFitness > -{ +{ typedef PyFitness Fitness; - + boost::python::object getFitness() const { return invalid()? Fitness(): fitness(); } void setFitness(boost::python::object f) { if (f == Fitness()) invalidate(); else fitness(f); } boost::python::object getGenome() const { return genome; } void setGenome(boost::python::object g) { genome = g; } boost::python::object genome; - + std::string to_string() const { - std::string result; - result += boost::python::extract(boost::python::str(getFitness())); - result += ' '; - result += boost::python::extract(boost::python::str(genome)); - return result; + std::string result; + result += boost::python::extract(boost::python::str(getFitness())); + result += ' '; + result += boost::python::extract(boost::python::str(genome)); + return result; } bool operator<(const PyEO& other) const { return EO::operator<(other); } @@ -139,17 +140,16 @@ std::ostream& operator<<(std::ostream& os, const PyEO& _eo); struct PyEO_pickle_suite : boost::python::pickle_suite { typedef PyEO::Fitness Fitness; - - static - boost::python::tuple getstate(const PyEO& _eo) + + static boost::python::tuple getstate(const PyEO& _eo) { - return boost::python::make_tuple(_eo.getFitness(), _eo.genome); + return boost::python::make_tuple(_eo.getFitness(), _eo.genome); } - static - void setstate(PyEO& _eo, boost::python::tuple pickled) + + static void setstate(PyEO& _eo, boost::python::tuple pickled) { - _eo.setFitness( Fitness(pickled[0]) ); - _eo.genome = pickled[1]; + _eo.setFitness( Fitness(pickled[0]) ); + _eo.genome = pickled[1]; } }; diff --git a/eo/src/pyeo/PyEO/__init__.py b/eo/src/pyeo/PyEO/__init__.py index cc679542..2818319b 100644 --- a/eo/src/pyeo/PyEO/__init__.py +++ b/eo/src/pyeo/PyEO/__init__.py @@ -1,4 +1,3 @@ - from PyEO import * try: @@ -8,80 +7,77 @@ except ImportError: else: class eoGnuplot1DMonitor(eoMonitor): - def __init__(self): - eoMonitor.__init__(self) - self.values = [] - self.indices = [] - self.g = Gnuplot.Gnuplot() - self.g.reset(); - - - def handleParam(self, i, param): - param = float(param) + def __init__(self): + eoMonitor.__init__(self) + self.values = [] + self.indices = [] + self.g = Gnuplot.Gnuplot() + self.g.reset(); - while len(self.values) <= i: - self.values.append( [] ) + def handleParam(self, i, param): + param = float(param) - self.values[i].append(param) - - def __call__(self): - - l = len(self) + while len(self.values) <= i: + self.values.append( [] ) - if l > 3 or l == 0: - print 'Can only handle 1 to 3 params currently' - - i = 0 - for param in self: - self.handleParam(i,param) - i += 1 - - self.indices.append( len(self.indices) ) + self.values[i].append(param) + + def __call__(self): + l = len(self) + + if l > 3 or l == 0: + print 'Can only handle 1 to 3 params currently' + + i = 0 + for param in self: + self.handleParam(i,param) + i += 1 + + self.indices.append( len(self.indices) ) - data1 = Gnuplot.Data(self.indices, self.values[0], with = 'lines') - - if l == 1: - self.g.plot(data1) - else: - data2 = Gnuplot.Data(self.indices, self.values[1], with = 'lines') + data1 = Gnuplot.Data(self.indices, self.values[0], with = 'lines') - if l == 2: - self.g.plot(data1, data2) - else: - data3 = Gnuplot.Data(self.indices, self.values[2], with = 'lines') + if l == 1: + self.g.plot(data1) + else: + data2 = Gnuplot.Data(self.indices, self.values[1], with = 'lines') - self.g.plot(data1, data2, data3) + if l == 2: + self.g.plot(data1, data2) + else: + data3 = Gnuplot.Data(self.indices, self.values[2], with = 'lines') + + self.g.plot(data1, data2, data3) def SeperatedVolumeMonitor(eoMonitor): def __init__(self, file): - eoMonitor.__init__(self) - self.file = file - self.initialized = None; + eoMonitor.__init__(self) + self.file = file + self.initialized = None; def __call__(self): - pass + pass class eoStat(eoStatBase, eoValueParam): def __init__(self): - eoStatBase.__init__(self) - eoValueParam.__init__(self) - + eoStatBase.__init__(self) + eoValueParam.__init__(self) + class eoSortedStat(eoSortedStatBase, eoValueParam): def __init__(self): - eoSortedStatBase.__init__(self) - eoValueParam.__init__(self) + eoSortedStatBase.__init__(self) + eoValueParam.__init__(self) class eoAverageStat(eoStat): def __call__(self, pop): - sum = 0.0; - for indy in pop: - sum += indy.fitness + sum = 0.0; + for indy in pop: + sum += indy.fitness - sum /= len(pop) - self.object = sum + sum /= len(pop) + self.object = sum class eoBestFitnessStat(eoSortedStat): - def __call__(self, pop): - self.object = pop[0].fitness + self.object = pop[0].fitness diff --git a/eo/src/pyeo/abstract1.cpp b/eo/src/pyeo/abstract1.cpp index e8e84777..43c0dadb 100644 --- a/eo/src/pyeo/abstract1.cpp +++ b/eo/src/pyeo/abstract1.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -34,13 +34,19 @@ void abstract1() /* Abstract Classes: overrideble from python */ def_abstract_functor >("eoEvalFunc"); def_abstract_functor >("eoInit"); - + def_abstract_functor >("eoTransform"); - - class_, bases > >("eoSGATransform", - init< eoQuadOp&, double, - eoMonOp&, double>()) - .def("__call__", &eoSGATransform::operator()); - + + class_, bases > > + ("eoSGATransform", + init< + eoQuadOp&, + double, + eoMonOp&, + double + >() + ) + .def("__call__", &eoSGATransform::operator()); + def_abstract_functor >("eoPopEvalFunc"); -} +} diff --git a/eo/src/pyeo/algos.cpp b/eo/src/pyeo/algos.cpp index 12feaf19..caa2fcd3 100644 --- a/eo/src/pyeo/algos.cpp +++ b/eo/src/pyeo/algos.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -31,76 +31,96 @@ using namespace boost::python; void algos() { def_abstract_functor >("eoAlgo"); - + /* Algorithms */ - class_, bases >, boost::noncopyable>("eoSGA", - init&, - eoQuadOp&, float, - eoMonOp&, float, - eoEvalFunc&, - eoContinue&>() - [ - with_custodian_and_ward<1,2, - with_custodian_and_ward<1,3, - with_custodian_and_ward<1,5, - with_custodian_and_ward<1,7, - with_custodian_and_ward<1,8> - > - > - > - >() - ]) - .def("__call__", &eoSGA::operator()) - ; - - class_, bases > >("eoEasyEA", - init< - eoContinue&, - eoEvalFunc&, - eoBreed&, - eoReplacement& >() ) - .def( init< - eoContinue&, - eoPopEvalFunc&, - eoBreed&, - eoReplacement&>() ) - .def( init< - eoContinue&, - eoEvalFunc&, - eoBreed&, - eoMerge&, - eoReduce& >() ) - .def( init< - eoContinue&, - eoEvalFunc&, - eoSelect&, - eoTransform&, - eoReplacement&>()) - .def( init< - eoContinue&, - eoEvalFunc&, - eoSelect&, - eoTransform&, - eoMerge&, - eoReduce&>()) - .def("__call__", &eoEasyEA::operator()) - ; - + class_, bases >, boost::noncopyable> + ("eoSGA", + init< + eoSelectOne&, + eoQuadOp&, + float, + eoMonOp&, + float, + eoEvalFunc&, + eoContinue& + >() + [ + with_custodian_and_ward<1,2, + with_custodian_and_ward<1,3, + with_custodian_and_ward<1,5, + with_custodian_and_ward<1,7, + with_custodian_and_ward<1,8> + > + > + > + >() + ] + ) + .def("__call__", &eoSGA::operator()) + ; + + class_, bases > > + ("eoEasyEA", + init< + eoContinue&, + eoEvalFunc&, + eoBreed&, + eoReplacement& + >() + ) + .def( init< + eoContinue&, + eoEvalFunc&, + eoBreed&, + eoReplacement&, + unsigned + >() ) + .def( init< + eoContinue&, + eoPopEvalFunc&, + eoBreed&, + eoReplacement& + >() ) + .def( init< + eoContinue&, + eoEvalFunc&, + eoBreed&, + eoMerge&, + eoReduce& + >() ) + .def( init< + eoContinue&, + eoEvalFunc&, + eoSelect&, + eoTransform&, + eoReplacement& + >() ) + .def( init< + eoContinue&, + eoEvalFunc&, + eoSelect&, + eoTransform&, + eoMerge&, + eoReduce& + >() ) + .def("__call__", &eoEasyEA::operator()) + ; + /* - class_, bases< eoAlgo > >("eoCellularEasyEA", - init< eoContinue&, - eoEvalFunc&, - eoSelectOne&, - eoBinOp&, - eoMonOp&, - eoSelectOne&>()) - .def( - init< eoContinue&, - eoEvalFunc&, - eoSelectOne&, - eoQuadOp&, - eoMonOp&, - eoSelectOne&>()) - ; + class_, bases< eoAlgo > >("eoCellularEasyEA", + init< eoContinue&, + eoEvalFunc&, + eoSelectOne&, + eoBinOp&, + eoMonOp&, + eoSelectOne&>()) + .def( + init< eoContinue&, + eoEvalFunc&, + eoSelectOne&, + eoQuadOp&, + eoMonOp&, + eoSelectOne&>()) + ; */ } diff --git a/eo/src/pyeo/breeders.cpp b/eo/src/pyeo/breeders.cpp index 30cf0994..c66b6bcc 100644 --- a/eo/src/pyeo/breeders.cpp +++ b/eo/src/pyeo/breeders.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -27,9 +27,19 @@ using namespace boost::python; -#define DEF3(x, i1, i2) class_, bases > >(#x, \ - init()[with_custodian_and_ward<1,2,with_custodian_and_ward<1,3> >()])\ - .def("__call__", &eoBreed::operator()) +#define DEF3(x, i1, i2) \ + class_, bases > > \ + (#x, \ + init() \ + [ \ + with_custodian_and_ward<1,2, \ + with_custodian_and_ward<1,3 \ + > \ + > \ + () \ + ] \ + ) \ + .def("__call__", &eoBreed::operator()) void breeders() { @@ -38,14 +48,12 @@ void breeders() DEF3(eoSelectTransform, eoSelect&, eoTransform&); DEF3(eoGeneralBreeder, eoSelectOne&, eoGenOp&) - .def( init&, eoGenOp&, double>()[WC2]) - .def( init&, eoGenOp&, double, bool>()[WC2] ) - .def( init&, eoGenOp&, eoHowMany>() ); + .def( init&, eoGenOp&, double>()[WC2]) + .def( init&, eoGenOp&, double, bool>()[WC2] ) + .def( init&, eoGenOp&, eoHowMany>() ); DEF3(eoOneToOneBreeder, eoGenOp&, eoEvalFunc&) - .def( init&, eoEvalFunc&, double>()[WC2] ) - .def( init&, eoEvalFunc&, double, eoHowMany>()[WC2] ); - + .def( init&, eoEvalFunc&, double>()[WC2] ) + .def( init&, eoEvalFunc&, double, eoHowMany>()[WC2] ); } - diff --git a/eo/src/pyeo/continuators.cpp b/eo/src/pyeo/continuators.cpp index 4f1a76c5..d31613d2 100644 --- a/eo/src/pyeo/continuators.cpp +++ b/eo/src/pyeo/continuators.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -40,28 +40,34 @@ void add_checkpoint(); void continuators() { /* Counters, wrappers etc */ - - class_, bases > >("eoEvalFuncCounter", - init< eoEvalFunc&, std::string>()) - .def("__call__", &eoEvalFuncCounter::operator()) - ; + + class_, bases > > + ("eoEvalFuncCounter", + init< eoEvalFunc&, std::string>() + ) + .def("__call__", &eoEvalFuncCounter::operator()) + ; /* Continuators */ - def_abstract_functor >("eoContinue"); - - class_, bases >, boost::noncopyable >("eoGenContinue", init() ) - .def("__call__", &eoGenContinue::operator()) - ; - - class_, bases > >("eoCombinedContinue", init&>()[WC1]) - .def( init&, eoContinue& >()[WC2] ) - .def("add", &eoCombinedContinue::add, WC1) - .def("__call__", &eoCombinedContinue::operator()) - ; - - class_, bases > >("eoEvalContinue", - init&, unsigned long>()[WC1]) - .def("__call__", &eoEvalContinue::operator()) - ; + def_abstract_functor >("eoContinue"); + + class_, bases >, boost::noncopyable > + ("eoGenContinue", init() ) + .def("__call__", &eoGenContinue::operator()) + ; + + class_, bases > > + ("eoCombinedContinue", init&>()[WC1]) + .def( init&, eoContinue& >()[WC2] ) + .def("add", &eoCombinedContinue::add, WC1) + .def("__call__", &eoCombinedContinue::operator()) + ; + + class_, bases > > + ("eoEvalContinue", + init&, unsigned long>()[WC1] + ) + .def("__call__", &eoEvalContinue::operator()) + ; DEF2(eoFitContinue, object); // object is the fitness type @@ -77,14 +83,14 @@ void addSortedStat(eoCheckPoint& c, eoSortedStatBase& s) { c.add(s); void add_checkpoint() { - class_, bases< eoContinue > >("eoCheckPoint", - - init&> ()[with_custodian_and_ward<1,2>()] - ) - .def("add", addContinue, with_custodian_and_ward<1,2>() ) - .def("add", addMonitor, with_custodian_and_ward<1,2>() ) - .def("add", addStat, with_custodian_and_ward<1,2>()) - .def("add", addSortedStat, with_custodian_and_ward<1,2>()) - .def("__call__", &eoCheckPoint::operator()) - ; + class_, bases< eoContinue > > + ("eoCheckPoint", + init&> ()[with_custodian_and_ward<1,2>()] + ) + .def("add", addContinue, with_custodian_and_ward<1,2>() ) + .def("add", addMonitor, with_custodian_and_ward<1,2>() ) + .def("add", addStat, with_custodian_and_ward<1,2>()) + .def("add", addSortedStat, with_custodian_and_ward<1,2>()) + .def("__call__", &eoCheckPoint::operator()) + ; } diff --git a/eo/src/pyeo/def_abstract_functor.h b/eo/src/pyeo/def_abstract_functor.h index 7324dc48..4c3101df 100644 --- a/eo/src/pyeo/def_abstract_functor.h +++ b/eo/src/pyeo/def_abstract_functor.h @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -23,104 +23,104 @@ #include -// DEFINES for call +// DEFINES for call #define WC1 boost::python::with_custodian_and_ward<1,2>() #define WC2 boost::python::with_custodian_and_ward<1,2, with_custodian_and_ward<1,3> >() namespace eoutils { -using namespace boost::python; - -template -class ProcWrapper : public Proc -{ - public: - PyObject* self; - ProcWrapper(PyObject* s) : self(s) {} + using namespace boost::python; - typename Proc::result_type operator()(void) + template + class ProcWrapper : public Proc { - return boost::python::call_method(self, "__call__"); - } -}; - -template -void make_abstract_functor(std::string name, typename eoFunctorBase::procedure_tag) -{ - typedef ProcWrapper Wrapper; - boost::python::class_(name.c_str(), boost::python::init<>() ) - .def("__call__", &Wrapper::operator()); -} - -template -void make_abstract_functor_ref(std::string name, typename eoFunctorBase::procedure_tag) -{ - typedef ProcWrapper Wrapper; - boost::python::class_(name.c_str(), boost::python::init<>() ) - .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>()); -} - -template -class UnaryWrapper : public Unary -{ public: - PyObject* self; - UnaryWrapper(PyObject* s) : self(s) {} + PyObject* self; + ProcWrapper(PyObject* s) : self(s) {} - typename Unary::result_type operator()(typename Unary::argument_type a) - { - return boost::python::call_method(self, "__call__", boost::ref(a) ); - } -}; + typename Proc::result_type operator()(void) + { + return boost::python::call_method(self, "__call__"); + } + }; -template -void make_abstract_functor(std::string name, typename eoFunctorBase::unary_function_tag) -{ - typedef UnaryWrapper Wrapper; - - boost::python::class_(name.c_str(), boost::python::init<>() ) - .def("__call__", &Wrapper::operator()) - ; -} - -template -void make_abstract_functor_ref(std::string name, typename eoFunctorBase::unary_function_tag) -{ - typedef UnaryWrapper Wrapper; - - boost::python::class_(name.c_str(), boost::python::init<>() ) - .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>() ) - ; -} - -template -class BinaryWrapper : public Binary -{ - public: - PyObject* self; - BinaryWrapper(PyObject* s) : self(s) {} - typename Binary::result_type operator()(typename Binary::first_argument_type a1, typename Binary::second_argument_type a2) + template + void make_abstract_functor(std::string name, typename eoFunctorBase::procedure_tag) { - return boost::python::call_method< - typename Binary::result_type>(self, "__call__", boost::ref(a1), boost::ref(a2) ); + typedef ProcWrapper Wrapper; + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator()); } -}; -template -void make_abstract_functor(std::string name, typename eoFunctorBase::binary_function_tag) -{ - typedef BinaryWrapper Wrapper; - boost::python::class_(name.c_str(), boost::python::init<>() ) - .def("__call__", &Wrapper::operator()); -} + template + void make_abstract_functor_ref(std::string name, typename eoFunctorBase::procedure_tag) + { + typedef ProcWrapper Wrapper; + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>()); + } -template -void make_abstract_functor_ref(std::string name, typename eoFunctorBase::binary_function_tag) -{ - typedef BinaryWrapper Wrapper; - boost::python::class_(name.c_str(), boost::python::init<>() ) - .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>() ); -} + template + class UnaryWrapper : public Unary + { + public: + PyObject* self; + UnaryWrapper(PyObject* s) : self(s) {} + + typename Unary::result_type operator()(typename Unary::argument_type a) + { + return boost::python::call_method(self, "__call__", boost::ref(a) ); + } + }; + + template + void make_abstract_functor(std::string name, typename eoFunctorBase::unary_function_tag) + { + typedef UnaryWrapper Wrapper; + + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator()) + ; + } + + template + void make_abstract_functor_ref(std::string name, typename eoFunctorBase::unary_function_tag) + { + typedef UnaryWrapper Wrapper; + + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>() ) + ; + } + + template + class BinaryWrapper : public Binary + { + public: + PyObject* self; + BinaryWrapper(PyObject* s) : self(s) {} + typename Binary::result_type operator()(typename Binary::first_argument_type a1, typename Binary::second_argument_type a2) + { + return boost::python::call_method< + typename Binary::result_type>(self, "__call__", boost::ref(a1), boost::ref(a2) ); + } + }; + + template + void make_abstract_functor(std::string name, typename eoFunctorBase::binary_function_tag) + { + typedef BinaryWrapper Wrapper; + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator()); + } + + template + void make_abstract_functor_ref(std::string name, typename eoFunctorBase::binary_function_tag) + { + typedef BinaryWrapper Wrapper; + boost::python::class_(name.c_str(), boost::python::init<>() ) + .def("__call__", &Wrapper::operator(), boost::python::return_internal_reference<>() ); + } }// namespace eoutils diff --git a/eo/src/pyeo/geneticOps.cpp b/eo/src/pyeo/geneticOps.cpp index 2665837b..40617680 100644 --- a/eo/src/pyeo/geneticOps.cpp +++ b/eo/src/pyeo/geneticOps.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -31,22 +31,22 @@ using namespace boost::python; class GenOpWrapper : public eoGenOp { - public: +public: PyObject* self; GenOpWrapper(PyObject* p) : self(p) {} unsigned max_production(void) { - return call_method(self,"max_production"); + return call_method(self,"max_production"); } std::string className() const { - return "GenOpDerivative"; // never saw the use of className anyway + return "GenOpDerivative"; // never saw the use of className anyway } - + void apply(eoPopulator& populator ) { - boost::python::call_method(self,"apply", boost::ref( populator ) ); + boost::python::call_method(self,"apply", boost::ref( populator ) ); } }; @@ -54,15 +54,15 @@ class PopulatorWrapper : public eoPopulator { public: PyObject* self; - PopulatorWrapper(PyObject* p, const eoPop& src, eoPop& dest) - : eoPopulator(src, dest), self(p) - { - //throw std::runtime_error("abstract base class"); - } - + PopulatorWrapper(PyObject* p, const eoPop& src, eoPop& dest) + : eoPopulator(src, dest), self(p) + { + //throw std::runtime_error("abstract base class"); + } + const PyEO& select() { - return call_method(self,"select"); + return call_method(self,"select"); } }; @@ -94,62 +94,62 @@ public: void geneticOps() { class_, PopulatorWrapper, boost::noncopyable> - ("eoPopulator", init&, eoPop&>() ) - .def("select", &PopulatorWrapper::select, return_internal_reference<>() ) - .def("get", &eoPopulator::operator*, return_internal_reference<>() ) - .def("next", &eoPopulator::operator++, return_internal_reference<>() ) - .def("insert", &eoPopulator::insert) - .def("reserve", &eoPopulator::reserve) - .def("source", &eoPopulator::source, return_internal_reference<>() ) - .def("offspring", &eoPopulator::offspring, return_internal_reference<>() ) - .def("tellp", &eoPopulator::tellp) - .def("seekp", &eoPopulator::seekp) - .def("exhausted", &eoPopulator::exhausted) - ; + ("eoPopulator", init&, eoPop&>() ) + .def("select", &PopulatorWrapper::select, return_internal_reference<>() ) + .def("get", &eoPopulator::operator*, return_internal_reference<>() ) + .def("next", &eoPopulator::operator++, return_internal_reference<>() ) + .def("insert", &eoPopulator::insert) + .def("reserve", &eoPopulator::reserve) + .def("source", &eoPopulator::source, return_internal_reference<>() ) + .def("offspring", &eoPopulator::offspring, return_internal_reference<>() ) + .def("tellp", &eoPopulator::tellp) + .def("seekp", &eoPopulator::seekp) + .def("exhausted", &eoPopulator::exhausted) + ; class_, bases > > - ("eoSeqPopulator", init&, eoPop&>() ) - .def("select", &eoSeqPopulator::select, return_internal_reference<>() ) - ; - + ("eoSeqPopulator", init&, eoPop&>() ) + .def("select", &eoSeqPopulator::select, return_internal_reference<>() ) + ; + class_, bases > > - ("eoSelectivePopulator", init&, eoPop&, eoSelectOne& >() ) - .def("select", &eoSeqPopulator::select, return_internal_reference<>() ) - ; + ("eoSelectivePopulator", init&, eoPop&, eoSelectOne& >() ) + .def("select", &eoSeqPopulator::select, return_internal_reference<>() ) + ; enum_::OpType>("OpType") - .value("unary", eoOp::unary) - .value("binary", eoOp::binary) - .value("quadratic", eoOp::quadratic) - .value("general", eoOp::general) - ; - + .value("unary", eoOp::unary) + .value("binary", eoOp::binary) + .value("quadratic", eoOp::quadratic) + .value("general", eoOp::general) + ; + class_ >("eoOp", init::OpType>()) - .def("getType", &eoOp::getType); - + .def("getType", &eoOp::getType); + class_, MonOpWrapper, bases >, boost::noncopyable>("eoMonOp", init<>()) - .def("__call__", &MonOpWrapper::operator(), "an example docstring"); + .def("__call__", &MonOpWrapper::operator(), "an example docstring"); class_, BinOpWrapper, bases >, boost::noncopyable>("eoBinOp", init<>()) - .def("__call__", &BinOpWrapper::operator()); + .def("__call__", &BinOpWrapper::operator()); class_, QuadOpWrapper, bases >, boost::noncopyable>("eoQuadOp", init<>()) - .def("__call__", &QuadOpWrapper::operator()); - + .def("__call__", &QuadOpWrapper::operator()); + class_, GenOpWrapper, bases >, boost::noncopyable>("eoGenOp", init<>()) - .def("max_production", &GenOpWrapper::max_production) - .def("className", &GenOpWrapper::className) - .def("apply", &GenOpWrapper::apply) - .def("__call__", &eoGenOp::operator()) - ; - + .def("max_production", &GenOpWrapper::max_production) + .def("className", &GenOpWrapper::className) + .def("apply", &GenOpWrapper::apply) + .def("__call__", &eoGenOp::operator()) + ; + class_, bases >, boost::noncopyable>("eoSequentialOp", init<>()) - .def("add", &eoSequentialOp::add, WC1) - .def("apply", &eoSequentialOp::apply) - ; - + .def("add", &eoSequentialOp::add, WC1) + .def("apply", &eoSequentialOp::apply) + ; + class_, bases >, boost::noncopyable>("eoProportionalOp", init<>()) - .def("add", &eoProportionalOp::add, WC1) - .def("apply", &eoProportionalOp::apply) - ; - + .def("add", &eoProportionalOp::add, WC1) + .def("apply", &eoProportionalOp::apply) + ; + /* Cloning */ class_, bases > >("eoMonCloneOp").def("__call__", &eoMonCloneOp::operator()); class_, bases > >("eoBinCloneOp").def("__call__", &eoBinCloneOp::operator()); diff --git a/eo/src/pyeo/mergers.cpp b/eo/src/pyeo/mergers.cpp index fd2b3411..f41af049 100644 --- a/eo/src/pyeo/mergers.cpp +++ b/eo/src/pyeo/mergers.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -31,11 +31,10 @@ using namespace boost::python; void mergers() { def_abstract_functor >("eoMerge"); - + DEF2(eoElitism, double) - .def( init() ); + .def( init() ); DEF(eoNoElitism); DEF(eoPlus); } - diff --git a/eo/src/pyeo/monitors.cpp b/eo/src/pyeo/monitors.cpp index 8215128d..02d011d8 100644 --- a/eo/src/pyeo/monitors.cpp +++ b/eo/src/pyeo/monitors.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -26,47 +26,46 @@ using namespace boost::python; class MonitorWrapper : public eoMonitor { - public: - PyObject* self; - list objects; - - MonitorWrapper(PyObject* p) :self(p) {} +public: + PyObject* self; + list objects; - eoMonitor& operator()() - { - call_method(self, "__call__"); - return *this; - } + MonitorWrapper(PyObject* p) :self(p) {} - std::string getString(int i) - { - if (static_cast(i) >= vec.size()) - { - throw index_error("Index out of bounds"); - } - - return vec[i]->getValue(); - } + eoMonitor& operator()() + { + call_method(self, "__call__"); + return *this; + } - unsigned size() { return vec.size(); } + std::string getString(int i) + { + if (static_cast(i) >= vec.size()) + { + throw index_error("Index out of bounds"); + } + + return vec[i]->getValue(); + } + + unsigned size() { return vec.size(); } }; void monitors() { - /** - * Change of interface: I encountered some difficulties with + /** + * Change of interface: I encountered some difficulties with * transferring eoParams from and to Python, so now we can * only get at the strings contained in the eoParams. * sorry */ - - class_("eoMonitor", init<>()) - .def("lastCall", &eoMonitor::lastCall) - .def("add", &eoMonitor::add) - .def("__call__", &MonitorWrapper::operator(), return_internal_reference<1>() ) - .def("__getitem__", &MonitorWrapper::getString, - "Returns the string value of the indexed Parameter") - .def("__len__", &MonitorWrapper::size) - ; -} + class_("eoMonitor", init<>()) + .def("lastCall", &eoMonitor::lastCall) + .def("add", &eoMonitor::add) + .def("__call__", &MonitorWrapper::operator(), return_internal_reference<1>() ) + .def("__getitem__", &MonitorWrapper::getString, + "Returns the string value of the indexed Parameter") + .def("__len__", &MonitorWrapper::size) + ; +} diff --git a/eo/src/pyeo/perf2worth.cpp b/eo/src/pyeo/perf2worth.cpp index 3ca13996..a257b0cd 100644 --- a/eo/src/pyeo/perf2worth.cpp +++ b/eo/src/pyeo/perf2worth.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -17,6 +17,7 @@ along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + #include #include "PyEO.h" @@ -30,19 +31,18 @@ struct Perf2WorthWrapper : public eoPerf2Worth void operator()( const eoPop& pop) { - call_method(self, "__call__", boost::ref(pop)); + call_method(self, "__call__", boost::ref(pop)); } - }; numeric::array get_worths(eoPerf2Worth& p) { std::vector& worths = p.value(); list result; - + for (unsigned i = 0; i < worths.size(); ++i) - result.append(worths[i]); - + result.append(worths[i]); + return numeric::array(result); } @@ -53,36 +53,37 @@ struct CachedPerf2WorthWrapper : public eoPerf2WorthCached void calculate_worths(const eoPop& pop) { - call_method(self, "calculate_worths", boost::ref(pop)); + call_method(self, "calculate_worths", boost::ref(pop)); } }; -void perf2worth() +void perf2worth() { //numeric::array::set_module_and_type("Numeric", "ArrayType"); - - class_< - eoPerf2Worth, - Perf2WorthWrapper, - bases< eoValueParam > >, - boost::noncopyable>("eoPerf2Worth", init<>()) - - .def("__call__", &Perf2WorthWrapper::operator()) - .def("sort_pop", &eoPerf2Worth::sort_pop) - //.def("value", get_worths) - ; - class_, CachedPerf2WorthWrapper, bases >, boost::noncopyable> - ("eoPerf2WorthCached", init<>()) - .def("__call__", &eoPerf2WorthCached::operator()) - .def("calculate_worths", &CachedPerf2WorthWrapper::calculate_worths) - ; - + class_, + Perf2WorthWrapper, + bases< eoValueParam > >, + boost::noncopyable>("eoPerf2Worth", init<>()) + + .def("__call__", &Perf2WorthWrapper::operator()) + .def("sort_pop", &eoPerf2Worth::sort_pop) + //.def("value", get_worths) + ; + + class_, + CachedPerf2WorthWrapper, + bases >, + boost::noncopyable>("eoPerf2WorthCached", init<>()) + + .def("__call__", &eoPerf2WorthCached::operator()) + .def("calculate_worths", &CachedPerf2WorthWrapper::calculate_worths) + ; + //class_, bases > >("eoNoPerf2Worth") -// .def("__call__", &eoNoPerf2Worth::operator()); - - class_, bases > >("eoNDSorting_II") - .def("calculate_worths", &eoNDSorting_II::calculate_worths); + // .def("__call__", &eoNoPerf2Worth::operator()); + + class_, + bases > >("eoNDSorting_II") + .def("calculate_worths", &eoNDSorting_II::calculate_worths); } - - diff --git a/eo/src/pyeo/pickle.h b/eo/src/pyeo/pickle.h index ee2706fb..0e30654a 100644 --- a/eo/src/pyeo/pickle.h +++ b/eo/src/pyeo/pickle.h @@ -29,32 +29,31 @@ #include /** Implements pickle support for eoPersistent derivatives */ - template struct T_pickle_suite : boost::python::pickle_suite { static std::string print_to_string(const T& t) { - std::ostringstream os; - t.printOn(os); - os << std::ends; - return os.str(); + std::ostringstream os; + t.printOn(os); + os << std::ends; + return os.str(); } static boost::python::tuple getstate(const T& t) { - std::string s = print_to_string(t); - return boost::python::make_tuple( boost::python::str(s)); + std::string s = print_to_string(t); + return boost::python::make_tuple( boost::python::str(s)); } static void setstate(T& t, boost::python::tuple pickled) { - std::string s = boost::python::extract(pickled[0]); - std::istringstream is(s); - t.readFrom(is); + std::string s = boost::python::extract(pickled[0]); + std::istringstream is(s); + t.readFrom(is); } }; @@ -65,7 +64,7 @@ template boost::python::class_& pickle(boost::python::class_& c) { return c.def_pickle(T_pickle_suite()) - .def("__str__", T_pickle_suite::print_to_string); + .def("__str__", T_pickle_suite::print_to_string); } #endif diff --git a/eo/src/pyeo/random_numbers.cpp b/eo/src/pyeo/random_numbers.cpp index aa9e4feb..c9047385 100644 --- a/eo/src/pyeo/random_numbers.cpp +++ b/eo/src/pyeo/random_numbers.cpp @@ -61,52 +61,52 @@ struct RNG_pickle_suite : boost::python::pickle_suite static boost::python::tuple getstate(const eoRng& _rng) { - return boost::python::make_tuple(str(rng_to_string(_rng))); + return boost::python::make_tuple(str(rng_to_string(_rng))); } static void setstate(eoRng& _rng, boost::python::tuple pickled) { - std::string state = extract(pickled[0]); - rng_from_string(_rng, state); + std::string state = extract(pickled[0]); + rng_from_string(_rng, state); } }; int spin(eoRng& _rng, numeric::array values, double total) { - if (total == 0.0) - { - unsigned sz = len(values); - for (unsigned i = 0; i < sz; ++i) - { - total += extract(values[i]); //extract? - } - } + if (total == 0.0) + { + unsigned sz = len(values); + for (unsigned i = 0; i < sz; ++i) + { + total += extract(values[i]); //extract? + } + } - double chance = _rng.uniform() * total; + double chance = _rng.uniform() * total; - int i = 0; - while (chance >= 0.0) - chance -= extract(values[i++]); + int i = 0; + while (chance >= 0.0) + chance -= extract(values[i++]); - return --i; + return --i; } void random_numbers() { class_("eoRng", init()) - .def("flip", &eoRng::flip) - .def("random", &eoRng::random) - .def("rand", &eoRng::rand) - .def("rand_max", &eoRng::rand_max) - .def("reseed", &eoRng::reseed) - // .def("uniform", &eoRng::uniform) - .def("normal", normal) - .def("negexp", &eoRng::negexp) - .def("to_string", rng_to_string) - .def("from_string", rng_from_string) - .def("roulette_wheel", spin) - .def_pickle(RNG_pickle_suite()) - ; + .def("flip", &eoRng::flip) + .def("random", &eoRng::random) + .def("rand", &eoRng::rand) + .def("rand_max", &eoRng::rand_max) + .def("reseed", &eoRng::reseed) + // .def("uniform", &eoRng::uniform) + .def("normal", normal) + .def("negexp", &eoRng::negexp) + .def("to_string", rng_to_string) + .def("from_string", rng_from_string) + .def("roulette_wheel", spin) + .def_pickle(RNG_pickle_suite()) + ; def("rng", get_rng, return_value_policy()); } diff --git a/eo/src/pyeo/reduce.cpp b/eo/src/pyeo/reduce.cpp index a23c15cd..6c9b78c6 100644 --- a/eo/src/pyeo/reduce.cpp +++ b/eo/src/pyeo/reduce.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -27,7 +27,7 @@ using namespace boost::python; // unfortunately have to define it specially class eoReduceWrapper : public eoReduce { - public: +public: PyObject* self; eoReduceWrapper(PyObject* s) : self(s) {} void operator()(eoPop& pop, unsigned i) @@ -38,7 +38,6 @@ class eoReduceWrapper : public eoReduce void reduce() { - // ref trick in def_abstract_functor does not work for unsigned int :-( class_, eoReduceWrapper, boost::noncopyable>("eoReduce", init<>()) .def("__call__", &eoReduceWrapper::operator()); @@ -62,4 +61,3 @@ void reduce() .def("__call__", &eoReduce::operator()) ; } - diff --git a/eo/src/pyeo/replacement.cpp b/eo/src/pyeo/replacement.cpp index 9867a113..eb1bc5d7 100644 --- a/eo/src/pyeo/replacement.cpp +++ b/eo/src/pyeo/replacement.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -31,8 +31,9 @@ using namespace boost::python; #define DEF(x) class_, bases > >(#x).def("__call__", &eoReplacement::operator()) #define DEF2(x, i1) class_, bases > >(#x, init() ).def("__call__", &eoReplacement::operator()) -#define DEF3(x, i1, i2) class_, bases > >(#x, \ - init() [WC2])\ +#define DEF3(x, i1, i2) class_, bases > > \ + (#x, \ + init() [WC2]) \ .def("__call__", &eoReplacement::operator()) void replacement() @@ -40,12 +41,12 @@ void replacement() def_abstract_functor >("eoReplacement"); // eoReplacement.h - DEF(eoGenerationalReplacement); - - class_, bases > > + DEF(eoGenerationalReplacement); + + class_, bases > > ("eoWeakElitistReplacement", init< eoReplacement& >()[WC1]); - + // eoMergeReduce.h DEF3(eoMergeReduce, eoMerge&, eoReduce& ); DEF(eoPlusReplacement); @@ -60,13 +61,12 @@ void replacement() // eoReduceMergeReduce.h //class_, bases > >("eoReplacement", -// init&, -// eoHowMany, eoReduce&, eoReduce&>()) -// .def("__call__", &eoReplacement::operator()); - + // init&, + // eoHowMany, eoReduce&, eoReduce&>()) + // .def("__call__", &eoReplacement::operator()); + //eoMGGReplacement DEF(eoMGGReplacement) .def( init() ) .def( init() ); } - diff --git a/eo/src/pyeo/selectOne.cpp b/eo/src/pyeo/selectOne.cpp index 554a6e36..5a28fcff 100644 --- a/eo/src/pyeo/selectOne.cpp +++ b/eo/src/pyeo/selectOne.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -33,10 +33,10 @@ using namespace boost::python; class eoSelectOneWrapper : public eoSelectOne { - public: +public: PyObject* self; eoSelectOneWrapper(PyObject* p) : self(p) {} - const PyEO& operator()(const eoPop& pop) + const PyEO& operator()(const eoPop& pop) { return boost::python::call_method< const PyEO& >(self, "__call__", boost::ref(pop)); } @@ -57,7 +57,7 @@ void add_select(std::string name, Init init) .def("__call__", &Select::operator(), return_internal_reference<>() ) ; } - + template void add_select(std::string name, Init1 init1, Init2 init2) { @@ -70,38 +70,39 @@ void add_select(std::string name, Init1 init1, Init2 init2) void selectOne() { /* Concrete classes */ - + pickle(class_("eoHowMany", init<>()) - .def( init() ) - .def( init() ) - .def( init() ) - .def("__call__", &eoHowMany::operator()) - .def("__neg__", &eoHowMany::operator-) - ); - + .def( init() ) + .def( init() ) + .def( init() ) + .def("__call__", &eoHowMany::operator()) + .def("__neg__", &eoHowMany::operator-) + ); + class_, eoSelectOneWrapper, boost::noncopyable>("eoSelectOne", init<>()) .def("__call__", &eoSelectOneWrapper::operator(), return_internal_reference<>() ) .def("setup", &eoSelectOne::setup); - + /* SelectOne derived classes */ - + add_select >("eoDetTournamentSelect", init<>(), init() ); add_select >("eoStochTournamentSelect", init<>(), init() ); - add_select >("eoTruncatedSelectOne", - init&, double>()[WC1], init&, eoHowMany >()[WC1] ); - + add_select >("eoTruncatedSelectOne", + init&, double>()[WC1], + init&, eoHowMany >()[WC1] + ); + // eoProportionalSelect is not feasible to implement at this point as fitness is not recognizable as a float // use eoDetTournament instead: with a t-size of 2 it is equivalent to eoProportional with linear scaling //add_select >("eoProportionalSelect", init&>() ); - + add_select >("eoRandomSelect"); add_select >("eoBestSelect"); add_select >("eoNoSelect"); - + add_select >("eoSequentialSelect", init<>(), init()); add_select >("eoEliteSequentialSelect"); /* * eoSelectFromWorth.h:class eoSelectFromWorth : public eoSelectOne - - */ + */ } diff --git a/eo/src/pyeo/selectors.cpp b/eo/src/pyeo/selectors.cpp index ba8d405d..7c8f4096 100644 --- a/eo/src/pyeo/selectors.cpp +++ b/eo/src/pyeo/selectors.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -53,9 +53,8 @@ void selectors() DEF3(eoTruncSelect, eoSelectOne&, eoHowMany); class_, bases > >("eoTruncatedSelectMany", - init&, double, double>()[WC1]) + init&, double, double>()[WC1]) .def(init&, double, double, bool> ()[WC1]) .def(init&, double, double, bool, bool> ()[WC1]) .def(init&, eoHowMany, eoHowMany> ()[WC1]); - } diff --git a/eo/src/pyeo/statistics.cpp b/eo/src/pyeo/statistics.cpp index 9c436ba5..fbad9269 100644 --- a/eo/src/pyeo/statistics.cpp +++ b/eo/src/pyeo/statistics.cpp @@ -5,9 +5,9 @@ using namespace boost::python; -class StatBaseWrapper : public eoStatBase +class StatBaseWrapper : public eoStatBase { - public: +public: PyObject* self; StatBaseWrapper(PyObject* p) : self(p) {} @@ -17,9 +17,9 @@ class StatBaseWrapper : public eoStatBase } }; -class SortedStatBaseWrapper : public eoSortedStatBase +class SortedStatBaseWrapper : public eoSortedStatBase { - public: +public: PyObject* self; SortedStatBaseWrapper(PyObject* p) : self(p) {} @@ -31,13 +31,13 @@ class SortedStatBaseWrapper : public eoSortedStatBase typedef std::vector eoPopView; -const PyEO& popview_getitem(const std::vector& pop, int it) -{ +const PyEO& popview_getitem(const std::vector& pop, int it) +{ unsigned item = unsigned(it); if (item > pop.size()) throw index_error("too much"); - - return *pop[item]; + + return *pop[item]; } void statistics() @@ -52,7 +52,7 @@ void statistics() .def("__getitem__", popview_getitem, return_internal_reference<>() ) .def("__len__", &eoPopView::size) ; - + class_, SortedStatBaseWrapper, boost::noncopyable> ("eoSortedStatBase", init<>()) .def("lastCall", &eoSortedStatBase::lastCall) diff --git a/eo/src/pyeo/test/maxone.py b/eo/src/pyeo/test/maxone.py index c2b6a0cf..3544d498 100644 --- a/eo/src/pyeo/test/maxone.py +++ b/eo/src/pyeo/test/maxone.py @@ -1,4 +1,3 @@ - import sys sys.path.append('..') @@ -10,47 +9,47 @@ from copy import copy class MinimFit(float): def __cmp__(self, other): - if other == None: # I seem to be getting None's, don't know why - return 1 - return float.__cmp__(other, self) - + if other == None: # I seem to be getting None's, don't know why + return 1 + return float.__cmp__(other, self) + class EvalFunc(eoEvalFunc): def __call__(self, eo): - eo.fitness = reduce(lambda x,y: x+y, eo.genome, 0) - + eo.fitness = reduce(lambda x,y: x+y, eo.genome, 0) + class MinEvalFunc(eoEvalFunc): def __call__(self, eo): - f = reduce(lambda x,y: x+y, eo.genome, 0 ) - eo.fitness = MinimFit(f) + f = reduce(lambda x,y: x+y, eo.genome, 0 ) + eo.fitness = MinimFit(f) class Init(eoInit): def __init__(self, genome_length = 10): - eoInit.__init__(self) - self.length = genome_length + eoInit.__init__(self) + self.length = genome_length def __call__(self, eo): - eo.genome = [rng().flip(0.5) for x in range(self.length)] - + eo.genome = [rng().flip(0.5) for x in range(self.length)] + class Mutate(eoMonOp): def __call__(self, eo): - eo.genome = copy(eo.genome) + eo.genome = copy(eo.genome) - prob = 1. / len(eo.genome) - for i in range(len(eo.genome)): - if rng().flip(0.5): - eo.genome[i] = 1-eo.genome[i]; - return 1 + prob = 1. / len(eo.genome) + for i in range(len(eo.genome)): + if rng().flip(0.5): + eo.genome[i] = 1-eo.genome[i]; + return 1 class Crossover(eoQuadOp): def __call__(self, eo1, eo2): - eo1.genome = copy(eo1.genome); - eo2.genome = copy(eo2.genome); + eo1.genome = copy(eo1.genome); + eo2.genome = copy(eo2.genome); - point = rng().random( len(eo1.genome) ); + point = rng().random( len(eo1.genome) ); - eo1.genome[:point] = eo2.genome[:point]; - eo2.genome[point:] = eo1.genome[point:]; - - return 1 + eo1.genome[:point] = eo2.genome[:point]; + eo2.genome[point:] = eo1.genome[point:]; + + return 1 evaluate = EvalFunc() init = Init(3) @@ -58,34 +57,32 @@ mutate = Mutate() xover = Crossover() if __name__ == '__main__': - + eo = EO() eo1 = EO() - + init(eo1) init(eo) evaluate(eo) print eo - + for i in range(10): - xover(eo, eo1) - mutate(eo) - - evaluate(eo) - print eo, eo1 - + xover(eo, eo1) + mutate(eo) + + evaluate(eo) + print eo, eo1 + print print print - + pop = eoPop(1, init) - + pop[0] = eo; mutate(pop[0]) pop[0].invalidate() evaluate(pop[0]) - - print pop[0], eo - + print pop[0], eo diff --git a/eo/src/pyeo/test/test_breeders.py b/eo/src/pyeo/test/test_breeders.py index 5d3fc760..c23d4787 100644 --- a/eo/src/pyeo/test/test_breeders.py +++ b/eo/src/pyeo/test/test_breeders.py @@ -1,18 +1,16 @@ from maxone import * import unittest - + class TestBreeders(unittest.TestCase): - def runtest(self, breed): - pop = eoPop(50, Init(20)) evaluate = EvalFunc() - print 'HERE' + print 'HERE' for indy in pop: evaluate(indy) newpop = eoPop(); breed(pop,newpop) - + print pop.best() for indy in newpop: evaluate(indy) print newpop.best() @@ -28,6 +26,5 @@ class TestBreeders(unittest.TestCase): def suite(): return unittest.makeSuite(TestSGA,'test') - if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_mo.py b/eo/src/pyeo/test/test_mo.py index ac847290..5a7a79a4 100644 --- a/eo/src/pyeo/test/test_mo.py +++ b/eo/src/pyeo/test/test_mo.py @@ -2,35 +2,33 @@ from maxone import * from math import exp import unittest - class MyInit(eoInit): def __call__(self, eo): eo.genome = [rng().normal(), rng().normal(), rng().normal()]; class MyMutate(eoMonOp): def __call__(self, eo): - std = 0.05 eo.genome = copy(eo.genome) - + eo.genome[0] += rng().normal() * std eo.genome[1] += rng().normal() * std - eo.genome[2] += rng().normal() * std + eo.genome[2] += rng().normal() * std return 1 class AnEval(eoEvalFunc): def __init__(self): eoEvalFunc.__init__(self) - + setObjectivesSize(2); setObjectivesValue(0,1); setObjectivesValue(1,1); - + def __call__(self, eo): x = abs(eo.genome[0]) y = abs(eo.genome[1]) z = abs(eo.genome[2]) - + eo.fitness = [ x / (x+y+z), y /(x+y+z) ] import Gnuplot @@ -47,71 +45,65 @@ def do_plot(pop): l2.append(indy.fitness[1]) d = Gnuplot.Data(l1,l2, with = 'points') - + d2 = Gnuplot.Data([0,1],[1,0], with='lines') - + g.plot(d,d2) - - class NSGA_II(eoAlgo): def __init__(self, ngens): - self.cont = eoGenContinue(ngens); - + self.selectOne = eoDetTournamentSelect(2); self.evaluate = AnEval() self.mutate = MyMutate() self.init = MyInit() - + self.seq = eoProportionalOp() self.seq.add(self.mutate, 1.0) - + self.perf2worth = eoNDSorting_II() - + def __call__(self, pop): - sz = len(pop) i = 0 while self.cont(pop): - newpop = eoPop() + newpop = eoPop() populator = eoSelectivePopulator(pop, newpop, self.selectOne); while len(newpop) < sz: self.seq(populator) - - for indy in newpop: + + for indy in newpop: self.evaluate(indy) pop.push_back(indy) self.perf2worth(pop) self.perf2worth.sort_pop(pop) - + #print pop[0].fitness, pop[0].genome pop.resize(sz) - + #worth = self.perf2worth.getValue() #print worth[0], worth[sz-1] - + i += 1 if i%100 == 0: - pass + pass do_plot(pop) - + worths = self.perf2worth.getValue() - + w0 = int(worths[0]-0.001) - + for i in range(len(pop)): if worths[i] <= w0: break; print pop[i].genome print pop[i].fitness - - + class TestNSGA_II(unittest.TestCase): - def testIndividuals(self): setObjectivesSize(2); setObjectivesValue(0,1); @@ -133,12 +125,12 @@ class TestNSGA_II(unittest.TestCase): self.failUnlessEqual(dominates(eo1, eo2), 1) self.failUnlessEqual(dominates(eo2, eo1), 0) self.failUnlessEqual(dominates(eo2, eo2), 0) - + def testNDSorting(self): setObjectivesSize(2); setObjectivesValue(0,-1) setObjectivesValue(1,-1); - + pop = eoPop() pop.resize(6) @@ -157,20 +149,18 @@ class TestNSGA_II(unittest.TestCase): for indy in pop: print indy.fitness - worths = srt.getValue() print worths print type(worths) def testNSGA_II(self): - evaluate = AnEval(); pop = eoPop(25, MyInit()) for indy in pop: evaluate(indy) - + nsga = NSGA_II(50) nsga(pop) - + if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_pickling.py b/eo/src/pyeo/test/test_pickling.py index 161668bb..81b3b9f5 100644 --- a/eo/src/pyeo/test/test_pickling.py +++ b/eo/src/pyeo/test/test_pickling.py @@ -5,9 +5,7 @@ import tempfile import os class TestPickling(unittest.TestCase): - def do_pickle(self, object): - filename = tempfile.mktemp() file = open(filename, 'wb') pickler = cPickle.Pickler(file) @@ -15,9 +13,9 @@ class TestPickling(unittest.TestCase): pickler.dump(object); del pickler file.close() - + file = open(filename) - + unpickler = cPickle.Unpickler(file) object2 = unpickler.load() @@ -29,15 +27,13 @@ class TestPickling(unittest.TestCase): return object2 def testInvalidEO(self): - eo = EO(); eo.genome = [1,2,3]; - + eo2 = self.do_pickle(eo) self.failUnlessEqual( str(eo), str(eo2) ) def testValidEO(self): - eo = EO(); eo.genome = [1,2,3]; eo.fitness = 10 @@ -45,19 +41,17 @@ class TestPickling(unittest.TestCase): eo2 = self.do_pickle(eo) self.failUnlessEqual( str(eo), str(eo2) ) - + def testPop(self): - pop = eoPop(40, init) - for indy in pop: + for indy in pop: evaluate(indy) pop2 = self.do_pickle(pop) - + self.failUnlessEqual( str(pop), str(pop2) ) def testHowMany(self): - howmany = eoHowMany(0.8); howmany2 = self.do_pickle(howmany) @@ -65,36 +59,33 @@ class TestPickling(unittest.TestCase): self.failUnlessEqual( str(howmany), str(howmany) ) def testRNG(self): - for i in range(10): rng().rand() - + rng2 = self.do_pickle(rng()) - + for i in range(100): a = rng().rand() b = rng2.rand() self.failUnlessEqual(a,b) def vParam(self,v): - v2 = self.do_pickle(v); self.failUnlessEqual(v.value, v2.value) - + def testValueParam(self): import Numeric - - self.vParam(eoValueParamInt(42,'int')) + + self.vParam(eoValueParamInt(42,'int')) self.vParam(eoValueParamFloat(4.2,'float')) - + v = eoValueParamVec() v.value = Numeric.arange(10) - self.vParam(v) + self.vParam(v) v = eoValueParamPair() v.value = (0.3,0.5) self.vParam(v) - if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_populator.py b/eo/src/pyeo/test/test_populator.py index a6743fda..12335956 100644 --- a/eo/src/pyeo/test/test_populator.py +++ b/eo/src/pyeo/test/test_populator.py @@ -20,36 +20,34 @@ class Xover(Crossover): return Crossover.__call__(self, eo1, eo2) class TestPopulator(unittest.TestCase): - def make_pop(self): pop = eoPop(20, init) for indy in pop: evaluate(indy) return pop - + def test_sequential(self): pop = self.make_pop() populator = eoSeqPopulator(pop, pop) - + print populator.get() print populator.get() - + def test_selective(self): sel = eoDetTournamentSelect(2) pop = self.make_pop() populator = eoSelectivePopulator(pop, pop, sel) - + print populator.get() print populator.get() def runOpContainer(self, opcontainer): - mutate = Mut() xover = Xover() - + print 'making seq' seq = opcontainer() - + print "xovertype", xover.getType() print "mutationtype", mutate.getType() @@ -58,29 +56,27 @@ class TestPopulator(unittest.TestCase): pop = self.make_pop(); offspring = eoPop() - + sel = eoDetTournamentSelect(2) - + print "making populator" populator = eoSelectivePopulator(pop, offspring, sel) print 'made' - + for i in xrange(1000): seq(populator) - + print mutate.cnt print xover.cnt def test_sequentialOp(self): - print '*'*20, "SequentialOp", '*'*20 + print '*'*20, "SequentialOp", '*'*20 self.runOpContainer(eoSequentialOp) - + def test_proportionalOp(self): - print '*'*20, "ProportionalOp", '*'*20 + print '*'*20, "ProportionalOp", '*'*20 self.runOpContainer(eoProportionalOp) - - if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_reduce.py b/eo/src/pyeo/test/test_reduce.py index 2ca99dc5..3e279168 100644 --- a/eo/src/pyeo/test/test_reduce.py +++ b/eo/src/pyeo/test/test_reduce.py @@ -2,11 +2,10 @@ from maxone import * import unittest class TestReduce(unittest.TestCase): - def run_test(self, ReduceClass, Arg = None): pop = eoPop(10, init) for indy in pop: evaluate(indy) - + if Arg: red = ReduceClass(Arg) else: @@ -14,8 +13,8 @@ class TestReduce(unittest.TestCase): red(pop, 5); - self.failUnlessEqual( len(pop), 5) - + self.failUnlessEqual( len(pop), 5) + def test_eoTruncate(self): self.run_test(eoTruncate) def test_eoRandomeReduce(self): @@ -28,7 +27,6 @@ class TestReduce(unittest.TestCase): self.run_test(eoDetTournamentTruncate, 2) def test_eoStochTournamentTruncate(self): self.run_test(eoStochTournamentTruncate, 0.9) - - + if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_selectone.py b/eo/src/pyeo/test/test_selectone.py index 1a25bc7f..f71913b9 100644 --- a/eo/src/pyeo/test/test_selectone.py +++ b/eo/src/pyeo/test/test_selectone.py @@ -3,64 +3,60 @@ import unittest class Init(eoInit): def __call__(self, eo): - pass + pass class TestSGA(unittest.TestCase): - def __init__(self, a): - unittest.TestCase.__init__(self, a) - self.pop = eoPop(4, Init()) + unittest.TestCase.__init__(self, a) + self.pop = eoPop(4, Init()) + + for i in range(len(self.pop)): + self.pop[i].fitness = i; - for i in range(len(self.pop)): - self.pop[i].fitness = i; - def do_test(self, selectOne): - - print '*'*20, "Testing", str(selectOne.__class__), '*'*20 - selection = [0. for i in range(len(self.pop))] + print '*'*20, "Testing", str(selectOne.__class__), '*'*20 + selection = [0. for i in range(len(self.pop))] + + nTries = 500 + for i in range(nTries): + selection[ selectOne(self.pop).fitness ] += 1 + + for i in range(len(self.pop)): + print i, selection[i], selection[i] / nTries + + return selection, nTries - nTries = 500 - for i in range(nTries): - selection[ selectOne(self.pop).fitness ] += 1 - - for i in range(len(self.pop)): - print i, selection[i], selection[i] / nTries - - return selection, nTries - def test_eoDetTournamenSelect(self): - - selectOne = eoDetTournamentSelect(2) - self.do_test(selectOne) - + selectOne = eoDetTournamentSelect(2) + self.do_test(selectOne) + def test_eoRandomSelect(self): - selectOne = eoRandomSelect() - self.do_test(selectOne) + selectOne = eoRandomSelect() + self.do_test(selectOne) def test_eoBestSelect(self): - selectOne = eoBestSelect() - (sel, nTries) = self.do_test(selectOne) + selectOne = eoBestSelect() + (sel, nTries) = self.do_test(selectOne) - self.failUnlessEqual(sel[0], 0); - self.failUnlessEqual(sel[-1], nTries); + self.failUnlessEqual(sel[0], 0); + self.failUnlessEqual(sel[-1], nTries); def test_eoNoSelect(self): - selectOne = eoNoSelect() - self.do_test(selectOne) + selectOne = eoNoSelect() + self.do_test(selectOne) def test_eoStochTournament(self): - selectOne = eoStochTournamentSelect(0.75) - self.do_test(selectOne) + selectOne = eoStochTournamentSelect(0.75) + self.do_test(selectOne) def test_eoSequentialSelect(self): - selectOne = eoSequentialSelect(); - self.do_test(selectOne) - + selectOne = eoSequentialSelect(); + self.do_test(selectOne) + def test_eoEliteSequentialSelect(self): - selectOne = eoEliteSequentialSelect(); - self.do_test(selectOne) - + selectOne = eoEliteSequentialSelect(); + self.do_test(selectOne) if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_sga.py b/eo/src/pyeo/test/test_sga.py index b84afe75..5f6d1c22 100644 --- a/eo/src/pyeo/test/test_sga.py +++ b/eo/src/pyeo/test/test_sga.py @@ -2,43 +2,44 @@ from maxone import * import unittest class TestSGA(unittest.TestCase): - def dotestSGA(self, evaluate): - init = Init(20) - mutate = Mutate() - xover = Crossover() + init = Init(20) + mutate = Mutate() + xover = Crossover() - pop = eoPop(50, init) - for indy in pop: evaluate(indy) + pop = eoPop(50, init) + for indy in pop: evaluate(indy) - select = eoDetTournamentSelect(3); - cont1 = eoGenContinue(20); - - cont = eoCheckPoint(cont1) - - mon = eoGnuplot1DMonitor() - - avg = eoAverageStat() - bst = eoBestFitnessStat() - mon.add(avg) - mon.add(bst) - - # add it to the checkpoint - cont.add(avg) - #cont.add(mon) - cont.add(bst) - - sga = eoSGA(select, xover, 0.6, mutate, 0.4, evaluate, cont); + select = eoDetTournamentSelect(3); + cont1 = eoGenContinue(20); - sga(pop) + cont = eoCheckPoint(cont1) + + mon = eoGnuplot1DMonitor() + + avg = eoAverageStat() + bst = eoBestFitnessStat() + mon.add(avg) + mon.add(bst) + + # add it to the checkpoint + cont.add(avg) + #cont.add(mon) + cont.add(bst) + + sga = eoSGA(select, xover, 0.6, mutate, 0.4, evaluate, cont); + + sga(pop) + + print pop.best() - print pop.best() def testSGA_Max(self): - evaluate = EvalFunc() - self.dotestSGA(evaluate) + evaluate = EvalFunc() + self.dotestSGA(evaluate) + def testSGA_Min(self): - evaluate = MinEvalFunc() - self.dotestSGA(evaluate) + evaluate = MinEvalFunc() + self.dotestSGA(evaluate) if __name__=='__main__': unittest.main() diff --git a/eo/src/pyeo/test/test_transform.py b/eo/src/pyeo/test/test_transform.py index 67d892e6..fb70de3e 100644 --- a/eo/src/pyeo/test/test_transform.py +++ b/eo/src/pyeo/test/test_transform.py @@ -1,61 +1,62 @@ """Test script for the eoSGATranform class""" from copy import deepcopy -from PyEO import * +from PyEO import * from maxone import * pop = eoPop() + for i in range(10): - eo = EO() - init(eo) - evaluate(eo) - pop.push_back(eo) + eo = EO() + init(eo) + evaluate(eo) + pop.push_back(eo) transform = eoSGATransform(xover, 0.8, mutate, 0.2) def test1(pop, transform): - pop = deepcopy(pop) - print "test 1" - print "Initial population:" - print pop + pop = deepcopy(pop) + print "test 1" + print "Initial population:" + print pop - transform(pop) + transform(pop) - print "GM pop:" - print pop + print "GM pop:" + print pop def test2(pop, transform): - pop = deepcopy(pop) + pop = deepcopy(pop) - print "test 2" - print "Initial population" - print pop + print "test 2" + print "Initial population" + print pop - checkpoint = eoCheckPoint(eoGenContinue(50)) - select = eoSelectNumber(eoDetTournamentSelect(3), 10) - replace = eoGenerationalReplacement() - - algo = eoEasyEA(checkpoint, evaluate, select, transform, replace) - algo(pop) + checkpoint = eoCheckPoint(eoGenContinue(50)) + select = eoSelectNumber(eoDetTournamentSelect(3), 10) + replace = eoGenerationalReplacement() - print "Evoluated pop:" - print pop + algo = eoEasyEA(checkpoint, evaluate, select, transform, replace) + algo(pop) + + print "Evoluated pop:" + print pop if __name__ == "__main__": - try: - test1(pop, transform) - except: - import sys - print - print "Caught an exception:" - print sys.exc_type, sys.exc_value - print + try: + test1(pop, transform) + except: + import sys + print + print "Caught an exception:" + print sys.exc_type, sys.exc_value + print - try: - test2(pop, transform) - except: - import sys - print - print "Caught an exception:" - print sys.exc_type, sys.exc_value - print + try: + test2(pop, transform) + except: + import sys + print + print "Caught an exception:" + print sys.exc_type, sys.exc_value + print diff --git a/eo/src/pyeo/valueParam.cpp b/eo/src/pyeo/valueParam.cpp index 60625180..59ed1a47 100644 --- a/eo/src/pyeo/valueParam.cpp +++ b/eo/src/pyeo/valueParam.cpp @@ -1,6 +1,6 @@ /* PyEO - + Copyright (C) 2003 Maarten Keijzer This program is free software; you can redistribute it and/or modify @@ -33,13 +33,12 @@ public: PyObject* self; ParamWrapper(PyObject* p) : self(p) {} ParamWrapper(PyObject* p, - std::string a, - std::string b, - std::string c, - char d, - bool e) : eoParam(a,b,c,d,e), self(p) {} + std::string a, + std::string b, + std::string c, + char d, + bool e) : eoParam(a,b,c,d,e), self(p) {} - std::string getValue() const { return call_method(self, "getValueAsString"); @@ -49,7 +48,6 @@ public: { call_method(self, "setValueAsString", s); } - }; template @@ -63,7 +61,7 @@ struct ValueParam_pickle_suite : boost::python::pickle_suite str def(_param.defValue()); str l(_param.longName()); object s(_param.shortName()); - object r(_param.required()); + object r(_param.required()); return make_tuple(v,d,def,l,s,r); } static @@ -90,31 +88,31 @@ void setv(eoValueParam& v, U val) { v.value() = val; } template <> numeric::array getv< std::vector, numeric::array > - (const eoValueParam< std::vector >& param) +(const eoValueParam< std::vector >& param) { const std::vector& v = param.value(); list result; for (unsigned i =0; i < v.size(); ++i) result.append(v[i]); - + return numeric::array(result); } template <> void setv< std::vector, numeric::array > - (eoValueParam< std::vector >& param, numeric::array val) +(eoValueParam< std::vector >& param, numeric::array val) { std::vector& v = param.value(); v.resize( boost::python::len(val) ); for (unsigned i = 0; i < v.size(); ++i) - { - extract x(val[i]); - if (!x.check()) - throw std::runtime_error("double expected"); - - v[i] = x(); - } + { + extract x(val[i]); + if (!x.check()) + throw std::runtime_error("double expected"); + + v[i] = x(); + } } template <> @@ -126,7 +124,7 @@ tuple getv, tuple > template <> void setv< std::pair, tuple > - (eoValueParam< std::pair >& p, tuple val) +(eoValueParam< std::pair >& p, tuple val) { extract first(val[0]); extract second(val[1]); @@ -145,7 +143,7 @@ void define_valueParam(std::string prefix) { std::string name = "eoValueParam"; name += prefix; - + class_, bases >(name.c_str(), init<>()) .def(init()) .def(init()) @@ -173,7 +171,7 @@ void valueParam() .def("shortName", &eoParam::shortName) .def("required", &eoParam::required) ; - + define_valueParam("Int"); define_valueParam("Float"); define_valueParam, numeric::array >("Vec"); @@ -191,4 +189,3 @@ void valueParam() .add_property("object", &ValueParam::getObj, &ValueParam::setObj) ; } - diff --git a/eo/src/pyeo/valueParam.h b/eo/src/pyeo/valueParam.h index 783f2fc1..940a4351 100644 --- a/eo/src/pyeo/valueParam.h +++ b/eo/src/pyeo/valueParam.h @@ -7,23 +7,22 @@ class ValueParam : public eoParam // ValueParam containing python object { boost::python::object obj; - - public: - - ValueParam() : eoParam(), obj() {} - - ValueParam(boost::python::object o, - std::string longName, - std::string d = "No Description", - char s = 0, - bool r = false) : eoParam(longName, "", d, s, r) - { - std::cerr << "HI" << std::endl; - obj = o; - eoParam::defValue(getValue()); - } - +public: + + ValueParam() : eoParam(), obj() {} + + ValueParam(boost::python::object o, + std::string longName, + std::string d = "No Description", + char s = 0, + bool r = false) : eoParam(longName, "", d, s, r) + { + std::cerr << "HI" << std::endl; + obj = o; + eoParam::defValue(getValue()); + } + std::string getValue() const { boost::python::str s = boost::python::str(obj); @@ -37,7 +36,6 @@ class ValueParam : public eoParam // ValueParam containing python object boost::python::object getObj() const { return obj;} void setObj(boost::python::object o) { obj = o; } - }; #endif diff --git a/eo/src/utils/ChangeLog b/eo/src/utils/ChangeLog index a661c0cf..dac74c49 100644 --- a/eo/src/utils/ChangeLog +++ b/eo/src/utils/ChangeLog @@ -1,42 +1,42 @@ 2007-08-22 Jochen Küpper - * eoRNG.h (eoRng::random): Add comment on truncation as standard way of - floating point to integer conversion. + * eoRNG.h (eoRng::random): Add comment on truncation as standard way of + floating point to integer conversion. 2006-12-04 Jochen Küpper - * eoRNG.h (eoRng::normal(stdev)): Revert erroneous change. + * eoRNG.h (eoRng::normal(stdev)): Revert erroneous change. 2006-12-02 Jochen Küpper - * eoTimedMonitor.h (eoTimedMonitor::seconds): Make unsigned. + * eoTimedMonitor.h (eoTimedMonitor::seconds): Make unsigned. - * eoRNG.h: Cleanup docs and document /all/ members. + * eoRNG.h: Cleanup docs and document /all/ members. - * eoRNG.cpp, eoRNG.h (K, M, N): Declare static and initialize in cpp. + * eoRNG.cpp, eoRNG.h (K, M, N): Declare static and initialize in cpp. 2006-12-01 Jochen Küpper - * eoRNG.cpp: Use C++ style cast. + * eoRNG.cpp: Use C++ style cast. - * Makefile.am: Add missing header for distribution. + * Makefile.am: Add missing header for distribution. 2006-11-30 Jochen Küpper - * eoRNG.h: Generally include + * eoRNG.h: Generally include 2006-11-16 Jochen Küpper - * eoParser.h (eoParser::getORcreateParam): Make this a real if-then-else - clause around ptParam (found or not). + * eoParser.h (eoParser::getORcreateParam): Make this a real if-then-else + clause around ptParam (found or not). - * eoParam.h (eoValueParam::setValue): Document. - (eoValueParam >::setValue): Allow delimiters ',' and - ';'. A plain ' ' does not work, as it is not correctly read by - eoParser::readFrom. + * eoParam.h (eoValueParam::setValue): Document. + (eoValueParam >::setValue): Allow delimiters ',' and + ';'. A plain ' ' does not work, as it is not correctly read by + eoParser::readFrom. - * Local Variables: - * coding: iso-8859-1 - * mode: flyspell - * fill-column: 80 - * End: + * Local Variables: + * coding: iso-8859-1 + * mode: flyspell + * fill-column: 80 + * End: diff --git a/eo/src/utils/compatibility.h b/eo/src/utils/compatibility.h index af20a792..937ab8a0 100644 --- a/eo/src/utils/compatibility.h +++ b/eo/src/utils/compatibility.h @@ -2,12 +2,12 @@ ----------------------------------------------------------------------------- compatibility.h - File to store some compiler specific stuff in. Currently handles, or + File to store some compiler specific stuff in. Currently handles, or least tries to handle the min() max() problems when using MSVC (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 - + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -33,15 +33,15 @@ #ifdef __GNUC__ #if __GNUC__ < 3 - // check for stdlibc++v3 which does have ios_base - #ifndef _CPP_BITS_IOSBASE_H - typedef ios ios_base; // not currently defined in GCC - #endif + // check for stdlibc++v3 which does have ios_base + #ifndef _CPP_BITS_IOSBASE_H + typedef ios ios_base; // not currently defined in GCC + #endif #endif #endif #if defined(_MSC_VER) && (_MSC_VER < 1300) -/* +/* Maarten: added this code here because Mirkosoft has the nasty habit of #define min and max in stdlib.h (and windows.h) I'm trying to undo this horrible macro magic (microsoft yet macrohard) @@ -67,7 +67,7 @@ namespace std // else return b; } - + template const T& max(const T& a, const T& b) { if(a > b) @@ -79,4 +79,4 @@ namespace std #endif // _MSC_VER -#endif +#endif diff --git a/eo/src/utils/eoCheckPoint.h b/eo/src/utils/eoCheckPoint.h index d6df8b78..ea562e8b 100644 --- a/eo/src/utils/eoCheckPoint.h +++ b/eo/src/utils/eoCheckPoint.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoCheckPoint.h // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -52,12 +52,12 @@ */ /** eoCheckPoint is a container class. - It contains std::vectors of (pointers to) + It contains std::vectors of (pointers to) eoContinue (modif. MS July 16. 2002) eoStats, eoUpdater and eoMonitor - it is an eoContinue, so its operator() will be called every generation - + it is an eoContinue, so its operator() will be called every generation - and will return the contained-combined-eoContinue result - but before that it will call in turn every single + but before that it will call in turn every single {statistics, updaters, monitors} that it has been given, and after that, if stopping, all lastCall methods of the above. */ @@ -66,7 +66,7 @@ class eoCheckPoint : public eoContinue { public : - eoCheckPoint(eoContinue& _cont) + eoCheckPoint(eoContinue& _cont) { continuators.push_back(&_cont); } @@ -118,31 +118,31 @@ bool eoCheckPoint::operator()(const eoPop& _pop) bool bContinue = true; for (i = 0; i < continuators.size(); ++i) - if ( !(*continuators[i])(_pop) ) - bContinue = false; + if ( !(*continuators[i])(_pop) ) + bContinue = false; - if (! bContinue) // we're going to stop: lastCall, gentlemen + if (! bContinue) // we're going to stop: lastCall, gentlemen { - if (!sorted.empty()) - { - for (i = 0; i < sorted.size(); ++i) - { - sorted[i]->lastCall(sorted_pop); - } - } - for (i = 0; i < stats.size(); ++i) - stats[i]->lastCall(_pop); + if (!sorted.empty()) + { + for (i = 0; i < sorted.size(); ++i) + { + sorted[i]->lastCall(sorted_pop); + } + } + for (i = 0; i < stats.size(); ++i) + stats[i]->lastCall(_pop); - for (i = 0; i < updaters.size(); ++i) - updaters[i]->lastCall(); + for (i = 0; i < updaters.size(); ++i) + updaters[i]->lastCall(); - for (i = 0; i < monitors.size(); ++i) - monitors[i]->lastCall(); + for (i = 0; i < monitors.size(); ++i) + monitors[i]->lastCall(); } return bContinue; } -/** returns a string with all className() +/** returns a string with all className() * of data separated with "\n" (for debugging) */ template diff --git a/eo/src/utils/eoData.h b/eo/src/utils/eoData.h index ea70cabe..876b0095 100644 --- a/eo/src/utils/eoData.h +++ b/eo/src/utils/eoData.h @@ -45,4 +45,3 @@ #define eo_is_an_integer false #endif - diff --git a/eo/src/utils/eoDistance.h b/eo/src/utils/eoDistance.h index 1a7c9edd..b26f249d 100644 --- a/eo/src/utils/eoDistance.h +++ b/eo/src/utils/eoDistance.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoDistance.h // (c) GeNeura Team, 1998, Marc Schoenauer 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -28,11 +28,11 @@ #include -/** @addtogroup Stats +/** @addtogroup Stats * @{ * */ -/** +/** This is a generic class for distance functors: takes 2 things and returns a double */ @@ -41,8 +41,8 @@ class eoDistance : public eoBF {}; -/** - This is a generic class for Euclidain distance (L2 norm) computation: +/** + This is a generic class for Euclidain distance (L2 norm) computation: assumes the 2 things are std::vectors of something that is double-castable */ template< class EOT > @@ -54,16 +54,16 @@ public: double sum=0.0; for (unsigned i=0; i<_v1.size(); i++) { - double r = static_cast (_v1[i]) - static_cast (_v2[i]); - sum += r*r; + double r = static_cast (_v1[i]) - static_cast (_v2[i]); + sum += r*r; } return sqrt(sum); } }; -/** - This is a generic class for L1 distance computation: - assumes the 2 things are std::vectors of something +/** + This is a generic class for L1 distance computation: + assumes the 2 things are std::vectors of something that is double-castable For bitstrings, this is the Hamming distance */ @@ -76,15 +76,15 @@ public: double sum=0.0; for (unsigned i=0; i<_v1.size(); i++) { - double r = static_cast (_v1[i]) - static_cast (_v2[i]); - sum += fabs(r); + double r = static_cast (_v1[i]) - static_cast (_v2[i]); + sum += fabs(r); } return sum; } }; -/* this distance measures the difference in fitness - * I am not sure it can be of any use, though ... +/* this distance measures the difference in fitness + * I am not sure it can be of any use, though ... * except for some testing */ template< class EOT > @@ -100,5 +100,5 @@ public: /** @} */ - + #endif diff --git a/eo/src/utils/eoFDCStat.h b/eo/src/utils/eoFDCStat.h index a604533f..1d2050b7 100644 --- a/eo/src/utils/eoFDCStat.h +++ b/eo/src/utils/eoFDCStat.h @@ -33,7 +33,7 @@ /** The Fitness Distance Correlation computation. - + Stores the values into eoValueParam so they can be snapshot by some eoGnuplotSnapshot ... @@ -53,7 +53,7 @@ public: /** Ctor with the optimum */ eoFDCStat(eoDistance & _dist, EOT & _theBest, - std::string _description = "FDC") : + std::string _description = "FDC") : eoStat(0, _description), dist(_dist), theBest(_theBest), boolOpt(true) {} @@ -63,30 +63,30 @@ public: virtual void operator()(const eoPop& _pop) { unsigned i; - if (!boolOpt) // take the local best - theBest = _pop.best_element(); + if (!boolOpt) // take the local best + theBest = _pop.best_element(); unsigned int pSize = _pop.size(); distToBest.value().resize(pSize); fitnesses.value().resize(pSize); double sumFit = 0.0, sumDist = 0.0; for (i=0; i & dist; EOT theBest; - bool boolOpt; // whether the best is known or not + bool boolOpt; // whether the best is known or not eoValueParam > distToBest; eoValueParam > fitnesses; }; @@ -119,12 +119,12 @@ class eoFDCFileSnapshot : public eoFileSnapshot // is an eoMonitor public: /** Ctor: in addition to the parameters of the ctor of an eoFileSnapshot we need here an eoFDCStat. The 2 std::vectors (distances to optimum - and fitnesses) are added to the monitor so they can be processed + and fitnesses) are added to the monitor so they can be processed later to a file - and eventually by gnuplot */ eoFDCFileSnapshot(eoFDCStat & _FDCstat, - std::string _dirname = "tmpFDC", unsigned _frequency = 1, - std::string _filename = "FDC", std::string _delim = " "): + std::string _dirname = "tmpFDC", unsigned _frequency = 1, + std::string _filename = "FDC", std::string _delim = " "): eoFileSnapshot(_dirname, _frequency, _filename, _delim), FDCstat(_FDCstat) { @@ -142,4 +142,3 @@ private: }; #endif - diff --git a/eo/src/utils/eoFeasibleRatioStat.h b/eo/src/utils/eoFeasibleRatioStat.h index 8d669dbe..cbbe1738 100644 --- a/eo/src/utils/eoFeasibleRatioStat.h +++ b/eo/src/utils/eoFeasibleRatioStat.h @@ -1,11 +1,10 @@ - /* (c) 2010 Thales group This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; version 2 + License as published by the Free Software Foundation; version 2 of the License. This library is distributed in the hope that it will be useful, @@ -46,11 +45,11 @@ public: eoFeasibleRatioStat( std::string description = "FeasibleRatio" ) : eoStat( 0.0, description ) {} - virtual void operator()( const eoPop & pop ) + virtual void operator()( const eoPop & pop ) { #ifndef NDEBUG assert( pop.size() > 0 ); - + double count = static_cast( std::count_if( pop.begin(), pop.end(), eoIsFeasible ) ); double size = static_cast( pop.size() ); double ratio = count/size; @@ -60,9 +59,8 @@ public: value() = static_cast( std::count_if( pop.begin(), pop.end(), eoIsFeasible ) ) / static_cast( pop.size() ); #endif } - + virtual std::string className(void) const { return "eoFeasibleRatioStat"; } }; #endif // _eoFeasibleRatioStat_h_ - diff --git a/eo/src/utils/eoFileMonitor.cpp b/eo/src/utils/eoFileMonitor.cpp index cd5cbab6..3cc96deb 100644 --- a/eo/src/utils/eoFileMonitor.cpp +++ b/eo/src/utils/eoFileMonitor.cpp @@ -1,7 +1,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #include #include @@ -32,21 +32,21 @@ void eoFileMonitor::printHeader(std::ostream& os) void eoFileMonitor::printHeader() { // create file - ofstream os(filename.c_str()); + ofstream os(filename.c_str()); if (!os) { string str = "eoFileMonitor could not open: " + filename; throw runtime_error(str); } - + printHeader(os); } eoMonitor& eoFileMonitor::operator()(void) { - ofstream os(filename.c_str(), - overwrite ? + ofstream os(filename.c_str(), + overwrite ? ios_base::out|ios_base::trunc // truncate : ios_base::out|ios_base::app // append @@ -58,7 +58,7 @@ eoMonitor& eoFileMonitor::operator()(void) throw runtime_error(str); } - if ( + if ( header // we want to write headers && firstcall // we do not want to write headers twice && !keep // if we append to an existing file, headers are useless @@ -67,17 +67,17 @@ eoMonitor& eoFileMonitor::operator()(void) printHeader(); firstcall = false; } - + return operator()(os); } eoMonitor& eoFileMonitor::operator()(std::ostream& os) { - + iterator it = vec.begin(); - + os << (*it)->getValue(); - + for(++it; it != vec.end(); ++it) { os << delim.c_str() << (*it)->getValue(); @@ -87,4 +87,3 @@ eoMonitor& eoFileMonitor::operator()(std::ostream& os) return *this; } - diff --git a/eo/src/utils/eoFileMonitor.h b/eo/src/utils/eoFileMonitor.h index b89fd1e6..9438d25c 100644 --- a/eo/src/utils/eoFileMonitor.h +++ b/eo/src/utils/eoFileMonitor.h @@ -58,16 +58,16 @@ public : * @param _overwrite if true, overwrite the existing file */ eoFileMonitor( - std::string _filename, - std::string _delim = " ", - bool _keep_existing = false, + std::string _filename, + std::string _delim = " ", + bool _keep_existing = false, bool _header = false, bool _overwrite = false ) - : filename(_filename), - delim(_delim), - keep(_keep_existing), - header(_header), + : filename(_filename), + delim(_delim), + keep(_keep_existing), + header(_header), firstcall(true), overwrite(_overwrite) { @@ -84,7 +84,7 @@ public : //! Called first, try to open the file in append mode and write the header if asked virtual eoMonitor& operator()(void); - /*! Main call, normally called at each generation. + /*! Main call, normally called at each generation. Write the content of the registered vector into the file, each item being separated by delim */ virtual eoMonitor& operator()(std::ostream& os); @@ -104,13 +104,13 @@ private : //! delimiter to use between each write std::string delim; - + //! should we append or create a new file - bool keep; - + bool keep; + //! printing header at begin of file? bool header; - + //! flag to avoid calling twice operator()(void) bool firstcall; diff --git a/eo/src/utils/eoFileSnapshot.h b/eo/src/utils/eoFileSnapshot.h index b5d5142b..cdd2e36c 100644 --- a/eo/src/utils/eoFileSnapshot.h +++ b/eo/src/utils/eoFileSnapshot.h @@ -58,7 +58,7 @@ public : typedef eoValueParam > vDoubleParam; eoFileSnapshot(std::string _dirname, unsigned _frequency = 1, std::string _filename = "gen", - std::string _delim = " ", unsigned _counter = 0, bool _rmFiles = true): + std::string _delim = " ", unsigned _counter = 0, bool _rmFiles = true): dirname(_dirname), frequency(_frequency), filename(_filename), delim(_delim), counter(_counter), boolChanged(true) { @@ -71,11 +71,11 @@ public : // now make sure there is a dir without any genXXX file in it if (res) // no dir present { - s = std::string("mkdir ")+dirname; + s = std::string("mkdir ")+dirname; } else if (!res && _rmFiles) { - s = std::string("/bin/rm ")+dirname+ "/" + filename + "*"; + s = std::string("/bin/rm ")+dirname+ "/" + filename + "*"; } else s = " "; @@ -111,9 +111,9 @@ public : { if (counter % frequency) { - boolChanged = false; // subclass with gnuplot will do nothing - counter++; - return (*this); + boolChanged = false; // subclass with gnuplot will do nothing + counter++; + return (*this); } counter++; boolChanged = true; @@ -137,35 +137,35 @@ public : static_cast >* >(vec[0]); const std::vector v = ptParam->value(); - if (vec.size() == 1) // only one std::vector: -> add number in front + if (vec.size() == 1) // only one std::vector: -> add number in front { - for (unsigned k=0; k > vv(vec.size()); - vv[0]=v; - for (unsigned i=1; i >* >(vec[1]); - vv[i] = ptParam->value(); - if (vv[i].size() != v.size()) - throw std::runtime_error("Dimension error in eoSnapshotMonitor"); - } - for (unsigned k=0; k > vv(vec.size()); + vv[0]=v; + for (unsigned i=1; i >* >(vec[1]); + vv[i] = ptParam->value(); + if (vv[i].size() != v.size()) + throw std::runtime_error("Dimension error in eoSnapshotMonitor"); + } + for (unsigned k=0; k(T(), _description), func(f) {} - + using eoStat::value; - + void operator()(const eoPop& pop) { value() = func(pop); } @@ -32,7 +31,7 @@ private: func_t func; }; -/** +/** * @ingroup Stats */ template @@ -43,4 +42,3 @@ eoFuncPtrStat& makeFuncPtrStat( T (*func)(const eoPop&), eoFunctorS } #endif - diff --git a/eo/src/utils/eoGnuplot1DSnapshot.h b/eo/src/utils/eoGnuplot1DSnapshot.h index 05015b64..38c5af74 100644 --- a/eo/src/utils/eoGnuplot1DSnapshot.h +++ b/eo/src/utils/eoGnuplot1DSnapshot.h @@ -64,8 +64,8 @@ class eoGnuplot1DSnapshot: public eoFileSnapshot, public eoGnuplot // Ctor eoGnuplot1DSnapshot(std::string _dirname, eoRealVectorBounds & _bounds, - unsigned _frequency = 1, std::string _filename = "gen", - std::string _delim = " ", unsigned _counter = 0, bool _rmFiles = true ) : + unsigned _frequency = 1, std::string _filename = "gen", + std::string _delim = " ", unsigned _counter = 0, bool _rmFiles = true ) : eoFileSnapshot(_dirname, _frequency, _filename, _delim, _counter, _rmFiles), eoGnuplot(_filename,"set data style points"), pointSize(5) diff --git a/eo/src/utils/eoHowMany.h b/eo/src/utils/eoHowMany.h index 2f02216e..1105f3b7 100644 --- a/eo/src/utils/eoHowMany.h +++ b/eo/src/utils/eoHowMany.h @@ -123,7 +123,7 @@ public: if (count == 0) { unsigned int res = static_cast( std::ceil( rate * _size ) ); - + if( res == 0 ) { eo::log << eo::warnings << "Call to a eoHowMany instance returns 0 (rate=" << rate << ", size=" << _size << ")" << std::endl; } diff --git a/eo/src/utils/eoIntBounds.cpp b/eo/src/utils/eoIntBounds.cpp index 59350240..11cd942d 100644 --- a/eo/src/utils/eoIntBounds.cpp +++ b/eo/src/utils/eoIntBounds.cpp @@ -60,12 +60,12 @@ eoIntBounds* eoGeneralIntBounds::getBoundsFromString(std::string _value) std::string sMinBounds = sBounds.substr(0,posDelim); if ( (sMinBounds != std::string("-inf")) && - (sMinBounds != std::string("-infinity")) - ) - { - minBounded = true; - minBound = read_int(sMinBounds); - } + (sMinBounds != std::string("-infinity")) + ) + { + minBounded = true; + minBound = read_int(sMinBounds); + } // max bound size_t posEndDelim = sBounds.find_first_not_of(delim,posDelim); @@ -73,26 +73,26 @@ eoIntBounds* eoGeneralIntBounds::getBoundsFromString(std::string _value) std::string sMaxBounds = sBounds.substr(posEndDelim); if ( (sMaxBounds != std::string("+inf")) && - (sMaxBounds != std::string("+infinity")) - ) - { - maxBounded = true; - maxBound = read_int(sMaxBounds); - } + (sMaxBounds != std::string("+infinity")) + ) + { + maxBounded = true; + maxBound = read_int(sMaxBounds); + } // now create the embedded eoIntBounds object eoIntBounds * locBound; if (minBounded && maxBounded) - { - if (maxBound <= minBound) - throw std::runtime_error("Syntax error in eoGeneralIntBounds Ctor"); - locBound = new eoIntInterval(minBound, maxBound); - } + { + if (maxBound <= minBound) + throw std::runtime_error("Syntax error in eoGeneralIntBounds Ctor"); + locBound = new eoIntInterval(minBound, maxBound); + } else if (!minBounded && !maxBounded) // no bound at all - locBound = new eoIntNoBounds; + locBound = new eoIntNoBounds; else if (!minBounded && maxBounded) - locBound = new eoIntAboveBound(maxBound); + locBound = new eoIntAboveBound(maxBound); else if (minBounded && !maxBounded) - locBound = new eoIntBelowBound(minBound); + locBound = new eoIntBelowBound(minBound); return locBound; } diff --git a/eo/src/utils/eoIntBounds.h b/eo/src/utils/eoIntBounds.h index 807751da..2127c92f 100644 --- a/eo/src/utils/eoIntBounds.h +++ b/eo/src/utils/eoIntBounds.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoIntBounds.h // (c) Marc Schoenauer 2001, Maarten Keijzer 2000, GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifndef _eoIntBounds_h #define _eoIntBounds_h -#include // std::exceptions! +#include // std::exceptions! #include /** @@ -42,24 +42,24 @@ Scalar type: Basic class is eoIntBounds, a pure virtual. The following pure virtual methods are to be used in mutations: -- void foldsInBounds(long int &) that folds any value that falls out of +- void foldsInBounds(long int &) that folds any value that falls out of the bounds back into the bounds, by bouncing on the limit (if any) -- bool isInBounds(long int) that simply says whether or not the argument +- bool isInBounds(long int) that simply says whether or not the argument is in the bounds - void truncate(long int &) that set the argument to the bound value it it exceeds it -So mutation can choose -- iterate trying until they fall in bounds, +So mutation can choose +- iterate trying until they fall in bounds, - only try once and "restd::pair" by using the foldsInBounds method - only try once and restd::pair using the truncate method (will create a huge bias toward the bound if the soluiton is not far from the bounds) -There is also a uniform() method that generates a uniform value +There is also a uniform() method that generates a uniform value (if possible, i.e. if bounded) in the interval. -Derived class are -eoIntInterval that holds a minimum and maximum value, +Derived class are +eoIntInterval that holds a minimum and maximum value, eoIntNoBounds the "unbounded bounds" (-infinity, +infinity) eoIntBelowBound the half-bounded interval [min, +infinity) eoIntAboveBound the half-bounded interval (-infinity, max] @@ -68,7 +68,7 @@ THis file also contains the declaration of *the* global object that is the unbounded bound */ class eoIntBounds : public eoPersistent -{ +{ public: virtual ~eoIntBounds(){} @@ -97,7 +97,7 @@ public: */ virtual void foldsInBounds(double &) const = 0; - /** foldsInBounds for ints: + /** foldsInBounds for ints: * call the method for double and convert back */ virtual void foldsInBounds(long int & i) const { @@ -112,24 +112,24 @@ public: /** truncate for ints: call the method for double and convert back */ - virtual void truncate(long int & i) const + virtual void truncate(long int & i) const { double r = double(i); truncate(r); i = (long int)(r); } - /** get minimum value + /** get minimum value * std::exception if does not exist - */ + */ virtual long int minimum() const = 0 ; /** get maximum value * std::exception if does not exist - */ + */ virtual long int maximum() const = 0 ; /** get range * std::exception if unbounded - */ + */ virtual long int range() const = 0; /** random generator of uniform numbers in bounds @@ -165,11 +165,11 @@ public: { throw std::logic_error("Trying to get minimum of unbounded eoIntBounds"); } - virtual long int maximum() const + virtual long int maximum() const { throw std::logic_error("Trying to get maximum of unbounded eoIntBounds"); } - virtual long int range() const + virtual long int range() const { throw std::logic_error("Trying to get range of unbounded eoIntBounds"); } @@ -212,7 +212,7 @@ public: } /** for memory managements - ugly */ - virtual eoIntBounds * dup() const + virtual eoIntBounds * dup() const { return new eoIntNoBounds(*this); } @@ -236,18 +236,18 @@ class eoIntInterval : public eoIntBounds { public : virtual ~eoIntInterval(){} - - /** + + /** Simple bounds = minimum and maximum (allowed) */ - eoIntInterval(long int _min=0, long int _max=1) : - repMinimum(_min), repMaximum(_max), repRange(_max-_min) + eoIntInterval(long int _min=0, long int _max=1) : + repMinimum(_min), repMaximum(_max), repRange(_max-_min) { if (repRange<=0) throw std::logic_error("Void range in eoIntBounds"); } - // accessors + // accessors virtual long int minimum() const { return repMinimum; } virtual long int maximum() const { return repMaximum; } virtual long int range() const { return repRange; } @@ -258,18 +258,18 @@ public : virtual bool isMinBounded(void) const {return true;} virtual bool isMaxBounded(void) const {return true;} - virtual double uniform(eoRng & _rng = eo::rng) const + virtual double uniform(eoRng & _rng = eo::rng) const { return repMinimum + _rng.uniform(repRange); - } + } - virtual long int random(eoRng & _rng = eo::rng) const + virtual long int random(eoRng & _rng = eo::rng) const { return repMinimum + _rng.random(repRange); - } + } // says if a given double is within the bounds - virtual bool isInBounds(double _r) const + virtual bool isInBounds(double _r) const { if (_r < repMinimum) return false; @@ -279,36 +279,36 @@ public : } // folds a value into bounds - virtual void foldsInBounds(double & _r) const + virtual void foldsInBounds(double & _r) const { long iloc; double dlargloc = 2 * range() ; if (fabs(_r) > 1.0E9) // iloc too large! { - _r = uniform(); - return; + _r = uniform(); + return; } if ( (_r > maximum()) ) { - iloc = (long) ( (_r-minimum()) / dlargloc ) ; - _r -= dlargloc * iloc ; - if ( _r > maximum() ) - _r = 2*maximum() - _r ; + iloc = (long) ( (_r-minimum()) / dlargloc ) ; + _r -= dlargloc * iloc ; + if ( _r > maximum() ) + _r = 2*maximum() - _r ; } - - if (_r < minimum()) + + if (_r < minimum()) { - iloc = (long) ( (maximum()-_r) / dlargloc ) ; - _r += dlargloc * iloc ; - if (_r < minimum()) - _r = 2*minimum() - _r ; + iloc = (long) ( (maximum()-_r) / dlargloc ) ; + _r += dlargloc * iloc ; + if (_r < minimum()) + _r = 2*minimum() - _r ; } - } + } // truncates to the bounds - virtual void truncate(double & _r) const + virtual void truncate(double & _r) const { if (_r < repMinimum) _r = repMinimum; @@ -341,7 +341,7 @@ public : } /** for memory managements - ugly */ - virtual eoIntBounds * dup() const + virtual eoIntBounds * dup() const { return new eoIntInterval(*this); } @@ -349,7 +349,7 @@ public : private : long int repMinimum; long int repMaximum; - long int repRange; // to minimize operations ??? + long int repRange; // to minimize operations ??? }; /** @@ -361,22 +361,22 @@ private : class eoIntBelowBound : public eoIntBounds { public : - virtual ~eoIntBelowBound(){} - /** + virtual ~eoIntBelowBound(){} + /** Simple bounds = minimum */ - eoIntBelowBound(long int _min=0) : + eoIntBelowBound(long int _min=0) : repMinimum(_min) {} - // accessors + // accessors virtual long int minimum() const { return repMinimum; } - virtual long int maximum() const + virtual long int maximum() const { throw std::logic_error("Trying to get maximum of eoIntBelowBound"); } - virtual long int range() const + virtual long int range() const { throw std::logic_error("Trying to get range of eoIntBelowBound"); } @@ -402,7 +402,7 @@ public : virtual bool isMaxBounded(void) const {return false;} // says if a given double is within the bounds - virtual bool isInBounds(double _r) const + virtual bool isInBounds(double _r) const { if (_r < repMinimum) return false; @@ -410,16 +410,16 @@ public : } // folds a value into bounds - virtual void foldsInBounds(double & _r) const + virtual void foldsInBounds(double & _r) const { // easy as a pie: symmetry w.r.t. minimum - if (_r < repMinimum) // nothing to do otherwise + if (_r < repMinimum) // nothing to do otherwise _r = 2*repMinimum - _r; return ; - } + } // truncates to the bounds - virtual void truncate(double & _r) const + virtual void truncate(double & _r) const { if (_r < repMinimum) _r = repMinimum; @@ -450,7 +450,7 @@ public : } /** for memory managements - ugly */ - virtual eoIntBounds * dup() const + virtual eoIntBounds * dup() const { return new eoIntBelowBound(*this); } @@ -469,22 +469,22 @@ class eoIntAboveBound : public eoIntBounds { public : virtual ~eoIntAboveBound(){} - - /** + + /** Simple bounds = minimum */ - eoIntAboveBound(long int _max=0) : + eoIntAboveBound(long int _max=0) : repMaximum(_max) {} - // accessors + // accessors virtual long int maximum() const { return repMaximum; } - virtual long int minimum() const + virtual long int minimum() const { throw std::logic_error("Trying to get minimum of eoIntAboveBound"); } - virtual long int range() const + virtual long int range() const { throw std::logic_error("Trying to get range of eoIntAboveBound"); } @@ -510,7 +510,7 @@ public : virtual bool isMaxBounded(void) const {return true;} // says if a given double is within the bounds - virtual bool isInBounds(double _r) const + virtual bool isInBounds(double _r) const { if (_r > repMaximum) return false; @@ -518,16 +518,16 @@ public : } // folds a value into bounds - virtual void foldsInBounds(double & _r) const + virtual void foldsInBounds(double & _r) const { // easy as a pie: symmetry w.r.t. maximum - if (_r > repMaximum) // nothing to do otherwise + if (_r > repMaximum) // nothing to do otherwise _r = 2*repMaximum - _r; return ; - } + } // truncates to the bounds - virtual void truncate(double & _r) const + virtual void truncate(double & _r) const { if (_r > repMaximum) _r = repMaximum; @@ -558,7 +558,7 @@ public : } /** for memory managements - ugly */ - virtual eoIntBounds * dup() const + virtual eoIntBounds * dup() const { return new eoIntAboveBound(*this); } @@ -598,13 +598,13 @@ public: if (maxBounded) maximum = bb.maximum(); if (minBounded && maxBounded) - repBound = new eoIntInterval(minimum, maximum); + repBound = new eoIntInterval(minimum, maximum); else if (!minBounded && !maxBounded) // no bound at all - repBound = new eoIntNoBounds; + repBound = new eoIntNoBounds; else if (!minBounded && maxBounded) - repBound = new eoIntAboveBound(maximum); + repBound = new eoIntAboveBound(maximum); else if (minBounded && !maxBounded) - repBound = new eoIntBelowBound(minimum); + repBound = new eoIntBelowBound(minimum); } eoGeneralIntBounds& operator=(const eoGeneralIntBounds& _b) @@ -624,13 +624,13 @@ public: delete repBound; // now reallocate if (minBounded && maxBounded) - repBound = new eoIntInterval(minimum, maximum); + repBound = new eoIntInterval(minimum, maximum); else if (!minBounded && !maxBounded) // no bound at all - repBound = new eoIntNoBounds; + repBound = new eoIntNoBounds; else if (!minBounded && maxBounded) - repBound = new eoIntAboveBound(maximum); + repBound = new eoIntAboveBound(maximum); else if (minBounded && !maxBounded) - repBound = new eoIntBelowBound(minimum); + repBound = new eoIntBelowBound(minimum); return (*this); } @@ -671,17 +671,17 @@ public: */ virtual void truncate(double & _x) const {return repBound->truncate(_x);} - /** get minimum value + /** get minimum value * std::exception if does not exist - */ + */ virtual long int minimum() const {return repBound->minimum();} /** get maximum value * std::exception if does not exist - */ + */ virtual long int maximum() const {return repBound->maximum();} /** get range * std::exception if unbounded - */ + */ virtual long int range() const {return repBound->range();} /** random generator of uniform doubles in bounds @@ -698,9 +698,9 @@ public: virtual eoIntBounds * dup() const {return repBound->dup();} /** for efficiency, it's better to use the embedded boud directly */ - const eoIntBounds & theBounds() const { return *repBound;} + const eoIntBounds & theBounds() const { return *repBound;} - /** don't forget the printOn method - + /** don't forget the printOn method - * again that of the embedded bound */ virtual void printOn(std::ostream& _os) const @@ -709,7 +709,7 @@ public: } /** no readFrom ??? Have to check that later */ - virtual void readFrom(std::istream& _is) + virtual void readFrom(std::istream& _is) { std::string s; _is >> s; diff --git a/eo/src/utils/eoLogger.cpp b/eo/src/utils/eoLogger.cpp index ff6f8407..b3002f46 100644 --- a/eo/src/utils/eoLogger.cpp +++ b/eo/src/utils/eoLogger.cpp @@ -1,7 +1,7 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- -/* - +/* + (c) Thales group, 2010 This library is free software; you can redistribute it and/or @@ -20,7 +20,7 @@ Contact: http://eodev.sourceforge.net -Authors: +Authors: Johann Dréo Caner Candan @@ -87,10 +87,10 @@ void eoLogger::printLevels() const std::cout << "Available verbose levels:" << std::endl; for (std::vector::const_iterator it = _sortedLevels.begin(), end = _sortedLevels.end(); - it != end; ++it) - { - std::cout << "\t" << *it << std::endl; - } + it != end; ++it) + { + std::cout << "\t" << *it << std::endl; + } ::exit(0); } @@ -116,15 +116,15 @@ eoLogger& operator<<(eoLogger& l, eo::setlevel v) eoLogger& operator<<(eoLogger& l, std::ostream& os) { if (l._standard_io_streams.find(&os) != l._standard_io_streams.end()) - { - l._fd = l._standard_io_streams[&os]; - } + { + l._fd = l._standard_io_streams[&os]; + } return l; } eoLogger::outbuf::outbuf(const int& fd, - const eo::Levels& contexlvl, - const eo::Levels& selectedlvl) + const eo::Levels& contexlvl, + const eo::Levels& selectedlvl) : _fd(fd), _contextLevel(contexlvl), _selectedLevel(selectedlvl) {} @@ -132,11 +132,11 @@ int eoLogger::outbuf::overflow(int_type c) { if (_selectedLevel >= _contextLevel) { - if (_fd >= 0 && c != EOF) - { - ssize_t num; - num = ::write(_fd, &c, 1); - } + if (_fd >= 0 && c != EOF) + { + ssize_t num; + num = ::write(_fd, &c, 1); + } } return c; } @@ -144,14 +144,14 @@ int eoLogger::outbuf::overflow(int_type c) namespace eo { file::file(const std::string f) - : _f(f) + : _f(f) {} setlevel::setlevel(const std::string v) - : _v(v), _lvl((Levels)-1) + : _v(v), _lvl((Levels)-1) {} setlevel::setlevel(const Levels lvl) - : _v(std::string("")), _lvl(lvl) + : _v(std::string("")), _lvl(lvl) {} } diff --git a/eo/src/utils/eoLogger.h b/eo/src/utils/eoLogger.h index c5ca7e3d..11b0cbee 100644 --- a/eo/src/utils/eoLogger.h +++ b/eo/src/utils/eoLogger.h @@ -1,6 +1,6 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- -/* +/* (c) Thales group, 2010 This library is free software; you can redistribute it and/or @@ -19,7 +19,7 @@ Contact: http://eodev.sourceforge.net -Authors: +Authors: Johann Dréo Caner Candan @@ -106,12 +106,12 @@ namespace eo * /!\ If you want to add a level dont forget to add it at the implementation of the class eoLogger in the ctor */ enum Levels {quiet = 0, - errors, - warnings, - progress, - logging, - debug, - xdebug}; + errors, + warnings, + progress, + logging, + debug, + xdebug}; /** * file @@ -119,8 +119,8 @@ namespace eo */ struct file { - file(const std::string f); - const std::string _f; + file(const std::string f); + const std::string _f; }; /** @@ -129,10 +129,10 @@ namespace eo */ struct setlevel { - setlevel(const std::string v); - setlevel(const Levels lvl); - const std::string _v; - const Levels _lvl; + setlevel(const std::string v); + setlevel(const Levels lvl); + const std::string _v; + const Levels _lvl; }; } @@ -142,7 +142,7 @@ namespace eo * Use of a global variable eo::log to easily use the logger like std::cout */ class eoLogger : public eoObject, - public std::ostream + public std::ostream { public: eoLogger(); @@ -159,7 +159,7 @@ public: * if( eo::log.getLevelSelected() >= eo::progress ) {...} */ eo::Levels getLevelSelected() const { return _selectedLevel; } - + /*! Returns the current level of the context * the one given when you output message with the logger */ @@ -176,15 +176,15 @@ private: class outbuf : public std::streambuf { public: - outbuf(const int& fd, - const eo::Levels& contexlvl, - const eo::Levels& selectedlvl); + outbuf(const int& fd, + const eo::Levels& contexlvl, + const eo::Levels& selectedlvl); protected: - virtual int overflow(int_type c); + virtual int overflow(int_type c); private: - const int& _fd; - const eo::Levels& _contextLevel; - const eo::Levels& _selectedLevel; + const int& _fd; + const eo::Levels& _contextLevel; + const eo::Levels& _selectedLevel; }; private: diff --git a/eo/src/utils/eoMOFitnessStat.h b/eo/src/utils/eoMOFitnessStat.h index 64102139..8e1b2d3f 100644 --- a/eo/src/utils/eoMOFitnessStat.h +++ b/eo/src/utils/eoMOFitnessStat.h @@ -85,7 +85,7 @@ public: } } private: - unsigned int objective; // The objective we're storing + unsigned int objective; // The objective we're storing }; #endif diff --git a/eo/src/utils/eoMonitor.h b/eo/src/utils/eoMonitor.h index e02900f2..1c92e9c0 100644 --- a/eo/src/utils/eoMonitor.h +++ b/eo/src/utils/eoMonitor.h @@ -1,7 +1,7 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- // (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -31,7 +31,7 @@ /** @defgroup Monitors Monitoring * - * Monitors take a set of value parameters (eoValueParam) objects and + * Monitors take a set of value parameters (eoValueParam) objects and * output them on a given stream, file, pipe, etc. * * They can be called from within an eoCheckPoint, to print different values diff --git a/eo/src/utils/eoOStreamMonitor.cpp b/eo/src/utils/eoOStreamMonitor.cpp index 3a29dd68..3365301e 100644 --- a/eo/src/utils/eoOStreamMonitor.cpp +++ b/eo/src/utils/eoOStreamMonitor.cpp @@ -1,7 +1,7 @@ #ifdef _MSC_VER // to avoid long name warnings #pragma warning(disable:4786) -#endif +#endif #include #include diff --git a/eo/src/utils/eoOStreamMonitor.h b/eo/src/utils/eoOStreamMonitor.h index 7436f6ef..b09a11b5 100644 --- a/eo/src/utils/eoOStreamMonitor.h +++ b/eo/src/utils/eoOStreamMonitor.h @@ -1,4 +1,3 @@ - /* (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 @@ -22,7 +21,7 @@ Authors: todos@geneura.ugr.es Marc.Schoenauer@polytechnique.fr mkeijzer@dhi.dk - Johann Dréo + Johann Dréo */ #ifndef _eoOStreamMonitor_h_ @@ -45,15 +44,15 @@ Authors: class eoOStreamMonitor : public eoMonitor { public : - eoOStreamMonitor( std::ostream & _out, bool _verbose=true, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : - out(_out), delim(_delim), width(_width), fill(_fill), firsttime(true) + eoOStreamMonitor( std::ostream & _out, bool _verbose=true, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : + out(_out), delim(_delim), width(_width), fill(_fill), firsttime(true) { - (void)_verbose; + (void)_verbose; eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoOStreamMonitor constructor is deprecated and will be removed in the next release" << std::endl; } - eoOStreamMonitor( std::ostream & _out, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : - out(_out), delim(_delim), width(_width), fill(_fill), firsttime(true) + eoOStreamMonitor( std::ostream & _out, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : + out(_out), delim(_delim), width(_width), fill(_fill), firsttime(true) {} eoMonitor& operator()(void); @@ -69,4 +68,3 @@ private : }; #endif // _eoOStreamMonitor_h_ - diff --git a/eo/src/utils/eoParallel.cpp b/eo/src/utils/eoParallel.cpp index e0ce63aa..d9d09c38 100644 --- a/eo/src/utils/eoParallel.cpp +++ b/eo/src/utils/eoParallel.cpp @@ -45,11 +45,11 @@ eoParallel::~eoParallel() { #ifdef _OPENMP if ( doMeasure() ) - { - double _t_end = omp_get_wtime(); - eoLogger log; - log << eo::file("measure_" + prefix()) << _t_end - _t_start << std::endl; - } + { + double _t_end = omp_get_wtime(); + eoLogger log; + log << eo::file("measure_" + prefix()) << _t_end - _t_start << std::endl; + } #endif // !_OPENMP } @@ -63,20 +63,20 @@ std::string eoParallel::prefix() const std::string value( _prefix.value() ); if ( _isEnabled.value() ) - { - if ( _isDynamic.value() ) - { - value += "_dynamic.out"; - } - else - { - value += "_parallel.out"; - } - } + { + if ( _isDynamic.value() ) + { + value += "_dynamic.out"; + } + else + { + value += "_parallel.out"; + } + } else - { - value += "_sequential.out"; - } + { + value += "_sequential.out"; + } return value; } @@ -98,17 +98,17 @@ void make_parallel(eoParser& parser) #ifdef _OPENMP if ( eo::parallel.isEnabled() ) - { - if ( eo::parallel.nthreads() > 0 ) - { - omp_set_num_threads( eo::parallel.nthreads() ); - } - } + { + if ( eo::parallel.nthreads() > 0 ) + { + omp_set_num_threads( eo::parallel.nthreads() ); + } + } if ( eo::parallel.doMeasure() ) - { - eo::parallel._t_start = omp_get_wtime(); - } + { + eo::parallel._t_start = omp_get_wtime(); + } #endif // !_OPENMP } diff --git a/eo/src/utils/eoParam.h b/eo/src/utils/eoParam.h index 868507cf..948092c9 100644 --- a/eo/src/utils/eoParam.h +++ b/eo/src/utils/eoParam.h @@ -135,8 +135,8 @@ private: /** eoValueParam: templatized derivation of eoParam. Can be used to contain - any scalar value type. It makes use of std::strstream to get and set values. - + any scalar value type. It makes use of std::strstream to get and set values. + @todo This should be changed to std::stringstream when that class is available in g++. Note also that there is a template specialization for std::pair and @@ -186,7 +186,7 @@ public : /** Change the parameter value */ - void value( ValueType val ) + void value( ValueType val ) { // convert to string std::ostringstream os; @@ -431,7 +431,7 @@ public: // Here, we do have args _os << "("; - if (narg == 1) // 1 arg only + if (narg == 1) // 1 arg only { _os << second[0] << ")" ; return _os; @@ -453,9 +453,9 @@ public: void readFrom(std::string & _value) { - second.resize(0); // just in case + second.resize(0); // just in case size_t pos = _value.find('('); - if (pos >= _value.size()) // no arguments + if (pos >= _value.size()) // no arguments { first = _value; return; @@ -484,4 +484,3 @@ std::istream & operator>>(std::istream & _is, eoParamParamType & _rate); /** @} */ #endif - diff --git a/eo/src/utils/eoParser.cpp b/eo/src/utils/eoParser.cpp index 23970023..7150882a 100644 --- a/eo/src/utils/eoParser.cpp +++ b/eo/src/utils/eoParser.cpp @@ -74,19 +74,19 @@ eoParser::eoParser ( unsigned _argc, char **_argv , string _programDescription, unsigned i; for (i = 1; i < _argc; ++i) { - if(_argv[i][0] == '@') + if(_argv[i][0] == '@') { // read response file - char *pts = _argv[i]+1; // yes a char*, sorry :-) - ifstream ifs (pts); - ifs.peek(); // check if it exists - if (!ifs) + char *pts = _argv[i]+1; // yes a char*, sorry :-) + ifstream ifs (pts); + ifs.peek(); // check if it exists + if (!ifs) { - string msg = string("Could not open response file: ") + pts; - throw runtime_error(msg); + string msg = string("Could not open response file: ") + pts; + throw runtime_error(msg); } - // read - will be overwritten by command-line - readFrom(ifs); - break; // stop reading command line args for '@' + // read - will be overwritten by command-line + readFrom(ifs); + break; // stop reading command line args for '@' } } // now read arguments on command-line @@ -188,59 +188,59 @@ void eoParser::readFrom(istream& is) processing = (str.find(string("Parser"))= 3) value = string(str.begin() + 3, str.end()); - } + } else - { + { value = string(str.begin() + 2, str.end()); - } - } + } + } shortNameMap[str[1]] = value; - } - } - } + } + } + } } updateParameters(); @@ -268,8 +268,8 @@ void eoParser::printOn(ostream& os) const eoParam* param = p->second; - if (!isItThere(*param)) // comment out the ones not set by the user - os << "# "; + if (!isItThere(*param)) // comment out the ones not set by the user + os << "# "; string str = "--" + param->longName() + "=" + param->getValue(); @@ -329,12 +329,12 @@ void eoParser::printHelp(ostream& os) } if (p->second->shortName()) - os << "-" << p->second->shortName() << ", "; + os << "-" << p->second->shortName() << ", "; os << "--" <second->longName() <<":\t" - << p->second->description() ; + << p->second->description() ; - os << "\n" << setw(20) << ( (p->second->required())?"Required":"Optional" ); + os << "\n" << setw(20) << ( (p->second->required())?"Required":"Optional" ); os <<". By default: "<second->defValue() << '\n'; } // for p @@ -377,7 +377,7 @@ bool eoParser::userNeedsHelp(void) // search for unknown short names for (ShortNameMapType::const_iterator sIt = shortNameMap.begin(); sIt != shortNameMap.end(); ++sIt) - { + { char entry = sIt->first; MultiMapType::const_iterator it; @@ -403,7 +403,7 @@ bool eoParser::userNeedsHelp(void) string msg = "Use -h or --help to get help about available parameters"; messages.push_back( msg ); } - + } // if stopOnUnknownParam return needHelp.value() || !messages.empty(); @@ -421,4 +421,3 @@ istream & operator>>(istream & _is, eoParamParamType & _rate) _rate.readFrom(_is); return _is; } - diff --git a/eo/src/utils/eoParser.h b/eo/src/utils/eoParser.h index a96ec1be..0088ff4f 100644 --- a/eo/src/utils/eoParser.h +++ b/eo/src/utils/eoParser.h @@ -119,7 +119,7 @@ public: * @param _shortHand Single charachter shorthand for specifying the configuration file */ eoParser ( unsigned _argc, char **_argv , std::string _programDescription = "", - std::string _lFileParamName = "param-file", char _shortHand = 'p'); + std::string _lFileParamName = "param-file", char _shortHand = 'p'); /** Processes the parameter and puts it in the appropriate section for readability diff --git a/eo/src/utils/eoParserLogger.cpp b/eo/src/utils/eoParserLogger.cpp index 21b67f6c..df70589a 100644 --- a/eo/src/utils/eoParserLogger.cpp +++ b/eo/src/utils/eoParserLogger.cpp @@ -25,10 +25,10 @@ Caner Candan #include "eoParserLogger.h" eoParserLogger::eoParserLogger(unsigned _argc, char** _argv, - std::string _programDescription /*= ""*/ - , - std::string _lFileParamName /*= "param-file"*/, - char _shortHand /*= 'p'*/) + std::string _programDescription /*= ""*/ + , + std::string _lFileParamName /*= "param-file"*/, + char _shortHand /*= 'p'*/) : eoParser(_argc, _argv, _programDescription, _lFileParamName, _shortHand), _verbose("quiet", "verbose", "Set the verbose level", 'v'), _printVerboseLevels(false, "print-verbose-levels", "Print verbose levels", 'l'), @@ -50,9 +50,9 @@ eoParserLogger::eoParserLogger(unsigned _argc, char** _argv, //------------------------------------------------------------------ if ( ! _output.value().empty() ) - { - eo::log << eo::file( _output.value() ); - } + { + eo::log << eo::file( _output.value() ); + } //------------------------------------------------------------------ @@ -62,9 +62,9 @@ eoParserLogger::eoParserLogger(unsigned _argc, char** _argv, //------------------------------------------------------------------ if ( _printVerboseLevels.value() ) - { - eo::log.printLevels(); - } + { + eo::log.printLevels(); + } //------------------------------------------------------------------ diff --git a/eo/src/utils/eoParserLogger.h b/eo/src/utils/eoParserLogger.h index 20f67652..48cb53ec 100644 --- a/eo/src/utils/eoParserLogger.h +++ b/eo/src/utils/eoParserLogger.h @@ -17,8 +17,8 @@ Contact: http://eodev.sourceforge.net Authors: - Johann Dréo - Caner Candan + Johann Dréo + Caner Candan */ #ifndef EO_PARSER_LOGGER_H @@ -37,9 +37,9 @@ class eoParserLogger : public eoParser { public: eoParserLogger(unsigned _argc, char** _argv, - std::string _programDescription = "", - std::string _lFileParamName = "param-file", - char _shortHand = 'p'); + std::string _programDescription = "", + std::string _lFileParamName = "param-file", + char _shortHand = 'p'); ~eoParserLogger(); private: diff --git a/eo/src/utils/eoPopStat.h b/eo/src/utils/eoPopStat.h index 86c5dc04..f3f091a6 100644 --- a/eo/src/utils/eoPopStat.h +++ b/eo/src/utils/eoPopStat.h @@ -59,9 +59,9 @@ public: /** default Ctor, void std::string by default, as it appears on the description line once at beginning of evolution. and is meaningless there. _howMany defaults to 0, that is, the whole - population*/ + population*/ eoPopStat(unsigned _howMany = 0, std::string _desc ="") - : eoStat("", _desc), combien( _howMany) {} + : eoStat("", _desc), combien( _howMany) {} /** Fills the value() of the eoParam with the dump of the population. Adds a \n before so it does not get mixed up with the rest of the stats @@ -119,15 +119,15 @@ public: */ void operator()(const std::vector& _pop) { - value() = ""; // empty + value() = ""; // empty unsigned howMany=combien?combien:_pop.size(); for (unsigned i = 0; i < howMany; ++i) { - std::ostringstream os; - os << *_pop[i] << std::endl; + std::ostringstream os; + os << *_pop[i] << std::endl; - // paranoid: - value() += os.str(); + // paranoid: + value() += os.str(); } } private: diff --git a/eo/src/utils/eoRNG.cpp b/eo/src/utils/eoRNG.cpp index 79a53d30..b538499f 100644 --- a/eo/src/utils/eoRNG.cpp +++ b/eo/src/utils/eoRNG.cpp @@ -16,4 +16,3 @@ namespace eo // global random number generator object eoRng rng(static_cast(time(0))); } - diff --git a/eo/src/utils/eoRNG.h b/eo/src/utils/eoRNG.h index 3cad9fcc..9885eff5 100644 --- a/eo/src/utils/eoRNG.h +++ b/eo/src/utils/eoRNG.h @@ -25,7 +25,7 @@ Old contact information: todos@geneura.ugr.es, http://geneura.ugr.es #ifndef EO_RANDOM_NUMBER_GENERATOR #define EO_RANDOM_NUMBER_GENERATOR -/** @addtogroup Random +/** @addtogroup Random * @{ * */ diff --git a/eo/src/utils/eoRealBounds.cpp b/eo/src/utils/eoRealBounds.cpp index 1667f644..89dcb358 100644 --- a/eo/src/utils/eoRealBounds.cpp +++ b/eo/src/utils/eoRealBounds.cpp @@ -78,7 +78,7 @@ void eoRealVectorBounds::readFrom(std::string _value) if (ownedBounds.size()>0) for (unsigned i = 0; i < ownedBounds.size(); ++i) { - delete ownedBounds[i]; + delete ownedBounds[i]; } ownedBounds.resize(0); factor.resize(0); @@ -89,29 +89,29 @@ void eoRealVectorBounds::readFrom(std::string _value) while (_value.size()>0) { if (!remove_leading(_value, delim)) // only delimiters were left - break; + break; // look for opening char size_t posDeb = _value.find_first_of("[("); if (posDeb >= _value.size()) // nothing left to read (though probably a syntax error there) - { - break; - } + { + break; + } // ending char std::string closeChar = (_value[posDeb] == '(' ? std::string(")") : std::string("]") ); size_t posFin = _value.find_first_of(std::string(closeChar)); if (posFin >= _value.size()) - throw std::runtime_error("Syntax error when reading bounds"); + throw std::runtime_error("Syntax error when reading bounds"); // y a-t-il un nbre devant unsigned count = 1; if (posDeb > 0) // something before opening - { - std::string sCount = _value.substr(0, posDeb); - count = read_int(sCount); - if (count <= 0) - throw std::runtime_error("Syntax error when reading bounds"); - } + { + std::string sCount = _value.substr(0, posDeb); + count = read_int(sCount); + if (count <= 0) + throw std::runtime_error("Syntax error when reading bounds"); + } // the bounds std::string sBounds = _value.substr(posDeb+1, posFin-posDeb-1); @@ -121,7 +121,7 @@ void eoRealVectorBounds::readFrom(std::string _value) remove_leading(sBounds, delim); size_t posDelim = sBounds.find_first_of(delim); if (posDelim >= sBounds.size()) - throw std::runtime_error("Syntax error when reading bounds"); + throw std::runtime_error("Syntax error when reading bounds"); bool minBounded=false, maxBounded=false; double minBound=0, maxBound=0; @@ -129,38 +129,38 @@ void eoRealVectorBounds::readFrom(std::string _value) // min bound std::string sMinBounds = sBounds.substr(0,posDelim); if (sMinBounds != std::string("-inf")) - { - minBounded = true; - minBound = read_double(sMinBounds); - } + { + minBounded = true; + minBound = read_double(sMinBounds); + } // max bound size_t posEndDelim = sBounds.find_first_not_of(delim,posDelim); std::string sMaxBounds = sBounds.substr(posEndDelim); if (sMaxBounds != std::string("+inf")) - { - maxBounded = true; - maxBound = read_double(sMaxBounds); - } + { + maxBounded = true; + maxBound = read_double(sMaxBounds); + } // now create the eoRealBounds objects eoRealBounds *ptBounds; if (minBounded && maxBounded) - ptBounds = new eoRealInterval(minBound, maxBound); + ptBounds = new eoRealInterval(minBound, maxBound); else if (!minBounded && !maxBounded) // no bound at all - ptBounds = new eoRealNoBounds; + ptBounds = new eoRealNoBounds; else if (!minBounded && maxBounded) - ptBounds = new eoRealAboveBound(maxBound); + ptBounds = new eoRealAboveBound(maxBound); else if (minBounded && !maxBounded) - ptBounds = new eoRealBelowBound(minBound); + ptBounds = new eoRealBelowBound(minBound); // store it for memory management ownedBounds.push_back(ptBounds); // push the count factor.push_back(count); // and add count of it to the actual bounds for (unsigned i=0; i 1 already!) factor[factor.size()-1] += missing; } @@ -221,12 +221,12 @@ eoRealBounds* eoGeneralRealBounds::getBoundsFromString(std::string _value) std::string sMinBounds = sBounds.substr(0,posDelim); if ( (sMinBounds != std::string("-inf")) && - (sMinBounds != std::string("-infinity")) - ) - { - minBounded = true; - minBound = read_double(sMinBounds); - } + (sMinBounds != std::string("-infinity")) + ) + { + minBounded = true; + minBound = read_double(sMinBounds); + } // max bound size_t posEndDelim = sBounds.find_first_not_of(delim,posDelim); @@ -234,26 +234,26 @@ eoRealBounds* eoGeneralRealBounds::getBoundsFromString(std::string _value) std::string sMaxBounds = sBounds.substr(posEndDelim); if ( (sMaxBounds != std::string("+inf")) && - (sMaxBounds != std::string("+infinity")) - ) - { - maxBounded = true; - maxBound = read_double(sMaxBounds); - } + (sMaxBounds != std::string("+infinity")) + ) + { + maxBounded = true; + maxBound = read_double(sMaxBounds); + } // now create the embedded eoRealBounds object eoRealBounds * locBound; if (minBounded && maxBounded) - { - if (maxBound <= minBound) - throw std::runtime_error("Syntax error in eoGeneralRealBounds Ctor"); - locBound = new eoRealInterval(minBound, maxBound); - } + { + if (maxBound <= minBound) + throw std::runtime_error("Syntax error in eoGeneralRealBounds Ctor"); + locBound = new eoRealInterval(minBound, maxBound); + } else if (!minBounded && !maxBounded) // no bound at all - locBound = new eoRealNoBounds; + locBound = new eoRealNoBounds; else if (!minBounded && maxBounded) - locBound = new eoRealAboveBound(maxBound); + locBound = new eoRealAboveBound(maxBound); else if (minBounded && !maxBounded) - locBound = new eoRealBelowBound(minBound); + locBound = new eoRealBelowBound(minBound); return locBound; } diff --git a/eo/src/utils/eoRealBounds.h b/eo/src/utils/eoRealBounds.h index f79aac04..47c06100 100644 --- a/eo/src/utils/eoRealBounds.h +++ b/eo/src/utils/eoRealBounds.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoRealBounds.h // (c) Marc Schoenauer 2001, Maarten Keijzer 2000, GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,7 +27,7 @@ #ifndef _eoRealBounds_h #define _eoRealBounds_h -#include // std::exceptions! +#include // std::exceptions! #include /** @@ -55,24 +55,24 @@ Scalar type: Basic class is eoRealBounds, a pure virtual. The following pure virtual methods are to be used in mutations: -- void foldsInBounds(double &) that folds any value that falls out of +- void foldsInBounds(double &) that folds any value that falls out of the bounds back into the bounds, by bouncing on the limit (if any) -- bool isInBounds(double) that simply says whether or not the argument +- bool isInBounds(double) that simply says whether or not the argument is in the bounds - void truncate(double &) that set the argument to the bound value it it exceeds it -So mutation can choose -- iterate trying until they fall in bounds, +So mutation can choose +- iterate trying until they fall in bounds, - only try once and "restd::pair" by using the foldsInBounds method - only try once and restd::pair using the truncate method (will create a huge bias toward the bound if the soluiton is not far from the bounds) -There is also a uniform() method that generates a uniform value +There is also a uniform() method that generates a uniform value (if possible, i.e. if bounded) in the interval. -Derived class are -eoRealInterval that holds a minimum and maximum value, +Derived class are +eoRealInterval that holds a minimum and maximum value, eoRealNoBounds the "unbounded bounds" (-infinity, +infinity) eoRealBelowBound the half-bounded interval [min, +infinity) eoRealAboveBound the half-bounded interval (-infinity, max] @@ -83,7 +83,7 @@ is the unbounded bound @ingroup Bounds */ class eoRealBounds : public eoPersistent -{ +{ public: virtual ~eoRealBounds(){} @@ -116,17 +116,17 @@ public: */ virtual void truncate(double &) const = 0; - /** get minimum value + /** get minimum value * std::exception if does not exist - */ + */ virtual double minimum() const = 0 ; /** get maximum value * std::exception if does not exist - */ + */ virtual double maximum() const = 0 ; /** get range * std::exception if unbounded - */ + */ virtual double range() const = 0; /** random generator of uniform numbers in bounds @@ -159,16 +159,16 @@ public: { throw std::logic_error("Trying to get minimum of unbounded eoRealBounds"); } - virtual double maximum() const + virtual double maximum() const { throw std::logic_error("Trying to get maximum of unbounded eoRealBounds"); } - virtual double range() const + virtual double range() const { throw std::logic_error("Trying to get range of unbounded eoRealBounds"); } - virtual double uniform(eoRng & _rng = eo::rng) const + virtual double uniform(eoRng & _rng = eo::rng) const { (void)_rng; @@ -199,7 +199,7 @@ public: } /** for memory managements - ugly */ - virtual eoRealBounds * dup() const + virtual eoRealBounds * dup() const { return new eoRealNoBounds(*this); } @@ -220,18 +220,18 @@ class eoRealInterval : public eoRealBounds { public : virtual ~eoRealInterval(){} - - /** + + /** Simple bounds = minimum and maximum (allowed) */ - eoRealInterval(double _min=0, double _max=1) : - repMinimum(_min), repMaximum(_max), repRange(_max-_min) + eoRealInterval(double _min=0, double _max=1) : + repMinimum(_min), repMaximum(_max), repRange(_max-_min) { if (repRange<=0) throw std::logic_error("Void range in eoRealBounds"); } - // accessors + // accessors virtual double minimum() const { return repMinimum; } virtual double maximum() const { return repMaximum; } virtual double range() const { return repRange; } @@ -242,13 +242,13 @@ public : virtual bool isMinBounded(void) const {return true;} virtual bool isMaxBounded(void) const {return true;} - virtual double uniform(eoRng & _rng = eo::rng) const + virtual double uniform(eoRng & _rng = eo::rng) const { return repMinimum + _rng.uniform(repRange); - } + } // says if a given double is within the bounds - virtual bool isInBounds(double _r) const + virtual bool isInBounds(double _r) const { if (_r < repMinimum) return false; @@ -258,36 +258,36 @@ public : } // folds a value into bounds - virtual void foldsInBounds(double & _r) const + virtual void foldsInBounds(double & _r) const { long iloc; double dlargloc = 2 * range() ; if (fabs(_r) > 1.0E9) // iloc too large! { - _r = uniform(); - return; + _r = uniform(); + return; } if ( (_r > maximum()) ) { - iloc = (long) ( (_r-minimum()) / dlargloc ) ; - _r -= dlargloc * iloc ; - if ( _r > maximum() ) - _r = 2*maximum() - _r ; + iloc = (long) ( (_r-minimum()) / dlargloc ) ; + _r -= dlargloc * iloc ; + if ( _r > maximum() ) + _r = 2*maximum() - _r ; } - - if (_r < minimum()) + + if (_r < minimum()) { - iloc = (long) ( (maximum()-_r) / dlargloc ) ; - _r += dlargloc * iloc ; - if (_r < minimum()) - _r = 2*minimum() - _r ; + iloc = (long) ( (maximum()-_r) / dlargloc ) ; + _r += dlargloc * iloc ; + if (_r < minimum()) + _r = 2*minimum() - _r ; } - } + } // truncates to the bounds - virtual void truncate(double & _r) const + virtual void truncate(double & _r) const { if (_r < repMinimum) _r = repMinimum; @@ -320,7 +320,7 @@ public : } /** for memory managements - ugly */ - virtual eoRealBounds * dup() const + virtual eoRealBounds * dup() const { return new eoRealInterval(*this); } @@ -328,7 +328,7 @@ public : private : double repMinimum; double repMaximum; - double repRange; // to minimize operations ??? + double repRange; // to minimize operations ??? }; /** @@ -339,22 +339,22 @@ private : class eoRealBelowBound : public eoRealBounds { public : - virtual ~eoRealBelowBound(){} - /** + virtual ~eoRealBelowBound(){} + /** Simple bounds = minimum */ - eoRealBelowBound(double _min=0) : + eoRealBelowBound(double _min=0) : repMinimum(_min) {} - // accessors + // accessors virtual double minimum() const { return repMinimum; } - virtual double maximum() const + virtual double maximum() const { throw std::logic_error("Trying to get maximum of eoRealBelowBound"); } - virtual double range() const + virtual double range() const { throw std::logic_error("Trying to get range of eoRealBelowBound"); } @@ -374,7 +374,7 @@ public : virtual bool isMaxBounded(void) const {return false;} // says if a given double is within the bounds - virtual bool isInBounds(double _r) const + virtual bool isInBounds(double _r) const { if (_r < repMinimum) return false; @@ -382,16 +382,16 @@ public : } // folds a value into bounds - virtual void foldsInBounds(double & _r) const + virtual void foldsInBounds(double & _r) const { // easy as a pie: symmetry w.r.t. minimum - if (_r < repMinimum) // nothing to do otherwise + if (_r < repMinimum) // nothing to do otherwise _r = 2*repMinimum - _r; return ; - } + } // truncates to the bounds - virtual void truncate(double & _r) const + virtual void truncate(double & _r) const { if (_r < repMinimum) _r = repMinimum; @@ -405,7 +405,7 @@ public : * but reading should not be done here, because of bound problems * see eoRealVectorBounds */ - virtual void readFrom(std::istream& _is) + virtual void readFrom(std::istream& _is) { (void)_is; @@ -422,7 +422,7 @@ public : } /** for memory managements - ugly */ - virtual eoRealBounds * dup() const + virtual eoRealBounds * dup() const { return new eoRealBelowBound(*this); } @@ -438,22 +438,22 @@ class eoRealAboveBound : public eoRealBounds { public : virtual ~eoRealAboveBound(){} - - /** + + /** Simple bounds = minimum */ - eoRealAboveBound(double _max=0) : + eoRealAboveBound(double _max=0) : repMaximum(_max) {} - // accessors + // accessors virtual double maximum() const { return repMaximum; } - virtual double minimum() const + virtual double minimum() const { throw std::logic_error("Trying to get minimum of eoRealAboveBound"); } - virtual double range() const + virtual double range() const { throw std::logic_error("Trying to get range of eoRealAboveBound"); } @@ -473,7 +473,7 @@ public : virtual bool isMaxBounded(void) const {return true;} // says if a given double is within the bounds - virtual bool isInBounds(double _r) const + virtual bool isInBounds(double _r) const { if (_r > repMaximum) return false; @@ -481,16 +481,16 @@ public : } // folds a value into bounds - virtual void foldsInBounds(double & _r) const + virtual void foldsInBounds(double & _r) const { // easy as a pie: symmetry w.r.t. maximum - if (_r > repMaximum) // nothing to do otherwise + if (_r > repMaximum) // nothing to do otherwise _r = 2*repMaximum - _r; return ; - } + } // truncates to the bounds - virtual void truncate(double & _r) const + virtual void truncate(double & _r) const { if (_r > repMaximum) _r = repMaximum; @@ -521,7 +521,7 @@ public : } /** for memory managements - ugly */ - virtual eoRealBounds * dup() const + virtual eoRealBounds * dup() const { return new eoRealAboveBound(*this); } @@ -560,13 +560,13 @@ public: if (maxBounded) maximum = bb.maximum(); if (minBounded && maxBounded) - repBound = new eoRealInterval(minimum, maximum); + repBound = new eoRealInterval(minimum, maximum); else if (!minBounded && !maxBounded) // no bound at all - repBound = new eoRealNoBounds; + repBound = new eoRealNoBounds; else if (!minBounded && maxBounded) - repBound = new eoRealAboveBound(maximum); + repBound = new eoRealAboveBound(maximum); else if (minBounded && !maxBounded) - repBound = new eoRealBelowBound(minimum); + repBound = new eoRealBelowBound(minimum); } eoGeneralRealBounds& operator=(const eoGeneralRealBounds& _b) @@ -586,13 +586,13 @@ public: delete repBound; // now reallocate if (minBounded && maxBounded) - repBound = new eoRealInterval(minimum, maximum); + repBound = new eoRealInterval(minimum, maximum); else if (!minBounded && !maxBounded) // no bound at all - repBound = new eoRealNoBounds; + repBound = new eoRealNoBounds; else if (!minBounded && maxBounded) - repBound = new eoRealAboveBound(maximum); + repBound = new eoRealAboveBound(maximum); else if (minBounded && !maxBounded) - repBound = new eoRealBelowBound(minimum); + repBound = new eoRealBelowBound(minimum); return (*this); } @@ -633,17 +633,17 @@ public: */ virtual void truncate(double & _x) const {return repBound->truncate(_x);} - /** get minimum value + /** get minimum value * std::exception if does not exist - */ + */ virtual double minimum() const {return repBound->minimum();} /** get maximum value * std::exception if does not exist - */ + */ virtual double maximum() const {return repBound->maximum();} /** get range * std::exception if unbounded - */ + */ virtual double range() const {return repBound->range();} /** random generator of uniform numbers in bounds @@ -655,9 +655,9 @@ public: virtual eoRealBounds * dup() const {return repBound->dup();} /** for efficiency, it's better to use the embedded boud directly */ - const eoRealBounds & theBounds() const { return *repBound;} + const eoRealBounds & theBounds() const { return *repBound;} - /** don't forget the printOn method - + /** don't forget the printOn method - * again that of the embedded bound */ virtual void printOn(std::ostream& _os) const @@ -666,7 +666,7 @@ public: } /** no readFrom ??? Have to check that later */ - virtual void readFrom(std::istream& _is) + virtual void readFrom(std::istream& _is) { std::string s; _is >> s; diff --git a/eo/src/utils/eoRealVectorBounds.h b/eo/src/utils/eoRealVectorBounds.h index 5e3a460f..56feff34 100644 --- a/eo/src/utils/eoRealVectorBounds.h +++ b/eo/src/utils/eoRealVectorBounds.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoRealVectorBounds.h // (c) Marc Schoenauer 2001, Maarten Keijzer 2000, GeNeura Team, 1998 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -27,93 +27,93 @@ #ifndef _eoRealVectorBounds_h #define _eoRealVectorBounds_h -#include // std::exceptions! +#include // std::exceptions! #include #include /** Vector type for bounds (see eoRealBounds.h for scalar types) ------------ -Class eoRealVectorBounds implements the std::vectorized version: +Class eoRealVectorBounds implements the std::vectorized version: it is basically a std::vector of eoRealBounds * and forwards all request to the elements of the std::vector. -This file also contains the global variables and eoDummyVectorNoBounds +This file also contains the global variables and eoDummyVectorNoBounds that are used as defaults in ctors (i.e. when no bounds are given, it is assumed unbounded values) -THe 2 main classes defined here are +THe 2 main classes defined here are eoRealBaseVectorBounds, base class that handles all useful functions eoRealVectorBounds which derives from the preceding *and* eoPersistent - and also has a mechanism for memory handling of the pointers + and also has a mechanism for memory handling of the pointers it has to allocate @ingroup Bounds */ class eoRealBaseVectorBounds : public std::vector -{ +{ public: // virtual desctructor (to avoid warning?) virtual ~eoRealBaseVectorBounds(){} - /** Default Ctor. + /** Default Ctor. */ eoRealBaseVectorBounds() : std::vector(0) {} /** Ctor: same bounds for everybody, given as an eoRealBounds */ - eoRealBaseVectorBounds(unsigned _dim, eoRealBounds & _bounds) : + eoRealBaseVectorBounds(unsigned _dim, eoRealBounds & _bounds) : std::vector(_dim, &_bounds) {} - + /** Ctor, particular case of dim-2 */ - eoRealBaseVectorBounds(eoRealBounds & _xbounds, eoRealBounds & _ybounds) : + eoRealBaseVectorBounds(eoRealBounds & _xbounds, eoRealBounds & _ybounds) : std::vector(0) { - push_back( &_xbounds); - push_back( &_ybounds); + push_back( &_xbounds); + push_back( &_ybounds); } - + /** test: is i_th component bounded */ - virtual bool isBounded(unsigned _i) - { + virtual bool isBounded(unsigned _i) + { return (*this)[_i]->isBounded(); } - + /** test: bounded iff all are bounded */ - virtual bool isBounded(void) + virtual bool isBounded(void) { for (unsigned i=0; iisBounded()) - return false; + return false; return true; } /** Self-test: true iff i_th component has no bounds at all */ - virtual bool hasNoBoundAtAll(unsigned _i) - { + virtual bool hasNoBoundAtAll(unsigned _i) + { return (*this)[_i]->hasNoBoundAtAll(); } - + /** Self-test: true iff all components have no bound at all */ - virtual bool hasNoBoundAtAll(void) + virtual bool hasNoBoundAtAll(void) { for (unsigned i=0; ihasNoBoundAtAll()) - return false; + return false; return true; } - virtual bool isMinBounded(unsigned _i) + virtual bool isMinBounded(unsigned _i) { return (*this)[_i]->isMinBounded();} ; - virtual bool isMaxBounded(unsigned _i) + virtual bool isMaxBounded(unsigned _i) { return (*this)[_i]->isMaxBounded();} ; /** Folds a real value back into the bounds - i_th component @@ -130,7 +130,7 @@ public: for (unsigned i=0; ifoldsInBounds(_v[i]); - } + } } /** Truncates a real value to the bounds - i_th component @@ -147,7 +147,7 @@ public: for (unsigned i=0; itruncate(_v[i]); - } + } } /** test: is i_th component within the bounds? @@ -161,7 +161,7 @@ public: { for (unsigned i=0; iprintOn(_os); - _os << ";"; + operator[](i)->printOn(_os); + _os << ";"; } } }; @@ -234,19 +234,19 @@ public: /** Ctor: same bounds for everybody, given as an eoRealBounds */ - eoRealVectorBounds(unsigned _dim, eoRealBounds & _bounds) : + eoRealVectorBounds(unsigned _dim, eoRealBounds & _bounds) : eoRealBaseVectorBounds(_dim, _bounds), factor(1,_dim), ownedBounds(0) {} - + /** Ctor, particular case of dim-2 */ - eoRealVectorBounds(eoRealBounds & _xbounds, eoRealBounds & _ybounds) : + eoRealVectorBounds(eoRealBounds & _xbounds, eoRealBounds & _ybounds) : eoRealBaseVectorBounds(_xbounds, _ybounds), factor(2,1), ownedBounds(0) {} - + /** Simple bounds = minimum and maximum (allowed) */ - eoRealVectorBounds(unsigned _dim, double _min, double _max) : + eoRealVectorBounds(unsigned _dim, double _min, double _max) : eoRealBaseVectorBounds(), factor(1, _dim), ownedBounds(0) { if (_max-_min<=0) @@ -261,7 +261,7 @@ public: /** Ctor: different bounds for different variables, std::vectors of double */ - eoRealVectorBounds(std::vector _min, std::vector _max) : + eoRealVectorBounds(std::vector _min, std::vector _max) : factor(_min.size(), 1), ownedBounds(0) { if (_max.size() != _min.size()) @@ -270,9 +270,9 @@ public: eoRealBounds *ptBounds; for (unsigned i=0; i<_min.size(); i++) { - ptBounds = new eoRealInterval(_min[i], _max[i]); - ownedBounds.push_back(ptBounds); - push_back(ptBounds); + ptBounds = new eoRealInterval(_min[i], _max[i]); + ownedBounds.push_back(ptBounds); + push_back(ptBounds); } } @@ -320,26 +320,26 @@ public: unsigned int index=factor[0]; if (factor.size()>1) for (unsigned i=1; i 1) - _os << factor[i]; - operator[](index)->printOn(_os); - index += factor[i]; - } + { + _os << ";"; + if (factor[i] > 1) + _os << factor[i]; + operator[](index)->printOn(_os); + index += factor[i]; + } } /** Eventually increases the size by duplicating last bound */ void adjust_size(unsigned _dim); - /** need to rewrite copy ctor and assignement operator + /** need to rewrite copy ctor and assignement operator * because of ownedBounds */ eoRealVectorBounds(const eoRealVectorBounds &); -private:// WARNING: there is no reason for both std::vector below +private:// WARNING: there is no reason for both std::vector below //to be synchronized in any manner - std::vector factor; // std::list of nb of "grouped" bounds - std::vector ownedBounds; + std::vector factor; // std::list of nb of "grouped" bounds + std::vector ownedBounds; // keep this one private eoRealVectorBounds& operator=(const eoRealVectorBounds&); }; @@ -352,19 +352,19 @@ private:// WARNING: there is no reason for both std::vector below @ingroup Bounds */ class eoRealVectorNoBounds: public eoRealVectorBounds -{ +{ public: // virtual desctructor (to avoid warning?) virtual ~eoRealVectorNoBounds(){} - /** + /** * Ctor: nothing to do, but beware of dimension: call base class ctor */ - eoRealVectorNoBounds(unsigned _dim) : + eoRealVectorNoBounds(unsigned _dim) : eoRealVectorBounds( (_dim?_dim:1), eoDummyRealNoBounds) {} - + virtual bool isBounded(unsigned) {return false;} virtual bool isBounded(void) {return false;} @@ -383,7 +383,7 @@ public: virtual bool isInBounds(unsigned, double) {return true;} virtual bool isInBounds(std::vector) {return true;} - // accessors + // accessors virtual double minimum(unsigned) { throw std::logic_error("Trying to get minimum of eoRealVectorNoBounds"); @@ -397,7 +397,7 @@ public: throw std::logic_error("Trying to get range of eoRealVectorNoBounds"); } - virtual double averageRange() + virtual double averageRange() { throw std::logic_error("Trying to get average range of eoRealVectorNoBounds"); } diff --git a/eo/src/utils/eoScalarFitnessStat.h b/eo/src/utils/eoScalarFitnessStat.h index f472722a..e56e4682 100644 --- a/eo/src/utils/eoScalarFitnessStat.h +++ b/eo/src/utils/eoScalarFitnessStat.h @@ -52,10 +52,10 @@ public: { value().resize(_popPters.size()); for (unsigned i=0; i<_popPters.size(); i++) - { - value()[i] = _popPters[i]->fitness(); - range.truncate(value()[i]); - } + { + value()[i] = _popPters[i]->fitness(); + range.truncate(value()[i]); + } } private : diff --git a/eo/src/utils/eoStat.h b/eo/src/utils/eoStat.h index 8529f1ce..916bcf43 100644 --- a/eo/src/utils/eoStat.h +++ b/eo/src/utils/eoStat.h @@ -44,7 +44,7 @@ Contact: http://eodev.sourceforge.net * * Compute various statistics on a population. * - * Objects of those classes are generally called by an eoCheckPoint + * Objects of those classes are generally called by an eoCheckPoint * to compute statistics about the population at a given generation. * As they inherit from eoValueParam, they can be printed drectly, * for instance by an eoMonitor. @@ -433,7 +433,7 @@ public: eoInterquartileRangeStat( typename EOT::Fitness start, std::string description = "IQR" ) : eoStat( start, description ) {} - virtual void operator()( const eoPop & _pop ) + virtual void operator()( const eoPop & _pop ) { if( _pop.size() == 0 ) { // how to implement value() = 0 ? @@ -444,14 +444,14 @@ public: unsigned int quartile = pop.size()/4; std::nth_element( pop.begin(), pop.begin()+quartile*1, pop.end() ); typename EOT::Fitness Q1 = pop[quartile].fitness(); - + std::nth_element( pop.begin(), pop.begin()+quartile*3, pop.end() ); typename EOT::Fitness Q3 = pop[quartile*3].fitness(); value() = Q1 - Q3; } } - + virtual std::string className(void) const { return "eoInterquartileRangeStat"; } }; /** @example t-eoIQRStat.cpp @@ -459,7 +459,7 @@ public: /** Compute the average size of indivudals over the population * - * Obviously, will work only on representations that implement the (standard) "size()" method, + * Obviously, will work only on representations that implement the (standard) "size()" method, * like any STL container. */ template @@ -469,10 +469,10 @@ public: using eoStat::value; - eoAverageSizeStat( std::string description = "Av.Size" ) : + eoAverageSizeStat( std::string description = "Av.Size" ) : eoStat( 0.0, description ) {} // 0 by default - virtual void operator()( const eoPop & pop ) + virtual void operator()( const eoPop & pop ) { size_t pop_size = pop.size(); @@ -487,10 +487,9 @@ public: value() = static_cast(sum) / static_cast(pop_size); } - + virtual std::string className(void) const { return "eoAverageSizeStat"; } }; /** @} */ #endif - diff --git a/eo/src/utils/eoState.cpp b/eo/src/utils/eoState.cpp index c5997fe1..d9d06d99 100644 --- a/eo/src/utils/eoState.cpp +++ b/eo/src/utils/eoState.cpp @@ -123,24 +123,24 @@ void eoState::load(std::istream& is) while (getline(is, str)) { - if (is.eof()) - throw runtime_error("No section in load file"); - if (is_section(str, name)) - break; + if (is.eof()) + throw runtime_error("No section in load file"); + if (is_section(str, name)) + break; removeComment(str, getCommentString()); fullstring += str + "\n"; } - istringstream the_stream(fullstring); + istringstream the_stream(fullstring); object->readFrom(the_stream); } } - else // if (is_section(str, name)) - what if file empty - { - getline(is, str); // try next line! - // if (is.eof()) - // throw runtime_error("No section in load file"); - } + else // if (is_section(str, name)) - what if file empty + { + getline(is, str); // try next line! + // if (is.eof()) + // throw runtime_error("No section in load file"); + } } } @@ -172,7 +172,7 @@ string eoState::createObjectName(eoObject* obj) { if (obj == 0) { - ostringstream os; + ostringstream os; os << objectMap.size(); return os.str(); } @@ -184,7 +184,7 @@ string eoState::createObjectName(eoObject* obj) unsigned count = 1; while (it != objectMap.end()) { - ostringstream os; + ostringstream os; os << obj->className().c_str() << count++; name = os.str(); it = objectMap.find(name); @@ -192,4 +192,3 @@ string eoState::createObjectName(eoObject* obj) return name; } - diff --git a/eo/src/utils/eoStdoutMonitor.h b/eo/src/utils/eoStdoutMonitor.h index 91fcc11c..a1979b5d 100644 --- a/eo/src/utils/eoStdoutMonitor.h +++ b/eo/src/utils/eoStdoutMonitor.h @@ -1,6 +1,6 @@ // -*- mode: c++; c-indent-level: 4; c++-member-init-indent: 8; comment-column: 35; -*- -/* +/* (c) Marc Schoenauer, Maarten Keijzer and GeNeura Team, 2000 (c) Thales group, 2010 This library is free software; you can redistribute it and/or @@ -24,7 +24,7 @@ Authors: todos@geneura.ugr.es Marc.Schoenauer@polytechnique.fr mkeijzer@dhi.dk - Johann Dréo + Johann Dréo */ #ifndef _eoStdoutMonitor_h @@ -43,18 +43,17 @@ Authors: class eoStdoutMonitor : public eoOStreamMonitor { public : - eoStdoutMonitor(bool _verbose, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : - eoOStreamMonitor( std::cout, _verbose, _delim, _width, _fill) - { + eoStdoutMonitor(bool _verbose, std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : + eoOStreamMonitor( std::cout, _verbose, _delim, _width, _fill) + { eo::log << eo::warnings << "WARNING: the use of the verbose parameter in eoStdutMonitor constructor is deprecated and will be removed in the next release" << std::endl; } - eoStdoutMonitor(std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : - eoOStreamMonitor( std::cout, _delim, _width, _fill) + eoStdoutMonitor(std::string _delim = "\t", unsigned int _width=20, char _fill=' ' ) : + eoOStreamMonitor( std::cout, _delim, _width, _fill) {} virtual std::string className(void) const { return "eoStdoutMonitor"; } }; #endif - diff --git a/eo/src/utils/eoTimeCounter.h b/eo/src/utils/eoTimeCounter.h index 5774844b..62371415 100644 --- a/eo/src/utils/eoTimeCounter.h +++ b/eo/src/utils/eoTimeCounter.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoTimeCounter.h // (c) Marc Schoenauer, Maarten Keijzer, and GeNeura Team, 2002 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -40,30 +40,30 @@ class eoTimeCounter : public eoUpdater, public eoValueParam { public: - eoTimeCounter() : eoValueParam(0.0, "Time") // : firstTime(true) + eoTimeCounter() : eoValueParam(0.0, "Time") // : firstTime(true) { start = time(NULL); } - - /** simply stores the time spent in process in its value() */ + + /** simply stores the time spent in process in its value() */ virtual void operator()() { // ask for system time utime = clock(); - + // if (firstTime) /* first generation */ // { - // firstTime=false; - // firstUtime = tmsStruct.tms_utime; + // firstTime=false; + // firstUtime = tmsStruct.tms_utime; // } // store elapsed user time // value(tmsStruct.tms_utime - firstUtime); // value()=double(utime)/CLOCKS_PER_SEC; double seconds_elapsed = time(NULL) - start; - + value() = (seconds_elapsed > 2140) ? seconds_elapsed : double(utime)/CLOCKS_PER_SEC; } - + private: // bool firstTime; // clock_t firstUtime; diff --git a/eo/src/utils/eoTimedMonitor.h b/eo/src/utils/eoTimedMonitor.h index aa660a79..a06ae6cc 100644 --- a/eo/src/utils/eoTimedMonitor.h +++ b/eo/src/utils/eoTimedMonitor.h @@ -51,25 +51,25 @@ public: eoTimedMonitor(unsigned seconds_) : last_tick(0), seconds(seconds_) {} eoMonitor& operator()(void) { - bool monitor = false; - if (last_tick == 0) { - monitor = true; - last_tick = clock(); - } + bool monitor = false; + if (last_tick == 0) { + monitor = true; + last_tick = clock(); + } - clock_t tick = clock(); + clock_t tick = clock(); - if ( (unsigned)(tick-last_tick) >= seconds * CLOCKS_PER_SEC) { - monitor = true; - } + if ( (unsigned)(tick-last_tick) >= seconds * CLOCKS_PER_SEC) { + monitor = true; + } - if (monitor) { - for (unsigned i = 0; i < monitors.size(); ++i) { - (*monitors[i])(); - } - last_tick = clock(); - } - return *this; + if (monitor) { + for (unsigned i = 0; i < monitors.size(); ++i) { + (*monitors[i])(); + } + last_tick = clock(); + } + return *this; } void add(eoMonitor& mon) { monitors.push_back(&mon); } diff --git a/eo/src/utils/eoUniformInit.h b/eo/src/utils/eoUniformInit.h index fa1b874d..cede61b7 100644 --- a/eo/src/utils/eoUniformInit.h +++ b/eo/src/utils/eoUniformInit.h @@ -24,8 +24,8 @@ */ //----------------------------------------------------------------------------- -/** Copied from the eoRndGenerators to have objects deriving from eoInit - * As the whole initialization mechanism in EO is based on eoInit rather than +/** Copied from the eoRndGenerators to have objects deriving from eoInit + * As the whole initialization mechanism in EO is based on eoInit rather than * eoRndGenerators, we might as well have these directly written without * overhead @@ -69,14 +69,14 @@ template class eoUniformInit : public eoInit public : /** Ctor with only a max bound */ eoUniformInit(T _max = T(1.0), eoRng& _rng = rng) : - minim(T(0.0)), range(_max), uniform(_rng) + minim(T(0.0)), range(_max), uniform(_rng) {} - + /** Ctor with an eoRealBound */ eoUniformInit(eoRealBounds & _bound, eoRng& _rng = rng) : minim(_bound.minimum()), range(_bound.range()), uniform(_rng) {} - + /** Ctor with explicit min and max */ eoUniformInit(T _min, T _max, eoRng& _rng = rng) : minim(_min), range(_max-_min), uniform(_rng) @@ -84,14 +84,14 @@ template class eoUniformInit : public eoInit if (_min>_max) throw std::logic_error("Min is greater than Max in uniform_generator"); } - + /** Generates the number, uses a static_cast to get the right behaviour for ints and unsigneds */ - void operator()(T & _t) - { - _t = minim+static_cast(uniform.uniform(range)); + void operator()(T & _t) + { + _t = minim+static_cast(uniform.uniform(range)); } private : diff --git a/eo/src/utils/eoUpdatable.h b/eo/src/utils/eoUpdatable.h index 4c029c54..202ef962 100644 --- a/eo/src/utils/eoUpdatable.h +++ b/eo/src/utils/eoUpdatable.h @@ -79,13 +79,13 @@ public : void operator()(void) { - time_t now = time(0); + time_t now = time(0); - if (now >= last_time + interval) - { - last_time = now; - eoDynUpdater::operator() (); - } + if (now >= last_time + interval) + { + last_time = now; + eoDynUpdater::operator() (); + } } private : const time_t interval; @@ -106,10 +106,10 @@ public : void operator()(void) { - if (++counter % interval == 0) - { - eoDynUpdater::operator() (); - } + if (++counter % interval == 0) + { + eoDynUpdater::operator() (); + } } private : const unsigned interval; diff --git a/eo/src/utils/eoUpdater.cpp b/eo/src/utils/eoUpdater.cpp index fa6ca109..dd6a3896 100644 --- a/eo/src/utils/eoUpdater.cpp +++ b/eo/src/utils/eoUpdater.cpp @@ -20,7 +20,7 @@ void eoTimedStateSaver::operator()(void) if (now >= last_time + interval) { last_time = now; - ostringstream os; + ostringstream os; os << prefix << (now - first_time) << '.' << extension; state.save(os.str()); } @@ -28,7 +28,7 @@ void eoTimedStateSaver::operator()(void) void eoCountedStateSaver::doItNow(void) { - ostringstream os; + ostringstream os; os << prefix << counter << '.' << extension; state.save(os.str()); } @@ -44,5 +44,3 @@ void eoCountedStateSaver::lastCall(void) if (saveOnLastCall) doItNow(); } - - diff --git a/eo/src/utils/eoUpdater.h b/eo/src/utils/eoUpdater.h index ab8ae425..072b9a9b 100644 --- a/eo/src/utils/eoUpdater.h +++ b/eo/src/utils/eoUpdater.h @@ -45,8 +45,8 @@ class eoUpdater : public eoF public: virtual void lastCall() {} virtual std::string className(void) const { return "eoUpdater"; } - - template + + template eoUpdater& addTo(eoCheckPoint& cp) { cp.add(*this); return *this; } }; @@ -149,8 +149,8 @@ public : eoCountedStateSaver(unsigned _interval, const eoState& _state, std::string _prefix = "state", std::string _extension = "sav", unsigned _counter = 0) : state(_state), interval(_interval), counter(_counter), - saveOnLastCall(true), - prefix(_prefix), extension(_extension) {} + saveOnLastCall(true), + prefix(_prefix), extension(_extension) {} virtual void lastCall(void); void operator()(void); diff --git a/eo/src/utils/make_help.cpp b/eo/src/utils/make_help.cpp index a9aa74f9..a7ab040c 100644 --- a/eo/src/utils/make_help.cpp +++ b/eo/src/utils/make_help.cpp @@ -95,7 +95,7 @@ bool testDirRes(std::string _dirName, bool _erase=true) return true; } // else - if (_erase) // OK to erase + if (_erase) // OK to erase { s = string("/bin/rm ")+ _dirName + "/*"; int res = system(s.c_str()); diff --git a/eo/src/utils/pipecom.cpp b/eo/src/utils/pipecom.cpp index 46ad5489..a175112f 100644 --- a/eo/src/utils/pipecom.cpp +++ b/eo/src/utils/pipecom.cpp @@ -29,14 +29,14 @@ int Check( PCom *com ) { if( ! com ) { - fprintf( stderr, "PipeCom: Null pointer.\n" ); - fflush( stderr ); - return 0; + fprintf( stderr, "PipeCom: Null pointer.\n" ); + fflush( stderr ); + return 0; } if( kill( com->pid, 0 ) != 0 ) { - fprintf( stderr, "PipeCom: process doesn't exists.\n" ); - fflush( stderr ); - return 0; + fprintf( stderr, "PipeCom: process doesn't exists.\n" ); + fflush( stderr ); + return 0; } return 1; } @@ -59,46 +59,46 @@ PCom * PipeComOpenArgv( char *prog, char *argv[] ) PCom * ret = NULL; if( pipe( toFils ) < 0 ) { - perror( "PipeComOpen: Creating pipes" ); - return ret; + perror( "PipeComOpen: Creating pipes" ); + return ret; } if( pipe( toPere ) < 0 ) { - perror( "PipeComOpen: Creating pipes" ); - return ret; + perror( "PipeComOpen: Creating pipes" ); + return ret; } switch( (sonPid = vfork()) ) { case -1: - perror("PipeComOpen: fork failed" ); - return ret; - break; + perror("PipeComOpen: fork failed" ); + return ret; + break; case 0: - /* --- Here's the son --- */ - /* --- replace old stdin --- */ - if( dup2( toFils[0], fileno(stdin) ) < 0 ) { - perror( "PipeComOpen(son): could not connect" ); - exit( -1 ); - /* --- AVOIR: kill my father --- */ - } - if( dup2( toPere[1], fileno(stdout) ) < 0 ) { - perror( "PipeComOpen(son): could not connect" ); - exit( -1 ); - } - if( execvp( prog, argv ) < 0 ) { - perror( prog ); - perror( "PipeComOpen: can't exec" ); - exit(1); - } - break; + /* --- Here's the son --- */ + /* --- replace old stdin --- */ + if( dup2( toFils[0], fileno(stdin) ) < 0 ) { + perror( "PipeComOpen(son): could not connect" ); + exit( -1 ); + /* --- AVOIR: kill my father --- */ + } + if( dup2( toPere[1], fileno(stdout) ) < 0 ) { + perror( "PipeComOpen(son): could not connect" ); + exit( -1 ); + } + if( execvp( prog, argv ) < 0 ) { + perror( prog ); + perror( "PipeComOpen: can't exec" ); + exit(1); + } + break; default: - ret = (PCom *) malloc( sizeof(PCom) ); - if( ! ret ) - return NULL; + ret = (PCom *) malloc( sizeof(PCom) ); + if( ! ret ) + return NULL; - ret->fWrit = (FILE *)fdopen( toFils[1], "w" ); - ret->fRead = (FILE *)fdopen( toPere[0], "r" ); - ret->pid = sonPid; + ret->fWrit = (FILE *)fdopen( toFils[1], "w" ); + ret->fRead = (FILE *)fdopen( toPere[0], "r" ); + ret->pid = sonPid; } return ret; } @@ -108,7 +108,7 @@ int PipeComSend( PCom *to, const char *line ) { int nb = 0; if( ! Check(to ) ) - return nb; + return nb; nb = fprintf( to->fWrit, line, 0 ); fflush( to->fWrit ); return nb; @@ -119,7 +119,7 @@ int PipeComSendn( PCom *to, const char *data, int n ) { int nb = 0; if( ! Check(to) ) - return nb; + return nb; nb = fwrite( data, 1, n, to->fWrit ); fflush( to->fWrit ); @@ -130,14 +130,14 @@ int PipeComSendn( PCom *to, const char *data, int n ) int PipeComReceive( PCom *from, char *data, int max ) { if( ! Check(from) ) - return 0; + return 0; if( ! data ) { fprintf( stderr, "PipeComReceive: Invalid data pointer\n" ); fflush( stderr ); return 0; } if( fgets( data, max, from->fRead ) ) - return strlen(data); + return strlen(data); return 0; } @@ -146,7 +146,7 @@ int PipeComReceive( PCom *from, char *data, int max ) int PipeComClose( PCom *to ) { if( ! Check(to) ) - return 0; + return 0; fclose( to->fRead ); fclose( to->fWrit ); free( to ); @@ -159,8 +159,8 @@ int PipeComWaitFor( PCom *from, char *what ) { char buffer[256]; do { - if( ! PipeComReceive( from, buffer, 256 ) ) - return 0; + if( ! PipeComReceive( from, buffer, 256 ) ) + return 0; } while( strcmp( buffer, what ) ); return 1; } diff --git a/eo/src/utils/selectors.h b/eo/src/utils/selectors.h index d1765b99..37df7997 100644 --- a/eo/src/utils/selectors.h +++ b/eo/src/utils/selectors.h @@ -146,14 +146,14 @@ It roulette_wheel(It _begin, It _end, double total, eoRng& _gen = rng) double roulette = _gen.uniform(total); - if (roulette == 0.0) // covers the case where total==0.0 + if (roulette == 0.0) // covers the case where total==0.0 return _begin + _gen.random(_end - _begin); // uniform choice It i = _begin; while (roulette > 0.0) { - roulette -= static_cast(*(i++)); + roulette -= static_cast(*(i++)); } return --i; @@ -164,14 +164,14 @@ const EOT& roulette_wheel(const eoPop& _pop, double total, eoRng& _gen = rn { double roulette = _gen.uniform(total); - if (roulette == 0.0) // covers the case where total==0.0 + if (roulette == 0.0) // covers the case where total==0.0 return _pop[_gen.random(_pop.size())]; // uniform choice typename eoPop::const_iterator i = _pop.begin(); while (roulette > 0.0) { - roulette -= static_cast((i++)->fitness()); + roulette -= static_cast((i++)->fitness()); } return *--i; @@ -182,14 +182,14 @@ EOT& roulette_wheel(eoPop& _pop, double total, eoRng& _gen = rng) { float roulette = _gen.uniform(total); - if (roulette == 0.0) // covers the case where total==0.0 + if (roulette == 0.0) // covers the case where total==0.0 return _pop[_gen.random(_pop.size())]; // uniform choice typename eoPop::iterator i = _pop.begin(); while (roulette > 0.0) { - roulette -= static_cast((i++)->fitness()); + roulette -= static_cast((i++)->fitness()); } return *--i; @@ -205,7 +205,7 @@ It deterministic_tournament(It _begin, It _end, unsigned _t_size, eoRng& _gen = It competitor = _begin + _gen.random(_end - _begin); if (*best < *competitor) - { + { best = competitor; } }