diff --git a/eo/configure.in b/eo/configure.in index 33fcb747..50e64950 100644 --- a/eo/configure.in +++ b/eo/configure.in @@ -30,6 +30,7 @@ AC_CHECK_PROG(DOXYGEN, doxygen, doxygen, true) dnl Checks for header files. AC_HEADER_STDC +AC_CHECK_HEADERS(inttypes.h) AC_CHECK_HEADERS(limits.h) AC_CHECK_HEADERS(values.h) AC_CXX_HAVE_NUMERIC_LIMITS @@ -39,6 +40,8 @@ AC_CXX_NAMESPACES dnl Checks for typedefs, structures, and compiler characteristics. AC_C_CONST AC_C_INLINE +AC_CHECK_SIZEOF([unsigned long]) +AC_CHECK_TYPES(uint32_t) AC_TYPE_SIZE_T dnl Checks for libraries. diff --git a/eo/src/do/make_pop.h b/eo/src/do/make_pop.h index 87d7e5f3..0fe927a5 100644 --- a/eo/src/do/make_pop.h +++ b/eo/src/do/make_pop.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_pop.h // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 -/* +/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either @@ -49,7 +49,7 @@ template eoPop& do_make_pop(eoParser & _parser, eoState& _state, eoInit & _init) { // random seed - eoValueParam& seedParam = _parser.createParam(uint32(0), "seed", "Random number seed", 'S'); + eoValueParam& seedParam = _parser.createParam(uint32_t(0), "seed", "Random number seed", 'S'); if (seedParam.value() == 0) seedParam.value() = time(0); eoValueParam& popSize = _parser.createParam(unsigned(20), "popSize", "Population Size", 'P', "Evolution Engine"); @@ -57,10 +57,10 @@ eoPop& do_make_pop(eoParser & _parser, eoState& _state, eoInit & _ini // Either load or initialize // create an empty pop and let the state handle the memory eoPop& pop = _state.takeOwnership(eoPop()); - + eoValueParam& loadNameParam = _parser.createParam(std::string(""), "Load","A save file to restart from",'L', "Persistence" ); eoValueParam & recomputeFitnessParam = _parser.createParam(false, "recomputeFitness", "Recompute the fitness after re-loading the pop.?", 'r', "Persistence" ); - + if (loadNameParam.value() != "") // something to load { // create another state for reading @@ -71,7 +71,7 @@ eoPop& do_make_pop(eoParser & _parser, eoState& _state, eoInit & _ini inState.registerObject(pop); inState.registerObject(rng); inState.load(loadNameParam.value()); // load the pop and the rng - // the fitness is read in the file: + // the fitness is read in the file: // do only evaluate the pop if the fitness has changed if (recomputeFitnessParam.value()) { @@ -92,7 +92,7 @@ eoPop& do_make_pop(eoParser & _parser, eoState& _state, eoInit & _ini } if (pop.size() < popSize.value()) // missing some guys - { + { // Init pop from the randomizer: need to use the append function pop.append(popSize.value(), _init); } diff --git a/eo/src/ga/make_PBILdistrib.h b/eo/src/ga/make_PBILdistrib.h index 67ede354..73b0e829 100644 --- a/eo/src/ga/make_PBILdistrib.h +++ b/eo/src/ga/make_PBILdistrib.h @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // make_PBILdistrib.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 @@ -49,15 +49,15 @@ template eoPBILDistrib & do_make_PBILdistrib(eoParser & _parser, eoState& _state, EOT) { // First the random seed - eoValueParam& seedParam = _parser.createParam(uint32(0), "seed", "Random number seed", 'S'); + eoValueParam& seedParam = _parser.createParam(uint32_t(0), "seed", "Random number seed", 'S'); if (seedParam.value() == 0) seedParam.value() = time(0); - // chromosome size: + // chromosome size: unsigned theSize; // but it might have been already read in the definition fo the performance - eoParam* ptParam = _parser.getParamWithLongName(std::string("chromSize")); - + eoParam* ptParam = _parser.getParamWithLongName(std::string("chromSize")); + if (!ptParam) // not already defined: read it here { theSize = _parser.createParam(unsigned(10), "chromSize", "The length of the bitstrings", 'n',"Problem").value(); @@ -67,17 +67,17 @@ eoPBILDistrib & do_make_PBILdistrib(eoParser & _parser, eoState& _state, E eoValueParam* ptChromSize = dynamic_cast*>(ptParam); theSize = ptChromSize->value(); } - + eoPBILDistrib * ptDistrib = new eoPBILDistrib(theSize); _state.storeFunctor(ptDistrib); // now the initialization: read a previously saved distribution, or random - eoValueParam& loadNameParam = _parser.createParam(std::string(""), "Load","A save file to restart from",'L', "Persistence" ); + eoValueParam& loadNameParam = _parser.createParam(std::string(""), "Load","A save file to restart from",'L', "Persistence" ); if (loadNameParam.value() != "") // something to load { // create another state for reading eoState inState; // a state for loading - WITHOUT the parser - // register the rng and the distribution in the state, + // register the rng and the distribution in the state, // so they can be loaded, // and the present run will be the exact continuation of the saved run // eventually with different parameters diff --git a/eo/src/utils/eoRNG.h b/eo/src/utils/eoRNG.h index 9821d6c8..02ab6e48 100644 --- a/eo/src/utils/eoRNG.h +++ b/eo/src/utils/eoRNG.h @@ -1,6 +1,6 @@ /* * Random number generator adapted from (see comments below) -* +* * The random number generator is modified into a class * by Maarten Keijzer (mak@dhi.dk). Also added the Box-Muller * transformation to generate normal deviates. @@ -70,7 +70,7 @@ // // -// uint32 must be an unsigned integer type capable of holding at least 32 +// uint32_t must be an unsigned integer type capable of holding at least 32 // bits; exactly 32 should be fastest, but 64 is better on an Alpha with // GCC at -O3 optimization so try your options and see what's best for you // @@ -81,6 +81,12 @@ #ifndef EO_RANDOM_NUMBER_GENERATOR #define EO_RANDOM_NUMBER_GENERATOR +#ifdef HAVE_CONFIG_H +#include +#endif +#ifdef HAVE_INTTYPES_H +#include +#endif #include "../eoPersistent.h" #include "../eoObject.h" @@ -89,7 +95,14 @@ // Unfortunately MSVC's preprocessor does not comprehend sizeof() // so neat preprocessing tricks will not work -typedef unsigned long uint32; // Compiler and platform dependent! +#if(! (defined HAVE_UINT32_T)) +#if(SIZEOF_UNSIGNED_LONG == 4) +typedef unsigned long uint32_t; +#else +#error Need to provide a type for uint32_t in eoRNG.h. +#endif +#endif + //----------------------------------------------------------------------------- // eoRng @@ -101,7 +114,7 @@ for generating random numbers. The various member functions implement useful fun for evolutionary algorithms. Included are: rand(), random(), flip() and normal(). Note for people porting EO to other platforms: please make sure that the typedef -uint32 in the file eoRng.h is exactly 32 bits long. It may be longer, but not +uint32_t in the file eoRng.h is exactly 32 bits long. It may be longer, but not shorter. If it is longer, file compatibility between EO on different platforms may be broken. */ @@ -113,8 +126,8 @@ public : @see reseed to see why the parameter to initialize is doubled */ - eoRng(uint32 s) : state(0), next(0), left(-1), cached(false), N(624), M(397), K(0x9908B0DFU) { - state = new uint32[N+1]; + eoRng(uint32_t s) : state(0), next(0), left(-1), cached(false), N(624), M(397), K(0x9908B0DFU) { + state = new uint32_t[N+1]; initialize(2*s); } @@ -130,10 +143,10 @@ public : * the argument to reseed is now doubled before being passed on. * * Manually divide the seed by 2 if you want to re-run old runs - * + * * MS. 5 Oct. 2001 */ - void reseed(uint32 s) + void reseed(uint32_t s) { initialize(2*s); } @@ -141,7 +154,7 @@ public : /** Re-initializes the Random Number Generator - old version */ - void oldReseed(uint32 s) + void oldReseed(uint32_t s) { initialize(s); } @@ -153,37 +166,37 @@ public : { // random number between [0, m] return m * double(rand()) / double(1.0 + rand_max()); } - + /** random() returns a random integer in the range [0, m) */ - uint32 random(uint32 m) + uint32_t random(uint32_t m) { - return uint32(uniform() * double(m)); + return uint32_t(uniform() * double(m)); } /** - flip() tosses a biased coin such that flip(x/100.0) will + flip() tosses a biased coin such that flip(x/100.0) will returns true x% of the time */ bool flip(float bias=0.5) { return uniform() < bias; } - + /** normal() zero mean gaussian deviate with standard deviation of 1 */ - double normal(void); // gaussian mutation, stdev 1 + double normal(void); // gaussian mutation, stdev 1 /** normal(stdev) zero mean gaussian deviate with user defined standard deviation */ - double normal(double stdev) + double normal(double stdev) { return stdev * normal(); } - + /** normal(mean, stdev) user defined mean gaussian deviate with user defined standard deviation */ @@ -203,13 +216,13 @@ public : /** rand() returns a random number in the range [0, rand_max) */ - uint32 rand(); - + uint32_t rand(); + /** rand_max() the maximum returned by rand() */ - uint32 rand_max(void) const { return (uint32) 0xffffffff; } - + uint32_t rand_max(void) const { return (uint32_t) 0xffffffff; } + /** roulette_wheel(vec, total = 0) does a roulette wheel selection on the input std::vector vec. If the total is not supplied, it is @@ -219,11 +232,11 @@ public : int roulette_wheel(const std::vector& vec, T total = 0) { if (total == 0) - { // count + { // count for (unsigned i = 0; i < vec.size(); ++i) total += vec[i]; } - + double fortune = uniform() * total; int i = 0; @@ -231,19 +244,19 @@ public : { fortune -= vec[i++]; } - + return --i; } - /** + /** * choice(vec), returns a uniformly chosen element from the vector */ template const T& choice(const std::vector& vec) { return vec[rng.random(vec.size())]; } - + template T& choice(std::vector& vec) { return vec[rng.random(vec.size())]; } - + /// void printOn(std::ostream& _os) const { @@ -275,11 +288,11 @@ public : std::string className(void) const { return "Mersenne-Twister"; } private : - uint32 restart(void); - void initialize(uint32 seed); + uint32_t restart(void); + void initialize(uint32_t seed); - uint32* state; // the array for the state - uint32* next; + uint32_t* state; // the array for the state + uint32_t* next; int left; // for normal distribution @@ -288,7 +301,7 @@ private : const int N; const int M; - const uint32 K; // a magic constant + const uint32_t K; // a magic constant /** @@ -319,7 +332,7 @@ using eo::rng; #define loBits(u) ((u) & 0x7FFFFFFFU) // mask the highest bit of u #define mixBits(u, v) (hiBit(u)|loBits(v)) // move hi bit of u to hi bit of v -inline void eoRng::initialize(uint32 seed) +inline void eoRng::initialize(uint32_t seed) { // // We initialize state[0..(N-1)] via the generator @@ -369,7 +382,7 @@ inline void eoRng::initialize(uint32 seed) left = -1; - register uint32 x = (seed | 1U) & 0xFFFFFFFFU, *s = state; + register uint32_t x = (seed | 1U) & 0xFFFFFFFFU, *s = state; register int j; for(left=0, *s++=x, j=N; --j; @@ -377,9 +390,9 @@ inline void eoRng::initialize(uint32 seed) } -inline uint32 eoRng::restart(void) +inline uint32_t eoRng::restart(void) { - register uint32 *p0=state, *p2=state+2, *pM=state+M, s0, s1; + register uint32_t *p0=state, *p2=state+2, *pM=state+M, s0, s1; register int j; left=N-1, next=state+1; @@ -397,10 +410,10 @@ inline uint32 eoRng::restart(void) return(s1 ^ (s1 >> 18)); } -inline uint32 eoRng::rand(void) +inline uint32_t eoRng::rand(void) { - uint32 y; + uint32_t y; if(--left < 0) return(restart()); @@ -428,20 +441,20 @@ inline double eoRng::normal(void) var2 = 2.0 * uniform() - 1.0; rSquare = var1 * var1 + var2 * var2; - } + } while (rSquare >= 1.0 || rSquare == 0.0); - + factor = sqrt(-2.0 * log(rSquare) / rSquare); - + cacheValue = var1 * factor; cached = true; - + return (var2 * factor); } namespace eo { // a few convenience functions for generating numbers - + /** * Templatized random function, works with most basic types such as: * char @@ -453,7 +466,7 @@ namespace eo { template inline T random(const T& mx) { return static_cast(rng.uniform() * mx); } - + /** Normal distribution */ inline double normal() { return rng.normal(); } } diff --git a/eo/src/utils/rnd_generators.h b/eo/src/utils/rnd_generators.h index d1058ab1..a8528321 100644 --- a/eo/src/utils/rnd_generators.h +++ b/eo/src/utils/rnd_generators.h @@ -8,7 +8,7 @@ normal_generator : normally distributed floats or doubles (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 @@ -36,26 +36,26 @@ /** The class uniform_generator can be used in the STL generate function - to easily generate random floats and doubles - either in [0, _max) if only 1 value (_max) is given + to easily generate random floats and doubles + either in [0, _max) if only 1 value (_max) is given (or none, as _max defaults to 1.0) or in [_min,_max) if 2 values are given (_min, _max) */ template class uniform_generator { - // added new ctor with 2 params, and modified the data to minim and range + // added new ctor with 2 params, and modified the data to minim and range // (was maxim only). MS 3/11/2000 public : - uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : + uniform_generator(T _max = T(1.0), eoRng& _rng = rng) : minim(T(0.0)), range(_max), uniform(_rng) {} - uniform_generator(T _min, T _max, eoRng& _rng = rng) : - minim(_min), range(_max-_min), uniform(_rng) + uniform_generator(T _min, T _max, eoRng& _rng = rng) : + minim(_min), range(_max-_min), uniform(_rng) { if (_min>_max) - throw std::logic_error("Min is greater than Max in uniform_generator"); + throw std::logic_error("Min is greater than Max in uniform_generator"); } - - T operator()(void) { return minim+static_cast(uniform.uniform(range)); } + + T operator()(void) { return minim+static_cast(uniform.uniform(range)); } private : T minim; @@ -71,8 +71,8 @@ class boolean_generator { public : boolean_generator(float _bias = 0.5, eoRng& _rng = rng) : bias(_bias), gen(_rng) {} - - bool operator()(void) { return gen.flip(bias); } + + bool operator()(void) { return gen.flip(bias); } private : float bias; eoRng& gen; @@ -80,26 +80,26 @@ class boolean_generator /** The class random_generator can be used in the STL generate function - to easily generate random ints + to easily generate random ints either between [0, _max) if only one value (_max) is given to the ctor or in [_min,_max) if 2 values are given (_min, _max) */ -template class random_generator +template class random_generator { public : - // added new ctor with 2 params, and modified the data to minim and range + // added new ctor with 2 params, and modified the data to minim and range // (was maxim only). MS 3/11/2000 - random_generator(T _max, eoRng& _rng = rng) : + random_generator(T _max, eoRng& _rng = rng) : minim(T(0.0)), range(_max), random(_rng) {} - random_generator(T _min, T _max, eoRng& _rng = rng) : - minim(_min), range(_max-_min), random(_rng) + random_generator(T _min, T _max, eoRng& _rng = rng) : + minim(_min), range(_max-_min), random(_rng) { if (_min>_max) - throw std::logic_error("Min is greater than Max in random_generator"); + throw std::logic_error("Min is greater than Max in random_generator"); } - + T operator()(void) { return (T) (minim + random.random(range)); } - + private : T minim; T range; @@ -114,18 +114,18 @@ inline bool random_generator::operator()(void) } /** - Another class random_generator that can be used in the STL random_shuffle - function (see eoPop::shuffle): its operator() takes an unsigned argument m + Another class random_generator that can be used in the STL random_shuffle + function (see eoPop::shuffle): its operator() takes an unsigned argument m and must return an unsigned uniformly distributed in [0,m} */ -template class UF_random_generator +template class UF_random_generator { public : - UF_random_generator(eoRng& _rng = rng) : + UF_random_generator(eoRng& _rng = rng) : random(_rng) {} - + T operator()(T _t) { return (T) (random.random(_t)); } - + private : eoRng& random; }; @@ -140,9 +140,9 @@ template class normal_generator { public : normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {} - + T operator()(void) { return (T) normal.normal(stdev); } - + private : T stdev; eoRng& normal; @@ -157,9 +157,9 @@ template class negexp_generator { public : negexp_generator(T _mean = 1.0, eoRng& _rng = rng) : mean(_mean), negexp(_rng) {} - + T operator()(void) { return (T) negexp.negexp(mean); } - + private : T mean; eoRng& negexp; diff --git a/eo/test/t-eoCheckpointing.cpp b/eo/test/t-eoCheckpointing.cpp index 6e826a4a..11d5d593 100644 --- a/eo/test/t-eoCheckpointing.cpp +++ b/eo/test/t-eoCheckpointing.cpp @@ -5,10 +5,10 @@ #pragma warning(disable:4786) #endif -#include // runtime_error +#include // runtime_error //----------------------------------------------------------------------------- -// tt.cpp: +// tt.cpp: // //----------------------------------------------------------------------------- @@ -40,18 +40,18 @@ public : int the_main(int argc, char **argv) { // ok, we have a command line parser and a state - + typedef eoBit Chrom; eoParser parser(argc, argv); - + // Define Parameters - eoValueParam rate(0.01, "mutationRatePerBit", "Initial value for mutation rate per bit"); + eoValueParam rate(0.01, "mutationRatePerBit", "Initial value for mutation rate per bit"); eoValueParam factor(0.99, "mutationFactor", "Decrease factor for mutation rate"); - eoValueParam seed(time(0), "seed", "Random number seed"); + eoValueParam seed(time(0), "seed", "Random number seed"); eoValueParam load_name("", "Load","Load",'L'); eoValueParam save_name("", "Save","Save",'S'); - + // Register them parser.processParam(rate, "Genetic Operators"); parser.processParam(factor, "Genetic Operators"); @@ -61,27 +61,27 @@ int the_main(int argc, char **argv) eoState state; state.registerObject(parser); - + if (load_name.value() != "") - { // load the parser. This is only neccessary when the user wants to + { // load the parser. This is only neccessary when the user wants to // be able to change the parameters in the state file by hand. state.load(load_name.value()); // load the parser } - + // Create the algorithm here typedef Dummy EoType; eoDummyPop pop; - + eoGenContinue genTerm(5); // run for 5 generations - eoCheckPoint checkpoint(genTerm); + eoCheckPoint checkpoint(genTerm); // The algorithm will now quit after five generations // Create a counter parameter eoValueParam generationCounter(0, "Generation"); - - // Create an incrementor (wich is an eoUpdater). Note that the + + // Create an incrementor (wich is an eoUpdater). Note that the // Parameter's value is passed by reference, so every time the incrementer increments, // the data in generationCounter will change. eoIncrementor increment(generationCounter.value()); @@ -91,7 +91,7 @@ int the_main(int argc, char **argv) // The file monitor will print parameters to a comma seperated file eoFileMonitor monitor("monitor.csv"); - + // the checkpoint mechanism can handle multiple monitors checkpoint.add(monitor); @@ -108,9 +108,9 @@ int the_main(int argc, char **argv) monitor.add(stats); // save state every third generation - eoCountedStateSaver stateSaver1(3, state, "generation"); - // save state every 2 seconds - eoTimedStateSaver stateSaver2(2, state, "time"); + eoCountedStateSaver stateSaver1(3, state, "generation"); + // save state every 2 seconds + eoTimedStateSaver stateSaver2(2, state, "time"); // And add the two savers to the checkpoint checkpoint.add(stateSaver1); @@ -138,7 +138,7 @@ int the_main(int argc, char **argv) // initialize rng and population rng.reseed(seed.value()); - + pop.resize(2); pop[0].fitness(1); @@ -148,7 +148,7 @@ int the_main(int argc, char **argv) while(checkpoint(pop)) { pop[0].fitness(pop[0].fitness() + 1); - + time_t now = time(0); while (time(0) == now) {} // wait a second to test timed saver diff --git a/eo/test/t-eoESFull.cpp b/eo/test/t-eoESFull.cpp index 7b555025..7a217b58 100644 --- a/eo/test/t-eoESFull.cpp +++ b/eo/test/t-eoESFull.cpp @@ -2,7 +2,7 @@ #ifdef _MSC_VER #pragma warning(disable:4786) -#endif +#endif #include #include @@ -20,20 +20,21 @@ using namespace std; #include "real_value.h" // the sphere fitness -// Now the main -/////////////// +// Now the main +/////////////// typedef eoMinimizingFitness FitT; template void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _bounds, eoValueParam _load_name); - -int main_function(int argc, char *argv[]) + +int main_function(int argc, char *argv[]) { // Create the command-line parser eoParser parser( argc, argv, "Basic EA for vector with adaptive mutations"); // Define Parameters and load them - eoValueParam& seed = parser.createParam(static_cast(time(0)), "seed", "Random number seed"); + eoValueParam& seed = parser.createParam(static_cast(time(0)), + "seed", "Random number seed"); eoValueParam& load_name = parser.createParam(string(), "Load","Load a state file",'L'); eoValueParam& save_name = parser.createParam(string(), "Save","Saves a state file",'S'); eoValueParam& stdevs = parser.createParam(false, "Stdev", "Use adaptive mutation rates", 's'); @@ -47,7 +48,7 @@ int main_function(int argc, char *argv[]) rng.reseed(seed.value()); if (!load_name.value().empty()) - { // load the parser. This is only neccessary when the user wants to + { // load the parser. This is only neccessary when the user wants to // be able to change the parameters in the state file by hand // Note that only parameters inserted in the parser at this point // will be loaded!. @@ -57,7 +58,7 @@ int main_function(int argc, char *argv[]) state.registerObject(rng); eoRealVectorBounds bounds(chromSize.value(), minimum.value(), maximum.value()); - + // Run the appropriate algorithm if (stdevs.value() == false && corr.value() == false) { @@ -67,7 +68,7 @@ int main_function(int argc, char *argv[]) { runAlgorithm(eoEsFull(),parser, state, bounds, load_name); } - else + else { runAlgorithm(eoEsStdev(), parser, state, bounds, load_name); } @@ -80,11 +81,11 @@ int main_function(int argc, char *argv[]) state.save(file_name); } - return 0; + return 0; } // A main that catches the exceptions - + int main(int argc, char **argv) { #ifdef _MSC_VER @@ -94,7 +95,7 @@ int main(int argc, char **argv) _CrtSetDbgFlag(flag); // _CrtSetBreakAlloc(100); #endif - + try { main_function(argc, argv); @@ -103,7 +104,7 @@ int main(int argc, char **argv) { std::cout << "Exception: " << e.what() << '\n'; } - + return 1; } @@ -124,7 +125,7 @@ void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _ // Initialization eoEsChromInit init(_bounds); - + // State takes ownership of pop because it needs to save it in caller eoPop& pop = _state.takeOwnership(eoPop(mu.value(), init)); @@ -158,8 +159,8 @@ void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _ checkpoint.add(average); // only mutation (== with rate 1.0) - eoMonGenOp op(mutate); - + eoMonGenOp op(mutate); + // the selection: sequential selection eoSequentialSelect select; // the general breeder (lambda is a rate -> true) diff --git a/eo/test/t-eoGenOp.cpp b/eo/test/t-eoGenOp.cpp index 23d1c8f8..b5770399 100644 --- a/eo/test/t-eoGenOp.cpp +++ b/eo/test/t-eoGenOp.cpp @@ -3,7 +3,7 @@ //----------------------------------------------------------------------------- // eoGenOp.cpp // (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 @@ -126,7 +126,7 @@ class one2threeOp : public eoGenOp // :-) class two2oneOp : public eoGenOp // :-) { - public: + public: unsigned max_production(void) { return 1; } void apply(eoPopulator& _plop) @@ -141,7 +141,7 @@ class two2oneOp : public eoGenOp // :-) class three2threeOp : public eoGenOp // :-) { - public: + public: unsigned max_production(void) { return 3; } void apply(eoPopulator& _plop) @@ -182,7 +182,7 @@ void init(eoPop & _pop, unsigned _pSize) char s[255]; std::ostrstream os(s, 254); #endif - + os << i << std::ends; _pop[i] = Dummy(os.str()); _pop[i].fitness(i); @@ -197,7 +197,7 @@ int the_main(int argc, char **argv) eoValueParam parentSizeParam = parser.createParam(unsigned(10), "parentSize", "Parent size",'P'); pSize = parentSizeParam.value(); // global variable - eoValueParam seedParam(time(0), "seed", "Random number seed", 'S'); + eoValueParam seedParam(time(0), "seed", "Random number seed", 'S'); parser.processParam( seedParam ); eo::rng.reseed(seedParam.value()); diff --git a/eo/test/t-eoSelect.cpp b/eo/test/t-eoSelect.cpp index 4f3078e9..30fb0008 100644 --- a/eo/test/t-eoSelect.cpp +++ b/eo/test/t-eoSelect.cpp @@ -5,7 +5,7 @@ #pragma warning(disable:4786) #endif -#include // runtime_error +#include // runtime_error // general #include @@ -52,7 +52,7 @@ void testSelectMany(eoSelect & _select, std::string _name) { unsigned i; std::cout << "\n\n" << fitnessType + _name << std::endl; - std::cout << "===============\n"; + std::cout << "===============\n"; eoDummyPop parents(parentsOrg); eoDummyPop offspring(0); @@ -93,7 +93,7 @@ void testSelectOne(eoSelectOne & _select, eoHowMany & _offspringRate, //----------------------------------------------------------------------------- int the_main(int argc, char **argv) -{ +{ eoParser parser(argc, argv); eoValueParam parentSizeParam = parser.createParam(unsigned(10), "parentSize", "Parent size",'P'); pSize = parentSizeParam.value(); // global variable @@ -129,7 +129,7 @@ eoValueParam tournamentSizeParam = parser.createParam(unsigned(2), "to // hard-coded directory name ... system("mkdir ResSelect"); - std::cout << "Testing the Selections\nParents size = " << pSize + std::cout << "Testing the Selections\nParents size = " << pSize << ", offspring rate = " << oRate; std::cout << " and putting rsulting files in dir ResSelect" << std::endl; @@ -150,13 +150,14 @@ eoValueParam tournamentSizeParam = parser.createParam(unsigned(2), "to parentsOrg[i].fitness(i); parentsOrg[pSize-1].fitness(10*pSize); } - else + else throw std::runtime_error("Invalid fitness Type"+fitnessType); std::cout << "Initial parents (odd)\n" << parentsOrg << std::endl; // random seed - eoValueParam& seedParam = parser.createParam(uint32(0), "seed", "Random number seed", 'S'); + eoValueParam& seedParam = parser.createParam(uint32_t(0), "seed", + "Random number seed", 'S'); if (seedParam.value() == 0) seedParam.value() = time(0); rng.reseed(seedParam.value()); diff --git a/eo/test/t-eoSharing.cpp b/eo/test/t-eoSharing.cpp index 965041ab..031276af 100644 --- a/eo/test/t-eoSharing.cpp +++ b/eo/test/t-eoSharing.cpp @@ -74,7 +74,7 @@ void testSelectMany(eoSelect & _select, std::string _name) { unsigned i; std::cout << "\n\n" << fitnessType + _name << std::endl; - std::cout << "===============\n"; + std::cout << "===============\n"; eoDummyPop parents(parentsOrg); eoDummyPop offspring(0); @@ -117,11 +117,11 @@ void testSelectOne(eoSelectOne & _select, eoHowMany & _offspringRate, //----------------------------------------------------------------------------- int the_main(int argc, char **argv) -{ +{ eoParser parser(argc, argv); // random seed - eoValueParam& seedParam = parser.createParam(uint32(0), "seed", "Random number seed", 'S'); + eoValueParam& seedParam = parser.createParam(uint32_t(0), "seed", "Random number seed", 'S'); if (seedParam.value() == 0) seedParam.value() = time(0); rng.reseed(seedParam.value()); @@ -158,7 +158,7 @@ int the_main(int argc, char **argv) for (i=0; i // runtime_error +#include // runtime_error //----------------------------------------------------------------------------- -// tt.cpp: +// tt.cpp: // //----------------------------------------------------------------------------- @@ -36,16 +36,16 @@ struct Dummy : public EO int the_main(int argc, char **argv) { // ok, we have a command line parser and a state - + typedef eoBit Chrom; eoParser parser(argc, argv); - + // Define Parameters - eoValueParam dimParam((unsigned int)(5), "dimension", "dimension"); - eoValueParam rate(0.01, "mutationRatePerBit", "Initial value for mutation rate per bit"); + eoValueParam dimParam((unsigned int)(5), "dimension", "dimension"); + eoValueParam rate(0.01, "mutationRatePerBit", "Initial value for mutation rate per bit"); eoValueParam factor(0.99, "mutationFactor", "Decrease factor for mutation rate"); - eoValueParam seed(time(0), "seed", "Random number seed"); + eoValueParam seed(time(0), "seed", "Random number seed"); // test if user entered or if default value used if (parser.isItThere(seed)) std::cout << "YES\n"; @@ -55,7 +55,7 @@ int the_main(int argc, char **argv) eoValueParam load_name("", "Load","Load",'L'); eoValueParam save_name("", "Save","Save",'S'); - + // Register them parser.processParam(dimParam, "Genetic Operators"); parser.processParam(rate, "Genetic Operators"); @@ -73,16 +73,16 @@ int the_main(int argc, char **argv) eoState state; state.registerObject(parser); - + if (load_name.value() != "") - { // load the parser. This is only neccessary when the user wants to + { // load the parser. This is only neccessary when the user wants to // be able to change the parameters in the state file by hand. state.load(load_name.value()); // load the parser } - + // Create the algorithm here - + // Register the algorithm state.registerObject(rng); //state.registerObject(pop); diff --git a/eo/tutorial/Lesson3/SecondBitEA.cpp b/eo/tutorial/Lesson3/SecondBitEA.cpp index dfcf8e13..0a250c67 100644 --- a/eo/tutorial/Lesson3/SecondBitEA.cpp +++ b/eo/tutorial/Lesson3/SecondBitEA.cpp @@ -13,7 +13,7 @@ // standard includes #include #include // cout -#include // runtime_error +#include // runtime_error #ifdef HAVE_SSTREAM #include #else @@ -42,8 +42,8 @@ void main_function(int argc, char **argv) //----------------------------------------------------------------------------- // instead of having all values of useful parameters as constants, read them: // either on the command line (--option=value or -o=value) -// or in a parameter file (same syntax, order independent, -// # = usual comment character +// or in a parameter file (same syntax, order independent, +// # = usual comment character // or in the environment (TODO) // First define a parser from the command-line arguments @@ -52,7 +52,7 @@ void main_function(int argc, char **argv) // For each parameter, define Parameter, read it through the parser, // and assign the value to the variable - eoValueParam seedParam(time(0), "seed", "Random number seed", 'S'); + eoValueParam seedParam(time(0), "seed", "Random number seed", 'S'); parser.processParam( seedParam ); unsigned seed = seedParam.value(); @@ -74,7 +74,7 @@ void main_function(int argc, char **argv) eoValueParam loadNameParam("", "Load","A save file to restart from",'L'); parser.processParam( loadNameParam, "Persistence" ); string loadName = loadNameParam.value(); - + eoValueParam maxGenParam(100, "maxGen", "Maximum number of generations",'G'); parser.processParam( maxGenParam, "Stopping criterion" ); unsigned maxGen = maxGenParam.value(); @@ -88,7 +88,7 @@ void main_function(int argc, char **argv) unsigned steadyGen = steadyGenParam.value(); // operators probabilities at the algorithm level - eoValueParam pCrossParam(0.6, "pCross", "Probability of Crossover", 'C'); + eoValueParam pCrossParam(0.6, "pCross", "Probability of Crossover", 'C'); parser.processParam( pCrossParam, "Genetic Operators" ); double pCross = pCrossParam.value(); @@ -117,7 +117,7 @@ void main_function(int argc, char **argv) eoValueParam bitFlipRateParam(0.01, "bitFlipRate", "Relative rate for bit-flip mutation", 'B'); parser.processParam( bitFlipRateParam, "Genetic Operators" ); double bitFlipRate = bitFlipRateParam.value(); - + eoValueParam oneBitRateParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'D'); parser.processParam( oneBitRateParam, "Genetic Operators" ); double oneBitRate = oneBitRateParam.value(); @@ -163,11 +163,11 @@ void main_function(int argc, char **argv) // eventually with different parameters inState.registerObject(rng); inState.registerObject(pop); - + if (loadName != "") { inState.load(loadName); // load the pop and the rng - // the fitness is read in the file: + // the fitness is read in the file: // do only evaluate the pop if the fitness has changed } else @@ -177,14 +177,14 @@ void main_function(int argc, char **argv) // based on boolean_generator class (see utils/rnd_generator.h) eoUniformGenerator uGen; eoInitFixedLength random(vecSize, uGen); - + // Init pop from the randomizer: need to use the append function - pop.append(popSize, random); - // and evaluate pop (STL syntax) + pop.append(popSize, random); + // and evaluate pop (STL syntax) apply(eval, pop); } // end of initializatio of the population -// OUTPUT +// OUTPUT // sort pop for pretty printout pop.sort(); // Print (sorted) intial population (raw printout) @@ -198,12 +198,12 @@ void main_function(int argc, char **argv) // The robust tournament selection eoDetTournamentSelect selectOne(tSize); // tSize in [2,POPSIZE] // is now encapsulated in a eoSelectPerc (stands for Percentage) - eoSelectPerc select(selectOne); + eoSelectPerc select(selectOne); // REPLACE - // And we now have the full slection/replacement - though with + // And we now have the full slection/replacement - though with // the same generational replacement at the moment :-) - eoGenerationalReplacement replace; + eoGenerationalReplacement replace; // OPERATORS ////////////////////////////////////// @@ -225,7 +225,7 @@ void main_function(int argc, char **argv) // standard bit-flip mutation for bitstring eoBitMutation mutationBitFlip(pMutPerBit); // mutate exactly 1 bit per individual - eoDetBitFlip mutationOneBit; + eoDetBitFlip mutationOneBit; // Combine them with relative rates eoPropCombinedMonOp mutation(mutationBitFlip, bitFlipRate); mutation.add(mutationOneBit, oneBitRate, true); @@ -243,27 +243,27 @@ void main_function(int argc, char **argv) eoCombinedContinue continuator(genCont); continuator.add(steadyCont); continuator.add(fitCont); - - + + // CHECKPOINT - // but now you want to make many different things every generation + // but now you want to make many different things every generation // (e.g. statistics, plots, ...). // the class eoCheckPoint is dedicated to just that: - // Declare a checkpoint (from a continuator: an eoCheckPoint + // Declare a checkpoint (from a continuator: an eoCheckPoint // IS AN eoContinue and will be called in the loop of all algorithms) eoCheckPoint checkpoint(continuator); - + // Create a counter parameter eoValueParam generationCounter(0, "Gen."); - - // Create an incrementor (sub-class of eoUpdater). Note that the - // parameter's value is passed by reference, + + // Create an incrementor (sub-class of eoUpdater). Note that the + // parameter's value is passed by reference, // so every time the incrementer is updated (every generation), // the data in generationCounter will change. eoIncrementor increment(generationCounter.value()); - // Add it to the checkpoint, + // Add it to the checkpoint, // so the counter is updated (here, incremented) every generation checkpoint.add(increment); @@ -279,11 +279,11 @@ void main_function(int argc, char **argv) // The Stdout monitor will print parameters to the screen ... eoStdoutMonitor monitor(false); - + // when called by the checkpoint (i.e. at every generation) 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(eval); // because now eval is an eoEvalFuncCounter! monitor.add(bestStat); @@ -291,7 +291,7 @@ void main_function(int argc, char **argv) // A file monitor: will print parameters to ... a File, yes, you got it! eoFileMonitor fileMonitor("stats.xg", " "); - + // the checkpoint mechanism can handle multiple monitors checkpoint.add(fileMonitor); @@ -309,9 +309,9 @@ void main_function(int argc, char **argv) // and feed the state to state savers // save state every 100th generation - eoCountedStateSaver stateSaver1(20, outState, "generation"); - // save state every 1 seconds - eoTimedStateSaver stateSaver2(1, outState, "time"); + eoCountedStateSaver stateSaver1(20, outState, "generation"); + // save state every 1 seconds + eoTimedStateSaver stateSaver2(1, outState, "time"); // Don't forget to add the two savers to the checkpoint checkpoint.add(stateSaver1); @@ -323,13 +323,13 @@ void main_function(int argc, char **argv) // the algorithm //////////////////////////////////////// - // Easy EA requires + // Easy EA requires // stopping criterion, eval, selection, transformation, replacement eoEasyEA gga(checkpoint, eval, select, transform, replace); // Apply algo to pop - that's it! gga(pop); - + // OUTPUT // Print (sorted) intial population pop.sort(); diff --git a/eo/tutorial/Lesson3/exercise3.1.cpp b/eo/tutorial/Lesson3/exercise3.1.cpp index 30000541..55a89a24 100644 --- a/eo/tutorial/Lesson3/exercise3.1.cpp +++ b/eo/tutorial/Lesson3/exercise3.1.cpp @@ -13,7 +13,7 @@ // standard includes #include #include // cout -#include // runtime_error +#include // runtime_error #ifdef HAVE_SSTREAM #include #else @@ -42,8 +42,8 @@ void main_function(int argc, char **argv) //----------------------------------------------------------------------------- // instead of having all values of useful parameters as constants, read them: // either on the command line (--option=value or -o=value) -// or in a parameter file (same syntax, order independent, -// # = usual comment character +// or in a parameter file (same syntax, order independent, +// # = usual comment character // or in the environment (TODO) // First define a parser from the command-line arguments @@ -52,7 +52,7 @@ void main_function(int argc, char **argv) // For each parameter, define Parameter, read it through the parser, // and assign the value to the variable - eoValueParam seedParam(time(0), "seed", "Random number seed", 'S'); + eoValueParam seedParam(time(0), "seed", "Random number seed", 'S'); parser.processParam( seedParam ); unsigned seed = seedParam.value(); @@ -88,7 +88,7 @@ void main_function(int argc, char **argv) unsigned steadyGen = steadyGenParam.value(); // operators probabilities at the algorithm level - eoValueParam pCrossParam(0.6, "pCross", "Probability of Crossover", 'C'); + eoValueParam pCrossParam(0.6, "pCross", "Probability of Crossover", 'C'); parser.processParam( pCrossParam, "Genetic Operators" ); double pCross = pCrossParam.value(); @@ -117,7 +117,7 @@ void main_function(int argc, char **argv) eoValueParam bitFlipRateParam(0.01, "bitFlipRate", "Relative rate for bit-flip mutation", 'B'); parser.processParam( bitFlipRateParam, "Genetic Operators" ); double bitFlipRate = bitFlipRateParam.value(); - + eoValueParam oneBitRateParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'D'); parser.processParam( oneBitRateParam, "Genetic Operators" ); double oneBitRate = oneBitRateParam.value(); @@ -163,11 +163,11 @@ void main_function(int argc, char **argv) // eventually with different parameters inState.registerObject(rng); inState.registerObject(pop); - + if (loadName != "") { inState.load(loadName); // load the pop and the rng - // the fitness is read in the file: + // the fitness is read in the file: // do only evaluate the pop if the fitness has changed } else @@ -177,14 +177,14 @@ void main_function(int argc, char **argv) // based on boolean_generator class (see utils/rnd_generator.h) eoUniformGenerator uGen; eoInitFixedLength random(vecSize, uGen); - + // Init pop from the randomizer: need to use the append function - pop.append(popSize, random); - // and evaluate pop (STL syntax) + pop.append(popSize, random); + // and evaluate pop (STL syntax) apply(eval, pop); } // end of initializatio of the population -// OUTPUT +// OUTPUT // sort pop for pretty printout // pop.sort(); // Print (sorted) intial population (raw printout) @@ -202,13 +202,13 @@ void main_function(int argc, char **argv) eoSelectPerc select(selectOne);// by default rate==1 // REPLACE - // And we now have the full slection/replacement - though with + // And we now have the full slection/replacement - though with // generational replacement at the moment :-) - eoGenerationalReplacement replace; + eoGenerationalReplacement replace; // want to add (weak) elitism? easy! // rename the eoGenerationalReplacement replace_main, // then encapsulate it in the elitist replacement - // eoWeakElitistReplacement replace(replace_main); + // eoWeakElitistReplacement replace(replace_main); // OPERATORS ////////////////////////////////////// @@ -230,7 +230,7 @@ void main_function(int argc, char **argv) // standard bit-flip mutation for bitstring eoBitMutation mutationBitFlip(pMutPerBit); // mutate exactly 1 bit per individual - eoDetBitFlip mutationOneBit; + eoDetBitFlip mutationOneBit; // Combine them with relative rates eoPropCombinedMonOp mutation(mutationBitFlip, bitFlipRate); mutation.add(mutationOneBit, oneBitRate, true); @@ -252,27 +252,27 @@ void main_function(int argc, char **argv) #ifndef _MSC_VER eoCtrlCContinue ctrlC; continuator.add(ctrlC); -#endif - +#endif + // CHECKPOINT - // but now you want to make many different things every generation + // but now you want to make many different things every generation // (e.g. statistics, plots, ...). // the class eoCheckPoint is dedicated to just that: - // Declare a checkpoint (from a continuator: an eoCheckPoint + // Declare a checkpoint (from a continuator: an eoCheckPoint // IS AN eoContinue and will be called in the loop of all algorithms) eoCheckPoint checkpoint(continuator); - + // Create a counter parameter eoValueParam generationCounter(0, "Gen."); - - // Create an incrementor (sub-class of eoUpdater). Note that the - // parameter's value is passed by reference, + + // Create an incrementor (sub-class of eoUpdater). Note that the + // parameter's value is passed by reference, // so every time the incrementer is updated (every generation), // the data in generationCounter will change. eoIncrementor increment(generationCounter.value()); - // Add it to the checkpoint, + // Add it to the checkpoint, // so the counter is updated (here, incremented) every generation checkpoint.add(increment); @@ -306,7 +306,7 @@ void main_function(int argc, char **argv) monitor.add(SecondStat); monitor.add(fdcStat); - // test de eoPopStat and/or eoSortedPopStat. + // test de eoPopStat and/or eoSortedPopStat. // Dumps the whole pop every 10 gen. // eoSortedPopStat popStat(10, "Dump of whole population"); // eoPopStat popStat(10, "Dump of whole population"); @@ -365,9 +365,9 @@ void main_function(int argc, char **argv) // and feed the state to state savers // save state every 100th generation - eoCountedStateSaver stateSaver1(100, outState, "generation"); - // save state every 1 seconds - eoTimedStateSaver stateSaver2(1, outState, "time"); + eoCountedStateSaver stateSaver1(100, outState, "generation"); + // save state every 1 seconds + eoTimedStateSaver stateSaver2(1, outState, "time"); // Don't forget to add the two savers to the checkpoint checkpoint.add(stateSaver1); @@ -379,13 +379,13 @@ void main_function(int argc, char **argv) // the algorithm //////////////////////////////////////// - // Easy EA requires + // Easy EA requires // selection, transformation, eval, replacement, and stopping criterion eoEasyEA gga(checkpoint, eval, select, transform, replace); // Apply algo to pop - that's it! gga(pop); - + // OUTPUT // Print (sorted) intial population pop.sort();