Make sure uint32_t is defined correctly in eoRNG.h and use it where

appropriate.
This commit is contained in:
kuepper 2005-09-26 10:18:15 +00:00
commit 6e0c4a7264
13 changed files with 238 additions and 220 deletions

View file

@ -30,6 +30,7 @@ AC_CHECK_PROG(DOXYGEN, doxygen, doxygen, true)
dnl Checks for header files. dnl Checks for header files.
AC_HEADER_STDC AC_HEADER_STDC
AC_CHECK_HEADERS(inttypes.h)
AC_CHECK_HEADERS(limits.h) AC_CHECK_HEADERS(limits.h)
AC_CHECK_HEADERS(values.h) AC_CHECK_HEADERS(values.h)
AC_CXX_HAVE_NUMERIC_LIMITS AC_CXX_HAVE_NUMERIC_LIMITS
@ -39,6 +40,8 @@ AC_CXX_NAMESPACES
dnl Checks for typedefs, structures, and compiler characteristics. dnl Checks for typedefs, structures, and compiler characteristics.
AC_C_CONST AC_C_CONST
AC_C_INLINE AC_C_INLINE
AC_CHECK_SIZEOF([unsigned long])
AC_CHECK_TYPES(uint32_t)
AC_TYPE_SIZE_T AC_TYPE_SIZE_T
dnl Checks for libraries. dnl Checks for libraries.

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// make_pop.h // make_pop.h
// (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001 // (c) Maarten Keijzer, Marc Schoenauer and GeNeura Team, 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -49,7 +49,7 @@ template <class EOT>
eoPop<EOT>& do_make_pop(eoParser & _parser, eoState& _state, eoInit<EOT> & _init) eoPop<EOT>& do_make_pop(eoParser & _parser, eoState& _state, eoInit<EOT> & _init)
{ {
// random seed // random seed
eoValueParam<uint32>& seedParam = _parser.createParam(uint32(0), "seed", "Random number seed", 'S'); eoValueParam<uint32_t>& seedParam = _parser.createParam(uint32_t(0), "seed", "Random number seed", 'S');
if (seedParam.value() == 0) if (seedParam.value() == 0)
seedParam.value() = time(0); seedParam.value() = time(0);
eoValueParam<unsigned>& popSize = _parser.createParam(unsigned(20), "popSize", "Population Size", 'P', "Evolution Engine"); eoValueParam<unsigned>& popSize = _parser.createParam(unsigned(20), "popSize", "Population Size", 'P', "Evolution Engine");
@ -57,10 +57,10 @@ eoPop<EOT>& do_make_pop(eoParser & _parser, eoState& _state, eoInit<EOT> & _ini
// Either load or initialize // Either load or initialize
// create an empty pop and let the state handle the memory // create an empty pop and let the state handle the memory
eoPop<EOT>& pop = _state.takeOwnership(eoPop<EOT>()); eoPop<EOT>& pop = _state.takeOwnership(eoPop<EOT>());
eoValueParam<std::string>& loadNameParam = _parser.createParam(std::string(""), "Load","A save file to restart from",'L', "Persistence" ); eoValueParam<std::string>& loadNameParam = _parser.createParam(std::string(""), "Load","A save file to restart from",'L', "Persistence" );
eoValueParam<bool> & recomputeFitnessParam = _parser.createParam(false, "recomputeFitness", "Recompute the fitness after re-loading the pop.?", 'r', "Persistence" ); eoValueParam<bool> & recomputeFitnessParam = _parser.createParam(false, "recomputeFitness", "Recompute the fitness after re-loading the pop.?", 'r', "Persistence" );
if (loadNameParam.value() != "") // something to load if (loadNameParam.value() != "") // something to load
{ {
// create another state for reading // create another state for reading
@ -71,7 +71,7 @@ eoPop<EOT>& do_make_pop(eoParser & _parser, eoState& _state, eoInit<EOT> & _ini
inState.registerObject(pop); inState.registerObject(pop);
inState.registerObject(rng); inState.registerObject(rng);
inState.load(loadNameParam.value()); // load the pop and the 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 // do only evaluate the pop if the fitness has changed
if (recomputeFitnessParam.value()) if (recomputeFitnessParam.value())
{ {
@ -92,7 +92,7 @@ eoPop<EOT>& do_make_pop(eoParser & _parser, eoState& _state, eoInit<EOT> & _ini
} }
if (pop.size() < popSize.value()) // missing some guys if (pop.size() < popSize.value()) // missing some guys
{ {
// Init pop from the randomizer: need to use the append function // Init pop from the randomizer: need to use the append function
pop.append(popSize.value(), _init); pop.append(popSize.value(), _init);
} }

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// make_PBILdistrib.h // make_PBILdistrib.h
// (c) Marc Schoenauer, Maarten Keijzer, 2001 // (c) Marc Schoenauer, Maarten Keijzer, 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -49,15 +49,15 @@ template <class EOT>
eoPBILDistrib<EOT> & do_make_PBILdistrib(eoParser & _parser, eoState& _state, EOT) eoPBILDistrib<EOT> & do_make_PBILdistrib(eoParser & _parser, eoState& _state, EOT)
{ {
// First the random seed // First the random seed
eoValueParam<uint32>& seedParam = _parser.createParam(uint32(0), "seed", "Random number seed", 'S'); eoValueParam<uint32_t>& seedParam = _parser.createParam(uint32_t(0), "seed", "Random number seed", 'S');
if (seedParam.value() == 0) if (seedParam.value() == 0)
seedParam.value() = time(0); seedParam.value() = time(0);
// chromosome size: // chromosome size:
unsigned theSize; unsigned theSize;
// but it might have been already read in the definition fo the performance // 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 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();
@ -67,17 +67,17 @@ eoPBILDistrib<EOT> & do_make_PBILdistrib(eoParser & _parser, eoState& _state, E
eoValueParam<unsigned>* ptChromSize = dynamic_cast<eoValueParam<unsigned>*>(ptParam); eoValueParam<unsigned>* ptChromSize = dynamic_cast<eoValueParam<unsigned>*>(ptParam);
theSize = ptChromSize->value(); theSize = ptChromSize->value();
} }
eoPBILDistrib<EOT> * ptDistrib = new eoPBILDistrib<EOT>(theSize); eoPBILDistrib<EOT> * ptDistrib = new eoPBILDistrib<EOT>(theSize);
_state.storeFunctor(ptDistrib); _state.storeFunctor(ptDistrib);
// now the initialization: read a previously saved distribution, or random // now the initialization: read a previously saved distribution, or random
eoValueParam<std::string>& loadNameParam = _parser.createParam(std::string(""), "Load","A save file to restart from",'L', "Persistence" ); eoValueParam<std::string>& loadNameParam = _parser.createParam(std::string(""), "Load","A save file to restart from",'L', "Persistence" );
if (loadNameParam.value() != "") // something to load if (loadNameParam.value() != "") // something to load
{ {
// create another state for reading // create another state for reading
eoState inState; // a state for loading - WITHOUT the parser 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, // so they can be loaded,
// and the present run will be the exact continuation of the saved run // and the present run will be the exact continuation of the saved run
// eventually with different parameters // eventually with different parameters

View file

@ -1,6 +1,6 @@
/* /*
* Random number generator adapted from (see comments below) * Random number generator adapted from (see comments below)
* *
* The random number generator is modified into a class * The random number generator is modified into a class
* by Maarten Keijzer (mak@dhi.dk). Also added the Box-Muller * by Maarten Keijzer (mak@dhi.dk). Also added the Box-Muller
* transformation to generate normal deviates. * 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 // 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 // GCC at -O3 optimization so try your options and see what's best for you
// //
@ -81,6 +81,12 @@
#ifndef EO_RANDOM_NUMBER_GENERATOR #ifndef EO_RANDOM_NUMBER_GENERATOR
#define EO_RANDOM_NUMBER_GENERATOR #define EO_RANDOM_NUMBER_GENERATOR
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif
#include "../eoPersistent.h" #include "../eoPersistent.h"
#include "../eoObject.h" #include "../eoObject.h"
@ -89,7 +95,14 @@
// Unfortunately MSVC's preprocessor does not comprehend sizeof() // Unfortunately MSVC's preprocessor does not comprehend sizeof()
// so neat preprocessing tricks will not work // 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 // 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(). for evolutionary algorithms. Included are: rand(), random(), flip() and normal().
Note for people porting EO to other platforms: please make sure that the typedef 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 shorter. If it is longer, file compatibility between EO on different platforms
may be broken. may be broken.
*/ */
@ -113,8 +126,8 @@ public :
@see reseed to see why the parameter to initialize is doubled @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) { eoRng(uint32_t s) : state(0), next(0), left(-1), cached(false), N(624), M(397), K(0x9908B0DFU) {
state = new uint32[N+1]; state = new uint32_t[N+1];
initialize(2*s); initialize(2*s);
} }
@ -130,10 +143,10 @@ public :
* the argument to reseed is now doubled before being passed on. * 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 * Manually divide the seed by 2 if you want to re-run old runs
* *
* MS. 5 Oct. 2001 * MS. 5 Oct. 2001
*/ */
void reseed(uint32 s) void reseed(uint32_t s)
{ {
initialize(2*s); initialize(2*s);
} }
@ -141,7 +154,7 @@ public :
/** /**
Re-initializes the Random Number Generator - old version Re-initializes the Random Number Generator - old version
*/ */
void oldReseed(uint32 s) void oldReseed(uint32_t s)
{ {
initialize(s); initialize(s);
} }
@ -153,37 +166,37 @@ public :
{ // random number between [0, m] { // random number between [0, m]
return m * double(rand()) / double(1.0 + rand_max()); return m * double(rand()) / double(1.0 + rand_max());
} }
/** /**
random() returns a random integer in the range [0, m) 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 returns true x% of the time
*/ */
bool flip(float bias=0.5) bool flip(float bias=0.5)
{ {
return uniform() < bias; return uniform() < bias;
} }
/** /**
normal() zero mean gaussian deviate with standard deviation of 1 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 normal(stdev) zero mean gaussian deviate with user defined standard deviation
*/ */
double normal(double stdev) double normal(double stdev)
{ {
return stdev * normal(); return stdev * normal();
} }
/** /**
normal(mean, stdev) user defined mean gaussian deviate with user defined standard deviation 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) rand() returns a random number in the range [0, rand_max)
*/ */
uint32 rand(); uint32_t rand();
/** /**
rand_max() the maximum returned by 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 roulette_wheel(vec, total = 0) does a roulette wheel selection
on the input std::vector vec. If the total is not supplied, it is 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<T>& vec, T total = 0) int roulette_wheel(const std::vector<T>& vec, T total = 0)
{ {
if (total == 0) if (total == 0)
{ // count { // count
for (unsigned i = 0; i < vec.size(); ++i) for (unsigned i = 0; i < vec.size(); ++i)
total += vec[i]; total += vec[i];
} }
double fortune = uniform() * total; double fortune = uniform() * total;
int i = 0; int i = 0;
@ -231,19 +244,19 @@ public :
{ {
fortune -= vec[i++]; fortune -= vec[i++];
} }
return --i; return --i;
} }
/** /**
* choice(vec), returns a uniformly chosen element from the vector * choice(vec), returns a uniformly chosen element from the vector
*/ */
template <class T> template <class T>
const T& choice(const std::vector<T>& vec) { return vec[rng.random(vec.size())]; } const T& choice(const std::vector<T>& vec) { return vec[rng.random(vec.size())]; }
template <class T> template <class T>
T& choice(std::vector<T>& vec) { return vec[rng.random(vec.size())]; } T& choice(std::vector<T>& vec) { return vec[rng.random(vec.size())]; }
/// ///
void printOn(std::ostream& _os) const void printOn(std::ostream& _os) const
{ {
@ -275,11 +288,11 @@ public :
std::string className(void) const { return "Mersenne-Twister"; } std::string className(void) const { return "Mersenne-Twister"; }
private : private :
uint32 restart(void); uint32_t restart(void);
void initialize(uint32 seed); void initialize(uint32_t seed);
uint32* state; // the array for the state uint32_t* state; // the array for the state
uint32* next; uint32_t* next;
int left; int left;
// for normal distribution // for normal distribution
@ -288,7 +301,7 @@ private :
const int N; const int N;
const int M; 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 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 #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 // We initialize state[0..(N-1)] via the generator
@ -369,7 +382,7 @@ inline void eoRng::initialize(uint32 seed)
left = -1; left = -1;
register uint32 x = (seed | 1U) & 0xFFFFFFFFU, *s = state; register uint32_t x = (seed | 1U) & 0xFFFFFFFFU, *s = state;
register int j; register int j;
for(left=0, *s++=x, j=N; --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; register int j;
left=N-1, next=state+1; left=N-1, next=state+1;
@ -397,10 +410,10 @@ inline uint32 eoRng::restart(void)
return(s1 ^ (s1 >> 18)); return(s1 ^ (s1 >> 18));
} }
inline uint32 eoRng::rand(void) inline uint32_t eoRng::rand(void)
{ {
uint32 y; uint32_t y;
if(--left < 0) if(--left < 0)
return(restart()); return(restart());
@ -428,20 +441,20 @@ inline double eoRng::normal(void)
var2 = 2.0 * uniform() - 1.0; var2 = 2.0 * uniform() - 1.0;
rSquare = var1 * var1 + var2 * var2; rSquare = var1 * var1 + var2 * var2;
} }
while (rSquare >= 1.0 || rSquare == 0.0); while (rSquare >= 1.0 || rSquare == 0.0);
factor = sqrt(-2.0 * log(rSquare) / rSquare); factor = sqrt(-2.0 * log(rSquare) / rSquare);
cacheValue = var1 * factor; cacheValue = var1 * factor;
cached = true; cached = true;
return (var2 * factor); return (var2 * factor);
} }
namespace eo { namespace eo {
// a few convenience functions for generating numbers // a few convenience functions for generating numbers
/** /**
* Templatized random function, works with most basic types such as: * Templatized random function, works with most basic types such as:
* char * char
@ -453,7 +466,7 @@ namespace eo {
template <typename T> template <typename T>
inline inline
T random(const T& mx) { return static_cast<T>(rng.uniform() * mx); } T random(const T& mx) { return static_cast<T>(rng.uniform() * mx); }
/** Normal distribution */ /** Normal distribution */
inline double normal() { return rng.normal(); } inline double normal() { return rng.normal(); }
} }

View file

@ -8,7 +8,7 @@
normal_generator : normally distributed floats or doubles normal_generator : normally distributed floats or doubles
(c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000 (c) Maarten Keijzer (mak@dhi.dk) and GeNeura Team, 1999, 2000
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -36,26 +36,26 @@
/** /**
The class uniform_generator can be used in the STL generate function The class uniform_generator can be used in the STL generate function
to easily generate random floats and doubles to easily generate random floats and doubles
either in [0, _max) if only 1 value (_max) is given either in [0, _max) if only 1 value (_max) is given
(or none, as _max defaults to 1.0) (or none, as _max defaults to 1.0)
or in [_min,_max) if 2 values are given (_min, _max) or in [_min,_max) if 2 values are given (_min, _max)
*/ */
template <class T = double> class uniform_generator template <class T = double> 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 // (was maxim only). MS 3/11/2000
public : 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) {} minim(T(0.0)), range(_max), uniform(_rng) {}
uniform_generator(T _min, T _max, eoRng& _rng = rng) : uniform_generator(T _min, T _max, eoRng& _rng = rng) :
minim(_min), range(_max-_min), uniform(_rng) minim(_min), range(_max-_min), uniform(_rng)
{ {
if (_min>_max) 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<T>(uniform.uniform(range)); } T operator()(void) { return minim+static_cast<T>(uniform.uniform(range)); }
private : private :
T minim; T minim;
@ -71,8 +71,8 @@ class boolean_generator
{ {
public : public :
boolean_generator(float _bias = 0.5, eoRng& _rng = rng) : bias(_bias), gen(_rng) {} 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 : private :
float bias; float bias;
eoRng& gen; eoRng& gen;
@ -80,26 +80,26 @@ class boolean_generator
/** /**
The class random_generator can be used in the STL generate function 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 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) or in [_min,_max) if 2 values are given (_min, _max)
*/ */
template <class T = uint32> class random_generator template <class T = uint32_t> class random_generator
{ {
public : 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 // (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) {} minim(T(0.0)), range(_max), random(_rng) {}
random_generator(T _min, T _max, eoRng& _rng = rng) : random_generator(T _min, T _max, eoRng& _rng = rng) :
minim(_min), range(_max-_min), random(_rng) minim(_min), range(_max-_min), random(_rng)
{ {
if (_min>_max) 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)); } T operator()(void) { return (T) (minim + random.random(range)); }
private : private :
T minim; T minim;
T range; T range;
@ -114,18 +114,18 @@ inline bool random_generator<bool>::operator()(void)
} }
/** /**
Another class random_generator that can be used in the STL random_shuffle Another class random_generator that can be used in the STL random_shuffle
function (see eoPop::shuffle): its operator() takes an unsigned argument m function (see eoPop::shuffle): its operator() takes an unsigned argument m
and must return an unsigned uniformly distributed in [0,m} and must return an unsigned uniformly distributed in [0,m}
*/ */
template <class T = uint32> class UF_random_generator template <class T = uint32_t> class UF_random_generator
{ {
public : public :
UF_random_generator(eoRng& _rng = rng) : UF_random_generator(eoRng& _rng = rng) :
random(_rng) {} random(_rng) {}
T operator()(T _t) { return (T) (random.random(_t)); } T operator()(T _t) { return (T) (random.random(_t)); }
private : private :
eoRng& random; eoRng& random;
}; };
@ -140,9 +140,9 @@ template <class T = double> class normal_generator
{ {
public : public :
normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {} normal_generator(T _stdev = T(1.0), eoRng& _rng = rng) : stdev(_stdev), normal(_rng) {}
T operator()(void) { return (T) normal.normal(stdev); } T operator()(void) { return (T) normal.normal(stdev); }
private : private :
T stdev; T stdev;
eoRng& normal; eoRng& normal;
@ -157,9 +157,9 @@ template <class T = double> class negexp_generator
{ {
public : public :
negexp_generator(T _mean = 1.0, eoRng& _rng = rng) : mean(_mean), negexp(_rng) {} negexp_generator(T _mean = 1.0, eoRng& _rng = rng) : mean(_mean), negexp(_rng) {}
T operator()(void) { return (T) negexp.negexp(mean); } T operator()(void) { return (T) negexp.negexp(mean); }
private : private :
T mean; T mean;
eoRng& negexp; eoRng& negexp;

View file

@ -5,10 +5,10 @@
#pragma warning(disable:4786) #pragma warning(disable:4786)
#endif #endif
#include <stdexcept> // runtime_error #include <stdexcept> // runtime_error
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// tt.cpp: // tt.cpp:
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -40,18 +40,18 @@ public :
int the_main(int argc, char **argv) int the_main(int argc, char **argv)
{ // ok, we have a command line parser and a state { // ok, we have a command line parser and a state
typedef eoBit<float> Chrom; typedef eoBit<float> Chrom;
eoParser parser(argc, argv); eoParser parser(argc, argv);
// Define Parameters // Define Parameters
eoValueParam<double> rate(0.01, "mutationRatePerBit", "Initial value for mutation rate per bit"); eoValueParam<double> rate(0.01, "mutationRatePerBit", "Initial value for mutation rate per bit");
eoValueParam<double> factor(0.99, "mutationFactor", "Decrease factor for mutation rate"); eoValueParam<double> factor(0.99, "mutationFactor", "Decrease factor for mutation rate");
eoValueParam<uint32> seed(time(0), "seed", "Random number seed"); eoValueParam<uint32_t> seed(time(0), "seed", "Random number seed");
eoValueParam<std::string> load_name("", "Load","Load",'L'); eoValueParam<std::string> load_name("", "Load","Load",'L');
eoValueParam<std::string> save_name("", "Save","Save",'S'); eoValueParam<std::string> save_name("", "Save","Save",'S');
// Register them // Register them
parser.processParam(rate, "Genetic Operators"); parser.processParam(rate, "Genetic Operators");
parser.processParam(factor, "Genetic Operators"); parser.processParam(factor, "Genetic Operators");
@ -61,27 +61,27 @@ int the_main(int argc, char **argv)
eoState state; eoState state;
state.registerObject(parser); state.registerObject(parser);
if (load_name.value() != "") 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. // be able to change the parameters in the state file by hand.
state.load(load_name.value()); // load the parser state.load(load_name.value()); // load the parser
} }
// Create the algorithm here // Create the algorithm here
typedef Dummy EoType; typedef Dummy EoType;
eoDummyPop pop; eoDummyPop pop;
eoGenContinue<EoType> genTerm(5); // run for 5 generations eoGenContinue<EoType> genTerm(5); // run for 5 generations
eoCheckPoint<EoType> checkpoint(genTerm); eoCheckPoint<EoType> checkpoint(genTerm);
// The algorithm will now quit after five generations // The algorithm will now quit after five generations
// Create a counter parameter // Create a counter parameter
eoValueParam<unsigned> generationCounter(0, "Generation"); eoValueParam<unsigned> 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, // Parameter's value is passed by reference, so every time the incrementer increments,
// the data in generationCounter will change. // the data in generationCounter will change.
eoIncrementor<unsigned> increment(generationCounter.value()); eoIncrementor<unsigned> 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 // The file monitor will print parameters to a comma seperated file
eoFileMonitor monitor("monitor.csv"); eoFileMonitor monitor("monitor.csv");
// the checkpoint mechanism can handle multiple monitors // the checkpoint mechanism can handle multiple monitors
checkpoint.add(monitor); checkpoint.add(monitor);
@ -108,9 +108,9 @@ int the_main(int argc, char **argv)
monitor.add(stats); monitor.add(stats);
// save state every third generation // save state every third generation
eoCountedStateSaver stateSaver1(3, state, "generation"); eoCountedStateSaver stateSaver1(3, state, "generation");
// save state every 2 seconds // save state every 2 seconds
eoTimedStateSaver stateSaver2(2, state, "time"); eoTimedStateSaver stateSaver2(2, state, "time");
// And add the two savers to the checkpoint // And add the two savers to the checkpoint
checkpoint.add(stateSaver1); checkpoint.add(stateSaver1);
@ -138,7 +138,7 @@ int the_main(int argc, char **argv)
// initialize rng and population // initialize rng and population
rng.reseed(seed.value()); rng.reseed(seed.value());
pop.resize(2); pop.resize(2);
pop[0].fitness(1); pop[0].fitness(1);
@ -148,7 +148,7 @@ int the_main(int argc, char **argv)
while(checkpoint(pop)) while(checkpoint(pop))
{ {
pop[0].fitness(pop[0].fitness() + 1); pop[0].fitness(pop[0].fitness() + 1);
time_t now = time(0); time_t now = time(0);
while (time(0) == now) {} // wait a second to test timed saver while (time(0) == now) {} // wait a second to test timed saver

View file

@ -2,7 +2,7 @@
#ifdef _MSC_VER #ifdef _MSC_VER
#pragma warning(disable:4786) #pragma warning(disable:4786)
#endif #endif
#include <algorithm> #include <algorithm>
#include <string> #include <string>
@ -20,20 +20,21 @@ using namespace std;
#include "real_value.h" // the sphere fitness #include "real_value.h" // the sphere fitness
// Now the main // Now the main
/////////////// ///////////////
typedef eoMinimizingFitness FitT; typedef eoMinimizingFitness FitT;
template <class EOT> template <class EOT>
void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _bounds, eoValueParam<string> _load_name); void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _bounds, eoValueParam<string> _load_name);
int main_function(int argc, char *argv[]) int main_function(int argc, char *argv[])
{ {
// Create the command-line parser // Create the command-line parser
eoParser parser( argc, argv, "Basic EA for vector<float> with adaptive mutations"); eoParser parser( argc, argv, "Basic EA for vector<float> with adaptive mutations");
// Define Parameters and load them // Define Parameters and load them
eoValueParam<uint32>& seed = parser.createParam(static_cast<uint32>(time(0)), "seed", "Random number seed"); eoValueParam<uint32_t>& seed = parser.createParam(static_cast<uint32_t>(time(0)),
"seed", "Random number seed");
eoValueParam<string>& load_name = parser.createParam(string(), "Load","Load a state file",'L'); eoValueParam<string>& load_name = parser.createParam(string(), "Load","Load a state file",'L');
eoValueParam<string>& save_name = parser.createParam(string(), "Save","Saves a state file",'S'); eoValueParam<string>& save_name = parser.createParam(string(), "Save","Saves a state file",'S');
eoValueParam<bool>& stdevs = parser.createParam(false, "Stdev", "Use adaptive mutation rates", 's'); eoValueParam<bool>& 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()); rng.reseed(seed.value());
if (!load_name.value().empty()) 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 // be able to change the parameters in the state file by hand
// Note that only parameters inserted in the parser at this point // Note that only parameters inserted in the parser at this point
// will be loaded!. // will be loaded!.
@ -57,7 +58,7 @@ int main_function(int argc, char *argv[])
state.registerObject(rng); state.registerObject(rng);
eoRealVectorBounds bounds(chromSize.value(), minimum.value(), maximum.value()); eoRealVectorBounds bounds(chromSize.value(), minimum.value(), maximum.value());
// Run the appropriate algorithm // Run the appropriate algorithm
if (stdevs.value() == false && corr.value() == false) if (stdevs.value() == false && corr.value() == false)
{ {
@ -67,7 +68,7 @@ int main_function(int argc, char *argv[])
{ {
runAlgorithm(eoEsFull<FitT>(),parser, state, bounds, load_name); runAlgorithm(eoEsFull<FitT>(),parser, state, bounds, load_name);
} }
else else
{ {
runAlgorithm(eoEsStdev<FitT>(), parser, state, bounds, load_name); runAlgorithm(eoEsStdev<FitT>(), parser, state, bounds, load_name);
} }
@ -80,11 +81,11 @@ int main_function(int argc, char *argv[])
state.save(file_name); state.save(file_name);
} }
return 0; return 0;
} }
// A main that catches the exceptions // A main that catches the exceptions
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
#ifdef _MSC_VER #ifdef _MSC_VER
@ -94,7 +95,7 @@ int main(int argc, char **argv)
_CrtSetDbgFlag(flag); _CrtSetDbgFlag(flag);
// _CrtSetBreakAlloc(100); // _CrtSetBreakAlloc(100);
#endif #endif
try try
{ {
main_function(argc, argv); main_function(argc, argv);
@ -103,7 +104,7 @@ int main(int argc, char **argv)
{ {
std::cout << "Exception: " << e.what() << '\n'; std::cout << "Exception: " << e.what() << '\n';
} }
return 1; return 1;
} }
@ -124,7 +125,7 @@ void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _
// Initialization // Initialization
eoEsChromInit<EOT> init(_bounds); eoEsChromInit<EOT> init(_bounds);
// State takes ownership of pop because it needs to save it in caller // State takes ownership of pop because it needs to save it in caller
eoPop<EOT>& pop = _state.takeOwnership(eoPop<EOT>(mu.value(), init)); eoPop<EOT>& pop = _state.takeOwnership(eoPop<EOT>(mu.value(), init));
@ -158,8 +159,8 @@ void runAlgorithm(EOT, eoParser& _parser, eoState& _state, eoRealVectorBounds& _
checkpoint.add(average); checkpoint.add(average);
// only mutation (== with rate 1.0) // only mutation (== with rate 1.0)
eoMonGenOp<EOT> op(mutate); eoMonGenOp<EOT> op(mutate);
// the selection: sequential selection // the selection: sequential selection
eoSequentialSelect<EOT> select; eoSequentialSelect<EOT> select;
// the general breeder (lambda is a rate -> true) // the general breeder (lambda is a rate -> true)

View file

@ -3,7 +3,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eoGenOp.cpp // eoGenOp.cpp
// (c) Maarten Keijzer and Marc Schoenauer, 2001 // (c) Maarten Keijzer and Marc Schoenauer, 2001
/* /*
This library is free software; you can redistribute it and/or This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either License as published by the Free Software Foundation; either
@ -126,7 +126,7 @@ class one2threeOp : public eoGenOp<EOT> // :-)
class two2oneOp : public eoGenOp<EOT> // :-) class two2oneOp : public eoGenOp<EOT> // :-)
{ {
public: public:
unsigned max_production(void) { return 1; } unsigned max_production(void) { return 1; }
void apply(eoPopulator<EOT>& _plop) void apply(eoPopulator<EOT>& _plop)
@ -141,7 +141,7 @@ class two2oneOp : public eoGenOp<EOT> // :-)
class three2threeOp : public eoGenOp<EOT> // :-) class three2threeOp : public eoGenOp<EOT> // :-)
{ {
public: public:
unsigned max_production(void) { return 3; } unsigned max_production(void) { return 3; }
void apply(eoPopulator<EOT>& _plop) void apply(eoPopulator<EOT>& _plop)
@ -182,7 +182,7 @@ void init(eoPop<Dummy> & _pop, unsigned _pSize)
char s[255]; char s[255];
std::ostrstream os(s, 254); std::ostrstream os(s, 254);
#endif #endif
os << i << std::ends; os << i << std::ends;
_pop[i] = Dummy(os.str()); _pop[i] = Dummy(os.str());
_pop[i].fitness(i); _pop[i].fitness(i);
@ -197,7 +197,7 @@ int the_main(int argc, char **argv)
eoValueParam<unsigned int> parentSizeParam = parser.createParam(unsigned(10), "parentSize", "Parent size",'P'); eoValueParam<unsigned int> parentSizeParam = parser.createParam(unsigned(10), "parentSize", "Parent size",'P');
pSize = parentSizeParam.value(); // global variable pSize = parentSizeParam.value(); // global variable
eoValueParam<uint32> seedParam(time(0), "seed", "Random number seed", 'S'); eoValueParam<uint32_t> seedParam(time(0), "seed", "Random number seed", 'S');
parser.processParam( seedParam ); parser.processParam( seedParam );
eo::rng.reseed(seedParam.value()); eo::rng.reseed(seedParam.value());

View file

@ -5,7 +5,7 @@
#pragma warning(disable:4786) #pragma warning(disable:4786)
#endif #endif
#include <stdexcept> // runtime_error #include <stdexcept> // runtime_error
// general // general
#include <eo> #include <eo>
@ -52,7 +52,7 @@ void testSelectMany(eoSelect<EOT> & _select, std::string _name)
{ {
unsigned i; unsigned i;
std::cout << "\n\n" << fitnessType + _name << std::endl; std::cout << "\n\n" << fitnessType + _name << std::endl;
std::cout << "===============\n"; std::cout << "===============\n";
eoDummyPop parents(parentsOrg); eoDummyPop parents(parentsOrg);
eoDummyPop offspring(0); eoDummyPop offspring(0);
@ -93,7 +93,7 @@ void testSelectOne(eoSelectOne<EOT> & _select, eoHowMany & _offspringRate,
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
int the_main(int argc, char **argv) int the_main(int argc, char **argv)
{ {
eoParser parser(argc, argv); eoParser parser(argc, argv);
eoValueParam<unsigned> parentSizeParam = parser.createParam(unsigned(10), "parentSize", "Parent size",'P'); eoValueParam<unsigned> parentSizeParam = parser.createParam(unsigned(10), "parentSize", "Parent size",'P');
pSize = parentSizeParam.value(); // global variable pSize = parentSizeParam.value(); // global variable
@ -129,7 +129,7 @@ eoValueParam<unsigned> tournamentSizeParam = parser.createParam(unsigned(2), "to
// hard-coded directory name ... // hard-coded directory name ...
system("mkdir ResSelect"); system("mkdir ResSelect");
std::cout << "Testing the Selections\nParents size = " << pSize std::cout << "Testing the Selections\nParents size = " << pSize
<< ", offspring rate = " << oRate; << ", offspring rate = " << oRate;
std::cout << " and putting rsulting files in dir ResSelect" << std::endl; std::cout << " and putting rsulting files in dir ResSelect" << std::endl;
@ -150,13 +150,14 @@ eoValueParam<unsigned> tournamentSizeParam = parser.createParam(unsigned(2), "to
parentsOrg[i].fitness(i); parentsOrg[i].fitness(i);
parentsOrg[pSize-1].fitness(10*pSize); parentsOrg[pSize-1].fitness(10*pSize);
} }
else else
throw std::runtime_error("Invalid fitness Type"+fitnessType); throw std::runtime_error("Invalid fitness Type"+fitnessType);
std::cout << "Initial parents (odd)\n" << parentsOrg << std::endl; std::cout << "Initial parents (odd)\n" << parentsOrg << std::endl;
// random seed // random seed
eoValueParam<uint32>& seedParam = parser.createParam(uint32(0), "seed", "Random number seed", 'S'); eoValueParam<uint32_t>& seedParam = parser.createParam(uint32_t(0), "seed",
"Random number seed", 'S');
if (seedParam.value() == 0) if (seedParam.value() == 0)
seedParam.value() = time(0); seedParam.value() = time(0);
rng.reseed(seedParam.value()); rng.reseed(seedParam.value());

View file

@ -74,7 +74,7 @@ void testSelectMany(eoSelect<EOT> & _select, std::string _name)
{ {
unsigned i; unsigned i;
std::cout << "\n\n" << fitnessType + _name << std::endl; std::cout << "\n\n" << fitnessType + _name << std::endl;
std::cout << "===============\n"; std::cout << "===============\n";
eoDummyPop parents(parentsOrg); eoDummyPop parents(parentsOrg);
eoDummyPop offspring(0); eoDummyPop offspring(0);
@ -117,11 +117,11 @@ void testSelectOne(eoSelectOne<EOT> & _select, eoHowMany & _offspringRate,
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
int the_main(int argc, char **argv) int the_main(int argc, char **argv)
{ {
eoParser parser(argc, argv); eoParser parser(argc, argv);
// random seed // random seed
eoValueParam<uint32>& seedParam = parser.createParam(uint32(0), "seed", "Random number seed", 'S'); eoValueParam<uint32_t>& seedParam = parser.createParam(uint32_t(0), "seed", "Random number seed", 'S');
if (seedParam.value() == 0) if (seedParam.value() == 0)
seedParam.value() = time(0); seedParam.value() = time(0);
rng.reseed(seedParam.value()); rng.reseed(seedParam.value());
@ -158,7 +158,7 @@ int the_main(int argc, char **argv)
for (i=0; i<peakNumber; i++) for (i=0; i<peakNumber; i++)
nbIndiPerPeak[i] = pSize/peakNumber; nbIndiPerPeak[i] = pSize/peakNumber;
} }
else // parameters passed by user else // parameters passed by user
if (peakParam.second.size() != peakNumber) if (peakParam.second.size() != peakNumber)
{ {
std::cerr << "ERROR, not enough nb of indis per peaks" << std::endl; std::cerr << "ERROR, not enough nb of indis per peaks" << std::endl;
@ -174,7 +174,7 @@ int the_main(int argc, char **argv)
} }
// compute exact total // compute exact total
sum = 0; sum = 0;
for (i=0; i<peakNumber; i++) for (i=0; i<peakNumber; i++)
sum += nbIndiPerPeak[i]; sum += nbIndiPerPeak[i];
if (sum != pSize) if (sum != pSize)
@ -182,8 +182,8 @@ int the_main(int argc, char **argv)
pSize = pSizeParam.value() = sum; pSize = pSizeParam.value() = sum;
std::cerr << "WARNING, adjusting pSize to " << pSize << std::endl; std::cerr << "WARNING, adjusting pSize to " << pSize << std::endl;
} }
make_help(parser); make_help(parser);
// hard-coded directory name ... // hard-coded directory name ...
std::cout << "Testing the Sharing\n"; std::cout << "Testing the Sharing\n";

View file

@ -5,10 +5,10 @@
#pragma warning(disable:4786) #pragma warning(disable:4786)
#endif #endif
#include <stdexcept> // runtime_error #include <stdexcept> // runtime_error
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// tt.cpp: // tt.cpp:
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -36,16 +36,16 @@ struct Dummy : public EO<double>
int the_main(int argc, char **argv) int the_main(int argc, char **argv)
{ // ok, we have a command line parser and a state { // ok, we have a command line parser and a state
typedef eoBit<float> Chrom; typedef eoBit<float> Chrom;
eoParser parser(argc, argv); eoParser parser(argc, argv);
// Define Parameters // Define Parameters
eoValueParam<unsigned int> dimParam((unsigned int)(5), "dimension", "dimension"); eoValueParam<unsigned int> dimParam((unsigned int)(5), "dimension", "dimension");
eoValueParam<double> rate(0.01, "mutationRatePerBit", "Initial value for mutation rate per bit"); eoValueParam<double> rate(0.01, "mutationRatePerBit", "Initial value for mutation rate per bit");
eoValueParam<double> factor(0.99, "mutationFactor", "Decrease factor for mutation rate"); eoValueParam<double> factor(0.99, "mutationFactor", "Decrease factor for mutation rate");
eoValueParam<uint32> seed(time(0), "seed", "Random number seed"); eoValueParam<uint32_t> seed(time(0), "seed", "Random number seed");
// test if user entered or if default value used // test if user entered or if default value used
if (parser.isItThere(seed)) if (parser.isItThere(seed))
std::cout << "YES\n"; std::cout << "YES\n";
@ -55,7 +55,7 @@ int the_main(int argc, char **argv)
eoValueParam<std::string> load_name("", "Load","Load",'L'); eoValueParam<std::string> load_name("", "Load","Load",'L');
eoValueParam<std::string> save_name("", "Save","Save",'S'); eoValueParam<std::string> save_name("", "Save","Save",'S');
// Register them // Register them
parser.processParam(dimParam, "Genetic Operators"); parser.processParam(dimParam, "Genetic Operators");
parser.processParam(rate, "Genetic Operators"); parser.processParam(rate, "Genetic Operators");
@ -73,16 +73,16 @@ int the_main(int argc, char **argv)
eoState state; eoState state;
state.registerObject(parser); state.registerObject(parser);
if (load_name.value() != "") 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. // be able to change the parameters in the state file by hand.
state.load(load_name.value()); // load the parser state.load(load_name.value()); // load the parser
} }
// Create the algorithm here // Create the algorithm here
// Register the algorithm // Register the algorithm
state.registerObject(rng); state.registerObject(rng);
//state.registerObject(pop); //state.registerObject(pop);

View file

@ -13,7 +13,7 @@
// standard includes // standard includes
#include <fstream> #include <fstream>
#include <iostream> // cout #include <iostream> // cout
#include <stdexcept> // runtime_error #include <stdexcept> // runtime_error
#ifdef HAVE_SSTREAM #ifdef HAVE_SSTREAM
#include <sstream> #include <sstream>
#else #else
@ -42,8 +42,8 @@ void main_function(int argc, char **argv)
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// instead of having all values of useful parameters as constants, read them: // instead of having all values of useful parameters as constants, read them:
// either on the command line (--option=value or -o=value) // either on the command line (--option=value or -o=value)
// or in a parameter file (same syntax, order independent, // or in a parameter file (same syntax, order independent,
// # = usual comment character // # = usual comment character
// or in the environment (TODO) // or in the environment (TODO)
// First define a parser from the command-line arguments // 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, // For each parameter, define Parameter, read it through the parser,
// and assign the value to the variable // and assign the value to the variable
eoValueParam<uint32> seedParam(time(0), "seed", "Random number seed", 'S'); eoValueParam<uint32_t> seedParam(time(0), "seed", "Random number seed", 'S');
parser.processParam( seedParam ); parser.processParam( seedParam );
unsigned seed = seedParam.value(); unsigned seed = seedParam.value();
@ -74,7 +74,7 @@ void main_function(int argc, char **argv)
eoValueParam<string> loadNameParam("", "Load","A save file to restart from",'L'); eoValueParam<string> loadNameParam("", "Load","A save file to restart from",'L');
parser.processParam( loadNameParam, "Persistence" ); parser.processParam( loadNameParam, "Persistence" );
string loadName = loadNameParam.value(); string loadName = loadNameParam.value();
eoValueParam<unsigned int> maxGenParam(100, "maxGen", "Maximum number of generations",'G'); eoValueParam<unsigned int> maxGenParam(100, "maxGen", "Maximum number of generations",'G');
parser.processParam( maxGenParam, "Stopping criterion" ); parser.processParam( maxGenParam, "Stopping criterion" );
unsigned maxGen = maxGenParam.value(); unsigned maxGen = maxGenParam.value();
@ -88,7 +88,7 @@ void main_function(int argc, char **argv)
unsigned steadyGen = steadyGenParam.value(); unsigned steadyGen = steadyGenParam.value();
// operators probabilities at the algorithm level // operators probabilities at the algorithm level
eoValueParam<double> pCrossParam(0.6, "pCross", "Probability of Crossover", 'C'); eoValueParam<double> pCrossParam(0.6, "pCross", "Probability of Crossover", 'C');
parser.processParam( pCrossParam, "Genetic Operators" ); parser.processParam( pCrossParam, "Genetic Operators" );
double pCross = pCrossParam.value(); double pCross = pCrossParam.value();
@ -117,7 +117,7 @@ void main_function(int argc, char **argv)
eoValueParam<double> bitFlipRateParam(0.01, "bitFlipRate", "Relative rate for bit-flip mutation", 'B'); eoValueParam<double> bitFlipRateParam(0.01, "bitFlipRate", "Relative rate for bit-flip mutation", 'B');
parser.processParam( bitFlipRateParam, "Genetic Operators" ); parser.processParam( bitFlipRateParam, "Genetic Operators" );
double bitFlipRate = bitFlipRateParam.value(); double bitFlipRate = bitFlipRateParam.value();
eoValueParam<double> oneBitRateParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'D'); eoValueParam<double> oneBitRateParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'D');
parser.processParam( oneBitRateParam, "Genetic Operators" ); parser.processParam( oneBitRateParam, "Genetic Operators" );
double oneBitRate = oneBitRateParam.value(); double oneBitRate = oneBitRateParam.value();
@ -163,11 +163,11 @@ void main_function(int argc, char **argv)
// eventually with different parameters // eventually with different parameters
inState.registerObject(rng); inState.registerObject(rng);
inState.registerObject(pop); inState.registerObject(pop);
if (loadName != "") if (loadName != "")
{ {
inState.load(loadName); // load the pop and the rng 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 // do only evaluate the pop if the fitness has changed
} }
else else
@ -177,14 +177,14 @@ void main_function(int argc, char **argv)
// based on boolean_generator class (see utils/rnd_generator.h) // based on boolean_generator class (see utils/rnd_generator.h)
eoUniformGenerator<bool> uGen; eoUniformGenerator<bool> uGen;
eoInitFixedLength<Indi> random(vecSize, uGen); eoInitFixedLength<Indi> random(vecSize, uGen);
// Init pop from the randomizer: need to use the append function // Init pop from the randomizer: need to use the append function
pop.append(popSize, random); pop.append(popSize, random);
// and evaluate pop (STL syntax) // and evaluate pop (STL syntax)
apply<Indi>(eval, pop); apply<Indi>(eval, pop);
} // end of initializatio of the population } // end of initializatio of the population
// OUTPUT // OUTPUT
// sort pop for pretty printout // sort pop for pretty printout
pop.sort(); pop.sort();
// Print (sorted) intial population (raw printout) // Print (sorted) intial population (raw printout)
@ -198,12 +198,12 @@ void main_function(int argc, char **argv)
// The robust tournament selection // The robust tournament selection
eoDetTournamentSelect<Indi> selectOne(tSize); // tSize in [2,POPSIZE] eoDetTournamentSelect<Indi> selectOne(tSize); // tSize in [2,POPSIZE]
// is now encapsulated in a eoSelectPerc (stands for Percentage) // is now encapsulated in a eoSelectPerc (stands for Percentage)
eoSelectPerc<Indi> select(selectOne); eoSelectPerc<Indi> select(selectOne);
// REPLACE // 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 :-) // the same generational replacement at the moment :-)
eoGenerationalReplacement<Indi> replace; eoGenerationalReplacement<Indi> replace;
// OPERATORS // OPERATORS
////////////////////////////////////// //////////////////////////////////////
@ -225,7 +225,7 @@ void main_function(int argc, char **argv)
// standard bit-flip mutation for bitstring // standard bit-flip mutation for bitstring
eoBitMutation<Indi> mutationBitFlip(pMutPerBit); eoBitMutation<Indi> mutationBitFlip(pMutPerBit);
// mutate exactly 1 bit per individual // mutate exactly 1 bit per individual
eoDetBitFlip<Indi> mutationOneBit; eoDetBitFlip<Indi> mutationOneBit;
// Combine them with relative rates // Combine them with relative rates
eoPropCombinedMonOp<Indi> mutation(mutationBitFlip, bitFlipRate); eoPropCombinedMonOp<Indi> mutation(mutationBitFlip, bitFlipRate);
mutation.add(mutationOneBit, oneBitRate, true); mutation.add(mutationOneBit, oneBitRate, true);
@ -243,27 +243,27 @@ void main_function(int argc, char **argv)
eoCombinedContinue<Indi> continuator(genCont); eoCombinedContinue<Indi> continuator(genCont);
continuator.add(steadyCont); continuator.add(steadyCont);
continuator.add(fitCont); continuator.add(fitCont);
// CHECKPOINT // 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, ...). // (e.g. statistics, plots, ...).
// the class eoCheckPoint is dedicated to just that: // 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) // IS AN eoContinue and will be called in the loop of all algorithms)
eoCheckPoint<Indi> checkpoint(continuator); eoCheckPoint<Indi> checkpoint(continuator);
// Create a counter parameter // Create a counter parameter
eoValueParam<unsigned> generationCounter(0, "Gen."); eoValueParam<unsigned> generationCounter(0, "Gen.");
// Create an incrementor (sub-class of eoUpdater). Note that the // Create an incrementor (sub-class of eoUpdater). Note that the
// parameter's value is passed by reference, // parameter's value is passed by reference,
// so every time the incrementer is updated (every generation), // so every time the incrementer is updated (every generation),
// the data in generationCounter will change. // the data in generationCounter will change.
eoIncrementor<unsigned> increment(generationCounter.value()); eoIncrementor<unsigned> increment(generationCounter.value());
// Add it to the checkpoint, // Add it to the checkpoint,
// so the counter is updated (here, incremented) every generation // so the counter is updated (here, incremented) every generation
checkpoint.add(increment); checkpoint.add(increment);
@ -279,11 +279,11 @@ void main_function(int argc, char **argv)
// The Stdout monitor will print parameters to the screen ... // The Stdout monitor will print parameters to the screen ...
eoStdoutMonitor monitor(false); eoStdoutMonitor monitor(false);
// 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);
monitor.add(eval); // because now eval is an eoEvalFuncCounter! monitor.add(eval); // because now eval is an eoEvalFuncCounter!
monitor.add(bestStat); 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! // A file monitor: will print parameters to ... a File, yes, you got it!
eoFileMonitor fileMonitor("stats.xg", " "); eoFileMonitor fileMonitor("stats.xg", " ");
// the checkpoint mechanism can handle multiple monitors // the checkpoint mechanism can handle multiple monitors
checkpoint.add(fileMonitor); checkpoint.add(fileMonitor);
@ -309,9 +309,9 @@ void main_function(int argc, char **argv)
// and feed the state to state savers // and feed the state to state savers
// save state every 100th generation // save state every 100th generation
eoCountedStateSaver stateSaver1(20, outState, "generation"); eoCountedStateSaver stateSaver1(20, outState, "generation");
// save state every 1 seconds // save state every 1 seconds
eoTimedStateSaver stateSaver2(1, outState, "time"); eoTimedStateSaver stateSaver2(1, outState, "time");
// Don't forget to add the two savers to the checkpoint // Don't forget to add the two savers to the checkpoint
checkpoint.add(stateSaver1); checkpoint.add(stateSaver1);
@ -323,13 +323,13 @@ void main_function(int argc, char **argv)
// the algorithm // the algorithm
//////////////////////////////////////// ////////////////////////////////////////
// Easy EA requires // Easy EA requires
// stopping criterion, eval, selection, transformation, replacement // stopping criterion, eval, selection, transformation, replacement
eoEasyEA<Indi> gga(checkpoint, eval, select, transform, replace); eoEasyEA<Indi> gga(checkpoint, eval, select, transform, replace);
// Apply algo to pop - that's it! // Apply algo to pop - that's it!
gga(pop); gga(pop);
// OUTPUT // OUTPUT
// Print (sorted) intial population // Print (sorted) intial population
pop.sort(); pop.sort();

View file

@ -13,7 +13,7 @@
// standard includes // standard includes
#include <fstream> #include <fstream>
#include <iostream> // cout #include <iostream> // cout
#include <stdexcept> // runtime_error #include <stdexcept> // runtime_error
#ifdef HAVE_SSTREAM #ifdef HAVE_SSTREAM
#include <sstream> #include <sstream>
#else #else
@ -42,8 +42,8 @@ void main_function(int argc, char **argv)
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// instead of having all values of useful parameters as constants, read them: // instead of having all values of useful parameters as constants, read them:
// either on the command line (--option=value or -o=value) // either on the command line (--option=value or -o=value)
// or in a parameter file (same syntax, order independent, // or in a parameter file (same syntax, order independent,
// # = usual comment character // # = usual comment character
// or in the environment (TODO) // or in the environment (TODO)
// First define a parser from the command-line arguments // 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, // For each parameter, define Parameter, read it through the parser,
// and assign the value to the variable // and assign the value to the variable
eoValueParam<uint32> seedParam(time(0), "seed", "Random number seed", 'S'); eoValueParam<uint32_t> seedParam(time(0), "seed", "Random number seed", 'S');
parser.processParam( seedParam ); parser.processParam( seedParam );
unsigned seed = seedParam.value(); unsigned seed = seedParam.value();
@ -88,7 +88,7 @@ void main_function(int argc, char **argv)
unsigned steadyGen = steadyGenParam.value(); unsigned steadyGen = steadyGenParam.value();
// operators probabilities at the algorithm level // operators probabilities at the algorithm level
eoValueParam<double> pCrossParam(0.6, "pCross", "Probability of Crossover", 'C'); eoValueParam<double> pCrossParam(0.6, "pCross", "Probability of Crossover", 'C');
parser.processParam( pCrossParam, "Genetic Operators" ); parser.processParam( pCrossParam, "Genetic Operators" );
double pCross = pCrossParam.value(); double pCross = pCrossParam.value();
@ -117,7 +117,7 @@ void main_function(int argc, char **argv)
eoValueParam<double> bitFlipRateParam(0.01, "bitFlipRate", "Relative rate for bit-flip mutation", 'B'); eoValueParam<double> bitFlipRateParam(0.01, "bitFlipRate", "Relative rate for bit-flip mutation", 'B');
parser.processParam( bitFlipRateParam, "Genetic Operators" ); parser.processParam( bitFlipRateParam, "Genetic Operators" );
double bitFlipRate = bitFlipRateParam.value(); double bitFlipRate = bitFlipRateParam.value();
eoValueParam<double> oneBitRateParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'D'); eoValueParam<double> oneBitRateParam(0.01, "oneBitRate", "Relative rate for deterministic bit-flip mutation", 'D');
parser.processParam( oneBitRateParam, "Genetic Operators" ); parser.processParam( oneBitRateParam, "Genetic Operators" );
double oneBitRate = oneBitRateParam.value(); double oneBitRate = oneBitRateParam.value();
@ -163,11 +163,11 @@ void main_function(int argc, char **argv)
// eventually with different parameters // eventually with different parameters
inState.registerObject(rng); inState.registerObject(rng);
inState.registerObject(pop); inState.registerObject(pop);
if (loadName != "") if (loadName != "")
{ {
inState.load(loadName); // load the pop and the rng 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 // do only evaluate the pop if the fitness has changed
} }
else else
@ -177,14 +177,14 @@ void main_function(int argc, char **argv)
// based on boolean_generator class (see utils/rnd_generator.h) // based on boolean_generator class (see utils/rnd_generator.h)
eoUniformGenerator<bool> uGen; eoUniformGenerator<bool> uGen;
eoInitFixedLength<Indi> random(vecSize, uGen); eoInitFixedLength<Indi> random(vecSize, uGen);
// Init pop from the randomizer: need to use the append function // Init pop from the randomizer: need to use the append function
pop.append(popSize, random); pop.append(popSize, random);
// and evaluate pop (STL syntax) // and evaluate pop (STL syntax)
apply<Indi>(eval, pop); apply<Indi>(eval, pop);
} // end of initializatio of the population } // end of initializatio of the population
// OUTPUT // OUTPUT
// sort pop for pretty printout // sort pop for pretty printout
// pop.sort(); // pop.sort();
// Print (sorted) intial population (raw printout) // Print (sorted) intial population (raw printout)
@ -202,13 +202,13 @@ void main_function(int argc, char **argv)
eoSelectPerc<Indi> select(selectOne);// by default rate==1 eoSelectPerc<Indi> select(selectOne);// by default rate==1
// REPLACE // 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 :-) // generational replacement at the moment :-)
eoGenerationalReplacement<Indi> replace; eoGenerationalReplacement<Indi> replace;
// want to add (weak) elitism? easy! // want to add (weak) elitism? easy!
// rename the eoGenerationalReplacement replace_main, // rename the eoGenerationalReplacement replace_main,
// then encapsulate it in the elitist replacement // then encapsulate it in the elitist replacement
// eoWeakElitistReplacement<Indi> replace(replace_main); // eoWeakElitistReplacement<Indi> replace(replace_main);
// OPERATORS // OPERATORS
////////////////////////////////////// //////////////////////////////////////
@ -230,7 +230,7 @@ void main_function(int argc, char **argv)
// standard bit-flip mutation for bitstring // standard bit-flip mutation for bitstring
eoBitMutation<Indi> mutationBitFlip(pMutPerBit); eoBitMutation<Indi> mutationBitFlip(pMutPerBit);
// mutate exactly 1 bit per individual // mutate exactly 1 bit per individual
eoDetBitFlip<Indi> mutationOneBit; eoDetBitFlip<Indi> mutationOneBit;
// Combine them with relative rates // Combine them with relative rates
eoPropCombinedMonOp<Indi> mutation(mutationBitFlip, bitFlipRate); eoPropCombinedMonOp<Indi> mutation(mutationBitFlip, bitFlipRate);
mutation.add(mutationOneBit, oneBitRate, true); mutation.add(mutationOneBit, oneBitRate, true);
@ -252,27 +252,27 @@ void main_function(int argc, char **argv)
#ifndef _MSC_VER #ifndef _MSC_VER
eoCtrlCContinue<Indi> ctrlC; eoCtrlCContinue<Indi> ctrlC;
continuator.add(ctrlC); continuator.add(ctrlC);
#endif #endif
// CHECKPOINT // 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, ...). // (e.g. statistics, plots, ...).
// the class eoCheckPoint is dedicated to just that: // 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) // IS AN eoContinue and will be called in the loop of all algorithms)
eoCheckPoint<Indi> checkpoint(continuator); eoCheckPoint<Indi> checkpoint(continuator);
// Create a counter parameter // Create a counter parameter
eoValueParam<unsigned> generationCounter(0, "Gen."); eoValueParam<unsigned> generationCounter(0, "Gen.");
// Create an incrementor (sub-class of eoUpdater). Note that the // Create an incrementor (sub-class of eoUpdater). Note that the
// parameter's value is passed by reference, // parameter's value is passed by reference,
// so every time the incrementer is updated (every generation), // so every time the incrementer is updated (every generation),
// the data in generationCounter will change. // the data in generationCounter will change.
eoIncrementor<unsigned> increment(generationCounter.value()); eoIncrementor<unsigned> increment(generationCounter.value());
// Add it to the checkpoint, // Add it to the checkpoint,
// so the counter is updated (here, incremented) every generation // so the counter is updated (here, incremented) every generation
checkpoint.add(increment); checkpoint.add(increment);
@ -306,7 +306,7 @@ void main_function(int argc, char **argv)
monitor.add(SecondStat); monitor.add(SecondStat);
monitor.add(fdcStat); monitor.add(fdcStat);
// test de eoPopStat and/or eoSortedPopStat. // test de eoPopStat and/or eoSortedPopStat.
// Dumps the whole pop every 10 gen. // Dumps the whole pop every 10 gen.
// eoSortedPopStat<Indi> popStat(10, "Dump of whole population"); // eoSortedPopStat<Indi> popStat(10, "Dump of whole population");
// eoPopStat<Indi> popStat(10, "Dump of whole population"); // eoPopStat<Indi> popStat(10, "Dump of whole population");
@ -365,9 +365,9 @@ void main_function(int argc, char **argv)
// and feed the state to state savers // and feed the state to state savers
// save state every 100th generation // save state every 100th generation
eoCountedStateSaver stateSaver1(100, outState, "generation"); eoCountedStateSaver stateSaver1(100, outState, "generation");
// save state every 1 seconds // save state every 1 seconds
eoTimedStateSaver stateSaver2(1, outState, "time"); eoTimedStateSaver stateSaver2(1, outState, "time");
// Don't forget to add the two savers to the checkpoint // Don't forget to add the two savers to the checkpoint
checkpoint.add(stateSaver1); checkpoint.add(stateSaver1);
@ -379,13 +379,13 @@ void main_function(int argc, char **argv)
// the algorithm // the algorithm
//////////////////////////////////////// ////////////////////////////////////////
// Easy EA requires // Easy EA requires
// selection, transformation, eval, replacement, and stopping criterion // selection, transformation, eval, replacement, and stopping criterion
eoEasyEA<Indi> gga(checkpoint, eval, select, transform, replace); eoEasyEA<Indi> gga(checkpoint, eval, select, transform, replace);
// Apply algo to pop - that's it! // Apply algo to pop - that's it!
gga(pop); gga(pop);
// OUTPUT // OUTPUT
// Print (sorted) intial population // Print (sorted) intial population
pop.sort(); pop.sort();